repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
jwren/intellij-community
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/Utils.kt
1
10629
// 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.core import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.caches.resolve.computeTypeInContext import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveToDescriptors import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory import org.jetbrains.kotlin.idea.resolve.languageVersionSettings import org.jetbrains.kotlin.idea.util.getImplicitReceiversWithInstanceToExpression import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.CallableId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.parentOrNull import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DelegatingBindingTrace import org.jetbrains.kotlin.resolve.QualifiedExpressionResolver import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore import org.jetbrains.kotlin.resolve.calls.CallResolver import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.components.isVararg import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext import org.jetbrains.kotlin.resolve.calls.context.CheckArgumentTypesMode import org.jetbrains.kotlin.resolve.calls.context.ContextDependency import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.results.ResolutionStatus import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.calls.util.getDispatchReceiverWithSmartCast import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf import java.util.* /** * See `ArgumentsToParametersMapper` class in the compiler. */ fun Call.mapArgumentsToParameters(targetDescriptor: CallableDescriptor): Map<ValueArgument, ValueParameterDescriptor> { val parameters = targetDescriptor.valueParameters if (parameters.isEmpty()) return emptyMap() val map = HashMap<ValueArgument, ValueParameterDescriptor>() val parametersByName = if (targetDescriptor.hasStableParameterNames()) parameters.associateBy { it.name } else emptyMap() var positionalArgumentIndex: Int? = 0 for (argument in valueArguments) { if (argument is LambdaArgument) { map[argument] = parameters.last() } else { val argumentName = argument.getArgumentName()?.asName if (argumentName != null) { val parameter = parametersByName[argumentName] if (parameter != null) { map[argument] = parameter if (parameter.index == positionalArgumentIndex) { positionalArgumentIndex++ continue } } positionalArgumentIndex = null } else { if (positionalArgumentIndex != null && positionalArgumentIndex < parameters.size) { val parameter = parameters[positionalArgumentIndex] map[argument] = parameter if (!parameter.isVararg) { positionalArgumentIndex++ } } } } } return map } fun ImplicitReceiver.asExpression(resolutionScope: LexicalScope, psiFactory: KtPsiFactory): KtExpression? { val expressionFactory = resolutionScope.getImplicitReceiversWithInstanceToExpression() .entries .firstOrNull { it.key.containingDeclaration == this.declarationDescriptor } ?.value ?: return null return expressionFactory.createExpression(psiFactory) } fun KtImportDirective.targetDescriptors(resolutionFacade: ResolutionFacade = this.getResolutionFacade()): Collection<DeclarationDescriptor> { // For codeFragments imports are created in dummy file if (this.containingKtFile.doNotAnalyze != null) return emptyList() val nameExpression = importedReference?.getQualifiedElementSelector() as? KtSimpleNameExpression ?: return emptyList() return nameExpression.mainReference.resolveToDescriptors(resolutionFacade.analyze(nameExpression)) } fun Call.resolveCandidates( bindingContext: BindingContext, resolutionFacade: ResolutionFacade, expectedType: KotlinType = expectedType(this, bindingContext), filterOutWrongReceiver: Boolean = true, filterOutByVisibility: Boolean = true ): Collection<ResolvedCall<FunctionDescriptor>> { val resolutionScope = callElement.getResolutionScope(bindingContext, resolutionFacade) val inDescriptor = resolutionScope.ownerDescriptor val dataFlowInfo = bindingContext.getDataFlowInfoBefore(callElement) val bindingTrace = DelegatingBindingTrace(bindingContext, "Temporary trace") val callResolutionContext = BasicCallResolutionContext.create( bindingTrace, resolutionScope, this, expectedType, dataFlowInfo, ContextDependency.INDEPENDENT, CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS, false, resolutionFacade.languageVersionSettings, resolutionFacade.dataFlowValueFactory ).replaceCollectAllCandidates(true) @OptIn(FrontendInternals::class) val callResolver = resolutionFacade.frontendService<CallResolver>() val results = callResolver.resolveFunctionCall(callResolutionContext) var candidates = results.allCandidates!! if (callElement is KtConstructorDelegationCall) { // for "this(...)" delegation call exclude caller from candidates inDescriptor as ConstructorDescriptor candidates = candidates.filter { it.resultingDescriptor.original != inDescriptor.original } } if (filterOutWrongReceiver) { candidates = candidates.filter { it.status != ResolutionStatus.RECEIVER_TYPE_ERROR && it.status != ResolutionStatus.RECEIVER_PRESENCE_ERROR } } if (filterOutByVisibility) { candidates = candidates.filter { DescriptorVisibilityUtils.isVisible( it.getDispatchReceiverWithSmartCast(), it.resultingDescriptor, inDescriptor, resolutionFacade.languageVersionSettings ) } } return candidates } private fun expectedType(call: Call, bindingContext: BindingContext): KotlinType { return (call.callElement as? KtExpression)?.let { bindingContext[BindingContext.EXPECTED_EXPRESSION_TYPE, it.getQualifiedExpressionForSelectorOrThis()] } ?: TypeUtils.NO_EXPECTED_TYPE } fun KtCallableDeclaration.canOmitDeclaredType(initializerOrBodyExpression: KtExpression, canChangeTypeToSubtype: Boolean): Boolean { val declaredType = (unsafeResolveToDescriptor() as? CallableDescriptor)?.returnType ?: return false val bindingContext = initializerOrBodyExpression.analyze() val scope = initializerOrBodyExpression.getResolutionScope(bindingContext, initializerOrBodyExpression.getResolutionFacade()) val expressionType = initializerOrBodyExpression.computeTypeInContext(scope) ?: return false if (KotlinTypeChecker.DEFAULT.equalTypes(expressionType, declaredType)) return true return canChangeTypeToSubtype && expressionType.isSubtypeOf(declaredType) } fun FqName.quoteSegmentsIfNeeded(): String { return pathSegments().joinToString(".") { it.asString().quoteIfNeeded() } } fun FqName.quoteIfNeeded() = FqName(quoteSegmentsIfNeeded()) fun CallableId.asFqNameWithRootPrefixIfNeeded() = asSingleFqName().withRootPrefixIfNeeded() fun FqName.withRootPrefixIfNeeded(targetElement: KtElement? = null) = if (canAddRootPrefix() && targetElement?.canAddRootPrefix() != false) FqName(QualifiedExpressionResolver.ROOT_PREFIX_FOR_IDE_RESOLUTION_MODE_WITH_DOT + asString()) else this fun FqName.canAddRootPrefix(): Boolean = !asString().startsWith(QualifiedExpressionResolver.ROOT_PREFIX_FOR_IDE_RESOLUTION_MODE_WITH_DOT) && !thisOrParentIsRoot() fun FqName.thisOrParentIsRoot(): Boolean = parentOrNull()?.isRoot != false fun KtElement.canAddRootPrefix(): Boolean = getParentOfTypes2<KtImportDirective, KtPackageDirective>() == null fun isEnumCompanionPropertyWithEntryConflict(element: PsiElement, expectedName: String): Boolean { if (element !is KtProperty) return false val propertyClass = element.containingClassOrObject as? KtObjectDeclaration ?: return false if (!propertyClass.isCompanion()) return false val outerClass = propertyClass.containingClassOrObject as? KtClass ?: return false if (!outerClass.isEnum()) return false return outerClass.declarations.any { it is KtEnumEntry && it.name == expectedName } } fun KtCallExpression.receiverValue(): ReceiverValue? { val resolvedCall = getResolvedCall(safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)) ?: return null return resolvedCall.dispatchReceiver ?: resolvedCall.extensionReceiver } fun KtCallExpression.receiverType(): KotlinType? = receiverValue()?.type fun KtExpression.resolveType(): KotlinType? = this.analyze(BodyResolveMode.PARTIAL).getType(this) fun KtModifierKeywordToken.toVisibility(): DescriptorVisibility { return when (this) { KtTokens.PUBLIC_KEYWORD -> DescriptorVisibilities.PUBLIC KtTokens.PRIVATE_KEYWORD -> DescriptorVisibilities.PRIVATE KtTokens.PROTECTED_KEYWORD -> DescriptorVisibilities.PROTECTED KtTokens.INTERNAL_KEYWORD -> DescriptorVisibilities.INTERNAL else -> throw IllegalArgumentException("Unknown visibility modifier:$this") } }
apache-2.0
ebc4ea65c5f099cdc16bc897f6bf82bb
45.828194
158
0.766017
5.301247
false
false
false
false
chemickypes/Glitchy
glitchappcore/src/main/java/me/bemind/glitchappcore/history/HistoryPresenter.kt
1
3450
package me.bemind.glitchappcore.history import android.content.Context import android.graphics.Bitmap import android.os.Bundle import android.util.Log import io.reactivex.Observable import io.reactivex.Scheduler import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import me.bemind.glitchappcore.ImageDescriptor import java.util.ArrayList import java.util.concurrent.Callable /** * Created by angelomoroni on 14/04/17. */ interface IHistoryPresenter { var hasHistory :Boolean var canBack : Boolean fun clearHistory() fun addImage(bitmap: Bitmap,newPhoto:Boolean = false) fun back() fun lastImage() fun getHistoryToSave(): ArrayList<ImageDescriptor>? fun restoreHistory(savedInstanceState: Bundle?, list: ArrayList<ImageDescriptor>?, setImage:Boolean = true) } class HistoryPresenter(val context:Context) : IHistoryPresenter { val historyLogic = HistoryLogic(context) var historyView : IHistoryView? = null val image : Bitmap? get() = historyLogic.lastBitmap private var disposable: Disposable? = null override var hasHistory: Boolean get() = historyLogic.hasHistory set(value) {/*nothing*/} override var canBack: Boolean get() = historyLogic.canBack() set(value) {} override fun clearHistory() { historyLogic.clearHistory() } override fun addImage(bitmap: Bitmap,newPhoto: Boolean) { disposable = Observable.fromCallable { historyLogic.addBitmap(bitmap,newPhoto);1} .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { Log.i("Save","save")}, {t->t.printStackTrace()} ) } override fun lastImage() { observableImage( { historyLogic.lastBitmap }, { b -> historyView?.setPreviousImage(b) } ) } override fun back() { observableImage( { historyLogic.back() }, { b -> historyView?.setPreviousImage(b) } ) } override fun getHistoryToSave(): ArrayList<ImageDescriptor>? { disposable?.dispose() return historyLogic.getStack() } override fun restoreHistory(savedInstanceState: Bundle?,list: ArrayList<ImageDescriptor>?,setImage: Boolean) { historyLogic.setStack(list) if(savedInstanceState==null) historyLogic.clearHistory() if(setImage){ observableImage( { historyLogic.lastBitmap }, { b -> historyView?.setPreviousImage(b,true) } ) } } fun observableImage(callableFunction: () -> Bitmap?, nextAction: (t: Bitmap?) -> Unit) { disposable = Observable.fromCallable(callableFunction) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( nextAction, { t -> t.printStackTrace() } ) } }
apache-2.0
cc6d4102c2d0a39ca88f03f38d88ae92
24.746269
114
0.574493
5.081001
false
false
false
false
jwren/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinUObjectLiteralExpression.kt
1
3484
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.psi.KtObjectLiteralExpression import org.jetbrains.kotlin.psi.KtSuperTypeCallEntry import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.internal.DelegatedMultiResolve @ApiStatus.Internal class KotlinUObjectLiteralExpression( override val sourcePsi: KtObjectLiteralExpression, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), UObjectLiteralExpression, UCallExpression, DelegatedMultiResolve, KotlinUElementWithType { override val declaration: UClass by lz { sourcePsi.objectDeclaration.toLightClass() ?.let { languagePlugin?.convertOpt(it, this) } ?: KotlinInvalidUClass("<invalid object code>", sourcePsi, this) } override fun getExpressionType() = sourcePsi.objectDeclaration.toPsiType() private val superClassConstructorCall by lz { sourcePsi.objectDeclaration.superTypeListEntries.firstOrNull { it is KtSuperTypeCallEntry } as? KtSuperTypeCallEntry } override val classReference: UReferenceExpression? by lz { superClassConstructorCall?.let { ObjectLiteralClassReference(it, this) } } override val valueArgumentCount: Int get() = superClassConstructorCall?.valueArguments?.size ?: 0 override val valueArguments by lz { val psi = superClassConstructorCall ?: return@lz emptyList<UExpression>() psi.valueArguments.map { baseResolveProviderService.baseKotlinConverter.convertOrEmpty(it.getArgumentExpression(), this) } } override val typeArgumentCount: Int get() = superClassConstructorCall?.typeArguments?.size ?: 0 override val typeArguments by lz { val psi = superClassConstructorCall ?: return@lz emptyList<PsiType>() psi.typeArguments.map { typeArgument -> typeArgument.typeReference?.let { baseResolveProviderService.resolveToType(it, this, boxed = true) } ?: UastErrorType } } override fun resolve() = superClassConstructorCall?.let { baseResolveProviderService.resolveCall(it) } override fun getArgumentForParameter(i: Int): UExpression? = superClassConstructorCall?.let { baseResolveProviderService.getArgumentForParameter(it, i, this) } private class ObjectLiteralClassReference( override val sourcePsi: KtSuperTypeCallEntry, givenParent: UElement? ) : KotlinAbstractUElement(givenParent), USimpleNameReferenceExpression { override val javaPsi: PsiElement? get() = null override val psi: KtSuperTypeCallEntry get() = sourcePsi override fun resolve() = baseResolveProviderService.resolveCall(sourcePsi)?.containingClass override val uAnnotations: List<UAnnotation> get() = emptyList() override val resolvedName: String get() = identifier override val identifier: String get() = psi.name ?: referenceNameElement.sourcePsi?.text ?: "<error>" override val referenceNameElement: UElement get() = KotlinUIdentifier(psi.typeReference?.nameElement, this) } }
apache-2.0
aa94da56c8540d026453e9abf4a5fcfd
37.711111
158
0.724168
5.683524
false
false
false
false
K0zka/kerub
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/storage/share/iscsi/tgtd/TgtdIscsiShareExecutorTest.kt
2
2909
package com.github.kerubistan.kerub.planner.steps.storage.share.iscsi.tgtd import com.github.kerubistan.kerub.data.config.HostConfigurationDao import com.github.kerubistan.kerub.host.FireWall import com.github.kerubistan.kerub.host.HostManager import com.github.kerubistan.kerub.host.ServiceManager import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.VirtualStorageDevice import com.github.kerubistan.kerub.model.dynamic.VirtualStorageLvmAllocation import com.github.kerubistan.kerub.testLvmCapability import com.github.kerubistan.kerub.utils.junix.iscsi.tgtd.TgtAdmin import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import io.github.kerubistan.kroki.size.GB import org.apache.commons.io.input.NullInputStream import org.apache.commons.io.output.NullOutputStream import org.apache.sshd.client.channel.ChannelExec import org.apache.sshd.client.future.OpenFuture import org.apache.sshd.client.session.ClientSession import org.apache.sshd.client.subsystem.sftp.SftpClient import org.junit.Test import java.util.UUID class TgtdIscsiShareExecutorTest { private val hostConfigDao: HostConfigurationDao = mock() val hostManager: HostManager = mock() private val firewall: FireWall = mock() private val serviceManager: ServiceManager = mock() val session: ClientSession = mock() val channel: ChannelExec = mock() val sftp: SftpClient = mock() val openFuture: OpenFuture = mock() val host = Host( id = UUID.randomUUID(), address = "test-1.example.com", publicKey = "", dedicated = true ) val vStorage = VirtualStorageDevice( id = UUID.randomUUID(), name = "disk-1", expectations = listOf(), size = 16.GB ) @Test fun testExecute() { whenever(hostManager.getFireWall(any())).thenReturn(firewall) whenever(session.createExecChannel(any())).thenReturn(channel) whenever(channel.open()).thenReturn(openFuture) whenever(channel.invertedErr).thenReturn(NullInputStream(0)) whenever(channel.invertedOut).thenReturn(NullInputStream(0)) whenever(channel.out).thenReturn(NullOutputStream()) whenever(session.createSftpClient()).thenReturn(sftp) whenever(sftp.write(any())).thenReturn(NullOutputStream()) whenever(hostManager.getServiceManager(any())).thenReturn(serviceManager) TgtdIscsiShareExecutor(hostConfigDao, HostCommandExecutorStub(session), hostManager) .execute( step = TgtdIscsiShare( host = host, allocation = VirtualStorageLvmAllocation( hostId = host.id, path = "", actualSize = vStorage.size, vgName = "test-vg", capabilityId = testLvmCapability.id), vstorage = vStorage ) ) verify(firewall).open(eq(3260), eq("tcp")) verify(serviceManager).start(TgtAdmin) } }
apache-2.0
889bd3115580a4ece773168503af5853
35.375
86
0.768649
3.777922
false
true
false
false
google/playhvz
Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/chatlist/CreateChatDialog.kt
1
5258
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.app.playhvz.screens.chatlist import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import androidx.core.widget.doOnTextChanged import androidx.emoji.widget.EmojiEditText import androidx.fragment.app.DialogFragment import com.app.playhvz.R import com.app.playhvz.app.EspressoIdlingResource import com.app.playhvz.common.globals.CrossClientConstants.Companion.HUMAN import com.app.playhvz.common.globals.CrossClientConstants.Companion.ZOMBIE import com.app.playhvz.firebase.operations.ChatDatabaseOperations import com.app.playhvz.utils.SystemUtils import kotlinx.coroutines.runBlocking class CreateChatDialog(val gameId: String, val playerId: String) : DialogFragment() { companion object { private val TAG = CreateChatDialog::class.qualifiedName } private lateinit var allegianceFilterCheckbox: CheckBox private lateinit var allegianceHuman: RadioButton private lateinit var allegianceZombie: RadioButton private lateinit var dialogView: View private lateinit var errorLabel: TextView private lateinit var inputLabel: TextView private lateinit var inputText: EmojiEditText private lateinit var negativeButton: Button private lateinit var positiveButton: Button private lateinit var progressBar: ProgressBar private var chatName: String? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { dialogView = inflater.inflate(R.layout.dialog_create_chat, null) allegianceFilterCheckbox = dialogView.findViewById(R.id.allegiance_filter_checkbox) allegianceHuman = dialogView.findViewById(R.id.radio_human) allegianceZombie = dialogView.findViewById(R.id.radio_zombie) errorLabel = dialogView.findViewById(R.id.error_label) inputLabel = dialogView.findViewById(R.id.dialog_label) inputText = dialogView.findViewById(R.id.dialog_input) negativeButton = dialogView.findViewById(R.id.negative_button) positiveButton = dialogView.findViewById(R.id.positive_button) progressBar = dialogView.findViewById(R.id.progress_bar) inputText.doOnTextChanged { text, _, _, _ -> when { text.isNullOrEmpty() -> { positiveButton.isEnabled = false } else -> { positiveButton.isEnabled = true } } errorLabel.visibility = View.GONE } initDialogViews() return dialogView } private fun initDialogViews() { errorLabel.visibility = View.GONE inputLabel.setText(getString(R.string.chat_creation_name_label)) inputText.setHint(getString(R.string.chat_creation_name_hint)) positiveButton.setText(getString(R.string.button_create)) positiveButton.setOnClickListener { positiveButton.isEnabled = false createChat() } negativeButton.text = getString(R.string.button_cancel) negativeButton.setOnClickListener { this.dismiss() } allegianceFilterCheckbox.setOnClickListener { val enableSelection = allegianceFilterCheckbox.isChecked allegianceHuman.isEnabled = enableSelection allegianceZombie.isEnabled = enableSelection } } private fun createChat() { progressBar.visibility = View.VISIBLE val chatName = inputText.text.toString() val onSuccess = { progressBar.visibility = View.INVISIBLE dismiss() SystemUtils.hideKeyboard(requireView()) // TODO: open newly created chat room } val onFailure = { progressBar.visibility = View.INVISIBLE errorLabel.setText(R.string.join_game_error_label_player) errorLabel.visibility = View.VISIBLE positiveButton.isEnabled = false } var allegianceFilter = "none" if (allegianceFilterCheckbox.isChecked) { allegianceFilter = if (allegianceHuman.isChecked) { HUMAN } else { ZOMBIE } } runBlocking { EspressoIdlingResource.increment() ChatDatabaseOperations.asyncCreateChatRoom( gameId, playerId, chatName, allegianceFilter, onSuccess, onFailure ) EspressoIdlingResource.decrement() } } }
apache-2.0
26e8a8233cfe12fee32537dc709518de
36.297872
91
0.672879
5.017176
false
false
false
false
ebean-orm/avaje-ebeanorm-examples
e-kotlin-maven/src/main/java/org/example/domain/Contact.kt
1
936
package org.example.domain; import com.avaje.ebean.Model import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.validation.constraints.NotNull import javax.validation.constraints.Size /** * Contact entity bean. */ @Entity @Table(name = "be_contact") public class Contact() : BaseModel() { @Size(max = 50) public var firstName: String? = null @Size(max = 50) public var lastName: String? = null @Size(max = 200) public var email: String? = null; @Size(max = 20) public var phone: String? = null; @NotNull @ManyToOne(optional = false) public var customer: Customer? = null; /** * Construct with firstName and lastName. */ constructor(firstName: String, lastName: String) : this() { this.firstName = firstName; this.lastName = lastName; } companion object : Model.Find<Long, Contact>() {} }
apache-2.0
1cae8bbb703468a6260541d508627306
20.272727
61
0.700855
3.729084
false
false
false
false
stoyicker/dinger
data/src/main/kotlin/data/tinder/dislike/DislikeSourceModule.kt
1
1786
package data.tinder.dislike import com.nytimes.android.external.store3.base.Fetcher import com.nytimes.android.external.store3.base.impl.FluentMemoryPolicyBuilder import com.nytimes.android.external.store3.base.impl.FluentStoreBuilder import com.nytimes.android.external.store3.base.impl.StalePolicy import com.nytimes.android.external.store3.base.impl.Store import com.nytimes.android.external.store3.middleware.moshi.MoshiParserFactory import com.squareup.moshi.Moshi import dagger.Lazy import dagger.Module import dagger.Provides import data.crash.CrashReporterModule import data.network.ParserModule import data.tinder.TinderApi import data.tinder.TinderApiModule import okio.BufferedSource import reporter.CrashReporter import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module(includes = [ ParserModule::class, TinderApiModule::class, CrashReporterModule::class]) internal class DislikeSourceModule { @Provides @Singleton fun store(moshiBuilder: Moshi.Builder, api: TinderApi) = FluentStoreBuilder.parsedWithKey<String, BufferedSource, DislikeResponse>( Fetcher { fetch(it, api) }) { parsers = listOf(MoshiParserFactory.createSourceParser( moshiBuilder.build(), DislikeResponse::class.java)) memoryPolicy = FluentMemoryPolicyBuilder.build { expireAfterWrite = 1 expireAfterTimeUnit = TimeUnit.SECONDS memorySize = 0 } stalePolicy = StalePolicy.NETWORK_BEFORE_STALE } @Provides @Singleton fun source(store: Lazy<Store<DislikeResponse, String>>, crashReporter: CrashReporter) = DislikeSource(store, crashReporter) private fun fetch(requestParameters: String, api: TinderApi) = api.dislike(requestParameters).map { it.source() } }
mit
bf7aa153a482a86183838f0155092f28
37
80
0.773236
4.26253
false
false
false
false
androidx/androidx
compose/runtime/runtime/integration-tests/src/androidAndroidTest/kotlin/androidx/compose/runtime/ProduceStateTests.kt
3
1756
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.runtime import androidx.test.filters.MediumTest import androidx.compose.ui.test.junit4.createComposeRule import kotlinx.coroutines.channels.Channel import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import androidx.test.ext.junit.runners.AndroidJUnit4 import kotlin.test.assertEquals @MediumTest @RunWith(AndroidJUnit4::class) class ProduceStateTests { @get:Rule val rule = createComposeRule() @Test fun testProducingState() { var observedResult = -1 val emitter = Channel<Int>(Channel.BUFFERED) rule.setContent { val state by produceState(0, emitter) { for (item in emitter) { value = item } } DisposableEffect(state) { observedResult = state onDispose { } } } assertEquals(0, observedResult, "observedResult after initial composition") emitter.trySend(1) rule.runOnIdle { assertEquals(1, observedResult, "observedResult after emitting new value") } } }
apache-2.0
2e06c08d38b460f64cae7a7457f4df56
28.779661
86
0.67369
4.514139
false
true
false
false
androidx/androidx
compose/ui/ui-text/src/androidAndroidTest/kotlin/androidx/compose/ui/text/platform/TextTestExtensions.kt
3
1716
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.platform import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Typeface import android.text.Layout import android.text.TextPaint import androidx.compose.ui.text.android.InternalPlatformTextApi import androidx.compose.ui.text.android.TextLayout fun Layout.bitmap(): Bitmap { val bitmap = Bitmap.createBitmap( this.width, this.height, Bitmap.Config.ARGB_8888 ) this.draw(Canvas(bitmap)) return bitmap } @OptIn(InternalPlatformTextApi::class) fun TextLayout.bitmap(): Bitmap { return layout.bitmap() } fun Typeface.bitmap(): Bitmap { return bitmap("abc") } @OptIn(InternalPlatformTextApi::class) fun Typeface.bitmap(text: String): Bitmap { val fontSize = 10.0f val paint = TextPaint() paint.textSize = fontSize paint.typeface = this // 1.5 is a random number to increase the size of bitmap a little val layout = TextLayout( charSequence = text, textPaint = paint, width = text.length * fontSize * 1.5f ) return layout.bitmap() }
apache-2.0
28bc95d738ed6db8e3e4dbce831b7708
28.101695
75
0.72028
4.095465
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-database/src/main/kotlin/com/onyx/buffer/BufferObjectType.kt
1
3150
package com.onyx.buffer import com.onyx.extension.common.ClassMetadata import com.onyx.persistence.IManagedEntity import com.onyx.persistence.context.SchemaContext import java.util.Date /** * This Enum indicates all of the different types of objects that can be serialized */ enum class BufferObjectType constructor(private val type: Class<*>?) { NULL(null), REFERENCE(null), ENUM(Enum::class.java), // Primitives BYTE(Byte::class.javaPrimitiveType), INT(Int::class.javaPrimitiveType), LONG(Long::class.javaPrimitiveType), SHORT(Short::class.javaPrimitiveType), FLOAT(Float::class.javaPrimitiveType), DOUBLE(Double::class.javaPrimitiveType), BOOLEAN(Boolean::class.javaPrimitiveType), CHAR(Char::class.javaPrimitiveType), // Primitive Arrays BYTE_ARRAY(ByteArray::class.java), INT_ARRAY(IntArray::class.java), LONG_ARRAY(LongArray::class.java), SHORT_ARRAY(ShortArray::class.java), FLOAT_ARRAY(FloatArray::class.java), DOUBLE_ARRAY(DoubleArray::class.java), BOOLEAN_ARRAY(BooleanArray::class.java), CHAR_ARRAY(CharArray::class.java), OBJECT_ARRAY(Array<Any>::class.java), OTHER_ARRAY(Array<Any>::class.java), // Mutable MUTABLE_BYTE(Byte::class.javaObjectType), MUTABLE_INT(Int::class.javaObjectType), MUTABLE_LONG(Long::class.javaObjectType), MUTABLE_SHORT(Short::class.javaObjectType), MUTABLE_FLOAT(Float::class.javaObjectType), MUTABLE_DOUBLE(Double::class.javaObjectType), MUTABLE_BOOLEAN(Boolean::class.javaObjectType), MUTABLE_CHAR(Char::class.javaObjectType), // Object Serializable BUFFERED(BufferStreamable::class.java), // Objects DATE(Date::class.java), STRING(String::class.java), CLASS(Class::class.java), COLLECTION(Collection::class.java), MAP(Map::class.java), ENTITY(IManagedEntity::class.java), OTHER(null); companion object { /** * Get Object type for the class * * @param `value` Object in Question * @return The serializer type that correlates to that class. */ fun getTypeCodeForClass(value: Any?, context: SchemaContext?): BufferObjectType { if (value == null) return NULL val type = value.javaClass if(context != null && ClassMetadata.MANAGED_ENTITY.isAssignableFrom(type)) return ENTITY if (type.isEnum) return ENUM else if (value is IManagedEntity && context == null) return OTHER return enumValues .firstOrNull { it.type != null && it.type.isAssignableFrom(type) } ?.let { if (it === OBJECT_ARRAY && type != Array<Any>::class.java) { OTHER_ARRAY } else it } ?: OTHER } // Java in all of its wisdom clones the array each time you invoke values. // Surprisingly this is expensive so, this is a way around that. val enumValues = values() } }
agpl-3.0
b081c019acdfd3376e6780622dbf5f11
29.882353
89
0.628571
4.532374
false
false
false
false
3sidedcube/react-native-navigation
lib/android/app/src/main/java/com/reactnativenavigation/viewcontrollers/modal/ModalAnimator.kt
1
5468
package com.reactnativenavigation.viewcontrollers.modal import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.AnimatorSet import android.content.Context import com.reactnativenavigation.viewcontrollers.common.BaseAnimator import com.reactnativenavigation.options.AnimationOptions import com.reactnativenavigation.options.FadeAnimation import com.reactnativenavigation.utils.ScreenAnimationListener import com.reactnativenavigation.viewcontrollers.viewcontroller.ViewController import com.reactnativenavigation.views.element.TransitionAnimatorCreator import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import java.util.* open class ModalAnimator @JvmOverloads constructor( context: Context, private val transitionAnimatorCreator: TransitionAnimatorCreator = TransitionAnimatorCreator() ) : BaseAnimator(context) { val isRunning: Boolean get() = runningAnimators.isNotEmpty() private val runningAnimators: MutableMap<ViewController<*>, Animator?> = HashMap() open fun show(appearing: ViewController<*>, disappearing: ViewController<*>?, show: AnimationOptions, listener: ScreenAnimationListener) { GlobalScope.launch(Dispatchers.Main.immediate) { val set = createShowModalAnimator(appearing, listener) if (show.hasElementTransitions() && disappearing != null) { setupShowModalWithSharedElementTransition(disappearing, appearing, show, set) } else { set.playTogether(show.getAnimation(appearing.view, getDefaultPushAnimation(appearing.view))) } set.start() } } open fun dismiss(appearing: ViewController<*>?, disappearing: ViewController<*>, dismiss: AnimationOptions, listener: ScreenAnimationListener) { GlobalScope.launch(Dispatchers.Main.immediate) { if (runningAnimators.containsKey(disappearing)) { runningAnimators[disappearing]?.cancel() listener.onEnd() } else { val set = createDismissAnimator(disappearing, listener) if (dismiss.hasElementTransitions() && appearing != null) { setupDismissAnimationWithSharedElementTransition(disappearing, appearing, dismiss, set) } else { set.play(dismiss.getAnimation(disappearing.view, getDefaultPopAnimation(disappearing.view))) } set.start() } } } private fun createShowModalAnimator(appearing: ViewController<*>, listener: ScreenAnimationListener): AnimatorSet { val set = AnimatorSet() set.addListener(object : AnimatorListenerAdapter() { private var isCancelled = false override fun onAnimationStart(animation: Animator) { runningAnimators[appearing] = animation listener.onStart() } override fun onAnimationCancel(animation: Animator) { isCancelled = true listener.onCancel() } override fun onAnimationEnd(animation: Animator) { runningAnimators.remove(appearing) if (!isCancelled) listener.onEnd() } }) return set } private suspend fun setupShowModalWithSharedElementTransition( disappearing: ViewController<*>, appearing: ViewController<*>, show: AnimationOptions, set: AnimatorSet ) { val fade = if (show.isFadeAnimation()) show else FadeAnimation().content val transitionAnimators = transitionAnimatorCreator.create(show, fade, disappearing, appearing) set.playTogether(fade.getAnimation(appearing.view), transitionAnimators) transitionAnimators.listeners.forEach { listener: Animator.AnimatorListener -> set.addListener(listener) } transitionAnimators.removeAllListeners() } private fun createDismissAnimator(disappearing: ViewController<*>, listener: ScreenAnimationListener): AnimatorSet { val set = AnimatorSet() set.addListener(object : AnimatorListenerAdapter() { private var isCancelled = false override fun onAnimationStart(animation: Animator) { listener.onStart() } override fun onAnimationCancel(animation: Animator) { isCancelled = true listener.onCancel() } override fun onAnimationEnd(animation: Animator) { runningAnimators.remove(disappearing) if (!isCancelled) listener.onEnd() } }) return set } private suspend fun setupDismissAnimationWithSharedElementTransition( disappearing: ViewController<*>, appearing: ViewController<*>, dismiss: AnimationOptions, set: AnimatorSet ) { val fade = if (dismiss.isFadeAnimation()) dismiss else FadeAnimation(true).content val transitionAnimators = transitionAnimatorCreator.create(dismiss, fade, disappearing, appearing) set.playTogether(fade.getAnimation(disappearing.view), transitionAnimators) transitionAnimators.listeners.forEach { listener: Animator.AnimatorListener -> set.addListener(listener) } transitionAnimators.removeAllListeners() } }
mit
7cc45e7cf78177dc615c87a74b24e2b2
43.096774
148
0.677396
6.002195
false
false
false
false
jwren/intellij-community
plugins/grazie/src/main/kotlin/com/intellij/grazie/spellcheck/GrazieSpellchecker.kt
1
4412
// 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.grazie.spellcheck import com.intellij.grazie.GrazieConfig import com.intellij.grazie.GraziePlugin import com.intellij.grazie.detector.heuristics.rule.RuleFilter import com.intellij.grazie.detector.utils.collections.emptyLinkedSet import com.intellij.grazie.ide.msg.GrazieStateLifecycle import com.intellij.grazie.jlanguage.Lang import com.intellij.grazie.jlanguage.LangTool import com.intellij.grazie.utils.LinkedSet import com.intellij.grazie.utils.toLinkedSet import com.intellij.openapi.application.ex.ApplicationUtil import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.ClassLoaderUtil import org.languagetool.JLanguageTool import org.languagetool.rules.spelling.SpellingCheckRule import org.slf4j.LoggerFactory import java.util.concurrent.Callable object GrazieSpellchecker : GrazieStateLifecycle { private const val MAX_SUGGESTIONS_COUNT = 3 private val filter by lazy { RuleFilter.withAllBuiltIn() } private fun filterCheckers(word: String): Set<SpellerTool> { val checkers = this.checkers.value if (checkers.isEmpty()) return emptySet() val preferred = filter.filter(listOf(word)).preferred return checkers.filter { checker -> preferred.any { checker.lang.equalsTo(it) } }.toSet() } private val logger = LoggerFactory.getLogger(GrazieSpellchecker::class.java) data class SpellerTool(val tool: JLanguageTool, val lang: Lang, val speller: SpellingCheckRule, val suggestLimit: Int) { fun check(word: String): Boolean? = synchronized(speller) { if (word.isBlank()) return true ClassLoaderUtil.computeWithClassLoader<Boolean, Throwable>(GraziePlugin.classLoader) { if (speller.match(tool.getRawAnalyzedSentence(word)).isEmpty()) { if (!speller.isMisspelled(word)) true else { // if the speller does not return matches, but the word is still misspelled (not in the dictionary), // then this word was ignored by the rule (e.g. alien word), and we cannot be sure about its correctness // let's try adding a small change to a word to see if it's alien val mutated = word + word.last() + word.last() if (speller.match(tool.getRawAnalyzedSentence(mutated)).isEmpty()) null else true } } else false } } fun suggest(text: String): Set<String> = synchronized(speller) { ClassLoaderUtil.computeWithClassLoader<Set<String>, Throwable>(GraziePlugin.classLoader) { speller.match(tool.getRawAnalyzedSentence(text)) .flatMap { match -> match.suggestedReplacements.map { text.replaceRange(match.fromPos, match.toPos, it) } } .take(suggestLimit).toSet() } } } @Volatile private var checkers: Lazy<LinkedSet<SpellerTool>> = initCheckers() private fun initCheckers() = lazy(LazyThreadSafetyMode.PUBLICATION) { GrazieConfig.get().availableLanguages.filterNot { it.isEnglish() }.mapNotNull { lang -> ProgressManager.checkCanceled() val tool = LangTool.getTool(lang) tool.allSpellingCheckRules.firstOrNull()?.let { SpellerTool(tool, lang, it, MAX_SUGGESTIONS_COUNT) } }.toLinkedSet() } override fun update(prevState: GrazieConfig.State, newState: GrazieConfig.State) { checkers = initCheckers() LangTool.runAsync { checkers.value } } fun isCorrect(word: String): Boolean? { val myCheckers = filterCheckers(word) var isAlien = true myCheckers.forEach { speller -> when (speller.check(word)) { true -> return true false -> isAlien = false } } return if (isAlien) null else false } /** * Checks text for spelling mistakes. */ fun getSuggestions(word: String): LinkedSet<String> { val filtered = filterCheckers(word) if (filtered.isEmpty()) return emptyLinkedSet() val indicator = EmptyProgressIndicator.notNullize(ProgressManager.getGlobalProgressIndicator()) return ApplicationUtil.runWithCheckCanceled(Callable { filtered.map { speller -> indicator.checkCanceled() speller.suggest(word) }.flatten().toLinkedSet() }, indicator) } }
apache-2.0
8789974b4797b31a031193f8de3a77bb
37.701754
140
0.714869
4.359684
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/completion/tests/testData/smart/propertyDelegate/ExplicitVarType.kt
13
1391
import kotlin.reflect.KProperty class X1 { operator fun getValue(thisRef: C, property: KProperty<*>): String = "" operator fun setValue(thisRef: C, property: KProperty<*>, value: String) {} } class X2 { operator fun getValue(thisRef: C, property: KProperty<*>): String = "" operator fun setValue(thisRef: C, property: KProperty<*>, value: CharSequence) {} } class X3 { operator fun getValue(thisRef: C, property: KProperty<*>): CharSequence = "" operator fun setValue(thisRef: C, property: KProperty<*>, value: String) {} } fun createX1() = X1() fun createX2() = X2() fun createX3() = X3() class C { var property: CharSequence by <caret> } // ABSENT: lazy // EXIST: { itemText: "Delegates.notNull", tailText:"() (kotlin.properties)", typeText: "ReadWriteProperty<Any?, CharSequence>", attributes:"" } // EXIST: { itemText: "Delegates.observable", tailText:"(initialValue: CharSequence, crossinline onChange: (KProperty<*>, CharSequence, CharSequence) -> Unit) (kotlin.properties)", typeText: "ReadWriteProperty<Any?, CharSequence>", attributes:"" } // EXIST: { itemText: "Delegates.vetoable", tailText:"(initialValue: CharSequence, crossinline onChange: (KProperty<*>, CharSequence, CharSequence) -> Boolean) (kotlin.properties)", typeText: "ReadWriteProperty<Any?, CharSequence>", attributes:"" } // ABSENT: createX1 // EXIST: createX2 // ABSENT: createX3
apache-2.0
fcaef430e42786944274cebdaa593821
42.46875
248
0.703091
4.079179
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/structuralsearch/countFilter/mmStatementInDoWhile.kt
4
346
fun foo() { var x = 0 <warning descr="SSR">do { } while (false)</warning> <warning descr="SSR">do { x += 1 } while (false)</warning> <warning descr="SSR">do { x += 1 x *= 2 } while (false)</warning> do { x += 1 x *= 2 x *= x } while (false) print(x) }
apache-2.0
84b3d297d39dbe158799d3b50b5e616f
13.416667
29
0.413295
3.425743
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/util/expectActualUtil.kt
1
7806
// 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.util import com.intellij.openapi.module.Module import com.intellij.openapi.util.NlsContexts import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.caches.project.ModuleSourceInfo import org.jetbrains.kotlin.idea.caches.project.implementedDescriptors import org.jetbrains.kotlin.idea.caches.project.implementingDescriptors import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.resolveToParameterDescriptorIfAny import org.jetbrains.kotlin.idea.core.toDescriptor import org.jetbrains.kotlin.idea.util.application.executeCommand import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.KtConstructor import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtEnumEntry import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.multiplatform.ExpectedActualResolver fun MemberDescriptor.expectedDescriptors() = (module.implementedDescriptors + module) .mapNotNull { it.declarationOf(this) } // TODO: Sort out the cases with multiple expected descriptors fun MemberDescriptor.expectedDescriptor() = expectedDescriptors().firstOrNull() fun KtDeclaration.expectedDeclarationIfAny(): KtDeclaration? { val expectedDescriptor = (toDescriptor() as? MemberDescriptor)?.expectedDescriptor() ?: return null return DescriptorToSourceUtils.descriptorToDeclaration(expectedDescriptor) as? KtDeclaration } fun DeclarationDescriptor.liftToExpected(): DeclarationDescriptor? { if (this is MemberDescriptor) { return when { isExpect -> this isActual -> expectedDescriptor() else -> null } } if (this is ValueParameterDescriptor) { val containingExpectedDescriptor = containingDeclaration.liftToExpected() as? CallableDescriptor ?: return null return containingExpectedDescriptor.valueParameters.getOrNull(index) } return null } fun KtDeclaration.liftToExpected(): KtDeclaration? { val descriptor = resolveToDescriptorIfAny() val expectedDescriptor = descriptor?.liftToExpected() ?: return null return DescriptorToSourceUtils.descriptorToDeclaration(expectedDescriptor) as? KtDeclaration } fun KtParameter.liftToExpected(): KtParameter? { val parameterDescriptor = resolveToParameterDescriptorIfAny() val expectedDescriptor = parameterDescriptor?.liftToExpected() ?: return null return DescriptorToSourceUtils.descriptorToDeclaration(expectedDescriptor) as? KtParameter } fun ModuleDescriptor.hasDeclarationOf(descriptor: MemberDescriptor) = declarationOf(descriptor) != null private fun ModuleDescriptor.declarationOf(descriptor: MemberDescriptor): DeclarationDescriptor? = with(ExpectedActualResolver) { val expectedCompatibilityMap = findExpectedForActual(descriptor, this@declarationOf) expectedCompatibilityMap?.get(ExpectedActualResolver.Compatibility.Compatible)?.firstOrNull() ?: expectedCompatibilityMap?.values?.flatten()?.firstOrNull() } fun ModuleDescriptor.hasActualsFor(descriptor: MemberDescriptor) = actualsFor(descriptor).isNotEmpty() fun ModuleDescriptor.actualsFor(descriptor: MemberDescriptor, checkCompatible: Boolean = false): List<DeclarationDescriptor> = with(ExpectedActualResolver) { if (checkCompatible) { descriptor.findCompatibleActualForExpected(this@actualsFor) } else { descriptor.findAnyActualForExpected(this@actualsFor) } }.filter { (it as? MemberDescriptor)?.isEffectivelyActual() == true } private fun MemberDescriptor.isEffectivelyActual(checkConstructor: Boolean = true): Boolean = isActual || isEnumEntryInActual() || isConstructorInActual(checkConstructor) private fun MemberDescriptor.isConstructorInActual(checkConstructor: Boolean) = checkConstructor && this is ClassConstructorDescriptor && containingDeclaration.isEffectivelyActual(checkConstructor) private fun MemberDescriptor.isEnumEntryInActual() = (DescriptorUtils.isEnumEntry(this) && (containingDeclaration as? MemberDescriptor)?.isActual == true) fun DeclarationDescriptor.actualsForExpected(): Collection<DeclarationDescriptor> { if (this is MemberDescriptor) { if (!this.isExpect) return emptyList() return (module.implementingDescriptors + module).flatMap { it.actualsFor(this) } } if (this is ValueParameterDescriptor) { return containingDeclaration.actualsForExpected().mapNotNull { (it as? CallableDescriptor)?.valueParameters?.getOrNull(index) } } return emptyList() } fun KtDeclaration.hasAtLeastOneActual() = actualsForExpected().isNotEmpty() // null means "any platform" here fun KtDeclaration.actualsForExpected(module: Module? = null): Set<KtDeclaration> = resolveToDescriptorIfAny(BodyResolveMode.FULL) ?.actualsForExpected() ?.filter { module == null || (it.module.getCapability(ModuleInfo.Capability) as? ModuleSourceInfo)?.module == module } ?.mapNotNullTo(LinkedHashSet()) { DescriptorToSourceUtils.descriptorToDeclaration(it) as? KtDeclaration } ?: emptySet() fun KtDeclaration.isExpectDeclaration(): Boolean = if (hasExpectModifier()) true else containingClassOrObject?.isExpectDeclaration() == true fun KtDeclaration.hasMatchingExpected() = (toDescriptor() as? MemberDescriptor)?.expectedDescriptor() != null fun KtDeclaration.isEffectivelyActual(checkConstructor: Boolean = true): Boolean = when { hasActualModifier() -> true this is KtEnumEntry || checkConstructor && this is KtConstructor<*> -> containingClass()?.hasActualModifier() == true else -> false } fun KtDeclaration.runOnExpectAndAllActuals(checkExpect: Boolean = true, useOnSelf: Boolean = false, f: (KtDeclaration) -> Unit) { if (hasActualModifier()) { val expectElement = liftToExpected() expectElement?.actualsForExpected()?.forEach { if (it !== this) { f(it) } } expectElement?.let { f(it) } } else if (!checkExpect || isExpectDeclaration()) { actualsForExpected().forEach { f(it) } } if (useOnSelf) f(this) } fun KtDeclaration.collectAllExpectAndActualDeclaration(withSelf: Boolean = true): Set<KtDeclaration> = when { isExpectDeclaration() -> actualsForExpected() hasActualModifier() -> liftToExpected()?.let { it.actualsForExpected() + it - this }.orEmpty() else -> emptySet() }.let { if (withSelf) it + this else it } fun KtDeclaration.runCommandOnAllExpectAndActualDeclaration( @NlsContexts.Command command: String = "", writeAction: Boolean = false, withSelf: Boolean = true, f: (KtDeclaration) -> Unit ) { val (pointers, project) = runReadAction { collectAllExpectAndActualDeclaration(withSelf).map { it.createSmartPointer() } to project } fun process() { for (pointer in pointers) { val declaration = pointer.element ?: continue f(declaration) } } if (writeAction) { project.executeWriteCommand(command, ::process) } else { project.executeCommand(command, command = ::process) } }
apache-2.0
76a4119464aa4f3074b0660850a50985
41.895604
158
0.753395
5.065542
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/branchedTransformations/IntroduceWhenSubjectInspection.kt
4
1627
// 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.branchedTransformations import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.inspections.AbstractApplicabilityBasedInspection import org.jetbrains.kotlin.idea.intentions.branchedTransformations.getSubjectToIntroduce import org.jetbrains.kotlin.idea.intentions.branchedTransformations.introduceSubject import org.jetbrains.kotlin.idea.util.textRangeIn import org.jetbrains.kotlin.psi.KtWhenExpression class IntroduceWhenSubjectInspection : AbstractApplicabilityBasedInspection<KtWhenExpression>(KtWhenExpression::class.java) { override fun isApplicable(element: KtWhenExpression) = element.getSubjectToIntroduce() != null override fun inspectionHighlightRangeInElement(element: KtWhenExpression) = element.whenKeyword.textRangeIn(element) override fun inspectionText(element: KtWhenExpression) = KotlinBundle.message("when.with.subject.should.be.used") override val defaultFixText get() = KotlinBundle.message("introduce.when.subject") override fun fixText(element: KtWhenExpression): String { val subject = element.getSubjectToIntroduce() ?: return "" return KotlinBundle.message("introduce.0.as.subject.0.when", subject.text) } override fun applyTo(element: KtWhenExpression, project: Project, editor: Editor?) { element.introduceSubject() } }
apache-2.0
8df9fd48dcd9b661722360cc2b407542
49.84375
158
0.808236
4.960366
false
false
false
false
erdo/asaf-project
example-kt-07apollo/src/androidTest/java/foo/bar/example/foreapollokt/DrawableMatcher.kt
1
2168
package foo.bar.example.foreapollokt import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.drawable.Drawable import android.view.View import android.widget.ImageView import org.hamcrest.Description import org.hamcrest.TypeSafeMatcher /** * * https://medium.com/@dbottillo/android-ui-test-espresso-matcher-for-imageview-1a28c832626f * https://github.com/dbottillo/Blog/blob/espresso_match_imageview/app/src/androidTest/java/com/danielebottillo/blog/config/DrawableMatcher.java * */ class DrawableMatcher internal constructor(private val expectedId: Int) : TypeSafeMatcher<View>(View::class.java) { private var resourceName: String? = null override fun matchesSafely(target: View): Boolean { if (target !is ImageView) { return false } if (expectedId == EMPTY) { return target.drawable == null } if (expectedId == ANY) { return target.drawable != null } val resources = target.getContext().resources val expectedDrawable = resources.getDrawable(expectedId) resourceName = resources.getResourceEntryName(expectedId) if (expectedDrawable == null) { return false } val bitmap = getBitmap(target.drawable) val otherBitmap = getBitmap(expectedDrawable) return bitmap.sameAs(otherBitmap) } private fun getBitmap(drawable: Drawable): Bitmap { val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) drawable.setBounds(0, 0, canvas.width, canvas.height) drawable.draw(canvas) return bitmap } override fun describeTo(description: Description) { description.appendText("with drawable from resource id: ") description.appendValue(expectedId) if (resourceName != null) { description.appendText("[") description.appendText(resourceName) description.appendText("]") } } companion object { internal val EMPTY = -1 internal val ANY = -2 } }
apache-2.0
61793f2f6a480008ba5814b4dc4ff1ba
32.353846
144
0.674815
4.612766
false
false
false
false
Jire/Charlatano
src/main/kotlin/com/charlatano/game/entity/Weapon.kt
1
1717
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.game.entity import com.charlatano.game.CSGO.csgoEXE import com.charlatano.game.Weapons import com.charlatano.game.me import com.charlatano.game.netvars.NetVarOffsets import com.charlatano.game.netvars.NetVarOffsets.flNextPrimaryAttack import com.charlatano.game.netvars.NetVarOffsets.iClip1 import com.charlatano.utils.extensions.uint import org.jire.kna.float import org.jire.kna.short typealias Weapon = Long internal fun Weapon.bullets() = csgoEXE.uint(this + iClip1) internal fun Weapon.nextPrimaryAttack() = csgoEXE.float(this + flNextPrimaryAttack).toDouble() internal fun Weapon.canFire(): Boolean = if (bullets() > 0) { val nextAttack = nextPrimaryAttack() nextAttack <= 0 || nextAttack < me.time() } else false internal fun Weapon.type(): Weapons { var id = 42 if (this > 0) id = csgoEXE.short(this + NetVarOffsets.iItemDefinitionIndex).toInt() return Weapons[id] }
agpl-3.0
4d5f0c86cef8159b2502ecc648a3c2bf
34.791667
94
0.761794
3.67666
false
false
false
false
general-mobile/kotlin-android-mvp-starter
{{cookiecutter.repo_name}}/app/src/main/kotlin/utils/timber/CrashReportTree.kt
1
882
package {{ cookiecutter.package_name }}.utils.timber import android.util.Log import com.crashlytics.android.Crashlytics import timber.log.Timber class CrashReportTree : Timber.Tree() { private val CRASHLYTICS_KEY_PRIORITY = "priority" private val CRASHLYTICS_KEY_TAG = "tag" private val CRASHLYTICS_KEY_MESSAGE = "message" override fun log(priority: Int, tag: String, message: String, t: Throwable?) { if (priority == Log.VERBOSE || priority == Log.DEBUG || priority == Log.INFO) { return } Crashlytics.setInt(CRASHLYTICS_KEY_PRIORITY, priority) Crashlytics.setString(CRASHLYTICS_KEY_TAG, tag) Crashlytics.setString(CRASHLYTICS_KEY_MESSAGE, message) if (t == null) { Crashlytics.logException(Exception(message)) } else { Crashlytics.logException(t) } } }
mit
34b8f708310c167259ccf25ae46f83ef
29.413793
87
0.65873
4.121495
false
false
false
false
sg26565/hott-transmitter-config
Test/src/main/kotlin/Coroutines.kt
1
1806
import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlin.concurrent.thread fun main1() { val lock = Object() println("start") thread { println("thread start") Thread.sleep(1000) synchronized(lock) { println("notify") lock.notify() } println("thread stop") } synchronized(lock) { println("wait") lock.wait() } println("done") } class FixedPool(val workerCount: Int) { val channel = Channel<Task>() val jobs = mutableListOf<Job>() init { start() // start immediately } fun start() { repeat(workerCount) { i -> jobs.add(GlobalScope.launch { // or use your own coroutine context for (task in channel) { println("worker-$i starts ${task.name}") task() println("worker-$i finished ${task.name}") } }) } } fun execute(block: Task) { GlobalScope.launch(Dispatchers.Unconfined) { // seems safe to use Unconfined channel.send(block) } } suspend fun join() { for (j in jobs) j.join() } fun close() = channel.close() } class Task(val name: String, val time: Long) { operator fun invoke() { val start = System.currentTimeMillis() val stop = start + time while (System.currentTimeMillis() < stop); } } fun random() = (Math.random() * 10000).toLong() fun main() { runBlocking { val pool = FixedPool(8) repeat(100) { i-> pool.execute(Task(i.toString(), random())) } // We must wait; in long running app maybe not needed pool.close() pool.join() } }
lgpl-3.0
e18e509b071eb32570f0a073c6abf755
20.5
84
0.529347
4.3
false
false
false
false
minibugdev/DrawableBadge
library/src/main/java/com/minibugdev/drawablebadge/DrawableBadge.kt
1
7402
package com.minibugdev.drawablebadge import android.content.Context import android.graphics.* import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.text.TextPaint import android.view.Gravity import androidx.annotation.* import androidx.core.content.ContextCompat import androidx.core.content.res.ResourcesCompat import androidx.core.graphics.drawable.DrawableCompat class DrawableBadge private constructor(val context: Context, @ColorInt val textColor: Int, @ColorInt val badgeColor: Int, @ColorInt val badgeBorderColor: Int, val badgeBorderSize: Float, val badgeSize: Float, val badgeGravity: Int, val badgeMargin: Float, val bitmap: Bitmap, val isShowBorder: Boolean, val maximumCounter: Int, val isShowCounter: Boolean,){ class Builder(private val context: Context) { @ColorInt private var textColor: Int? = null @ColorInt private var badgeColor: Int? = null @ColorInt private var badgeBorderColor: Int? = null private var badgeBorderSize: Float? = null private var badgeSize: Float? = null private var badgeGravity: Int? = null private var badgeMargin: Float? = null private var bitmap: Bitmap? = null private var isShowBorder: Boolean? = null private var maximumCounter: Int? = null private var isShowCounter: Boolean? = null private fun createBitmapFromDrawable(drawable: Drawable): Bitmap { val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) drawable.setBounds(0, 0, canvas.width, canvas.height) drawable.draw(canvas) return bitmap } fun drawableResId(@DrawableRes drawableRes: Int) = apply { val res = context.resources bitmap = BitmapFactory.decodeResource(res, drawableRes) if (bitmap == null) { ResourcesCompat.getDrawable(res, drawableRes, null) ?.current ?.let { drawable(it) } } } fun drawable(drawable: Drawable): Builder = apply { val drawableCompat = DrawableCompat.wrap(drawable) bitmap = when (drawableCompat) { is BitmapDrawable -> drawableCompat.bitmap else -> createBitmapFromDrawable(drawableCompat) } } fun bitmap(bitmap: Bitmap) = apply { this.bitmap = bitmap } fun textColor(@ColorRes textColorRes: Int) = apply { this.textColor = ContextCompat.getColor(context, textColorRes) } fun badgeColor(@ColorRes badgeColorRes: Int) = apply { this.badgeColor = ContextCompat.getColor(context, badgeColorRes) } fun badgeBorderColor(@ColorRes badgeBorderColorRes: Int) = apply { this.badgeBorderColor = ContextCompat.getColor(context, badgeBorderColorRes) } fun badgeBorderSize(@DimenRes badgeBorderSize: Int) = apply { this.badgeBorderSize = context.resources.getDimensionPixelOffset(badgeBorderSize) .toFloat() } fun badgeBorderSize(@Px badgeBorderSize: Float) = apply { this.badgeBorderSize = badgeBorderSize } fun badgeSize(@DimenRes badgeSize: Int) = apply { this.badgeSize = context.resources.getDimensionPixelOffset(badgeSize) .toFloat() } fun badgeSize(@Px badgeSize: Float) = apply { this.badgeSize = badgeSize } fun badgeGravity(badgeGravity: Int) = apply { this.badgeGravity = badgeGravity } fun badgeMargin(@DimenRes badgeMargin: Int) = apply { this.badgeMargin = context.resources.getDimensionPixelOffset(badgeMargin) .toFloat() } fun badgeMargin(@Px badgeMargin: Float) = apply { this.badgeMargin = badgeMargin } fun showBorder(isShowBorder: Boolean) = apply { this.isShowBorder = isShowBorder } fun maximumCounter(maximumCounter: Int) = apply { this.maximumCounter = maximumCounter } fun showCounter(isShowCounter: Boolean) = apply { this.isShowCounter = isShowCounter } fun build(): DrawableBadge { if (bitmap == null) throw IllegalArgumentException("Badge drawable/bitmap can not be null.") if (badgeSize == null) badgeSize(R.dimen.default_badge_size) if (textColor == null) textColor(R.color.default_badge_text_color) if (badgeColor == null) badgeColor(R.color.default_badge_color) if (badgeBorderColor == null) badgeBorderColor(R.color.default_badge_border_color) if (badgeBorderSize == null) badgeBorderSize(R.dimen.default_badge_border_size) if (badgeGravity == null) badgeGravity(Gravity.TOP or Gravity.END) if (isShowBorder == null) showBorder(true) if (maximumCounter == null) maximumCounter(MAXIMUM_COUNT) if (isShowCounter == null) showCounter(true) return DrawableBadge( context = context, bitmap = bitmap!!, textColor = textColor!!, badgeColor = badgeColor!!, badgeBorderColor = badgeBorderColor!!, badgeBorderSize = badgeBorderSize!!, badgeSize = badgeSize!!, badgeGravity = badgeGravity!!, badgeMargin = badgeMargin ?: 0.0f, isShowBorder = isShowBorder!!, maximumCounter = maximumCounter!!, isShowCounter = isShowCounter!!) } } fun get(counter: Int): Drawable { val resources = context.resources if (counter == 0) return BitmapDrawable(resources, bitmap) val sourceBitmap = bitmap val width = sourceBitmap.width val height = sourceBitmap.height val output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) val canvas = Canvas(output) val rect = Rect(0, 0, width, height) val paint = Paint().apply { isAntiAlias = true isFilterBitmap = true isDither = true textAlign = Paint.Align.CENTER color = badgeColor } canvas.drawBitmap(sourceBitmap, rect, rect, paint) val badgeRect = getBadgeRect(rect) canvas.drawOval(badgeRect, paint) if (isShowBorder) { val paintBorder = Paint().apply { isAntiAlias = true isFilterBitmap = true isDither = true textAlign = Paint.Align.CENTER style = Paint.Style.STROKE color = badgeBorderColor strokeWidth = badgeBorderSize } canvas.drawOval(badgeRect, paintBorder) } if(isShowCounter) { val textSize: Float val text: String val max = if (maximumCounter > MAXIMUM_COUNT) MAXIMUM_COUNT else maximumCounter if (counter > max) { textSize = badgeRect.height() * 0.45f text = "$max+" } else { textSize = badgeRect.height() * 0.55f text = counter.toString() } val textPaint = TextPaint().apply { this.isAntiAlias = true this.color = textColor this.textSize = textSize } val x = badgeRect.centerX() - (textPaint.measureText(text) / 2f) val y = badgeRect.centerY() - (textPaint.ascent() + textPaint.descent()) * 0.5f canvas.drawText(text, x, y, textPaint) } return BitmapDrawable(resources, output) } private fun getBadgeRect(bound: Rect): RectF { val borderSize = if (isShowBorder) badgeBorderSize else 0f val adjustSpace = borderSize + badgeMargin val dest = Rect() val size = badgeSize.toInt() Gravity.apply(badgeGravity, size, size, bound, adjustSpace.toInt(), adjustSpace.toInt(), dest) return RectF(dest) } companion object { private const val MAXIMUM_COUNT = 99 } }
mit
e9c2e4606dad32f16e12f4c04fe3224f
34.247619
147
0.684139
4.069269
false
false
false
false
collave/workbench-android-common
library/src/main/kotlin/com/collave/workbench/common/android/component/state/StatefulDataRequest.kt
1
1910
package com.collave.workbench.common.android.component.state import io.reactivex.Single import kotlin.reflect.KProperty /** * Created by Andrew on 4/20/2017. */ open class StatefulDataRequest<T> : StatefulRequest<T> { protected var creator: (Array<out Any?>)-> Single<T> protected var initial: ((Array<out Any?>)-> Single<T>)? = null constructor(creator: (Array<out Any?>)-> Single<T>): super() { this.creator = creator } constructor(creator: (Array<out Any?>)-> Single<T>, initial: (Array<out Any?>)-> Single<T>): this(creator) { this.initial = initial } val dataVariable = NullableVariable<T>() var data by dataVariable private set val onDataUpdated get() = dataVariable.onValueUpdated override fun createRequest(vararg args: Any?) = if (data == null) createInitialRequest(*args) else creator.invoke(args) open fun createInitialRequest(vararg args: Any?) = initial?.invoke(args) ?: creator.invoke(args) override fun handleResult(result: T) { data = result } operator fun getValue(thisRef: Any?, property: KProperty<*>): T? { return data } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) { data = value } fun updateData(value: T) { data = value } fun executeInitial(vararg args: Any?) { if (data == null) { execute(*args) } } fun executeSingle(vararg args: Any?): Single<T?> { val single = stateVariable .onValueUpdated .skipWhile { it == State.InProgress } .firstOrError() .map { if (it == State.RequestError) { throw lastError ?: Exception() } data!! } execute(*args) return single } }
gpl-3.0
276a9969d2fe4322ca37b084d78cd5a4
26.3
123
0.573298
4.360731
false
false
false
false
Petrulak/kotlin-mvp-clean-architecture
app/src/main/java/com/petrulak/cleankotlin/ui/example1/fragment/Example1Fragment.kt
1
1708
package com.petrulak.cleankotlin.ui.example1.fragment import android.os.Bundle import android.view.View import com.petrulak.cleankotlin.App import com.petrulak.cleankotlin.R import com.petrulak.cleankotlin.di.component.DaggerViewComponent import com.petrulak.cleankotlin.di.module.PresenterModule import com.petrulak.cleankotlin.domain.model.Weather import com.petrulak.cleankotlin.ui.base.BaseFragment import com.petrulak.cleankotlin.ui.example1.fragment.Example1Contract.Presenter import kotlinx.android.synthetic.main.fragment_weather.* import javax.inject.Inject class Example1Fragment : BaseFragment(), Example1Contract.View { private var presenter: Presenter? = null override fun layoutId() = R.layout.fragment_weather override fun initializeDependencies() { DaggerViewComponent.builder() .applicationComponent(App.instance.appComponent()) .presenterModule(PresenterModule()) .build().inject(this) } @Inject override fun attachPresenter(presenter: Presenter) { this.presenter = presenter this.presenter?.attachView(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) presenter?.start() btn_refresh.setOnClickListener { presenter?.refresh() } } override fun onDestroy() { presenter?.stop() super.onDestroy() } override fun showWeather(data: Weather) { tv_city.text = data.name tv_visibility.text = data.visibility.toString() } companion object { fun newInstance(): Example1Fragment { return Example1Fragment() } } }
mit
0e68dca5a26df6d5500129f6d628d241
29.5
79
0.714871
4.628726
false
false
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/lists/AddListDialogFragment.kt
1
4931
package com.battlelancer.seriesguide.lists import android.app.Dialog import android.content.Context import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.widget.TextView import androidx.appcompat.app.AppCompatDialogFragment import androidx.fragment.app.FragmentManager import com.battlelancer.seriesguide.R import com.battlelancer.seriesguide.databinding.DialogListManageBinding import com.battlelancer.seriesguide.provider.SeriesGuideContract import com.battlelancer.seriesguide.util.safeShow import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.textfield.TextInputLayout /** * Displays a dialog to add a new list to lists. */ class AddListDialogFragment : AppCompatDialogFragment() { private var binding: DialogListManageBinding? = null override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val binding = DialogListManageBinding.inflate(layoutInflater) this.binding = binding // title val editTextName = binding.textInputLayoutListManageListName.editText!! editTextName.addTextChangedListener( ListNameTextWatcher( requireContext(), binding.textInputLayoutListManageListName, binding.buttonPositive, null ) ) // buttons binding.buttonNegative.setText(android.R.string.cancel) binding.buttonNegative.setOnClickListener { dismiss() } binding.buttonPositive.setText(R.string.list_add) binding.buttonPositive.setOnClickListener { val editText = this.binding?.textInputLayoutListManageListName?.editText ?: return@setOnClickListener // add list val listName = editText.text.toString().trim() ListsTools.addList(requireContext(), listName) dismiss() } binding.buttonPositive.isEnabled = false return MaterialAlertDialogBuilder(requireContext()) .setView(binding.getRoot()) .create() } override fun onDestroyView() { super.onDestroyView() binding = null } /** * Disables the given button if the watched text has only whitespace or the list name is already * used. Does currently not protect against a new list resulting in the same list id (if * inserted just resets the properties of the existing list). */ class ListNameTextWatcher( private val context: Context, private val textInputLayoutName: TextInputLayout, private val buttonPositive: TextView, private val currentName: String? ) : TextWatcher { private val listNames: HashSet<String> init { val listNameQuery = context.contentResolver .query( SeriesGuideContract.Lists.CONTENT_URI, arrayOf(SeriesGuideContract.Lists._ID, SeriesGuideContract.Lists.NAME), null, null, null ) listNames = HashSet() if (listNameQuery != null) { while (listNameQuery.moveToNext()) { listNames.add(listNameQuery.getString(1)) } listNameQuery.close() } } override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { val name = s.toString().trim { it <= ' ' } if (name.isEmpty()) { buttonPositive.isEnabled = false return } if (currentName != null && currentName == name) { buttonPositive.isEnabled = true return } if (listNames.contains(name)) { textInputLayoutName.error = context.getString(R.string.error_name_already_exists) textInputLayoutName.isErrorEnabled = true buttonPositive.isEnabled = false } else { textInputLayoutName.error = null textInputLayoutName.isErrorEnabled = false buttonPositive.isEnabled = true } } override fun afterTextChanged(s: Editable) {} } companion object { private const val TAG = "addlistdialog" /** * Display a dialog which allows to edit the title of this list or remove it. */ fun show(fm: FragmentManager) { // replace any currently showing list dialog (do not add it to the back stack) val ft = fm.beginTransaction() val prev = fm.findFragmentByTag(TAG) if (prev != null) { ft.remove(prev) } AddListDialogFragment().safeShow(fm, ft, TAG) } } }
apache-2.0
b3bc8d92284a7074547a952e109bdbab
34.73913
100
0.623606
5.353963
false
false
false
false
VerifAPS/verifaps-lib
lang/src/main/kotlin/edu/kit/iti/formal/automation/sfclang/SFCLayouter.kt
1
3279
package edu.kit.iti.formal.automation.sfclang /*- * #%L * iec61131lang * %% * Copyright (C) 2016 Alexander Weigl * %% * This program isType 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 isType 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 clone of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ /** * Created by weigl on 11.09.15. * * @author weigl * @version $Id: $Id */ class SFCLayouter/* static class LayoutMetaData { int childBranching = 0; double width, height, x, y; } HashMap<String, LayoutMetaData> meta = new HashMap<>(); private final SFCImplementation sfcDeclaration; public SFCLayouter(SFCImplementation DECLARATION) { sfcDeclaration = DECLARATION; } public void widthOfSubSfc(StepDeclaration step) { Queue<StepDeclaration> steps = new LinkedList<>(); Set<String> visited = new HashSet<>(); while (!steps.isEmpty()) { step = steps.poll(); visited.add(step.getName()); for (TransitionDeclaration successor : getSuccessors(step)) { for (String childName : successor.getTo()) { if (visited.contains(childName)) continue; } } } } public int widthOfSubSfc(Set<String> visited, StepDeclaration step) { visited.add(step.getName()); int sum = 0; for (TransitionDeclaration successor : getSuccessors(step)) { for (String childName : successor.getTo()) { if (visited.contains(childName)) continue; sum += widthOfSubSfc(visited, sfcDeclaration.getStep(childName)); } } getMetaData(step.getName()).childBranching = sum; return sum; } private LayoutMetaData getMetaData(String name) { return meta.get(name); } public void layout() { StepDeclaration init = null; for (StepDeclaration s : sfcDeclaration.getSteps()) { if (s.isInitialStep()) { init = s; break; } } placeIn(init, 0, 0); List<TransitionDeclaration> transitions = getSuccessors(init); int[] size = new int[transitions.size()]; for (TransitionDeclaration t : transitions) { } } private void placeIn(StepDeclaration s, int x, int y) { } public List<TransitionDeclaration> getSuccessors(StepDeclaration sd) { List<TransitionDeclaration> list = new ArrayList<>(); for (TransitionDeclaration t : sfcDeclaration.getTransitions()) { if (t.getFrom().contains(sd.getName())) { list.add(t); } } return list; } */
gpl-3.0
4ba9eb6f25072224f9700db68791fa50
26.554622
81
0.601708
4.437077
false
false
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/shows/overview/OverviewFragment.kt
1
31842
package com.battlelancer.seriesguide.shows.overview import android.os.Bundle import android.os.Handler import android.os.Looper import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.AnimationUtils import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.TooltipCompat import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.loader.app.LoaderManager import androidx.loader.content.Loader import com.battlelancer.seriesguide.R import com.battlelancer.seriesguide.SgApp import com.battlelancer.seriesguide.api.Action import com.battlelancer.seriesguide.backend.settings.HexagonSettings import com.battlelancer.seriesguide.comments.TraktCommentsActivity import com.battlelancer.seriesguide.databinding.FragmentOverviewBinding import com.battlelancer.seriesguide.extensions.ActionsHelper import com.battlelancer.seriesguide.extensions.EpisodeActionsContract import com.battlelancer.seriesguide.extensions.EpisodeActionsLoader import com.battlelancer.seriesguide.extensions.ExtensionManager.EpisodeActionReceivedEvent import com.battlelancer.seriesguide.preferences.MoreOptionsActivity import com.battlelancer.seriesguide.settings.AppSettings import com.battlelancer.seriesguide.settings.AppSettings.setAskedForFeedback import com.battlelancer.seriesguide.settings.DisplaySettings.isDisplayExactDate import com.battlelancer.seriesguide.settings.DisplaySettings.preventSpoilers import com.battlelancer.seriesguide.shows.RemoveShowDialogFragment import com.battlelancer.seriesguide.shows.database.SgEpisode2 import com.battlelancer.seriesguide.shows.database.SgShow2 import com.battlelancer.seriesguide.shows.episodes.EpisodeFlags import com.battlelancer.seriesguide.shows.episodes.EpisodeTools import com.battlelancer.seriesguide.shows.episodes.EpisodesActivity import com.battlelancer.seriesguide.shows.search.similar.SimilarShowsActivity import com.battlelancer.seriesguide.shows.tools.ShowStatus import com.battlelancer.seriesguide.streaming.StreamingSearch import com.battlelancer.seriesguide.streaming.StreamingSearch.initButtons import com.battlelancer.seriesguide.tmdbapi.TmdbTools import com.battlelancer.seriesguide.tmdbapi.TmdbTools2 import com.battlelancer.seriesguide.traktapi.CheckInDialogFragment import com.battlelancer.seriesguide.traktapi.RateDialogFragment import com.battlelancer.seriesguide.traktapi.TraktCredentials import com.battlelancer.seriesguide.traktapi.TraktRatingsFetcher.fetchEpisodeRatingsAsync import com.battlelancer.seriesguide.traktapi.TraktTools import com.battlelancer.seriesguide.ui.BaseMessageActivity.ServiceActiveEvent import com.battlelancer.seriesguide.ui.BaseMessageActivity.ServiceCompletedEvent import com.battlelancer.seriesguide.util.ImageTools.tmdbOrTvdbStillUrl import com.battlelancer.seriesguide.util.LanguageTools import com.battlelancer.seriesguide.util.ServiceUtils import com.battlelancer.seriesguide.util.ShareUtils import com.battlelancer.seriesguide.util.TextTools import com.battlelancer.seriesguide.util.TimeTools import com.battlelancer.seriesguide.util.Utils import com.battlelancer.seriesguide.util.ViewTools import com.battlelancer.seriesguide.util.copyTextToClipboardOnLongClick import com.squareup.picasso.Callback import com.squareup.picasso.Picasso import kotlinx.coroutines.Job import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode import timber.log.Timber /** * Displays general information about a show and, if there is one, the next episode to watch. */ class OverviewFragment : Fragment(), EpisodeActionsContract { private var binding: FragmentOverviewBinding? = null /** Inflated on demand from ViewStub. */ private var feedbackView: FeedbackView? = null private val handler = Handler(Looper.getMainLooper()) private var ratingFetchJob: Job? = null private val model: OverviewViewModel by viewModels { OverviewViewModelFactory(showId, requireActivity().application) } private var showId: Long = 0 private var hasSetEpisodeWatched = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) showId = requireArguments().getLong(ARG_LONG_SHOW_ROWID) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return FragmentOverviewBinding.inflate(inflater, container, false) .also { binding = it } .root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val binding = binding!! with(binding) { containerOverviewEpisode.visibility = View.GONE containerOverviewEmpty.visibility = View.GONE buttonOverviewFavoriteShow.setOnClickListener { onButtonFavoriteClick() } containerOverviewEpisodeCard.setOnClickListener { v: View? -> runIfHasEpisode { episode -> // display episode details val intent = EpisodesActivity.intentEpisode(episode.id, requireContext()) Utils.startActivityWithAnimation(activity, intent, v) } } // Empty view buttons. buttonOverviewSimilarShows.setOnClickListener { val show = model.show.value if (show?.tmdbId != null) { startActivity( SimilarShowsActivity.intent( requireContext(), show.tmdbId, show.title ) ) } } buttonOverviewRemoveShow.setOnClickListener { RemoveShowDialogFragment.show(showId, parentFragmentManager, requireContext()) } // episode buttons with(includeButtons) { buttonEpisodeWatchedUpTo.visibility = View.GONE // Unused in this fragment. buttonEpisodeCheckin.setOnClickListener { onButtonCheckInClick() } buttonEpisodeWatched.setOnClickListener { onButtonWatchedClick() } buttonEpisodeCollected.setOnClickListener { onButtonCollectedClick() } buttonEpisodeSkip.setOnClickListener { onButtonSkipClicked() } TooltipCompat.setTooltipText( buttonEpisodeCheckin, buttonEpisodeCheckin.contentDescription ) TooltipCompat.setTooltipText( buttonEpisodeWatched, buttonEpisodeWatched.contentDescription ) TooltipCompat.setTooltipText( buttonEpisodeSkip, buttonEpisodeSkip.contentDescription ) initButtons( buttonEpisodeStreamingSearch, buttonEpisodeStreamingSearchInfo, parentFragmentManager ) } // ratings with(includeRatings) { root.setOnClickListener { onButtonRateClick() } TooltipCompat.setTooltipText( root, root.context.getString(R.string.action_rate) ) textViewRatingsRange.text = getString(R.string.format_rating_range, 10) } with(includeServices.includeMore) { buttonEpisodeShare.setOnClickListener { shareEpisode() } buttonEpisodeCalendar.setOnClickListener { createCalendarEvent() } buttonEpisodeComments.setOnClickListener { onButtonCommentsClick(buttonEpisodeComments) } } // set up long-press to copy text to clipboard (d-pad friendly vs text selection) textViewEpisodeDescription.copyTextToClipboardOnLongClick() textGuestStars.copyTextToClipboardOnLongClick() textDvdNumber.copyTextToClipboardOnLongClick() // Hide show info if show fragment is visible due to multi-pane layout. val isDisplayShowInfo = resources.getBoolean(R.bool.isOverviewSinglePane) containerOverviewShow.visibility = if (isDisplayShowInfo) View.VISIBLE else View.GONE } model.show.observe(viewLifecycleOwner) { sgShow2: SgShow2? -> if (sgShow2 == null) { Timber.e("Failed to load show %s", showId) requireActivity().finish() return@observe } this.binding?.also { populateShowViews(it, sgShow2) } val episodeId = if (sgShow2.nextEpisode != null && sgShow2.nextEpisode.isNotEmpty()) { sgShow2.nextEpisode.toLong() } else -1 model.setEpisodeId(episodeId) model.setShowTmdbId(sgShow2.tmdbId) } model.episode.observe(viewLifecycleOwner) { sgEpisode2: SgEpisode2? -> this.binding?.also { maybeAddFeedbackView(it) // May be null if there is no next episode. updateEpisodeViews(it, sgEpisode2) } } model.watchProvider.observe(viewLifecycleOwner) { watchInfo: TmdbTools2.WatchInfo? -> if (watchInfo != null) { this.binding?.let { StreamingSearch.configureButton( it.includeButtons.buttonEpisodeStreamingSearch, watchInfo, true ) } } } } override fun onResume() { super.onResume() val event = EventBus.getDefault().getStickyEvent(ServiceActiveEvent::class.java) setEpisodeButtonsEnabled(event == null) EventBus.getDefault().register(this) loadEpisodeActionsDelayed() } override fun onPause() { super.onPause() EventBus.getDefault().unregister(this) } override fun onDestroyView() { super.onDestroyView() // Always cancel the request here, this is safe to call even if the image has been loaded. // This ensures that the anonymous callback we have does not prevent the fragment from // being garbage collected. It also prevents our callback from getting invoked even after the // fragment is destroyed. Picasso.get().cancelRequest(binding!!.imageViewOverviewEpisode) binding = null } override fun onDestroy() { super.onDestroy() handler.removeCallbacks(episodeActionsRunnable) // Release reference to any job. ratingFetchJob = null } private fun createCalendarEvent() { val currentShow = model.show.value val currentEpisode = model.episode.value if (currentShow == null || currentEpisode == null) { return } // add calendar event ShareUtils.suggestCalendarEvent( activity, currentShow.title, TextTools.getNextEpisodeString( requireContext(), currentEpisode.season, currentEpisode.number, currentEpisode.title ), currentEpisode.firstReleasedMs, currentShow.runtime ) } private fun onButtonFavoriteClick() { val currentShow = model.show.value ?: return SgApp.getServicesComponent(requireContext()).showTools() .storeIsFavorite(showId, !currentShow.favorite) } private fun onButtonCheckInClick() { runIfHasEpisode { episode -> CheckInDialogFragment .show(requireContext(), parentFragmentManager, episode.id) } } private fun onButtonWatchedClick() { hasSetEpisodeWatched = true changeEpisodeFlag(EpisodeFlags.WATCHED) } private fun onButtonCollectedClick() { runIfHasEpisode { episode -> EpisodeTools.episodeCollected(context, episode.id, !episode.collected) } } private fun onButtonSkipClicked() { changeEpisodeFlag(EpisodeFlags.SKIPPED) } private fun changeEpisodeFlag(episodeFlag: Int) { runIfHasEpisode { episode -> EpisodeTools.episodeWatched(context, episode.id, episodeFlag) } } private fun onButtonRateClick() { runIfHasEpisode { episode -> RateDialogFragment.newInstanceEpisode(episode.id) .safeShow(context, parentFragmentManager) } } private fun onButtonCommentsClick(v: View?) { runIfHasEpisode { episode -> val i = TraktCommentsActivity.intentEpisode(requireContext(), episode.title, episode.id) Utils.startActivityWithAnimation(activity, i, v) } } private fun shareEpisode() { val currentShow = model.show.value ?: return runIfHasEpisode { episode -> if (currentShow.tmdbId != null) { ShareUtils.shareEpisode( activity, currentShow.tmdbId, episode.season, episode.number, currentShow.title, episode.title ) } } } @Subscribe(threadMode = ThreadMode.MAIN) override fun onEventMainThread(event: EpisodeActionReceivedEvent) { runIfHasEpisode { episode -> if (episode.tmdbId == event.episodeTmdbId) { loadEpisodeActionsDelayed() } } } @Subscribe(threadMode = ThreadMode.MAIN) fun onEventEpisodeTask(@Suppress("UNUSED_PARAMETER") event: ServiceActiveEvent?) { setEpisodeButtonsEnabled(false) } @Subscribe(threadMode = ThreadMode.MAIN) fun onEventEpisodeTask(@Suppress("UNUSED_PARAMETER") event: ServiceCompletedEvent?) { setEpisodeButtonsEnabled(true) } private fun setEpisodeButtonsEnabled(enabled: Boolean) { val binding = binding ?: return with(binding.includeButtons) { buttonEpisodeWatched.isEnabled = enabled buttonEpisodeCollected.isEnabled = enabled buttonEpisodeSkip.isEnabled = enabled buttonEpisodeCheckin.isEnabled = enabled } } private fun updateEpisodeViews(binding: FragmentOverviewBinding, episode: SgEpisode2?) { if (episode != null) { // hide check-in if not connected to trakt or hexagon is enabled val isConnectedToTrakt = TraktCredentials.get(requireContext()).hasCredentials() val displayCheckIn = (isConnectedToTrakt && !HexagonSettings.isEnabled(requireContext())) binding.includeButtons.buttonEpisodeCheckin.visibility = if (displayCheckIn) View.VISIBLE else View.GONE binding.includeButtons.buttonEpisodeStreamingSearch.nextFocusUpId = if (displayCheckIn) R.id.buttonCheckIn else R.id.buttonEpisodeWatched // populate episode details populateEpisodeViews(binding, episode) populateEpisodeDescriptionAndTvdbButton(binding) // load full info and ratings, image, actions loadEpisodeDetails() loadEpisodeImage(binding.imageViewOverviewEpisode, episode.image) loadEpisodeActionsDelayed() binding.containerOverviewEmpty.visibility = View.GONE binding.containerOverviewEpisodeCard.visibility = View.VISIBLE binding.containerOverviewEpisodeDetails.visibility = View.VISIBLE } else { // No next episode: display empty view with suggestion on what to do. binding.textViewOverviewNotMigrated.visibility = View.GONE binding.containerOverviewEmpty.visibility = View.VISIBLE binding.containerOverviewEpisodeCard.visibility = View.GONE binding.containerOverviewEpisodeDetails.visibility = View.GONE } // animate view into visibility if (binding.containerOverviewEpisode.visibility == View.GONE) { binding.containerOverviewProgress.startAnimation( AnimationUtils.loadAnimation( binding.containerOverviewProgress.context, android.R.anim.fade_out ) ) binding.containerOverviewProgress.visibility = View.GONE binding.containerOverviewEpisode.startAnimation( AnimationUtils.loadAnimation( binding.containerOverviewEpisode.context, android.R.anim.fade_in ) ) binding.containerOverviewEpisode.visibility = View.VISIBLE } } private fun populateEpisodeViews(binding: FragmentOverviewBinding, episode: SgEpisode2) { ViewTools.configureNotMigratedWarning( binding.textViewOverviewNotMigrated, episode.tmdbId == null ) // title val season = episode.season val number = episode.number val title = TextTools.getEpisodeTitle( requireContext(), if (preventSpoilers(requireContext())) null else episode.title, number ) binding.episodeTitle.text = title // number val infoText = StringBuilder() infoText.append(getString(R.string.season_number, season)) infoText.append(" ") infoText.append(getString(R.string.episode_number, number)) val episodeAbsoluteNumber = episode.absoluteNumber if (episodeAbsoluteNumber != null && episodeAbsoluteNumber > 0 && episodeAbsoluteNumber != number) { infoText.append(" (").append(episodeAbsoluteNumber).append(")") } // release date val releaseTime = episode.firstReleasedMs val timeText = if (releaseTime != -1L) { val actualRelease = TimeTools.applyUserOffset(requireContext(), releaseTime) // "Oct 31 (Fri)" or "in 14 mins (Fri)" val dateTime: String = if (isDisplayExactDate(requireContext())) { TimeTools.formatToLocalDateShort(requireContext(), actualRelease) } else { TimeTools.formatToLocalRelativeTime(context, actualRelease) } getString( R.string.format_date_and_day, dateTime, TimeTools.formatToLocalDay(actualRelease) ) } else { null } binding.textOverviewEpisodeInfo.text = TextTools.buildTitleAndSecondary( requireContext(), infoText.toString(), R.style.TextAppearance_SeriesGuide_Caption, timeText, R.style.TextAppearance_SeriesGuide_Caption_Dim ) // watched button binding.includeButtons.buttonEpisodeWatched.also { val isWatched = EpisodeTools.isWatched(episode.watched) if (isWatched) { ViewTools.setVectorDrawableTop(it, R.drawable.ic_watched_24dp) } else { ViewTools.setVectorDrawableTop(it, R.drawable.ic_watch_black_24dp) } val plays = episode.plays it.text = TextTools.getWatchedButtonText(requireContext(), isWatched, plays) } // collected button binding.includeButtons.buttonEpisodeCollected.also { val isCollected = episode.collected if (isCollected) { ViewTools.setVectorDrawableTop(it, R.drawable.ic_collected_24dp) } else { ViewTools.setVectorDrawableTop(it, R.drawable.ic_collect_black_24dp) } it.setText( if (isCollected) R.string.state_in_collection else R.string.action_collection_add ) TooltipCompat.setTooltipText( it, it.context.getString( if (isCollected) R.string.action_collection_remove else R.string.action_collection_add ) ) } // dvd number var isShowingMeta = ViewTools.setLabelValueOrHide( binding.labelDvdNumber, binding.textDvdNumber, episode.dvdNumber ) // guest stars isShowingMeta = isShowingMeta or ViewTools.setLabelValueOrHide( binding.labelGuestStars, binding.textGuestStars, TextTools.splitPipeSeparatedStrings(episode.guestStars) ) // hide divider if no meta is visible binding.dividerOverviewEpisodeDetails.visibility = if (isShowingMeta) View.VISIBLE else View.GONE // Trakt rating binding.includeRatings.also { it.textViewRatingsValue.text = TraktTools.buildRatingString(episode.ratingGlobal) it.textViewRatingsVotes.text = TraktTools.buildRatingVotesString( activity, episode.ratingVotes ) // user rating it.textViewRatingsUser.text = TraktTools.buildUserRatingString( activity, episode.ratingUser ) } binding.includeServices.includeMore.also { // IMDb button ViewTools.configureImdbButton( it.buttonEpisodeImdb, lifecycleScope, requireContext(), model.show.value, episode ) // trakt button if (episode.tmdbId != null) { val traktLink = TraktTools.buildEpisodeUrl(episode.tmdbId) ViewTools.openUriOnClick(it.buttonEpisodeTrakt, traktLink) it.buttonEpisodeTrakt.copyTextToClipboardOnLongClick(traktLink) } } } /** * Updates the episode description and TVDB button. Need both show and episode data loaded. */ private fun populateEpisodeDescriptionAndTvdbButton(binding: FragmentOverviewBinding) { val show = model.show.value val episode = model.episode.value if (show == null || episode == null) { // no show or episode data available return } var overview = episode.overview val languageCode = show.language?.let { LanguageTools.mapLegacyShowCode(it) } if (TextUtils.isEmpty(overview)) { // no description available, show no translation available message overview = TextTools.textNoTranslation(requireContext(), languageCode) } else if (preventSpoilers(requireContext())) { overview = getString(R.string.no_spoilers) } binding.textViewEpisodeDescription.text = TextTools.textWithTmdbSource( binding.textViewEpisodeDescription.context, overview ) // TMDb button val showTmdbId = show.tmdbId if (showTmdbId != null) { val url = TmdbTools.buildEpisodeUrl(showTmdbId, episode.season, episode.number) val buttonTmdb = binding.includeServices.includeMore.buttonEpisodeTmdb ViewTools.openUriOnClick(buttonTmdb, url) buttonTmdb.copyTextToClipboardOnLongClick(url) } } override fun loadEpisodeActions() { // do not load actions if there is no episode runIfHasEpisode { episode -> val args = Bundle() args.putLong(ARG_EPISODE_ID, episode.id) LoaderManager.getInstance(this) .restartLoader( OverviewActivityImpl.OVERVIEW_ACTIONS_LOADER_ID, args, episodeActionsLoaderCallbacks ) } } private var episodeActionsRunnable = Runnable { loadEpisodeActions() } override fun loadEpisodeActionsDelayed() { handler.removeCallbacks(episodeActionsRunnable) handler.postDelayed( episodeActionsRunnable, EpisodeActionsContract.ACTION_LOADER_DELAY_MILLIS.toLong() ) } private fun loadEpisodeImage(imageView: ImageView, imagePath: String?) { if (imagePath.isNullOrEmpty()) { imageView.setImageDrawable(null) return } if (preventSpoilers(requireContext())) { // show image placeholder imageView.scaleType = ImageView.ScaleType.CENTER_INSIDE imageView.setImageResource(R.drawable.ic_photo_gray_24dp) } else { // try loading image ServiceUtils.loadWithPicasso( requireContext(), tmdbOrTvdbStillUrl(imagePath, requireContext(), false) ) .error(R.drawable.ic_photo_gray_24dp) .into(imageView, object : Callback { override fun onSuccess() { imageView.scaleType = ImageView.ScaleType.CENTER_CROP } override fun onError(e: Exception) { imageView.scaleType = ImageView.ScaleType.CENTER_INSIDE } } ) } } private fun loadEpisodeDetails() { runIfHasEpisode { episode -> val ratingFetchJob = ratingFetchJob if (ratingFetchJob == null || !ratingFetchJob.isActive) { this.ratingFetchJob = fetchEpisodeRatingsAsync( requireContext(), episode.id ) } } } private fun populateShowViews(binding: FragmentOverviewBinding, show: SgShow2) { // set show title in action bar val showTitle = show.title val actionBar = (requireActivity() as AppCompatActivity).supportActionBar if (actionBar != null) { actionBar.title = showTitle requireActivity().title = getString(R.string.description_overview) + showTitle } // status ShowStatus.setStatusAndColor(binding.overviewShowStatus, show.statusOrUnknown) // favorite val isFavorite = show.favorite binding.buttonOverviewFavoriteShow.also { it.setImageResource( if (isFavorite) R.drawable.ic_star_black_24dp else R.drawable.ic_star_border_black_24dp ) it.contentDescription = getString( if (isFavorite) R.string.context_unfavorite else R.string.context_favorite ) TooltipCompat.setTooltipText(it, it.contentDescription) } // Regular network, release time and length. val network = show.network var time: String? = null val releaseTime = show.releaseTime if (releaseTime != null && releaseTime != -1) { val weekDay = show.releaseWeekDayOrDefault val release = TimeTools.getShowReleaseDateTime( requireContext(), releaseTime, weekDay, show.releaseTimeZone, show.releaseCountry, network ) val dayString = TimeTools.formatToLocalDayOrDaily(requireContext(), release, weekDay) val timeString = TimeTools.formatToLocalTime(requireContext(), release) // "Mon 08:30" time = "$dayString $timeString" } val runtime = getString( R.string.runtime_minutes, show.runtime.toString() ) val combinedString = TextTools.dotSeparate(TextTools.dotSeparate(network, time), runtime) binding.overviewShowNetworkAndTime.text = combinedString // set up long-press to copy text to clipboard (d-pad friendly vs text selection) binding.overviewShowNetworkAndTime.copyTextToClipboardOnLongClick() // Remaining episodes binding.textOverviewEpisodeHeader.text = TextTools.buildTitleAndSecondary( requireContext(), getString(R.string.next_to_watch), R.style.TextAppearance_SeriesGuide_Body2_Bold, TextTools.getRemainingEpisodes(requireContext().resources, show.unwatchedCount), R.style.TextAppearance_SeriesGuide_Body2_Dim ) // episode description might need show language, so update it here as well populateEpisodeDescriptionAndTvdbButton(binding) } private fun runIfHasEpisode(block: (episode: SgEpisode2) -> Unit) { val currentEpisode = model.episode.value if (currentEpisode != null) { block.invoke(currentEpisode) } } private fun maybeAddFeedbackView(binding: FragmentOverviewBinding) { if (feedbackView != null || !hasSetEpisodeWatched || !AppSettings.shouldAskForFeedback(requireContext())) { return // can or should not add feedback view } (binding.viewStubOverviewFeedback.inflate() as FeedbackView).also { feedbackView = it it.setCallback(object : FeedbackView.Callback { override fun onRate() { if (Utils.launchWebsite(context, getString(R.string.url_store_page))) { hideFeedbackView() } } override fun onFeedback() { if (Utils.tryStartActivity( requireContext(), MoreOptionsActivity.getFeedbackEmailIntent(requireContext()), true )) { hideFeedbackView() } } override fun onDismiss() { hideFeedbackView() } }) } } private fun hideFeedbackView() { feedbackView?.visibility = View.GONE setAskedForFeedback(requireContext()) } private val episodeActionsLoaderCallbacks: LoaderManager.LoaderCallbacks<MutableList<Action>?> = object : LoaderManager.LoaderCallbacks<MutableList<Action>?> { override fun onCreateLoader(id: Int, args: Bundle?): Loader<MutableList<Action>?> { val episodeId = args!!.getLong(ARG_EPISODE_ID) return EpisodeActionsLoader(requireContext(), episodeId) } override fun onLoadFinished( loader: Loader<MutableList<Action>?>, data: MutableList<Action>? ) { val binding = binding ?: return if (data == null) { Timber.e("onLoadFinished: did not receive valid actions") } else { Timber.d("onLoadFinished: received %s actions", data.size) } ActionsHelper.populateActions( requireActivity().layoutInflater, requireActivity().theme, binding.includeServices.containerEpisodeActions, data ) } override fun onLoaderReset(loader: Loader<MutableList<Action>?>) { val binding = binding ?: return ActionsHelper.populateActions( requireActivity().layoutInflater, requireActivity().theme, binding.includeServices.containerEpisodeActions, null ) } } companion object { private const val ARG_LONG_SHOW_ROWID = "show_id" private const val ARG_EPISODE_ID = "episode_id" fun buildArgs(showRowId: Long): Bundle { val args = Bundle() args.putLong(ARG_LONG_SHOW_ROWID, showRowId) return args } fun newInstance(showRowId: Long): OverviewFragment { return OverviewFragment().apply { arguments = buildArgs(showRowId) } } } }
apache-2.0
95153153370d9fe356792d18ab77d0e1
39.003769
106
0.630771
5.347103
false
false
false
false
flutter/packages
packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/MultipleArityTests.kt
1
2480
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package com.example.test_plugin import io.flutter.plugin.common.BinaryMessenger import io.mockk.every import io.mockk.mockk import io.mockk.slot import junit.framework.TestCase import org.junit.Test import java.nio.ByteBuffer import java.util.ArrayList class MultipleArityTests: TestCase() { @Test fun testSimpleHost() { val binaryMessenger = mockk<BinaryMessenger>() val api = mockk<MultipleArityHostApi>() val inputX = 10L val inputY = 5L val channelName = "dev.flutter.pigeon.MultipleArityHostApi.subtract" val handlerSlot = slot<BinaryMessenger.BinaryMessageHandler>() every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit every { api.subtract(any(), any()) } answers { firstArg<Long>() - secondArg<Long>() } MultipleArityHostApi.setUp(binaryMessenger, api) val codec = MultipleArityHostApi.codec val message = codec.encodeMessage(listOf(inputX, inputY)) message?.rewind() handlerSlot.captured.onMessage(message) { it?.rewind() @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as HashMap<String, Any>? assertNotNull(wrapped) wrapped?.let { assertEquals(inputX - inputY, wrapped["result"]) } } } @Test fun testSimpleFlutter() { val binaryMessenger = mockk<BinaryMessenger>() val api = MultipleArityFlutterApi(binaryMessenger) val inputX = 10L val inputY = 5L every { binaryMessenger.send(any(), any(), any()) } answers { val codec = MultipleArityFlutterApi.codec val message = arg<ByteBuffer>(1) val reply = arg<BinaryMessenger.BinaryReply>(2) message.position(0) val args = codec.decodeMessage(message) as ArrayList<*> val argX = args[0] as Long val argY = args[1] as Long val replyData = codec.encodeMessage(argX - argY) replyData?.position(0) reply.reply(replyData) } var didCall = false api.subtract(inputX, inputY) { didCall = true assertEquals(inputX - inputY, it) } assertTrue(didCall) } }
bsd-3-clause
73b719add0cf43122dbf134b7f2586ca
31.631579
99
0.631855
4.350877
false
true
false
false
AlmasB/FXGL
fxgl-core/src/main/kotlin/com/almasb/fxgl/core/math/Vec3.kt
1
2893
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.core.math import java.io.Serializable /** * A 3D vector with float precision. * Can be used to represent a point in 3D space. * Can be used instead of JavaFX Point3D to avoid object allocations. * This is also preferred for private or scoped fields. * * @author Almas Baimagambetov ([email protected]) */ class Vec3 @JvmOverloads constructor( @JvmField var x: Float = 0f, @JvmField var y: Float = 0f, @JvmField var z: Float = 0f ) : Serializable { companion object { @JvmStatic private val serialVersionUID = 1L @JvmStatic fun dot(a: Vec3, b: Vec3): Float { return a.x * b.x + a.y * b.y + a.z * b.z } @JvmStatic fun cross(a: Vec3, b: Vec3): Vec3 { return Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x) } } constructor(copy: Vec3) : this(copy.x, copy.y, copy.z) constructor(x: Double, y: Double, z: Double) : this(x.toFloat(), y.toFloat(), z.toFloat()) fun set(other: Vec3): Vec3 { x = other.x y = other.y z = other.z return this } fun set(otherX: Float, otherY: Float, otherZ: Float): Vec3 { x = otherX y = otherY z = otherZ return this } fun addLocal(other: Vec3): Vec3 { x += other.x y += other.y z += other.z return this } fun subLocal(other: Vec3): Vec3 { x -= other.x y -= other.y z -= other.z return this } fun mulLocal(scalar: Float): Vec3 { x *= scalar y *= scalar z *= scalar return this } fun negateLocal(): Vec3 { x = -x y = -y z = -z return this } fun setZero() { x = 0f y = 0f z = 0f } fun copy(): Vec3 { return Vec3(this) } override fun toString(): String { return "($x,$y,$z)" } override fun hashCode(): Int { val prime = 31 var result = 1 result = prime * result + java.lang.Float.floatToIntBits(x) result = prime * result + java.lang.Float.floatToIntBits(y) result = prime * result + java.lang.Float.floatToIntBits(z) return result } override fun equals(other: Any?): Boolean { if (other === this) return true if (other is Vec3) { return java.lang.Float.floatToIntBits(x) == java.lang.Float.floatToIntBits(other.x) && java.lang.Float.floatToIntBits(y) == java.lang.Float.floatToIntBits(other.y) && java.lang.Float.floatToIntBits(z) == java.lang.Float.floatToIntBits(other.z) } return false } }
mit
4860eac47282246ed75fb076dfc6921e
23.319328
99
0.54027
3.481348
false
false
false
false
googlecodelabs/android-compose-codelabs
BasicStateCodelab/app/src/main/java/com/codelabs/state/ui/theme/Type.kt
1
1412
/* * 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.codelabs.state.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ )
apache-2.0
64692ac5485c03df9239a2c965bf045a
31.837209
75
0.712465
4.344615
false
false
false
false
elect86/modern-jogl-examples
src/main/kotlin/glNext/tut03/cpuPositionOffset.kt
2
2982
package glNext.tut03 import com.jogamp.newt.event.KeyEvent import com.jogamp.opengl.GL.* import glm.glm import com.jogamp.opengl.GL3 import glNext.* import glm.set import glm.vec._2.Vec2 import main.framework.Framework import uno.buffer.* import uno.glsl.programOf /** * Created by GBarbieri on 21.02.2017. */ fun main(args: Array<String>) { CpuPositionOffset_Next().setup("Tutorial 03 - CPU Position Offset") } class CpuPositionOffset_Next : Framework() { var theProgram = 0 val positionBufferObject = intBufferBig(1) val vao = intBufferBig(1) val vertexPositions = floatBufferOf( +0.25f, +0.25f, 0.0f, 1.0f, +0.25f, -0.25f, 0.0f, 1.0f, -0.25f, -0.25f, 0.0f, 1.0f) var startingTime = 0L override fun init(gl: GL3) = with(gl) { initializeProgram(gl) initializeVertexBuffer(gl) glGenVertexArray(vao) glBindVertexArray(vao) startingTime = System.currentTimeMillis() } fun initializeProgram(gl: GL3) { theProgram = programOf(gl, javaClass, "tut03", "standard.vert", "standard.frag") } fun initializeVertexBuffer(gl: GL3) = gl.initArrayBuffer(positionBufferObject) { data(vertexPositions, GL_STATIC_DRAW) } override fun display(gl: GL3) = with(gl) { val offset = Vec2(0f) computePositionOffsets(offset) adjustVertexData(gl, offset) clear { color() } usingProgram(theProgram) { withVertexLayout(positionBufferObject, glf.pos4) { glDrawArrays(3) } } } fun computePositionOffsets(offset: Vec2) { val loopDuration = 5.0f val scale = glm.PIf * 2.0f / loopDuration val elapsedTime = (System.currentTimeMillis() - startingTime) / 1_000f val fCurrTimeThroughLoop = elapsedTime % loopDuration offset.x = glm.cos(fCurrTimeThroughLoop * scale) * 0.5f offset.y = glm.sin(fCurrTimeThroughLoop * scale) * 0.5f } fun adjustVertexData(gl: GL3, offset: Vec2) = with(gl) { val newData = floatBufferBig(vertexPositions.capacity()) repeat(vertexPositions.capacity()) { newData[it] = vertexPositions[it] } for (iVertex in 0 until vertexPositions.capacity() step 4) { newData[iVertex + 0] = vertexPositions[iVertex + 0] + offset.x newData[iVertex + 1] = vertexPositions[iVertex + 1] + offset.y } withArrayBuffer(positionBufferObject) { subData(newData) } newData.destroy() } override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) { glViewport(w, h) } override fun end(gl: GL3) = with(gl) { glDeleteProgram(theProgram) glDeleteBuffer(positionBufferObject) glDeleteVertexArray(vao) destroyBuffers(positionBufferObject, vao, vertexPositions) } override fun keyPressed(keyEvent: KeyEvent) { when (keyEvent.keyCode) { KeyEvent.VK_ESCAPE -> quit() } } }
mit
687a8308c106758ac15119970861b3a9
25.633929
124
0.640174
3.877763
false
false
false
false
arcao/Geocaching4Locus
app/src/main/java/com/arcao/geocaching4locus/download_rectangle/DownloadRectangleViewModel.kt
1
6061
package com.arcao.geocaching4locus.download_rectangle import android.app.Application import com.arcao.geocaching4locus.R import com.arcao.geocaching4locus.base.BaseViewModel import com.arcao.geocaching4locus.base.constants.AppConstants import com.arcao.geocaching4locus.base.coroutine.CoroutinesDispatcherProvider import com.arcao.geocaching4locus.base.usecase.GetPointsFromRectangleCoordinatesUseCase import com.arcao.geocaching4locus.base.usecase.WritePointToPackPointsFileUseCase import com.arcao.geocaching4locus.base.util.Command import com.arcao.geocaching4locus.base.util.invoke import com.arcao.geocaching4locus.data.account.AccountManager import com.arcao.geocaching4locus.error.exception.IntendedException import com.arcao.geocaching4locus.error.handler.ExceptionHandler import com.arcao.geocaching4locus.live_map.model.LastLiveMapCoordinates import com.arcao.geocaching4locus.settings.manager.FilterPreferenceManager import com.arcao.geocaching4locus.update.UpdateActivity import kotlinx.coroutines.Job import kotlinx.coroutines.flow.map import locus.api.manager.LocusMapManager import timber.log.Timber class DownloadRectangleViewModel constructor( private val context: Application, private val accountManager: AccountManager, private val exceptionHandler: ExceptionHandler, private val getPointsFromRectangleCoordinates: GetPointsFromRectangleCoordinatesUseCase, private val writePointToPackPointsFile: WritePointToPackPointsFileUseCase, private val filterPreferenceManager: FilterPreferenceManager, private val locusMapManager: LocusMapManager, dispatcherProvider: CoroutinesDispatcherProvider ) : BaseViewModel(dispatcherProvider) { val action = Command<DownloadRectangleAction>() private var job: Job? = null fun startDownload() { if (job?.isActive == true) { job?.cancel() } job = mainLaunch { if (locusMapManager.isLocusMapNotInstalled) { action(DownloadRectangleAction.LocusMapNotInstalled) return@mainLaunch } if (accountManager.account == null) { action(DownloadRectangleAction.SignIn) return@mainLaunch } val liveMapCoordinates = LastLiveMapCoordinates.value if (liveMapCoordinates == null) { action(DownloadRectangleAction.LastLiveMapDataInvalid) return@mainLaunch } Timber.i( "source=download_rectangle;center=%s;topLeft=%s;bottomRight=%s", liveMapCoordinates.center, liveMapCoordinates.topLeft, liveMapCoordinates.bottomRight ) doDownload(liveMapCoordinates) } } @Suppress("EXPERIMENTAL_API_USAGE") private suspend fun doDownload(liveMapCoordinates: LastLiveMapCoordinates) = computationContext { val downloadIntent = locusMapManager.createSendPointsIntent( callImport = true, center = true ) var count = AppConstants.INITIAL_REQUEST_SIZE var receivedGeocaches = 0 try { showProgress(R.string.progress_download_geocaches, maxProgress = count) { val geocaches = getPointsFromRectangleCoordinates( liveMapCoordinates.center, liveMapCoordinates.topLeft, liveMapCoordinates.bottomRight, filterPreferenceManager.simpleCacheData, filterPreferenceManager.geocacheLogsCount, filterPreferenceManager.showDisabled, filterPreferenceManager.showFound, filterPreferenceManager.showOwn, filterPreferenceManager.geocacheTypes, filterPreferenceManager.containerTypes, filterPreferenceManager.difficultyMin, filterPreferenceManager.difficultyMax, filterPreferenceManager.terrainMin, filterPreferenceManager.terrainMax, AppConstants.LIVEMAP_CACHES_COUNT ) { count = it }.map { list -> receivedGeocaches += list.size updateProgress(progress = receivedGeocaches, maxProgress = count) // apply additional downloading full geocache if required if (filterPreferenceManager.simpleCacheData) { list.forEach { point -> point.gcData?.cacheID?.let { cacheId -> point.setExtraOnDisplay( context.packageName, UpdateActivity::class.java.name, UpdateActivity.PARAM_SIMPLE_CACHE_ID, cacheId ) } } } list } writePointToPackPointsFile(geocaches) } } catch (e: Exception) { mainContext { action( DownloadRectangleAction.Error( if (receivedGeocaches > 0) { exceptionHandler(IntendedException(e, downloadIntent)) } else { exceptionHandler(e) } ) ) } return@computationContext } mainContext { action(DownloadRectangleAction.Finish(downloadIntent)) } } fun cancelDownload() { job?.cancel() action(DownloadRectangleAction.Cancel) } }
gpl-3.0
e3474891645941ed71c4d71b8d227303
41.090278
92
0.590992
5.772381
false
false
false
false
kittinunf/ReactiveAndroid
reactiveandroid-design/src/main/kotlin/com/github/kittinunf/reactiveandroid/support/design/widget/TabLayoutEvent.kt
1
2544
package com.github.kittinunf.reactiveandroid.support.design.widget import android.support.design.widget.TabLayout import com.github.kittinunf.reactiveandroid.ExtensionFieldDelegate import com.github.kittinunf.reactiveandroid.subscription.AndroidMainThreadSubscription import io.reactivex.Observable //================================================================================ // Events //================================================================================ fun TabLayout.rx_tabSelected(): Observable<TabLayout.Tab> { return Observable.create { subscriber -> _tabSelected.onTabSelected { if (it != null) subscriber.onNext(it) } subscriber.setDisposable(AndroidMainThreadSubscription { setOnTabSelectedListener(null) }) } } fun TabLayout.rx_tabUnselected(): Observable<TabLayout.Tab> { return Observable.create { subscriber -> _tabSelected.onTabUnselected { if (it != null) subscriber.onNext(it) } subscriber.setDisposable(AndroidMainThreadSubscription { setOnTabSelectedListener(null) }) } } fun TabLayout.rx_tabReselected(): Observable<TabLayout.Tab> { return Observable.create { subscriber -> _tabSelected.onTabReselected { if (it != null) subscriber.onNext(it) } subscriber.setDisposable(AndroidMainThreadSubscription { setOnTabSelectedListener(null) }) } } private val TabLayout._tabSelected: _TabLayout_OnTabSelectedListener by ExtensionFieldDelegate({ _TabLayout_OnTabSelectedListener() }, { setOnTabSelectedListener(it) }) class _TabLayout_OnTabSelectedListener : TabLayout.OnTabSelectedListener { private var onTabReselected: ((TabLayout.Tab?) -> Unit)? = null private var onTabUnselected: ((TabLayout.Tab?) -> Unit)? = null private var onTabSelected: ((TabLayout.Tab?) -> Unit)? = null fun onTabReselected(listener: (TabLayout.Tab?) -> Unit) { onTabReselected = listener } override fun onTabReselected(tab: TabLayout.Tab?) { onTabReselected?.invoke(tab) } fun onTabUnselected(listener: (TabLayout.Tab?) -> Unit) { onTabUnselected = listener } override fun onTabUnselected(tab: TabLayout.Tab?) { onTabUnselected?.invoke(tab) } fun onTabSelected(listener: (TabLayout.Tab?) -> Unit) { onTabSelected = listener } override fun onTabSelected(tab: TabLayout.Tab?) { onTabSelected?.invoke(tab) } }
mit
5ddcf5345cdff52910dc095c047fa570
29.650602
107
0.64033
5.234568
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/ide/typing/utils.kt
1
1829
package org.rust.ide.typing import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.highlighter.HighlighterIterator import com.intellij.psi.tree.IElementType import com.intellij.util.text.CharSequenceSubSequence import org.rust.lang.core.psi.RustLiteral import org.rust.lang.core.psi.RustLiteralTokenType fun isValidOffset(offset: Int, text: CharSequence): Boolean = 0 <= offset && offset <= text.length /** * Beware that this returns `false` for EOF! */ fun isValidInnerOffset(offset: Int, text: CharSequence): Boolean = 0 <= offset && offset < text.length /** * Get previous and next token types relative to [iterator] position. */ fun getSiblingTokens(iterator: HighlighterIterator): Pair<IElementType?, IElementType?> { iterator.retreat() val prev = if (iterator.atEnd()) null else iterator.tokenType iterator.advance() iterator.advance() val next = if (iterator.atEnd()) null else iterator.tokenType iterator.retreat() return prev to next } /** * Creates virtual [RustLiteral] PSI element assuming that it is represented as * single, contiguous token in highlighter, in other words - it doesn't contain * any escape sequences etc. (hence 'dumb'). */ fun getLiteralDumb(iterator: HighlighterIterator): RustLiteral? { val start = iterator.start val end = iterator.end val document = iterator.document val text = document.charsSequence val literalText = CharSequenceSubSequence(text, start, end) val elementType = iterator.tokenType as? RustLiteralTokenType ?: return null return elementType.createLeafNode(literalText) as RustLiteral } fun Document.deleteChar(offset: Int) { deleteString(offset, offset + 1) } fun CharSequence.endsWithUnescapedBackslash(): Boolean = takeLastWhile { it == '\\' }.length % 2 == 1
mit
127fb8ce59698ed65a5d54cf1945c691
31.660714
89
0.741935
4.224018
false
false
false
false
LorittaBot/Loritta
web/spicy-morenitta/src/main/kotlin/net/perfectdreams/spicymorenitta/routes/user.dashboard/DailyShopDashboardRoute.kt
1
29408
package net.perfectdreams.spicymorenitta.routes.user.dashboard import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import kotlinx.browser.document import kotlinx.browser.window import kotlinx.coroutines.delay import kotlinx.dom.clear import kotlinx.html.a import kotlinx.html.b import kotlinx.html.canvas import kotlinx.html.div import kotlinx.html.dom.append import kotlinx.html.dom.create import kotlinx.html.h1 import kotlinx.html.i import kotlinx.html.id import kotlinx.html.img import kotlinx.html.p import kotlinx.html.span import kotlinx.html.style import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.json.JSON import net.perfectdreams.loritta.cinnamon.pudding.data.BackgroundWithVariations import net.perfectdreams.loritta.cinnamon.pudding.data.DefaultBackgroundVariation import net.perfectdreams.loritta.common.utils.Rarity import net.perfectdreams.loritta.serializable.DailyShopBackgroundEntry import net.perfectdreams.loritta.serializable.DailyShopResult import net.perfectdreams.loritta.serializable.ProfileDesign import net.perfectdreams.loritta.serializable.ProfileSectionsResponse import net.perfectdreams.spicymorenitta.SpicyMorenitta import net.perfectdreams.spicymorenitta.application.ApplicationCall import net.perfectdreams.spicymorenitta.http import net.perfectdreams.spicymorenitta.locale import net.perfectdreams.spicymorenitta.routes.UpdateNavbarSizePostRender import net.perfectdreams.spicymorenitta.utils.FanArtArtist import net.perfectdreams.spicymorenitta.utils.LockerUtils import net.perfectdreams.spicymorenitta.utils.TingleModal import net.perfectdreams.spicymorenitta.utils.TingleOptions import net.perfectdreams.spicymorenitta.utils.awaitLoad import net.perfectdreams.spicymorenitta.utils.generateAd import net.perfectdreams.spicymorenitta.utils.locale.buildAsHtml import net.perfectdreams.spicymorenitta.utils.loriUrl import net.perfectdreams.spicymorenitta.utils.onClick import net.perfectdreams.spicymorenitta.utils.select import net.perfectdreams.spicymorenitta.utils.visibleModal import org.w3c.dom.Audio import org.w3c.dom.CanvasRenderingContext2D import org.w3c.dom.HTMLCanvasElement import org.w3c.dom.HTMLDivElement import org.w3c.dom.HTMLElement import org.w3c.dom.Image import kotlin.js.Date class DailyShopDashboardRoute(val m: SpicyMorenitta) : UpdateNavbarSizePostRender("/user/@me/dashboard/daily-shop") { override val keepLoadingScreen: Boolean get() = true var generatedAt = -1L override fun onRender(call: ApplicationCall) { super.onRender(call) SpicyMorenitta.INSTANCE.launch { fixDummyNavbarHeight(call) /* m.fixLeftSidebarScroll { switchContent(call) } */ m.launch { val timeUntilMidnight = getTimeUntilUTCMidnight() info("The page will be automatically updated @ $timeUntilMidnight") delay(timeUntilMidnight) m.showLoadingScreen() regen(true) m.hideLoadingScreen() } m.launch { while (true) { val timeElement = document.select<HTMLDivElement?>("#when-will-be-the-next-update") if (timeElement != null) { val timeInSeconds = getTimeUntilUTCMidnight() / 1_000 val s = timeInSeconds % 60 val m = (timeInSeconds / 60) % 60 val h = (timeInSeconds / (60 * 60)) % 24 debug("time in seconds: $timeInSeconds") debug("h: $h") debug("m: $m") debug("s: $s") timeElement.clear() timeElement.append { span { if (h != 0L) { +"${h + 1} Horas" } else if (m != 0L) { +"$m Minutos" } else if (s != 0L) { +"$s Segundos" } } } } delay(1_000) } } regen(false) m.hideLoadingScreen() } } suspend fun regen(keepRechecking: Boolean) { // ===[ DAILY SHOP ]=== val dailyJob = m.async { val payload = http.get { url("${window.location.origin}/api/v1/economy/daily-shop") }.bodyAsText() val result = JSON.nonstrict.decodeFromString(DailyShopResult.serializer(), payload) info("Shop was successfully updated! generatedAt = ${result.generatedAt}") generatedAt = result.generatedAt return@async result } // TODO: Fix this! I don't know why it is like that /* val dailyJob = m.async { while (true) { val payload = http.get<String> { url("${window.location.origin}/api/v1/economy/daily-shop") } val result = JSON.nonstrict.decodeFromString(DailyShopResult.serializer(), payload) if (keepRechecking && generatedAt == result.generatedAt) { info("Waiting for 5_000ms until we recheck the shop again, looks like it wasn't fully updated yet...") delay(5_000) continue } info("Shop was successfully updated! generatedAt = ${result.generatedAt}") generatedAt = result.generatedAt return@async result } throw RuntimeException("Should never happen!") } */ // ===[ USERS SHENANIGANS ]=== val usersShenanigansJob = m.async { debug("Retrieving profiles & background info...") val payload = http.get { url("${window.location.origin}/api/v1/users/@me/profiles,backgrounds,profileDesigns") }.bodyAsText() debug("Retrieved profiles & background info!") val result = JSON.nonstrict.decodeFromString(ProfileSectionsResponse.serializer(), payload) return@async result } // ===[ USER PROFILE IMAGE ]=== val profileWrapperJob = m.async { val profileWrapper = Image() debug("Awaiting load...") profileWrapper.awaitLoad("${window.location.origin}/api/v1/users/@me/profile?t=${Date().getTime()}") debug("Load complete!") profileWrapper } debug("await #1") val dailyShop = dailyJob.await() debug("await #2") val userBackgrounds = usersShenanigansJob.await() debug("await #3") val profileWrapper = profileWrapperJob.await() debug("await #4") // Those should always be present due to our URL query, but who knows, right? // I tried using the "error" method to throw an IllegalArgumentException in a nice way... but the "Logger" class also has a "error" method, smh val backgroundsWrapper = userBackgrounds.backgrounds ?: throw IllegalArgumentException("Background Wrapper is not present! Bug?") val profileDataWrapper = userBackgrounds.profile ?: throw IllegalArgumentException("Profile Data Wrapper is not present! Bug?") val profileDesigns = userBackgrounds.profileDesigns ?: throw IllegalArgumentException("Profile Designs is not present! Bug?") val allArtists = (dailyShop.backgrounds.map { it.backgroundWithVariations.background.createdBy } + dailyShop.profileDesigns.mapNotNull { it.createdBy }) .flatten() .distinct() val fanArtArtistsJob = m.async { if (allArtists.isEmpty()) return@async listOf<FanArtArtist>() val payload = http.get { url("${window.location.origin}/api/v1/loritta/fan-arts?query=all&filter=${allArtists.joinToString(",")}") }.bodyAsText() JSON.nonstrict.decodeFromString(ListSerializer(FanArtArtist.serializer()), payload) } val fanArtArtists = fanArtArtistsJob.await() debug("Everything is retrieved! Let's go!") generateShop( dailyShop, profileDataWrapper, backgroundsWrapper, profileDesigns, profileWrapper, fanArtArtists ) } fun getTimeUntilUTCMidnight(): Long { val date = Date() date.asDynamic().setUTCHours(24, 0, 0, 0) val now = Date().getTime() val diff = date.getTime().toLong() - now.toLong() return diff } fun generateShop( dailyShop: DailyShopResult, profileDataWrapper: ProfileSectionsResponse.ProfileDataWrapper, backgroundsWrapper: ProfileSectionsResponse.BackgroundsWrapper, profileDesigns: List<ProfileDesign>, profileWrapper: Image, fanArtArtists: List<FanArtArtist> ) { info("Generating Shop...") val entriesDiv = document.select<HTMLDivElement>("#bundles-content") entriesDiv.clear() entriesDiv.append { div { id = "daily-shop" div { style = "text-align: center;" img(src = "https://loritta.website/assets/img/fanarts/Loritta_17_-_Allouette.png") { style = "width: 400px;" } h1 { + locale["website.dailyShop.title"] } p { + "Bem-vind@ a loja diária de itens! O lugar para comprar itens para o seu \"+perfil\" da Loritta!" } p { + "Todo o dia as 00:00 UTC (21:00 no horário do Brasil) a loja é atualizada com novos itens! Então volte todo o dia para verificar ^-^" } } div { generateAd("5964074013", "Loritta Daily Shop") } div(classes = "shop-reset-timer") { div(classes = "horizontal-line") {} i(classes = "fas fa-stopwatch stopwatch") {} div(classes = "shop-timer") { div(classes = "shop-timer-date") { id = "when-will-be-the-next-update" } div(classes = "shop-timer-subtitle") { + locale["website.dailyShop.untilTheNextShopUpdate"] } } } div(classes = "loritta-items-wrapper") { // A list containing all of the items in the shop // We are now going to sort it by rarity val allItemsInTheShop = dailyShop.profileDesigns.map { ProfileDesignItemWrapper(it) } + dailyShop.backgrounds.map { BackgroundItemWrapper(it) } val sortedByRarityAllItemsInTheShop = allItemsInTheShop.sortedByDescending { it.rarity } for (shopItem in sortedByRarityAllItemsInTheShop) { val bought = when (shopItem) { is BackgroundItemWrapper -> shopItem.hasBought(backgroundsWrapper) is ProfileDesignItemWrapper -> shopItem.hasBought(profileDesigns) } div(classes = "shop-item-entry rarity-${shopItem.rarity.name.toLowerCase()}") { div { style = "position: relative;" div { style = "overflow: hidden; line-height: 0;" canvas("canvas-background-preview") { id = "canvas-preview-${shopItem.internalName}" width = "800" height = "600" // we try to keep the item shop with at least two columns if you are using 720p // 1080p can have at least three columns // we do that by setting a min-width (to avoid the items being waaaay too small) and a max-width (to avoid waaaay big items) // and a width: 24vw; just to reuse the window width style = "width: 24vw; min-width: 250px; max-width: 320px; height: auto;" } } div(classes = "item-entry-information rarity-${shopItem.rarity.name.toLowerCase()}") { div(classes = "item-entry-title rarity-${shopItem.rarity.name.toLowerCase()}") { +(locale["${shopItem.localePrefix}.${shopItem.internalName}.title"]) } div(classes = "item-entry-type") { + locale["${shopItem.localePrefix}.name"] } } if (shopItem.tag != null) { div(classes = "item-new-tag") { + locale[shopItem.tag!!] } } } div(classes = "item-user-information") { if (bought) { i(classes = "fas fa-check") { style = "color: #80ff00;" } +" ${locale["website.dailyShop.itemAlreadyBought"]}" } else { +"${shopItem.price} Sonhos" } } } } } } } // Setup the images for the item entires in the daily shop for (profileDesign in dailyShop.profileDesigns) { val bought = profileDesign.internalName in profileDesigns.map { it.internalName } val canvasPreview = document.select<HTMLCanvasElement>("#canvas-preview-${profileDesign.internalName}") m.launch { val (image) = LockerUtils.prepareProfileDesignsCanvasPreview(m, profileDesign, canvasPreview) canvasPreview.parentElement!!.parentElement!!.onClick { openProfileDesignInformation(profileDataWrapper, profileDesign, bought, image, fanArtArtists) } } } for (backgroundEntry in dailyShop.backgrounds) { val backgroundWithVariations = backgroundEntry.backgroundWithVariations val (background, variations) = backgroundWithVariations val bought = backgroundsWrapper.backgrounds.any { background.id == it.background.id } val canvasPreview = document.select<HTMLCanvasElement>("#canvas-preview-${background.id}") m.launch { val variation = backgroundWithVariations.variations.firstOrNull { it is DefaultBackgroundVariation } if (variation != null) { val (image) = LockerUtils.prepareBackgroundCanvasPreview( m, dailyShop.dreamStorageServiceUrl, dailyShop.namespace, variation, canvasPreview ) canvasPreview.parentElement!!.parentElement!!.onClick { openBackgroundInformation( profileDataWrapper, backgroundWithVariations, bought, StaticBackgroundImage(image), profileWrapper, fanArtArtists ) } } } } } fun openProfileDesignInformation(result: ProfileSectionsResponse.ProfileDataWrapper, background: ProfileDesign, alreadyBought: Boolean, image: Image, fanArtArtists: List<FanArtArtist>) { val modal = TingleModal( TingleOptions( footer = true, cssClass = arrayOf("tingle-modal--overflow") ) ) modal.setContent( document.create.div(classes = "item-shop-preview") { div { style = "flex-grow: 1;" h1 { style = "word-break: break-word; text-align: center;" +(locale["profileDesigns.${background.internalName}.title"]) } div { style = "margin-bottom: 10px;" +(locale["profileDesigns.${background.internalName}.description"]) if (background.createdBy != null) { val artists = fanArtArtists.filter { it.id in background.createdBy!! } if (artists.isNotEmpty()) { artists.forEach { div { val name = (it.info.override?.name ?: it.user?.name ?: it.info.name ?: it.id) +"Criado por " a(href = "/fanarts/${it.id}") { +name } } } } } } if (background.set != null) { div { i { locale.buildAsHtml(locale["website.dailyShop.partOfTheSet"], { num -> if (num == 0) { b { + (locale["sets.${background.set}"]) } } }) { + it } } } } } div(classes = "canvas-preview-wrapper") { canvas("canvas-preview-only-bg") { style = """width: 400px;""" width = "800" height = "600" } canvas("canvas-preview") { style = """width: 400px;""" width = "800" height = "600" } } } ) val cash = Audio("${loriUrl}assets/snd/css1_cash.wav") if (!alreadyBought) { val canBuy = result.money >= background.rarity.getProfilePrice() val classes = if (canBuy) "button-discord-info" else "button-discord-disabled" modal.addFooterBtn("<i class=\"fas fa-gift\"></i> Comprar", "buy-button-modal button-discord $classes pure-button button-discord-modal") { if (canBuy) { m.launch { m.showLoadingScreen() val response = sendItemPurchaseRequest("profile-design", background.internalName) if (response.status != HttpStatusCode.OK) { } visibleModal.select<HTMLElement>(".buy-button-modal") .remove() m.launch { regen(false) m.hideLoadingScreen() cash.play() } } } } } modal.addFooterBtn("<i class=\"fas fa-times\"></i> Fechar", "button-discord pure-button button-discord-modal button-discord-modal-secondary-action") { modal.close() } modal.open() val openModal = visibleModal val canvasCheckout = visibleModal.select<HTMLCanvasElement>(".canvas-preview") val canvasCheckoutOnlyBg = visibleModal.select<HTMLCanvasElement>(".canvas-preview-only-bg") val canvasPreviewContext = (canvasCheckout.getContext("2d")!! as CanvasRenderingContext2D) val canvasPreviewOnlyBgContext = (canvasCheckoutOnlyBg.getContext("2d")!! as CanvasRenderingContext2D) canvasPreviewOnlyBgContext .drawImage( image, 0.0, 0.0, image.width.toDouble(), image.height.toDouble(), 0.0, 0.0, 800.0, 600.0 ) } fun openBackgroundInformation(result: ProfileSectionsResponse.ProfileDataWrapper, backgroundWithVariations: BackgroundWithVariations, alreadyBought: Boolean, backgroundImg: BackgroundImage, profileWrapper: Image, fanArtArtists: List<FanArtArtist>) { val (background, variations) = backgroundWithVariations val modal = TingleModal( TingleOptions( footer = true, cssClass = arrayOf("tingle-modal--overflow") ) ) val defaultVariation = variations.first { it is DefaultBackgroundVariation } modal.setContent( document.create.div(classes = "item-shop-preview") { div { style = "flex-grow: 1;" h1 { style = "word-break: break-word; text-align: center;" +(locale["backgrounds.${background.id}.title"]) } div { style = "margin-bottom: 10px;" +(locale["backgrounds.${background.id}.description"]) val artists = fanArtArtists.filter { it.id in background.createdBy } if (artists.isNotEmpty()) { artists.forEach { div { val name = (it.info.override?.name ?: it.user?.name ?: it.info.name ?: it.id) +"Criado por " a(href = "/fanarts/${it.id}") { +name } } } } } if (background.set != null) { div { i { locale.buildAsHtml(locale["website.dailyShop.partOfTheSet"], { num -> if (num == 0) { b { + (locale["sets.${background.set}"]) } } }) { + it } } } } } div(classes = "canvas-preview-wrapper") { canvas("canvas-preview-only-bg") { style = """width: 400px;""" width = "800" height = "600" } canvas("canvas-preview") { style = """width: 400px;""" width = "800" height = "600" } } } ) val cash = Audio("${loriUrl}assets/snd/css1_cash.wav") if (!alreadyBought) { val canBuy = result.money >= background.rarity.getBackgroundPrice() val classes = if (canBuy) "button-discord-info" else "button-discord-disabled" modal.addFooterBtn("<i class=\"fas fa-gift\"></i> Comprar", "buy-button-modal button-discord $classes pure-button button-discord-modal") { if (canBuy) { m.launch { m.showLoadingScreen() val response = sendItemPurchaseRequest("background", background.id) if (response.status != HttpStatusCode.OK) { } visibleModal.select<HTMLElement>(".buy-button-modal") .remove() m.launch { regen(false) m.hideLoadingScreen() cash.play() } } } } } modal.addFooterBtn("<i class=\"fas fa-times\"></i> Fechar", "button-discord pure-button button-discord-modal button-discord-modal-secondary-action") { modal.close() } modal.open() val openModal = visibleModal val canvasCheckout = visibleModal.select<HTMLCanvasElement>(".canvas-preview") val canvasCheckoutOnlyBg = visibleModal.select<HTMLCanvasElement>(".canvas-preview-only-bg") val canvasPreviewContext = (canvasCheckout.getContext("2d")!! as CanvasRenderingContext2D) val canvasPreviewOnlyBgContext = (canvasCheckoutOnlyBg.getContext("2d")!! as CanvasRenderingContext2D) if (backgroundImg is StaticBackgroundImage) { canvasPreviewContext .drawImage( backgroundImg.image, (defaultVariation.crop?.x ?: 0).toDouble(), (defaultVariation.crop?.y ?: 0).toDouble(), (defaultVariation.crop?.width ?: backgroundImg.image.width).toDouble(), (defaultVariation.crop?.height ?: backgroundImg.image.height).toDouble(), 0.0, 0.0, 800.0, 600.0 ) canvasPreviewOnlyBgContext .drawImage( backgroundImg.image, (defaultVariation.crop?.x ?: 0).toDouble(), (defaultVariation.crop?.y ?: 0).toDouble(), (defaultVariation.crop?.width ?: backgroundImg.image.width).toDouble(), (defaultVariation.crop?.height ?: backgroundImg.image.height).toDouble(), 0.0, 0.0, 800.0, 600.0 ) canvasPreviewContext.drawImage(profileWrapper, 0.0, 0.0) } } /** * Sends a daily shop item purchase request, asking to buy a [itemType] [internalName] * * @param itemType what kind of item it is * @param internalName what is the internal name (ID) of the item * @return the http response */ private suspend fun sendItemPurchaseRequest(itemType: String, internalName: String) = http.post("${loriUrl}api/v1/economy/daily-shop/buy/$itemType/$internalName") { setBody("{}") } open class BackgroundImage class StaticBackgroundImage(val image: Image) : BackgroundImage() sealed class ShopItemWrapper { abstract val internalName: String abstract val rarity: Rarity abstract val tag: String? abstract val localePrefix: String? abstract val price: Int? } class BackgroundItemWrapper(backgroundEntry: DailyShopBackgroundEntry) : ShopItemWrapper() { val background = backgroundEntry.backgroundWithVariations.background override val internalName = background.id override val rarity = background.rarity override val tag = backgroundEntry.tag override val localePrefix = "backgrounds" override val price = rarity.getBackgroundPrice() /** * Checks if the user has already bought the item or not * * @return if the user already has the item */ fun hasBought(backgroundsWrapper: ProfileSectionsResponse.BackgroundsWrapper) = backgroundsWrapper.backgrounds.any { it.background.id == internalName } } class ProfileDesignItemWrapper(profileDesign: ProfileDesign) : ShopItemWrapper() { override val internalName = profileDesign.internalName override val rarity = profileDesign.rarity override val tag = profileDesign.tag override val localePrefix = "profileDesigns" override val price = rarity.getProfilePrice() /** * Checks if the user has already bought the item or not * * @return if the user already has the item */ fun hasBought(profileDesigns: List<ProfileDesign>) = profileDesigns.any { it.internalName == internalName } } }
agpl-3.0
1ed6d72d5841f5d3b849b5b07fdddb04
40.650142
253
0.504319
5.291344
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/commands/CinnamonSlashCommandExecutor.kt
1
5020
package net.perfectdreams.loritta.cinnamon.discord.interactions.commands import dev.kord.common.entity.Snowflake import kotlinx.datetime.Clock import mu.KotlinLogging import net.perfectdreams.discordinteraktions.common.commands.ApplicationCommandContext import net.perfectdreams.discordinteraktions.common.commands.GuildApplicationCommandContext import net.perfectdreams.discordinteraktions.common.commands.SlashCommandExecutor import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments import net.perfectdreams.i18nhelper.core.I18nContext import net.perfectdreams.loritta.common.commands.ApplicationCommandType import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.utils.metrics.InteractionsMetrics import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext as CinnamonApplicationCommandContext /** * Discord InteraKTions' [SlashCommandExecutor] wrapper, used to provide Cinnamon-specific features. */ abstract class CinnamonSlashCommandExecutor(val loritta: LorittaBot) : SlashCommandExecutor(), CommandExecutorWrapper { companion object { private val logger = KotlinLogging.logger {} } private val executorClazzName: String = this::class.simpleName ?: "UnknownExecutor" val rest = loritta.rest val applicationId = loritta.config.loritta.discord.applicationId abstract suspend fun execute( context: CinnamonApplicationCommandContext, args: SlashCommandArguments ) override suspend fun execute( context: ApplicationCommandContext, args: SlashCommandArguments ) { val rootDeclarationClazzName = (context.applicationCommandDeclaration as CinnamonSlashCommandDeclaration).declarationWrapper::class .simpleName ?: "UnknownCommand" val stringifiedArgumentNames = stringifyArgumentNames(args.types) logger.info { "(${context.sender.id.value}) $this $stringifiedArgumentNames" } val timer = InteractionsMetrics.EXECUTED_COMMAND_LATENCY_COUNT .labels(rootDeclarationClazzName, executorClazzName) .startTimer() val guildId = (context as? GuildApplicationCommandContext)?.guildId val result = executeCommand( rootDeclarationClazzName, executorClazzName, context, args, guildId ) var stacktrace: String? = null if (result is CommandExecutorWrapper.CommandExecutionFailure) stacktrace = result.throwable.stackTraceToString() val commandLatency = timer.observeDuration() logger.info { "(${context.sender.id.value}) $this $stringifiedArgumentNames - OK! Result: ${result}; Took ${commandLatency * 1000}ms" } loritta.pudding.executedInteractionsLog.insertApplicationCommandLog( context.sender.id.value.toLong(), guildId?.value?.toLong(), context.channelId.value.toLong(), Clock.System.now(), ApplicationCommandType.CHAT_INPUT, rootDeclarationClazzName, executorClazzName, buildJsonWithArguments(args.types), stacktrace == null, commandLatency, stacktrace ) } private suspend fun executeCommand( rootDeclarationClazzName: String, executorClazzName: String, context: ApplicationCommandContext, args: SlashCommandArguments, guildId: Snowflake? ): CommandExecutorWrapper.CommandExecutionResult { // These variables are used in the catch { ... } block, to make our lives easier var i18nContext: I18nContext? = null val cinnamonContext: CinnamonApplicationCommandContext? try { val serverConfig = getGuildServerConfigOrLoadDefaultConfig(loritta, guildId) val locale = loritta.localeManager.getLocaleById(serverConfig.localeId) i18nContext = loritta.languageManager.getI18nContextByLegacyLocaleId(serverConfig.localeId) cinnamonContext = convertInteraKTionsContextToCinnamonContext(loritta, context, i18nContext, locale) // Don't let users that are banned from using Loritta if (CommandExecutorWrapper.handleIfBanned(loritta, cinnamonContext)) return CommandExecutorWrapper.CommandExecutionSuccess launchUserInfoCacheUpdater(loritta, context, args) execute( cinnamonContext, args ) launchAdditionalNotificationsCheckerAndSender(loritta, context, i18nContext) return CommandExecutorWrapper.CommandExecutionSuccess } catch (e: Throwable) { return convertThrowableToCommandExecutionResult( loritta, context, i18nContext, rootDeclarationClazzName, executorClazzName, e ) } } }
agpl-3.0
f6fa68052da0fadaaaf5b5bf5334cded
39.491935
143
0.705578
5.724059
false
false
false
false
wakingrufus/mastodon-jfx
src/test/kotlin/com/github/wakingrufus/mastodon/ui/NotificationFeedViewTest.kt
1
2334
package com.github.wakingrufus.mastodon.ui import com.github.wakingrufus.mastodon.TornadoFxTest import com.github.wakingrufus.mastodon.data.NotificationFeed import com.sys1yagi.mastodon4j.api.entity.Account import com.sys1yagi.mastodon4j.api.entity.Notification import com.sys1yagi.mastodon4j.api.entity.Status import javafx.collections.FXCollections import mu.KLogging import org.junit.Test class NotificationFeedViewTest : TornadoFxTest() { companion object : KLogging() @Test fun test() { val account = Account( id = 1, displayName = "displayName", userName = "username") showViewWithParams<NotificationFeedView>(mapOf( "notificationFeed" to NotificationFeed( name = "userName", server = "http://mastodon.social", notifications = FXCollections.observableArrayList( Notification( account = account, type = Notification.Type.Follow.value), Notification( status = Status( content = "<p>toot</p>", account = account), account = account, type = Notification.Type.Favourite.value), Notification( status = Status( content = "<p>toot</p>", account = account), account = account, type = Notification.Type.Mention.value), Notification( status = Status( content = "<p>toot</p>", account = account), account = account, type = Notification.Type.Reblog.value) ) ) )) } }
mit
7d26c06bcce37f4083ef341c6975bd95
44.784314
82
0.420737
6.429752
false
true
false
false
DevCharly/kotlin-ant-dsl
src/main/kotlin/com/devcharly/kotlin/ant/selectors/scriptselector.kt
1
2643
/* * 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.Path import org.apache.tools.ant.types.Reference import org.apache.tools.ant.types.optional.ScriptSelector /****************************************************************************** DO NOT EDIT - this file was generated ******************************************************************************/ interface IScriptSelectorNested : INestedComponent { fun scriptselector( manager: String? = null, language: String? = null, src: String? = null, classpath: String? = null, classpathref: String? = null, setbeans: Boolean? = null, selected: Boolean? = null, error: String? = null, nested: (KScriptSelector.() -> Unit)? = null) { _addScriptSelector(ScriptSelector().apply { component.project.setProjectReference(this); _init(manager, language, src, classpath, classpathref, setbeans, selected, error, nested) }) } fun _addScriptSelector(value: ScriptSelector) } fun ScriptSelector._init( manager: String?, language: String?, src: String?, classpath: String?, classpathref: String?, setbeans: Boolean?, selected: Boolean?, error: String?, nested: (KScriptSelector.() -> Unit)?) { if (manager != null) setManager(manager) if (language != null) setLanguage(language) if (src != null) setSrc(project.resolveFile(src)) if (classpath != null) setClasspath(Path(project, classpath)) if (classpathref != null) setClasspathRef(Reference(project, classpathref)) if (setbeans != null) setSetBeans(setbeans) if (selected != null) setSelected(selected) if (error != null) setError(error) if (nested != null) nested(KScriptSelector(this)) } class KScriptSelector(val component: ScriptSelector) { fun classpath(location: String? = null, path: String? = null, cache: Boolean? = null, nested: (KPath.() -> Unit)? = null) { component.createClasspath().apply { component.project.setProjectReference(this) _init(location, path, cache, nested) } } operator fun String.unaryPlus() = component.addText(this) }
apache-2.0
65bdc1a756615c402a6a3284cec820b3
29.034091
124
0.676882
3.660665
false
false
false
false
bassaer/ChatMessageView
chatmessageview/src/main/kotlin/com/github/bassaer/chatmessageview/view/ChatView.kt
1
9584
package com.github.bassaer.chatmessageview.view import android.content.Context import android.content.res.ColorStateList import android.graphics.drawable.Drawable import android.os.Handler import android.text.TextWatcher import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.AdapterView import android.widget.LinearLayout import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.DrawableCompat import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.github.bassaer.chatmessageview.R import com.github.bassaer.chatmessageview.model.Attribute import com.github.bassaer.chatmessageview.model.Message import kotlinx.android.synthetic.main.chat_view.view.* import kotlinx.android.synthetic.main.option_button.view.* /** * Chat view with edit view and send button * Created by nakayama on 2016/08/08. */ class ChatView : LinearLayout { private lateinit var inputMethodManager: InputMethodManager private var sendIconId = R.drawable.ic_action_send private var optionIconId = R.drawable.ic_action_add private var sendIconColor = ContextCompat.getColor(context, R.color.lightBlue500) private var optionIconColor = ContextCompat.getColor(context, R.color.lightBlue500) private var isEnableAutoScroll = true private var isEnableAutoHidingKeyboard = true private var attribute: Attribute var inputText: String get() = inputBox.text.toString() set(input) = inputBox.setText(input) val isEnabledSendButton: Boolean get() = sendButton.isEnabled constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { attribute = Attribute(context, attrs) init(context) } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { attribute = Attribute(context, attrs) init(context) } private fun init(context: Context) { inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager LayoutInflater.from(context).inflate(R.layout.chat_view, this) chatContainer.isEnabled = false if (attribute.isOptionButtonEnable) { LayoutInflater.from(context).inflate(R.layout.option_button, optionButtonContainer) } messageView.init(attribute) messageView.isFocusableInTouchMode = true //if touched Chat screen messageView.onItemClickListener = AdapterView.OnItemClickListener { _, _, _, _ -> hideKeyboard() } //if touched empty space chatContainer.setOnClickListener { hideKeyboard() } messageView.setOnKeyboardAppearListener(object : MessageView.OnKeyboardAppearListener { override fun onKeyboardAppeared(hasChanged: Boolean) { //Appeared keyboard if (hasChanged) { Handler().postDelayed({ //Scroll to end messageView.scrollToEnd() }, 500) } } }) } /** * Hide software keyboard */ private fun hideKeyboard() { //Hide keyboard inputMethodManager.hideSoftInputFromWindow( messageView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS) //Move focus to background messageView.requestFocus() } fun setLeftBubbleColor(color: Int) { messageView.setLeftBubbleColor(color) } fun setRightBubbleColor(color: Int) { messageView.setRightBubbleColor(color) } /** * Set message to right side * @param message Sent message */ fun send(message: Message) { messageView.setMessage(message) //Hide keyboard after post if (isEnableAutoHidingKeyboard) { hideKeyboard() } //Scroll to bottom after post if (isEnableAutoScroll) { messageView.scrollToEnd() } } /** * Set message to left side * @param message Received message */ fun receive(message: Message) { messageView.setMessage(message) if (isEnableAutoScroll) { messageView.scrollToEnd() } } fun setOnClickSendButtonListener(listener: View.OnClickListener) { sendButton.setOnClickListener(listener) } fun setOnClickOptionButtonListener(listener: View.OnClickListener) { optionButton?.setOnClickListener(listener) } var inputType: Int get() = inputBox.inputType set(type) { inputBox.inputType = type } var inputTextColor: Int get() = inputBox.currentTextColor set(color) { inputBox.setTextColor(color) } fun setInputTextSize(unit: Int, size: Float) { inputBox.setTextSize(unit, size) } override fun setBackgroundColor(color: Int) { messageView.setBackgroundColor(color) chatContainer.setBackgroundColor(color) } fun setSendButtonColor(color: Int) { sendIconColor = color sendButton.setImageDrawable(getColoredDrawable(color, sendIconId)) } fun setOptionButtonColor(color: Int) { optionIconColor = color optionButton.setImageDrawable(getColoredDrawable(color, optionIconId)) } private fun getColoredDrawable(color: Int, iconId: Int): Drawable { val colorStateList = ColorStateList.valueOf(color) val icon = ContextCompat.getDrawable(context, iconId)!! val wrappedDrawable = DrawableCompat.wrap(icon) DrawableCompat.setTintList(wrappedDrawable, colorStateList) return wrappedDrawable } fun setSendIcon(resId: Int) { sendIconId = resId setSendButtonColor(sendIconColor) } fun setOptionIcon(resId: Int) { optionIconId = resId setOptionButtonColor(optionIconColor) } fun setInputTextHint(hint: String) { inputBox.hint = hint } fun setUsernameTextColor(color: Int) { messageView.setUsernameTextColor(color) } fun setSendTimeTextColor(color: Int) { messageView.setSendTimeTextColor(color) } fun setDateSeparatorColor(color: Int) { messageView.setDateSeparatorTextColor(color) } fun setRightMessageTextColor(color: Int) { messageView.setRightMessageTextColor(color) } fun setMessageStatusTextColor(color: Int) { messageView.setMessageStatusColor(color) } fun setMessageStatusColor(color: Int){ messageView.setMessageStatusColor(color) } fun updateMessageStatus(message: Message, status: Int) { messageView.updateMessageStatus(message, status) } fun setOnBubbleClickListener(listener: Message.OnBubbleClickListener) { messageView.setOnBubbleClickListener(listener) } fun setOnBubbleLongClickListener(listener: Message.OnBubbleLongClickListener) { messageView.setOnBubbleLongClickListener(listener) } fun setOnIconClickListener(listener: Message.OnIconClickListener) { messageView.setOnIconClickListener(listener) } fun setOnIconLongClickListener(listener: Message.OnIconLongClickListener) { messageView.setOnIconLongClickListener(listener) } fun setLeftMessageTextColor(color: Int) { messageView.setLeftMessageTextColor(color) } /** * Auto Scroll when message received. * @param enable Whether auto scroll is enable or not */ fun setAutoScroll(enable: Boolean) { isEnableAutoScroll = enable } fun setMessageMarginTop(px: Int) { messageView.setMessageMarginTop(px) } fun setMessageMarginBottom(px: Int) { messageView.setMessageMarginBottom(px) } /** * Add TEXT watcher * @param watcher behavior when text view status is changed */ fun addTextWatcher(watcher: TextWatcher) { inputBox.addTextChangedListener(watcher) } fun setEnableSendButton(enable: Boolean) { sendButton.isEnabled = enable } /** * Auto hiding keyboard after post * @param autoHidingKeyboard if true, keyboard will be hided after post */ fun setAutoHidingKeyboard(autoHidingKeyboard: Boolean) { this.isEnableAutoHidingKeyboard = autoHidingKeyboard } fun setOnRefreshListener(listener: SwipeRefreshLayout.OnRefreshListener) { chatContainer.setOnRefreshListener(listener) } fun setRefreshing(refreshing: Boolean) { chatContainer.isRefreshing = refreshing } fun setEnableSwipeRefresh(enable: Boolean) { chatContainer.isEnabled = enable } fun addInputChangedListener(watcher: TextWatcher) { inputBox.addTextChangedListener(watcher) } fun scrollToEnd() { messageView.scrollToEnd() } fun setMaxInputLine(lines: Int) { inputBox.maxLines = lines } fun setMessageFontSize(size: Float) { messageView.setMessageFontSize(size) } fun setUsernameFontSize(size: Float) { messageView.setUsernameFontSize(size) } fun setTimeLabelFontSize(size: Float) { messageView.setTimeLabelFontSize(size) } fun setMessageMaxWidth(width: Int) { messageView.setMessageMaxWidth(width) } fun setDateSeparatorFontSize(size: Float) { messageView.setDateSeparatorFontSize(size) } fun getMessageView(): MessageView = messageView }
apache-2.0
45dbc96b5e3d893f001d6e29ab63fcdd
28.219512
113
0.683013
4.914872
false
false
false
false
lttng/lttng-scope
jabberwocky-lttng/src/main/kotlin/com/efficios/jabberwocky/lttng/kernel/analysis/os/KernelThreadInfo.kt
2
8105
/* * Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]> * Copyright (C) 2014-2015 École Polytechnique de Montréal * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.efficios.jabberwocky.lttng.kernel.analysis.os import ca.polymtl.dorsal.libdelorean.IStateSystemReader import ca.polymtl.dorsal.libdelorean.statevalue.IntegerStateValue /** * Get the ID of the thread running on the CPU at time ts * * TODO: This method may later be replaced by an aspect, when the aspect can * resolve to something that is not an event * * @param cpuId * The CPU number the process is running on * @param ts * The timestamp at which we want the running process * @return The TID of the thread running on CPU cpuId at time ts or * {@code null} if either no thread is running or we do not know. */ fun IStateSystemReader.getThreadOnCpu(cpuId: Long, ts: Long): Int? { val cpuQuark = getQuarkAbsolute(Attributes.CPUS, cpuId.toString(), Attributes.CURRENT_THREAD) val sv = querySingleState(ts, cpuQuark).stateValue return (sv as? IntegerStateValue)?.value } // // /** // * Get the TIDs of the threads from an analysis // * // * @param module // * The kernel analysis instance to run this method on // * @return The set of TIDs corresponding to the threads // */ // public static Collection<Integer> getThreadIds(KernelAnalysisModule module) { // ITmfStateSystem ss = module.getStateSystem(); // if (ss == null) { // return Collections.EMPTY_SET; // } // int threadQuark; // try { // threadQuark = ss.getQuarkAbsolute(Attributes.THREADS); // Set<@NonNull Integer> tids = new TreeSet<>(); // for (Integer quark : ss.getSubAttributes(threadQuark, false)) { // final @NonNull String attributeName = ss.getAttributeName(quark); // tids.add(attributeName.startsWith(Attributes.THREAD_0_PREFIX) ? 0 : Integer.parseInt(attributeName)); // } // return tids; // } catch (AttributeNotFoundException e) { // } // return Collections.EMPTY_SET; // } // // /** // * Get the parent process ID of a thread // * // * @param module // * The kernel analysis instance to run this method on // * @param threadId // * The thread ID of the process for which to get the parent // * @param ts // * The timestamp at which to get the parent // * @return The parent PID or {@code null} if the PPID is not found. // */ // public static @Nullable Integer getParentPid(KernelAnalysisModule module, Integer threadId, long ts) { // ITmfStateSystem ss = module.getStateSystem(); // if (ss == null) { // return null; // } // Integer ppidNode; // try { // ppidNode = ss.getQuarkAbsolute(Attributes.THREADS, threadId.toString(), Attributes.PPID); // ITmfStateInterval ppidInterval = ss.querySingleState(ts, ppidNode); // ITmfStateValue ppidValue = ppidInterval.getStateValue(); // // if (ppidValue.getType().equals(Type.INTEGER)) { // return Integer.valueOf(ppidValue.unboxInt()); // } // } catch (AttributeNotFoundException | StateSystemDisposedException | TimeRangeException e) { // } // return null; // } // // /** // * Get the executable name of the thread ID. If the thread ID was used // * multiple time or the name changed in between, it will return the last // * name the thread has taken, or {@code null} if no name is found // * // * @param module // * The kernel analysis instance to run this method on // * @param threadId // * The thread ID of the process for which to get the name // * @return The last executable name of this process, or {@code null} if not // * found // */ // public static @Nullable String getExecutableName(KernelAnalysisModule module, Integer threadId) { // ITmfStateSystem ss = module.getStateSystem(); // if (ss == null) { // return null; // } // try { // Integer execNameNode = ss.getQuarkAbsolute(Attributes.THREADS, threadId.toString(), Attributes.EXEC_NAME); // List<ITmfStateInterval> execNameIntervals = StateSystemUtils.queryHistoryRange(ss, execNameNode, ss.getStartTime(), ss.getCurrentEndTime()); // // ITmfStateValue execNameValue; // String execName = null; // for (ITmfStateInterval interval : execNameIntervals) { // execNameValue = interval.getStateValue(); // if (execNameValue.getType().equals(Type.STRING)) { // execName = execNameValue.unboxStr(); // } // } // return execName; // } catch (AttributeNotFoundException | StateSystemDisposedException | TimeRangeException e) { // } // return null; // } // // /** // * Get the priority of this thread at time ts // * // * @param module // * The kernel analysis instance to run this method on // * @param threadId // * The ID of the thread to query // * @param ts // * The timestamp at which to query // * @return The priority of the thread or <code>-1</code> if not available // */ // public static int getThreadPriority(KernelAnalysisModule module, int threadId, long ts) { // ITmfStateSystem ss = module.getStateSystem(); // if (ss == null) { // return -1; // } // try { // int prioQuark = ss.getQuarkAbsolute(Attributes.THREADS, String.valueOf(threadId), Attributes.PRIO); // return ss.querySingleState(ts, prioQuark).getStateValue().unboxInt(); // } catch (AttributeNotFoundException | StateSystemDisposedException e) { // return -1; // } // } // /** // * Get the status intervals for a given thread with a resolution // * // * @param module // * The kernel analysis instance to run this method on // * @param threadId // * The ID of the thread to get the intervals for // * @param start // * The start time of the requested range // * @param end // * The end time of the requested range // * @param resolution // * The resolution or the minimal time between the requested // * intervals. If interval times are smaller than resolution, only // * the first interval is returned, the others are ignored. // * @param monitor // * A progress monitor for this task // * @return The list of status intervals for this thread, an empty list is // * returned if either the state system is {@code null} or the quark // * is not found // */ // public static List<ITmfStateInterval> getStatusIntervalsForThread(KernelAnalysisModule module, Integer threadId, long start, long end, long resolution, IProgressMonitor monitor) { // ITmfStateSystem ss = module.getStateSystem(); // if (ss == null) { // return Collections.EMPTY_LIST; // } // // try { // int threadQuark = ss.getQuarkAbsolute(Attributes.THREADS, threadId.toString()); // List<ITmfStateInterval> statusIntervals = StateSystemUtils.queryHistoryRange(ss, threadQuark, // Math.max(start, ss.getStartTime()), Math.min(end - 1, ss.getCurrentEndTime()), resolution, null); // return statusIntervals; // } catch (AttributeNotFoundException | StateSystemDisposedException | TimeRangeException e) { // } // return Collections.EMPTY_LIST; // }
epl-1.0
93534c4e56f62b4ff32dca0edaa3c588
42.805405
185
0.611255
3.987697
false
false
false
false
iZettle/wrench
wrench-app/src/main/java/com/izettle/wrench/dialogs/enumvalue/EnumValueFragment.kt
1
2888
package com.izettle.wrench.dialogs.enumvalue import android.app.Dialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.izettle.wrench.R import com.izettle.wrench.database.WrenchPredefinedConfigurationValue import com.izettle.wrench.databinding.FragmentEnumValueBinding import org.koin.androidx.viewmodel.ext.android.viewModel class EnumValueFragment : DialogFragment(), PredefinedValueRecyclerViewAdapter.Listener { private lateinit var binding: FragmentEnumValueBinding private val viewModel: FragmentEnumValueViewModel by viewModel() private lateinit var adapter: PredefinedValueRecyclerViewAdapter override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { assert(arguments != null) binding = FragmentEnumValueBinding.inflate(LayoutInflater.from(context)) val args = EnumValueFragmentArgs.fromBundle(arguments!!) viewModel.init(args.configurationId, args.scopeId) viewModel.configuration.observe(this, Observer { wrenchConfiguration -> if (wrenchConfiguration != null) { requireDialog().setTitle(wrenchConfiguration.key) } }) viewModel.selectedConfigurationValueLiveData.observe(this, Observer { wrenchConfigurationValue -> if (wrenchConfigurationValue != null) { viewModel.selectedConfigurationValue = wrenchConfigurationValue } }) adapter = PredefinedValueRecyclerViewAdapter(this) binding.list.adapter = adapter binding.list.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false) viewModel.predefinedValues.observe(this, Observer { items -> if (items != null) { adapter.submitList(items) } }) return AlertDialog.Builder(activity!!) .setTitle(".") .setView(binding.root) .setNegativeButton(R.string.revert ) { _, _ -> if (viewModel.selectedConfigurationValue != null) { viewModel.deleteConfigurationValue() } dismiss() } .create() } override fun onClick(view: View, item: WrenchPredefinedConfigurationValue) { viewModel.updateConfigurationValue(item.value!!) dismiss() } companion object { fun newInstance(args: EnumValueFragmentArgs): EnumValueFragment { val fragment = EnumValueFragment() fragment.arguments = args.toBundle() return fragment } } }
mit
fe3a916a95fe22aa851133d309d68d5d
35.1
105
0.677978
5.564547
false
true
false
false
chenxyu/android-banner
bannerlibrary/src/main/java/com/chenxyu/bannerlibrary/indicator/CircleView.kt
1
4427
package com.chenxyu.bannerlibrary.indicator import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.util.AttributeSet import android.view.View import androidx.recyclerview.widget.RecyclerView import com.chenxyu.bannerlibrary.extend.dpToPx /** * @Author: ChenXingYu * @CreateDate: 2021/5/16 17:05 * @Description: 环状指示器(平移) * @Version: 1.0 */ internal class CircleView : View { private val mPaint: Paint = Paint() private var mMeasureWidth: Int = 0 private var mMeasureHeight: Int = 0 private var selectedPosition: Int = 0 /** * 方向 */ var orientation: Int = RecyclerView.HORIZONTAL /** * 数量 */ var circleCount: Int = 0 /** * 选中颜色 */ var selectedColor: Int = Color.WHITE /** * 默认颜色 */ var normalColor: Int = Color.parseColor("#88FFFFFF") /** * 圆间隔(DP) */ var spacing: Int = 4 /** * 圆宽(DP) */ var circleWidth: Float = 7F /** * 圆高(DP) */ var circleHeight: Float = 7F init { mPaint.apply { isAntiAlias = true style = Paint.Style.FILL } } constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val widthMode = MeasureSpec.getMode(widthMeasureSpec) val widthSize = MeasureSpec.getSize(widthMeasureSpec) val heightMode = MeasureSpec.getMode(heightMeasureSpec) val heightSize = MeasureSpec.getSize(heightMeasureSpec) mMeasureWidth = 0 mMeasureHeight = 0 if (widthMode == MeasureSpec.EXACTLY) { mMeasureWidth = widthSize } else if (widthMode == MeasureSpec.AT_MOST) { mMeasureWidth = widthSize.coerceAtMost(width) } if (heightMode == MeasureSpec.EXACTLY) { mMeasureHeight = heightSize } else if (heightMode == MeasureSpec.AT_MOST) { mMeasureHeight = heightSize.coerceAtMost(height) } setMeasuredDimension(mMeasureWidth, mMeasureHeight) } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) when (orientation) { RecyclerView.HORIZONTAL -> { // 默认圆 mPaint.color = normalColor repeat(circleCount) { i -> canvas?.drawCircle( circleWidth.times(i).plus(spacing.times(i)).plus( circleWidth.div(2)).dpToPx(context), circleHeight.div(2).dpToPx(context), circleWidth.div(2).dpToPx(context), mPaint) } // 选中圆 mPaint.color = selectedColor canvas?.drawCircle( circleWidth.times(selectedPosition).plus(spacing.times(selectedPosition)).plus( circleWidth.div(2)).dpToPx(context), circleHeight.div(2).dpToPx(context), circleWidth.div(2).dpToPx(context), mPaint) } RecyclerView.VERTICAL -> { // 默认圆 mPaint.color = normalColor repeat(circleCount) { i -> canvas?.drawCircle(circleWidth.div(2).dpToPx(context), circleHeight.times(i).plus(spacing.times(i)).plus( circleHeight.div(2)).dpToPx(context), circleHeight.div(2).dpToPx(context), mPaint) } // 选中圆 mPaint.color = selectedColor canvas?.drawCircle(circleWidth.div(2).dpToPx(context), circleHeight.times(selectedPosition).plus(spacing.times(selectedPosition)).plus( circleHeight.div(2)).dpToPx(context), circleHeight.div(2).dpToPx(context), mPaint) } } } fun scrollTo(position: Int) { if (circleCount > 0 && position >= 0 && position < circleCount) { selectedPosition = position invalidate() } } }
mit
7ca42aed5a6ce71c465b3585b19cc5ab
29.971429
104
0.552249
4.717084
false
false
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/ext/RsDocAndAttributeOwner.kt
1
3728
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi.ext import com.intellij.psi.NavigatablePsiElement import org.rust.lang.core.psi.* interface RsDocAndAttributeOwner : RsElement, NavigatablePsiElement interface RsInnerAttributeOwner : RsDocAndAttributeOwner { /** * Outer attributes are always children of the owning node. * In contrast, inner attributes can be either direct * children or grandchildren. */ val innerAttrList: List<RsInnerAttr> } /** * An element with attached outer attributes and documentation comments. * Such elements should use left edge binder to properly wrap preceding comments. * * Fun fact: in Rust, documentation comments are a syntactic sugar for attribute syntax. * * ``` * /// docs * fn foo() {} * ``` * * is equivalent to * * ``` * #[doc="docs"] * fn foo() {} * ``` */ interface RsOuterAttributeOwner : RsDocAndAttributeOwner { val outerAttrList: List<RsOuterAttr> } /** * Find the first outer attribute with the given identifier. */ fun RsOuterAttributeOwner.findOuterAttr(name: String): RsOuterAttr? = outerAttrList.find { it.metaItem.referenceName == name } /** * Returns [QueryAttributes] for given PSI element. */ val RsDocAndAttributeOwner.queryAttributes: QueryAttributes get() = QueryAttributes(this) /** * Allows for easy querying [RsDocAndAttributeOwner] for specific attributes. * * **Do not instantiate directly**, use [RsDocAndAttributeOwner.queryAttributes] instead. */ class QueryAttributes( private val psi: RsDocAndAttributeOwner ) { private val attributes: Sequence<RsAttr> = Sequence { (psi as? RsInnerAttributeOwner)?.innerAttrList.orEmpty().iterator() } + Sequence { (psi as? RsOuterAttributeOwner)?.outerAttrList.orEmpty().iterator() } val isDocHidden: Boolean get() = hasAttributeWithArg("doc", "hidden") fun hasCfgAttr(): Boolean { if (psi is RsFunction) { val stub = psi.stub if (stub != null) return stub.isCfg } return hasAttribute("cfg") } // `#[attributeName]`, `#[attributeName(arg)]`, `#[attributeName = "Xxx"]` fun hasAttribute(attributeName: String): Boolean { val attrs = attrsByName(attributeName) return attrs.any() } // `#[attributeName]` fun hasAtomAttribute(attributeName: String): Boolean { val attrs = attrsByName(attributeName) return attrs.any { !it.hasEq && it.metaItemArgs == null } } // `#[attributeName(arg)]` fun hasAttributeWithArg(attributeName: String, arg: String): Boolean { val attrs = attrsByName(attributeName) return attrs.any { it.metaItemArgs?.metaItemList?.any { it.referenceName == arg } ?: false } } fun lookupStringValueForKey(key: String): String? = metaItems .filter { it.referenceName == key } .mapNotNull { it.value } .singleOrNull() val langAttribute: String? get() = getStringAttributes("lang").firstOrNull() val deriveAttributes: Sequence<RsMetaItem> get() = attrsByName("derive") // `#[attributeName = "Xxx"]` private fun getStringAttributes(attributeName: String): Sequence<String?> = attrsByName(attributeName).map { it.value } val metaItems: Sequence<RsMetaItem> get() = attributes.mapNotNull { it.metaItem } /** * Get a sequence of all attributes named [name] */ private fun attrsByName(name: String): Sequence<RsMetaItem> = metaItems.filter { it.referenceName == name } override fun toString(): String = "QueryAttributes(${attributes.joinToString { it.text }})" }
mit
6ca935f60c17000cc4c7c2ebbc99c80e
29.557377
129
0.674356
4.179372
false
false
false
false
kpsmith/rss-xbrl
src/main/kotlin/lol/driveways/xbrl/scraper/Edgar.kt
1
1713
package lol.driveways.xbrl.scraper import com.amazonaws.services.lambda.runtime.Context import java.io.InputStream import java.net.HttpURLConnection import java.net.URL import java.util.concurrent.ArrayBlockingQueue import javax.xml.stream.XMLInputFactory import javax.xml.stream.XMLStreamReader class Edgar { fun scrape(context: Context?) { val start = System.currentTimeMillis() val edgarRss = "https://www.sec.gov/Archives/edgar/usgaap.rss.xml" val filingQueue = ArrayBlockingQueue<Filing>(200) val u = Uploader(filingQueue, 10) withHttpConnection(edgarRss, { http -> withInputStream(http, { inputStream -> withReader(inputStream, { reader -> StreamReader(reader, filingQueue).processAll() log.info("Finished reading filings.") }) }) }) u.signalInputClosed(context) println(System.currentTimeMillis() - start) } fun withReader(input: InputStream, block: (XMLStreamReader) -> Unit) { block(XMLInputFactory.newInstance().createXMLStreamReader(input)) } fun withInputStream(connection: HttpURLConnection, block: (InputStream) -> Unit) { var input: InputStream? = null try { input = connection.inputStream block(input) } finally { input?.close() } } fun withHttpConnection(url: kotlin.String, block: (HttpURLConnection) -> Unit) { var con: HttpURLConnection? = null try { con = URL(url).openConnection() as HttpURLConnection block(con) } finally { con?.disconnect() } } }
mit
5b94decb957b5c8b0d191d3f1d2e3580
30.740741
86
0.623468
4.519789
false
false
false
false
Commit451/LabCoat
app/src/main/java/com/commit451/gitlab/viewHolder/AccountViewHolder.kt
2
1917
package com.commit451.gitlab.viewHolder import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.PopupMenu import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import coil.api.load import coil.transform.CircleCropTransformation import com.commit451.addendum.recyclerview.bindView import com.commit451.gitlab.R import com.commit451.gitlab.model.Account import com.commit451.gitlab.util.ImageUtil /** * A signed in account */ class AccountViewHolder(view: View) : RecyclerView.ViewHolder(view) { companion object { fun inflate(parent: ViewGroup): AccountViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_account, parent, false) return AccountViewHolder(view) } } private val image: ImageView by bindView(R.id.account_image) private val textUsername: TextView by bindView(R.id.account_username) private val textServer: TextView by bindView(R.id.account_server) private val buttonMore: View by bindView(R.id.account_more) val popupMenu: PopupMenu init { popupMenu = PopupMenu(itemView.context, buttonMore) popupMenu.menuInflater.inflate(R.menu.logout, popupMenu.menu) buttonMore.setOnClickListener { popupMenu.show() } } fun bind(account: Account, isActive: Boolean, colorSelected: Int) { textServer.text = account.serverUrl.toString() textUsername.text = account.email if (isActive) { itemView.setBackgroundColor(colorSelected) } else { itemView.background = null } image.load(ImageUtil.getAvatarUrl(account.email, itemView.resources.getDimensionPixelSize(R.dimen.user_list_image_size))) { transformations(CircleCropTransformation()) } } }
apache-2.0
984cb12a5fb450636b5bf78ef86b2644
31.491525
131
0.719353
4.447796
false
false
false
false
chrisbanes/tivi
ui/followed/src/main/java/app/tivi/home/followed/FollowedViewState.kt
1
1323
/* * 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 * * 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 app.tivi.home.followed import app.tivi.api.UiMessage import app.tivi.data.entities.SortOption import app.tivi.data.entities.TraktUser import app.tivi.trakt.TraktAuthState internal data class FollowedViewState( val user: TraktUser? = null, val authState: TraktAuthState = TraktAuthState.LOGGED_OUT, val isLoading: Boolean = false, val selectionOpen: Boolean = false, val selectedShowIds: Set<Long> = emptySet(), val filterActive: Boolean = false, val filter: String? = null, val availableSorts: List<SortOption> = emptyList(), val sort: SortOption = SortOption.SUPER_SORT, val message: UiMessage? = null ) { companion object { val Empty = FollowedViewState() } }
apache-2.0
2bb47243835e6bc5fe0de77274e7a414
32.923077
75
0.727891
4.009091
false
false
false
false
chrisbanes/tivi
data/src/main/java/app/tivi/data/daos/RelatedShowsDao.kt
1
1926
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.data.daos import androidx.room.Dao import androidx.room.Query import androidx.room.Transaction import app.tivi.data.entities.RelatedShowEntry import app.tivi.data.resultentities.RelatedShowEntryWithShow import kotlinx.coroutines.flow.Flow @Dao abstract class RelatedShowsDao : PairEntryDao<RelatedShowEntry, RelatedShowEntryWithShow>() { @Transaction @Query("SELECT * FROM related_shows WHERE show_id = :showId ORDER BY order_index") abstract override fun entries(showId: Long): List<RelatedShowEntry> @Transaction @Query("SELECT * FROM related_shows WHERE show_id = :showId ORDER BY order_index") abstract fun entriesObservable(showId: Long): Flow<List<RelatedShowEntry>> @Transaction @Query("SELECT * FROM related_shows WHERE show_id = :showId ORDER BY order_index") abstract override fun entriesWithShows(showId: Long): List<RelatedShowEntryWithShow> @Transaction @Query("SELECT * FROM related_shows WHERE show_id = :showId ORDER BY order_index") abstract override fun entriesWithShowsObservable(showId: Long): Flow<List<RelatedShowEntryWithShow>> @Query("DELETE FROM related_shows WHERE show_id = :showId") abstract override suspend fun deleteWithShowId(showId: Long) @Query("DELETE FROM related_shows") abstract suspend fun deleteAll() }
apache-2.0
5cf000ef2471fd5f5fc71b2818dcf156
38.306122
104
0.757529
4.223684
false
false
false
false
square/curtains
curtains/src/main/java/curtains/internal/NextDrawListener.kt
1
2338
package curtains.internal import android.os.Build import android.view.View import android.view.View.OnAttachStateChangeListener import android.view.ViewTreeObserver.OnDrawListener import androidx.annotation.RequiresApi /** * A utility class to listen to the next ondraw call on a view hierarchy, working around AOSP bugs. */ @RequiresApi(16) internal class NextDrawListener( private val view: View, private val onDrawCallback: () -> Unit ) : OnDrawListener, OnAttachStateChangeListener { private var invoked = false override fun onDraw() { if (invoked) return invoked = true view.removeOnAttachStateChangeListener(this) // ViewTreeObserver.removeOnDrawListener() throws if called from the onDraw() callback mainHandler.post { view.viewTreeObserver.let { viewTreeObserver -> if (viewTreeObserver.isAlive) { viewTreeObserver.removeOnDrawListener(this) } } } onDrawCallback() } fun safelyRegisterForNextDraw() { // Prior to API 26, OnDrawListener wasn't merged back from the floating ViewTreeObserver into // the real ViewTreeObserver. // https://android.googlesource.com/platform/frameworks/base/+/9f8ec54244a5e0343b9748db3329733f259604f3 if (Build.VERSION.SDK_INT >= 26 || (view.viewTreeObserver.isAlive && view.isAttachedToWindowCompat)) { view.viewTreeObserver.addOnDrawListener(this) } else { view.addOnAttachStateChangeListener(this) } } override fun onViewAttachedToWindow(view: View) { view.viewTreeObserver.addOnDrawListener(this) // Backed by CopyOnWriteArrayList, ok to self remove from onViewDetachedFromWindow() view.removeOnAttachStateChangeListener(this) } override fun onViewDetachedFromWindow(view: View) { view.viewTreeObserver.removeOnDrawListener(this) // Backed by CopyOnWriteArrayList, ok to self remove from onViewDetachedFromWindow() view.removeOnAttachStateChangeListener(this) } companion object { fun View.onNextDraw(onDrawCallback: () -> Unit) { val nextDrawListener = NextDrawListener(this, onDrawCallback) nextDrawListener.safelyRegisterForNextDraw() } } } private val View.isAttachedToWindowCompat: Boolean get() { if (Build.VERSION.SDK_INT >= 19) { return isAttachedToWindow } return windowToken != null }
apache-2.0
eb045e0cb27f5bbc46073c772ee8da92
31.943662
107
0.742515
4.694779
false
false
false
false
stoman/CompetitiveProgramming
problems/2020adventofcode16b/submissions/accepted/Stefan.kt
2
1563
import java.math.BigInteger import java.util.* fun main() { val s = Scanner(System.`in`).useDelimiter("""\s\syour ticket:\s|\s\snearby tickets:\s""") // Read ranges. val sRanges = Scanner(s.next()).useDelimiter(""":\s|\sor\s|-|\n""") val ranges = mutableMapOf<String, Set<IntRange>>() while (sRanges.hasNext()) { val name = sRanges.next() ranges[name] = setOf(sRanges.nextInt()..sRanges.nextInt(), sRanges.nextInt()..sRanges.nextInt()) } // Read tickets val myTicket: List<Int> = s.next().split(",").map { it.toInt() } val sTickets = Scanner(s.next()) val tickets = mutableListOf<List<Int>>() while (sTickets.hasNext()) { tickets.add(sTickets.next().split(",").map { it.toInt() }) } // Determine meaning of fields. val validTickets = tickets.filter { ticket -> ticket.none { i -> ranges.values.flatten().none { i in it } } } var possible = mutableMapOf<Int, Set<String>>() for (i in myTicket.indices) { possible[i] = ranges.filter { entry -> validTickets.map { it[i] }.all { nr -> entry.value.any { nr in it } } }.map { it.key } .toSet() } val mapping = mutableMapOf<String, Int>() while (true) { val next: Int = possible.keys.firstOrNull { possible[it]!!.size == 1 } ?: break val name: String = possible[next]!!.first() mapping[name] = next possible = possible.mapValues { it.value.filter { n -> n != name }.toSet() }.toMutableMap() } println(mapping.filterKeys { it.startsWith("departure") }.map { myTicket[it.value].toBigInteger() } .reduce(BigInteger::times)) }
mit
699042a5b4c48e8b856a2e502c84983e
37.121951
117
0.632758
3.52027
false
false
false
false
Waverunner/HarvesterDroid
tracker-gh/src/main/kotlin/com/lewisjmorgan/harvesterdroid/galaxyharvester/GalaxyHarvesterGalaxyList.kt
1
911
package com.lewisjmorgan.harvesterdroid.galaxyharvester import com.lewisjmorgan.harvesterdroid.api.Galaxy import com.lewisjmorgan.harvesterdroid.api.GalaxyList @Suppress("MemberVisibilityCanBePrivate", "PropertyName") class GalaxyHarvesterGalaxyList: GalaxyList { val galaxy_values: MutableList<String> = mutableListOf() val galaxy_names: MutableList<String> = mutableListOf() val galaxy_prop1: MutableList<String> = mutableListOf() override fun getGalaxies(): List<Galaxy> { // Construct the galaxies val galaxyList = mutableListOf<Galaxy>() if (galaxy_values.size == galaxy_names.size && galaxy_names.size == galaxy_prop1.size) { galaxy_values.forEachIndexed { index, id -> // Only want the active galaxies if (galaxy_prop1[index] == "Active") { galaxyList.add(Galaxy(id, galaxy_names[index])) } } } return galaxyList.toList() } }
gpl-3.0
d07c74e7212dba4e8f7e6d11b6f60307
35.48
92
0.715697
3.943723
false
false
false
false
Nandi/http
src/main/kotlin/com/headlessideas/http/Request.kt
1
1612
package com.headlessideas.http import java.io.BufferedReader import java.net.InetSocketAddress class Request(val httpVersion: String, val method: Method = Method.GET, val path: String, val headers: List<Header>, val body: String? = null, var clientAddress: InetSocketAddress? = null) { override fun toString(): String { return "${clientAddress?.address} $httpVersion $method $path" } companion object { fun fromStream(input: BufferedReader): Request { val requestLine = input.readLine() val (method, path, httpVersion) = requestLine.split(" ") val headers = mutableListOf<Header>() var body: String? = null var s = input.readLine() while (s != null && s.isNotEmpty()) { val (name, value) = s.split(": ", limit = 2) headers.add(Header(name, value)) s = input.readLine() } //if there is a content length header, we need to read the body from the input val contentLength = headers.find { it.name.equals("content-length", true) } if (contentLength != null) { val charArray = CharArray(contentLength.value.toInt()) input.read(charArray) body = charArray.toString() } return Request(httpVersion, Method.get(method), checkPath(path), headers, body) } private fun checkPath(path: String): String = path.takeUnless { it == "/" } ?: path + "index.html" } }
mit
ff300592f4a61e6c93c3e941a2074eca
35.659091
106
0.565136
4.699708
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/repository/PlayRepository.kt
1
22530
package com.boardgamegeek.repository import android.app.PendingIntent import android.content.ContentProviderOperation import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Build import androidx.annotation.StringRes import androidx.core.content.contentValuesOf import com.boardgamegeek.BggApplication import com.boardgamegeek.R import com.boardgamegeek.db.CollectionDao import com.boardgamegeek.db.GameDao import com.boardgamegeek.db.PlayDao import com.boardgamegeek.entities.* import com.boardgamegeek.extensions.* import com.boardgamegeek.io.Adapter import com.boardgamegeek.mappers.mapToEntity import com.boardgamegeek.pref.SyncPrefs import com.boardgamegeek.pref.SyncPrefs.Companion.TIMESTAMP_PLAYS_NEWEST_DATE import com.boardgamegeek.pref.SyncPrefs.Companion.TIMESTAMP_PLAYS_OLDEST_DATE import com.boardgamegeek.pref.clearPlaysTimestamps import com.boardgamegeek.provider.BggContract.* import com.boardgamegeek.provider.BggContract.Companion.INVALID_ID import com.boardgamegeek.service.SyncService import com.boardgamegeek.ui.PlayStatsActivity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import timber.log.Timber import kotlin.math.min class PlayRepository(val application: BggApplication) { private val playDao = PlayDao(application) private val gameDao = GameDao(application) private val collectionDao = CollectionDao(application) private val prefs: SharedPreferences by lazy { application.preferences() } private val syncPrefs: SharedPreferences by lazy { SyncPrefs.getPrefs(application.applicationContext) } private val username: String? by lazy { prefs[AccountPreferences.KEY_USERNAME, ""] } private val bggService = Adapter.createForXml() enum class SortBy(val daoSortBy: PlayDao.PlaysSortBy) { DATE(PlayDao.PlaysSortBy.DATE), LOCATION(PlayDao.PlaysSortBy.LOCATION), GAME(PlayDao.PlaysSortBy.GAME), LENGTH(PlayDao.PlaysSortBy.LENGTH), } suspend fun loadPlay(internalId: Long): PlayEntity? = playDao.loadPlay(internalId) suspend fun refreshPlay( internalId: Long, playId: Int, gameId: Int, timestamp: Long = System.currentTimeMillis() ): PlayEntity? = withContext(Dispatchers.IO) { var page = 1 if (username.isNullOrBlank() || internalId == INVALID_ID.toLong() || playId == INVALID_ID || gameId == INVALID_ID ) { null } else { var returnedPlay: PlayEntity? = null do { val result = bggService.playsByGame(username, gameId, page++) val plays = result.plays.mapToEntity(timestamp) saveFromSync(plays, timestamp) Timber.i("Synced plays for game ID %s (page %,d)", gameId, page) if (returnedPlay == null) returnedPlay = plays.find { it.playId == playId } } while (result.hasMorePages() && returnedPlay == null) returnedPlay } } suspend fun getPlays(sortBy: SortBy = SortBy.DATE) = playDao.loadPlays(sortBy.daoSortBy) suspend fun getPendingPlays() = playDao.loadPendingPlays() suspend fun getDraftPlays() = playDao.loadDraftPlays() suspend fun getUpdatingPlays() = playDao.loadPlays(selection = playDao.createPendingUpdatePlaySelectionAndArgs(), includePlayers = true) suspend fun getDeletingPlays() = playDao.loadPlays(selection = playDao.createPendingDeletePlaySelectionAndArgs(), includePlayers = true) suspend fun loadPlaysByGame(gameId: Int) = playDao.loadPlaysByGame(gameId, PlayDao.PlaysSortBy.DATE) suspend fun loadPlaysByLocation(location: String) = playDao.loadPlaysByLocation(location) suspend fun loadPlaysByUsername(username: String) = playDao.loadPlaysByUsername(username) suspend fun loadPlaysByPlayerName(playerName: String) = playDao.loadPlaysByPlayerName(playerName) suspend fun loadPlaysByPlayer(name: String, gameId: Int, isUser: Boolean) = playDao.loadPlaysByPlayerAndGame(name, gameId, isUser) suspend fun refreshPlays() = withContext(Dispatchers.IO) { val syncInitiatedTimestamp = System.currentTimeMillis() val newestTimestamp = syncPrefs[TIMESTAMP_PLAYS_NEWEST_DATE] ?: 0L val minDate = if (newestTimestamp == 0L) null else newestTimestamp.asDateForApi() var page = 1 do { val response = bggService.plays(username, minDate, null, page++) val plays = response.plays.mapToEntity(syncInitiatedTimestamp) saveFromSync(plays, syncInitiatedTimestamp) plays.maxOfOrNull { it.dateInMillis }?.let { if (it > syncPrefs[TIMESTAMP_PLAYS_NEWEST_DATE] ?: 0L) { syncPrefs[TIMESTAMP_PLAYS_NEWEST_DATE] = it } } plays.minOfOrNull { it.dateInMillis }?.let { if (it < syncPrefs[TIMESTAMP_PLAYS_OLDEST_DATE] ?: Long.MAX_VALUE) { syncPrefs[TIMESTAMP_PLAYS_OLDEST_DATE] = it } } if (minDate == null) { Timber.i("Synced page %,d of the newest plays (%,d plays in this page)", page - 1, plays.size) } else { Timber.i("Synced page %,d of plays from %s or later (%,d plays in this page)", page - 1, minDate, plays.size) } } while (response.hasMorePages()) if (minDate != null) { deleteUnupdatedPlaysSince(syncInitiatedTimestamp, newestTimestamp) } val oldestTimestamp = syncPrefs[TIMESTAMP_PLAYS_OLDEST_DATE] ?: Long.MAX_VALUE if (oldestTimestamp > 0) { page = 1 val maxDate = if (oldestTimestamp == Long.MAX_VALUE) null else oldestTimestamp.asDateForApi() do { val response = bggService.plays(username, null, maxDate, page++) val plays = response.plays.mapToEntity(syncInitiatedTimestamp) saveFromSync(plays, syncInitiatedTimestamp) plays.minOfOrNull { it.dateInMillis }?.let { if (it < syncPrefs[TIMESTAMP_PLAYS_OLDEST_DATE] ?: Long.MAX_VALUE) { syncPrefs[TIMESTAMP_PLAYS_OLDEST_DATE] = it } } if (maxDate == null) { Timber.i("Synced page %,d of the oldest plays (%,d plays in this page)", page - 1, plays.size) } else { Timber.i("Synced page %,d of plays from %s or earlier (%,d plays in this page)", page - 1, maxDate, plays.size) } } while (response.hasMorePages()) if (oldestTimestamp != Long.MAX_VALUE) { deleteUnupdatedPlaysBefore(syncInitiatedTimestamp, oldestTimestamp) } syncPrefs[TIMESTAMP_PLAYS_OLDEST_DATE] = 0L } else { Timber.i("Not syncing old plays; already caught up.") } calculatePlayStats() } suspend fun deleteUnupdatedPlaysSince(syncTimestamp: Long, playDate: Long): Int { return playDao.deleteUnupdatedPlaysByDate(syncTimestamp, playDate, ">=") } suspend fun deleteUnupdatedPlaysBefore(syncTimestamp: Long, playDate: Long): Int { return playDao.deleteUnupdatedPlaysByDate(syncTimestamp, playDate, "<=") } suspend fun refreshPlays(timeInMillis: Long) = withContext(Dispatchers.IO) { if (timeInMillis <= 0L && !username.isNullOrBlank()) { emptyList() } else { val plays = mutableListOf<PlayEntity>() val timestamp = System.currentTimeMillis() val date = timeInMillis.asDateForApi() var page = 1 do { val response = bggService.playsByDate(username, date, date, page++) val playsPage = response.plays.mapToEntity(timestamp) saveFromSync(playsPage, timestamp) plays += playsPage Timber.i("Synced plays for %s (page %,d)", timeInMillis.asDateForApi(), page) } while (response.hasMorePages()) calculatePlayStats() plays } } suspend fun loadForStats( includeIncompletePlays: Boolean, includeExpansions: Boolean, includeAccessories: Boolean ): List<GameForPlayStatEntity> { // TODO use PlayDao if either of these is false // val isOwnedSynced = PreferencesUtils.isStatusSetToSync(application, BggService.COLLECTION_QUERY_STATUS_OWN) // val isPlayedSynced = PreferencesUtils.isStatusSetToSync(application, BggService.COLLECTION_QUERY_STATUS_PLAYED) val playInfo = gameDao.loadPlayInfo(includeIncompletePlays, includeExpansions, includeAccessories) return filterGamesOwned(playInfo) } private suspend fun filterGamesOwned(playInfo: List<GameForPlayStatEntity>): List<GameForPlayStatEntity> = withContext(Dispatchers.Default) { val items = collectionDao.load() val games = mutableListOf<GameForPlayStatEntity>() playInfo.forEach { game -> games += game.copy(isOwned = items.any { item -> item.gameId == game.id && item.own }) } games.toList() } suspend fun loadPlayers(sortBy: PlayDao.PlayerSortBy = PlayDao.PlayerSortBy.NAME): List<PlayerEntity> { return playDao.loadPlayers(Plays.buildPlayersByUniquePlayerUri(), sortBy = sortBy) } suspend fun loadPlayersByGame(gameId: Int): List<PlayPlayerEntity> { return playDao.loadPlayersByGame(gameId) } suspend fun loadPlayersForStats(includeIncompletePlays: Boolean): List<PlayerEntity> { return playDao.loadPlayersForStats(includeIncompletePlays) } suspend fun loadUserPlayer(username: String): PlayerEntity? { return playDao.loadUserPlayer(username) } suspend fun loadNonUserPlayer(playerName: String): PlayerEntity? { return playDao.loadNonUserPlayer(playerName) } suspend fun loadUserColors(username: String): List<PlayerColorEntity> { return playDao.loadColors(PlayerColors.buildUserUri(username)) } suspend fun loadPlayerColors(playerName: String): List<PlayerColorEntity> { return playDao.loadColors(PlayerColors.buildPlayerUri(playerName)) } suspend fun savePlayerColors(playerName: String, colors: List<String>?) { playDao.saveColorsForPlayer(PlayerColors.buildPlayerUri(playerName), colors) } suspend fun saveUserColors(username: String, colors: List<String>?) { playDao.saveColorsForPlayer(PlayerColors.buildUserUri(username), colors) } suspend fun loadUserPlayerDetail(username: String): List<PlayerDetailEntity> { return playDao.loadPlayerDetail( Plays.buildPlayerUri(), "${PlayPlayers.Columns.USER_NAME}=?", arrayOf(username) ) } suspend fun loadNonUserPlayerDetail(playerName: String): List<PlayerDetailEntity> { return playDao.loadPlayerDetail( Plays.buildPlayerUri(), "${PlayPlayers.Columns.USER_NAME.whereEqualsOrNull()} AND play_players.${PlayPlayers.Columns.NAME}=?", arrayOf("", playerName) ) } suspend fun loadLocations(sortBy: PlayDao.LocationSortBy = PlayDao.LocationSortBy.NAME): List<LocationEntity> { return playDao.loadLocations(sortBy) } suspend fun logQuickPlay(gameId: Int, gameName: String) { val playEntity = PlayEntity( gameId = gameId, gameName = gameName, rawDate = PlayEntity.currentDate(), updateTimestamp = System.currentTimeMillis() ) playDao.upsert(playEntity) SyncService.sync(application, SyncService.FLAG_SYNC_PLAYS_UPLOAD) } suspend fun saveFromSync(plays: List<PlayEntity>, startTime: Long) { var updateCount = 0 var insertCount = 0 var unchangedCount = 0 var dirtyCount = 0 var errorCount = 0 plays.forEach { play -> when (playDao.save(play, startTime)) { PlayDao.SaveStatus.UPDATED -> updateCount++ PlayDao.SaveStatus.INSERTED -> insertCount++ PlayDao.SaveStatus.DIRTY -> dirtyCount++ PlayDao.SaveStatus.ERROR -> errorCount++ PlayDao.SaveStatus.UNCHANGED -> unchangedCount++ } } Timber.i( "Updated %1$,d, inserted %2$,d, %3$,d unchanged, %4$,d dirty, %5$,d", updateCount, insertCount, unchangedCount, dirtyCount, errorCount ) } suspend fun delete(internalId: Long): Boolean { return playDao.delete(internalId) } suspend fun markAsSynced(internalId: Long, playId: Int) { playDao.update( internalId, contentValuesOf( Plays.Columns.PLAY_ID to playId, Plays.Columns.DIRTY_TIMESTAMP to 0, Plays.Columns.UPDATE_TIMESTAMP to 0, Plays.Columns.DELETE_TIMESTAMP to 0, ) ) } suspend fun markAsDiscarded(internalId: Long) { playDao.update( internalId, contentValuesOf( Plays.Columns.DELETE_TIMESTAMP to 0, Plays.Columns.UPDATE_TIMESTAMP to 0, Plays.Columns.DIRTY_TIMESTAMP to 0, ) ) } suspend fun markAsUpdated(internalId: Long) { playDao.update( internalId, contentValuesOf( Plays.Columns.UPDATE_TIMESTAMP to System.currentTimeMillis(), Plays.Columns.DELETE_TIMESTAMP to 0, Plays.Columns.DIRTY_TIMESTAMP to 0, ) ) } suspend fun markAsDeleted(internalId: Long) { playDao.update( internalId, contentValuesOf( Plays.Columns.DELETE_TIMESTAMP to System.currentTimeMillis(), Plays.Columns.UPDATE_TIMESTAMP to 0, Plays.Columns.DIRTY_TIMESTAMP to 0, ) ) } suspend fun updateGamePlayCount(gameId: Int) = withContext(Dispatchers.Default) { val allPlays = playDao.loadPlaysByGame(gameId) val playCount = allPlays .filter { it.deleteTimestamp == 0L } .sumOf { it.quantity } gameDao.update(gameId, contentValuesOf(Games.Columns.NUM_PLAYS to playCount)) } suspend fun loadPlayersByLocation(location: String = ""): List<PlayerEntity> = withContext(Dispatchers.IO) { playDao.loadPlayersByLocation(location) } suspend fun updatePlaysWithNickName(username: String, nickName: String): Int = withContext(Dispatchers.IO) { val count = playDao.countNickNameUpdatePlays(username, nickName) val batch = arrayListOf<ContentProviderOperation>() batch += playDao.createDirtyPlaysForUserAndNickNameOperations(username, nickName) batch += playDao.createNickNameUpdateOperation(username, nickName) application.contentResolver.applyBatch(batch) // is this better for DAO? count } suspend fun renamePlayer(oldName: String, newName: String) = withContext(Dispatchers.IO) { val batch = arrayListOf<ContentProviderOperation>() batch += playDao.createDirtyPlaysForNonUserPlayerOperations(oldName) batch += playDao.createRenameUpdateOperation(oldName, newName) batch += playDao.createCopyPlayerColorsOperations(oldName, newName) batch += playDao.createDeletePlayerColorsOperation(oldName) application.contentResolver.applyBatch(batch)// is this better for DAO? } data class RenameLocationResults(val oldLocationName: String, val newLocationName: String, val count: Int) suspend fun renameLocation( oldLocationName: String, newLocationName: String, ): RenameLocationResults = withContext(Dispatchers.IO) { val batch = arrayListOf<ContentProviderOperation>() val values = contentValuesOf(Plays.Columns.LOCATION to newLocationName) batch.add( ContentProviderOperation .newUpdate(Plays.CONTENT_URI) .withValues(values) .withSelection( "${Plays.Columns.LOCATION}=? AND (${Plays.Columns.UPDATE_TIMESTAMP.greaterThanZero()} OR ${Plays.Columns.DIRTY_TIMESTAMP.greaterThanZero()})", arrayOf(oldLocationName) ).build() ) values.put(Plays.Columns.UPDATE_TIMESTAMP, System.currentTimeMillis()) batch.add( ContentProviderOperation .newUpdate(Plays.CONTENT_URI) .withValues(values) .withSelection( "${Plays.Columns.LOCATION}=? AND ${Plays.Columns.UPDATE_TIMESTAMP.whereZeroOrNull()} AND ${Plays.Columns.DELETE_TIMESTAMP.whereZeroOrNull()} AND ${Plays.Columns.DIRTY_TIMESTAMP.whereZeroOrNull()}", arrayOf(oldLocationName) ).build() ) val results = application.contentResolver.applyBatch(batch) RenameLocationResults(oldLocationName, newLocationName, results.sumOf { it.count ?: 0 }) } suspend fun addUsernameToPlayer(playerName: String, username: String) = withContext(Dispatchers.IO) { // TODO verify username exists on BGG val batch = arrayListOf<ContentProviderOperation>() batch += playDao.createDirtyPlaysForNonUserPlayerOperations(playerName) batch += playDao.createAddUsernameOperation(playerName, username) batch += playDao.createCopyPlayerColorsToUserOperations(playerName, username) batch += playDao.createDeletePlayerColorsOperation(playerName) application.contentResolver.applyBatch(batch) } suspend fun save(play: PlayEntity, internalId: Long = play.internalId): Long { val id = playDao.upsert(play, internalId) // if the play is "current" (for today and about to be synced), remember the location and players to be used in the next play val isUpdating = play.updateTimestamp > 0 val endTime = play.dateInMillis + min(60 * 24, play.length) * 60 * 1000 val isToday = play.dateInMillis.isToday() || endTime.isToday() if (!play.isSynced && isUpdating && isToday) { prefs.putLastPlayTime(System.currentTimeMillis()) prefs.putLastPlayLocation(play.location) prefs.putLastPlayPlayerEntities(play.players) } return id } suspend fun resetPlays() { // resets the sync timestamps, removes the plays' hashcode, and request a sync syncPrefs.clearPlaysTimestamps() val count = playDao.updateAllPlays(contentValuesOf(Plays.Columns.SYNC_HASH_CODE to 0)) Timber.i("Cleared the hashcode from %,d plays.", count) SyncService.sync(application, SyncService.FLAG_SYNC_PLAYS) } suspend fun deletePlays() { syncPrefs.clearPlaysTimestamps() playDao.deletePlays() gameDao.resetPlaySync() } suspend fun calculatePlayStats() = withContext(Dispatchers.Default) { if (syncPrefs[TIMESTAMP_PLAYS_OLDEST_DATE, Long.MAX_VALUE] ?: Long.MAX_VALUE == 0L) { val includeIncompletePlays = prefs[PlayStats.LOG_PLAY_STATS_INCOMPLETE, false] ?: false val includeExpansions = prefs[PlayStats.LOG_PLAY_STATS_EXPANSIONS, false] ?: false val includeAccessories = prefs[PlayStats.LOG_PLAY_STATS_ACCESSORIES, false] ?: false val playStats = loadForStats(includeIncompletePlays, includeExpansions, includeAccessories) val playStatsEntity = PlayStatsEntity(playStats, prefs.isStatusSetToSync(COLLECTION_STATUS_OWN)) updateGameHIndex(playStatsEntity.hIndex) val playerStats = loadPlayersForStats(includeIncompletePlays) val playerStatsEntity = PlayerStatsEntity(playerStats) updatePlayerHIndex(playerStatsEntity.hIndex) } } fun updateGameHIndex(hIndex: HIndexEntity) { updateHIndex( application, hIndex, PlayStats.KEY_GAME_H_INDEX, R.string.game, NOTIFICATION_ID_PLAY_STATS_GAME_H_INDEX ) } fun updatePlayerHIndex(hIndex: HIndexEntity) { updateHIndex( application, hIndex, PlayStats.KEY_PLAYER_H_INDEX, R.string.player, NOTIFICATION_ID_PLAY_STATS_PLAYER_H_INDEX ) } private fun updateHIndex( context: Context, hIndex: HIndexEntity, key: String, @StringRes typeResId: Int, notificationId: Int ) { if (hIndex.h != HIndexEntity.INVALID_H_INDEX) { val old = HIndexEntity(prefs[key, 0] ?: 0, prefs[key + PlayStats.KEY_H_INDEX_N_SUFFIX, 0] ?: 0) if (old != hIndex) { prefs[key] = hIndex.h prefs[key + PlayStats.KEY_H_INDEX_N_SUFFIX] = hIndex.n @StringRes val messageId = if (hIndex.h > old.h || hIndex.h == old.h && hIndex.n < old.n) R.string.sync_notification_h_index_increase else R.string.sync_notification_h_index_decrease context.notify( context.createNotificationBuilder( R.string.title_play_stats, NotificationChannels.STATS, PlayStatsActivity::class.java ) .setContentText(context.getText(messageId, context.getString(typeResId), hIndex.description)) .setContentIntent( PendingIntent.getActivity( context, 0, Intent(context, PlayStatsActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0, ) ), NotificationTags.PLAY_STATS, notificationId ) } } } companion object { private const val NOTIFICATION_ID_PLAY_STATS_GAME_H_INDEX = 0 private const val NOTIFICATION_ID_PLAY_STATS_PLAYER_H_INDEX = 1 } }
gpl-3.0
02a051ca0016b2e903f6c441b44d89a6
41.270169
217
0.640257
4.601716
false
false
false
false
mediathekview/MediathekView
src/main/kotlin/feed/FeedMessage.kt
1
397
package feed /* * A RSS message */ data class FeedMessage( val title: String, val description: String, val link: String, val author: String, val guid: String ) { override fun toString(): String { return ("FeedMessage [title=" + title + ", description=" + description + ", link=" + link + ", author=" + author + ", guid=" + guid + "]") } }
gpl-3.0
cde4ccff5e1f1d327ec6acd36204811e
25.533333
85
0.551637
4.135417
false
false
false
false
Mauin/detekt
detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/FormattingRule.kt
1
2984
package io.gitlab.arturbosch.detekt.formatting import com.github.shyiko.ktlint.core.EditorConfig import com.github.shyiko.ktlint.core.KtLint import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Location import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.api.SingleAssign import io.gitlab.arturbosch.detekt.api.SourceLocation import io.gitlab.arturbosch.detekt.api.TextLocation import org.jetbrains.kotlin.com.intellij.lang.ASTNode import org.jetbrains.kotlin.com.intellij.lang.FileASTNode import org.jetbrains.kotlin.com.intellij.psi.PsiElement import org.jetbrains.kotlin.com.intellij.testFramework.LightVirtualFile import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.psiUtil.endOffset /** * Rule to detect formatting violations. * * @author Artur Bosch */ abstract class FormattingRule(config: Config) : Rule(config) { abstract val wrapping: com.github.shyiko.ktlint.core.Rule protected fun issueFor(description: String) = Issue(javaClass.simpleName, Severity.Style, description, Debt.FIVE_MINS) protected val isAndroid get() = config.valueOrDefault("android", false) private var positionByOffset: (offset: Int) -> Pair<Int, Int> by SingleAssign() private var root: KtFile by SingleAssign() override fun visit(root: KtFile) { this.root = root root.node.putUserData(KtLint.ANDROID_USER_DATA_KEY, isAndroid) positionByOffset = calculateLineColByOffset(root.text).let { val offsetDueToLineBreakNormalization = calculateLineBreakOffset(root.text) return@let { offset: Int -> it(offset + offsetDueToLineBreakNormalization(offset)) } } editorConfigUpdater()?.let { updateFunc -> val oldEditorConfig = root.node.getUserData(KtLint.EDITOR_CONFIG_USER_DATA_KEY) root.node.putUserData(KtLint.EDITOR_CONFIG_USER_DATA_KEY, updateFunc(oldEditorConfig)) } } open fun editorConfigUpdater(): ((oldEditorConfig: EditorConfig?) -> EditorConfig)? = null fun apply(node: ASTNode) { if (ruleShouldOnlyRunOnFileNode(node)) { return } wrapping.visit(node, autoCorrect) { _, message, _ -> val (line, column) = positionByOffset(node.startOffset) report(CodeSmell(issue, Entity(node.toString(), "", "", Location(SourceLocation(line, column), TextLocation(node.startOffset, node.psi.endOffset), "($line, $column)", root.originalFilePath() ?: root.containingFile.name)), message)) } } private fun ruleShouldOnlyRunOnFileNode(node: ASTNode) = wrapping is com.github.shyiko.ktlint.core.Rule.Modifier.RestrictToRoot && node !is FileASTNode private fun PsiElement.originalFilePath() = (this.containingFile.viewProvider.virtualFile as? LightVirtualFile)?.originalFile?.name }
apache-2.0
caf7c3bf1b67e642e8c1fd226fb7c4c6
37.25641
91
0.773123
3.74404
false
true
false
false
Mithrandir21/Duopoints
app/src/main/java/com/duopoints/android/ui/lists/UserLevelEventAdapter.kt
1
2386
package com.duopoints.android.ui.lists import android.view.View import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.load.engine.DiskCacheStrategy import com.duopoints.android.MainAct import com.duopoints.android.R import com.duopoints.android.fragments.userprofile.UserProfileFrag import com.duopoints.android.logistics.cloudstorage.GlideApp import com.duopoints.android.logistics.cloudstorage.Storage import com.duopoints.android.rest.models.composites.CompositeUserLevel import com.duopoints.android.ui.lists.base.BaseAdapterDelegate import com.duopoints.android.ui.lists.base.BaseViewHolder import com.duopoints.android.ui.views.LikeButton import de.hdodenhof.circleimageview.CircleImageView class UserLevelEventAdapter(private val eventClicks: LevelUpClicks) : BaseAdapterDelegate<CompositeUserLevel, UserLevelEventAdapter.LevelUpHolder>(CompositeUserLevel::class.java, R.layout.list_user_level_up_item) { override fun bindViewHolder(item: CompositeUserLevel, holder: LevelUpHolder) { GlideApp.with(holder.itemView) .load(Storage.getAvatarRef(item.userImageUUID())) .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true) .error(R.drawable.user_female) .into(holder.userLevelUpUserImage) holder.userLevelUpUserImage.setOnClickListener { v -> (v.context as MainAct).addFragment(UserProfileFrag.newInstance(item.user), true) } holder.userLevelUpTitle.text = "Reached Level " + item.userLevelNumber GlideApp.with(holder.itemView).load(R.drawable.level_up).into(holder.userLevelUpImage) } override fun createViewHolder(view: View): LevelUpHolder { return LevelUpHolder(view) } class LevelUpHolder(itemView: View) : BaseViewHolder(itemView) { var userLevelUpUserImage: CircleImageView = itemView.findViewById(R.id.userLevelUpUserImage) var userLevelUpTitle: TextView = itemView.findViewById(R.id.userLevelUpTitle) var userLevelUpLikeButton: LikeButton = itemView.findViewById(R.id.userLevelUpLikeButton) var userLevelUpImage: ImageView = itemView.findViewById(R.id.userLevelUpImage) } interface LevelUpClicks { fun clickedLike(compositePointEvent: CompositeUserLevel) fun clickedUnlike(compositePointEvent: CompositeUserLevel) } }
gpl-3.0
0d5ee4353c33e1256dc342319f459a8f
46.72
214
0.774518
4.156794
false
false
false
false
jamieadkins95/Roach
app/src/main/java/com/jamieadkins/gwent/card/detail/CardDetailsView.kt
1
4076
package com.jamieadkins.gwent.card.detail import android.content.Context import android.graphics.Typeface import android.util.AttributeSet import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.jamieadkins.gwent.R import com.jamieadkins.gwent.base.VerticalSpaceItemDecoration import com.jamieadkins.gwent.base.convertDpToPixel import com.jamieadkins.gwent.base.items.SubHeaderItem import com.jamieadkins.gwent.bus.GwentCardClickEvent import com.jamieadkins.gwent.bus.RxBus import com.jamieadkins.gwent.card.list.GwentCardItem import com.jamieadkins.gwent.domain.card.model.GwentCard import com.jamieadkins.gwent.domain.card.model.GwentCardColour import com.jamieadkins.gwent.main.GwentStringHelper import com.xwray.groupie.GroupAdapter import com.xwray.groupie.kotlinandroidextensions.Item import com.xwray.groupie.kotlinandroidextensions.ViewHolder as GroupieViewHolder class CardDetailsView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : RecyclerView(context, attrs, defStyleAttr) { private val cardAdapter = GroupAdapter<GroupieViewHolder>() init { layoutManager = LinearLayoutManager(context) adapter = cardAdapter addItemDecoration( VerticalSpaceItemDecoration(context.convertDpToPixel(8f).toInt())) cardAdapter.setOnItemClickListener { item, _ -> when (item) { is GwentCardItem -> RxBus.post(GwentCardClickEvent(item.card.id)) } } } fun showCardDetails(card: GwentCard, relatedCards: List<GwentCard>) { val items = mutableListOf<Item>() if (card.tooltip.isNotEmpty()) { items.add(SubHeaderItem(R.string.tooltip)) items.add(ElevatedTextItem(card.tooltip)) } if (card.keywords.isNotEmpty()) { items.add(SubHeaderItem(R.string.keywords)) items.addAll(card.keywords.map { ElevatedTextItem(it.description) }) } if (card.flavor.isNotEmpty()) { items.add(SubHeaderItem(R.string.flavor)) items.add(ElevatedTextItem(card.flavor, Typeface.defaultFromStyle(Typeface.ITALIC))) } if (card.secondaryFaction != null) { val factionName = GwentStringHelper.getFactionString(context, card.secondaryFaction) factionName?.let { items.add(SubHeaderItem(R.string.secondary_faction)) items.add(ElevatedTextItem(it)) } } if (card.categories.isNotEmpty()) { items.add(SubHeaderItem(R.string.categories)) items.add(ElevatedTextItem(card.categories.joinToString())) } items.add(SubHeaderItem(R.string.type)) items.add(ElevatedTextItem(GwentStringHelper.getTypeString(resources, card.type))) if (card.colour != GwentCardColour.LEADER && card.provisions > 0) { items.add(SubHeaderItem(R.string.provisions)) items.add(ElevatedTextItem(card.provisions.toString())) } if (card.strength > 0) { items.add(SubHeaderItem(R.string.strength)) items.add(ElevatedTextItem(card.strength.toString())) } if (card.colour == GwentCardColour.LEADER) { items.add(SubHeaderItem(R.string.extra_provisions)) items.add(ElevatedTextItem(card.extraProvisions.toString())) } items.add(SubHeaderItem(R.string.expansion)) items.add(ElevatedTextItem(GwentStringHelper.getExpansion(context.resources, card.expansion))) if (card.collectible) { items.add(SubHeaderItem(R.string.craft)) items.add(CraftCostItem(card.craftCost)) items.add(SubHeaderItem(R.string.mill)) items.add(CraftCostItem(card.millValue)) } if (card.relatedCards.isNotEmpty()) { items.add(SubHeaderItem(R.string.related)) items.addAll(relatedCards.map { GwentCardItem(it) }) } cardAdapter.update(items) } }
apache-2.0
f232cb2e34415dd2514a88e7b44c8503
38.970588
102
0.686948
4.290526
false
false
false
false
hartwigmedical/hmftools
cider/src/main/java/com/hartwig/hmftools/cider/layout/ReadLayout.kt
1
10523
package com.hartwig.hmftools.cider.layout import com.hartwig.hmftools.cider.CiderUtils import com.hartwig.hmftools.cider.ReadKey import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashMap import kotlin.collections.HashSet //data class class ReadLayout(var id: String = String()) { internal val allSequenceSupport: SequenceSupport = SequenceSupport() internal val highQualSequenceSupport: SequenceSupport = SequenceSupport() var alignedPosition: Int = 0 abstract class Read ( val readKey: ReadKey, val sequence: String, val baseQualities: ByteArray, val alignedPosition: Int) { init { require(sequence.length == baseQualities.size, { "sequence.length != baseQualities.size" }) } val readLength: Int get() { return sequence.length } // this function allows us to copy the layout read with different aligned position abstract fun copy(alignedPosition: Int): Read } private val mutableReads: MutableList<Read> = ArrayList() private val mutableReadSet: MutableSet<ReadKey> = HashSet() val reads: List<Read> get() = mutableReads private var sequenceCache: String? = null val length: Int get() { return allSequenceSupport.support.size } val highQualSequence: String get() { return highQualSequenceSupport.sequence } fun consensusSequence(): String { if (sequenceCache == null) updateConsensusSequence() return sequenceCache!! } fun highQualSupportString(): String { return highQualSequenceSupport.supportString() } fun highQualSupportCounts(): IntArray { return highQualSequenceSupport.counts() } fun getAllSequenceSupportAt(index: Int) : Map.Entry<Char, Int> { return allSequenceSupport.support[index].likelyBaseSupport() } fun getHighQualSequenceSupportAt(index: Int) : Map.Entry<Char, Int> { return highQualSequenceSupport.support[index].likelyBaseSupport() } // get the reads covering the segment fun getSegmentReads(start: Int, end: Int) : List<Read> { val segmentReads = ArrayList<Read>() for (r in reads) { val readStart = getReadOffset(r) val readEnd = readStart + r.readLength if (readStart < end && start < readEnd) { segmentReads.add(r) } } return segmentReads } fun getReadsAt(index: Int) : List<Read> { return getSegmentReads(index, index + 1) } class BaseSupport { internal var likelyBase: Char = 'N' private var aCount: Int = 0 private var cCount: Int = 0 private var gCount: Int = 0 private var tCount: Int = 0 fun generateCountMap() : Map<Char, Int> { val countMap: MutableMap<Char, Int> = HashMap() for (base in arrayOf('A', 'C', 'G', 'T')) { val baseCount = count(base) if (baseCount > 0) countMap[base] = baseCount } return countMap } fun count(base: Char): Int { return when (base) { 'A' -> aCount 'C' -> cCount 'G' -> gCount 'T' -> tCount else -> 0 } } // return true if the likely base has changed, false otherwise fun addToCount(base: Char) : Boolean { when (base) { 'A' -> ++aCount 'C' -> ++cCount 'G' -> ++gCount 'T' -> ++tCount } return updateLikelyBase(base) } private fun updateLikelyBase(baseWithAddedCount: Char) : Boolean { if (likelyBase != baseWithAddedCount && count(baseWithAddedCount) > count(likelyBase)) { likelyBase = baseWithAddedCount return true } return false } fun likelyBaseSupport(): Map.Entry<Char, Int> { if (likelyBase == 'N') return sNullSupport return AbstractMap.SimpleImmutableEntry(likelyBase, likelyBaseSupportCount()) } fun likelyBaseSupportCount(): Int { return count(likelyBase) } } class SequenceSupport ( var sequence: String = String()) { private val mMutableSupport: MutableList<BaseSupport> = ArrayList() val support: List<BaseSupport> get() { return mMutableSupport } internal fun ensureLength(l: Int) { val lengthChange = l - support.size if (lengthChange > 0) { for (i in 0 until lengthChange) { mMutableSupport.add(BaseSupport()) } sequence += "N".repeat(lengthChange) } } internal fun shiftRightBy(s: Int) { if (s <= 0) return // also need to add some items for (i in 0 until s) { mMutableSupport.add(BaseSupport()) } // rotate the new items to the front Collections.rotate(support, s) sequence = "N".repeat(s) + sequence } internal fun updateSequence() { val stringBuilder = StringBuilder(support.size) for (baseSupport in support) { stringBuilder.append(baseSupport.likelyBase) } sequence = stringBuilder.toString() } fun supportString(): String { return CiderUtils.countsToString(counts()) } fun counts(): IntArray { val countArray = IntArray(sequence.length) for (i in sequence.indices) { val base: Char = sequence[i] val readCount: Int = support[i].count(base) countArray[i] = readCount } return countArray } } fun addRead(read: Read, minBaseQuality: Byte) : Boolean { if (!mutableReadSet.add(read.readKey)) return false if (mutableReads.isEmpty()) { // this if first read alignedPosition = read.alignedPosition } else if (read.alignedPosition > alignedPosition) { // update max offset for each group item val offsetChange = read.alignedPosition - alignedPosition if (offsetChange > 0) { allSequenceSupport.shiftRightBy(offsetChange) highQualSequenceSupport.shiftRightBy(offsetChange) } alignedPosition = read.alignedPosition } mutableReads.add(read) // now use the aligned position to line up the read with the group val seqOffset = getReadOffset(read) val readSeqEnd = read.sequence.length + seqOffset allSequenceSupport.ensureLength(readSeqEnd) highQualSequenceSupport.ensureLength(readSeqEnd) // now we want to update the consensus sequence // we recalculate it from scratch for now var allSequenceChanged = false var highQualSequenceChanged = false // update the support for (i in read.sequence.indices) { val baseQual = read.baseQualities[i] val b: Char = read.sequence[i] if (b != 'N') { allSequenceChanged = allSequenceSupport.support[seqOffset + i].addToCount(b) or allSequenceChanged if (baseQual >= minBaseQuality) { highQualSequenceChanged = highQualSequenceSupport.support[seqOffset + i].addToCount(b) or highQualSequenceChanged } } } if (allSequenceChanged) allSequenceSupport.updateSequence() if (highQualSequenceChanged) highQualSequenceSupport.updateSequence() if (allSequenceChanged || highQualSequenceChanged) sequenceCache = null return true } private fun updateConsensusSequence() { // combine high qual with low qual val stringBuilder = StringBuilder(allSequenceSupport.sequence.length) for (i in allSequenceSupport.sequence.indices) { val base = highQualSequenceSupport.sequence[i] if (base == 'N') { // if high quality sequence is not sure, use the low qual one stringBuilder.append(allSequenceSupport.sequence[i]) } else { stringBuilder.append(base) } } sequenceCache = stringBuilder.toString() } private fun getReadOffset(read: Read) : Int { return alignedPosition - read.alignedPosition } // merge all the reads from another layout. alignedPositionShift specifies the change to // the aligned position of the reads that are merged in. fun mergeIn(layout: ReadLayout, alignedPositionShift: Int, minBaseQuality: Byte) { for (r in layout.reads) { if (alignedPositionShift == 0) addRead(r, minBaseQuality) else addRead(r.copy(alignedPosition = r.alignedPosition + alignedPositionShift), minBaseQuality) } } companion object { val sNullSupport : Map.Entry<Char, Int> = AbstractMap.SimpleImmutableEntry('N', 0) // merge in another layout to this layout, and create a new layout // the new layout will have the same aligned position as this layout fun merge(layout1: ReadLayout, layout2: ReadLayout, alignedPositionShift1: Int, alignedPositionShift2: Int, minBaseQuality: Byte) : ReadLayout { // unfortunately in java / kotlin it is difficult to clone objects // will do it the slow way of building it from ground up again val merged = ReadLayout() merged.mergeIn(layout1, alignedPositionShift1, minBaseQuality) merged.mergeIn(layout2, alignedPositionShift2, minBaseQuality) return merged } } }
gpl-3.0
d9324167f98a8f9a1dea983e149dd7a6
28.980057
133
0.565048
4.789713
false
false
false
false
googlesamples/mlkit
android/android-snippets/app/src/main/java/com/google/example/mlkit/kotlin/FaceDetectionActivity.kt
1
5409
/* * Copyright 2020 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.google.example.mlkit.kotlin import androidx.appcompat.app.AppCompatActivity import com.google.mlkit.vision.common.InputImage import com.google.mlkit.vision.face.* class FaceDetectionActivity : AppCompatActivity() { private fun detectFaces(image: InputImage) { // [START set_detector_options] val options = FaceDetectorOptions.Builder() .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE) .setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL) .setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_ALL) .setMinFaceSize(0.15f) .enableTracking() .build() // [END set_detector_options] // [START get_detector] val detector = FaceDetection.getClient(options) // Or, to use the default option: // val detector = FaceDetection.getClient(); // [END get_detector] // [START run_detector] val result = detector.process(image) .addOnSuccessListener { faces -> // Task completed successfully // [START_EXCLUDE] // [START get_face_info] for (face in faces) { val bounds = face.boundingBox val rotY = face.headEulerAngleY // Head is rotated to the right rotY degrees val rotZ = face.headEulerAngleZ // Head is tilted sideways rotZ degrees // If landmark detection was enabled (mouth, ears, eyes, cheeks, and // nose available): val leftEar = face.getLandmark(FaceLandmark.LEFT_EAR) leftEar?.let { val leftEarPos = leftEar.position } // If classification was enabled: if (face.smilingProbability != null) { val smileProb = face.smilingProbability } if (face.rightEyeOpenProbability != null) { val rightEyeOpenProb = face.rightEyeOpenProbability } // If face tracking was enabled: if (face.trackingId != null) { val id = face.trackingId } } // [END get_face_info] // [END_EXCLUDE] } .addOnFailureListener { e -> // Task failed with an exception // ... } // [END run_detector] } private fun faceOptionsExamples() { // [START mlkit_face_options_examples] // High-accuracy landmark detection and face classification val highAccuracyOpts = FaceDetectorOptions.Builder() .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE) .setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL) .setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_ALL) .build() // Real-time contour detection val realTimeOpts = FaceDetectorOptions.Builder() .setContourMode(FaceDetectorOptions.CONTOUR_MODE_ALL) .build() // [END mlkit_face_options_examples] } private fun processFaceList(faces: List<Face>) { // [START mlkit_face_list] for (face in faces) { val bounds = face.boundingBox val rotY = face.headEulerAngleY // Head is rotated to the right rotY degrees val rotZ = face.headEulerAngleZ // Head is tilted sideways rotZ degrees // If landmark detection was enabled (mouth, ears, eyes, cheeks, and // nose available): val leftEar = face.getLandmark(FaceLandmark.LEFT_EAR) leftEar?.let { val leftEarPos = leftEar.position } // If contour detection was enabled: val leftEyeContour = face.getContour(FaceContour.LEFT_EYE)?.points val upperLipBottomContour = face.getContour(FaceContour.UPPER_LIP_BOTTOM)?.points // If classification was enabled: if (face.smilingProbability != null) { val smileProb = face.smilingProbability } if (face.rightEyeOpenProbability != null) { val rightEyeOpenProb = face.rightEyeOpenProbability } // If face tracking was enabled: if (face.trackingId != null) { val id = face.trackingId } } // [END mlkit_face_list] } }
apache-2.0
34f926668a03dbe11f0303945dcd5144
39.977273
100
0.565909
5.151429
false
false
false
false
dafi/photoshelf
birthday/src/main/java/com/ternaryop/photoshelf/birthday/repository/BirthdayRepository.kt
1
966
package com.ternaryop.photoshelf.birthday.repository import com.ternaryop.photoshelf.api.ApiManager import com.ternaryop.photoshelf.api.birthday.FindParams import com.ternaryop.photoshelf.lifecycle.CommandMutableLiveData import com.ternaryop.utils.date.dayOfMonth import com.ternaryop.utils.date.month import java.util.Calendar import javax.inject.Inject import javax.inject.Singleton @Singleton class BirthdayRepository @Inject constructor() { private val _count = CommandMutableLiveData<Int>() val count = _count.asLiveData() suspend fun count() = _count.post(true) { birthdayCount() } private suspend fun birthdayCount(): Int { val now = Calendar.getInstance() return ApiManager.birthdayService().findByDate( FindParams(onlyTotal = true, month = now.month + 1, dayOfMonth = now.dayOfMonth).toQueryMap() ).response.total.toInt() } fun clearCount() { _count.setLastValue(null, false) } }
mit
552fb135d8d1ae0d4a853bcb30e6a56d
32.310345
105
0.740166
4.255507
false
false
false
false
ken-kentan/student-portal-plus
app/src/main/java/jp/kentan/studentportalplus/ui/notice/NoticeViewModel.kt
1
1625
package jp.kentan.studentportalplus.ui.notice import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.ViewModel import jp.kentan.studentportalplus.data.PortalRepository import jp.kentan.studentportalplus.data.component.NoticeQuery import jp.kentan.studentportalplus.data.model.Notice import jp.kentan.studentportalplus.ui.SingleLiveData class NoticeViewModel( private val portalRepository: PortalRepository ) : ViewModel() { var query = NoticeQuery() private set(value) { field = value queryLiveData.value = query } private val queryLiveData = MutableLiveData<NoticeQuery>() val noticeList: LiveData<List<Notice>> = Transformations.switchMap(queryLiveData) { portalRepository.getNoticeList(it) } val startDetailActivity = SingleLiveData<Long>() init { queryLiveData.value = query } fun onClick(id: Long) { startDetailActivity.value = id } fun onFavoriteClick(data: Notice) { portalRepository.updateNotice(data.copy(isFavorite = !data.isFavorite)) } fun onQueryTextChange(text: String?) { query = query.copy(keyword = text) } fun onFilterApplyClick( range: NoticeQuery.DateRange, isUnread: Boolean, isRead: Boolean, isFavorite: Boolean ) { query = query.copy( dateRange = range, isUnread = isUnread, isRead = isRead, isFavorite = isFavorite ) } }
gpl-3.0
854407a86796334a021ee3c2c2766877
27.017241
87
0.666462
4.821958
false
false
false
false
Light-Team/ModPE-IDE-Source
languages/language-json/src/main/kotlin/com/brackeys/ui/language/json/styler/JsonStyler.kt
1
4776
/* * Copyright 2021 Brackeys IDE contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.brackeys.ui.language.json.styler import android.util.Log import com.brackeys.ui.language.base.model.SyntaxScheme import com.brackeys.ui.language.base.span.StyleSpan import com.brackeys.ui.language.base.span.SyntaxHighlightSpan import com.brackeys.ui.language.base.styler.LanguageStyler import com.brackeys.ui.language.base.utils.StylingResult import com.brackeys.ui.language.base.utils.StylingTask import com.brackeys.ui.language.json.lexer.JsonLexer import com.brackeys.ui.language.json.lexer.JsonToken import java.io.IOException import java.io.StringReader class JsonStyler private constructor() : LanguageStyler { companion object { private const val TAG = "JsonStyler" private var jsonStyler: JsonStyler? = null fun getInstance(): JsonStyler { return jsonStyler ?: JsonStyler().also { jsonStyler = it } } } private var task: StylingTask? = null override fun execute(sourceCode: String, syntaxScheme: SyntaxScheme): List<SyntaxHighlightSpan> { val syntaxHighlightSpans = mutableListOf<SyntaxHighlightSpan>() val sourceReader = StringReader(sourceCode) val lexer = JsonLexer(sourceReader) while (true) { try { when (lexer.advance()) { JsonToken.NUMBER -> { val styleSpan = StyleSpan(syntaxScheme.numberColor) val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd) syntaxHighlightSpans.add(syntaxHighlightSpan) } JsonToken.LBRACE, JsonToken.RBRACE, JsonToken.LBRACK, JsonToken.RBRACK, JsonToken.COMMA, JsonToken.COLON -> { val styleSpan = StyleSpan(syntaxScheme.operatorColor) val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd) syntaxHighlightSpans.add(syntaxHighlightSpan) } JsonToken.TRUE, JsonToken.FALSE, JsonToken.NULL -> { val styleSpan = StyleSpan(syntaxScheme.langConstColor) val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd) syntaxHighlightSpans.add(syntaxHighlightSpan) } JsonToken.DOUBLE_QUOTED_STRING, JsonToken.SINGLE_QUOTED_STRING -> { val styleSpan = StyleSpan(syntaxScheme.stringColor) val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd) syntaxHighlightSpans.add(syntaxHighlightSpan) } JsonToken.BLOCK_COMMENT, JsonToken.LINE_COMMENT -> { val styleSpan = StyleSpan(syntaxScheme.commentColor) val syntaxHighlightSpan = SyntaxHighlightSpan(styleSpan, lexer.tokenStart, lexer.tokenEnd) syntaxHighlightSpans.add(syntaxHighlightSpan) } JsonToken.IDENTIFIER, JsonToken.WHITESPACE, JsonToken.BAD_CHARACTER -> { continue } JsonToken.EOF -> { break } } } catch (e: IOException) { Log.e(TAG, e.message, e) break } } return syntaxHighlightSpans } override fun enqueue(sourceCode: String, syntaxScheme: SyntaxScheme, stylingResult: StylingResult) { task?.cancelTask() task = StylingTask( doAsync = { execute(sourceCode, syntaxScheme) }, onSuccess = stylingResult ) task?.executeTask() } override fun cancel() { task?.cancelTask() task = null } }
apache-2.0
f4f7292a88e610459500b505adb107a3
38.808333
114
0.591709
5.108021
false
false
false
false
ledao/chatbot
src/main/kotlin/com/davezhao/models/UserLogTable.kt
1
615
package com.davezhao.models import org.jetbrains.exposed.sql.Table object UserLogTable : Table() { val id = integer(name = "id").autoIncrement().primaryKey() val userQuery = varchar(name = "user_query", length = 300) val hitQuestion = varchar(name = "hit_question", length = 300) val answer = varchar(name = "answer", length = 300) // val similarScore = decimal(name = "similar_score", precision = 4, scale = 1) val similarScore = varchar(name = "similar_score", length = 20) val createtime = datetime(name = "createtime") override val tableName: String get() = "user_log" }
gpl-3.0
3d8840d54acf6330e93652fa5934c614
40.066667
82
0.671545
3.617647
false
false
false
false
nemerosa/ontrack
ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/GQLTypePromotionLevel.kt
1
6932
package net.nemerosa.ontrack.graphql.schema import graphql.Scalars import graphql.schema.DataFetcher import graphql.schema.DataFetchingEnvironment import graphql.schema.GraphQLObjectType import graphql.schema.GraphQLTypeReference import net.nemerosa.ontrack.common.and import net.nemerosa.ontrack.graphql.support.* import net.nemerosa.ontrack.graphql.support.pagination.GQLPaginatedListFactory import net.nemerosa.ontrack.model.pagination.PaginatedList import net.nemerosa.ontrack.model.structure.* import net.nemerosa.ontrack.model.support.FreeTextAnnotatorContributor import org.springframework.stereotype.Component import java.time.LocalDateTime @Component class GQLTypePromotionLevel( private val structureService: StructureService, creation: GQLTypeCreation, private val promotionRun: GQLTypePromotionRun, projectEntityFieldContributors: List<GQLProjectEntityFieldContributor>, private val projectEntityInterface: GQLProjectEntityInterface, private val paginatedListFactory: GQLPaginatedListFactory, private val buildDisplayNameService: BuildDisplayNameService, freeTextAnnotatorContributors: List<FreeTextAnnotatorContributor> ) : AbstractGQLProjectEntity<PromotionLevel>( PromotionLevel::class.java, ProjectEntityType.PROMOTION_LEVEL, projectEntityFieldContributors, creation, freeTextAnnotatorContributors ) { override fun getTypeName(): String = PROMOTION_LEVEL override fun createType(cache: GQLTypeCache): GraphQLObjectType = GraphQLObjectType.newObject() .name(PROMOTION_LEVEL) .withInterface(projectEntityInterface.typeRef) .fields(projectEntityInterfaceFields()) // Image flag .field { it.name("image") .description("Flag to indicate if an image is associated") .type(Scalars.GraphQLBoolean) } // Ref to branch .field { it.name("branch") .description("Reference to branch") .type(GraphQLTypeReference(GQLTypeBranch.BRANCH)) } // Promotion runs .field { it.name("promotionRuns") .deprecate("Use the paginated promotion runs with the `promotionRunsPaginated` field.") .description("List of runs for this promotion") .type(listType(promotionRun.typeRef)) .arguments(listArguments()) .dataFetcher(promotionLevelPromotionRunsFetcher()) } // Paginated promotion runs .field( paginatedListFactory.createPaginatedField<PromotionLevel, PromotionRun>( cache = cache, fieldName = "promotionRunsPaginated", fieldDescription = "Paginated list of promotion runs", itemType = promotionRun, arguments = listOf( dateTimeArgument(ARG_BEFORE_DATE, "Keeps only runs before this data / time"), dateTimeArgument(ARG_AFTER_DATE, "Keeps only runs after this data / time"), stringArgument(ARG_NAME, "Regular expression on the name of the build name"), stringArgument(ARG_VERSION, "Regular expression on the release property attached to the build name") ), itemPaginatedListProvider = { env, promotionLevel, offset, size -> val beforeDate: LocalDateTime? = env.getArgument(ARG_BEFORE_DATE) val afterDate: LocalDateTime? = env.getArgument(ARG_AFTER_DATE) val name: String? = env.getArgument(ARG_NAME) val version: String? = env.getArgument(ARG_VERSION) // Promotion run filter var filter: (PromotionRun) -> Boolean = { true } if (beforeDate != null) { filter = filter and { run -> run.signature.time <= beforeDate } } if (afterDate != null) { filter = filter and { run -> run.signature.time >= afterDate } } if (!name.isNullOrBlank()) { val r = name.toRegex() filter = filter and { run -> run.build.name.matches(r) } } if (!version.isNullOrBlank()) { val r = version.toRegex() filter = filter and { run -> val buildVersion = buildDisplayNameService.getBuildDisplayName(run.build) buildVersion.matches(r) } } // Gets the filtered list of promotion runs val runs = structureService.getPromotionRunsForPromotionLevel(promotionLevel.id) .filter(filter) // Pagination PaginatedList.Companion.create(runs, offset, size) } ) ) // OK .build() private fun promotionLevelPromotionRunsFetcher(): DataFetcher<List<PromotionRun>> = DataFetcher { environment: DataFetchingEnvironment -> val promotionLevel = environment.getSource<PromotionLevel>() // Gets all the promotion runs val promotionRuns = structureService.getPromotionRunsForPromotionLevel(promotionLevel.id) // Filters according to the arguments stdListArgumentsFilter(promotionRuns, environment) } override fun getSignature(entity: PromotionLevel): Signature? { return entity.signature } companion object { const val PROMOTION_LEVEL = "PromotionLevel" // Filtering for the paginated promotion runs const val ARG_AFTER_DATE = "afterDate" const val ARG_BEFORE_DATE = "beforeDate" const val ARG_NAME = "name" const val ARG_VERSION = "version" } }
mit
7638cd74bdfd3a61d15033fcd23ee7a9
48.521429
136
0.533179
6.460391
false
false
false
false
wiltonlazary/kotlin-native
samples/gtk/src/gtkMain/kotlin/Main.kt
1
2023
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package sample.gtk import kotlinx.cinterop.* import gtk3.* // Note that all callback parameters must be primitive types or nullable C pointers. fun <F : CFunction<*>> g_signal_connect(obj: CPointer<*>, actionName: String, action: CPointer<F>, data: gpointer? = null, connect_flags: GConnectFlags = 0u) { g_signal_connect_data(obj.reinterpret(), actionName, action.reinterpret(), data = data, destroy_data = null, connect_flags = connect_flags) } fun activate(app: CPointer<GtkApplication>?, user_data: gpointer?) { val windowWidget = gtk_application_window_new(app)!! val window = windowWidget.reinterpret<GtkWindow>() gtk_window_set_title(window, "Window") gtk_window_set_default_size(window, 200, 200) val button_box = gtk_button_box_new( GtkOrientation.GTK_ORIENTATION_HORIZONTAL)!! gtk_container_add(window.reinterpret(), button_box) val button = gtk_button_new_with_label("Konan говорит: click me!")!! g_signal_connect(button, "clicked", staticCFunction { _: CPointer<GtkWidget>?, _: gpointer? -> println("Hi Kotlin") }) g_signal_connect(button, "clicked", staticCFunction { widget: CPointer<GtkWidget>? -> gtk_widget_destroy(widget) }, window, G_CONNECT_SWAPPED) gtk_container_add (button_box.reinterpret(), button) gtk_widget_show_all(windowWidget) } fun gtkMain(args: Array<String>): Int { val app = gtk_application_new("org.gtk.example", G_APPLICATION_FLAGS_NONE)!! g_signal_connect(app, "activate", staticCFunction(::activate)) val status = memScoped { g_application_run(app.reinterpret(), args.size, args.map { it.cstr.ptr }.toCValues()) } g_object_unref(app) return status } fun main(args: Array<String>) { gtkMain(args) }
apache-2.0
8ed7b41f682c77f9a64fafad73c2de61
35
101
0.662698
3.587189
false
false
false
false
stripe/stripe-android
payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/menu/Menu.kt
1
11704
package com.stripe.android.ui.core.elements.menu /* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import androidx.compose.animation.core.LinearOutSlowInEasing import androidx.compose.animation.core.MutableTransitionState import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.tween import androidx.compose.animation.core.updateTransition import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.Card import androidx.compose.material.ContentAlpha import androidx.compose.material.DropdownMenu import androidx.compose.material.DropdownMenuItem import androidx.compose.material.LocalContentAlpha import androidx.compose.material.MaterialTheme import androidx.compose.material.ProvideTextStyle import androidx.compose.material.ripple.rememberRipple import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.Immutable import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.compose.ui.window.PopupPositionProvider import com.stripe.android.ui.core.paymentsColors import com.stripe.android.ui.core.paymentsShapes import kotlin.math.max import kotlin.math.min @Suppress("ModifierParameter") @Composable internal fun DropdownMenuContent( expandedStates: MutableTransitionState<Boolean>, transformOriginState: MutableState<TransformOrigin>, initialFirstVisibleItemIndex: Int, modifier: Modifier = Modifier, content: LazyListScope.() -> Unit ) { // Menu open/close animation. val transition = updateTransition(expandedStates, "DropDownMenu") val scale by transition.animateFloat( transitionSpec = { if (false isTransitioningTo true) { // Dismissed to expanded tween( durationMillis = InTransitionDuration, easing = LinearOutSlowInEasing ) } else { // Expanded to dismissed. tween( durationMillis = 1, delayMillis = OutTransitionDuration - 1 ) } }, label = "menu-scale" ) { if (it) { // Menu is expanded. 1f } else { // Menu is dismissed. 0.8f } } val alpha by transition.animateFloat( transitionSpec = { if (false isTransitioningTo true) { // Dismissed to expanded tween(durationMillis = 30) } else { // Expanded to dismissed. tween(durationMillis = OutTransitionDuration) } }, label = "menu-alpha" ) { if (it) { // Menu is expanded. 1f } else { // Menu is dismissed. 0f } } // TODO: Make sure this gets the rounded corner values Card( border = BorderStroke( MaterialTheme.paymentsShapes.borderStrokeWidth.dp, MaterialTheme.paymentsColors.componentBorder ), modifier = Modifier.graphicsLayer { scaleX = scale scaleY = scale this.alpha = alpha transformOrigin = transformOriginState.value }, elevation = MenuElevation ) { val lazyListState = rememberLazyListState( initialFirstVisibleItemIndex = initialFirstVisibleItemIndex ) LazyColumn( modifier = modifier .padding(vertical = DropdownMenuVerticalPadding), state = lazyListState, content = content ) } } @Composable internal fun DropdownMenuItemContent( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, contentPadding: PaddingValues = MenuDefaults.DropdownMenuItemContentPadding, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable RowScope.() -> Unit ) { // TODO(popam, b/156911853): investigate replacing this Row with ListItem Row( modifier = modifier .clickable( enabled = enabled, onClick = onClick, interactionSource = interactionSource, indication = rememberRipple(true) ) .fillMaxWidth() // Preferred min and max width used during the intrinsic measurement. .sizeIn( minWidth = DropdownMenuItemDefaultMaxWidth, // use the max width for both maxWidth = DropdownMenuItemDefaultMaxWidth, minHeight = DropdownMenuItemDefaultMinHeight ) .padding(contentPadding), verticalAlignment = Alignment.CenterVertically ) { val typography = MaterialTheme.typography ProvideTextStyle(typography.subtitle1) { val contentAlpha = if (enabled) ContentAlpha.high else ContentAlpha.disabled CompositionLocalProvider(LocalContentAlpha provides contentAlpha) { content() } } } } /** * Contains default values used for [DropdownMenuItem]. */ internal object MenuDefaults { /** * Default padding used for [DropdownMenuItem]. */ val DropdownMenuItemContentPadding = PaddingValues( horizontal = DropdownMenuItemHorizontalPadding, vertical = 0.dp ) } // Size defaults. private val MenuElevation = 8.dp internal val MenuVerticalMargin = 48.dp internal val DropdownMenuItemHorizontalPadding = 16.dp internal val DropdownMenuVerticalPadding = 8.dp internal val DropdownMenuItemDefaultMinWidth = 112.dp internal val DropdownMenuItemDefaultMaxWidth = 280.dp internal val DropdownMenuItemDefaultMinHeight = 48.dp // Menu open/close animation. internal const val InTransitionDuration = 120 internal const val OutTransitionDuration = 75 internal fun calculateTransformOrigin( parentBounds: IntRect, menuBounds: IntRect ): TransformOrigin { val pivotX = when { menuBounds.left >= parentBounds.right -> 0f menuBounds.right <= parentBounds.left -> 1f menuBounds.width == 0 -> 0f else -> { val intersectionCenter = ( max(parentBounds.left, menuBounds.left) + min(parentBounds.right, menuBounds.right) ) / 2 (intersectionCenter - menuBounds.left).toFloat() / menuBounds.width } } val pivotY = when { menuBounds.top >= parentBounds.bottom -> 0f menuBounds.bottom <= parentBounds.top -> 1f menuBounds.height == 0 -> 0f else -> { val intersectionCenter = ( max(parentBounds.top, menuBounds.top) + min(parentBounds.bottom, menuBounds.bottom) ) / 2 (intersectionCenter - menuBounds.top).toFloat() / menuBounds.height } } return TransformOrigin(pivotX, pivotY) } // Menu positioning. /** * Calculates the position of a Material [DropdownMenu]. */ // TODO(popam): Investigate if this can/should consider the app window size rather than screen size @Immutable internal data class DropdownMenuPositionProvider( val contentOffset: DpOffset, val density: Density, val onPositionCalculated: (IntRect, IntRect) -> Unit = { _, _ -> } ) : PopupPositionProvider { override fun calculatePosition( anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize ): IntOffset { // The min margin above and below the menu, relative to the screen. val verticalMargin = with(density) { MenuVerticalMargin.roundToPx() } // The content offset specified using the dropdown offset parameter. val contentOffsetX = with(density) { contentOffset.x.roundToPx() } val contentOffsetY = with(density) { contentOffset.y.roundToPx() } // Compute horizontal position. val toRight = anchorBounds.left + contentOffsetX val toLeft = anchorBounds.right - contentOffsetX - popupContentSize.width val toDisplayRight = windowSize.width - popupContentSize.width val toDisplayLeft = 0 val x = if (layoutDirection == LayoutDirection.Ltr) { sequenceOf( toRight, toLeft, // If the anchor gets outside of the window on the left, we want to position // toDisplayLeft for proximity to the anchor. Otherwise, toDisplayRight. if (anchorBounds.left >= 0) toDisplayRight else toDisplayLeft ) } else { sequenceOf( toLeft, toRight, // If the anchor gets outside of the window on the right, we want to position // toDisplayRight for proximity to the anchor. Otherwise, toDisplayLeft. if (anchorBounds.right <= windowSize.width) toDisplayLeft else toDisplayRight ) }.firstOrNull { it >= 0 && it + popupContentSize.width <= windowSize.width } ?: toLeft // Compute vertical position. val toBottom = maxOf(anchorBounds.bottom + contentOffsetY, verticalMargin) val toTop = anchorBounds.top - contentOffsetY - popupContentSize.height val toCenter = anchorBounds.top - popupContentSize.height / 2 val toDisplayBottom = windowSize.height - popupContentSize.height - verticalMargin val y = sequenceOf(toBottom, toTop, toCenter, toDisplayBottom).firstOrNull { it >= verticalMargin && it + popupContentSize.height <= windowSize.height - verticalMargin } ?: toTop onPositionCalculated( anchorBounds, IntRect(x, y, x + popupContentSize.width, y + popupContentSize.height) ) return IntOffset(x, y) } }
mit
7daf8cc1b0d80f9c6733b3d9f88667fb
36.037975
99
0.665584
5.234347
false
false
false
false
stripe/stripe-android
stripecardscan/src/main/java/com/stripe/android/stripecardscan/cardimageverification/result/MainLoopAggregator.kt
1
4972
package com.stripe.android.stripecardscan.cardimageverification.result import com.stripe.android.camera.framework.AggregateResultListener import com.stripe.android.camera.framework.ResultAggregator import com.stripe.android.camera.framework.util.FrameSaver import com.stripe.android.stripecardscan.cardimageverification.SavedFrame import com.stripe.android.stripecardscan.cardimageverification.SavedFrameType import com.stripe.android.stripecardscan.cardimageverification.analyzer.MainLoopAnalyzer import com.stripe.android.stripecardscan.cardimageverification.result.MainLoopAggregator.FinalResult import com.stripe.android.stripecardscan.cardimageverification.result.MainLoopAggregator.InterimResult import com.stripe.android.stripecardscan.payment.card.CardIssuer import com.stripe.android.stripecardscan.payment.card.CardMatchResult import com.stripe.android.stripecardscan.payment.card.RequiresMatchingCard import com.stripe.android.stripecardscan.payment.card.isValidPanLastFour import kotlinx.coroutines.runBlocking /** * Aggregate results from the main loop. Each frame will trigger an [InterimResult] to the * [listener]. Once the [MainLoopState.Finished] state is reached, a [FinalResult] will be sent to * the [listener]. * * This aggregator is a state machine. The full list of possible states are subclasses of * [MainLoopState]. This was written referencing this article: * https://thoughtbot.com/blog/finite-state-machines-android-kotlin-good-times */ internal class MainLoopAggregator( listener: AggregateResultListener<InterimResult, FinalResult>, override val requiredCardIssuer: CardIssuer?, override val requiredLastFour: String?, strictModeFrames: Int ) : RequiresMatchingCard, ResultAggregator< MainLoopAnalyzer.Input, MainLoopState, MainLoopAnalyzer.Prediction, InterimResult, FinalResult >( listener = listener, initialState = MainLoopState.Initial( requiredCardIssuer = requiredCardIssuer, requiredLastFour = requiredLastFour, strictModeFrames = strictModeFrames ), statsName = null // TODO: when we want to collect this in scan stats, give this a name ) { companion object { /** * The maximum number of saved frames per type to use. */ const val MAX_SAVED_FRAMES_PER_TYPE = 6 } internal data class FinalResult( val pan: String, val savedFrames: Map<SavedFrameType, List<SavedFrame>> ) internal data class InterimResult( val analyzerResult: MainLoopAnalyzer.Prediction, val frame: MainLoopAnalyzer.Input, val state: MainLoopState ) init { require(requiredLastFour == null || isValidPanLastFour(requiredLastFour)) { "Invalid last four" } require(requiredCardIssuer == null || requiredCardIssuer != CardIssuer.Unknown) { "Invalid required iin" } } private val frameSaver = object : FrameSaver<SavedFrameType, SavedFrame, InterimResult>() { override fun getMaxSavedFrames(savedFrameIdentifier: SavedFrameType): Int = MAX_SAVED_FRAMES_PER_TYPE override fun getSaveFrameIdentifier( frame: SavedFrame, metaData: InterimResult ): SavedFrameType? { val hasCard = metaData.analyzerResult.isCardVisible == true val matchesCard = compareToRequiredCard(metaData.analyzerResult.ocr?.pan) return when { matchesCard is CardMatchResult.Match || matchesCard is CardMatchResult.NoRequiredCard -> SavedFrameType(hasCard = hasCard, hasOcr = true) matchesCard is CardMatchResult.NoPan && hasCard -> SavedFrameType(hasCard = hasCard, hasOcr = false) else -> null } } } override suspend fun aggregateResult( frame: MainLoopAnalyzer.Input, result: MainLoopAnalyzer.Prediction ): Pair<InterimResult, FinalResult?> { val previousState = state val currentState = previousState.consumeTransition(result) state = currentState val interimResult = InterimResult( analyzerResult = result, frame = frame, state = currentState ) val savedFrame = SavedFrame( hasOcr = result.ocr?.pan?.isNotEmpty() == true, frame = frame ) frameSaver.saveFrame(savedFrame, interimResult) return if (currentState is MainLoopState.Finished) { val savedFrames = frameSaver.getSavedFrames() frameSaver.reset() interimResult to FinalResult(currentState.pan, savedFrames) } else { interimResult to null } } override fun reset() { super.reset() runBlocking { frameSaver.reset() } } }
mit
32d9af3c7c24a29e312fda59419cfdb2
36.383459
102
0.683829
4.699433
false
false
false
false
AndroidX/androidx
compose/material/material/src/commonMain/kotlin/androidx/compose/material/SwipeToDismiss.kt
3
8969
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.offset import androidx.compose.material.DismissDirection.EndToStart import androidx.compose.material.DismissDirection.StartToEnd import androidx.compose.material.DismissValue.Default import androidx.compose.material.DismissValue.DismissedToEnd import androidx.compose.material.DismissValue.DismissedToStart import androidx.compose.material.SwipeableDefaults.StandardResistanceFactor import androidx.compose.material.SwipeableDefaults.StiffResistanceFactor import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import kotlinx.coroutines.CancellationException import kotlin.math.roundToInt /** * The directions in which a [SwipeToDismiss] can be dismissed. */ enum class DismissDirection { /** * Can be dismissed by swiping in the reading direction. */ StartToEnd, /** * Can be dismissed by swiping in the reverse of the reading direction. */ EndToStart } /** * Possible values of [DismissState]. */ enum class DismissValue { /** * Indicates the component has not been dismissed yet. */ Default, /** * Indicates the component has been dismissed in the reading direction. */ DismissedToEnd, /** * Indicates the component has been dismissed in the reverse of the reading direction. */ DismissedToStart } /** * State of the [SwipeToDismiss] composable. * * @param initialValue The initial value of the state. * @param confirmStateChange Optional callback invoked to confirm or veto a pending state change. */ @ExperimentalMaterialApi class DismissState( initialValue: DismissValue, confirmStateChange: (DismissValue) -> Boolean = { true } ) : SwipeableState<DismissValue>(initialValue, confirmStateChange = confirmStateChange) { /** * The direction (if any) in which the composable has been or is being dismissed. * * If the composable is settled at the default state, then this will be null. Use this to * change the background of the [SwipeToDismiss] if you want different actions on each side. */ val dismissDirection: DismissDirection? get() = if (offset.value == 0f) null else if (offset.value > 0f) StartToEnd else EndToStart /** * Whether the component has been dismissed in the given [direction]. * * @param direction The dismiss direction. */ fun isDismissed(direction: DismissDirection): Boolean { return currentValue == if (direction == StartToEnd) DismissedToEnd else DismissedToStart } /** * Reset the component to the default position with animation and suspend until it if fully * reset or animation has been cancelled. This method will throw [CancellationException] if * the animation is interrupted * * @return the reason the reset animation ended */ suspend fun reset() = animateTo(targetValue = Default) /** * Dismiss the component in the given [direction], with an animation and suspend. This method * will throw [CancellationException] if the animation is interrupted * * @param direction The dismiss direction. */ suspend fun dismiss(direction: DismissDirection) { val targetValue = if (direction == StartToEnd) DismissedToEnd else DismissedToStart animateTo(targetValue = targetValue) } companion object { /** * The default [Saver] implementation for [DismissState]. */ fun Saver( confirmStateChange: (DismissValue) -> Boolean ) = Saver<DismissState, DismissValue>( save = { it.currentValue }, restore = { DismissState(it, confirmStateChange) } ) } } /** * Create and [remember] a [DismissState]. * * @param initialValue The initial value of the state. * @param confirmStateChange Optional callback invoked to confirm or veto a pending state change. */ @Composable @ExperimentalMaterialApi fun rememberDismissState( initialValue: DismissValue = Default, confirmStateChange: (DismissValue) -> Boolean = { true } ): DismissState { return rememberSaveable(saver = DismissState.Saver(confirmStateChange)) { DismissState(initialValue, confirmStateChange) } } /** * A composable that can be dismissed by swiping left or right. * * @sample androidx.compose.material.samples.SwipeToDismissListItems * * @param state The state of this component. * @param modifier Optional [Modifier] for this component. * @param directions The set of directions in which the component can be dismissed. * @param dismissThresholds The thresholds the item needs to be swiped in order to be dismissed. * @param background A composable that is stacked behind the content and is exposed when the * content is swiped. You can/should use the [state] to have different backgrounds on each side. * @param dismissContent The content that can be dismissed. */ @Composable @ExperimentalMaterialApi fun SwipeToDismiss( state: DismissState, modifier: Modifier = Modifier, directions: Set<DismissDirection> = setOf(EndToStart, StartToEnd), dismissThresholds: (DismissDirection) -> ThresholdConfig = { FixedThreshold(DISMISS_THRESHOLD) }, background: @Composable RowScope.() -> Unit, dismissContent: @Composable RowScope.() -> Unit ) = BoxWithConstraints(modifier) { val width = constraints.maxWidth.toFloat() val isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl val anchors = mutableMapOf(0f to Default) if (StartToEnd in directions) anchors += width to DismissedToEnd if (EndToStart in directions) anchors += -width to DismissedToStart val thresholds = { from: DismissValue, to: DismissValue -> dismissThresholds(getDismissDirection(from, to)!!) } val minFactor = if (EndToStart in directions) StandardResistanceFactor else StiffResistanceFactor val maxFactor = if (StartToEnd in directions) StandardResistanceFactor else StiffResistanceFactor Box( Modifier.swipeable( state = state, anchors = anchors, thresholds = thresholds, orientation = Orientation.Horizontal, enabled = state.currentValue == Default, reverseDirection = isRtl, resistance = ResistanceConfig( basis = width, factorAtMin = minFactor, factorAtMax = maxFactor ) ) ) { Row( content = background, modifier = Modifier.matchParentSize() ) Row( content = dismissContent, modifier = Modifier.offset { IntOffset(state.offset.value.roundToInt(), 0) } ) } } private fun getDismissDirection(from: DismissValue, to: DismissValue): DismissDirection? { return when { // settled at the default state from == to && from == Default -> null // has been dismissed to the end from == to && from == DismissedToEnd -> StartToEnd // has been dismissed to the start from == to && from == DismissedToStart -> EndToStart // is currently being dismissed to the end from == Default && to == DismissedToEnd -> StartToEnd // is currently being dismissed to the start from == Default && to == DismissedToStart -> EndToStart // has been dismissed to the end but is now animated back to default from == DismissedToEnd && to == Default -> StartToEnd // has been dismissed to the start but is now animated back to default from == DismissedToStart && to == Default -> EndToStart else -> null } } private val DISMISS_THRESHOLD = 56.dp
apache-2.0
8f4c04353db86ef938ccca615217858b
35.91358
99
0.705207
4.720526
false
false
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-tensorflow/src/main/kotlin/org/nd4j/samediff/frameworkimport/tensorflow/rule/attribute/TensorflowConditionalFieldValueIntIndexArrayRule.kt
1
5114
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.tensorflow.rule.attribute import org.nd4j.ir.OpNamespace import org.nd4j.samediff.frameworkimport.argDescriptorType import org.nd4j.samediff.frameworkimport.findOp import org.nd4j.samediff.frameworkimport.ir.IRAttribute import org.nd4j.samediff.frameworkimport.isNd4jTensorName import org.nd4j.samediff.frameworkimport.isOutputFrameworkAttributeName import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder import org.nd4j.samediff.frameworkimport.process.MappingProcess import org.nd4j.samediff.frameworkimport.rule.MappingRule import org.nd4j.samediff.frameworkimport.rule.attribute.AttributeValueType import org.nd4j.samediff.frameworkimport.rule.attribute.ConditionalFieldValueIntIndexArrayRule import org.nd4j.samediff.frameworkimport.tensorflow.ir.TensorflowIRAttr import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowAttributeName import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowTensorName import org.nd4j.samediff.frameworkimport.tensorflow.ir.tensorflowAttributeValueTypeFor import org.tensorflow.framework.* @MappingRule("tensorflow","conditionalfieldvalueintindex","attribute") class TensorflowConditionalFieldValueIntIndexArrayRule (mappingNamesToPerform: Map<String, String>, transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>>) : ConditionalFieldValueIntIndexArrayRule<GraphDef, OpDef, NodeDef, OpDef.AttrDef, AttrValue, TensorProto, DataType> (mappingNamesToPerform, transformerArgs) { override fun createIRAttribute(name: String, attrDef: OpDef.AttrDef, attributeValueType: AttrValue): IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType> { return TensorflowIRAttr(attrDef, attributeValueType) } override fun convertAttributesReverse(allInputArguments: List<OpNamespace.ArgDescriptor>, inputArgumentsToProcess: List<OpNamespace.ArgDescriptor>): List<IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType>> { TODO("Not yet implemented") } override fun isInputFrameworkTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return isTensorflowTensorName(name, opDef) } override fun isNd4jTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return isNd4jTensorName(name,nd4jOpDescriptor) } override fun isInputFrameworkAttributeName(name: String, mappingProcess: MappingProcess< GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType> ): Boolean { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return isTensorflowAttributeName(name, opDef) } override fun isOutputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return isOutputFrameworkAttributeName(name,nd4jOpDescriptor) } override fun argDescriptorType(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): OpNamespace.ArgDescriptor.ArgType { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return argDescriptorType(name,nd4jOpDescriptor) } override fun attributeValueTypeFor(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): AttributeValueType { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return tensorflowAttributeValueTypeFor(attributeName = name, opDef = opDef) } }
apache-2.0
773a6389276e0ff4f1b8e8a416ec6308
56.47191
221
0.768088
4.999022
false
false
false
false
sirdesmond/changecalculator
calculator-service/src/test/kotlin/sirdesmond/service/CalculatorServiceSpec.kt
1
3944
package sirdesmond.service import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.assertj.core.api.Assertions import org.jetbrains.spek.api.SubjectSpek import org.jetbrains.spek.api.dsl.it import sirdesmond.domain.Coin import sirdesmond.domain.Response import sirdesmond.domain.USCoin import sirdesmond.domain.allUSCoinsValues import sirdesmond.services.CalculatorService import sirdesmond.services.toResponse import kotlin.test.assertFailsWith /** * Created by kofikyei on 11/16/16. */ class CalculatorServiceSpec : SubjectSpek<CalculatorService>({ subject { CalculatorService() } it("should not calculate change if amount is less than a penny"){ assertFailsWith<IllegalArgumentException> { subject.optimalChange(-1.00, allUSCoinsValues) } } it("should fail if amount is smaller than smallest coin"){ assertFailsWith<IllegalArgumentException> { subject.dpMakeChange(0.03,setOf(5,10)) } } it("should calculate change with single coin") { Assertions.assertThat(subject.dpMakeChange(0.25,setOf(1, 5, 10, 25, 100))).containsExactly(25) } it("should calculate change with multiple coin") { Assertions.assertThat(subject.dpMakeChange(0.15,setOf(1, 5, 10, 25, 100))).containsExactly(5, 10) } it("should calculate change for some crazy set of coins") { Assertions.assertThat(subject.dpMakeChange(0.23,setOf(1, 4, 15, 20, 50))).containsExactly(4, 4, 15) } it("should calculate change for some seriously crazy set of coins") { Assertions.assertThat(subject.dpMakeChange(0.63,setOf(1, 5, 10, 21, 25))).containsExactly(21,21,21) } it("should convert list of coins to response"){ val coins = listOf<Coin>( USCoin.SilverDollar, USCoin.SilverDollar, USCoin.SilverDollar, USCoin.SilverDollar, USCoin.SilverDollar, USCoin.SilverDollar, USCoin.SilverDollar, USCoin.SilverDollar, USCoin.SilverDollar, USCoin.SilverDollar, USCoin.SilverDollar, USCoin.SilverDollar, USCoin.HalfDollar, USCoin.Quarter, USCoin.Dime ) val expectedResponse = Response( silver_dollar = 12, half_dollar = 1, quarter = 1, dime = 1, nickel = 0, penny = 0 ) assertThat(coins.toResponse().get(), equalTo(expectedResponse)) } it("should return optimal change for whole dollars"){ val expectedResponse = Response( silver_dollar = 10 ) assertThat(subject.optimalChange(10.00, allUSCoinsValues).get(), equalTo(expectedResponse)) } it("should return optimal change for really small values"){ val expectedResponse = Response( silver_dollar = 0, half_dollar = 1, quarter = 1, dime = 2, nickel = 0, penny = 4 ) assertThat(subject.optimalChange(0.99, allUSCoinsValues).get(), equalTo(expectedResponse)) } it("should return optimal change for simple fractions"){ val expectedResponse = Response( silver_dollar = 1, half_dollar = 1, quarter = 0, dime = 0, nickel = 1, penny = 1 ) assertThat(subject.optimalChange(1.56, allUSCoinsValues).get(), equalTo(expectedResponse)) } it("should return optimal change for bigger fractions"){ val expectedResponse = Response( silver_dollar = 12, half_dollar = 1, quarter = 1, dime = 1, nickel = 0, penny = 0 ) assertThat(subject.optimalChange(12.85, allUSCoinsValues).get(), equalTo(expectedResponse)) } })
mit
f2c4d9fc4eb143775c042841f87f0f72
32.151261
107
0.617647
4.11691
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/AvatarView.kt
1
19077
package com.habitrpg.android.habitica.ui import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Matrix import android.graphics.PointF import android.graphics.Rect import android.graphics.RectF import android.graphics.drawable.Drawable import android.text.TextUtils import android.util.AttributeSet import android.widget.FrameLayout import android.widget.ImageView import androidx.core.graphics.drawable.toBitmap import androidx.core.view.marginStart import androidx.core.view.marginTop import coil.clear import coil.load import coil.target.ImageViewTarget import com.habitrpg.android.habitica.BuildConfig import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.extensions.dpToPx import com.habitrpg.android.habitica.helpers.AppConfigManager import com.habitrpg.android.habitica.models.Avatar import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils import io.reactivex.rxjava3.functions.Consumer import java.util.Date import java.util.EnumMap import java.util.concurrent.atomic.AtomicInteger class AvatarView : FrameLayout { private var showBackground = true private var showMount = true private var showPet = true private var showSleeping = true private var hasBackground: Boolean = false private var hasMount: Boolean = false private var hasPet: Boolean = false private val imageViewHolder = mutableListOf<ImageView>() private var avatar: Avatar? = null private var avatarRectF: RectF? = null private val avatarMatrix = Matrix() private val numberLayersInProcess = AtomicInteger(0) private var avatarImageConsumer: Consumer<Bitmap?>? = null private var avatarBitmap: Bitmap? = null private var avatarCanvas: Canvas? = null private var currentLayers: Map<LayerType, String>? = null private val layerMap: Map<LayerType, String> get() { val avatar = this.avatar ?: return emptyMap() return getLayerMap(avatar, true) } private var spriteSubstitutions: Map<String, Map<String, String>> = HashMap() get() { if (Date().time - (lastSubstitutionCheck?.time ?: 0) > 180000) { field = AppConfigManager(null).spriteSubstitutions() lastSubstitutionCheck = Date() } return field } private var lastSubstitutionCheck: Date? = null private val originalRect: Rect get() = if (showMount || showPet) FULL_HERO_RECT else if (showBackground) COMPACT_HERO_RECT else HERO_ONLY_RECT private val avatarImage: Bitmap? get() { if (BuildConfig.DEBUG && (avatar == null || avatarRectF == null)) { error("Assertion failed") } val canvasRect = Rect(0, 0, 140.dpToPx(context), 147.dpToPx(context)) if (canvasRect.isEmpty) return null avatarBitmap = Bitmap.createBitmap(canvasRect.width(), canvasRect.height(), Bitmap.Config.ARGB_8888) avatarBitmap?.let { avatarCanvas = Canvas(it) } imageViewHolder.forEach { val lp = it.layoutParams val bitmap = it.drawable?.toBitmap(lp.width, lp.height) ?: return@forEach avatarCanvas?.drawBitmap(bitmap, Rect(0, 0, bitmap.width, bitmap.height), Rect(it.marginStart, it.marginTop, bitmap.width, bitmap.height), null) } return avatarBitmap } constructor(context: Context) : super(context) { init(null, 0) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(attrs, 0) } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { init(attrs, defStyle) } constructor(context: Context, showBackground: Boolean, showMount: Boolean, showPet: Boolean) : super(context) { this.showBackground = showBackground this.showMount = showMount this.showPet = showPet } private fun init(attrs: AttributeSet?, defStyle: Int) { // Load attributes val a = context.obtainStyledAttributes( attrs, R.styleable.AvatarView, defStyle, 0 ) try { showBackground = a.getBoolean(R.styleable.AvatarView_showBackground, true) showMount = a.getBoolean(R.styleable.AvatarView_showMount, true) showPet = a.getBoolean(R.styleable.AvatarView_showPet, true) showSleeping = a.getBoolean(R.styleable.AvatarView_showSleeping, true) } finally { a.recycle() } setWillNotDraw(false) } private fun showLayers(layerMap: Map<LayerType, String>) { var i = 0 currentLayers = layerMap numberLayersInProcess.set(layerMap.size) for ((layerKey, layerName) in layerMap) { val layerNumber = i++ val imageView = if (imageViewHolder.size <= layerNumber) { val newImageView = ImageView(context) newImageView.scaleType = ImageView.ScaleType.MATRIX addView(newImageView) imageViewHolder.add(newImageView) newImageView } else { imageViewHolder[layerNumber] } if (imageView.tag == layerName) { continue } imageView.tag = layerName imageView.clear() imageView.setImageResource(0) imageView.load(DataBindingUtils.BASE_IMAGE_URL + DataBindingUtils.getFullFilename(layerName)) { allowHardware(false) target(object : ImageViewTarget(imageView) { override fun onError(error: Drawable?) { super.onError(error) onLayerComplete() } override fun onSuccess(result: Drawable) { super.onSuccess(result) val bounds = getLayerBounds(layerKey, layerName, result) imageView.imageMatrix = avatarMatrix val layoutParams = imageView.layoutParams as? LayoutParams layoutParams?.topMargin = bounds.top layoutParams?.marginStart = bounds.left layoutParams?.width = bounds.right layoutParams?.height = bounds.bottom imageView.layoutParams = layoutParams onLayerComplete() } }) } } while (i < (imageViewHolder.size)) { imageViewHolder[i].clear() imageViewHolder[i].setImageResource(0) imageViewHolder[i].tag = null i++ } } private fun getLayerMap(avatar: Avatar, resetHasAttributes: Boolean): Map<LayerType, String> { val layerMap = getAvatarLayerMap(avatar, spriteSubstitutions) if (resetHasAttributes) { hasPet = false hasMount = hasPet hasBackground = hasMount } var mountName = avatar.currentMount if (showMount && mountName?.isNotEmpty() == true) { mountName = substituteOrReturn(spriteSubstitutions["mounts"], mountName) layerMap[LayerType.MOUNT_BODY] = "Mount_Body_$mountName" layerMap[LayerType.MOUNT_HEAD] = "Mount_Head_$mountName" if (resetHasAttributes) hasMount = true } var petName = avatar.currentPet if (showPet && petName?.isNotEmpty() == true) { petName = substituteOrReturn(spriteSubstitutions["pets"], petName) layerMap[LayerType.PET] = "Pet-$petName" if (resetHasAttributes) hasPet = true } var backgroundName = avatar.preferences?.background if (showBackground && backgroundName?.isNotEmpty() == true) { backgroundName = substituteOrReturn(spriteSubstitutions["backgrounds"], backgroundName) layerMap[LayerType.BACKGROUND] = "background_$backgroundName" if (resetHasAttributes) hasBackground = true } if (showSleeping && avatar.sleep) { layerMap[LayerType.ZZZ] = "zzz" } return layerMap } private fun substituteOrReturn(substitutions: Map<String, String>?, name: String): String { for (key in substitutions?.keys ?: arrayListOf()) { if (name.contains(key)) { return substitutions?.get(key) ?: name } } return name } @Suppress("ReturnCount") private fun getAvatarLayerMap(avatar: Avatar, substitutions: Map<String, Map<String, String>>): EnumMap<LayerType, String> { val layerMap = EnumMap<LayerType, String>(LayerType::class.java) if (!avatar.isValid()) { return layerMap } val prefs = avatar.preferences ?: return layerMap val outfit = if (prefs.costume) { avatar.costume } else { avatar.equipped } var hasVisualBuffs = false avatar.stats?.buffs?.let { buffs -> if (buffs.snowball == true) { layerMap[LayerType.VISUAL_BUFF] = "avatar_snowball_" + avatar.stats?.habitClass hasVisualBuffs = true } if (buffs.seafoam == true) { layerMap[LayerType.VISUAL_BUFF] = "seafoam_star" hasVisualBuffs = true } if (buffs.shinySeed == true) { layerMap[LayerType.VISUAL_BUFF] = "avatar_floral_" + avatar.stats?.habitClass hasVisualBuffs = true } if (buffs.spookySparkles == true) { layerMap[LayerType.VISUAL_BUFF] = "ghost" hasVisualBuffs = true } } val substitutedVisualBuff = substitutions["visualBuff"]?.get("full") if (substitutedVisualBuff != null) { layerMap[LayerType.VISUAL_BUFF] = substitutedVisualBuff hasVisualBuffs = true } val hair = prefs.hair if (!hasVisualBuffs) { if (!TextUtils.isEmpty(prefs.chair)) { layerMap[LayerType.CHAIR] = prefs.chair } if (outfit != null) { if (!TextUtils.isEmpty(outfit.back) && "back_base_0" != outfit.back) { layerMap[LayerType.BACK] = outfit.back } if (outfit.isAvailable(outfit.armor)) { layerMap[LayerType.ARMOR] = prefs.size + "_" + outfit.armor } if (outfit.isAvailable(outfit.body)) { layerMap[LayerType.BODY] = outfit.body } if (outfit.isAvailable(outfit.eyeWear)) { layerMap[LayerType.EYEWEAR] = outfit.eyeWear } if (outfit.isAvailable(outfit.head)) { layerMap[LayerType.HEAD] = outfit.head } if (outfit.isAvailable(outfit.headAccessory)) { layerMap[LayerType.HEAD_ACCESSORY] = outfit.headAccessory } if (outfit.isAvailable(outfit.shield)) { layerMap[LayerType.SHIELD] = outfit.shield } if (outfit.isAvailable(outfit.weapon)) { layerMap[LayerType.WEAPON] = outfit.weapon } } layerMap[LayerType.SKIN] = "skin_" + prefs.skin + if (prefs.sleep) "_sleep" else "" layerMap[LayerType.SHIRT] = prefs.size + "_shirt_" + prefs.shirt layerMap[LayerType.HEAD_0] = "head_0" if (hair != null) { val hairColor = hair.color if (hair.isAvailable(hair.base)) { layerMap[LayerType.HAIR_BASE] = "hair_base_" + hair.base + "_" + hairColor } if (hair.isAvailable(hair.bangs)) { layerMap[LayerType.HAIR_BANGS] = "hair_bangs_" + hair.bangs + "_" + hairColor } if (hair.isAvailable(hair.mustache)) { layerMap[LayerType.HAIR_MUSTACHE] = "hair_mustache_" + hair.mustache + "_" + hairColor } if (hair.isAvailable(hair.beard)) { layerMap[LayerType.HAIR_BEARD] = "hair_beard_" + hair.beard + "_" + hairColor } } } if (hair != null && hair.isAvailable(hair.flower)) { layerMap[LayerType.HAIR_FLOWER] = "hair_flower_" + hair.flower } return layerMap } private fun getLayerBounds(layerType: LayerType, layerName: String, drawable: Drawable): Rect { var offset: PointF? = null val bounds = Rect(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight) val boundsF = RectF(bounds) // lookup layer specific offset when (layerName) { "weapon_special_critical" -> offset = if (showMount || showPet) { // full hero box when { hasMount -> PointF(13.0f, 12.0f) hasPet -> PointF(13.0f, 24.5f + 12.0f) else -> PointF(13.0f, 28.0f + 12.0f) } } else if (showBackground) { // compact hero box PointF(-12.0f, 18.0f + 12.0f) } else { // hero only box PointF(-12.0f, 12.0f) } } // otherwise lookup default layer type based offset if (offset == null) { when (layerType) { LayerType.BACKGROUND -> if (!(showMount || showPet)) { offset = PointF(-25.0f, 0.0f) // compact hero box } LayerType.MOUNT_BODY, LayerType.MOUNT_HEAD -> offset = PointF(25.0f, 18.0f) // full hero box LayerType.CHAIR, LayerType.BACK, LayerType.SKIN, LayerType.SHIRT, LayerType.ARMOR, LayerType.BODY, LayerType.HEAD_0, LayerType.HAIR_BASE, LayerType.HAIR_BANGS, LayerType.HAIR_MUSTACHE, LayerType.HAIR_BEARD, LayerType.EYEWEAR, LayerType.VISUAL_BUFF, LayerType.HEAD, LayerType.HEAD_ACCESSORY, LayerType.HAIR_FLOWER, LayerType.SHIELD, LayerType.WEAPON, LayerType.ZZZ -> if (showMount || showPet) { // full hero box offset = when { hasMount -> if (layerMap[LayerType.MOUNT_HEAD]?.contains("Kangaroo") == true) { PointF(25.0f, 18f) } else { PointF(25.0f, 0f) } hasPet -> PointF(25.0f, 24.5f) else -> PointF(25.0f, 28.0f) } } else if (showBackground) { // compact hero box offset = PointF(0.0f, 18.0f) } LayerType.PET -> offset = PointF(0f, (FULL_HERO_RECT.height() - bounds.height()).toFloat()) } } if (offset != null) { when (layerName) { "head_special_0" -> offset = PointF(offset.x - 3, offset.y - 18) "weapon_special_0" -> offset = PointF(offset.x - 12, offset.y + 4) "weapon_special_1" -> offset = PointF(offset.x - 12, offset.y + 4) "weapon_special_critical" -> offset = PointF(offset.x - 12, offset.y + 4) "head_special_1" -> offset = PointF(offset.x, offset.y + 3) } val translateMatrix = Matrix() translateMatrix.setTranslate(offset.x, offset.y) translateMatrix.mapRect(boundsF) } // resize bounds to fit and keep original aspect ratio avatarMatrix.mapRect(boundsF) boundsF.round(bounds) return bounds } private fun onLayerComplete() { if (numberLayersInProcess.decrementAndGet() == 0) { avatarImageConsumer?.accept(avatarImage) } } fun onAvatarImageReady(consumer: Consumer<Bitmap?>) { avatarImageConsumer = consumer if (imageViewHolder.size > 0 && numberLayersInProcess.get() == 0) { avatarImageConsumer?.accept(avatarImage) } else { initAvatarRectMatrix() showLayers(layerMap) } } fun setAvatar(avatar: Avatar) { val oldUser = this.avatar this.avatar = avatar var equals = false if (oldUser != null) { val newLayerMap = getLayerMap(avatar, false) equals = currentLayers == newLayerMap } if (!equals) { invalidate() } } private fun initAvatarRectMatrix() { if (avatarRectF == null) { val srcRect = originalRect // full hero box when showMount and showPet is enabled (140w * 147h) // compact hero box when only showBackground is enabled (114w * 114h) // hero only box when all show settings disabled (90w * 90h) val width = if (this.width > 0) this.width.toFloat() else 140.dpToPx(context).toFloat() val height = if (this.height > 0) this.height.toFloat() else 147.dpToPx(context).toFloat() avatarRectF = RectF(0f, 0f, width, height) avatarMatrix.setRectToRect(RectF(srcRect), avatarRectF, Matrix.ScaleToFit.START) avatarRectF = RectF(srcRect) avatarMatrix.mapRect(avatarRectF) } } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) initAvatarRectMatrix() // draw only when user is set if (avatar?.isValid() != true) return showLayers(layerMap) } override fun invalidateDrawable(drawable: Drawable) { invalidate() if (avatarCanvas != null) draw(avatarCanvas) } enum class LayerType { BACKGROUND, MOUNT_BODY, CHAIR, BACK, SKIN, SHIRT, ARMOR, BODY, HEAD_0, HAIR_BASE, HAIR_BANGS, HAIR_MUSTACHE, HAIR_BEARD, EYEWEAR, VISUAL_BUFF, HEAD, HEAD_ACCESSORY, HAIR_FLOWER, SHIELD, WEAPON, MOUNT_HEAD, ZZZ, PET } companion object { private val FULL_HERO_RECT = Rect(0, 0, 140, 147) private val COMPACT_HERO_RECT = Rect(0, 0, 114, 114) private val HERO_ONLY_RECT = Rect(0, 0, 90, 90) } }
gpl-3.0
c9984d1736305028255731112fc3b33d
36.230461
410
0.55449
4.549726
false
false
false
false
jorjoluiso/QuijoteLui
src/main/kotlin/com/quijotelui/controller/ElectronicoRestApi.kt
1
1159
package com.quijotelui.controller import com.quijotelui.model.Electronico import com.quijotelui.service.IElectronicoService import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* @RestController @RequestMapping("/rest/v1") class ElectronicoRestApi { @Autowired lateinit var electronicoService : IElectronicoService @CrossOrigin(value = "*") @GetMapping("/electronico/codigo/{codigo}/numero/{numero}") fun getElectronico(@PathVariable(value = "codigo") codigo : String, @PathVariable(value = "numero") numero : String) : ResponseEntity<MutableList<Electronico>> { if (codigo == null || numero == null) { return ResponseEntity(HttpStatus.CONFLICT) } val electronico = electronicoService.findByComprobante(codigo, numero) if (electronico.isEmpty()) { return ResponseEntity(HttpStatus.NOT_FOUND) } return ResponseEntity<MutableList<Electronico>>(electronico, HttpStatus.OK) } }
gpl-3.0
4c2eda619a18e22ecb67c1407b5a71d7
31.222222
83
0.714409
4.599206
false
false
false
false
yzbzz/beautifullife
icore/src/main/java/com/ddu/icore/ui/DefaultBindingFragment.kt
2
2835
package com.ddu.icore.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import com.ddu.icore.R import com.ddu.icore.common.ext.act import com.ddu.icore.ui.fragment.BaseBindingFragment import com.ddu.icore.ui.widget.TitleBar abstract class DefaultBindingFragment<T : ViewDataBinding> : BaseBindingFragment() { protected lateinit var mView: View var titleBar: TitleBar? = null protected set protected var mCustomerTitleBar: View? = null abstract fun getLayoutId(): Int lateinit var dataBinding: T override fun getContentView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val layoutId = getLayoutId() if (isShowTitleBar()) { dataBinding = DataBindingUtil.inflate(inflater, R.layout.i_activity_base, container, false) mView = dataBinding.root titleBar = mView.findViewById(R.id.ll_title_bar) inflater.inflate(layoutId, mView as ViewGroup, true) } else { dataBinding = DataBindingUtil.inflate(inflater, layoutId, container, false) mView = dataBinding.root } return mView } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initView() } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) } abstract fun initView() fun setTitle(resId: Int) { if (null != titleBar) { titleBar!!.setMiddleText(resId) } } fun setTitle(title: String) { if (null != titleBar) { titleBar!!.setMiddleText(title) } } fun setDefaultTitle(resId: Int) { if (null != titleBar) { titleBar!!.setDefaultTitle(resId) { act.onBackPressed() } } } fun setDefaultTitle(title: String) { if (null != titleBar) { titleBar!!.setDefaultTitle(title) { act.onBackPressed() } } } fun setRightText(text: String, onClickListener: View.OnClickListener) { if (null != titleBar) { titleBar!!.setRightText(text, onClickListener) } } fun setRightImg(resId: Int, onClickListener: View.OnClickListener) { if (null != titleBar) { titleBar!!.setRightImg(resId, onClickListener) } } fun setTitleBarOnClickListener(onClickListener: View.OnClickListener) { if (null != titleBar) { titleBar!!.setOnClickListener(onClickListener) } } companion object { const val ARGUMENT_TASK_ID = "ARGUMENT_TASK_ID" } }
apache-2.0
011da4e3048a863c09ba0169f35f66aa
27.928571
118
0.651146
4.709302
false
false
false
false
arcuri82/testing_security_development_enterprise_systems
advanced/security/distributed-session/ds-auth/src/main/kotlin/org/tsdes/advanced/security/distributedsession/auth/RestApi.kt
1
3076
package org.tsdes.advanced.security.distributedsession.auth import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.Authentication import org.springframework.security.core.authority.AuthorityUtils import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.core.userdetails.UsernameNotFoundException import org.springframework.web.bind.annotation.* import org.tsdes.advanced.security.distributedsession.auth.db.UserService import java.security.Principal /** * Created by arcuri82 on 08-Nov-17. */ @RestController class RestApi( private val service: UserService, private val authenticationManager: AuthenticationManager, private val userDetailsService: UserDetailsService ) { @RequestMapping("/user") fun user(user: Principal): ResponseEntity<Map<String, Any>> { val map = mutableMapOf<String,Any>() map["name"] = user.name map["roles"] = AuthorityUtils.authorityListToSet((user as Authentication).authorities) return ResponseEntity.ok(map) } @PostMapping(path = ["/signUp"], consumes = [(MediaType.APPLICATION_JSON_UTF8_VALUE)]) fun signIn(@RequestBody dto: AuthDto) : ResponseEntity<Void> { val userId : String = dto.userId!! val password : String = dto.password!! val registered = service.createUser(userId, password, setOf("USER")) if (!registered) { return ResponseEntity.status(400).build() } val userDetails = userDetailsService.loadUserByUsername(userId) val token = UsernamePasswordAuthenticationToken(userDetails, password, userDetails.authorities) authenticationManager.authenticate(token) if (token.isAuthenticated) { SecurityContextHolder.getContext().authentication = token } return ResponseEntity.status(204).build() } @PostMapping(path = ["/login"], consumes = [(MediaType.APPLICATION_JSON_UTF8_VALUE)]) fun login(@RequestBody dto: AuthDto) : ResponseEntity<Void> { val userId : String = dto.userId!! val password : String = dto.password!! val userDetails = try{ userDetailsService.loadUserByUsername(userId) } catch (e: UsernameNotFoundException){ return ResponseEntity.status(400).build() } val token = UsernamePasswordAuthenticationToken(userDetails, password, userDetails.authorities) authenticationManager.authenticate(token) if (token.isAuthenticated) { SecurityContextHolder.getContext().authentication = token return ResponseEntity.status(204).build() } return ResponseEntity.status(400).build() } }
lgpl-3.0
1c90ee7da425cc9df25a5027901d8813
34.77907
103
0.713264
5.204738
false
false
false
false
androidx/androidx
paging/paging-rxjava2/src/main/java/androidx/paging/rxjava2/RxRemoteMediator.kt
3
4763
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.paging.rxjava2 import androidx.paging.ExperimentalPagingApi import androidx.paging.LoadState import androidx.paging.LoadType import androidx.paging.LoadType.APPEND import androidx.paging.LoadType.PREPEND import androidx.paging.LoadType.REFRESH import androidx.paging.PagingData import androidx.paging.PagingSource import androidx.paging.PagingState import androidx.paging.RemoteMediator import androidx.paging.RemoteMediator.InitializeAction import androidx.paging.RemoteMediator.InitializeAction.LAUNCH_INITIAL_REFRESH import androidx.paging.RemoteMediator.MediatorResult import io.reactivex.Single import kotlinx.coroutines.rx2.await /** * RxJava2 compatibility wrapper around [RemoteMediator]'s suspending APIs. */ @ExperimentalPagingApi abstract class RxRemoteMediator<Key : Any, Value : Any> : RemoteMediator<Key, Value>() { /** * Implement this method to load additional remote data, which will then be stored for the * [PagingSource] to access. These loads take one of two forms: * * type == [LoadType.PREPEND] / [LoadType.APPEND] * The [PagingSource] has loaded a 'boundary' page, with a `null` adjacent key. This means * this method should load additional remote data to append / prepend as appropriate, and store * it locally. * * type == [LoadType.REFRESH] * The app (or [initialize]) has requested a remote refresh of data. This means the method * should generally load remote data, and **replace** all local data. * * The runtime of this method defines loading state behavior in boundary conditions, which * affects e.g., [LoadState] callbacks registered to [androidx.paging.PagingDataAdapter]. * * NOTE: A [PagingSource.load] request which is fulfilled by a page that hits a boundary * condition in either direction will trigger this callback with [LoadType.PREPEND] or * [LoadType.APPEND] or both. [LoadType.REFRESH] occurs as a result of [initialize]. * * @param loadType [LoadType] of the boundary condition which triggered this callback. * * [LoadType.PREPEND] indicates a boundary condition at the front of the list. * * [LoadType.APPEND] indicates a boundary condition at the end of the list. * * [LoadType.REFRESH] indicates this callback was triggered as the result of a requested * refresh - either driven by the UI, or by [initialize]. * @param state A copy of the state including the list of pages currently held in * memory of the currently presented [PagingData] at the time of starting the load. E.g. for * load(loadType = END), you can use the page or item at the end as input for what to load from * the network. * * @return [MediatorResult] signifying what [LoadState] to be passed to the UI, and whether * there's more data available. */ abstract fun loadSingle( loadType: LoadType, state: PagingState<Key, Value> ): Single<MediatorResult> /** * Callback fired during initialization of a [PagingData] stream, before initial load. * * This function runs to completion before any loading is performed. * * @return [InitializeAction] indicating the action to take after initialization: * * [LAUNCH_INITIAL_REFRESH] to immediately dispatch a [load] asynchronously with load type * [LoadType.REFRESH], to update paginated content when the stream is initialized. * Note: This also prevents [RemoteMediator] from triggering [PREPEND] or [APPEND] until * [REFRESH] succeeds. * * [SKIP_INITIAL_REFRESH][InitializeAction.SKIP_INITIAL_REFRESH] to wait for a * refresh request from the UI before dispatching a [load] with load type [LoadType.REFRESH]. */ open fun initializeSingle(): Single<InitializeAction> = Single.just(LAUNCH_INITIAL_REFRESH) final override suspend fun load(loadType: LoadType, state: PagingState<Key, Value>): MediatorResult { return loadSingle(loadType, state).await() } final override suspend fun initialize(): InitializeAction { return initializeSingle().await() } }
apache-2.0
c6b97630386d1eaf90f0dd34e8809950
47.121212
100
0.727063
4.463918
false
false
false
false
androidx/androidx
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/layout/OnPlacedModifier.kt
3
2884
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.layout import androidx.compose.runtime.Stable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.InspectorInfo import androidx.compose.ui.platform.InspectorValueInfo import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.internal.JvmDefaultWithCompatibility /** * Invoke [onPlaced] after the parent [LayoutModifier] and parent layout has been placed and before * child [LayoutModifier] is placed. This allows child [LayoutModifier] to adjust its * own placement based on where the parent is. * * @sample androidx.compose.ui.samples.OnPlaced */ @Stable fun Modifier.onPlaced( onPlaced: (LayoutCoordinates) -> Unit ) = this.then( OnPlacedModifierImpl( callback = onPlaced, inspectorInfo = debugInspectorInfo { name = "onPlaced" properties["onPlaced"] = onPlaced } ) ) private class OnPlacedModifierImpl( val callback: (LayoutCoordinates) -> Unit, inspectorInfo: InspectorInfo.() -> Unit ) : OnPlacedModifier, InspectorValueInfo(inspectorInfo) { override fun onPlaced(coordinates: LayoutCoordinates) { callback(coordinates) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is OnPlacedModifierImpl) return false return callback == other.callback } override fun hashCode(): Int { return callback.hashCode() } } /** * A modifier whose [onPlaced] is called after the parent [LayoutModifier] and parent layout has * been placed and before child [LayoutModifier] is placed. This allows child * [LayoutModifier] to adjust its own placement based on where the parent is. * * @sample androidx.compose.ui.samples.OnPlaced */ @JvmDefaultWithCompatibility interface OnPlacedModifier : Modifier.Element { /** * [onPlaced] is called after parent [LayoutModifier] and parent layout gets placed and * before any child [LayoutModifier] is placed. * * [coordinates] provides [LayoutCoordinates] of the [OnPlacedModifier]. Placement in both * parent [LayoutModifier] and parent layout can be calculated using the [LayoutCoordinates]. */ fun onPlaced(coordinates: LayoutCoordinates) }
apache-2.0
ff0abe25f1cc3534c48a9aaf7567a378
33.345238
99
0.728502
4.416539
false
false
false
false
androidx/androidx
benchmark/benchmark-common/src/androidTest/java/androidx/benchmark/PerfettoTraceTest.kt
3
2557
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.benchmark import androidx.benchmark.perfetto.ExperimentalPerfettoCaptureApi import androidx.benchmark.perfetto.PerfettoHelper import androidx.benchmark.perfetto.PerfettoTrace import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.filters.SdkSuppress import kotlin.test.assertFailsWith import kotlin.test.assertNotNull import kotlin.test.fail import org.junit.Assume.assumeTrue import org.junit.Test import org.junit.runner.RunWith @OptIn(ExperimentalPerfettoCaptureApi::class) @LargeTest @RunWith(AndroidJUnit4::class) @SdkSuppress(minSdkVersion = 21) class PerfettoTraceTest { @Test fun record_basic() { assumeTrue(PerfettoHelper.isAbiSupported()) var perfettoTrace: PerfettoTrace? = null PerfettoTrace.record( fileLabel = "testTrace", traceCallback = { trace -> perfettoTrace = trace } ) { // noop } assertNotNull(perfettoTrace) assert(perfettoTrace!!.path.matches(Regex(".*/testTrace_[0-9-]+.perfetto-trace"))) { "$perfettoTrace didn't match!" } } @Test fun record_reentrant() { assumeTrue(PerfettoHelper.isAbiSupported()) var perfettoTrace: PerfettoTrace? = null PerfettoTrace.record( fileLabel = "outer", traceCallback = { trace -> perfettoTrace = trace } ) { // tracing while tracing should fail assertFailsWith<IllegalStateException> { PerfettoTrace.record( fileLabel = "inner", traceCallback = { _ -> fail("inner trace should not complete / record") } ) { // noop } } } assertNotNull(perfettoTrace) } }
apache-2.0
3b89f8428ae8bde2b22bfc82004d50df
31.782051
92
0.640203
4.674589
false
true
false
false
Omico/CurrentActivity
build-logic/convention/src/main/kotlin/SigningConfigs.kt
1
1797
@file:Suppress("UnstableApiUsage") import com.android.build.api.dsl.ApplicationExtension import me.omico.age.dsl.configure import me.omico.age.dsl.localProperties import me.omico.age.dsl.withAndroidApplication import org.gradle.api.Project import java.io.File import java.util.Properties fun Project.configureAppSigningConfigsForRelease( properties: Properties = localProperties, ) = withAndroidApplication { if (hasNullSigningConfigProperties(properties)) return@withAndroidApplication configure<ApplicationExtension>("android") { signingConfigs { create("release") { storeFile = file(properties["store.file"] as String) storePassword = properties["store.password"] as String keyAlias = properties["key.alias"] as String keyPassword = properties["key.password"] as String } } buildTypes { release { signingConfig = signingConfigs.findByName("release") } } } } fun Project.hasNullSigningConfigProperties(properties: Properties): Boolean { val nullProperties = listOf("store.file", "store.password", "key.alias", "key.password") .mapNotNull { if (properties[it] == null) it else null } val hasNullProperties = nullProperties.isNotEmpty() if (hasNullProperties) logger.warn( "========================== Notice ==========================\n" + "You should set $nullProperties in your properties file. \n" + "Otherwise this signingConfig will not be applied.\n" + "The default properties file is ${rootDir}${File.separator}local.properties.\n" + "============================================================", ) return hasNullProperties }
gpl-3.0
54b3ccb11587319c2edbc24448fcbfda
39.840909
93
0.624374
4.728947
false
true
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/sponge/inspection/SpongePluginClassInspection.kt
1
5039
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.sponge.inspection import com.demonwav.mcdev.platform.sponge.SpongeModuleType import com.demonwav.mcdev.platform.sponge.util.SpongeConstants import com.demonwav.mcdev.platform.sponge.util.isSpongePluginClass import com.demonwav.mcdev.util.constantStringValue import com.intellij.codeInsight.daemon.impl.quickfix.AddDefaultConstructorFix import com.intellij.codeInsight.daemon.impl.quickfix.ModifierFix import com.intellij.codeInsight.intention.QuickFixFactory import com.intellij.codeInspection.AbstractBaseJavaLocalInspectionTool import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.lang.jvm.JvmModifier import com.intellij.psi.JavaElementVisitor import com.intellij.psi.PsiClass import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiFile import com.intellij.psi.PsiModifier class SpongePluginClassInspection : AbstractBaseJavaLocalInspectionTool() { override fun getStaticDescription() = "Checks the plugin class is valid." override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return if (SpongeModuleType.isInModule(holder.file)) { Visitor(holder) } else { PsiElementVisitor.EMPTY_VISITOR } } override fun processFile(file: PsiFile, manager: InspectionManager): List<ProblemDescriptor> { return if (SpongeModuleType.isInModule(file)) { super.processFile(file, manager) } else { emptyList() } } class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() { override fun visitClass(aClass: PsiClass) { if (!aClass.isSpongePluginClass()) { return } val ctorInjectAnnos = aClass.constructors.mapNotNull { val annotation = it.getAnnotation(SpongeConstants.INJECT_ANNOTATION) ?: return@mapNotNull null it to annotation } if (ctorInjectAnnos.size > 1) { val quickFixFactory = QuickFixFactory.getInstance() ctorInjectAnnos.forEach { (injectedMethod, injectAnno) -> holder.registerProblem( injectAnno, "There can only be one injected constructor.", quickFixFactory.createDeleteFix(injectAnno, "Remove this @Inject"), quickFixFactory.createDeleteFix(injectedMethod, "Remove this injected constructor") ) } } val hasInjectedCtor = ctorInjectAnnos.isNotEmpty() val emptyCtor = aClass.constructors.find { !it.hasParameters() } if (emptyCtor == null && !hasInjectedCtor && aClass.constructors.isNotEmpty()) { val classIdentifier = aClass.nameIdentifier if (classIdentifier != null) { holder.registerProblem( classIdentifier, "Plugin class must have an empty constructor or an @Inject constructor.", ProblemHighlightType.GENERIC_ERROR, AddDefaultConstructorFix(aClass) ) } } if (!hasInjectedCtor && emptyCtor != null && emptyCtor.hasModifier(JvmModifier.PRIVATE)) { val ctorIdentifier = emptyCtor.nameIdentifier if (ctorIdentifier != null) { holder.registerProblem( ctorIdentifier, "Plugin class empty constructor must not be private.", ProblemHighlightType.GENERIC_ERROR, ModifierFix(emptyCtor, PsiModifier.PACKAGE_LOCAL, true, false), ModifierFix(emptyCtor, PsiModifier.PROTECTED, true, false), ModifierFix(emptyCtor, PsiModifier.PUBLIC, true, false) ) } } val pluginAnnotation = aClass.getAnnotation(SpongeConstants.PLUGIN_ANNOTATION) ?: aClass.getAnnotation(SpongeConstants.JVM_PLUGIN_ANNOTATION) ?: return val pluginIdValue = pluginAnnotation.findAttributeValue("id") ?: return val pluginId = pluginIdValue.constantStringValue ?: return if (!SpongeConstants.ID_PATTERN.matcher(pluginId).matches()) { holder.registerProblem( pluginIdValue, "Plugin IDs should be lowercase, and only contain characters from a-z, dashes or underscores," + " start with a lowercase letter, and not exceed 64 characters." ) } } } }
mit
eca731421aad6115d1d150947a0072a8
42.439655
116
0.631871
5.507104
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/modules/plans/PlansPagerActivity.kt
2
4346
package ru.fantlab.android.ui.modules.plans import android.app.Application import android.app.Service import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import com.evernote.android.state.State import com.google.android.material.tabs.TabLayout import kotlinx.android.synthetic.main.appbar_tabbed_elevation.* import kotlinx.android.synthetic.main.tabbed_pager_layout.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.FragmentPagerAdapterModel import ru.fantlab.android.helper.BundleConstant import ru.fantlab.android.helper.Bundler import ru.fantlab.android.ui.adapter.FragmentsPagerAdapter import ru.fantlab.android.ui.base.BaseActivity import ru.fantlab.android.ui.base.BaseFragment import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter import ru.fantlab.android.ui.modules.plans.autplans.AutPlansFragment import ru.fantlab.android.ui.modules.plans.pubnews.PubnewsFragment import ru.fantlab.android.ui.modules.plans.pubplans.PubplansFragment class PlansPagerActivity : BaseActivity<PlansPagerMvp.View, BasePresenter<PlansPagerMvp.View>>(), PlansPagerMvp.View { @State var index: Int = 0 override fun layout(): Int = R.layout.tabbed_pager_layout override fun isTransparent(): Boolean = true override fun canBack(): Boolean = true override fun providePresenter(): BasePresenter<PlansPagerMvp.View> = BasePresenter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { index = intent?.extras?.getInt(BundleConstant.EXTRA, -1) ?: -1 } setTaskName(getString(R.string.plans)) title = getString(R.string.plans) selectMenuItem(R.id.plans, true) val adapter = FragmentsPagerAdapter( supportFragmentManager, FragmentPagerAdapterModel.buildForPlans(this) ) pager.adapter = adapter tabs.tabGravity = TabLayout.GRAVITY_FILL tabs.tabMode = TabLayout.MODE_SCROLLABLE tabs.setupWithViewPager(pager) if (savedInstanceState == null) { if (index != -1) { pager.currentItem = index } } tabs.addOnTabSelectedListener(object : TabLayout.ViewPagerOnTabSelectedListener(pager) { override fun onTabReselected(tab: TabLayout.Tab) { super.onTabReselected(tab) onScrollTop(tab.position) } }) fab.setImageResource(R.drawable.ic_filter) fab.show() fab.setOnClickListener { onFabClicked() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.plans_menu, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.sort -> { val fragment = pager.adapter?.instantiateItem(pager, pager.currentItem) when (pager.currentItem) { 0 -> { fragment as PubnewsFragment fragment.showSortDialog() } 1 -> { fragment as PubplansFragment fragment.showSortDialog() } 2 -> { fragment as AutPlansFragment fragment.showSortDialog() } } return true } } return super.onOptionsItemSelected(item) } override fun onScrollTop(index: Int) { if (pager.adapter == null) return val fragment = pager.adapter?.instantiateItem(pager, index) as? BaseFragment<*, *> if (fragment is BaseFragment) { fragment.onScrollTop(index) } } private fun onFabClicked() { when (pager.currentItem) { 0 -> { val fragment = pager.adapter?.instantiateItem(pager, pager.currentItem) as PubnewsFragment fragment.showFilterDialog() } 1 -> { val fragment = pager.adapter?.instantiateItem(pager, pager.currentItem) as PubplansFragment fragment.showFilterDialog() } 2 -> { val fragment = pager.adapter?.instantiateItem(pager, pager.currentItem) as AutPlansFragment fragment.showFilterDialog() } } } override fun onScrolled(isUp: Boolean) { if (isUp) { fab.hide() } else { fab.show() } } companion object { fun startActivity(context: Context, index: Int = -1) { val intent = Intent(context, PlansPagerActivity::class.java) intent.putExtras(Bundler.start() .put(BundleConstant.EXTRA, index) .end()) if (context is Service || context is Application) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } context.startActivity(intent) } } }
gpl-3.0
602d85b6754e2a2ba11eb49a6474574a
28.571429
97
0.739991
3.664418
false
false
false
false
CruGlobal/android-gto-support
gto-support-viewpager/src/main/kotlin/org/ccci/gto/android/common/viewpager/widget/SwipeRefreshLayoutViewPagerHelper.kt
2
1324
package org.ccci.gto.android.common.viewpager.widget import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import androidx.viewpager.widget.ViewPager import com.karumi.weak.weak class SwipeRefreshLayoutViewPagerHelper(layout: SwipeRefreshLayout? = null) : ViewPager.SimpleOnPageChangeListener() { var swipeRefreshLayout: SwipeRefreshLayout? by weak() init { swipeRefreshLayout = layout } private var _isRefreshing: Boolean? = null var isRefreshing: Boolean get() = _isRefreshing ?: swipeRefreshLayout?.isRefreshing ?: false set(value) { if (isIdle) { swipeRefreshLayout?.isRefreshing = value } else { _isRefreshing = value } } private var isIdle = true set(value) { if (value == field) return field = value _isRefreshing?.let { _isRefreshing = null isRefreshing = it } } override fun onPageScrollStateChanged(state: Int) { swipeRefreshLayout?.apply { when { state == ViewPager.SCROLL_STATE_IDLE -> isEnabled = true !isRefreshing -> isEnabled = false } } isIdle = state == ViewPager.SCROLL_STATE_IDLE } }
mit
64adad0dd6f82abe6f88a5f1700033e3
29.790698
118
0.594411
5.44856
false
false
false
false
Tvede-dk/CommonsenseAndroidKotlin
base/src/main/kotlin/com/commonsense/android/kotlin/base/Types.kt
1
990
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate") package com.commonsense.android.kotlin.base import kotlinx.coroutines.* /** * Created by kasper on 21/07/2017. */ typealias EmptyFunction = () -> Unit typealias EmptyReceiver<T> = T.() -> Unit typealias EmptyFunctionResult<T> = () -> T typealias AsyncEmptyFunction = suspend () -> Unit typealias AsyncFunctionUnit<T> = suspend (T) -> Unit typealias AsyncEmptyFunctionResult<T> = suspend () -> T /** * Function with 1 parameter that returns unit */ typealias FunctionUnit<E> = (E) -> Unit typealias FunctionResult<I, O> = (I) -> O typealias MapFunction<E, U> = (E) -> U typealias SuspendFunctionUnit<E> = suspend (E) -> Unit typealias FunctionBoolean<E> = (E) -> Boolean typealias StringList = List<String> /** * */ typealias AsyncCoroutineFunction = suspend CoroutineScope.() -> Unit /** * Function with 1 input and potential output * */ typealias AsyncFunction1<I1, O> = suspend (I1) -> O
mit
ac128eccafca87371a86c160ae062516
21.522727
77
0.70303
3.613139
false
false
true
false
TUWien/DocScan
app/src/main/java/at/ac/tuwien/caa/docscan/db/model/DocumentWithPages.kt
1
2619
package at.ac.tuwien.caa.docscan.db.model import android.os.Parcelable import androidx.annotation.Keep import androidx.room.Embedded import androidx.room.Ignore import androidx.room.Relation import at.ac.tuwien.caa.docscan.db.model.state.ExportState import at.ac.tuwien.caa.docscan.db.model.state.UploadState import at.ac.tuwien.caa.docscan.logic.NetworkStatus import kotlinx.parcelize.IgnoredOnParcel import kotlinx.parcelize.Parcelize @Keep @Parcelize data class DocumentWithPages( @Embedded val document: Document, @Relation( parentColumn = Document.KEY_ID, entityColumn = Page.KEY_DOC_ID ) var pages: List<Page> = listOf() ) : Parcelable { /** * An additional field to provide the current network status with the document, this is only * aggregated in some cases and needs to be done explicitly! */ @IgnoredOnParcel @Ignore var networkStatus: NetworkStatus = NetworkStatus.DISCONNECTED /** * An additional field to provide the doc with the info if the user has allowed uploads on metered networks. */ @IgnoredOnParcel @Ignore var hasUserAllowedMeteredNetwork: Boolean = false } fun DocumentWithPages.isProcessing(): Boolean { return pages.firstOrNull { page -> page.isProcessing() } != null } fun DocumentWithPages.isExporting(): Boolean { return pages.firstOrNull { page -> page.isExporting() } != null } fun DocumentWithPages.numberOfFinishedExports(): Int { return pages.count { page -> page.exportState == ExportState.DONE } } fun DocumentWithPages.numberOfFinishedUploads(): Int { return pages.count { page -> page.transkribusUpload.state == UploadState.UPLOADED } } /** * @return true if any of the pages is currently being uplodead. */ fun DocumentWithPages.isUploadInProgress(): Boolean { pages.forEach { page -> if (page.isUploadInProgress()) { return true } } return false } /** * @return true if any of the pages is currently being scheduled for upload. */ fun DocumentWithPages.isUploadScheduled(): Boolean { pages.forEach { page -> if (page.isUploadScheduled()) { return true } } return false } /** * @return true if all of the pages have been uploaded. */ fun DocumentWithPages.isUploaded(): Boolean { pages.forEach { page -> if (!page.isUploaded()) { return false } } return true } fun DocumentWithPages.isCropped(): Boolean { pages.forEach { page -> if (!page.isPostProcessed()) { return false } } return true }
lgpl-3.0
052d13ebe8a61c729a6de0036fc322ab
24.930693
112
0.684231
4.293443
false
false
false
false
CruGlobal/android-gto-support
gto-support-androidx-lifecycle/src/test/kotlin/org/ccci/gto/android/common/androidx/lifecycle/TransformationsCombineWithTest.kt
1
14049
package org.ccci.gto.android.common.androidx.lifecycle import androidx.lifecycle.MutableLiveData import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.contains import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify class TransformationsCombineWithTest : BaseLiveDataTest() { private val str1 = MutableLiveData<String>() private val str2 = MutableLiveData<String?>() private val str3 = MutableLiveData<String?>() private val str4 = MutableLiveData<String?>(null) private val str5 = MutableLiveData<String?>() private val str6 = MutableLiveData<String?>() // region switchCombine() & switchCombineWith() @Test fun `switchCombine() - 2 LiveDatas`() { val combined = switchCombine(str1, str2) { a, b -> MutableLiveData(listOfNotNull(a, b).joinToString()) } combined.observeForever(observer) verify(observer, never()).onChanged(any()) assertNull(combined.value) str1.value = "b" verify(observer, never()).onChanged(any()) assertNull(combined.value) str2.value = "c" verify(observer).onChanged(any()) assertEquals("b, c", combined.value) argumentCaptor<String> { verify(observer).onChanged(capture()) assertThat(allValues, contains("b, c")) } } @Test fun `switchCombineWith() - 2 LiveDatas`() { val combined = str1.switchCombineWith(str2) { a, b -> MutableLiveData(listOfNotNull(a, b).joinToString()) } combined.observeForever(observer) verify(observer, never()).onChanged(any()) assertNull(combined.value) str1.value = "b" verify(observer, never()).onChanged(any()) assertNull(combined.value) str2.value = "c" verify(observer).onChanged(any()) assertEquals("b, c", combined.value) argumentCaptor<String> { verify(observer).onChanged(capture()) assertThat(allValues, contains("b, c")) } } @Test fun verifySwitchCombineWithObserverCalledOnceOnInitialization() { str1.value = "a" str2.value = "b" str3.value = "c" val combined = str1.switchCombineWith(str2, str3) { a, b, c -> MutableLiveData(listOfNotNull(a, b, c).joinToString()) } combined.observeForever(observer) argumentCaptor<String> { verify(observer).onChanged(capture()) assertThat(allValues, contains("a, b, c")) } } // endregion switchCombine() & switchCombineWith() // region combine() & combineWith() @Test fun `combine() - 2 LiveDatas`() { val combined = combine(str1, str2) { a, b -> listOfNotNull(a, b).joinToString() } combined.observeForever(observer) verify(observer, never()).onChanged(any()) assertNull(combined.value) str1.value = "b" verify(observer, never()).onChanged(any()) assertNull(combined.value) str2.value = null verify(observer).onChanged(any()) assertEquals("b", combined.value) str2.value = "c" verify(observer, times(2)).onChanged(any()) assertEquals("b, c", combined.value) argumentCaptor<String> { verify(observer, times(2)).onChanged(capture()) assertThat(allValues, contains("b", "b, c")) } } @Test fun `combineWith() - 2 LiveDatas`() { val combined = str1.combineWith(str2) { a, b -> listOfNotNull(a, b).joinToString() } combined.observeForever(observer) verify(observer, never()).onChanged(any()) assertNull(combined.value) str1.value = "b" verify(observer, never()).onChanged(any()) assertNull(combined.value) str2.value = null verify(observer).onChanged(any()) assertEquals("b", combined.value) str2.value = "c" verify(observer, times(2)).onChanged(any()) assertEquals("b, c", combined.value) argumentCaptor<String> { verify(observer, times(2)).onChanged(capture()) assertThat(allValues, contains("b", "b, c")) } } @Test fun `combine() - 3 LiveDatas`() { val combined = combine(str1, str2, str3) { a, b, c -> listOfNotNull(a, b, c).joinToString() } combined.observeForever(observer) verify(observer, never()).onChanged(any()) assertNull(combined.value) str1.value = "b" verify(observer, never()).onChanged(any()) assertNull(combined.value) str2.value = null verify(observer, never()).onChanged(any()) assertNull(combined.value) str3.value = null verify(observer).onChanged(any()) assertEquals("b", combined.value) str3.value = "d" verify(observer, times(2)).onChanged(any()) assertEquals("b, d", combined.value) str2.value = "c" verify(observer, times(3)).onChanged(any()) assertEquals("b, c, d", combined.value) argumentCaptor<String> { verify(observer, times(3)).onChanged(capture()) assertThat(allValues, contains("b", "b, d", "b, c, d")) } } @Test fun `combineWith() - 3 LiveDatas`() { val combined = str1.combineWith(str2, str3) { a, b, c -> listOfNotNull(a, b, c).joinToString() } combined.observeForever(observer) verify(observer, never()).onChanged(any()) assertNull(combined.value) str1.value = "b" verify(observer, never()).onChanged(any()) assertNull(combined.value) str2.value = null verify(observer, never()).onChanged(any()) assertNull(combined.value) str3.value = null verify(observer).onChanged(any()) assertEquals("b", combined.value) str3.value = "d" verify(observer, times(2)).onChanged(any()) assertEquals("b, d", combined.value) str2.value = "c" verify(observer, times(3)).onChanged(any()) assertEquals("b, c, d", combined.value) argumentCaptor<String> { verify(observer, times(3)).onChanged(capture()) assertThat(allValues, contains("b", "b, d", "b, c, d")) } } @Test fun `combine() - 4 LiveDatas`() { val combined = combine(str1, str2, str3, str4) { a, b, c, d -> listOfNotNull(a, b, c, d).joinToString() } combined.observeForever(observer) verify(observer, never()).onChanged(any()) assertNull(combined.value) str1.value = "b" verify(observer, never()).onChanged(any()) assertNull(combined.value) str2.value = null verify(observer, never()).onChanged(any()) assertNull(combined.value) str3.value = null verify(observer).onChanged(any()) assertEquals("b", combined.value) str4.value = "e" verify(observer, times(2)).onChanged(any()) assertEquals("b, e", combined.value) str3.value = "d" verify(observer, times(3)).onChanged(any()) assertEquals("b, d, e", combined.value) str2.value = "c" verify(observer, times(4)).onChanged(any()) assertEquals("b, c, d, e", combined.value) argumentCaptor<String> { verify(observer, times(4)).onChanged(capture()) assertThat(allValues, contains("b", "b, e", "b, d, e", "b, c, d, e")) } } @Test fun `combineWith() - 4 LiveDatas`() { val combined = str1.combineWith(str2, str3, str4) { a, b, c, d -> listOfNotNull(a, b, c, d).joinToString() } combined.observeForever(observer) verify(observer, never()).onChanged(any()) assertNull(combined.value) str1.value = "b" verify(observer, never()).onChanged(any()) assertNull(combined.value) str2.value = null verify(observer, never()).onChanged(any()) assertNull(combined.value) str3.value = null verify(observer).onChanged(any()) assertEquals("b", combined.value) str4.value = "e" verify(observer, times(2)).onChanged(any()) assertEquals("b, e", combined.value) str3.value = "d" verify(observer, times(3)).onChanged(any()) assertEquals("b, d, e", combined.value) str2.value = "c" verify(observer, times(4)).onChanged(any()) assertEquals("b, c, d, e", combined.value) argumentCaptor<String> { verify(observer, times(4)).onChanged(capture()) assertThat(allValues, contains("b", "b, e", "b, d, e", "b, c, d, e")) } } @Test fun `combine() - 5 LiveDatas`() { val combined = combine(str1, str2, str3, str4, str5) { a, b, c, d, e -> listOfNotNull(a, b, c, d, e).joinToString() } combined.observeForever(observer) verify(observer, never()).onChanged(any()) assertNull(combined.value) str1.value = "b" verify(observer, never()).onChanged(any()) assertNull(combined.value) str2.value = null verify(observer, never()).onChanged(any()) assertNull(combined.value) str5.value = null verify(observer, never()).onChanged(any()) assertNull(combined.value) str3.value = null verify(observer).onChanged(any()) assertEquals("b", combined.value) str4.value = "e" verify(observer, times(2)).onChanged(any()) assertEquals("b, e", combined.value) str3.value = "d" verify(observer, times(3)).onChanged(any()) assertEquals("b, d, e", combined.value) str5.value = "f" verify(observer, times(4)).onChanged(any()) assertEquals("b, d, e, f", combined.value) str2.value = "c" verify(observer, times(5)).onChanged(any()) assertEquals("b, c, d, e, f", combined.value) argumentCaptor<String> { verify(observer, times(5)).onChanged(capture()) assertThat(allValues, contains("b", "b, e", "b, d, e", "b, d, e, f", "b, c, d, e, f")) } } @Test fun `combineWith() - 5 LiveDatas`() { val combined = str1.combineWith(str2, str3, str4, str5) { a, b, c, d, e -> listOfNotNull(a, b, c, d, e).joinToString() } combined.observeForever(observer) verify(observer, never()).onChanged(any()) assertNull(combined.value) str1.value = "b" verify(observer, never()).onChanged(any()) assertNull(combined.value) str2.value = null verify(observer, never()).onChanged(any()) assertNull(combined.value) str5.value = null verify(observer, never()).onChanged(any()) assertNull(combined.value) str3.value = null verify(observer).onChanged(any()) assertEquals("b", combined.value) str4.value = "e" verify(observer, times(2)).onChanged(any()) assertEquals("b, e", combined.value) str3.value = "d" verify(observer, times(3)).onChanged(any()) assertEquals("b, d, e", combined.value) str5.value = "f" verify(observer, times(4)).onChanged(any()) assertEquals("b, d, e, f", combined.value) str2.value = "c" verify(observer, times(5)).onChanged(any()) assertEquals("b, c, d, e, f", combined.value) argumentCaptor<String> { verify(observer, times(5)).onChanged(capture()) assertThat(allValues, contains("b", "b, e", "b, d, e", "b, d, e, f", "b, c, d, e, f")) } } @Test fun `combineWith() - 6 LiveDatas`() { val combined = str1.combineWith(str2, str3, str4, str5, str6) { a, b, c, d, e, f -> listOfNotNull(a, b, c, d, e, f).joinToString() } combined.observeForever(observer) verify(observer, never()).onChanged(any()) assertNull(combined.value) str1.value = "b" verify(observer, never()).onChanged(any()) assertNull(combined.value) str2.value = null verify(observer, never()).onChanged(any()) assertNull(combined.value) str5.value = null verify(observer, never()).onChanged(any()) assertNull(combined.value) str6.value = null verify(observer, never()).onChanged(any()) assertNull(combined.value) str3.value = null verify(observer).onChanged(any()) assertEquals("b", combined.value) str4.value = "e" verify(observer, times(2)).onChanged(any()) assertEquals("b, e", combined.value) str3.value = "d" verify(observer, times(3)).onChanged(any()) assertEquals("b, d, e", combined.value) str5.value = "f" verify(observer, times(4)).onChanged(any()) assertEquals("b, d, e, f", combined.value) str2.value = "c" verify(observer, times(5)).onChanged(any()) assertEquals("b, c, d, e, f", combined.value) str6.value = "g" verify(observer, times(6)).onChanged(any()) assertEquals("b, c, d, e, f, g", combined.value) argumentCaptor<String> { verify(observer, times(6)).onChanged(capture()) assertThat(allValues, contains("b", "b, e", "b, d, e", "b, d, e, f", "b, c, d, e, f", "b, c, d, e, f, g")) } } @Test fun verifyCombineWithObserverCalledOnceOnInitialization() { str1.value = "a" str2.value = "b" str3.value = "c" val combined = str1.combineWith(str2, str3) { a, b, c -> listOfNotNull(a, b, c).joinToString() } combined.observeForever(observer) argumentCaptor<String> { verify(observer).onChanged(capture()) assertThat(allValues, contains("a, b, c")) } } // endregion combine() & combineWith() }
mit
b54c20d63ac4237f640808ad1a8e61a8
36.364362
118
0.584881
3.951899
false
false
false
false
wordpress-mobile/AztecEditor-Android
aztec/src/main/kotlin/org/wordpress/aztec/spans/AztecMediaSpan.kt
1
3117
package org.wordpress.aztec.spans import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import android.graphics.drawable.Drawable import android.view.Gravity import org.wordpress.aztec.AztecAttributes import org.wordpress.aztec.AztecText import java.lang.ref.WeakReference import java.util.ArrayList abstract class AztecMediaSpan(context: Context, drawable: Drawable?, override var attributes: AztecAttributes = AztecAttributes(), var onMediaDeletedListener: AztecText.OnMediaDeletedListener? = null, editor: AztecText? = null) : AztecDynamicImageSpan(context, drawable), IAztecAttributedSpan { abstract val TAG: String private val overlays: ArrayList<Pair<Drawable?, Int>> = ArrayList() init { textView = editor?.let { WeakReference(editor) } } fun setOverlay(index: Int, newDrawable: Drawable?, gravity: Int) { if (overlays.lastIndex >= index) { overlays.removeAt(index) } if (newDrawable != null) { overlays.ensureCapacity(index + 1) overlays.add(index, Pair(newDrawable, gravity)) setInitBounds(newDrawable) } } fun clearOverlays() { overlays.clear() } fun setOverlayLevel(index: Int, level: Int): Boolean { return overlays.getOrNull(index)?.first?.setLevel(level) ?: false } private fun applyOverlayGravity(overlay: Drawable?, gravity: Int) { if (imageDrawable != null && overlay != null) { val rect = Rect(0, 0, imageDrawable!!.bounds.width(), imageDrawable!!.bounds.height()) val outRect = Rect() Gravity.apply(gravity, overlay.bounds.width(), overlay.bounds.height(), rect, outRect) overlay.setBounds(outRect.left, outRect.top, outRect.right, outRect.bottom) } } override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) { canvas.save() if (imageDrawable != null) { var transY = top if (mVerticalAlignment == ALIGN_BASELINE) { transY -= paint.fontMetricsInt.descent } canvas.translate(x, transY.toFloat()) imageDrawable!!.draw(canvas) } overlays.forEach { applyOverlayGravity(it.first, it.second) } overlays.forEach { it.first?.draw(canvas) } canvas.restore() } open fun getHtml(): String { val sb = StringBuilder("<$TAG ") attributes.removeAttribute("aztec_id") sb.append(attributes) sb.trim() sb.append(" />") return sb.toString() } fun getSource(): String { return attributes.getValue("src") ?: "" } abstract fun onClick() fun onMediaDeleted() { onMediaDeletedListener?.onMediaDeleted(attributes) } fun beforeMediaDeleted() { onMediaDeletedListener?.beforeMediaDeleted(attributes) } }
mpl-2.0
cd82196ea3349a098725333f9160988a
28.685714
136
0.624318
4.631501
false
false
false
false
world-federation-of-advertisers/panel-exchange-client
src/main/kotlin/org/wfanet/panelmatch/client/eventpreprocessing/BatchingDoFn.kt
1
2147
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.panelmatch.client.eventpreprocessing import org.apache.beam.sdk.metrics.Metrics import org.apache.beam.sdk.transforms.DoFn import org.apache.beam.sdk.transforms.SerializableFunction import org.apache.beam.sdk.transforms.windowing.GlobalWindow import org.joda.time.Instant /** * Batches [T]s into MutableLists. * * The sum of [getElementByteSize] involved on each item of an output MutableList is at most * [maxByteSize]. */ class BatchingDoFn<T>( private val maxByteSize: Long, private val getElementByteSize: SerializableFunction<T, Int> ) : DoFn<T, MutableList<T>>() { private var buffer = mutableListOf<T>() private var size: Long = 0L private val batchSizeDistribution = Metrics.distribution(BatchingDoFn::class.java, "batch-sizes") @ProcessElement fun process(c: ProcessContext) { val currElementSize: Int = getElementByteSize.apply(c.element()) if (currElementSize >= maxByteSize) { c.output(mutableListOf(c.element())) return } if (size + currElementSize > maxByteSize) { batchSizeDistribution.update(size) c.output(buffer) buffer = mutableListOf() size = 0 } buffer.add(c.element()) size += currElementSize } @FinishBundle @Synchronized @Throws(Exception::class) fun FinishBundle(context: FinishBundleContext) { if (buffer.isNotEmpty()) { batchSizeDistribution.update(size) context.output(buffer, Instant.now(), GlobalWindow.INSTANCE) buffer = mutableListOf() size = 0 } } }
apache-2.0
ae31471952b53375129b6dc3c7625845
32.030769
99
0.726129
3.998138
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/cafeteria/controller/CafeteriaManager.kt
1
3808
package de.tum.`in`.tumcampusapp.component.ui.cafeteria.controller import android.content.Context import android.preference.PreferenceManager import de.tum.`in`.tumcampusapp.api.tumonline.CacheControl import de.tum.`in`.tumcampusapp.component.notifications.ProvidesNotifications import de.tum.`in`.tumcampusapp.component.other.locations.LocationManager import de.tum.`in`.tumcampusapp.component.ui.cafeteria.CafeteriaMenuCard import de.tum.`in`.tumcampusapp.component.ui.cafeteria.model.CafeteriaMenu import de.tum.`in`.tumcampusapp.component.ui.cafeteria.model.CafeteriaWithMenus import de.tum.`in`.tumcampusapp.component.ui.cafeteria.repository.CafeteriaLocalRepository import de.tum.`in`.tumcampusapp.component.ui.overview.card.Card import de.tum.`in`.tumcampusapp.component.ui.overview.card.ProvidesCard import de.tum.`in`.tumcampusapp.database.TcaDb import de.tum.`in`.tumcampusapp.utils.Const import de.tum.`in`.tumcampusapp.utils.Utils import java.util.* import javax.inject.Inject /** * Cafeteria Manager, handles database stuff, external imports */ class CafeteriaManager @Inject constructor(private val context: Context) : ProvidesCard, ProvidesNotifications { val localRepository: CafeteriaLocalRepository init { val db = TcaDb.getInstance(context) localRepository = CafeteriaLocalRepository(db) } /** * Returns a list of [CafeteriaMenu]s of the best-matching cafeteria. If there's no * best-matching cafeteria, it returns an empty list. */ val bestMatchCafeteriaMenus: List<CafeteriaMenu> get() { val cafeteriaId = bestMatchMensaId return if (cafeteriaId == Const.NO_CAFETERIA_FOUND) { emptyList() } else getCafeteriaMenusByCafeteriaId(cafeteriaId) } // Choose which mensa should be shown val bestMatchMensaId: Int get() { val cafeteriaId = LocationManager(context).getCafeteria() if (cafeteriaId == Const.NO_CAFETERIA_FOUND) { Utils.log("could not get a Cafeteria from locationManager!") } return cafeteriaId } override fun getCards(cacheControl: CacheControl): List<Card> { val results = ArrayList<Card>() // ids have to be added to a new set because the data would be changed otherwise val cafeteriaIds = HashSet<String>(20) cafeteriaIds.addAll(PreferenceManager.getDefaultSharedPreferences(context) .getStringSet(Const.CAFETERIA_CARDS_SETTING, HashSet(0))!!) // adding the location based id to the set now makes sure that the cafeteria is not shown twice if (cafeteriaIds.contains(Const.CAFETERIA_BY_LOCATION_SETTINGS_ID)) { cafeteriaIds.remove(Const.CAFETERIA_BY_LOCATION_SETTINGS_ID) cafeteriaIds.add(LocationManager(context).getCafeteria().toString()) } for (id in cafeteriaIds) { val cafeteria = Integer.parseInt(id) if (cafeteria == Const.NO_CAFETERIA_FOUND) { // no cafeteria based on the location could be found continue } val card = CafeteriaMenuCard(context, localRepository.getCafeteriaWithMenus(cafeteria)) card.getIfShowOnStart()?.let { results.add(it) } } return results } override fun hasNotificationsEnabled(): Boolean { return Utils.getSettingBool(context, "card_cafeteria_phone", true) } private fun getCafeteriaMenusByCafeteriaId(cafeteriaId: Int): List<CafeteriaMenu> { val cafeteria = CafeteriaWithMenus(cafeteriaId) cafeteria.menuDates = localRepository.getAllMenuDates() return localRepository.getCafeteriaMenus(cafeteriaId, cafeteria.nextMenuDate) } }
gpl-3.0
ce31033d196a522e4cb218789cb894f6
40.402174
112
0.70063
4.632603
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/other/navigation/NavigationManager.kt
1
2650
package de.tum.`in`.tumcampusapp.component.other.navigation import android.content.Context import android.content.Intent import android.net.Uri import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentTransaction import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.other.generic.activity.BaseNavigationActivity import de.tum.`in`.tumcampusapp.component.other.generic.drawer.NavItem object NavigationManager { fun open(context: Context, navItem: NavItem) { when (navItem) { is NavItem.FragmentDestination -> open(context, navItem) is NavItem.ActivityDestination -> open(context, navItem) } } private fun open(context: Context, navItem: NavItem.FragmentDestination) { val fragment = Fragment.instantiate(context, navItem.fragment.name) val activity = context as? BaseNavigationActivity ?: return openFragment(activity, fragment) } private fun open(context: Context, navItem: NavItem.ActivityDestination) { val activity = context as? BaseNavigationActivity ?: return val intent = Intent(activity, navItem.activity) activity.startActivity(intent) } fun open(context: Context, destination: NavDestination) { when (destination) { is NavDestination.Fragment -> { val baseNavigationActivity = context as? BaseNavigationActivity ?: return val fragment = Fragment.instantiate(context, destination.clazz.name, destination.args) openFragment(baseNavigationActivity, fragment) } is NavDestination.Activity -> { val intent = Intent(context, destination.clazz) intent.putExtras(destination.args) context.startActivity(intent) } is NavDestination.Link -> { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(destination.url)) context.startActivity(intent) } } } private fun openFragment(activity: BaseNavigationActivity, fragment: Fragment) { activity .supportFragmentManager .beginTransaction() .setCustomAnimations(R.anim.fadein, R.anim.fadeout) .replace(R.id.contentFrame, fragment) .ensureBackToHome(activity) .commit() } private fun FragmentTransaction.ensureBackToHome( activity: BaseNavigationActivity ): FragmentTransaction { if (activity.supportFragmentManager.backStackEntryCount == 0) { addToBackStack(null) } return this } }
gpl-3.0
8d0a1e9a6101904ec354cdb958e3804c
36.857143
102
0.662642
5.018939
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/bikeway/AddCycleway.kt
1
17515
package de.westnordost.streetcomplete.quests.bikeway import de.westnordost.osmapi.map.MapDataWithGeometry import de.westnordost.osmapi.map.data.Element import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.elementfilter.filters.RelativeDate import de.westnordost.streetcomplete.data.elementfilter.filters.TagOlderThan import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression import de.westnordost.streetcomplete.data.meta.ANYTHING_UNPAVED import de.westnordost.streetcomplete.data.meta.MAXSPEED_TYPE_KEYS import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder import de.westnordost.streetcomplete.data.quest.NoCountriesExcept import de.westnordost.streetcomplete.data.meta.deleteCheckDatesForKey import de.westnordost.streetcomplete.data.meta.updateCheckDateForKey import de.westnordost.streetcomplete.data.osm.changes.StringMapEntryModify import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementPolylinesGeometry import de.westnordost.streetcomplete.data.osm.osmquest.OsmElementQuestType import de.westnordost.streetcomplete.ktx.containsAny import de.westnordost.streetcomplete.quests.bikeway.Cycleway.* import de.westnordost.streetcomplete.util.isNearAndAligned class AddCycleway : OsmElementQuestType<CyclewayAnswer> { override val commitMessage = "Add whether there are cycleways" override val wikiLink = "Key:cycleway" override val icon = R.drawable.ic_quest_bicycleway // See overview here: https://ent8r.github.io/blacklistr/?streetcomplete=bikeway/AddCycleway.kt // #749. sources: // Google Street View (driving around in virtual car) // https://en.wikivoyage.org/wiki/Cycling // http://peopleforbikes.org/get-local/ (US) override val enabledInCountries = NoCountriesExcept( // all of Northern and Western Europe, most of Central Europe, some of Southern Europe "NO", "SE", "FI", "IS", "DK", "GB", "IE", "NL", "BE", "FR", "LU", "DE", "PL", "CZ", "HU", "AT", "CH", "LI", "ES", "IT", // East Asia "JP", "KR", "TW", // some of China (East Coast) "CN-BJ", "CN-TJ", "CN-SD", "CN-JS", "CN-SH", "CN-ZJ", "CN-FJ", "CN-GD", "CN-CQ", // Australia etc "NZ", "AU", // some of Canada "CA-BC", "CA-QC", "CA-ON", "CA-NS", "CA-PE", // some of the US // West Coast, East Coast, Center, South "US-WA", "US-OR", "US-CA", "US-MA", "US-NJ", "US-NY", "US-DC", "US-CT", "US-FL", "US-MN", "US-MI", "US-IL", "US-WI", "US-IN", "US-AZ", "US-TX" ) override val isSplitWayEnabled = true override fun getTitle(tags: Map<String, String>) : Int = if (createCyclewaySides(tags, false) != null) R.string.quest_cycleway_resurvey_title else R.string.quest_cycleway_title2 override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> { val eligibleRoads = mapData.ways.filter { roadsFilter.matches(it) } /* we want to return two sets of roads: Those that do not have any cycleway tags, and those * that do but have been checked more than 4 years ago. */ /* For the first, the roadsWithMissingCycleway filter is not enough. In OSM, cycleways may be * mapped as separate ways as well and it is not guaranteed that in this case, * cycleway = separate or something is always tagged on the main road then. So, all roads * should be excluded whose center is within of ~15 meters of a cycleway, to be on the safe * side. */ val roadsWithMissingCycleway = eligibleRoads.filter { untaggedRoadsFilter.matches(it) }.toMutableList() if (roadsWithMissingCycleway.isNotEmpty()) { val maybeSeparatelyMappedCyclewayGeometries = mapData.ways .filter { maybeSeparatelyMappedCyclewaysFilter.matches(it) } .mapNotNull { mapData.getWayGeometry(it.id) as? ElementPolylinesGeometry } val minAngleToWays = 25.0 // filter out roads with missing sidewalks that are near footways roadsWithMissingCycleway.removeAll { road -> val minDistToWays = estimatedWidth(road.tags) / 2.0 + 6 val roadGeometry = mapData.getWayGeometry(road.id) as? ElementPolylinesGeometry roadGeometry?.isNearAndAligned(minDistToWays, minAngleToWays, maybeSeparatelyMappedCyclewayGeometries) ?: true } } /* For the second, nothing special. Filter out ways that have been checked less then 4 * years ago or have no known cycleway tags */ val oldRoadsWithKnownCycleways = eligibleRoads.filter { OLDER_THAN_4_YEARS.matches(it) && it.hasOnlyKnownCyclewayTags() } return roadsWithMissingCycleway + oldRoadsWithKnownCycleways } private fun estimatedWidth(tags: Map<String, String>): Float { val width = tags["width"]?.toFloatOrNull() if (width != null) return width val lanes = tags["lanes"]?.toIntOrNull() if (lanes != null) return lanes * 3f return 12f } override fun isApplicableTo(element: Element): Boolean? { val tags = element.tags ?: return false // can't determine for yet untagged roads by the tags alone because we need info about // surrounding geometry, but for already tagged ones, we can! if (!tags.keys.containsAny(KNOWN_CYCLEWAY_KEYS)) return null return roadsFilter.matches(element) && OLDER_THAN_4_YEARS.matches(element) && element.hasOnlyKnownCyclewayTags() } override fun createForm() = AddCyclewayForm() override fun applyAnswerTo(answer: CyclewayAnswer, changes: StringMapChangesBuilder) { if (answer.left == answer.right) { answer.left?.let { applyCyclewayAnswerTo(it.cycleway, Side.BOTH, 0, changes) } deleteCyclewayAnswerIfExists(Side.LEFT, changes) deleteCyclewayAnswerIfExists(Side.RIGHT, changes) } else { answer.left?.let { applyCyclewayAnswerTo(it.cycleway, Side.LEFT, it.dirInOneway, changes) } answer.right?.let { applyCyclewayAnswerTo(it.cycleway, Side.RIGHT, it.dirInOneway, changes) } deleteCyclewayAnswerIfExists(Side.BOTH, changes) } deleteCyclewayAnswerIfExists(null, changes) applySidewalkAnswerTo(answer.left?.cycleway, answer.right?.cycleway, changes) if (answer.isOnewayNotForCyclists) { changes.addOrModify("oneway:bicycle", "no") } else { changes.deleteIfPreviously("oneway:bicycle", "no") } // only set the check date if nothing was changed val isNotActuallyChangingAnything = changes.getChanges().all { change -> change is StringMapEntryModify && change.value == change.valueBefore } if (isNotActuallyChangingAnything) { changes.updateCheckDateForKey("cycleway") } else { changes.deleteCheckDatesForKey("cycleway") } } /** Just add a sidewalk if we implicitly know from the answer that there is one */ private fun applySidewalkAnswerTo( cyclewayLeft: Cycleway?, cyclewayRight: Cycleway?, changes: StringMapChangesBuilder ) { /* only tag if we know the sidewalk value for both sides (because it is not possible in OSM to specify the sidewalk value only for one side. sidewalk:right/left=yes is not well established. */ if (cyclewayLeft?.isOnSidewalk == true && cyclewayRight?.isOnSidewalk == true) { changes.addOrModify("sidewalk", "both") } } private enum class Side(val value: String) { LEFT("left"), RIGHT("right"), BOTH("both") } private fun applyCyclewayAnswerTo(cycleway: Cycleway, side: Side, dir: Int, changes: StringMapChangesBuilder ) { val directionValue = when { dir > 0 -> "yes" dir < 0 -> "-1" else -> null } val cyclewayKey = "cycleway:" + side.value when (cycleway) { NONE, NONE_NO_ONEWAY -> { changes.addOrModify(cyclewayKey, "no") } EXCLUSIVE_LANE, ADVISORY_LANE, UNSPECIFIED_LANE -> { changes.addOrModify(cyclewayKey, "lane") if (directionValue != null) { changes.addOrModify("$cyclewayKey:oneway", directionValue) } if (cycleway == EXCLUSIVE_LANE) changes.addOrModify("$cyclewayKey:lane", "exclusive") else if (cycleway == ADVISORY_LANE) changes.addOrModify("$cyclewayKey:lane","advisory") } TRACK -> { changes.addOrModify(cyclewayKey, "track") if (directionValue != null) { changes.addOrModify("$cyclewayKey:oneway", directionValue) } if (changes.getPreviousValue("$cyclewayKey:segregated") == "no") { changes.modify("$cyclewayKey:segregated", "yes") } } DUAL_TRACK -> { changes.addOrModify(cyclewayKey, "track") changes.addOrModify("$cyclewayKey:oneway", "no") } DUAL_LANE -> { changes.addOrModify(cyclewayKey, "lane") changes.addOrModify("$cyclewayKey:oneway", "no") changes.addOrModify("$cyclewayKey:lane", "exclusive") } SIDEWALK_EXPLICIT -> { // https://wiki.openstreetmap.org/wiki/File:Z240GemeinsamerGehundRadweg.jpeg changes.addOrModify(cyclewayKey, "track") changes.addOrModify("$cyclewayKey:segregated", "no") } PICTOGRAMS -> { changes.addOrModify(cyclewayKey, "shared_lane") changes.addOrModify("$cyclewayKey:lane", "pictogram") } SUGGESTION_LANE -> { changes.addOrModify(cyclewayKey, "shared_lane") changes.addOrModify("$cyclewayKey:lane", "advisory") } BUSWAY -> { changes.addOrModify(cyclewayKey, "share_busway") } else -> { throw IllegalArgumentException("Invalid cycleway") } } // clear previous cycleway:lane value if (!cycleway.isLane) { changes.deleteIfExists("$cyclewayKey:lane") } // clear previous cycleway:oneway=no value (if not about to set a new value) if (cycleway.isOneway && directionValue == null) { changes.deleteIfPreviously("$cyclewayKey:oneway", "no") } // clear previous cycleway:segregated=no value if (cycleway != SIDEWALK_EXPLICIT && cycleway != TRACK) { changes.deleteIfPreviously("$cyclewayKey:segregated", "no") } } /** clear previous answers for the given side */ private fun deleteCyclewayAnswerIfExists(side: Side?, changes: StringMapChangesBuilder) { val sideVal = if (side == null) "" else ":" + side.value val cyclewayKey = "cycleway$sideVal" // only things are cleared that are set by this quest // for example cycleway:surface should only be cleared by a cycleway surface quest etc. changes.deleteIfExists(cyclewayKey) changes.deleteIfExists("$cyclewayKey:lane") changes.deleteIfExists("$cyclewayKey:oneway") changes.deleteIfExists("$cyclewayKey:segregated") changes.deleteIfExists("sidewalk$sideVal:bicycle") } companion object { /* Excluded is - anything explicitly tagged as no bicycles or having to use separately mapped sidepath - if not already tagged with a cycleway: streets with low speed or that are not paved, as they are very unlikely to have cycleway infrastructure - if not already tagged, roads that are close (15m) to foot or cycleways (see #718) - if already tagged, if not older than 8 years or if the cycleway tag uses some unknown value */ // streets what may have cycleway tagging private val roadsFilter by lazy { """ ways with highway ~ primary|primary_link|secondary|secondary_link|tertiary|tertiary_link|unclassified|residential|service and area != yes and motorroad != yes and bicycle_road != yes and cyclestreet != yes and bicycle != no and bicycle != designated and access !~ private|no and bicycle != use_sidepath and bicycle:backward != use_sidepath and bicycle:forward != use_sidepath and sidewalk != separate """.toElementFilterExpression() } // streets that do not have cycleway tagging yet private val untaggedRoadsFilter by lazy { """ ways with ( highway ~ primary|primary_link|secondary|secondary_link|tertiary|tertiary_link|unclassified or highway = residential and ( maxspeed > 30 or (maxspeed ~ ".*mph" and maxspeed !~ "([1-9]|1[0-9]|20) mph") or $NOT_IN_30_ZONE_OR_LESS ) ) and !cycleway and !cycleway:left and !cycleway:right and !cycleway:both and !sidewalk:bicycle and !sidewalk:left:bicycle and !sidewalk:right:bicycle and !sidewalk:both:bicycle and ( !maxspeed or maxspeed > 20 or (maxspeed ~ ".*mph" and maxspeed !~ "([1-9]|1[0-2]) mph") or $NOT_IN_30_ZONE_OR_LESS ) and surface !~ ${ANYTHING_UNPAVED.joinToString("|")} """.toElementFilterExpression() } private val maybeSeparatelyMappedCyclewaysFilter by lazy { """ ways with highway ~ path|footway|cycleway """.toElementFilterExpression() } private val NOT_IN_30_ZONE_OR_LESS = MAXSPEED_TYPE_KEYS.joinToString(" or ") { """$it and $it !~ ".*zone:?([1-9]|[1-2][0-9]|30)"""" } private val OLDER_THAN_4_YEARS = TagOlderThan("cycleway", RelativeDate(-(365 * 4).toFloat())) private val KNOWN_CYCLEWAY_KEYS = setOf( "cycleway", "cycleway:left", "cycleway:right", "cycleway:both" ) private val KNOWN_CYCLEWAY_LANES_KEYS = setOf( "cycleway:lane", "cycleway:left:lane", "cycleway:right:lane", "cycleway:both:lane" ) private val KNOWN_CYCLEWAY_VALUES = setOf( "lane", "track", "shared_lane", "share_busway", "no", "none", // synonymous for oneway:bicycle=no + cycleway:right=no (if right hand traffic and oneway=yes) "opposite_lane", // + cycleway:left=lane "opposite_track", // + cycleway:left=track "opposite_share_busway", // + cycleway:left=share_busway "opposite", // + cycleway:left=no // ambiguous: "yes", // unclear what type "left", // unclear what type; wrong tagging scheme (sidewalk=left) "right", // unclear what type; wrong tagging scheme "both", // unclear what type; wrong tagging scheme "shared" // unclear if it is shared_lane or share_busway (or shared with pedestrians) ) /* Treat the opposite_* taggings as simple synonyms which will be overwritten by the new tagging. Community seems to be rather in consensus that both methods are equivalent or even the one without opposite_* being better/newer. https://forum.openstreetmap.org/viewtopic.php?id=65612 https://forum.openstreetmap.org/viewtopic.php?id=63464 https://forum.openstreetmap.org/viewtopic.php?id=62668 https://wiki.openstreetmap.org/w/index.php?title=Tag:cycleway%3Dopposite_lane&oldid=1820887 https://github.com/cyclosm/cyclosm-cartocss-style/issues/426 */ private val KNOWN_CYCLEWAY_LANE_VALUES = listOf( "exclusive", "advisory", "pictogram", "mandatory", "exclusive_lane", // same as exclusive. Exclusive lanes are mandatory for bicyclists "soft_lane", "advisory_lane", "dashed" // synonym for advisory lane ) private fun Element.hasOnlyKnownCyclewayTags(): Boolean { val tags = tags ?: return false val cyclewayTags = tags.filterKeys { it in KNOWN_CYCLEWAY_KEYS } // has no cycleway tagging if (cyclewayTags.isEmpty()) return false // any cycleway tagging is not known if (cyclewayTags.values.any { it !in KNOWN_CYCLEWAY_VALUES }) return false // any cycleway lane tagging is not known val cycleLaneTags = tags.filterKeys { it in KNOWN_CYCLEWAY_LANES_KEYS } if (cycleLaneTags.values.any { it !in KNOWN_CYCLEWAY_LANE_VALUES }) return false return true } } }
gpl-3.0
30797cde160acdbba8fc0d93574090cf
43.795396
126
0.608507
4.539917
false
false
false
false
robfletcher/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/RescheduleExecutionHandlerTest.kt
3
3716
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spinnaker.orca.TaskResolver import com.netflix.spinnaker.orca.api.pipeline.Task import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus import com.netflix.spinnaker.orca.api.test.pipeline import com.netflix.spinnaker.orca.api.test.stage import com.netflix.spinnaker.orca.api.test.task import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.q.RescheduleExecution import com.netflix.spinnaker.orca.q.RunTask import com.netflix.spinnaker.orca.q.TasksProvider import com.netflix.spinnaker.q.Queue import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.reset import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions import com.nhaarman.mockito_kotlin.whenever import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.lifecycle.CachingMode import org.jetbrains.spek.subject.SubjectSpek object RescheduleExecutionHandlerTest : SubjectSpek<RescheduleExecutionHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() val taskResolver = TaskResolver(TasksProvider(emptyList())) subject(CachingMode.GROUP) { RescheduleExecutionHandler(queue, repository, taskResolver) } fun resetMocks() = reset(queue, repository) describe("reschedule an execution") { val pipeline = pipeline { application = "spinnaker" status = ExecutionStatus.RUNNING stage { refId = "1" status = ExecutionStatus.SUCCEEDED } stage { refId = "2a" requisiteStageRefIds = listOf("1") status = ExecutionStatus.RUNNING task { id = "4" status = ExecutionStatus.RUNNING } } stage { refId = "2b" requisiteStageRefIds = listOf("1") status = ExecutionStatus.RUNNING task { id = "5" status = ExecutionStatus.RUNNING } } stage { refId = "3" requisiteStageRefIds = listOf("2a", "2b") status = ExecutionStatus.NOT_STARTED } } val message = RescheduleExecution(pipeline.type, pipeline.id, pipeline.application) beforeGroup { whenever(repository.retrieve(pipeline.type, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } @Suppress("UNCHECKED_CAST") it("it updates the time for each running task") { val stage2a = pipeline.stageByRef("2a") val stage2b = pipeline.stageByRef("2b") val task4 = stage2a.taskById("4") val task5 = stage2b.taskById("5") verify(queue).reschedule(RunTask(message, stage2a.id, task4.id, Class.forName(task4.implementingClass) as Class<out Task>)) verify(queue).reschedule(RunTask(message, stage2b.id, task5.id, Class.forName(task5.implementingClass) as Class<out Task>)) verifyNoMoreInteractions(queue) } } })
apache-2.0
a2c0da33df8f5290a88abc4ccac7e219
33.091743
129
0.717707
4.189402
false
true
false
false
robfletcher/orca
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/StageDefinitionBuilders.kt
1
5226
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q import com.netflix.spinnaker.orca.api.pipeline.SyntheticStageOwner import com.netflix.spinnaker.orca.api.pipeline.SyntheticStageOwner.STAGE_BEFORE import com.netflix.spinnaker.orca.api.pipeline.graph.StageDefinitionBuilder import com.netflix.spinnaker.orca.api.pipeline.graph.TaskNode import com.netflix.spinnaker.orca.api.pipeline.graph.TaskNode.DefinedTask import com.netflix.spinnaker.orca.api.pipeline.graph.TaskNode.TaskGraph import com.netflix.spinnaker.orca.api.pipeline.models.PipelineExecution import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution import com.netflix.spinnaker.orca.pipeline.RestrictExecutionDuringTimeWindow import com.netflix.spinnaker.orca.pipeline.StageExecutionFactory import com.netflix.spinnaker.orca.pipeline.graph.StageGraphBuilderImpl import com.netflix.spinnaker.orca.pipeline.model.TaskExecutionImpl /** * Build and append the tasks for [stage]. */ fun StageDefinitionBuilder.buildTasks(stage: StageExecution) { buildTaskGraph(stage) .listIterator() .forEachWithMetadata { processTaskNode(stage, it) } } fun StageDefinitionBuilder.addContextFlags(stage: StageExecution) { if (canManuallySkip(stage)) { // Provides a flag for the UI to indicate that the stage can be skipped. stage.context["canManuallySkip"] = true } } private fun processTaskNode( stage: StageExecution, element: IteratorElement<TaskNode>, isSubGraph: Boolean = false ) { element.apply { when (value) { is DefinedTask -> { val task = TaskExecutionImpl() task.id = (stage.tasks.size + 1).toString() task.name = value.name task.implementingClass = value.implementingClassName if (isSubGraph) { task.isLoopStart = isFirst task.isLoopEnd = isLast } else { task.isStageStart = isFirst task.isStageEnd = isLast } stage.tasks.add(task) } is TaskGraph -> { value .listIterator() .forEachWithMetadata { processTaskNode(stage, it, isSubGraph = true) } } } } } /** * Build the synthetic stages for [stage] and inject them into the execution. */ fun StageDefinitionBuilder.buildBeforeStages( stage: StageExecution, callback: (StageExecution) -> Unit = {} ) { val executionWindow = stage.buildExecutionWindow() val graph = StageGraphBuilderImpl.beforeStages(stage, executionWindow) beforeStages(stage, graph) val beforeStages = graph.build().toList() stage.execution.apply { beforeStages.forEach { it.sanitizeContext() injectStage(stages.indexOf(stage), it) callback.invoke(it) } } } fun StageDefinitionBuilder.buildAfterStages( stage: StageExecution, callback: (StageExecution) -> Unit = {} ) { val graph = StageGraphBuilderImpl.afterStages(stage) afterStages(stage, graph) val afterStages = graph.build().toList() stage.appendAfterStages(afterStages, callback) } fun StageDefinitionBuilder.buildFailureStages( stage: StageExecution, callback: (StageExecution) -> Unit = {} ) { val graph = StageGraphBuilderImpl.afterStages(stage) onFailureStages(stage, graph) val afterStages = graph.build().toList() stage.appendAfterStages(afterStages, callback) } fun StageExecution.appendAfterStages( afterStages: Iterable<StageExecution>, callback: (StageExecution) -> Unit = {} ) { val index = execution.stages.indexOf(this) + 1 afterStages.reversed().forEach { it.sanitizeContext() execution.injectStage(index, it) callback.invoke(it) } } private typealias SyntheticStages = Map<SyntheticStageOwner, List<StageExecution>> private fun StageExecution.buildExecutionWindow(): StageExecution? { if (context.getOrDefault("restrictExecutionDuringTimeWindow", false) as Boolean) { val execution = execution val executionWindow = StageExecutionFactory.newStage( execution, RestrictExecutionDuringTimeWindow.TYPE, RestrictExecutionDuringTimeWindow.TYPE, context.filterKeys { it !in setOf("restrictExecutionDuringTimeWindow", "stageTimeoutMs") }, this, STAGE_BEFORE ) executionWindow.refId = "$refId<0" return executionWindow } else { return null } } @Suppress("UNCHECKED_CAST") private fun PipelineExecution.injectStage(index: Int, stage: StageExecution) { stages.add(index, stage) } private fun StageExecution.sanitizeContext() { if (type != RestrictExecutionDuringTimeWindow.TYPE) { context.apply { remove("restrictExecutionDuringTimeWindow") remove("restrictedExecutionWindow") } } }
apache-2.0
e50038c65d60bcdc44799ea03a14db70
30.107143
97
0.732109
4.311881
false
false
false
false
andrewoma/kwery
mapper/src/test/kotlin/com/github/andrewoma/kwery/mappertest/example/test/ActorDaoTest.kt
1
3169
/* * Copyright (c) 2015 Andrew O'Malley * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.andrewoma.kwery.mappertest.example.test import com.github.andrewoma.kwery.mappertest.example.* import org.junit.Test import kotlin.properties.Delegates import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue class ActorDaoTest : AbstractFilmDaoTest<Actor, Int, ActorDao>() { override var dao: ActorDao by Delegates.notNull() override fun afterSessionSetup() { dao = ActorDao(session, FilmActorDao(session)) super.afterSessionSetup() } override val data = listOf( Actor(Name("John", "Wayne")), Actor(Name("Meg", "Ryan")), Actor(Name("Jeff", "Bridges"), ++staticId), Actor(Name("Yvonne", "Strahovsky"), ++staticId) ) override fun mutateContents(t: Actor) = t.copy(name = Name("Bradley", "Cooper")) override fun contentsEqual(t1: Actor, t2: Actor) = t1.name == t2.name @Test fun `findByExample matches example given`() { insertAll() val result = dao.findByExample(Actor().copy(name = Name("", lastName = "Ryan")), setOf(actorTable.LastName)) assertEquals(1, result.size) assertEquals("Meg", result.first().name.firstName) } @Test fun `findByLastNames matches multiple names`() { insertAll() val names = dao.findByLastNames(listOf("Ryan", "Bridges")).map { it.name } assertTrue(names.containsAll(setOf(Name("Jeff", "Bridges"), Name("Meg", "Ryan")))) assertFalse(names.contains(Name("Yvonne", "Strahovsky"))) } @Test fun `Insert with default key should result in a generated key`() { val actor = data[0] val inserted = dao.insert(actor) assertTrue(contentsEqual(actor, inserted)) assertFalse(actor.id == inserted.id) } @Test fun `Insert with non-default key should insert given key`() { val actor = data[3] val inserted = dao.insert(actor) assertTrue(contentsEqual(actor, inserted)) assertTrue(actor.id == inserted.id) } }
mit
61d4711ba86ee3ac8fb59fbf0358a914
38.625
116
0.687914
4.186262
false
true
false
false
MrSugarCaney/DirtyArrows
src/main/kotlin/nl/sugcube/dirtyarrows/bow/ability/HomingBow.kt
1
6729
package nl.sugcube.dirtyarrows.bow.ability import nl.sugcube.dirtyarrows.DirtyArrows import nl.sugcube.dirtyarrows.bow.BowAbility import nl.sugcube.dirtyarrows.bow.DefaultBow import nl.sugcube.dirtyarrows.util.* import org.bukkit.Color import org.bukkit.Location import org.bukkit.Material import org.bukkit.entity.Arrow import org.bukkit.entity.LivingEntity import org.bukkit.entity.Player import org.bukkit.event.entity.ProjectileHitEvent import org.bukkit.event.entity.ProjectileLaunchEvent import org.bukkit.inventory.ItemStack import java.util.concurrent.ConcurrentHashMap import kotlin.math.max /** * Shoots arrows that home in on nearby targets. * * @author SugarCaney */ open class HomingBow(plugin: DirtyArrows) : BowAbility( plugin = plugin, type = DefaultBow.HOMING, handleEveryNTicks = 1, canShootInProtectedRegions = true, removeArrow = false, description = "Shoot mini homing rockets.", costRequirements = listOf(ItemStack(Material.GUNPOWDER, 1)) ) { /** * Maps each arrow to the time when the arrow was shot. */ private val arrowShootTime = ConcurrentHashMap<Arrow, Long>() /** * How many milliseconds until the homing effect wears out. */ val homingPeriod = config.getInt("$node.homing-period") /** * How many milliseconds after firing the homing effects should be applied. */ val startTime = config.getInt("$node.start-time") /** * How many blocks away the shot can redirect. */ val targetRange = config.getDouble("$node.target-range") /** * How far from the arrow's location to start the search for targets. */ val sightDistance = config.getDouble("$node.sight-distance") /** * Value between [0.0, 1.0] where 0 is no homing and 1.0 is immediate homing. */ val homingStrength = config.getDouble("$node.homing-strength") /** * Strength of the explosions. */ val explosivePower = config.getFloat("$node.explosive-power") /** * The minimum velocity the arrow must have before it can become a homing arrow. * Lower velocities might create persistent arrows. */ val minimumVelocity = config.getDouble("$node.minimum-velocity") override fun launch(player: Player, arrow: Arrow, event: ProjectileLaunchEvent) { if (arrow.velocity.length() < minimumVelocity) return arrowShootTime[arrow] = System.currentTimeMillis() } override fun land(arrow: Arrow, player: Player, event: ProjectileHitEvent) { if (explosivePower > 0) { arrow.location.createExplosion(power = explosivePower, breakBlocks = false) unregisterArrow(arrow) arrow.remove() } } override fun particle(tickNumber: Int) = arrows.forEach { it.location.copyOf().fuzz(0.2).showColoredDust(Color.WHITE, 20) } override fun effect() { removeOldArrows() adjustVelocities() } /** * Removes all arrows from the [arrowShootTime] map if their homing period has exceeded. */ private fun removeOldArrows() { val now = System.currentTimeMillis() arrowShootTime.entries.removeIf { (_, time) -> now - time >= homingPeriod } } /** * Changes the velocities of the arrows such that they fly toward their target. */ private fun adjustVelocities() = arrows.forEach { arrow -> val lifespan = System.currentTimeMillis() - (arrowShootTime[arrow] ?: System.currentTimeMillis()) if (lifespan < startTime) return@forEach val target = arrow.findTarget() ?: return@forEach // Gives a more floaty and rockety feel to the arrow. // Without gravity, homing upwards becomes much easier/smoother. arrow.setGravity(false) // Use the Rodrigues' rotation formula to change the direction to the target, but maintain length/velocity. // https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula // // phi / angle := arccos ( (a, T-A) / |a||T-A| ) also defined in Bukkit's Vector.angle // k / planeNormal := ( a X (T-A) ) / |a||T-A| ) // a_new = a cos phi + (k X a) sin phi + k (k, a) (1 - cos phi) // // Where phi is the angle to rotate in the plane k through a and A-T. val targetLocation = target.location.copyOf(y = target.location.y + 0.75) val arrowLocation = arrow.location val arrowVelocity = arrow.velocity val targetDirection = targetLocation.toVector().subtract(arrowLocation.toVector()) // arrowVelocity diverges to targetMinusArrow, results in wacky cross products if they are equal. // Bukkit equals already has an EPSILON defined to compare doubles. if (arrowVelocity == targetDirection) return@forEach // How much the velocity much rotate toward the target. Homing strength in 0.0 through 1.0 for // proper behaviour. val angle = arrowVelocity.angle(targetDirection) * homingStrength // The vector that defines the plane to rotate the arrow over. val planeNormal = arrowVelocity.copyOf().crossProduct(targetDirection) .multiply(1.0 / arrowVelocity.length() * targetDirection.length()) .normalize() // Use Rodrigues rotation formula to apply the rotation. val updatedArrowVelocity = arrowVelocity.rotateAround(planeNormal, angle) // Ensure that the velocity size stays the same. arrow.velocity = updatedArrowVelocity .normalize() .multiply(arrowVelocity.length()) } /** * Looks for the target of this arrow. * * @return The target entity, or `null` when no target could be found. */ private fun Arrow.findTarget(): LivingEntity? { val searchLocation = searchLocation() return world.getNearbyEntities(searchLocation, targetRange, targetRange, targetRange) .asSequence() .mapNotNull { it as? LivingEntity } .filter { it != this.shooter } .minByOrNull { it.location.distance(searchLocation) } } /** * Get the location from where to search for targets. */ private fun Arrow.searchLocation(): Location { val shooter = shooter as? LivingEntity ?: return location val distanceFromShooter = shooter.location.distance(location) val lookThisFarAhead = max(0.0, sightDistance - distanceFromShooter) val direction = velocity.copyOf().normalize() val toAdd = direction.multiply(lookThisFarAhead) return location.copyOf(y = location.y + sightDistance / 2).add(toAdd) } }
gpl-3.0
5681385fb6deadf8bbe2ff6189fd9b4b
36.388889
115
0.659533
4.327331
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/util/lang/DateExtensions.kt
1
3877
package eu.kanade.tachiyomi.util.lang import android.content.Context import eu.kanade.tachiyomi.R import java.text.DateFormat import java.util.Calendar import java.util.Date import java.util.TimeZone fun Date.toDateTimestampString(dateFormatter: DateFormat): String { val date = dateFormatter.format(this) val time = DateFormat.getTimeInstance(DateFormat.SHORT).format(this) return "$date $time" } fun Date.toTimestampString(): String { return DateFormat.getTimeInstance(DateFormat.SHORT).format(this) } /** * Get date as time key * * @param date desired date * @return date as time key */ fun Long.toDateKey(): Date { val cal = Calendar.getInstance() cal.time = Date(this) cal[Calendar.HOUR_OF_DAY] = 0 cal[Calendar.MINUTE] = 0 cal[Calendar.SECOND] = 0 cal[Calendar.MILLISECOND] = 0 return cal.time } /** * Convert epoch long to Calendar instance * * @return Calendar instance at supplied epoch time. Null if epoch was 0. */ fun Long.toCalendar(): Calendar? { if (this == 0L) { return null } val cal = Calendar.getInstance() cal.timeInMillis = this return cal } /** * Convert local time millisecond value to Calendar instance in UTC * * @return UTC Calendar instance at supplied time. Null if time is 0. */ fun Long.toUtcCalendar(): Calendar? { if (this == 0L) { return null } val rawCalendar = Calendar.getInstance().apply { timeInMillis = this@toUtcCalendar } return Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { clear() set( rawCalendar.get(Calendar.YEAR), rawCalendar.get(Calendar.MONTH), rawCalendar.get(Calendar.DAY_OF_MONTH), rawCalendar.get(Calendar.HOUR_OF_DAY), rawCalendar.get(Calendar.MINUTE), rawCalendar.get(Calendar.SECOND), ) } } /** * Convert UTC time millisecond to Calendar instance in local time zone * * @return local Calendar instance at supplied UTC time. Null if time is 0. */ fun Long.toLocalCalendar(): Calendar? { if (this == 0L) { return null } val rawCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { timeInMillis = this@toLocalCalendar } return Calendar.getInstance().apply { clear() set( rawCalendar.get(Calendar.YEAR), rawCalendar.get(Calendar.MONTH), rawCalendar.get(Calendar.DAY_OF_MONTH), rawCalendar.get(Calendar.HOUR_OF_DAY), rawCalendar.get(Calendar.MINUTE), rawCalendar.get(Calendar.SECOND), ) } } private const val MILLISECONDS_IN_DAY = 86_400_000L fun Date.toRelativeString( context: Context, range: Int = 7, dateFormat: DateFormat = DateFormat.getDateInstance(DateFormat.SHORT), ): String { if (range == 0) { return dateFormat.format(this) } val now = Date() val difference = now.timeWithOffset.floorNearest(MILLISECONDS_IN_DAY) - this.timeWithOffset.floorNearest(MILLISECONDS_IN_DAY) val days = difference.floorDiv(MILLISECONDS_IN_DAY).toInt() return when { difference < 0 -> context.getString(R.string.recently) difference < MILLISECONDS_IN_DAY -> context.getString(R.string.relative_time_today) difference < MILLISECONDS_IN_DAY.times(range) -> context.resources.getQuantityString( R.plurals.relative_time, days, days, ) else -> dateFormat.format(this) } } private val Date.timeWithOffset: Long get() { return Calendar.getInstance().run { time = this@timeWithOffset val dstOffset = get(Calendar.DST_OFFSET) [email protected] + timeZone.rawOffset + dstOffset } } fun Long.floorNearest(to: Long): Long { return this.floorDiv(to) * to }
apache-2.0
e88739ce7f681dee419d634b57387ea6
27.507353
129
0.652566
4.005165
false
false
false
false
DevJake/SaltBot-2.0
src/main/kotlin/me/salt/utilities/util/MathUtil.kt
1
3201
/* * Copyright 2017 DevJake * * 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 me.salt.utilities.util import java.util.regex.Pattern object MathUtil { private val xPlusY = Pattern.compile("(-?[a-zA-Z0-9]+)\\s*[+]\\s*(-?[a-zA-Z0-9]+)") private val xDivY = Pattern.compile("(-?[a-zA-Z0-9]+)\\s*[/]\\s*(-?[a-zA-Z0-9]+)") private val xMultY = Pattern.compile("(-?[a-zA-Z0-9]+)\\s*[*]\\s*(-?[a-zA-Z0-9]+)") private val xMinusY = Pattern.compile("(-?[a-zA-Z0-9]+)\\s*[-]\\s*(-?[a-zA-Z0-9]+)") private val xBracketsY = Pattern.compile("([a-zA-Z0-9]+)\\s*\\(\\s*([a-zA-Z0-9\\-*+/]+\\s*)\\)") private val xPowY = Pattern.compile("(-?[a-zA-Z0-9]+)\\s*\\^\\s*(-?[a-zA-Z0-9]+)") /* For solving equations -> split equation down to smaller chunks -> note relation between chunks (add, subtract, powerof, etc) -> calculate chunks separately, note results -> compile outcomes together For resolving equation for 'x': -> locate '=' operator, if present -> simplify both sides as much as possible -> substitute desired value from left-to-right, or right-to-left, depending on complexity -> pass equation through algorithm to determine complexity (?) Some example inputs aiming to be supported: -> (2^3)+4 -> 2^3+4 -> (x) 2x+3y=7y //(val) indicates the value to be found -> (x) 2x+3y=9y-2 -> (x, y) 2x+3y=9y-2 -> -s 3x+2y-x+y^2 //-s indicates to 'simplify' -> x:2 y:1 2x+3y=9y-2 //Calculate for given values -> x:2 2x+3y=9y-2 //Calculate for given values -> n:1->10:2 2n^x //Print out the values of 1->10 in steps of 2, assigning val to n. Equivalent of sigma notation -> n:1->10:2 x:3 2n^x //As above, but substituting in x as 3 -> (2x+3y)(a-2b) //expand -> (x) (2x+3y)(a-2b) //expand and resolve for x (if possible) -> -s (2x+3y)(a-2b) //expand and simplify (if possible) Constants and operators -> pi as Pi -> sin(x) as Sine(x) -> cos(x) as Cosine(x) -> tan(x) as Tangent(x) -> sqrt(x) as Square-root(x) -> (n)rt(x) as n'th-root(x) */ private fun parse(expression: String): List<Expression> { TODO() } infix fun solveFor(element: String): Expression { TODO() } fun simplify(expression: Expression): Expression { TODO() } fun evaluate(expression: Expression): Expression { TODO() } } data class MathElementContainer(val lhs: Expression, val rhs: Expression, val operator: MathOperator) enum class MathOperator { MULT, DIV, SUB, ADD, POW, ROOT, SIN, COS, TAN } data class Expression(val value: Double, val expr: String)
apache-2.0
b5746e0c721f1926557cb892021c3b4d
30.70297
117
0.617932
3.169307
false
false
false
false
geeteshk/Hyper
app/src/main/java/io/geeteshk/hyper/ui/adapter/FileAdapter.kt
1
2318
/* * Copyright 2016 Geetesh Kalakoti <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.geeteshk.hyper.ui.adapter import android.content.Context import android.graphics.Typeface import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import io.geeteshk.hyper.R import io.geeteshk.hyper.extensions.inflate import io.geeteshk.hyper.util.editor.ResourceHelper import kotlinx.android.synthetic.main.item_file_project.view.* import java.io.File class FileAdapter(context: Context, private var openFiles: ArrayList<String>) : ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, openFiles) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val rootView: View = convertView ?: parent.inflate(R.layout.item_file_project) ResourceHelper.setIcon(rootView.fileIcon, File(openFiles[position]), 0xffffffff.toInt()) rootView.fileTitle.text = getPageTitle(position) rootView.fileTitle.setTextColor(0xffffffff.toInt()) rootView.fileTitle.typeface = Typeface.DEFAULT_BOLD return rootView } override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View { val rootView: View = convertView ?: parent.inflate(R.layout.item_file_project) ResourceHelper.setIcon(rootView.fileIcon, File(openFiles[position]), 0xffffffff.toInt()) rootView.fileTitle.text = getPageTitle(position) return rootView } private fun getPageTitle(position: Int): CharSequence = File(openFiles[position]).name override fun getCount(): Int = openFiles.size fun update(newFiles: ArrayList<String>) { openFiles.clear() openFiles.addAll(newFiles) notifyDataSetChanged() } }
apache-2.0
4dcc7d4eaf3ed8524621398d5937fba5
39.666667
159
0.742019
4.268877
false
false
false
false
Adventech/sabbath-school-android-2
common/design-compose/src/main/kotlin/app/ss/design/compose/extensions/Ext.kt
1
1549
/* * Copyright (c) 2022. Adventech <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package app.ss.design.compose.extensions import android.os.Build import androidx.annotation.ChecksSdkIntAtLeast import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalConfiguration @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.S) fun isS() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S @Composable fun isLargeScreen(): Boolean = LocalConfiguration.current.screenWidthDp >= 600
mit
41cec78151d06a82d0b1440c3b08cb3c
44.558824
80
0.777921
4.338936
false
true
false
false
k9mail/k-9
mail/common/src/main/java/com/fsck/k9/mail/internet/PartExtensions.kt
2
953
@file:JvmName("PartExtensions") package com.fsck.k9.mail.internet import com.fsck.k9.mail.Part /** * Return the `charset` parameter value of this [Part]'s `Content-Type` header. */ val Part.charset: String? get() { val contentTypeHeader = this.contentType ?: return null val (_, parameters, duplicateParameters) = MimeParameterDecoder.decodeBasic(contentTypeHeader) return parameters["charset"] ?: extractNonConflictingCharsetValue(duplicateParameters) } // If there are multiple "charset" parameters, but they all agree on the value, we use that value. private fun extractNonConflictingCharsetValue(duplicateParameters: List<Pair<String, String>>): String? { val charsets = duplicateParameters.asSequence() .filter { (parameterName, _) -> parameterName == "charset" } .map { (_, charset) -> charset.lowercase() } .toSet() return if (charsets.size == 1) charsets.first() else null }
apache-2.0
2611ce2d37451816d41d07c2cd7a2624
38.708333
105
0.704092
4.179825
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/motion/mark/MotionGotoFileMarkAction.kt
1
2032
/* * 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.action.motion.mark import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.MotionType import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.handler.Motion import com.maddyhome.idea.vim.handler.MotionActionHandler import com.maddyhome.idea.vim.handler.toMotionOrError import java.util.* class MotionGotoFileMarkAction : MotionActionHandler.ForEachCaret() { override val motionType: MotionType = MotionType.EXCLUSIVE override val argumentType: Argument.Type = Argument.Type.CHARACTER override val flags: EnumSet<CommandFlags> = EnumSet.of(CommandFlags.FLAG_SAVE_JUMP) override fun getOffset( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument?, operatorArguments: OperatorArguments, ): Motion { if (argument == null) return Motion.Error val mark = argument.character return injector.motion.moveCaretToFileMark(editor, mark, false).toMotionOrError() } } class MotionGotoFileMarkNoSaveJumpAction : MotionActionHandler.ForEachCaret() { override val motionType: MotionType = MotionType.EXCLUSIVE override val argumentType: Argument.Type = Argument.Type.CHARACTER override fun getOffset( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument?, operatorArguments: OperatorArguments, ): Motion { if (argument == null) return Motion.Error val mark = argument.character return injector.motion.moveCaretToFileMark(editor, mark, false).toMotionOrError() } }
mit
89a2f1a2917976110760fbc9eaf7d273
31.774194
85
0.777559
4.259958
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/photopicker/PhotoPickerActionModeCallback.kt
1
2802
package org.wordpress.android.ui.photopicker import android.view.Menu import android.view.MenuItem import androidx.appcompat.view.ActionMode import androidx.appcompat.view.ActionMode.Callback import androidx.lifecycle.Lifecycle import androidx.lifecycle.Lifecycle.Event.ON_START import androidx.lifecycle.Lifecycle.Event.ON_STOP import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import androidx.lifecycle.Observer import org.wordpress.android.R import org.wordpress.android.R.id import org.wordpress.android.ui.utils.UiString.UiStringRes import org.wordpress.android.ui.utils.UiString.UiStringText @Suppress("DEPRECATION") @Deprecated("This class is being refactored, if you implement any change, please also update " + "{@link org.wordpress.android.ui.mediapicker.MedaPickerActionModeCallback}") class PhotoPickerActionModeCallback( private val viewModel: PhotoPickerViewModel ) : Callback, LifecycleOwner { private lateinit var lifecycleRegistry: LifecycleRegistry @Suppress("DEPRECATION") override fun onCreateActionMode( actionMode: ActionMode, menu: Menu ): Boolean { lifecycleRegistry = LifecycleRegistry(this) lifecycleRegistry.handleLifecycleEvent(ON_START) viewModel.uiState.observe(this, Observer { uiState -> when (val uiModel = uiState.actionModeUiModel) { is PhotoPickerViewModel.ActionModeUiModel.Hidden -> { actionMode.finish() } is PhotoPickerViewModel.ActionModeUiModel.Visible -> { if (uiModel.showConfirmAction && menu.size() == 0) { val inflater = actionMode.menuInflater inflater.inflate(R.menu.photo_picker_action_mode, menu) } if (uiModel.actionModeTitle is UiStringText) { actionMode.title = uiModel.actionModeTitle.text } else if (uiModel.actionModeTitle is UiStringRes) { actionMode.setTitle(uiModel.actionModeTitle.stringRes) } } } }) return true } override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean { return false } override fun onActionItemClicked( mode: ActionMode, item: MenuItem ): Boolean { if (item.itemId == id.mnu_confirm_selection) { viewModel.performInsertAction() return true } return false } override fun onDestroyActionMode(mode: ActionMode) { viewModel.clearSelection() lifecycleRegistry.handleLifecycleEvent(ON_STOP) } override fun getLifecycle(): Lifecycle = lifecycleRegistry }
gpl-2.0
ddeca8638ca54fdaad45c1d1b351e35e
35.38961
96
0.668808
5.286792
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/jetpackoverlay/JetpackFeatureFullScreenOverlayViewModel.kt
1
5334
package org.wordpress.android.ui.jetpackoverlay import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineDispatcher import org.wordpress.android.modules.UI_THREAD import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureRemovalOverlayUtil.JetpackFeatureOverlayScreenType import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureRemovalOverlayUtil.JetpackOverlayDismissalType.CLOSE_BUTTON import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureRemovalOverlayUtil.JetpackOverlayDismissalType.CONTINUE_BUTTON import org.wordpress.android.ui.sitecreation.misc.SiteCreationSource import org.wordpress.android.ui.sitecreation.misc.SiteCreationSource.UNSPECIFIED import org.wordpress.android.viewmodel.ScopedViewModel import javax.inject.Inject import javax.inject.Named @HiltViewModel class JetpackFeatureFullScreenOverlayViewModel @Inject constructor( @Named(UI_THREAD) mainDispatcher: CoroutineDispatcher, private val jetpackFeatureOverlayContentBuilder: JetpackFeatureOverlayContentBuilder, private val jetpackFeatureRemovalPhaseHelper: JetpackFeatureRemovalPhaseHelper, private val jetpackFeatureRemovalOverlayUtil: JetpackFeatureRemovalOverlayUtil ) : ScopedViewModel(mainDispatcher) { private val _uiState = MutableLiveData<JetpackFeatureOverlayUIState>() val uiState: LiveData<JetpackFeatureOverlayUIState> = _uiState private val _action = MutableLiveData<JetpackFeatureOverlayActions>() val action: LiveData<JetpackFeatureOverlayActions> = _action private lateinit var screenType: JetpackFeatureOverlayScreenType private var isSiteCreationOverlayScreen: Boolean = false private var siteCreationOrigin: SiteCreationSource = UNSPECIFIED private var isDeepLinkOverlayScreen: Boolean = false fun openJetpackAppDownloadLink() { if (isSiteCreationOverlayScreen) { _action.value = JetpackFeatureOverlayActions.OpenPlayStore jetpackFeatureRemovalOverlayUtil.trackInstallJetpackTappedInSiteCreationOverlay(siteCreationOrigin) } else if (isDeepLinkOverlayScreen) { _action.value = JetpackFeatureOverlayActions.ForwardToJetpack jetpackFeatureRemovalOverlayUtil.trackInstallJetpackTappedInDeepLinkOverlay() } else { _action.value = JetpackFeatureOverlayActions.OpenPlayStore jetpackFeatureRemovalOverlayUtil.trackInstallJetpackTapped(screenType) } } fun continueToFeature() { _action.value = JetpackFeatureOverlayActions.DismissDialog if (isSiteCreationOverlayScreen) jetpackFeatureRemovalOverlayUtil.trackBottomSheetDismissedInSiteCreationOverlay( siteCreationOrigin, CONTINUE_BUTTON ) else if (isDeepLinkOverlayScreen) jetpackFeatureRemovalOverlayUtil.trackBottomSheetDismissedInDeepLinkOverlay(CONTINUE_BUTTON) else jetpackFeatureRemovalOverlayUtil.trackBottomSheetDismissed(screenType, CONTINUE_BUTTON) } fun closeBottomSheet() { _action.value = JetpackFeatureOverlayActions.DismissDialog if (isSiteCreationOverlayScreen) jetpackFeatureRemovalOverlayUtil.trackBottomSheetDismissedInSiteCreationOverlay( siteCreationOrigin, CLOSE_BUTTON ) else if (isDeepLinkOverlayScreen) jetpackFeatureRemovalOverlayUtil.trackBottomSheetDismissedInDeepLinkOverlay(CLOSE_BUTTON) else jetpackFeatureRemovalOverlayUtil.trackBottomSheetDismissed(screenType, CLOSE_BUTTON) } @Suppress("ReturnCount") fun init( overlayScreenType: JetpackFeatureOverlayScreenType?, isSiteCreationOverlay: Boolean, isDeepLinkOverlay: Boolean, siteCreationSource: SiteCreationSource, rtlLayout: Boolean ) { if (isSiteCreationOverlay) { isSiteCreationOverlayScreen = true siteCreationOrigin = siteCreationSource _uiState.postValue( jetpackFeatureOverlayContentBuilder.buildSiteCreationOverlayState( getSiteCreationPhase()!!, rtlLayout ) ) jetpackFeatureRemovalOverlayUtil.trackSiteCreationOverlayShown(siteCreationOrigin) return } if (isDeepLinkOverlay) { isDeepLinkOverlayScreen = true _uiState.postValue(jetpackFeatureOverlayContentBuilder.buildDeepLinkOverlayState(rtlLayout)) jetpackFeatureRemovalOverlayUtil.trackDeepLinkOverlayShown() return } screenType = overlayScreenType ?: return val params = JetpackFeatureOverlayContentBuilderParams( currentPhase = getCurrentPhase()!!, isRtl = rtlLayout, feature = overlayScreenType ) _uiState.postValue(jetpackFeatureOverlayContentBuilder.build(params = params)) jetpackFeatureRemovalOverlayUtil.onOverlayShown(overlayScreenType) } private fun getCurrentPhase() = jetpackFeatureRemovalPhaseHelper.getCurrentPhase() private fun getSiteCreationPhase() = jetpackFeatureRemovalPhaseHelper.getSiteCreationPhase() }
gpl-2.0
c95dae4fa32da072aa06cbb4dba0257b
45.789474
123
0.749344
5.516029
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/ui/fragments/editpost/EditPostFragment.kt
1
10182
package forpdateam.ru.forpda.ui.fragments.editpost import android.app.Activity import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AlertDialog import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.Toast import moxy.presenter.InjectPresenter import moxy.presenter.ProvidePresenter import forpdateam.ru.forpda.App import forpdateam.ru.forpda.R import forpdateam.ru.forpda.common.FilePickHelper import forpdateam.ru.forpda.entity.remote.editpost.AttachmentItem import forpdateam.ru.forpda.entity.remote.editpost.EditPostForm import forpdateam.ru.forpda.entity.remote.theme.ThemePage import forpdateam.ru.forpda.model.data.remote.api.RequestFile import forpdateam.ru.forpda.presentation.editpost.EditPostPresenter import forpdateam.ru.forpda.presentation.editpost.EditPostView import forpdateam.ru.forpda.ui.fragments.TabFragment import forpdateam.ru.forpda.ui.views.messagepanel.MessagePanel import forpdateam.ru.forpda.ui.views.messagepanel.attachments.AttachmentsPopup /** * Created by radiationx on 14.01.17. */ class EditPostFragment : TabFragment(), EditPostView { private var formType = 0 private lateinit var messagePanel: MessagePanel private lateinit var attachmentsPopup: AttachmentsPopup private var pollPopup: EditPollPopup? = null @InjectPresenter lateinit var presenter: EditPostPresenter @ProvidePresenter fun providePresenter(): EditPostPresenter = EditPostPresenter( App.get().Di().editPostRepository, App.get().Di().themeTemplate, App.get().Di().router, App.get().Di().errorHandler ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.apply { val postForm = EditPostForm() postForm.type = getInt(EditPostForm.ARG_TYPE) formType = postForm.type getParcelableArrayList<AttachmentItem>(ARG_ATTACHMENTS)?.also { postForm.attachments.addAll(it) } postForm.message = getString(ARG_MESSAGE, "") postForm.forumId = getInt(ARG_FORUM_ID) postForm.topicId = getInt(ARG_TOPIC_ID) postForm.postId = getInt(ARG_POST_ID) postForm.st = getInt(ARG_ST) presenter.initPostForm(postForm) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) messagePanel = MessagePanel(context, fragmentContainer, fragmentContent, true) attachmentsPopup = messagePanel.attachmentsPopup return viewFragment } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) messagePanel.addSendOnClickListener { presenter.onSendClick() } attachmentsPopup.setAddOnClickListener { tryPickFile() } attachmentsPopup.setDeleteOnClickListener { removeFiles() } arguments?.apply { val title = getString(ARG_THEME_NAME, "") setTitle("${App.get().getString(if (formType == EditPostForm.TYPE_NEW_POST) R.string.editpost_title_answer else R.string.editpost_title_edit)} $title") } messagePanel.editPollButton.setOnClickListener { pollPopup?.show() } } override fun onResumeOrShow() { super.onResumeOrShow() messagePanel.onResume() } override fun onPauseOrHide() { super.onPauseOrHide() messagePanel.onPause() } override fun onDestroy() { super.onDestroy() messagePanel.onDestroy() } override fun hideKeyboard() { super.hideKeyboard() messagePanel.hidePopupWindows() } override fun onBackPressed(): Boolean { super.onBackPressed() if (messagePanel.onBackPressed()) return true if (showExitDialog()) { return true } //Синхронизация с полем в фрагменте темы if (formType == EditPostForm.TYPE_NEW_POST) { showSyncDialog() return true } return false } private fun tryPickFile() { App.get().checkStoragePermission({ startActivityForResult(FilePickHelper.pickFile(false), TabFragment.REQUEST_PICK_FILE) }, App.getActivity()) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == TabFragment.REQUEST_PICK_FILE && resultCode == Activity.RESULT_OK) { if (data == null) { //Display an error return } uploadFiles(FilePickHelper.onActivityResult(context, data)) } } override fun showForm(form: EditPostForm) { if (form.errorCode != EditPostForm.ERROR_NONE) { Toast.makeText(context, R.string.editpost_error_edit, Toast.LENGTH_SHORT).show() presenter.exit() return } if (form.poll != null) { pollPopup = EditPollPopup(context) pollPopup?.setPoll(form.poll) messagePanel.editPollButton.visibility = View.VISIBLE } else { messagePanel.editPollButton.visibility = View.GONE } attachmentsPopup.onLoadAttachments(form) messagePanel.insertText(form.message) messagePanel.messageField.requestFocus() showKeyboard(messagePanel.messageField) } override fun setRefreshing(isRefreshing: Boolean) { messagePanel.formProgress.visibility = if (isRefreshing) View.VISIBLE else View.GONE messagePanel.messageField.visibility = if (isRefreshing) View.GONE else View.VISIBLE messagePanel.formProgress.visibility = View.GONE } override fun setSendRefreshing(isRefreshing: Boolean) { messagePanel.setProgressState(isRefreshing) } override fun sendMessage() { presenter.sendMessage(messagePanel.message, messagePanel.attachments) } override fun onPostSend(page: ThemePage, form: EditPostForm) { presenter.exitWithPage(page) } fun uploadFiles(files: List<RequestFile>) { val pending = attachmentsPopup.preUploadFiles(files) presenter.uploadFiles(files, pending) } private fun removeFiles() { attachmentsPopup.preDeleteFiles() val selectedFiles = attachmentsPopup.getSelected() presenter.deleteFiles(selectedFiles) } override fun onUploadFiles(items: List<AttachmentItem>) { attachmentsPopup.onUploadFiles(items) } override fun onDeleteFiles(items: List<AttachmentItem>) { attachmentsPopup.onDeleteFiles(items) } override fun showReasonDialog(form: EditPostForm) { val view = View.inflate(context, R.layout.edit_post_reason, null) val editText = view.findViewById<View>(R.id.edit_post_reason_field) as EditText editText.setText(form.editReason) AlertDialog.Builder(context!!) .setTitle(R.string.editpost_reason) .setView(view) .setPositiveButton(R.string.send) { _, _ -> presenter.onReasonEdit(editText.text.toString()) } .setNegativeButton(R.string.cancel, null) .show() } private fun showExitDialog(): Boolean { if (formType == EditPostForm.TYPE_EDIT_POST) { AlertDialog.Builder(context!!) .setMessage(R.string.editpost_lose_changes) .setPositiveButton(R.string.yes) { _, _ -> presenter.exit() } .setNegativeButton(R.string.no, null) .show() return true } return false } private fun showSyncDialog() { AlertDialog.Builder(context!!) .setMessage(R.string.editpost_sync) .setPositiveButton(R.string.ok) { _, _ -> val selectionRange = messagePanel.selectionRange presenter.exitWithSync( messagePanel.message, selectionRange, messagePanel.attachments ) } .setNegativeButton(R.string.no) { _, _ -> if (!showExitDialog()) { presenter.exit() } } .show() } companion object { const val ARG_THEME_NAME = "theme_name" const val ARG_ATTACHMENTS = "attachments" const val ARG_MESSAGE = "message" const val ARG_FORUM_ID = "forumId" const val ARG_TOPIC_ID = "topicId" const val ARG_POST_ID = "postId" const val ARG_ST = "st" fun fillArguments(args: Bundle, postId: Int, topicId: Int, forumId: Int, st: Int, themeName: String?): Bundle { if (themeName != null) args.putString(ARG_THEME_NAME, themeName) args.putInt(EditPostForm.ARG_TYPE, EditPostForm.TYPE_EDIT_POST) args.putInt(ARG_FORUM_ID, forumId) args.putInt(ARG_TOPIC_ID, topicId) args.putInt(ARG_POST_ID, postId) args.putInt(ARG_ST, st) return args } fun fillArguments(args: Bundle, form: EditPostForm, themeName: String?): Bundle { if (themeName != null) args.putString(ARG_THEME_NAME, themeName) args.putInt(EditPostForm.ARG_TYPE, EditPostForm.TYPE_NEW_POST) args.putParcelableArrayList(ARG_ATTACHMENTS, form.attachments) args.putString(ARG_MESSAGE, form.message) args.putInt(ARG_FORUM_ID, form.forumId) args.putInt(ARG_TOPIC_ID, form.topicId) args.putInt(ARG_POST_ID, form.postId) args.putInt(ARG_ST, form.st) return args } } }
gpl-3.0
7965797b5b1b58d8319cfae803051261
34.486014
163
0.633856
4.696437
false
false
false
false