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
pokk/SSFM
app/src/main/kotlin/taiwan/no1/app/ssfm/misc/extension/imageview/BindingAdapter.kt
1
2132
package taiwan.no1.app.ssfm.misc.extension.imageview import android.databinding.BindingAdapter import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.widget.ImageView import com.bumptech.glide.Glide import com.bumptech.glide.Priority import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.RequestOptions import com.mikhaellopez.circularimageview.CircularImageView /** * @author jieyi * @since 10/13/17 */ @BindingAdapter("android:src") fun ImageView.setSrc(bitmap: Bitmap) = setImageBitmap(bitmap) @BindingAdapter("android:src") fun ImageView.setSrc(resId: Int) = setImageResource(resId) @BindingAdapter("android:bkgDrawable") fun ImageView.setBackgroundDrawable(drawable: Drawable?) { drawable?.let { background = it } } @BindingAdapter("android:imageUrl", "android:placeHolder", "android:error", "android:imgHeight", "android:imgWidth", "android:fitCenter", "android:imgCallback", requireAll = false) fun ImageView.loadImage(url: String?, holderDrawable: Drawable?, errorDrawable: Drawable?, imgHeight: Int?, imgWidth: Int?, isFitCenter: Boolean = false, listener: RequestListener<Bitmap>?) { if (!url.isNullOrBlank()) { Glide.with(context).asBitmap().load(url).apply(RequestOptions().apply { if (isFitCenter) fitCenter() else centerCrop() holderDrawable?.let(this::placeholder) errorDrawable?.let(this::error) if (null != imgHeight && null != imgWidth) override(imgWidth, imgHeight) priority(Priority.HIGH) diskCacheStrategy(DiskCacheStrategy.RESOURCE) }).apply { listener?.let(this::listener) }.into(this) } } @BindingAdapter("android:shadowColor") fun CircularImageView.addShadowColor(color: Int) = setShadowColor(color)
apache-2.0
bae07d22bb899cf4bad30d653b1bc6f8
35.135593
84
0.65197
4.594828
false
false
false
false
nimakro/tornadofx
src/test/kotlin/tornadofx/tests/ListViewFragmentTestView.kt
2
1238
package tornadofx.tests import javafx.beans.property.SimpleStringProperty import javafx.geometry.Pos import javafx.scene.text.FontWeight import tornadofx.* class ListViewTestApp : App(ListViewFragmentTestView::class) class Item(value: String) { val valueProperty = SimpleStringProperty(value) } class MyItemViewModel : ItemViewModel<Item>() { val value = bind { item?.valueProperty } } class PersonListFragment : ListCellFragment<Person>() { val person = PersonModel().bindTo(this) override val root = form { fieldset { field("Name") { label(person.name) } field("Age") { label(person.age) } label(stringBinding(person.age) { "$value years old" }) { alignment = Pos.CENTER_RIGHT style { fontSize = 22.px fontWeight = FontWeight.BOLD } } } } } class ListViewFragmentTestView : View("ListCellFragment Test") { val items = listOf(Person("John", 42), Person("Jane", 24), Person("Tommy", 11)).observable() override val root = listview(items) { cellFragment(PersonListFragment::class) } }
apache-2.0
cf2edf628e35cdfc4f3ebdf3e6338fe7
25.934783
96
0.600162
4.654135
false
true
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/internal/KeymapToCsvAction.kt
7
2654
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.internal import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.KeyboardShortcut import com.intellij.openapi.fileChooser.FileChooserFactory import com.intellij.openapi.fileChooser.FileSaverDescriptor import com.intellij.openapi.keymap.KeymapManager internal class KeymapToCsvAction : AnAction() { override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun actionPerformed(e: AnActionEvent) { val allShortcuts = linkedMapOf<String, MutableMap<String, MutableList<String>>>() val seenModifierSets = mutableSetOf<String>() val columns = mutableListOf("", "shift", "ctrl", "alt", "meta") for (key in 'A'..'Z') { allShortcuts[key.toString()] = hashMapOf() } for (key in '0'..'9') { allShortcuts[key.toString()] = hashMapOf() } for (key in 1..12) { allShortcuts["F$key"] = hashMapOf() } val keymap = KeymapManager.getInstance().activeKeymap for (actionId in keymap.actionIdList) { val shortcuts = keymap.getShortcuts(actionId).filterIsInstance<KeyboardShortcut>() for (shortcut in shortcuts) { val keyStroke = shortcut.firstKeyStroke val str = keyStroke.toString() val keyName = str.substringAfterLast(' ', str) val modifiers = str.substringBeforeLast(' ').replace("pressed", "").trim() seenModifierSets += modifiers val forKey = allShortcuts.getOrPut(keyName) { hashMapOf() } val actionIds = forKey.getOrPut(modifiers) { mutableListOf() } actionIds.add(actionId) } } for (seenModifierSet in seenModifierSets) { if (seenModifierSet !in columns) { columns.add(seenModifierSet) } } val result = buildString { appendln("key," + columns.joinToString(",")) for ((key, shortcutsForKey) in allShortcuts) { append(key) for (column in columns) { append(",") val actionsForShortcut = shortcutsForKey[column] ?: emptyList<String>() append(actionsForShortcut.joinToString("|")) } appendln() } } val dialog = FileChooserFactory.getInstance().createSaveFileDialog( FileSaverDescriptor("Export Keymap to .csv", "Select file to save to:", "csv"), e.project) val virtualFileWrapper = dialog.save(null) virtualFileWrapper?.file?.writeText(result.replace("\n", "\r\n")) } }
apache-2.0
452b7ec134f077931316d553f56a6144
36.928571
120
0.685757
4.607639
false
false
false
false
GunoH/intellij-community
platform/webSymbols/src/com/intellij/webSymbols/query/WebSymbolNameConversionRules.kt
2
1120
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.webSymbols.query import com.intellij.webSymbols.WebSymbolQualifiedKind import com.intellij.webSymbols.query.impl.WebSymbolNameConversionRulesImpl interface WebSymbolNameConversionRules { val canonicalNames: Map<WebSymbolQualifiedKind, WebSymbolNameConverter> val matchNames: Map<WebSymbolQualifiedKind, WebSymbolNameConverter> val nameVariants: Map<WebSymbolQualifiedKind, WebSymbolNameConverter> companion object { @JvmStatic fun create(canonicalNames: Map<WebSymbolQualifiedKind, WebSymbolNameConverter> = emptyMap(), matchNames: Map<WebSymbolQualifiedKind, WebSymbolNameConverter> = emptyMap(), nameVariants: Map<WebSymbolQualifiedKind, WebSymbolNameConverter> = emptyMap()) = WebSymbolNameConversionRulesImpl(canonicalNames, matchNames, nameVariants) @JvmStatic fun empty() = WebSymbolNameConversionRulesImpl.empty @JvmStatic fun builder() = WebSymbolNameConversionRulesBuilder() } }
apache-2.0
509ca1934c2497bd412c7fdb81b9eee9
35.16129
120
0.782143
4.869565
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/conversion/copy/PlainTextPasteImportResolver.kt
1
11178
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.conversion.copy import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.progress.ProgressManager import com.intellij.psi.* import com.intellij.psi.search.PsiShortNamesCache import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMapper import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter import org.jetbrains.kotlin.idea.base.projectStructure.matches import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfoOrNull import org.jetbrains.kotlin.idea.base.util.runReadActionInSmartMode import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMemberDescriptor import org.jetbrains.kotlin.idea.core.isVisible import org.jetbrains.kotlin.idea.imports.canBeReferencedViaImport import org.jetbrains.kotlin.idea.references.mainReference import com.intellij.openapi.application.runReadAction import com.intellij.openapi.application.runWriteAction import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtImportDirective import org.jetbrains.kotlin.psi.psiUtil.referenceExpression import org.jetbrains.kotlin.utils.addToStdlib.safeAs /** * Tested with TextJavaToKotlinCopyPasteConversionTestGenerated */ class PlainTextPasteImportResolver(private val dataForConversion: DataForConversion, val targetFile: KtFile) { private val file = dataForConversion.file private val project = targetFile.project private val importList = file.importList!! // keep access to deprecated PsiElementFactory.SERVICE for bwc with <= 191 private val psiElementFactory = PsiElementFactory.getInstance(project) private val bindingContext by lazy { targetFile.analyzeWithContent() } private val resolutionFacade = targetFile.getResolutionFacade() private val shortNameCache = PsiShortNamesCache.getInstance(project) private val scope = file.resolveScope private val failedToResolveReferenceNames = HashSet<String>() private var ambiguityInResolution = false private var couldNotResolve = false val addedImports = mutableListOf<PsiImportStatementBase>() private fun canBeImported(descriptor: DeclarationDescriptorWithVisibility?): Boolean { return descriptor != null && descriptor.canBeReferencedViaImport() && descriptor.isVisible(targetFile, null, bindingContext, resolutionFacade) } private fun addImport(importStatement: PsiImportStatementBase, shouldAddToTarget: Boolean = false) { file.importList?.let { it.add(importStatement) if (shouldAddToTarget) addedImports.add(importStatement) } } fun addImportsFromTargetFile() { if (importList in dataForConversion.elementsAndTexts.toList()) return val task = { val addImportList = mutableListOf<PsiImportStatementBase>() fun tryConvertKotlinImport(importDirective: KtImportDirective) { val importPath = importDirective.importPath val importedReference = importDirective.importedReference if (importPath != null && !importPath.hasAlias() && importedReference is KtDotQualifiedExpression) { val receiver = importedReference .receiverExpression .referenceExpression() ?.mainReference ?.resolve() val selector = importedReference .selectorExpression ?.referenceExpression() ?.mainReference ?.resolve() val isPackageReceiver = receiver is PsiPackage val isClassReceiver = receiver is PsiClass val isClassSelector = selector is PsiClass if (importPath.isAllUnder) { when { isClassReceiver -> addImportList.add(psiElementFactory.createImportStaticStatement(receiver as PsiClass, "*")) isPackageReceiver -> addImportList.add(psiElementFactory.createImportStatementOnDemand((receiver as PsiPackage).qualifiedName)) } } else { when { isClassSelector -> addImportList.add(psiElementFactory.createImportStatement(selector as PsiClass)) isClassReceiver -> addImportList.add( psiElementFactory.createImportStaticStatement( receiver as PsiClass, importPath.importedName!!.asString() ) ) } } } } runReadAction { val importDirectives = targetFile.importDirectives importDirectives.forEachIndexed { index, value -> ProgressManager.checkCanceled() ProgressManager.getInstance().progressIndicator?.fraction = 1.0 * index / importDirectives.size tryConvertKotlinImport(value) } } ApplicationManager.getApplication().invokeAndWait { runWriteAction { addImportList.forEach { addImport(it) } } } } ProgressManager.getInstance().runProcessWithProgressSynchronously( task, KotlinBundle.message("copy.text.adding.imports"), true, project ) } fun tryResolveReferences() { val task = { fun performWriteAction(block: () -> Unit) { ApplicationManager.getApplication().invokeAndWait { runWriteAction { block() } } } fun tryResolveReference(reference: PsiQualifiedReference): Boolean { ProgressManager.checkCanceled() if (runReadAction { reference.resolve() } != null) return true val referenceName = runReadAction { reference.referenceName } ?: return false if (referenceName in failedToResolveReferenceNames) return false if (runReadAction { reference.qualifier } != null) return false val classes = runReadAction { shortNameCache.getClassesByName(referenceName, scope) .mapNotNull { psiClass -> val containingFile = psiClass.containingFile if (RootKindFilter.everything.matches(containingFile)) { psiClass to psiClass.getJavaMemberDescriptor() as? ClassDescriptor } else null }.filter { canBeImported(it.second) } } classes.find { (_, descriptor) -> JavaToKotlinClassMapper.mapPlatformClass(descriptor!!).isNotEmpty() }?.let { (psiClass, _) -> performWriteAction { addImport(psiElementFactory.createImportStatement(psiClass)) } } if (runReadAction { reference.resolve() } != null) return true classes.singleOrNull()?.let { (psiClass, _) -> performWriteAction { addImport(psiElementFactory.createImportStatement(psiClass), true) } } when { runReadAction { reference.resolve() } != null -> return true classes.isNotEmpty() -> { ambiguityInResolution = true return false } } val members = runReadAction { (shortNameCache.getMethodsByName(referenceName, scope).asList() + shortNameCache.getFieldsByName(referenceName, scope).asList()) .asSequence() .map { it as PsiMember } .filter { it.moduleInfoOrNull != null } .map { it to it.getJavaMemberDescriptor(resolutionFacade) as? DeclarationDescriptorWithVisibility } .filter { canBeImported(it.second) } .toList() } ProgressManager.checkCanceled() members.singleOrNull()?.let { (psiMember, _) -> performWriteAction { addImport( psiElementFactory.createImportStaticStatement(psiMember.containingClass!!, psiMember.name!!), true ) } } when { runReadAction { reference.resolve() } != null -> return false members.isNotEmpty() -> ambiguityInResolution = true else -> couldNotResolve = true } return false } val smartPointerManager = SmartPointerManager.getInstance(file.project) val elementsWithUnresolvedRef = project.runReadActionInSmartMode { PsiTreeUtil.collectElements(file) { element -> element.reference != null && element.reference is PsiQualifiedReference && element.reference?.resolve() == null }.map { smartPointerManager.createSmartPsiElementPointer(it) } } val reversed = elementsWithUnresolvedRef.reversed() val progressIndicator = ProgressManager.getInstance().progressIndicator progressIndicator?.isIndeterminate = false reversed.forEachIndexed { index, value -> progressIndicator?.fraction = 1.0 * index / reversed.size runReadAction { value.element?.reference?.safeAs<PsiQualifiedReference>() }?.let { reference -> if (!tryResolveReference(reference)) { runReadAction { reference.referenceName }?.let { failedToResolveReferenceNames += it } } } } } ProgressManager.checkCanceled() ProgressManager.getInstance().runProcessWithProgressSynchronously( task, KotlinBundle.message("copy.text.resolving.references"), true, project ) } }
apache-2.0
8efb019e0fbd6844a9ad4069beafee18
45.966387
158
0.598587
6.435233
false
false
false
false
vickychijwani/kotlin-koans-android
app/src/main/code/me/vickychijwani/kotlinkoans/util/app_utils.kt
1
2547
package me.vickychijwani.kotlinkoans.util import android.app.Activity import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.widget.Toast import com.crashlytics.android.Crashlytics import com.getkeepsafe.taptargetview.TapTarget import me.vickychijwani.kotlinkoans.R fun emailDeveloper(activity: Activity) { val emailSubject = activity.getString(R.string.email_subject, activity.getString(R.string.app_name)) val intent = Intent(Intent.ACTION_SENDTO) intent.data = Uri.parse("mailto:") // only email apps should handle this intent.putExtra(Intent.EXTRA_EMAIL, arrayOf("[email protected]")) intent.putExtra(Intent.EXTRA_SUBJECT, emailSubject) var body = "App version: " + getAppVersion(activity) + "\n" body += "Android API version: " + Build.VERSION.SDK_INT + "\n" body += "\n" intent.putExtra(Intent.EXTRA_TEXT, body) if (intent.resolveActivity(activity.packageManager) != null) { activity.startActivity(intent) } else { Toast.makeText(activity, R.string.intent_no_apps, Toast.LENGTH_LONG) .show() } } fun getAppVersion(context: Context): String { try { val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0) if (packageInfo != null) { return packageInfo.versionName } else { return context.getString(R.string.version_unknown) } } catch (e: PackageManager.NameNotFoundException) { Crashlytics.logException(RuntimeException("Failed to get package info, " + "see previous exception for details", e)) return context.getString(R.string.version_unknown) } } fun TapTarget.styleWithDefaults(): TapTarget { return this .outerCircleColor(R.color.tip_background) .titleTextColor(R.color.text_primary) .titleTextSize(18) .descriptionTextColor(R.color.text_primary) .descriptionTextSize(15) .outerCircleAlpha(1f) } fun openPlayStore(context: Context) { val appPackageName = context.packageName try { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName))) } catch (anfe: android.content.ActivityNotFoundException) { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName))) } }
mit
cf462eb35b98d1383e3f08f82bc64626
35.913043
124
0.691009
4.17541
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/profile/links/added/ProfileLinksFragment.kt
1
2159
package io.github.feelfreelinux.wykopmobilny.ui.modules.profile.links.added import android.os.Bundle import io.github.feelfreelinux.wykopmobilny.base.BaseLinksFragment import io.github.feelfreelinux.wykopmobilny.ui.modules.profile.ProfileActivity import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi import javax.inject.Inject class ProfileLinksFragment : BaseLinksFragment(), ProfileLinksView { companion object { const val TYPE_PUBLISHED = "TYPE_PUBLISHED" const val TYPE_DIGGED = "TYPE_DIGGED" const val TYPE_BURRIED = "TYPE_BURRIED" const val TYPE_ADDED = "TYPE_ADDED" const val EXTRA_TYPE = "TYPE" /** * Type determines data coming to this fragment. * @param type Type string TYPE_PUBLISHED / TYPE_DIGGED / TYPE_BURRIED / TYPE_ADDED */ fun newInstance(type: String): androidx.fragment.app.Fragment { val fragment = ProfileLinksFragment() val bundle = Bundle() bundle.putString(EXTRA_TYPE, type) fragment.arguments = bundle return fragment } } @Inject lateinit var userManager: UserManagerApi @Inject lateinit var presenter: ProfileLinksPresenter private val extraType by lazy { arguments?.getString(EXTRA_TYPE) } private val username by lazy { (activity as ProfileActivity).username } override var loadDataListener: (Boolean) -> Unit = { when (extraType) { TYPE_PUBLISHED -> presenter.loadPublished(it) TYPE_DIGGED -> presenter.loadDigged(it) TYPE_BURRIED -> presenter.loadBurried(it) TYPE_ADDED -> presenter.loadAdded(it) } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) presenter.subscribe(this) presenter.username = username linksAdapter.linksActionListener = presenter linksAdapter.loadNewDataListener = { loadDataListener(false) } loadDataListener(true) } override fun onDestroy() { presenter.unsubscribe() super.onDestroy() } }
mit
b47e30bea014510fe7223482071923b4
35.610169
91
0.679481
4.663067
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/pushDownConflictsUtils.kt
3
11083
// 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.refactoring.pushDown import com.intellij.psi.PsiElement import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.util.CommonRefactoringUtil import com.intellij.refactoring.util.RefactoringUIUtil import com.intellij.usageView.UsageInfo import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.refactoring.memberInfo.KtPsiClassWrapper import org.jetbrains.kotlin.idea.refactoring.pullUp.renderForConflicts import org.jetbrains.kotlin.idea.references.KtReference 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.languageVersionSettings import org.jetbrains.kotlin.idea.util.getTypeSubstitution import org.jetbrains.kotlin.idea.util.orEmpty import org.jetbrains.kotlin.idea.util.toSubstitutor import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.util.getCalleeExpressionIfAny import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.scopes.receivers.Qualifier import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.TypeSubstitutor import org.jetbrains.kotlin.util.findCallableMemberBySignature fun analyzePushDownConflicts( context: KotlinPushDownContext, usages: Array<out UsageInfo> ): MultiMap<PsiElement, String> { val targetClasses = usages.mapNotNull { it.element?.unwrapped } val conflicts = MultiMap<PsiElement, String>() val membersToPush = ArrayList<KtNamedDeclaration>() val membersToKeepAbstract = ArrayList<KtNamedDeclaration>() for (info in context.membersToMove) { val member = info.member if (!info.isChecked || ((member is KtClassOrObject || member is KtPsiClassWrapper) && info.overrides != null)) continue membersToPush += member if ((member is KtNamedFunction || member is KtProperty) && info.isToAbstract && (context.memberDescriptors[member] as CallableMemberDescriptor).modality != Modality.ABSTRACT) { membersToKeepAbstract += member } } for (targetClass in targetClasses) { checkConflicts(conflicts, context, targetClass, membersToKeepAbstract, membersToPush) } return conflicts } private fun checkConflicts( conflicts: MultiMap<PsiElement, String>, context: KotlinPushDownContext, targetClass: PsiElement, membersToKeepAbstract: List<KtNamedDeclaration>, membersToPush: ArrayList<KtNamedDeclaration> ) { if (targetClass !is KtClassOrObject) { conflicts.putValue( targetClass, KotlinBundle.message( "text.non.kotlin.0.will.not.be.affected.by.refactoring", RefactoringUIUtil.getDescription(targetClass, false) ) ) return } val targetClassDescriptor = context.resolutionFacade.resolveToDescriptor(targetClass) as ClassDescriptor val sourceClassType = context.sourceClassDescriptor.defaultType val substitutor = getTypeSubstitution(sourceClassType, targetClassDescriptor.defaultType)?.toSubstitutor().orEmpty() if (!context.sourceClass.isInterface() && targetClass is KtClass && targetClass.isInterface()) { val message = KotlinBundle.message( "text.0.inherits.from.1.it.will.not.be.affected.by.refactoring", targetClassDescriptor.renderForConflicts(), context.sourceClassDescriptor.renderForConflicts() ) conflicts.putValue(targetClass, message.capitalize()) } for (member in membersToPush) { checkMemberClashing(conflicts, context, member, membersToKeepAbstract, substitutor, targetClass, targetClassDescriptor) checkSuperCalls(conflicts, context, member, membersToPush) checkExternalUsages(conflicts, member, targetClassDescriptor, context.resolutionFacade) checkVisibility(conflicts, context, member, targetClassDescriptor) } } private fun checkMemberClashing( conflicts: MultiMap<PsiElement, String>, context: KotlinPushDownContext, member: KtNamedDeclaration, membersToKeepAbstract: List<KtNamedDeclaration>, substitutor: TypeSubstitutor, targetClass: KtClassOrObject, targetClassDescriptor: ClassDescriptor ) { when (member) { is KtNamedFunction, is KtProperty -> { val memberDescriptor = context.memberDescriptors[member] as CallableMemberDescriptor val clashingDescriptor = targetClassDescriptor.findCallableMemberBySignature(memberDescriptor.substitute(substitutor) as CallableMemberDescriptor) val clashingDeclaration = clashingDescriptor?.source?.getPsi() as? KtNamedDeclaration if (clashingDescriptor != null && clashingDeclaration != null) { if (memberDescriptor.modality != Modality.ABSTRACT && member !in membersToKeepAbstract) { val message = KotlinBundle.message( "text.0.already.contains.1", targetClassDescriptor.renderForConflicts(), clashingDescriptor.renderForConflicts() ) conflicts.putValue(clashingDeclaration, CommonRefactoringUtil.capitalize(message)) } if (!clashingDeclaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) { val message = KotlinBundle.message( "text.0.in.1.will.override.corresponding.member.of.2.after.refactoring", clashingDescriptor.renderForConflicts(), targetClassDescriptor.renderForConflicts(), context.sourceClassDescriptor.renderForConflicts() ) conflicts.putValue(clashingDeclaration, CommonRefactoringUtil.capitalize(message)) } } } is KtClassOrObject -> { targetClass.declarations .asSequence() .filterIsInstance<KtClassOrObject>() .firstOrNull() { it.name == member.name } ?.let { val message = KotlinBundle.message( "text.0.already.contains.nested.class.1", targetClassDescriptor.renderForConflicts(), CommonRefactoringUtil.htmlEmphasize(member.name ?: "") ) conflicts.putValue(it, message.capitalize()) } } } } private fun checkSuperCalls( conflicts: MultiMap<PsiElement, String>, context: KotlinPushDownContext, member: KtNamedDeclaration, membersToPush: ArrayList<KtNamedDeclaration> ) { member.accept( object : KtTreeVisitorVoid() { override fun visitSuperExpression(expression: KtSuperExpression) { val qualifiedExpression = expression.getQualifiedExpressionForReceiver() ?: return val refExpr = qualifiedExpression.selectorExpression.getCalleeExpressionIfAny() as? KtSimpleNameExpression ?: return for (descriptor in refExpr.mainReference.resolveToDescriptors(context.sourceClassContext)) { val memberDescriptor = descriptor as? CallableMemberDescriptor ?: continue val containingClass = memberDescriptor.containingDeclaration as? ClassDescriptor ?: continue if (!DescriptorUtils.isSubclass(context.sourceClassDescriptor, containingClass)) continue val memberInSource = context.sourceClassDescriptor.findCallableMemberBySignature(memberDescriptor)?.source?.getPsi() ?: continue if (memberInSource !in membersToPush) { conflicts.putValue( qualifiedExpression, KotlinBundle.message("text.pushed.member.will.not.be.available.in.0", qualifiedExpression.text) ) } } } } ) } internal fun checkExternalUsages( conflicts: MultiMap<PsiElement, String>, member: PsiElement, targetClassDescriptor: ClassDescriptor, resolutionFacade: ResolutionFacade ) { for (ref in ReferencesSearch.search(member, member.resolveScope, false)) { val calleeExpr = ref.element as? KtSimpleNameExpression ?: continue val resolvedCall = calleeExpr.getResolvedCall(resolutionFacade.analyze(calleeExpr)) ?: continue val callElement = resolvedCall.call.callElement val dispatchReceiver = resolvedCall.dispatchReceiver if (dispatchReceiver == null || dispatchReceiver is Qualifier) continue val receiverClassDescriptor = dispatchReceiver.type.constructor.declarationDescriptor as? ClassDescriptor ?: continue if (!DescriptorUtils.isSubclass(receiverClassDescriptor, targetClassDescriptor)) { conflicts.putValue(callElement, KotlinBundle.message("text.pushed.member.will.not.be.available.in.0", callElement.text)) } } } private fun checkVisibility( conflicts: MultiMap<PsiElement, String>, context: KotlinPushDownContext, member: KtNamedDeclaration, targetClassDescriptor: ClassDescriptor ) { fun reportConflictIfAny(targetDescriptor: DeclarationDescriptor) { val target = (targetDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() ?: return if (targetDescriptor is DeclarationDescriptorWithVisibility && !DescriptorVisibilityUtils.isVisibleIgnoringReceiver(targetDescriptor, targetClassDescriptor, context.resolutionFacade.languageVersionSettings) ) { val message = KotlinBundle.message( "text.0.uses.1.which.is.not.accessible.from.2", context.memberDescriptors.getValue(member).renderForConflicts(), targetDescriptor.renderForConflicts(), targetClassDescriptor.renderForConflicts() ) conflicts.putValue(target, message.capitalize()) } } member.accept( object : KtTreeVisitorVoid() { override fun visitReferenceExpression(expression: KtReferenceExpression) { super.visitReferenceExpression(expression) expression.references .flatMap { (it as? KtReference)?.resolveToDescriptors(context.sourceClassContext) ?: emptyList() } .forEach(::reportConflictIfAny) } } ) }
apache-2.0
4afa6d8be9ad57924eb0e1b509d28330
46.161702
184
0.695299
5.597475
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/DoubleBangToIfThenIntention.kt
3
4839
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.codeInsight.template.Template import com.intellij.codeInsight.template.TemplateBuilderImpl import com.intellij.codeInsight.template.TemplateEditingAdapter import com.intellij.codeInsight.template.TemplateManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiDocumentManager import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.utils.ChooseStringExpression import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.convertToIfNotNullExpression import org.jetbrains.kotlin.idea.intentions.branchedTransformations.convertToIfNullExpression import org.jetbrains.kotlin.idea.intentions.branchedTransformations.introduceValueForCondition import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isStableSimpleExpression import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement class DoubleBangToIfThenIntention : SelfTargetingRangeIntention<KtPostfixExpression>( KtPostfixExpression::class.java, KotlinBundle.lazyMessage("replace.expression.with.if.expression") ), LowPriorityAction { override fun applicabilityRange(element: KtPostfixExpression): TextRange? = if (element.operationToken == KtTokens.EXCLEXCL && element.baseExpression != null) element.operationReference.textRange else null override fun applyTo(element: KtPostfixExpression, editor: Editor?) { if (editor == null) throw IllegalArgumentException("This intention requires an editor") val base = KtPsiUtil.safeDeparenthesize(element.baseExpression!!, true) val expressionText = formatForUseInExceptionArgument(base.text!!) val defaultException = KtPsiFactory(element).createExpression("throw NullPointerException()") val isStatement = element.isUsedAsStatement(element.analyze()) val isStable = base.isStableSimpleExpression() val ifStatement = if (isStatement) element.convertToIfNullExpression(base, defaultException) else { val qualifiedExpressionForReceiver = element.getQualifiedExpressionForReceiver() val selectorExpression = qualifiedExpressionForReceiver?.selectorExpression val thenClause = selectorExpression?.let { KtPsiFactory(element).createExpressionByPattern("$0.$1", base, it) } ?: base (qualifiedExpressionForReceiver ?: element).convertToIfNotNullExpression(base, thenClause, defaultException) } val thrownExpression = ((if (isStatement) ifStatement.then else ifStatement.`else`) as KtThrowExpression).thrownExpression ?: return val message = StringUtil.escapeStringCharacters("Expression '$expressionText' must not be null") val nullPtrExceptionText = "NullPointerException(\"$message\")" val kotlinNullPtrExceptionText = "KotlinNullPointerException()" val exceptionLookupExpression = ChooseStringExpression(listOf(nullPtrExceptionText, kotlinNullPtrExceptionText)) val project = element.project val builder = TemplateBuilderImpl(thrownExpression) builder.replaceElement(thrownExpression, exceptionLookupExpression) PsiDocumentManager.getInstance(project).commitDocument(editor.document) PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document) editor.caretModel.moveToOffset(thrownExpression.node!!.startOffset) TemplateManager.getInstance(project).startTemplate(editor, builder.buildInlineTemplate(), object : TemplateEditingAdapter() { override fun templateFinished(template: Template, brokenOff: Boolean) { if (!isStable && !isStatement) { ifStatement.introduceValueForCondition(ifStatement.then!!, editor) } } }) } private fun formatForUseInExceptionArgument(expressionText: String): String { val lines = expressionText.split('\n') return if (lines.size > 1) lines.first().trim() + " ..." else expressionText.trim() } }
apache-2.0
43333321b6df80484c74e38f5597ccc9
53.370787
158
0.765861
5.613689
false
false
false
false
GunoH/intellij-community
platform/util/ui/src/com/intellij/ui/svg/SvgCacheManager.kt
2
6132
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment", "JAVA_MODULE_DOES_NOT_EXPORT_PACKAGE") package com.intellij.ui.svg import com.intellij.diagnostic.StartUpMeasurer import com.intellij.openapi.diagnostic.Logger import com.intellij.ui.icons.IconLoadMeasurer import com.intellij.util.ImageLoader import org.jetbrains.annotations.ApiStatus import org.jetbrains.mvstore.MVMap import org.jetbrains.mvstore.MVStore import org.jetbrains.mvstore.type.FixedByteArrayDataType import org.jetbrains.xxh3.Xxh3 import sun.awt.image.SunWritableRaster import java.awt.Image import java.awt.Point import java.awt.image.* import java.nio.ByteBuffer import java.nio.file.Path import java.util.concurrent.ConcurrentHashMap import java.util.function.BiConsumer private const val IMAGE_KEY_SIZE = java.lang.Long.BYTES + 3 private fun getLogger() = Logger.getInstance(SvgCacheManager::class.java) @ApiStatus.Internal data class SvgCacheMapper(@JvmField internal val scale: Float, @JvmField internal val isDark: Boolean, @JvmField internal val isStroke: Boolean) { constructor(scale: Float) : this(scale, false, false) val key = scale + (if (isDark) 10000 else 0) + (if (isStroke) 100000 else 0) val name = "icons@" + scale + (if (isDark) "_d" else "") + (if (isStroke) "_s" else "") } @ApiStatus.Internal class SvgCacheManager(dbFile: Path) { private val store: MVStore private val scaleToMap: MutableMap<Float, MVMap<ByteArray, ImageValue>> = ConcurrentHashMap(2, 0.75f, 2) private val mapBuilder: MVMap.Builder<ByteArray, ImageValue> companion object { fun <K, V> getMap(mapper: SvgCacheMapper, scaleToMap: MutableMap<Float, MVMap<K, V>>, store: MVStore, mapBuilder: MVMap.MapBuilder<MVMap<K, V>, K, V>): MVMap<K, V> { return scaleToMap.computeIfAbsent(mapper.key) { store.openMap(mapper.name, mapBuilder) } } fun readImage(value: ImageValue): Image { val dataBuffer = DataBufferInt(value.data, value.data.size) SunWritableRaster.makeTrackable(dataBuffer) return createImage(value.w, value.h, dataBuffer) } fun readImage(buffer: ByteBuffer, w: Int, h: Int): Image { val dataBuffer = DataBufferInt(w * h) buffer.asIntBuffer().get(SunWritableRaster.stealData(dataBuffer, 0)) SunWritableRaster.makeTrackable(dataBuffer) return createImage(w, h, dataBuffer) } } init { val storeErrorHandler = StoreErrorHandler() val storeBuilder = MVStore.Builder() .backgroundExceptionHandler(storeErrorHandler) .autoCommitDelay(60000) .compressionLevel(1) store = storeBuilder.openOrNewOnIoError(dbFile, true) { getLogger().debug("Cannot open icon cache database", it) } storeErrorHandler.isStoreOpened = true val mapBuilder = MVMap.Builder<ByteArray, ImageValue>() mapBuilder.keyType(FixedByteArrayDataType(IMAGE_KEY_SIZE)) mapBuilder.valueType(ImageValue.ImageValueSerializer()) this.mapBuilder = mapBuilder } private class StoreErrorHandler : BiConsumer<Throwable, MVStore> { var isStoreOpened = false override fun accept(e: Throwable, store: MVStore) { val logger = getLogger() if (isStoreOpened) { logger.error("Icon cache error (db=$store)") } else { logger.warn("Icon cache will be recreated or previous version of data reused, (db=$store)") } logger.debug(e) } } fun close() { store.close() } fun save() { store.triggerAutoSave() } fun loadFromCache(themeDigest: ByteArray, imageBytes: ByteArray, mapper: SvgCacheMapper, docSize: ImageLoader.Dimension2DDouble?): Image? { val key = getCacheKey(themeDigest, imageBytes) val map = getMap(mapper, scaleToMap, store, mapBuilder) try { val start = StartUpMeasurer.getCurrentTimeIfEnabled() val data = map.get(key) ?: return null val image = readImage(data) docSize?.setSize((data.w / mapper.scale).toDouble(), (data.h / mapper.scale).toDouble()) IconLoadMeasurer.svgCacheRead.end(start) return image } catch (e: Throwable) { getLogger().error(e) try { map.remove(key) } catch (e1: Exception) { getLogger().error("Cannot remove invalid entry", e1) } return null } } fun storeLoadedImage(themeDigest: ByteArray, imageBytes: ByteArray, mapper: SvgCacheMapper, image: BufferedImage) { val key = getCacheKey(themeDigest, imageBytes) getMap(mapper, scaleToMap, store, mapBuilder).put(key, writeImage(image)) } } private val ZERO_POINT = Point(0, 0) private fun getCacheKey(themeDigest: ByteArray, imageBytes: ByteArray): ByteArray { val contentDigest = Xxh3.hashLongs(longArrayOf( Xxh3.hash(imageBytes), Xxh3.hash(themeDigest))) val buffer = ByteBuffer.allocate(IMAGE_KEY_SIZE) // add content size to key to reduce chance of hash collision (write as medium int) buffer.put((imageBytes.size ushr 16).toByte()) buffer.put((imageBytes.size ushr 8).toByte()) buffer.put(imageBytes.size.toByte()) buffer.putLong(contentDigest) return buffer.array() } private fun createImage(w: Int, h: Int, dataBuffer: DataBufferInt): BufferedImage { val colorModel = ColorModel.getRGBdefault() as DirectColorModel val raster = Raster.createPackedRaster(dataBuffer, w, h, w, colorModel.masks, ZERO_POINT) @Suppress("UndesirableClassUsage") return BufferedImage(colorModel, raster, false, null) } private fun writeImage(image: BufferedImage): ImageValue { val w = image.width val h = image.height @Suppress("UndesirableClassUsage") val convertedImage = BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB) val g = convertedImage.createGraphics() g.drawImage(image, 0, 0, null) g.dispose() val dataBufferInt = convertedImage.raster.dataBuffer as DataBufferInt return ImageValue(dataBufferInt.data, w, h) }
apache-2.0
398b0130f4216ac37b6fbbef3c086d87
35.289941
120
0.704338
3.871212
false
false
false
false
zielu/GitToolBox
src/main/kotlin/zielu/gittoolbox/branch/OutdatedBranch.kt
1
502
package zielu.gittoolbox.branch import git4idea.GitLocalBranch import git4idea.GitRemoteBranch import java.time.ZonedDateTime internal data class OutdatedBranch( val localBranch: GitLocalBranch, val localHash: String, val reason: OutdatedReason, val latestCommitTimestamp: ZonedDateTime?, val remoteBranch: GitRemoteBranch? = null ) { fun getName(): String = localBranch.name fun hasRemote(): Boolean = remoteBranch != null fun getRemoteBranchName(): String? = remoteBranch?.name }
apache-2.0
7dc5970c625e57d6f01ad7cc35186dd6
25.421053
57
0.782869
4.648148
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/lib/java/StreamExLibrarySupportProvider.kt
6
2229
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.sequence.lib.java import com.intellij.debugger.streams.lib.LibrarySupport import com.intellij.debugger.streams.lib.LibrarySupportProvider import com.intellij.debugger.streams.lib.impl.StreamExLibrarySupport import com.intellij.debugger.streams.trace.TraceExpressionBuilder import com.intellij.debugger.streams.trace.dsl.impl.DslImpl import com.intellij.debugger.streams.wrapper.StreamChainBuilder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.debugger.sequence.psi.impl.KotlinChainTransformerImpl import org.jetbrains.kotlin.idea.debugger.sequence.psi.impl.PackageBasedCallChecker import org.jetbrains.kotlin.idea.debugger.sequence.psi.impl.TerminatedChainBuilder import org.jetbrains.kotlin.idea.debugger.sequence.psi.java.JavaStreamChainTypeExtractor import org.jetbrains.kotlin.idea.debugger.sequence.psi.java.StreamExCallChecker import org.jetbrains.kotlin.idea.debugger.sequence.trace.dsl.JavaPeekCallFactory import org.jetbrains.kotlin.idea.debugger.sequence.trace.dsl.KotlinStatementFactory import org.jetbrains.kotlin.idea.debugger.sequence.trace.impl.KotlinTraceExpressionBuilder class StreamExLibrarySupportProvider : LibrarySupportProvider { @Suppress("SpellCheckingInspection") private val streamChainBuilder = TerminatedChainBuilder( KotlinChainTransformerImpl(JavaStreamChainTypeExtractor()), StreamExCallChecker(PackageBasedCallChecker("one.util.streamex")) ) private val support by lazy { StreamExLibrarySupport() } private val dsl by lazy { DslImpl(KotlinStatementFactory(JavaPeekCallFactory())) } override fun getLanguageId(): String = KotlinLanguage.INSTANCE.id override fun getChainBuilder(): StreamChainBuilder = streamChainBuilder override fun getLibrarySupport(): LibrarySupport = support override fun getExpressionBuilder(project: Project): TraceExpressionBuilder = KotlinTraceExpressionBuilder(dsl, support.createHandlerFactory(dsl)) }
apache-2.0
af9643b0cd21d2db729e1077c570bf7e
53.390244
158
0.82638
4.634096
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ide/util/propertyService.kt
1
4274
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet", "ReplaceJavaStaticMethodWithKotlinAnalog") package com.intellij.ide.util import com.intellij.openapi.components.PersistentStateComponentWithModificationTracker import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.util.SimpleModificationTracker import kotlinx.serialization.Serializable import org.jetbrains.annotations.ApiStatus.Internal import org.jetbrains.annotations.NonNls import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.function.BiConsumer import java.util.function.Predicate @Internal sealed class BasePropertyService : PropertiesComponent(), PersistentStateComponentWithModificationTracker<BasePropertyService.MyState> { private val tracker = SimpleModificationTracker() @Serializable data class MyState( val keyToString: Map<String, String> = emptyMap(), val keyToStringList: Map<String, List<String>> = emptyMap() ) private val keyToString = ConcurrentHashMap<String, String>() private val keyToStringList = ConcurrentHashMap<String, List<String>>() override fun getStateModificationCount() = tracker.modificationCount fun removeIf(predicate: Predicate<String>) { keyToString.keys.removeIf(predicate) } fun forEachPrimitiveValue(consumer: BiConsumer<String, String>) { keyToString.forEach(consumer) } private fun doPut(key: String, value: String) { if (keyToString.put(key, value) !== value) { tracker.incModificationCount() } } override fun getState() = MyState(TreeMap(keyToString), TreeMap(keyToStringList)) override fun loadState(state: MyState) { keyToString.clear() keyToString.putAll(state.keyToString) keyToStringList.putAll(state.keyToStringList) } override fun getValue(name: String): String? = keyToString.get(name) override fun setValue(name: String, value: String?) { if (value == null) { unsetValue(name) } else { doPut(name, value) } } override fun setValue(name: String, value: String?, defaultValue: String?) { if (value == null || value == defaultValue) { unsetValue(name) } else { doPut(name, value) } } override fun setValue(name: String, value: Float, defaultValue: Float) { if (value == defaultValue) { unsetValue(name) } else { doPut(name, value.toString()) } } override fun setValue(name: String, value: Int, defaultValue: Int) { if (value == defaultValue) { unsetValue(name) } else { doPut(name, value.toString()) } } override fun setValue(name: String, value: Boolean, defaultValue: Boolean) { if (value == defaultValue) { unsetValue(name) } else { setValue(name, value.toString()) } } override fun unsetValue(name: String) { if (keyToString.remove(name) != null) { tracker.incModificationCount() } } override fun isValueSet(name: String) = keyToString.containsKey(name) override fun getValues(name: @NonNls String) = getList(name)?.toTypedArray() override fun setValues(name: @NonNls String, values: Array<String>?) { if (values.isNullOrEmpty()) { unsetValue(name) } else { keyToStringList.put(name, java.util.List.of(*values)) tracker.incModificationCount() } } override fun getList(name: String) = keyToStringList.get(name) override fun setList(name: String, values: MutableCollection<String>?) { if (values.isNullOrEmpty()) { unsetValue(name) } else { keyToStringList.put(name, java.util.List.copyOf(values)) tracker.incModificationCount() } } } @State(name = "PropertyService", storages = [ Storage(value = StoragePathMacros.NON_ROAMABLE_FILE), Storage(value = StoragePathMacros.CACHE_FILE, deprecated = true), ]) @Internal class AppPropertyService : BasePropertyService() @State(name = "PropertiesComponent", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)]) internal class ProjectPropertyService : BasePropertyService()
apache-2.0
7df2d49b3e767c87b3272f6353e37426
28.6875
136
0.719233
4.295477
false
false
false
false
craftsmenlabs/gareth-jvm
gareth-core/src/test/kotlin/org/craftsmenlabs/gareth/validator/integration/MockExecutionEndPoint.kt
1
1375
package org.craftsmenlabs.gareth.validator.integration import org.craftsmenlabs.gareth.validator.model.Duration import org.craftsmenlabs.gareth.validator.model.ExecutionRequest import org.craftsmenlabs.gareth.validator.model.ExecutionResult import org.craftsmenlabs.gareth.validator.model.ExecutionStatus import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("gareth/validator/v1/") class MockExecutionEndPoint { @RequestMapping(value = "baseline", method = arrayOf(RequestMethod.PUT)) fun executeBaseline(@RequestBody dto: ExecutionRequest): ExecutionResult { return ExecutionResult(dto.environment, ExecutionStatus.RUNNING) } @RequestMapping(value = "assume", method = arrayOf(RequestMethod.PUT)) fun executeAssumption(@RequestBody dto: ExecutionRequest): ExecutionResult { if (dto.glueLines.assume == "THROW") throw IllegalStateException("ASSUME_ERROR") return ExecutionResult(dto.environment, ExecutionStatus.SUCCESS) } @RequestMapping(value = "time", method = arrayOf(RequestMethod.PUT)) fun getTime(@RequestBody dto: ExecutionRequest): Duration = Duration("SECONDS", 2) }
gpl-2.0
f2c1eb7dc89a372353442ca29ac94a3f
41.96875
86
0.791273
4.841549
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/moduleUtils.kt
3
1053
// 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.facet.FacetManager import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.module.Module import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.idea.caches.project.ModuleSourceInfo import org.jetbrains.kotlin.idea.caches.project.PlatformModuleInfo fun Module.isAndroidModule(modelsProvider: IdeModifiableModelsProvider? = null): Boolean { val facetModel = modelsProvider?.getModifiableFacetModel(this) ?: FacetManager.getInstance(this) val facets = facetModel.allFacets return facets.any { it.javaClass.simpleName == "AndroidFacet" } } fun ModuleInfo.unwrapModuleSourceInfo(): ModuleSourceInfo? { return when (this) { is ModuleSourceInfo -> this is PlatformModuleInfo -> this.platformModule else -> null } }
apache-2.0
e66cb231d09dbdb26099b0c0b671cd3b
42.916667
158
0.787274
4.659292
false
false
false
false
mr-max/anko
dsl/testData/functional/percent/LayoutsTest.kt
2
5130
private val defaultInit: Any.() -> Unit = {} public open class _PercentFrameLayout(ctx: Context): android.support.percent.PercentFrameLayout(ctx) { public fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.support.percent.PercentFrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentFrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } public fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.support.percent.PercentFrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentFrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } public fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: android.support.percent.PercentFrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentFrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } public fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.support.percent.PercentFrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentFrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } public fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.support.percent.PercentFrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentFrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } public fun <T: View> T.lparams( source: android.widget.FrameLayout.LayoutParams?, init: android.support.percent.PercentFrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentFrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } public fun <T: View> T.lparams( source: android.support.percent.PercentFrameLayout.LayoutParams?, init: android.support.percent.PercentFrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentFrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } public open class _PercentRelativeLayout(ctx: Context): android.support.percent.PercentRelativeLayout(ctx) { public fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.support.percent.PercentRelativeLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentRelativeLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } public fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.support.percent.PercentRelativeLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentRelativeLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } public fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.support.percent.PercentRelativeLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentRelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } public fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.support.percent.PercentRelativeLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentRelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } }
apache-2.0
d98ca01294e2f84f793751244c366309
40.715447
108
0.666277
4.835061
false
false
false
false
pajato/Argus
app/src/androidTest/java/com/pajato/argus/EpisodicTest.kt
1
5423
package com.pajato.argus import android.app.Activity import android.app.Instrumentation import android.content.Intent import android.support.test.espresso.Espresso.onView import android.support.test.espresso.action.ViewActions.* import android.support.test.espresso.assertion.ViewAssertions.matches import android.support.test.espresso.intent.Intents import android.support.test.espresso.intent.matcher.IntentMatchers import android.support.test.espresso.matcher.ViewMatchers import android.support.test.espresso.matcher.ViewMatchers.withId import android.support.test.espresso.matcher.ViewMatchers.withText import android.util.Log import org.junit.Test /** * Test incrementing and setting the season and episode of the tv show. * * @author Bryan Scott -- [email protected] */ class EpisodicTest : ActivityTestBase<MainActivity>(MainActivity::class.java) { @Test fun testActivityResultTvShow() { val resultData = Intent() val title = "Stranger Things" resultData.putExtra(SearchActivity.TITLE_KEY, title) resultData.putExtra(SearchActivity.NETWORK_KEY, "Netflix") resultData.putExtra(SearchActivity.EPISODIC_KEY, true) val result = Instrumentation.ActivityResult(Activity.RESULT_OK, resultData) Intents.intending(IntentMatchers.toPackage("com.pajato.argus")).respondWith(result) onView(withId(R.id.fab)) .perform(click()) checkViewVisibility(ViewMatchers.withText(title), ViewMatchers.Visibility.VISIBLE) onView(withId(R.id.seasonText)) .check(matches(withText("1"))) onView(withId(R.id.episodeText)) .check(matches(withText("1"))) } @Test fun testIncrements() { val title = "The Simpsons" val network = "Fox" rule.activity.runOnUiThread { rule.activity.addVideo(Episodic(title, network)) } // Assert that the object comes in on Season 1 Episode 1 checkViewVisibility(withText(title), ViewMatchers.Visibility.VISIBLE) onView(withId(R.id.seasonText)) .check(matches(withText("1"))) onView(withId(R.id.episodeText)) .check(matches(withText("1"))) // Increment the episode. Ensure that the episode does change and the season does not. onView(withId(R.id.episodeLabel)) .perform(click()) onView(withId(R.id.seasonText)) .check(matches(withText("1"))) onView(withId(R.id.episodeText)) .check(matches(withText("2"))) // Increment the season. Ensure that the season does change and the episode does not. onView(withId(R.id.seasonLabel)) .perform(click()) onView(withId(R.id.seasonText)) .check(matches(withText("2"))) onView(withId(R.id.episodeText)) .check(matches(withText("2"))) } @Test fun testSets() { val title = "The Office" val network = "NBC" rule.activity.runOnUiThread { rule.activity.addVideo(Episodic(title, network)) } checkViewVisibility(withText(title), ViewMatchers.Visibility.VISIBLE) onView(withId(R.id.seasonText)) .check(matches(withText("1"))) onView(withId(R.id.episodeText)) .check(matches(withText("1"))) // Set the season with a long click and accept the change. onView(withId(R.id.seasonLabel)) .perform(longClick()) onView(withId(R.id.alertInput)) .perform(replaceText("3")) onView(withId(android.R.id.button1)) .perform(click()) checkViewVisibility(withText(title), ViewMatchers.Visibility.VISIBLE) onView(withId(R.id.seasonText)) .check(matches(withText("3"))) onView(withId(R.id.episodeText)) .check(matches(withText("1"))) // Set the season with a long click and discard the change. onView(withId(R.id.seasonLabel)) .perform(longClick()) onView(withId(R.id.alertInput)) .perform(replaceText("1")) onView(withId(android.R.id.button2)) .perform(click()) checkViewVisibility(withText(title), ViewMatchers.Visibility.VISIBLE) onView(withId(R.id.seasonText)) .check(matches(withText("3"))) onView(withId(R.id.episodeText)) .check(matches(withText("1"))) // Set the episode with a long click and accept the change. onView(withId(R.id.episodeLabel)) .perform(longClick()) onView(withId(R.id.alertInput)) .perform(replaceText("3")) onView(withId(android.R.id.button1)) .perform(click()) checkViewVisibility(withText(title), ViewMatchers.Visibility.VISIBLE) onView(withId(R.id.seasonText)) .check(matches(withText("3"))) onView(withId(R.id.episodeText)) .check(matches(withText("3"))) // Finally, ensure the season and episode data is persisted through a lifecycle. doLifeCycle() checkViewVisibility(withText(title), ViewMatchers.Visibility.VISIBLE) onView(withId(R.id.seasonText)) .check(matches(withText("3"))) onView(withId(R.id.episodeText)) .check(matches(withText("3"))) } }
gpl-3.0
cd1753dbc7c1105b0181c7d96a531e91
39.470149
94
0.635626
4.28357
false
true
false
false
CosmoRing/PokemonGoBot
src/main/kotlin/ink/abb/pogo/scraper/util/pokemon/Pokemon.kt
1
3710
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package ink.abb.pogo.scraper.util.pokemon import com.pokegoapi.api.pokemon.Pokemon import com.pokegoapi.api.pokemon.PokemonMetaRegistry import ink.abb.pogo.scraper.Settings fun Pokemon.getIv(): Int { val iv = individualAttack + individualDefense + individualStamina return iv } fun Pokemon.getIvPercentage(): Int { val iv = getIv() val ivPercentage = (iv * 100) / 45 return ivPercentage } fun Pokemon.getCpPercentageToPlayer(): Int { return (cp.toDouble() / maxCpForPlayer.toDouble() * 100).toInt() } fun Pokemon.getStatsFormatted(): String { val details = "Stamina: $individualStamina | Attack: $individualAttack | Defense: $individualDefense" val maxCpDetails = "Max Trainer CP: $maxCpForPlayer (${getCpPercentageToPlayer()}%)" return details + " | IV: ${getIv()} (${(getIvPercentage())}%) | $maxCpDetails " } fun Pokemon.shouldTransfer(settings: Settings, pokemonCounts: MutableMap<String, Int>): Pair<Boolean, String> { val obligatoryTransfer = settings.obligatoryTransfer val ignoredPokemon = settings.ignoredPokemon val ivPercentage = getIvPercentage() val minIVPercentage = settings.transferIvThreshold val minCP = settings.transferCpThreshold val minCpPercentage = settings.transferCpMinThreshold var shouldRelease = obligatoryTransfer.contains(this.pokemonId) var reason: String = "Obligatory transfer" if (!ignoredPokemon.contains(this.pokemonId)) { // shouldn't release? check for IV/CP if (!shouldRelease) { var ivTooLow = false var cpTooLow = false var maxCpInRange = false // never transfer > min IV percentage (unless set to -1) if (ivPercentage < minIVPercentage || minIVPercentage == -1) { ivTooLow = true } // never transfer > min CP (unless set to -1) if (this.cp < minCP || minCP == -1) { cpTooLow = true } reason = "CP < $minCP and IV < $minIVPercentage%" if (minCpPercentage != -1 && minCpPercentage >= getCpPercentageToPlayer()) { maxCpInRange = true reason += " and CP max $maxCpForPlayer: achieved ${getCpPercentageToPlayer()}% <= $minCpPercentage%" } shouldRelease = ivTooLow && cpTooLow && (maxCpInRange || minCpPercentage == -1) } // still shouldn't release? Check if we have too many val max = settings.maxPokemonAmount val name = this.pokemonId.name val count = pokemonCounts.getOrElse(name, { 0 }) + 1 pokemonCounts.put(name, count) if (!shouldRelease && max!=-1 && count > max) { shouldRelease = true reason = "Too many" } // Save pokemon for evolve stacking val ctoevolve = PokemonMetaRegistry.getMeta(this.pokemonId).candyToEvolve if (shouldRelease && settings.evolveBeforeTransfer.contains(this.pokemonId) && settings.evolveStackLimit > 0){ val maxtomantain = this.candy/ctoevolve; if(ctoevolve > 0 && count > maxtomantain){ shouldRelease = true reason = "Not enough candy ${this.candy}/$ctoevolve: max $maxtomantain" } else { shouldRelease = false } } } return Pair(shouldRelease, reason) }
gpl-3.0
18ab4dca2ead2c9f264f1fe4d4187a62
38.892473
118
0.644744
4.230331
false
false
false
false
KazaKago/Cryptore
library/src/main/java/com/kazakago/cryptore/RSACryptore.kt
1
2881
package com.kazakago.cryptore import android.annotation.TargetApi import android.content.Context import android.os.Build import android.security.KeyPairGeneratorSpec import java.io.IOException import java.math.BigInteger import java.security.* import java.security.cert.CertificateException import java.util.* import javax.crypto.Cipher import javax.crypto.NoSuchPaddingException import javax.security.auth.x500.X500Principal /** * RSA Cryptore. * * Created by KazaKago on 2016/04/22. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) class RSACryptore( alias: String, blockMode: BlockMode, encryptionPadding: EncryptionPadding, context: Context) : BaseCryptore( alias = alias, blockMode = blockMode, encryptionPadding = encryptionPadding, context = context) { @Throws(KeyStoreException::class, CertificateException::class, NoSuchAlgorithmException::class, IOException::class, NoSuchProviderException::class, InvalidAlgorithmParameterException::class) override fun createKeyStore(): KeyStore { return KeyStore.getInstance("AndroidKeyStore") } @Throws(NoSuchPaddingException::class, NoSuchAlgorithmException::class) override fun createCipher(blockMode: BlockMode, encryptionPadding: EncryptionPadding): Cipher { return Cipher.getInstance(CipherAlgorithm.RSA.rawValue + "/" + blockMode.rawValue + "/" + encryptionPadding.rawValue) } @Throws(UnrecoverableKeyException::class, NoSuchAlgorithmException::class, KeyStoreException::class, InvalidKeyException::class, IOException::class) override fun getEncryptKey(keyStore: KeyStore, alias: String): Key { return keyStore.getCertificate(alias).publicKey } @Throws(UnrecoverableKeyException::class, NoSuchAlgorithmException::class, KeyStoreException::class, InvalidAlgorithmParameterException::class, InvalidKeyException::class, IOException::class) override fun getDecryptKey(keyStore: KeyStore, alias: String): Key { return keyStore.getKey(alias, null) as PrivateKey } @Throws(NoSuchProviderException::class, NoSuchAlgorithmException::class, InvalidAlgorithmParameterException::class) override fun createNewKey(alias: String, blockMode: BlockMode, encryptionPadding: EncryptionPadding) { val start = Calendar.getInstance() val end = Calendar.getInstance() end.add(Calendar.YEAR, 100) val generator = KeyPairGenerator.getInstance(CipherAlgorithm.RSA.rawValue, "AndroidKeyStore") generator.initialize(KeyPairGeneratorSpec.Builder(this.context!!) .setAlias(alias) .setSubject(X500Principal("CN=Cryptore")) .setSerialNumber(BigInteger.ONE) .setStartDate(start.time) .setEndDate(end.time) .build()) generator.generateKeyPair() } }
mit
d4e5c545f3d6484253af456fe07ee871
41.367647
195
0.736203
4.730706
false
false
false
false
seventhroot/elysium
bukkit/rpk-payments-bukkit/src/main/kotlin/com/rpkit/payments/bukkit/group/RPKPaymentGroupImpl.kt
1
4863
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.payments.bukkit.group import com.rpkit.characters.bukkit.character.RPKCharacter import com.rpkit.economy.bukkit.currency.RPKCurrency import com.rpkit.payments.bukkit.RPKPaymentsBukkit import com.rpkit.payments.bukkit.database.table.RPKPaymentGroupInviteTable import com.rpkit.payments.bukkit.database.table.RPKPaymentGroupMemberTable import com.rpkit.payments.bukkit.database.table.RPKPaymentGroupOwnerTable import com.rpkit.payments.bukkit.event.group.* import com.rpkit.payments.bukkit.group.invite.RPKPaymentGroupInvite import com.rpkit.payments.bukkit.group.member.RPKPaymentGroupMember import com.rpkit.payments.bukkit.group.owner.RPKPaymentGroupOwner /** * Payment group implementation. */ class RPKPaymentGroupImpl( val plugin: RPKPaymentsBukkit, override var id: Int = 0, override var name: String, override var amount: Int, override var currency: RPKCurrency?, override var interval: Long, override var lastPaymentTime: Long, override var balance: Int ): RPKPaymentGroup { override val owners: List<RPKCharacter> get() = plugin.core.database.getTable(RPKPaymentGroupOwnerTable::class).get(this).map { owner -> owner.character } override val members: List<RPKCharacter> get() = plugin.core.database.getTable(RPKPaymentGroupMemberTable::class).get(this).map { owner -> owner.character } override val invites: List<RPKCharacter> get() = plugin.core.database.getTable(RPKPaymentGroupInviteTable::class).get(this).map { owner -> owner.character } override fun addOwner(character: RPKCharacter) { val event = RPKBukkitPaymentGroupOwnerAddEvent(this, character) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return plugin.core.database.getTable(RPKPaymentGroupOwnerTable::class).insert(RPKPaymentGroupOwner(paymentGroup = event.paymentGroup, character = event.character)) } override fun removeOwner(character: RPKCharacter) { val event = RPKBukkitPaymentGroupOwnerRemoveEvent(this, character) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return val ownerTable = plugin.core.database.getTable(RPKPaymentGroupOwnerTable::class) val owner = ownerTable.get(event.paymentGroup).firstOrNull { it.character == event.character } if (owner != null) { ownerTable.delete(owner) } } override fun addMember(character: RPKCharacter) { val event = RPKBukkitPaymentGroupMemberAddEvent(this, character) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return plugin.core.database.getTable(RPKPaymentGroupMemberTable::class).insert(RPKPaymentGroupMember(paymentGroup = event.paymentGroup, character = event.character)) } override fun removeMember(character: RPKCharacter) { val event = RPKBukkitPaymentGroupMemberRemoveEvent(this, character) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return val memberTable = plugin.core.database.getTable(RPKPaymentGroupMemberTable::class) val member = memberTable.get(event.paymentGroup).firstOrNull { it.character == event.character } if (member != null) { memberTable.delete(member) } } override fun addInvite(character: RPKCharacter) { val event = RPKBukkitPaymentGroupInviteEvent(this, character) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return plugin.core.database.getTable(RPKPaymentGroupInviteTable::class).insert(RPKPaymentGroupInvite(paymentGroup = event.paymentGroup, character = event.character)) } override fun removeInvite(character: RPKCharacter) { val event = RPKBukkitPaymentGroupUninviteEvent(this, character) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return val invite = plugin.core.database.getTable(RPKPaymentGroupInviteTable::class).get(event.paymentGroup).firstOrNull { it.character == event.character } if (invite != null) { plugin.core.database.getTable(RPKPaymentGroupInviteTable::class).delete(invite) } } }
apache-2.0
c5b0839655b190dbf8c3a4aa2ba6aacf
44.886792
166
0.736994
4.613852
false
false
false
false
ilya-g/kotlinx.collections.immutable
core/commonMain/src/adapters/ReadOnlyCollectionAdapters.kt
1
1862
/* * Copyright 2016-2019 JetBrains s.r.o. * Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file. */ package kotlinx.collections.immutable.adapters import kotlinx.collections.immutable.* /* These classes allow to expose read-only collection as immutable, if it's actually immutable one Use with caution: wrapping mutable collection as immutable is a contract violation of the latter. */ public open class ImmutableCollectionAdapter<E>(private val impl: Collection<E>) : ImmutableCollection<E>, Collection<E> by impl { override fun equals(other: Any?): Boolean = impl.equals(other) override fun hashCode(): Int = impl.hashCode() override fun toString(): String = impl.toString() } public class ImmutableListAdapter<E>(private val impl: List<E>) : ImmutableList<E>, List<E> by impl { override fun subList(fromIndex: Int, toIndex: Int): ImmutableList<E> = ImmutableListAdapter(impl.subList(fromIndex, toIndex)) override fun equals(other: Any?): Boolean = impl.equals(other) override fun hashCode(): Int = impl.hashCode() override fun toString(): String = impl.toString() } public class ImmutableSetAdapter<E>(impl: Set<E>) : ImmutableSet<E>, ImmutableCollectionAdapter<E>(impl) public class ImmutableMapAdapter<K, out V>(private val impl: Map<K, V>) : ImmutableMap<K, V>, Map<K, V> by impl { // TODO: Lazy initialize these properties? override val keys: ImmutableSet<K> = ImmutableSetAdapter(impl.keys) override val values: ImmutableCollection<V> = ImmutableCollectionAdapter(impl.values) override val entries: ImmutableSet<Map.Entry<K, V>> = ImmutableSetAdapter(impl.entries) override fun equals(other: Any?): Boolean = impl.equals(other) override fun hashCode(): Int = impl.hashCode() override fun toString(): String = impl.toString() }
apache-2.0
3806bbc33007a917251a2ffe0f49161f
40.4
130
0.737916
4.165548
false
false
false
false
gprince/KuickCheck
src/main/kotlin/org/kuickcheck/specification/dsl/Integers.kt
1
1649
package org.kuickcheck.specification.dsl import org.apache.commons.math3.random.RandomDataGenerator fun Integers.first(): Int = this.lowerBound fun Integers.last(): Int = this.upperBound class Integers : Source<Int> { class PseudoRandomIterator(val integers: Integers) : AbstractIterator<Int>() { val prng = RandomDataGenerator() override fun computeNext() { setNext(prng.nextInt(integers.lowerBound, integers.upperBound)) } } override operator fun iterator(): Iterator<Int> = PseudoRandomIterator(this) private var _lowerBound = Int.MIN_VALUE val lowerBound: Int get() = _lowerBound private var _upperBound = Int.MAX_VALUE val upperBound: Int get() = _upperBound companion object { fun integers(build: Integers.() -> Unit): Integers { val integers = Integers() integers.build() return integers } } fun allPositive(): Integers { this._lowerBound = 1 return this } fun from(lowerBound: () -> Int): Integers { this._lowerBound = lowerBound() return this } fun to(upperBound: () -> Int): Integers { this._upperBound = upperBound() return this } } //fun main(args: Array<String>) { // val source = Integers.integers { allPositive() } // val seq = source.asSequence() // val values = seq.filter { it % 2 == 0 }.filter { it >= 100 }.filter { it < 3000 }.take(100).toList() // println(values.partition { it * 0 == 0 }) // println(values.partition { it * 1 == it }) // println(values.partition { it < 1500 }) //}
apache-2.0
dd71a8604c94034d40d99511aa907afa
26.04918
106
0.610673
4.206633
false
false
false
false
NephyProject/Penicillin
src/main/kotlin/jp/nephy/penicillin/endpoints/lists/Unsubscribe.kt
1
4255
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * 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. */ @file:Suppress("UNUSED", "PublicApiImplicitType") package jp.nephy.penicillin.endpoints.lists import jp.nephy.penicillin.core.request.action.JsonObjectApiAction import jp.nephy.penicillin.core.request.formBody import jp.nephy.penicillin.core.session.post import jp.nephy.penicillin.endpoints.Lists import jp.nephy.penicillin.endpoints.Option import jp.nephy.penicillin.models.TwitterList /** * Unsubscribes the authenticated user from the specified list. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-subscribers-destroy) * * @param listId The numerical id of the list. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [JsonObjectApiAction] for [TwitterList] model. */ fun Lists.unsubscribe( listId: Long, vararg options: Option ) = unsubscribe(listId, null, null, null, *options) /** * Unsubscribes the authenticated user from the specified list. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-subscribers-destroy) * * @param slug You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you'll also have to specify the list owner using the owner_id or owner_screen_name parameters. * @param ownerScreenName The screen name of the user who owns the list being requested by a slug. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [JsonObjectApiAction] for [TwitterList] model. */ fun Lists.unsubscribeByOwnerScreenName( slug: String, ownerScreenName: String, vararg options: Option ) = unsubscribe(null, slug, ownerScreenName, null, *options) /** * Unsubscribes the authenticated user from the specified list. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-subscribers-destroy) * * @param slug You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you'll also have to specify the list owner using the owner_id or owner_screen_name parameters. * @param ownerId The user ID of the user who owns the list being requested by a slug. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [JsonObjectApiAction] for [TwitterList] model. */ fun Lists.unsubscribeByOwnerId( slug: String, ownerId: Long, vararg options: Option ) = unsubscribe(null, slug, null, ownerId, *options) private fun Lists.unsubscribe( listId: Long? = null, slug: String? = null, ownerScreenName: String? = null, ownerId: Long? = null, vararg options: Option ) = client.session.post("/1.1/lists/subscribers/destroy.json") { formBody( "list_id" to listId, "slug" to slug, "owner_screen_name" to ownerScreenName, "owner_id" to ownerId, *options ) }.jsonObject<TwitterList>()
mit
5678af4232351befadbe88926d0958bd
41.979798
208
0.746651
4.044677
false
false
false
false
AlexanderDashkov/hpcourse
csc/2015/any/any_1_kotlin/src/ru/bronti/hpcource/hw1/MyFuture.kt
4
4672
package ru.bronti.hpcource.hw1 import java.util.LinkedList import java.util.Queue import java.util.concurrent.Callable import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.RejectedExecutionException import java.lang.ThreadGroup import java.util.concurrent.* import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger public class MyFuture<V> (private val task: Callable<V>, val name: String, private val threadPool: MyThreadPool): Future<V> { private val resultMonitor = Object() val WAITING = 0 val RUNNING = 1 val DONE = 2 val CANCELLED = 4 val status = AtomicInteger(WAITING) volatile var workerThread: MyThread? = null volatile var result: V = null volatile var exeption: Exception? = null override public fun isDone(): Boolean = status.get() % CANCELLED >= DONE override public fun isCancelled(): Boolean = status.get() >= CANCELLED private fun doWaitOnce(expirationTime: Long?): Boolean { if (Thread.currentThread() is MyThread && !threadPool.isShut && !threadPool.queue.isEmpty() && !isCancelled()) { //println(Thread.currentThread().getName() + " is waiting for " + name) val wasInterrupted = Thread.interrupted() (Thread.currentThread() as MyThread).task.runTask(false) if (wasInterrupted) { Thread.currentThread().interrupt() } } else { synchronized(resultMonitor) { if (!isCancelled()) { if (expirationTime != null) { resultMonitor.wait(expirationTime - System.currentTimeMillis()) } else { resultMonitor.wait() } } } } if (expirationTime != null && System.currentTimeMillis() >= expirationTime) { return true } return false } private fun doGet(expirationTime: Long?): V { var timedOut = false while (!isDone() && !isCancelled() && !timedOut) { timedOut = doWaitOnce(expirationTime) } if (isCancelled()) { throw CancellationException() } if (!timedOut) { if (exeption != null) { throw ExecutionException(exeption) } return result } else { throw TimeoutException() } } override public fun get(timeout: Long, unit: TimeUnit): V { val expirationTime = System.currentTimeMillis() + unit.toMillis(timeout); return doGet(expirationTime) } override public fun get(): V { return doGet(null) } override public fun cancel(mayInterruptIfRunning: Boolean): Boolean { var result: Boolean = false synchronized(resultMonitor) { status.set(status.get() % CANCELLED + CANCELLED) resultMonitor.notifyAll() } if (mayInterruptIfRunning) { if (status.get() % CANCELLED == RUNNING) { workerThread!!.interrupt() result = true } //println(name + " interrupted while running") } result = result or (status.get() % CANCELLED == WAITING) status.set(CANCELLED + DONE + status.get() % DONE) return result } throws(javaClass<InterruptedException>()) fun run(thread: MyThread) { workerThread = thread var temp: V = null if (status.compareAndSet(WAITING, RUNNING)) { //println(name + " running") try { temp = task.call() } catch (e: InterruptedException) { synchronized(resultMonitor) { if (status.compareAndSet(RUNNING, RUNNING + DONE)) { result = temp resultMonitor.notifyAll() throw e } } } catch (e: Exception) { exeption = e } if (!isCancelled()) { synchronized(resultMonitor) { if (status.compareAndSet(RUNNING, RUNNING + DONE)) { result = temp resultMonitor.notifyAll() } } } } else { //println("skipped execution by " + name) } } fun getTaskAndCancel(): Callable<V> { cancel(true) return task } }
gpl-2.0
80ece0be3336154cc9c42141775ff78d
31.227586
87
0.534675
5.111597
false
false
false
false
jonnyzzz/TeamCity.Node
agent/src/main/java/com/jonnyzzz/teamcity/plugins/node/agent/nvm/HttpClient.kt
1
6576
/* * Copyright 2013-2015 Eugene Petrenko * * 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.jonnyzzz.teamcity.plugins.node.agent.nvm import com.jonnyzzz.teamcity.plugins.node.common.log4j import jetbrains.buildServer.version.ServerVersionHolder import org.apache.http.HttpResponse import org.apache.http.client.HttpClient import org.apache.http.client.methods.HttpUriRequest import org.apache.http.conn.ssl.SSLSocketFactory import org.apache.http.conn.ssl.TrustStrategy import org.apache.http.impl.client.DefaultHttpClient import org.apache.http.impl.conn.SchemeRegistryFactory import org.apache.http.params.BasicHttpParams import org.apache.http.params.HttpConnectionParams import org.apache.http.params.HttpProtocolParams import java.security.cert.X509Certificate import jetbrains.buildServer.serverSide.TeamCityProperties import org.apache.http.HttpHost import org.apache.http.auth.AuthScope import org.apache.http.auth.NTCredentials import org.apache.http.auth.UsernamePasswordCredentials import java.net.ProxySelector import org.apache.http.conn.scheme.Scheme import org.apache.http.impl.conn.ProxySelectorRoutePlanner import org.apache.http.client.protocol.RequestAcceptEncoding import org.apache.http.client.protocol.ResponseContentEncoding import org.apache.http.impl.conn.DefaultProxyRoutePlanner import org.apache.http.conn.ssl.X509HostnameVerifier import org.apache.http.impl.client.DefaultHttpRequestRetryHandler import org.apache.http.impl.conn.PoolingClientConnectionManager import org.springframework.beans.factory.DisposableBean import javax.net.ssl.SSLSession import javax.net.ssl.SSLSocket /** * @author Eugene Petrenko ([email protected]) * Date: 13.08.13 22:43 */ interface HttpClientWrapper { fun <T> execute(request: HttpUriRequest, action: HttpResponse.() -> T): T } /** * Created by Eugene Petrenko ([email protected]) * Date: 11.08.11 16:24 */ class HttpClientWrapperImpl : HttpClientWrapper, DisposableBean { private val LOG = log4j(NVMDownloader::class.java) private val myClient: HttpClient; init { val serverVersion = ServerVersionHolder.getVersion().displayVersion; val ps = BasicHttpParams(); DefaultHttpClient.setDefaultHttpParams(ps); HttpConnectionParams.setConnectionTimeout(ps, 300 * 1000); HttpConnectionParams.setSoTimeout(ps, 300 * 1000); HttpProtocolParams.setUserAgent(ps, "JetBrains TeamCity " + serverVersion); val cm = if (!TeamCityProperties.getBoolean("teamcity.node.verify.ssl.certificate")) { val schemaRegistry = SchemeRegistryFactory.createDefault() val sslSocketFactory = SSLSocketFactory( object : TrustStrategy { override fun isTrusted(chain: Array<out X509Certificate>?, authType: String?): Boolean { return true; } }, object : X509HostnameVerifier { override fun verify(host: String?, ssl: SSLSocket?) {} override fun verify(host: String?, cert: X509Certificate?) { } override fun verify(host: String?, cns: Array<out String>?, subjectAlts: Array<out String>?) { } override fun verify(p0: String?, p1: SSLSession?): Boolean = true }) schemaRegistry.register(Scheme("https", 443, sslSocketFactory)); PoolingClientConnectionManager(schemaRegistry) } else { PoolingClientConnectionManager() } val httpclient = DefaultHttpClient(cm, ps); httpclient.routePlanner = ProxySelectorRoutePlanner( httpclient.connectionManager!!.schemeRegistry, ProxySelector.getDefault()); httpclient.addRequestInterceptor(RequestAcceptEncoding()); httpclient.addResponseInterceptor(ResponseContentEncoding()); httpclient.httpRequestRetryHandler = DefaultHttpRequestRetryHandler(3, true); val PREFIX = "teamcity.http.proxy."; val SUFFIX = ".node"; val proxyHost = TeamCityProperties.getPropertyOrNull(PREFIX + "host" + SUFFIX) val proxyPort = TeamCityProperties.getInteger(PREFIX + "port" + SUFFIX, 3128) val proxyDomain = TeamCityProperties.getPropertyOrNull(PREFIX + "domain" + SUFFIX) val proxyUser = TeamCityProperties.getPropertyOrNull(PREFIX + "user" + SUFFIX) val proxyPassword = TeamCityProperties.getPropertyOrNull(PREFIX + "password" + SUFFIX) val proxyWorkstation = TeamCityProperties.getPropertyOrNull(PREFIX + "workstation" + SUFFIX) if (proxyHost != null && proxyPort > 0) { val proxy = HttpHost(proxyHost, proxyPort); httpclient.routePlanner = DefaultProxyRoutePlanner(proxy) if (proxyUser != null && proxyPassword != null) { if (proxyDomain != null || proxyWorkstation != null) { LOG.info("TeamCity.Node.NVM. Using HTTP proxy $proxyHost:$proxyPort, username: ${proxyDomain ?: proxyWorkstation ?: "."}\\$proxyUser") httpclient.credentialsProvider.setCredentials( AuthScope(proxyHost, proxyPort), NTCredentials(proxyUser, proxyPassword, proxyWorkstation, proxyDomain)) } else { LOG.info("TeamCity.Node.NVM. Using HTTP proxy $proxyHost:$proxyPort, username: $proxyUser") httpclient.credentialsProvider.setCredentials( AuthScope(proxyHost, proxyPort), UsernamePasswordCredentials(proxyUser, proxyPassword)) } } else { LOG.info("TeamCity.Node.NVM. Using HTTP proxy $proxyHost:$proxyPort") } } myClient = httpclient; } override fun <T> execute(request: HttpUriRequest, action: HttpResponse.() -> T): T { val response = myClient.execute(request)!! try { return response.action() } finally { request.abort() } } override fun destroy() { myClient.connectionManager!!.shutdown(); } }
apache-2.0
c5cd5ba6e5c8e681e2750cbe8d19d403
39.592593
144
0.700578
4.473469
false
false
false
false
vincent-maximilian/slakoverflow
src/main/kotlin/jmailen/http/RestClient.kt
1
1800
package jmailen.http import io.ktor.client.HttpClient import io.ktor.client.call.call import io.ktor.client.engine.apache.Apache import io.ktor.client.response.HttpResponse import io.ktor.content.TextContent import io.ktor.http.ContentType import io.ktor.http.HttpHeaders import io.ktor.http.HttpMethod import java.util.zip.GZIPInputStream import jmailen.serialization.Json import jmailen.slakoverflow.Logger import kotlinx.coroutines.experimental.runBlocking /** * Simplistic synchronous rest client atop Ktor http client. */ object RestClient { val http = HttpClient(Apache) inline fun <reified T : Any> get(url: String, message: Any? = null): T { return request(HttpMethod.Get, url, message) } inline fun <reified T : Any> post(url: String, message: Any? = null): T { return request(HttpMethod.Post, url, message) } inline fun <reified T : Any> request(httpMethod: HttpMethod, url: String, message: Any?) = runBlocking { val call = http.call(url) { method = httpMethod message?.let { body = TextContent(Json.write(message), ContentType.Application.Json) } } with(call.response) { when (status.value) { in 200..299 -> Logger.debug("request successful to {}, received {} bytes", url, headers[HttpHeaders.ContentLength] ?: "0") else -> throw RuntimeException("unexpected response to $url: state = $status, message = ${String(receiveBytes())}") } Json.read<T>(receiveBytes()) } } } fun HttpResponse.receiveBytes() = when (headers[HttpHeaders.ContentEncoding]) { "gzip" -> GZIPInputStream(receiveContent().inputStream()) else -> receiveContent().inputStream() }.readAllBytes()
mit
9b956a05fb9489702d684fb55a399b3d
34.294118
127
0.666667
4.215457
false
false
false
false
YiiGuxing/TranslationPlugin
src/main/kotlin/cn/yiiguxing/plugin/translate/diagnostic/diagnostic-utils.kt
1
2835
package cn.yiiguxing.plugin.translate.diagnostic import cn.yiiguxing.plugin.translate.util.toHexString import com.intellij.util.io.DigestUtil import java.security.MessageDigest import java.util.* private const val CAUSE_CAPTION = "CAUSE" private const val SUPPRESSED_CAPTION = "SUPPRESSED" private const val PLUGIN_PACKAGE = "cn.yiiguxing.plugin.translate" /** * Generate an ID for the [Throwable], used to identify its uniqueness. * * Note: The generated ID is based on [throwable][Throwable]'s * [stack trace][Throwable.stackTrace] and does not include its [message][Throwable.message], * So it can eliminate the influence of the dynamic content that may exist in the * [message][Throwable.message] on its uniqueness. Also, since the [message][Throwable.message] * is not used as input to generate the ID, it is also inaccurate, * but it is very useful in error reporting, it can avoid a lot of duplicate * error reports being submitted. So relative to the benefit it brings, * this loss of accuracy is acceptable. */ internal fun Throwable.generateId(): String { val md5 = DigestUtil.md5() // Guard against malicious overrides of Throwable.equals by // using a Set with identity equality semantics. val dejaVu = Collections.newSetFromMap(IdentityHashMap<Throwable, Boolean>()) update(md5, emptyArray(), null, dejaVu) return md5.digest().toHexString() } private fun Throwable.update( md5: MessageDigest, enclosingTrace: Array<out StackTraceElement>, caption: String?, dejaVu: MutableSet<Throwable> ) { if (this in dejaVu) { md5.update("[CIRCULAR REFERENCE: ${javaClass.name}]".toByteArray(Charsets.UTF_8)) return } dejaVu.add(this) caption?.let { md5.update(it.toByteArray(Charsets.UTF_8)) } md5.update(javaClass.name.toByteArray(Charsets.UTF_8)) val trace = stackTrace val lastIndexWithoutCommonFrames = trace.lastIndexWithoutCommonFrames(enclosingTrace) val lastPluginPackageIndex = trace.indexOfLast { it.className.startsWith(PLUGIN_PACKAGE) } var traceEndIndex = trace.lastIndex if (lastPluginPackageIndex >= 0) { traceEndIndex = lastPluginPackageIndex } if (lastIndexWithoutCommonFrames in 0 until traceEndIndex) { traceEndIndex = lastIndexWithoutCommonFrames } for (i in 0..traceEndIndex) { md5.update(trace[i].toString().toByteArray(Charsets.UTF_8)) } for (se in suppressed) { se.update(md5, trace, SUPPRESSED_CAPTION, dejaVu) } cause?.update(md5, trace, CAUSE_CAPTION, dejaVu) } private fun Array<out StackTraceElement>.lastIndexWithoutCommonFrames(other: Array<out StackTraceElement>): Int { var m = lastIndex var n = other.lastIndex while (m >= 0 && n >= 0 && this[m] == other[n]) { m-- n-- } return m }
mit
4621cc8a60db37782a0cbe8a4f00529e
34.012346
113
0.715697
3.970588
false
false
false
false
belyaev-mikhail/kcheck
src/main/kotlin/ru/spbstu/kotlin/generate/util/RandomEx.kt
1
3222
package ru.spbstu.kotlin.generate.util import java.util.* class HighQualityRandom(seed: Long = System.nanoTime()): Random(seed) { private var u: Long = 0L private var v = 4101842887655102017L private var w = 1L init { u = seed xor v; nextLong() v = u; nextLong() w = v; nextLong() } override fun nextLong(): Long { u = u * 2862933555777941757L + 7046029254386353087L; v = v xor (v ushr 17) v = v xor (v shl 31) v = v xor (v ushr 8) w = 4294957665L * (w and 0xffffffff) + (w ushr 32); var x = u xor (u shl 21); x = x xor (x ushr 35) x = x xor (x shl 4) return (x + v) xor w } override fun next(bits: Int): Int { return (nextLong() ushr (64 - bits)).toInt() } } fun Random.nextLong(bound: Long): Long { var bits: Long var v: Long do { bits = (nextLong() shl 1).ushr(1) v = bits % bound } while (bits - v + (bound - 1) < 0L) return v } fun Random.nextShort(): Short = nextInRange(Short.MIN_VALUE.toInt(), Short.MAX_VALUE.toInt() + 1).toShort() fun Random.nextShort(bound: Short): Short = nextInt(bound.toInt()).toShort() fun Random.nextByte(): Byte = nextInRange(Byte.MIN_VALUE.toInt(), Byte.MAX_VALUE.toInt() + 1).toByte() fun Random.nextByte(bound: Byte): Byte = nextInt(bound.toInt()).toByte() fun Random.nextChar(): Char = nextShort().toChar() fun Random.nextChar(alphabet: CharSequence) = alphabet[nextInt(alphabet.length)] fun Random.nextString(alphabet: CharSequence, minLength: Int = 0, maxLength: Int = 1001) = charSequence(alphabet).take(nextInRange(minLength, maxLength)).joinToString(separator = "") fun Random.nextInRange(min: Int, max: Int): Int = when { max == min -> min else -> (nextLong(max.toLong() - min.toLong()) + min).toInt() } fun Random.nextInRange(min: Long, max: Long): Long { // this is a bit tricky val minHalf = min / 2 val maxHalf = max / 2 val minOtherHalf = min - minHalf val maxOtherHalf = max - maxHalf return nextLong(maxHalf - minHalf + 1) + nextLong(maxOtherHalf - minOtherHalf) + min } fun Random.nextInRange(min: Short, max: Short): Short = (nextInt(max - min) + min).toShort() fun Random.nextInRange(min: Byte, max: Byte): Byte = (nextInt(max - min) + min).toByte() fun Random.nextInRange(min: Float, max: Float): Float = nextFloat() * (max - min) + min fun Random.nextInRange(min: Double, max: Double): Double = nextDouble() * (max - min) + min fun Random.intSequence() = generateSequence { nextInt() } fun Random.longSequence() = generateSequence { nextLong() } fun Random.shortSequence() = generateSequence { nextShort() } fun Random.byteSequence() = generateSequence { nextByte() } fun Random.booleanSequence() = generateSequence { nextBoolean() } fun Random.floatSequence() = generateSequence { nextFloat() } fun Random.doubleSequence() = generateSequence { nextDouble() } fun Random.charSequence(alphabet: CharSequence) = generateSequence { nextChar(alphabet) } fun Random.stringSequence(alphabet: CharSequence, minLength: Int = 0, maxLength: Int = 1000) = generateSequence { nextString(alphabet, minLength, maxLength) }
mit
a3fcfb13707b7f2dbe17a6473d8918ae
38.777778
107
0.652079
3.564159
false
false
false
false
SoulBeaver/SpriteSheetProcessor
src/test/java/com/sbg/rpg/console/SpriteSheetProcessorSpec.kt
1
3916
package com.sbg.rpg.console import com.sbg.rpg.packing.common.SpriteSheetWriter import com.sbg.rpg.packing.common.extensions.readImage import com.sbg.rpg.packing.unpacker.SpriteSheetUnpacker import io.mockk.* import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import java.nio.file.Paths import kotlin.test.assertFailsWith object SpriteSheetProcessorSpec : Spek({ given("an unpacking processor") { val unpacker = mockk<SpriteSheetUnpacker>() val writer = mockk<SpriteSheetWriter>() val unpackingProcessor = SpriteSheetUnpackingProcessor(unpacker, writer) on("trying to process a non-existing sprite sheet") { val cla = CommandLineArguments( spriteSheetPaths = listOf("doesNotExist"), exportFolder = "target", failFast = true ) it("should fail with an IllegalArgumentException") { assertFailsWith(IllegalArgumentException::class) { unpackingProcessor.processSpriteSheets(cla) } } } on("trying to process multiple sprite sheets without the -ff flag") { val spriteSheetPath = Paths.get(this.javaClass.classLoader.getResource("console/ManySprites.png").toURI()) val cla = CommandLineArguments( spriteSheetPaths = listOf("doesNotExist1", "doesNotExist2", spriteSheetPath.toAbsolutePath().toString()), exportFolder = "target", failFast = false ) it("should ignore all missing files") { every { unpacker.unpack(any()) } returns emptyList() unpackingProcessor.processSpriteSheets(cla) verify(exactly = 1) { unpacker.unpack(any()) } } } on("trying to process multiple sprite sheets with the -ff flag") { val cla = CommandLineArguments( spriteSheetPaths = listOf("doesNotExist1", "doesNotExist2", "doesNotExist3"), exportFolder = "target", failFast = true ) it("should fail the entire batch without processing a single sheet") { assertFailsWith(IllegalArgumentException::class) { unpackingProcessor.processSpriteSheets(cla) } } } } given("an unpacking processor") { val unpacker = mockk<SpriteSheetUnpacker>() val writer = mockk<SpriteSheetWriter>() val unpackingProcessor = SpriteSheetUnpackingProcessor(unpacker, writer) on("trying to process a single sprite sheet with multiple sprites") { val spriteSheetPath = Paths.get(this.javaClass.classLoader.getResource("console/ManySprites.png").toURI()) val cla = CommandLineArguments( spriteSheetPaths = listOf(spriteSheetPath.toAbsolutePath().toString()), exportFolder = "target", failFast = false ) it("returns a list of 14 sprites") { val sprite = Paths.get(this.javaClass.classLoader.getResource("console/CannedReturn.png").toURI()).readImage() val sprites = Array(14, { sprite }).toList() every { writer.write(any(), "png", any()) } just Runs every { writer.writeMetadata(any(), any()) } just Runs every { unpacker.unpack(any()) } returns sprites val actual = unpackingProcessor.processSpriteSheets(cla) verify(exactly = 1) { unpacker.unpack(any()) } verify(exactly = 14) { writer.write(any(), "png", any()) } verify(exactly = 0) { writer.writeMetadata(any(), any()) } } } } })
apache-2.0
4db9f2ca85d3652303cc16ca858a82fe
38.565657
126
0.597038
5.033419
false
false
false
false
Juuxel/ChatTime
server/src/main/kotlin/chattime/server/plugins/PermissionsPlugin.kt
1
6558
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package chattime.server.plugins import chattime.api.User import chattime.api.event.* import chattime.api.features.Commands import chattime.api.features.Permissions import chattime.api.features.Permissions.* import chattime.server.L10n class PermissionsPlugin : Permissions { private val permissions: HashMap<User, ArrayList<Permission>> = HashMap() private val globals: HashMap<String, Boolean> = HashMap() private val addPermission = "command.permissions.add" private val resetPermission = "command.permissions.reset" private val listPermission = "command.permissions.list" override val id = "Permissions" override fun load(event: PluginLoadEvent) { event.eventBus.subscribe(EventType.commandCall) { handleCommand(it) } event.eventBus.subscribe(EventType.userJoin) { handleUserJoin(it) } event.server.commandsPlugin.addCommand( Commands.construct("permissions", "Handle permissions.") { // TODO l10n permissionCommand(it) } ) /// Default permissions /// // Forbid the use of permissions add and reset by default globals[addPermission] = false globals[resetPermission] = false // Forbid kick by default globals["commands.kick"] = false } override fun addGlobalPermission(permission: Permission) { globals[permission.action] = permission.isAllowed } override fun hasPermission(user: User, action: String): Boolean = globals[action] == true || permissions[user]?.any { it.action == action && it.isAllowed } == true || user.id == "Server" private fun handleUserJoin(event: UserJoinEvent) { permissions[event.user] = ArrayList() } private fun handleCommand(event: CommandEvent) { val userPerms = permissions[event.sender] ?: return fun anyPerm(isAllowed: Boolean): Boolean = userPerms.any { it.action == event.commandName && it.isAllowed == isAllowed } if ( (globals["command." + event.commandName] == false && !anyPerm(true)) // No allows for forbidden cmd || anyPerm(false)) // Forbids for regular cmd { event.forbidMessage('!' + event.commandName) event.cancel() } } private fun permissionCommand(event: MessageEvent) { val params = Commands.getCommandParams(event.msg.message) if (params.size < 2) { event.pluginMessage("Usage: !permissions <subcommand: list, add, reset>") return } when (params[1]) { "list" -> { if (!hasPermission(event.sender, listPermission)) { event.forbidMessage(listPermission) return } try { val user = params.getOrElse(2) { event.sender.id } event.pluginMessage(L10n["commands.permissions.ofUser", user]) permissions[event.server.getUserById(user)]!!.forEach { event.sendMessageToSender("- ${it.action}: ${it.isAllowed}") } } catch (iae: IllegalArgumentException) { event.sendMessageToSender(iae.message ?: L10n["error.generic"]) } } "add" -> { if (!hasPermission(event.sender, addPermission)) { event.forbidMessage(addPermission) return } if (params.size < 5) { event.pluginMessage("Usage: !permissions add <user> <action> <isAllowed: true, false>") return } try { val user = params[2] val action = params[3] val isAllowed = params[4].toBoolean() val userPermissions = permissions[event.server.getUserById(user)]!! if (!hasPermission(event.sender, action)) { event.pluginMessage("You can't give others permissions you don't have yourself.") return } if (userPermissions.any { it.action == action }) userPermissions.removeAll { it.action == action } userPermissions += Permission(action, isAllowed) event.sendMessageToSender("Added a permission to $user for $action (allowed: $isAllowed)") } catch (iae: IllegalArgumentException) { event.sendMessageToSender(iae.message ?: L10n["error.generic"]) } } "reset" -> { if (!hasPermission(event.sender, resetPermission)) { event.forbidMessage(resetPermission) return } if (params.size < 3) { event.pluginMessage("Usage: !permissions reset <user> [<action>]") return } try { val user = params[2] val command = params.getOrElse(3, { "" }) permissions[event.server.getUserById(user)]!!.removeAll { command == "" || it.action == command } event.pluginMessage("Reset permissions of $user.") } catch (iae: IllegalArgumentException) { event.sendMessageToSender(iae.message ?: L10n["error.generic"]) } } else -> { event.pluginMessage("Unknown subcommand '${params[1]}'.") } } } private fun BaseMessageEvent.pluginMessage(msg: String) { sendMessageToSender("[Permissions] $msg") } private fun BaseMessageEvent.forbidMessage(action: String) { pluginMessage("Usage of $action denied.") } }
mpl-2.0
7cf44a8cb5a1d4ffc7685dc76427c789
30.990244
110
0.521958
5.127443
false
false
false
false
signed/intellij-community
platform/testFramework/src/com/intellij/mock/MockRunManager.kt
1
4165
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.mock import com.intellij.execution.* import com.intellij.execution.configurations.ConfigurationFactory import com.intellij.execution.configurations.ConfigurationType import com.intellij.execution.configurations.RunConfiguration import com.intellij.execution.configurations.RunProfile import com.intellij.openapi.util.Key import javax.swing.Icon /** * @author gregsh */ class MockRunManager : RunManagerEx() { override fun addConfiguration(settings: RunnerAndConfigurationSettings, isShared: Boolean) { } override fun hasSettings(settings: RunnerAndConfigurationSettings) = false override fun getConfigurationsList(type: ConfigurationType) = emptyList<RunConfiguration>() override fun makeStable(settings: RunnerAndConfigurationSettings) {} override val configurationFactories: Array<ConfigurationType> get() = emptyArray() override val configurationFactoriesWithoutUnknown: List<ConfigurationType> get() = emptyList() override val allConfigurationsList: List<RunConfiguration> get() = emptyList() override val allSettings: List<RunnerAndConfigurationSettings> get() = emptyList() override val tempConfigurationsList: List<RunnerAndConfigurationSettings> get() = emptyList() override var selectedConfiguration: RunnerAndConfigurationSettings? get() = null set(value) {} override fun createConfiguration(runConfiguration: RunConfiguration, factory: ConfigurationFactory): RunnerAndConfigurationSettings { throw UnsupportedOperationException() } override fun getConfigurationTemplate(factory: ConfigurationFactory): RunnerAndConfigurationSettings { throw UnsupportedOperationException() } override fun getConfigurationSettingsList(type: ConfigurationType): List<RunnerAndConfigurationSettings> { return emptyList() } override fun getStructure(type: ConfigurationType): Map<String, List<RunnerAndConfigurationSettings>> { return emptyMap() } override fun setTemporaryConfiguration(tempConfiguration: RunnerAndConfigurationSettings?) {} override fun getConfig(): RunManagerConfig { throw UnsupportedOperationException() } override fun createConfiguration(name: String, factory: ConfigurationFactory): RunnerAndConfigurationSettings { throw UnsupportedOperationException() } override fun addConfiguration(settings: RunnerAndConfigurationSettings) { } override fun getBeforeRunTasks(configuration: RunConfiguration): List<BeforeRunTask<*>> { return emptyList() } override fun <T : BeforeRunTask<*>> getBeforeRunTasks(taskProviderID: Key<T>): List<T> { return emptyList() } override fun <T : BeforeRunTask<*>> getBeforeRunTasks(settings: RunConfiguration, taskProviderID: Key<T>): List<T> { return emptyList() } override fun setBeforeRunTasks(runConfiguration: RunConfiguration, tasks: List<BeforeRunTask<*>>, addEnabledTemplateTasksIfAbsent: Boolean) {} override fun findConfigurationByName(name: String?): RunnerAndConfigurationSettings? { return null } override fun getConfigurationIcon(settings: RunnerAndConfigurationSettings): Icon? { return null } override fun getConfigurationIcon(settings: RunnerAndConfigurationSettings, withLiveIndicator: Boolean): Icon? { return null } override fun removeConfiguration(settings: RunnerAndConfigurationSettings?) {} override fun addRunManagerListener(listener: RunManagerListener) {} override fun removeRunManagerListener(listener: RunManagerListener) {} override fun refreshUsagesList(profile: RunProfile) {} }
apache-2.0
f0aebec20f2221c26ab47aa9b9fa1889
33.708333
144
0.783914
5.501982
false
true
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/ImageUtils.kt
1
14080
package net.perfectdreams.loritta.morenitta.utils import com.google.common.cache.CacheBuilder import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.utils.extensions.getOrNull import java.awt.* import java.awt.geom.RoundRectangle2D import java.awt.image.BufferedImage import java.util.* import java.util.concurrent.TimeUnit import kotlin.streams.toList fun Graphics.drawText(loritta: LorittaBot, text: String, x: Int, y: Int, maxX: Int? = null) { var currentX = x // X atual var currentY = y // Y atual var textToBeDrawn = text if (maxX != null) { var _text = "" var _x = x for (c in textToBeDrawn.toCharArray()) { val width = fontMetrics.charWidth(c) // Width do char (normalmente é 16) if (_x + width > maxX) { _text = _text.substring(0, _text.length - 4) _text += "..." break } _text += c _x += width } textToBeDrawn = _text } var idx = 0 for (c in textToBeDrawn.toCharArray()) { idx++ val width = fontMetrics.charWidth(c) // Width do char (normalmente é 16) if (!this.font.canDisplay(c)) { // Talvez seja um emoji! val emoteImage = ImageUtils.getTwitterEmoji(loritta, textToBeDrawn, idx) if (emoteImage != null) { this.drawImage(emoteImage.getScaledInstance(this.font.size, this.font.size, BufferedImage.SCALE_SMOOTH), currentX, currentY - this.font.size + 1, null) currentX += fontMetrics.maxAdvance } continue } this.drawString(c.toString(), currentX, currentY) // Escreva o char na imagem currentX += width // E adicione o width no nosso currentX } } fun Graphics.enableFontAntiAliasing(): Graphics2D { this as Graphics2D this.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON) return this } object ImageUtils { val emotes = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.HOURS).build<String, Optional<BufferedImage>>().asMap() fun getTwitterEmojiUrlId(emoji: String) = emoji.codePoints().toList().joinToString(separator = "-") { LorittaUtils.toUnicode(it).substring(2) } fun getTwitterEmoji(loritta: LorittaBot, text: String, index: Int): BufferedImage? { try { val imageUrl = "https://twemoji.maxcdn.com/2/72x72/" + LorittaUtils.toUnicode(text.codePointAt(index - 1)).substring(2) + ".png" try { if (emotes.containsKey(imageUrl)) return emotes[imageUrl]?.getOrNull() val emoteImage = LorittaUtils.downloadImage(loritta, imageUrl) emotes[imageUrl] = Optional.ofNullable(emoteImage) return emoteImage } catch (e: Exception) { // Outro try ... catch, esse é usado para evitar baixar imagens inexistentes, mas que o codepoint existe emotes[imageUrl] = Optional.empty() return null } } catch (e: Exception) { return null } } /** * Escreve um texto em um Graphics, fazendo wrap caso necessário * @param text Texto * @param startX X inicial * @param startY Y inicial * @param endX X máximo, caso o texto ultrapasse o endX, ele automaticamente irá fazer wrap para a próxima linha * @param endY Y máximo, atualmente unused * @param fontMetrics Metrics da fonte * @param graphics Graphics usado para escrever a imagem * @return Y final */ fun drawTextWrap(loritta: LorittaBot, text: String, startX: Int, startY: Int, endX: Int, endY: Int, fontMetrics: FontMetrics, graphics: Graphics): Int { val lineHeight = fontMetrics.height // Aqui é a altura da nossa fonte var currentX = startX // X atual var currentY = startY // Y atual var idx = 0 for (c in text.toCharArray()) { idx++ val width = fontMetrics.charWidth(c) // Width do char (normalmente é 16) if (currentX + width > endX) { // Se o currentX é maior que o endX... (Nós usamos currentX + width para verificar "ahead of time") currentX = startX // Nós iremos fazer wrapping do texto currentY += lineHeight } if (!graphics.font.canDisplay(c)) { val emoteImage = getTwitterEmoji(loritta, text, idx) if (emoteImage != null) { graphics.drawImage(emoteImage.getScaledInstance(graphics.font.size, graphics.font.size, BufferedImage.SCALE_SMOOTH), currentX, currentY - graphics.font.size + 1, null) currentX += fontMetrics.maxAdvance } continue } graphics.drawString(c.toString(), currentX, currentY) // Escreva o char na imagem currentX += width // E adicione o width no nosso currentX } return currentY } fun makeRoundedCorner(image: BufferedImage, cornerRadius: Int): BufferedImage { val w = image.width val h = image.height val output = BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB) val g2 = output.createGraphics() // This is what we want, but it only does hard-clipping, i.e. aliasing // g2.setClip(new RoundRectangle2D ...) // so instead fake soft-clipping by first drawing the desired clip shape // in fully opaque white with antialiasing enabled... g2.composite = AlphaComposite.Src g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g2.color = Color.WHITE g2.fill(RoundRectangle2D.Float(0f, 0f, w.toFloat(), h.toFloat(), cornerRadius.toFloat(), cornerRadius.toFloat())) // ... then compositing the image on top, // using the white shape from above as alpha source g2.composite = AlphaComposite.SrcAtop g2.drawImage(image, 0, 0, null) g2.dispose() return output } /** * Converts a given Image into a BufferedImage * * @param img The Image to be converted * @return The converted BufferedImage */ fun toBufferedImage(img: Image): BufferedImage { if (img is BufferedImage) { return img } // Create a buffered image with transparency val bimage = BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB) // Draw the image on to the buffered image val bGr = bimage.createGraphics() bGr.drawImage(img, 0, 0, null) bGr.dispose() // Return the buffered image return bimage } /** * Draw a String centered in the middle of a Rectangle. * * @param graphics The Graphics instance. * @param text The String to draw. * @param rect The Rectangle to center the text in. */ fun drawCenteredString(graphics: Graphics, text: String, rect: Rectangle, font: Font) { // Get the FontMetrics val metrics = graphics.getFontMetrics(font) // Determine the X coordinate for the text val x = rect.x + (rect.width - metrics.stringWidth(text)) / 2 // Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen) val y = rect.y + (rect.height - metrics.height) / 2 + metrics.ascent // Draw the String graphics.drawString(text, x, y) } /** * Draw a String centered in the middle of a Rectangle. * * @param graphics The Graphics instance. * @param text The String to draw. * @param rect The Rectangle to center the text in. */ fun drawCenteredStringEmoji(loritta: LorittaBot, graphics: Graphics, text: String, rect: Rectangle, font: Font) { // Get the FontMetrics val metrics = graphics.getFontMetrics(font) // Determine the X coordinate for the text var x = rect.x + (rect.width - metrics.stringWidth(text)) / 2 // Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen) val y = rect.y + (rect.height - metrics.height) / 2 + metrics.ascent var idx = 0 for (c in text.toCharArray()) { idx++ val width = graphics.fontMetrics.charWidth(c) // Width do char (normalmente é 16) if (!graphics.font.canDisplay(c)) { // Talvez seja um emoji! val emoteImage = getTwitterEmoji(loritta, text, idx) if (emoteImage != null) { graphics.drawImage(emoteImage.getScaledInstance(graphics.font.size, graphics.font.size, BufferedImage.SCALE_SMOOTH), x, y - graphics.font.size + 1, null) x += graphics.fontMetrics.maxAdvance } continue } graphics.drawString(c.toString(), x, y) // Escreva o char na imagem x += width // E adicione o width no nosso currentX } } /** * Draw a String centered in the middle of a Rectangle. * * @param graphics The Graphics instance. * @param text The String to draw. * @param rect The Rectangle to center the text in. */ fun drawCenteredStringOutlined(graphics: Graphics, text: String, rect: Rectangle, font: Font) { val color = graphics.color var g2d: Graphics2D? = null var paint: Paint? = null if (graphics is Graphics2D) { g2d = graphics paint = g2d.paint } // Get the FontMetrics val metrics = graphics.getFontMetrics(font) // Determine the X coordinate for the text val x = rect.x + (rect.width - metrics.stringWidth(text)) / 2 // Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen) val y = rect.y + (rect.height - metrics.height) / 2 + metrics.ascent // Draw the outline graphics.color = Color.BLACK graphics.drawString(text, x - 1, y) graphics.drawString(text, x + 1, y) graphics.drawString(text, x, y - 1) graphics.drawString(text, x, y + 1) // Draw the String graphics.color = color if (paint != null) { g2d!!.paint = paint } graphics.drawString(text, x, y) } /** * Escreve um texto em um Graphics, fazendo wrap caso necessário * * Esta versão separa entre espaços o texto, para ficar mais bonito * * @param text Texto * @param startX X inicial * @param startY Y inicial * @param endX X máximo, caso o texto ultrapasse o endX, ele automaticamente irá fazer wrap para a próxima linha * @param endY Y máximo, atualmente unused * @param fontMetrics Metrics da fonte * @param graphics Graphics usado para escrever a imagem * @return Y final */ fun drawTextWrapSpaces(loritta: LorittaBot, text: String, startX: Int, startY: Int, endX: Int, endY: Int, fontMetrics: FontMetrics, graphics: Graphics): Int { val lineHeight = fontMetrics.height // Aqui é a altura da nossa fonte var currentX = startX // X atual var currentY = startY // Y atual val split = text.split("((?<= )|(?= ))".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() // Nós precisamos deixar os espaços entre os splits! for (str in split) { var width = fontMetrics.stringWidth(str) // Width do texto que nós queremos colocar if (currentX + width > endX) { // Se o currentX é maior que o endX... (Nós usamos currentX + width para verificar "ahead of time") currentX = startX // Nós iremos fazer wrapping do texto currentY += lineHeight } var idx = 0 for (c in str.toCharArray()) { // E agora nós iremos printar todos os chars idx++ if (c == '\n') { currentX = startX // Nós iremos fazer wrapping do texto currentY += lineHeight continue } width = fontMetrics.charWidth(c) if (!graphics.font.canDisplay(c)) { // Talvez seja um emoji! val emoteImage = getTwitterEmoji(loritta, str, idx) if (emoteImage != null) { graphics.drawImage(emoteImage.getScaledInstance(width, width, BufferedImage.SCALE_SMOOTH), currentX, currentY - width, null) currentX += width } continue } graphics.drawString(c.toString(), currentX, currentY) // Escreva o char na imagem currentX += width // E adicione o width no nosso currentX } } return currentY } /** * Creates an image containing the [text] centralized on it */ fun createTextAsImage(loritta: LorittaBot, width: Int, height: Int, text: String): BufferedImage { val image = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) val graphics = image.graphics graphics.color = Color.WHITE graphics.fillRect(0, 0, width, height) val font = image.graphics.font.deriveFont(Font.BOLD, 22f) graphics.font = font graphics.color = Color.BLACK val fontMetrics = graphics.fontMetrics // Para escrever uma imagem centralizada, nós precisamos primeiro saber algumas coisas sobre o texto // Lista contendo (texto, posição) val lines = mutableListOf<String>() // Se está centralizado verticalmente ou não, por enquanto não importa para a gente val split = text.split(" ") var x = 0 var currentLine = StringBuilder() for (string in split) { val stringWidth = fontMetrics.stringWidth("$string ") val newX = x + stringWidth if (newX >= width) { var endResult = currentLine.toString().trim() if (endResult.isEmpty()) { // okay wtf // Se o texto é grande demais e o conteúdo atual está vazio... bem... substitua o endResult pela string atual endResult = string lines.add(endResult) x = 0 continue } lines.add(endResult) currentLine = StringBuilder() currentLine.append(' ') currentLine.append(string) x = fontMetrics.stringWidth("$string ") } else { currentLine.append(' ') currentLine.append(string) x = newX } } lines.add(currentLine.toString().trim()) // got it!!! // bem, supondo que cada fonte tem 22f de altura... // para centralizar é mais complicado val skipHeight = fontMetrics.ascent var y = (height / 2) - ((skipHeight - 10) * (lines.size - 1)) for (line in lines) { ImageUtils.drawCenteredStringEmoji(loritta, graphics, line, Rectangle(0, y, width, 24), font) y += skipHeight } return image } /** * Draws a string with a outline around it, the text will be drawn with the current color set in the graphics object * * @param graphics the image graphics * @param text the text that will be drawn * @param x where the text will be drawn in the x-axis * @param y where the text will be drawn in the y-axis * @param outlineColor the color of the outline * @param power the thickness of the outline */ fun drawStringWithOutline(graphics: Graphics, text: String, x: Int, y: Int, outlineColor: Color = Color.BLACK, power: Int = 2) { val originalColor = graphics.color graphics.color = outlineColor for (powerX in -power..power) { for (powerY in -power..power) { graphics.drawString(text, x + powerX, y + powerY) } } graphics.color = originalColor graphics.drawString(text, x, y) } }
agpl-3.0
e3db0a1f2696c7e5fccd4354552bf6d8
33.75495
172
0.693234
3.411079
false
false
false
false
talent-bearers/Slimefusion
src/main/java/talent/bearers/slimefusion/common/block/BlockZeleniDirt.kt
1
6605
package talent.bearers.slimefusion.common.block import com.teamwizardry.librarianlib.common.base.block.BlockMod import net.minecraft.block.IGrowable import net.minecraft.block.SoundType import net.minecraft.block.material.MapColor import net.minecraft.block.material.Material import net.minecraft.block.properties.PropertyEnum import net.minecraft.block.state.BlockStateContainer import net.minecraft.block.state.IBlockState import net.minecraft.entity.Entity import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.util.EnumFacing import net.minecraft.util.math.BlockPos import net.minecraft.util.math.RayTraceResult import net.minecraft.world.IBlockAccess import net.minecraft.world.World import net.minecraftforge.common.EnumPlantType import net.minecraftforge.common.IPlantable import talent.bearers.slimefusion.common.block.base.EnumStringSerializable import talent.bearers.slimefusion.common.lib.LibNames import java.util.* /** * @author WireSegal * Created at 7:33 AM on 12/27/16. */ class BlockZeleniDirt(name: String, val barren: Boolean = name == LibNames.SHALEDUST) : BlockMod(name, Material.GROUND, *EnumDirtVariant.getNamesFor(name)), IGrowable { init { setHardness(0.5F) tickRandomly = true } companion object { val TYPE: PropertyEnum<EnumDirtVariant> = PropertyEnum.create("type", EnumDirtVariant::class.java) } override fun getSoundType(state: IBlockState, world: World, pos: BlockPos, entity: Entity?): SoundType = if (state.getValue(TYPE) == EnumDirtVariant.DIRT) SoundType.GROUND else SoundType.PLANT override fun getMapColor(state: IBlockState) = if (state.getValue(TYPE) == EnumDirtVariant.DIRT) { if (barren) MapColor.GRAY else MapColor.LIGHT_BLUE } else { if (barren) MapColor.RED else MapColor.GRASS } override fun createBlockState() = BlockStateContainer(this, TYPE) override fun damageDropped(state: IBlockState) = state.getValue(TYPE).dropped override fun getPickBlock(state: IBlockState, target: RayTraceResult?, world: World?, pos: BlockPos?, player: EntityPlayer?) = ItemStack(this, 1, getMetaFromState(state)) override fun getMetaFromState(state: IBlockState) = state.getValue(TYPE).ordinal override fun getStateFromMeta(meta: Int) = defaultState.withProperty(TYPE, EnumDirtVariant[meta]) override fun updateTick(worldIn: World, pos: BlockPos, state: IBlockState, rand: Random) { if (!worldIn.isRemote && state.getValue(TYPE) == EnumDirtVariant.GRASS) { if (worldIn.getLightFromNeighbors(pos.up()) < 4 && worldIn.getBlockState(pos.up()).getLightOpacity(worldIn, pos.up()) > 2) { worldIn.setBlockState(pos, state.withProperty(TYPE, EnumDirtVariant.DIRT)) } else { if (worldIn.getLightFromNeighbors(pos.up()) >= 9) { for (i in 0..3) { val blockpos = pos.add(rand.nextInt(3) - 1, rand.nextInt(5) - 3, rand.nextInt(3) - 1) if (blockpos.y >= 0 && blockpos.y < 256 && !worldIn.isBlockLoaded(blockpos)) { return } val iblockstate = worldIn.getBlockState(blockpos.up()) val iblockstate1 = worldIn.getBlockState(blockpos) if (iblockstate1.block == this && iblockstate1.getValue(TYPE) == EnumDirtVariant.DIRT && worldIn.getLightFromNeighbors(blockpos.up()) >= 4 && iblockstate.getLightOpacity(worldIn, pos.up()) <= 2) { worldIn.setBlockState(blockpos, state) } } } } } } override fun canSustainPlant(state: IBlockState, world: IBlockAccess, pos: BlockPos, direction: EnumFacing, plantable: IPlantable): Boolean { return plantable.getPlantType(world, pos.offset(direction)) == EnumPlantType.Plains } override fun canUseBonemeal(worldIn: World, rand: Random, pos: BlockPos, state: IBlockState): Boolean { return !barren || state.getValue(TYPE) == EnumDirtVariant.DIRT } override fun grow(worldIn: World, rand: Random, pos: BlockPos, state: IBlockState) { if (state.getValue(TYPE) == EnumDirtVariant.DIRT) { worldIn.setBlockState(pos, state.withProperty(TYPE, EnumDirtVariant.GRASS)) } else { val empty = pos.up() for (i in 0..127) { var position = empty var j = 0 while (true) { if (j >= i / 16) { if (worldIn.isAirBlock(position)) { if (rand.nextInt(8) == 0) { worldIn.getBiome(position).plantFlower(worldIn, rand, position) } else { val grass = ModBlocks.FLOWER.defaultState.withProperty(BlockZeleniFlower.TYPE, BlockZeleniFlower.Type.GRASS) if (ModBlocks.FLOWER.canBlockStay(worldIn, position)) { worldIn.setBlockState(position, grass, 3) } } } break } position = position.add(rand.nextInt(3) - 1, (rand.nextInt(3) - 1) * rand.nextInt(3) / 2, rand.nextInt(3) - 1) if (worldIn.getBlockState(position.down()).block != this || worldIn.getBlockState(position).isNormalCube) { break } ++j } } } } override fun canGrow(worldIn: World, pos: BlockPos, state: IBlockState, isClient: Boolean): Boolean { return canUseBonemeal(worldIn, worldIn.rand, pos, state) } enum class EnumDirtVariant : EnumStringSerializable { DIRT, GRASS(0); val dropped: Int constructor(dropped: Int) { this.dropped = dropped } constructor() { dropped = ordinal } companion object { operator fun get(meta: Int) = EnumDirtVariant.values().getOrElse(meta) { DIRT } fun getNamesFor(prefix: String) = EnumDirtVariant.values() .map { prefix + "_" + it.getName() } .toTypedArray() } } }
mit
305088942cb2b9ee739ea85d90963c82
41.070064
220
0.597578
4.38579
false
false
false
false
Lennoard/HEBF
app/src/main/java/com/androidvip/hebf/receivers/NotificationButtonReceiver.kt
1
4149
package com.androidvip.hebf.receivers import android.app.NotificationManager import android.content.BroadcastReceiver import android.content.Context import android.content.Context.NOTIFICATION_SERVICE import android.content.Intent import android.widget.Toast import com.androidvip.hebf.R import com.androidvip.hebf.utils.* import com.androidvip.hebf.utils.gb.GameBoosterImpl import com.androidvip.hebf.utils.gb.GameBoosterNutellaImpl import com.androidvip.hebf.utils.vip.VipBatterySaverImpl import com.androidvip.hebf.utils.vip.VipBatterySaverNutellaImpl import com.topjohnwu.superuser.Shell import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class NotificationButtonReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val notifId = intent.getIntExtra(K.EXTRA_NOTIF_ID, -1) val actionId = intent.getIntExtra(K.EXTRA_NOTIF_ACTION_ID, -1) val manager = context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager? if (manager == null || actionId < 0 || notifId < 0) return GlobalScope.launch(Dispatchers.Default) { val isRooted = Shell.rootAccess() handleActionId(notifId, actionId, isRooted, context, manager) } } private suspend fun handleActionId( notifId: Int, actionId: Int, isRooted: Boolean, context: Context, manager: NotificationManager ) = withContext(Dispatchers.Main) { val closeNotifPanelIntent = Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS) val gameBooster = if (isRooted) { GameBoosterImpl(context) } else { GameBoosterNutellaImpl(context) } val vip = if (isRooted) { VipBatterySaverImpl(context) } else { VipBatterySaverNutellaImpl(context) } when (actionId) { K.NOTIF_ACTION_DISMISS_ID -> manager.cancel(notifId) K.NOTIF_ACTION_WM_RESET_ID -> { RootUtils.executeAsync("wm density reset") manager.cancel(notifId) } K.NOTIF_ACTION_BOOST_ID -> { context.sendBroadcast(closeNotifPanelIntent) Toast.makeText(context, "Boosted", Toast.LENGTH_SHORT).show() gameBooster.forceStopApps(context.applicationContext) RootUtils.executeAsync("sync && sysctl -w vm.drop_caches=3") System.gc() } K.NOTIF_ACTION_BOOST_LESS_ID -> { context.sendBroadcast(closeNotifPanelIntent) Toast.makeText(context, context.getString(R.string.done), Toast.LENGTH_LONG).show() System.gc() VipBatterySaverNutellaImpl.killApps(context, null) } K.NOTIF_ACTION_STOP_GB_ID -> { context.sendBroadcast(closeNotifPanelIntent) Toast.makeText(context, context.getString(R.string.game_off), Toast.LENGTH_LONG).show() manager.cancel(notifId) gameBooster.disable() } K.NOTIF_ACTION_STOP_GB_LESS_ID -> { context.sendBroadcast(closeNotifPanelIntent) Toast.makeText(context, context.getString(R.string.game_off), Toast.LENGTH_LONG).show() manager.cancel(notifId) gameBooster.disable() } K.NOTIF_ACTION_STOP_VIP_ID -> { context.sendBroadcast(closeNotifPanelIntent) manager.cancel(notifId) vip.disable() VipPrefs(context.applicationContext).putBoolean( K.PREF.VIP_SHOULD_STILL_ACTIVATE, false ) } K.NOTIF_ACTION_STOP_VIP_LESS_ID -> { context.sendBroadcast(closeNotifPanelIntent) GameBoosterNutellaImpl(context).toggleGameService(false) manager.cancel(notifId) vip.disable() } else -> manager.cancel(notifId) } } }
apache-2.0
6459a54d504e86f25d909925ae9a850c
35.403509
103
0.626898
4.5
false
false
false
false
VladRassokhin/intellij-hcl
src/kotlin/org/intellij/plugins/hil/codeinsight/FunctionInsertHandler.kt
1
4462
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.hil.codeinsight import com.intellij.codeInsight.completion.BasicInsertHandler import com.intellij.codeInsight.completion.CodeCompletionHandlerBase import com.intellij.codeInsight.completion.CompletionType import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.LookupElement import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorModificationUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import org.intellij.plugins.hcl.terraform.config.model.TypeModelProvider import org.intellij.plugins.hil.HILElementTypes import org.intellij.plugins.hil.psi.ILMethodCallExpression import org.intellij.plugins.hil.psi.ILSelectExpression import org.intellij.plugins.hil.psi.ILVariable object FunctionInsertHandler : BasicInsertHandler<LookupElement>() { override fun handleInsert(context: InsertionContext?, item: LookupElement?) { if (context == null || item == null) return val editor = context.editor val file = context.file val project = editor.project if (project == null || project.isDisposed) return val e = file.findElementAt(context.startOffset) ?: return val element: PsiElement? if (e.node?.elementType == HILElementTypes.ID) { element = e.parent } else { element = e } if (element !is ILVariable) return val function = TypeModelProvider.getModel(project).getFunction(item.lookupString) ?: return var offset: Int? = null val current: Int val expected = function.arguments.size var addBraces = false var place: Int = 0 // Probably first element in interpolation OR under ILSelectExpression val parent = element.parent if (parent is ILSelectExpression) { // Prohibited! return } if (parent is ILMethodCallExpression) { // Looks like function name modified current = parent.parameterList.parameters.size if (current != 0) { place = parent.parameterList.parameters.last().textOffset } } else { current = 0 addBraces = true } // TODO check context.completionChar before adding arguments or braces if (context.completionChar in " (") { context.setAddCompletionChar(false) } if (addBraces) { addBraces(editor, expected) editor.caretModel.moveToOffset(editor.caretModel.offset + 1) scheduleBasicCompletion(context) } else if (current < expected) { // TODO: Add some arguments // offset = editor.caretModel.offset + 2 // addArguments(expected, editor, place) // scheduleBasicCompletion(context) } PsiDocumentManager.getInstance(project).commitDocument(editor.document) if (offset != null) { editor.caretModel.moveToOffset(offset) } } private fun scheduleBasicCompletion(context: InsertionContext) { context.laterRunnable = object : Runnable { override fun run() { if (context.project.isDisposed || context.editor.isDisposed) return CodeCompletionHandlerBase(CompletionType.BASIC).invokeCompletion(context.project, context.editor) } } } private fun addArguments(count: Int, editor: Editor, place: Int) { val offset = editor.caretModel.offset editor.caretModel.moveToOffset(place) EditorModificationUtil.insertStringAtCaret(editor, "(${StringUtil.repeat(", ", count)})") editor.caretModel.moveToOffset(offset) } private fun addBraces(editor: Editor, expected: Int) { EditorModificationUtil.insertStringAtCaret(editor, "(${StringUtil.join((1..expected).map { "" }, ", ")})", false, false) // EditorModificationUtil.insertStringAtCaret(editor, " {}") // editor.caretModel.moveToOffset(editor.caretModel.offset - 1) } }
apache-2.0
6b11080b7c1133f3408280d481274f93
34.696
124
0.724563
4.484422
false
false
false
false
google/xplat
j2kt/jre/java/native/java/util/concurrent/atomic/AtomicInteger.kt
1
2079
/* * Copyright 2022 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 java.util.concurrent.atomic open class AtomicInteger internal constructor(private val ktAtomicInt: kotlinx.atomicfu.AtomicInt) : kotlin.Number() { constructor() : this(kotlinx.atomicfu.atomic(0)) constructor(initialValue: Int) : this(kotlinx.atomicfu.atomic(initialValue)) fun get(): Int = ktAtomicInt.value fun set(newValue: Int) { ktAtomicInt.value = newValue } fun lazySet(newValue: Int) = ktAtomicInt.lazySet(newValue) fun getAndSet(newValue: Int): Int = ktAtomicInt.getAndSet(newValue) fun compareAndSet(expect: Int, update: Int): Boolean = ktAtomicInt.compareAndSet(expect, update) fun getAndIncrement(): Int = ktAtomicInt.getAndIncrement() fun getAndDecrement(): Int = ktAtomicInt.getAndDecrement() fun getAndAdd(delta: Int): Int = ktAtomicInt.getAndAdd(delta) fun incrementAndGet(): Int = ktAtomicInt.incrementAndGet() fun decrementAndGet(): Int = ktAtomicInt.decrementAndGet() fun addAndGet(delta: Int): Int = ktAtomicInt.addAndGet(delta) override fun toString(): String = ktAtomicInt.toString() override fun toInt(): Int = ktAtomicInt.value override fun toLong(): Long = ktAtomicInt.value.toLong() override fun toFloat(): Float = ktAtomicInt.value.toFloat() override fun toDouble(): Double = ktAtomicInt.value.toDouble() override fun toByte(): Byte = ktAtomicInt.value.toByte() override fun toChar(): Char = ktAtomicInt.value.toChar() override fun toShort(): Short = ktAtomicInt.value.toShort() }
apache-2.0
5e9c62a1779db381803d4c52b61fa8b4
30.984615
100
0.742665
4.02907
false
false
false
false
chRyNaN/GuitarChords
sample/src/main/java/com/chrynan/sample/repository/values/OpenStandardGuitarChordValues.kt
1
7554
package com.chrynan.sample.repository.values import com.chrynan.chords.model.* // This is just setup this way for now because I'm too lazy to setup a database private val chordA by lazy { chord("A") { +ChordMarker.Muted(string = StringNumber(6)) +ChordMarker.Open(string = StringNumber(5)) +ChordMarker.Note( fret = FretNumber(2), finger = Finger.INDEX, string = StringNumber(4) ) +ChordMarker.Note( fret = FretNumber(2), finger = Finger.MIDDLE, string = StringNumber(3) ) +ChordMarker.Note( fret = FretNumber(2), finger = Finger.RING, string = StringNumber(2) ) +ChordMarker.Open(string = StringNumber(1)) } } private val chordAMinor by lazy { chord("Am") { +ChordMarker.Muted(string = StringNumber(6)) +ChordMarker.Open(string = StringNumber(5)) +ChordMarker.Note( fret = FretNumber(2), finger = Finger.MIDDLE, string = StringNumber(4) ) +ChordMarker.Note( fret = FretNumber(2), finger = Finger.RING, string = StringNumber(3) ) +ChordMarker.Note( fret = FretNumber(1), finger = Finger.INDEX, string = StringNumber(2) ) +ChordMarker.Open(string = StringNumber(1)) } } private val chordB by lazy { chord("B") { +ChordMarker.Muted(string = StringNumber(6)) +ChordMarker.Note( fret = FretNumber(1), finger = Finger.INDEX, string = StringNumber(5) ) +ChordMarker.Note( fret = FretNumber(3), finger = Finger.MIDDLE, string = StringNumber(4) ) +ChordMarker.Note( fret = FretNumber(3), finger = Finger.RING, string = StringNumber(3) ) +ChordMarker.Note( fret = FretNumber(3), finger = Finger.PINKY, string = StringNumber(2) ) +ChordMarker.Muted(string = StringNumber(1)) } } private val chordBMinor by lazy { chord("Bm") { +ChordMarker.Muted(string = StringNumber(6)) +ChordMarker.Bar( fret = FretNumber(2), finger = Finger.INDEX, startString = StringNumber(1), endString = StringNumber(5) ) +ChordMarker.Note( fret = FretNumber(4), finger = Finger.RING, string = StringNumber(4) ) +ChordMarker.Note( fret = FretNumber(4), finger = Finger.PINKY, string = StringNumber(3) ) +ChordMarker.Note( fret = FretNumber(3), finger = Finger.MIDDLE, string = StringNumber(2) ) } } private val chordC by lazy { chord("C") { +ChordMarker.Muted(string = StringNumber(6)) +ChordMarker.Note( fret = FretNumber(3), finger = Finger.RING, string = StringNumber(5) ) +ChordMarker.Note( fret = FretNumber(2), finger = Finger.MIDDLE, string = StringNumber(4) ) +ChordMarker.Open(string = StringNumber(3)) +ChordMarker.Note( fret = FretNumber(1), finger = Finger.INDEX, string = StringNumber(2) ) +ChordMarker.Open(string = StringNumber(1)) } } private val chordD by lazy { chord("D") { +ChordMarker.Muted(string = StringNumber(6)) +ChordMarker.Muted(string = StringNumber(5)) +ChordMarker.Open(string = StringNumber(4)) +ChordMarker.Note( fret = FretNumber(2), finger = Finger.INDEX, string = StringNumber(3) ) +ChordMarker.Note( fret = FretNumber(3), finger = Finger.RING, string = StringNumber(2) ) +ChordMarker.Note( fret = FretNumber(2), finger = Finger.MIDDLE, string = StringNumber(1) ) } } private val chordDMinor by lazy { chord("Dm") { +ChordMarker.Muted(string = StringNumber(6)) +ChordMarker.Muted(string = StringNumber(5)) +ChordMarker.Open(string = StringNumber(4)) +ChordMarker.Note( fret = FretNumber(2), finger = Finger.MIDDLE, string = StringNumber(3) ) +ChordMarker.Note( fret = FretNumber(3), finger = Finger.RING, string = StringNumber(2) ) +ChordMarker.Note( fret = FretNumber(1), finger = Finger.INDEX, string = StringNumber(1) ) } } private val chordE by lazy { chord("E") { +ChordMarker.Open(string = StringNumber(6)) +ChordMarker.Note( fret = FretNumber(2), finger = Finger.MIDDLE, string = StringNumber(5) ) +ChordMarker.Note( fret = FretNumber(2), finger = Finger.RING, string = StringNumber(4) ) +ChordMarker.Note( fret = FretNumber(1), finger = Finger.INDEX, string = StringNumber(3) ) +ChordMarker.Open(string = StringNumber(2)) +ChordMarker.Open(string = StringNumber(1)) } } private val chordEMinor by lazy { chord("Em") { +ChordMarker.Open(string = StringNumber(6)) +ChordMarker.Note( fret = FretNumber(2), finger = Finger.MIDDLE, string = StringNumber(5) ) +ChordMarker.Note( fret = FretNumber(2), finger = Finger.RING, string = StringNumber(4) ) +ChordMarker.Open(string = StringNumber(3)) +ChordMarker.Open(string = StringNumber(2)) +ChordMarker.Open(string = StringNumber(1)) } } private val chordF by lazy { chord("F") { +ChordMarker.Muted(string = StringNumber(6)) +ChordMarker.Muted(string = StringNumber(5)) +ChordMarker.Note( fret = FretNumber(3), finger = Finger.RING, string = StringNumber(4) ) +ChordMarker.Note( fret = FretNumber(2), finger = Finger.MIDDLE, string = StringNumber(3) ) +ChordMarker.Bar( fret = FretNumber(1), finger = Finger.INDEX, startString = StringNumber(1), endString = StringNumber(2) ) } } private val chordG by lazy { chord("G") { +ChordMarker.Note( fret = FretNumber(3), finger = Finger.MIDDLE, string = StringNumber(6) ) +ChordMarker.Note( fret = FretNumber(2), finger = Finger.INDEX, string = StringNumber(5) ) +ChordMarker.Open(string = StringNumber(4)) +ChordMarker.Open(string = StringNumber(3)) +ChordMarker.Note( fret = FretNumber(3), finger = Finger.RING, string = StringNumber(2) ) +ChordMarker.Note( fret = FretNumber(3), finger = Finger.PINKY, string = StringNumber(1) ) } } val openStandardGuitarChords = setOf(chordA, chordAMinor, chordB, chordBMinor, chordC, chordD, chordDMinor, chordE, chordEMinor, chordF, chordG)
apache-2.0
3d7bae190abddaa43e93ade3a91fbe5f
27.085502
117
0.521048
3.926195
false
false
false
false
simonorono/SRSM
src/main/kotlin/srsm/controller/util/Validators.kt
1
2986
/* * Copyright 2016 Sociedad Religiosa Servidores de María * * 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 srsm.controller.util import javafx.scene.control.Control import javafx.scene.control.DatePicker import javafx.scene.control.TextArea import javafx.scene.control.TextField import org.apache.commons.validator.routines.EmailValidator import srsm.Message fun required(vararg fields: Pair<String, Control>) { for (field in fields) { when (field.second) { is TextField -> { if ((field.second as TextField).text.isEmpty()) { Message.error("El campo \"${field.first}\" es requerido") throw Exception("Campo requerido vacio") } } is TextArea -> { if ((field.second as TextArea).text.isEmpty()) { Message.error("El campo \"${field.first}\" es requerido") throw Exception("Campo requerido vacio") } } else -> NotImplementedError() } } } fun integerFormat(vararg fields: Pair<String, TextField>) { fields.forEach { if (it.second.text.isNotEmpty() && !it.second.text.matches(Regex("\\d+"))) { Message.error("El campo \"${it.first}\" solo debe contener dígitos") throw Exception("Campo con mal formato") } } } fun phoneFormat(vararg fields: Pair<String, TextField>) { fields.forEach { if (it.second.text.isNotEmpty() && !it.second.text.matches(Regex("\\d{4}-\\d{7}"))) { Message.error("El campo \"${it.first}\" debe tener el formato XXXX-XXXXXXX") throw Exception("Campo con mal formato") } } } fun emailFormat(email: String) { if (email.isNotEmpty()) { val ev = EmailValidator.getInstance(false) if (!ev.isValid(email)) { Message.error("El correo electrónico tiene mal formato") throw Exception("Campo con mal formato") } } } fun dateValid(vararg fields: Pair<String, DatePicker>) { fields.forEach { if (it.second.editor.text != "" && it.second.value == null) { Message.error("${it.first} errada") throw Exception("Fecha mal formada") } } } fun passwords(pass1: String, pass2: String) { if (pass1 != pass2) { Message.error("Las contraseñas no coinciden") throw Exception("Contraseñas no coinciden") } }
apache-2.0
67fe2a5e281830af9402bfabaab47eab
32.494382
93
0.618249
3.922368
false
false
false
false
JayNewstrom/ScreenSwitcher
sample-screen-third/src/main/java/screenswitchersample/third/ThirdScreen.kt
1
1993
package screenswitchersample.third import android.view.View import androidx.annotation.LayoutRes import com.jaynewstrom.concrete.ConcreteBlock import com.jaynewstrom.screenswitcher.Screen import com.jaynewstrom.screenswitcher.ScreenSwitcherState import dagger.Component import dagger.Module import dagger.Provides import screenswitchersample.core.screen.BaseScreen import screenswitchersample.core.screen.DefaultScreenWallManager import screenswitchersample.core.screen.ScreenScope import screenswitchersample.core.screen.ScreenWallManager import javax.inject.Named object ThirdScreenFactory { fun create(navigator: ThirdNavigator): Screen = ThirdScreen(navigator) } private class ThirdScreen(private val navigator: ThirdNavigator) : BaseScreen<ThirdComponent>() { override fun createWallManager(screenSwitcherState: ScreenSwitcherState): ScreenWallManager<ThirdComponent> { return DefaultScreenWallManager({ ThirdScreenBlock(navigator) }) } @LayoutRes override fun layoutId(): Int = ThirdPresenter.layoutId() override fun bindView(view: View, component: ThirdComponent) { ThirdPresenter.bindView(view, component) } } @ScreenScope @Component(modules = [ThirdModule::class]) internal interface ThirdComponent { fun inject(dialog: ThirdScreenDialog) fun inject(presenter: ThirdPresenter) } private class ThirdScreenBlock(private val navigator: ThirdNavigator) : ConcreteBlock<ThirdComponent> { override fun name(): String = javaClass.name override fun createComponent(): ThirdComponent = DaggerThirdComponent.builder() .thirdModule(ThirdModule(navigator)) .build() } @Module private class ThirdModule(private val navigator: ThirdNavigator) { @Provides fun provideNavigator() = navigator @Module companion object { @JvmStatic @Provides @Named("dialogMessage") fun provideDialogMessage(): String { return "Rotate the device to see if it works!" } } }
apache-2.0
92905e2e95d352fafe334455a4551ada
32.216667
113
0.772704
4.790865
false
false
false
false
albertoruibal/karballo
karballo-common/src/main/kotlin/karballo/pgn/PgnImportExport.kt
1
3222
package karballo.pgn import karballo.Board import karballo.Move import karballo.util.Utils object PgnImportExport { /** * Parses a PGN and does all the moves in a board */ fun setBoard(b: Board, pgnString: String) { val game = PgnParser.parsePgn(pgnString) if (game!!.fenStartPosition != null) { b.fen = game.fenStartPosition!! } else { b.startPosition() } for (gameNode in game.pv!!.variation) { if (gameNode is GameNodeMove) { val move = Move.getFromString(b, gameNode.move, true) b.doMove(move) } } } fun getPgn(b: Board, whiteName: String?, blackName: String?, event: String? = null, site: String? = null, result: String? = null): String { var whiteNameVar = whiteName var blackNameVar = blackName var eventVar = event var siteVar = site var resultVar = result val sb = StringBuilder() if (whiteNameVar == null || "" == whiteNameVar) { whiteNameVar = "?" } if (blackNameVar == null || "" == blackNameVar) { blackNameVar = "?" } if (eventVar == null) { eventVar = "Chess Game" } if (siteVar == null) { siteVar = "-" } sb.append("[Event \"").append(eventVar).append("\"]\n") sb.append("[Site \"").append(siteVar).append("\"]\n") sb.append("[Date \"").append(Utils.instance.getCurrentDateIso().replace('-', '.')).append("\"]\n") sb.append("[Round \"?\"]\n") sb.append("[White \"").append(whiteNameVar).append("\"]\n") sb.append("[Black \"").append(blackNameVar).append("\"]\n") if (resultVar == null) { resultVar = "*" when (b.isEndGame) { 1 -> resultVar = "1-0" -1 -> resultVar = "0-1" 99 -> resultVar = "1/2-1/2" } } sb.append("[Result \"").append(resultVar).append("\"]\n") if (Board.FEN_START_POSITION != b.initialFen) { sb.append("[FEN \"").append(b.initialFen).append("\"]\n") } sb.append("[PlyCount \"").append(b.moveNumber - b.initialMoveNumber).append("\"]\n") sb.append("\n") val line = StringBuilder() for (i in b.initialMoveNumber..b.moveNumber - 1) { line.append(" ") if (i and 1 == 0) { line.append(i.ushr(1) + 1) line.append(". ") } line.append(b.getSanMove(i)) } line.append(" ") line.append(resultVar) // Cut line in a limit of 80 characters val tokens = line.toString().split("[ \\t\\n\\x0B\\f\\r]+".toRegex()).dropLastWhile(String::isEmpty).toTypedArray() var length = 0 for (token in tokens) { if (length + token.length + 1 > 80) { sb.append("\n") length = 0 } else if (length > 0) { sb.append(" ") length++ } length += token.length sb.append(token) } return sb.toString() } }
mit
20042b85c166896f81952ab9ca906f0b
29.990385
143
0.490379
3.924482
false
false
false
false
intrigus/chemie
android/src/main/kotlin/de/intrigus/chem/util/SimpleCursorLoader.kt
1
2890
package de.intrigus.chem.util /* * Copyright (C) 2010 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 android.content.Context import android.database.Cursor import android.support.v4.content.AsyncTaskLoader /** * Used to write apps that run on platforms prior to Android 3.0. When running * on Android 3.0 or above, this implementation is still used; it does not try * to switch to the framework's implementation. See the framework SDK * documentation for a class overview. * * * This was based on the CursorLoader class */ abstract class SimpleCursorLoader(context: Context) : AsyncTaskLoader<Cursor>(context) { private var mCursor: Cursor? = null /* Runs on a worker thread */ abstract override fun loadInBackground(): Cursor /* Runs on the UI thread */ override fun deliverResult(cursor: Cursor?) { if (isReset) { // An async query came in while the loader is stopped cursor?.close() return } val oldCursor = mCursor mCursor = cursor if (isStarted) { super.deliverResult(cursor) } if (oldCursor != null && oldCursor !== cursor && !oldCursor.isClosed) { oldCursor.close() } } /** * Starts an asynchronous load of the contacts list data. When the result is ready the callbacks * will be called on the UI thread. If a previous load has been completed and is still valid * the result may be passed to the callbacks immediately. * * * Must be called from the UI thread */ override fun onStartLoading() { if (mCursor != null) { deliverResult(mCursor) } if (takeContentChanged() || mCursor == null) { forceLoad() } } /** * Must be called from the UI thread */ override fun onStopLoading() { // Attempt to cancel the current load task if possible. cancelLoad() } override fun onCanceled(cursor: Cursor?) { if (cursor != null && !cursor.isClosed) { cursor.close() } } override fun onReset() { super.onReset() // Ensure the loader is stopped onStopLoading() if (mCursor != null && !mCursor!!.isClosed) { mCursor!!.close() } mCursor = null } }
apache-2.0
926618a95804792050c3df4eee66c294
28.20202
100
0.635294
4.515625
false
false
false
false
sephiroth74/Material-BottomNavigation
bottom-navigation/src/main/java/it/sephiroth/android/library/bottomnavigation/TabletBehavior.kt
1
2783
package it.sephiroth.android.library.bottomnavigation import android.content.Context import android.os.Build import android.util.AttributeSet import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.Toolbar import androidx.coordinatorlayout.widget.CoordinatorLayout import com.google.android.material.appbar.AppBarLayout import timber.log.Timber /** * Created by alessandro on 4/10/16 at 2:12 PM. * Project: Material-BottomNavigation */ class TabletBehavior(context: Context, attrs: AttributeSet) : VerticalScrollingBehavior<BottomNavigation>(context, attrs) { private var topInset: Int = 0 private var enabled: Boolean = false private var width: Int = 0 private var translucentStatus: Boolean = false fun setLayoutValues(bottomNavWidth: Int, topInset: Int, translucentStatus: Boolean) { this.translucentStatus = translucentStatus Timber.v("setLayoutValues(bottomNavWidth: $bottomNavWidth, topInset: $topInset)") Timber.v("translucentStatus: $translucentStatus") this.width = bottomNavWidth this.topInset = topInset this.enabled = true } override fun layoutDependsOn(parent: CoordinatorLayout, child: BottomNavigation, dependency: View): Boolean { return dependency is AppBarLayout || dependency is Toolbar } override fun onDependentViewChanged( parent: CoordinatorLayout, child: BottomNavigation, dependency: View): Boolean { val params = child.layoutParams as ViewGroup.MarginLayoutParams val top = if (Build.VERSION.SDK_INT > 19) topInset else if (translucentStatus) topInset else 0 params.topMargin = Math.max(dependency.top + dependency.height - top, if (translucentStatus) 0 else -top) if (translucentStatus) { if (params.topMargin < top) { child.setPadding(0, top - params.topMargin, 0, 0) } else { child.setPadding(0, 0, 0, 0) } } child.requestLayout() return true } override fun onNestedVerticalOverScroll( coordinatorLayout: CoordinatorLayout, child: BottomNavigation, @ScrollDirection direction: Int, currentOverScroll: Int, totalOverScroll: Int) { } override fun onDirectionNestedPreScroll( coordinatorLayout: CoordinatorLayout, child: BottomNavigation, target: View, dx: Int, dy: Int, consumed: IntArray, @ScrollDirection scrollDirection: Int) { } override fun onNestedDirectionFling( coordinatorLayout: CoordinatorLayout, child: BottomNavigation, target: View, velocityX: Float, velocityY: Float, @ScrollDirection scrollDirection: Int): Boolean { return false } }
mit
f66f14c992748297e15550bf3cfe9205
37.652778
123
0.699245
4.943162
false
false
false
false
sedovalx/xodus-entity-browser
entity-browser-app/src/main/kotlin/com/lehvolk/xodus/web/resources/EntityTypeResource.kt
1
3368
package com.lehvolk.xodus.web.resources import com.fasterxml.jackson.core.JsonProcessingException import com.lehvolk.xodus.web.ChangeSummary import com.lehvolk.xodus.web.EntityView import com.lehvolk.xodus.web.SearchPager import javax.ws.rs.* import javax.ws.rs.core.MediaType import javax.ws.rs.core.StreamingOutput @Path("/type") class EntityTypeResource : ApplicationResource() { @GET @Path("{id}/entities") fun searchEntities( @PathParam("id") id: Int, @QueryParam("q") term: String?, @QueryParam("offset") offset: Int = 0, @QueryParam("pageSize") pageSize: Int = 0): SearchPager { log.debug("searching entities by typeId: {}, term [{}] with offset = {} and pageSize = {}", id, term, offset, pageSize) if (offset < 0 || pageSize < 0) { throw BadRequestException() } safely { return storeService.searchType(id, term, offset, if (pageSize == 0) 50 else Math.min(pageSize, 1000)) } } @GET @Path("{id}/entity/{entityId}") fun getEntity( @PathParam("id") id: Int, @PathParam("entityId") entityId: Long): EntityView { log.debug("getting entity by typeId={} and entityId={}", id, entityId) safely { return storeService.getEntity(id, entityId) } } @PUT @Path("{id}/entity/{entityId}") fun updateEntity( @PathParam("id") id: Int, @PathParam("entityId") entityId: Long, vo: ChangeSummary): EntityView { if (log.isDebugEnabled) { log.debug("updating entity for type {} and id {}. ChangeSummary: {}", id, entityId, toString(vo)) } safely { return storeService.updateEntity(id, entityId, vo) } } @POST @Path("{id}/entity") fun newEntity( @PathParam("id") id: Int, vo: ChangeSummary): EntityView { if (log.isDebugEnabled) { log.debug("creating entity for type {} and ChangeSummary: {}", id, toString(vo)) } safely { return storeService.newEntity(id, vo) } } @DELETE @Path("{id}/entity/{entityId}") fun deleteEntity( @PathParam("id") id: Int, @PathParam("entityId") entityId: Long) { log.debug("deleting entity for type {} and id {}", id, entityId) safely { storeService.deleteEntity(id, entityId) } } @GET @Path("{id}/entity/{entityId}/blob/{blobName}") @Produces(MediaType.APPLICATION_OCTET_STREAM + ";charset=utf-8") fun getBlob( @PathParam("id") id: Int, @PathParam("entityId") entityId: Long, @PathParam("blobName") blobName: String): StreamingOutput { log.debug("getting entity blob data for type {} and id {} and blob '{}'", id, entityId, blobName) return StreamingOutput { safely { storeService.getBlob(id, entityId, blobName, it) } } } private fun toString(vo: ChangeSummary): String { try { return configurator.mapper.writeValueAsString(vo) } catch (e: JsonProcessingException) { return "Error converting vo to string. Check the server state this error should never happened" } } }
apache-2.0
9b3f3580c68dd61818c881451dc4e4c3
31.085714
113
0.578088
4.247163
false
false
false
false
Shynixn/BlockBall
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/proxy/BallDesignEntity.kt
1
4371
@file:Suppress("UNCHECKED_CAST") package com.github.shynixn.blockball.core.logic.business.proxy import com.github.shynixn.blockball.api.business.enumeration.BallSize import com.github.shynixn.blockball.api.business.enumeration.CompatibilityArmorSlotType import com.github.shynixn.blockball.api.business.enumeration.MaterialType import com.github.shynixn.blockball.api.business.proxy.BallProxy import com.github.shynixn.blockball.api.business.service.ItemTypeService import com.github.shynixn.blockball.api.business.service.PacketService import com.github.shynixn.blockball.api.business.service.ProxyService import com.github.shynixn.blockball.api.persistence.entity.Position import com.github.shynixn.blockball.core.logic.persistence.entity.EntityMetadataImpl import com.github.shynixn.blockball.core.logic.persistence.entity.ItemEntity import com.github.shynixn.blockball.core.logic.persistence.entity.PositionEntity class BallDesignEntity(val entityId: Int) { private val helmetItemStack by lazy { val item = ItemEntity { this.type = MaterialType.SKULL_ITEM.MinecraftNumericId.toString() this.dataValue = 3 this.skin = ball.meta.skin this.nbt = ball.meta.itemNbt } itemService.toItemStack<Any>(item) } /** * Rotation of the design in euler angles. */ var rotation: Position = PositionEntity(0.0, 0.0, 0.0) /** * Proxy service dependency. */ lateinit var proxyService: ProxyService /** * Packet service dependency. */ lateinit var packetService: PacketService /** * Item service dependency. */ lateinit var itemService: ItemTypeService /** * Reference. */ lateinit var ball: BallProxy /** * Spawns the ball for the given player. */ fun spawn(player: Any, position: Position) { packetService.sendEntitySpawnPacket(player, entityId, "ARMOR_STAND", position) if (!ball.meta.isSlimeVisible) { packetService.sendEntityEquipmentPacket( player, entityId, CompatibilityArmorSlotType.HELMET, helmetItemStack ) } packetService.sendEntityMetaDataPacket(player, entityId, EntityMetadataImpl { this.isInvisible = true this.isSmall = ball.meta.size == BallSize.SMALL }) } /** * Destroys the ball for the given player. */ fun destroy(player: Any) { packetService.sendEntityDestroyPacket(player, entityId) } /** * Ticks the hitbox. * @param players watching this hitbox. */ fun <P> tick(players: List<P>) { val position = proxyService.toPosition(ball.getLocation<Any>()) position.y = if (ball.meta.size == BallSize.NORMAL) { position.y + ball.meta.hitBoxRelocation - 1.2 } else { position.y + ball.meta.hitBoxRelocation - 0.4 } for (player in players) { packetService.sendEntityTeleportPacket(player, entityId, position) } if (ball.meta.rotating) { playRotationAnimation(players as List<Any>) } } /** * Plays the rotation animation. */ private fun playRotationAnimation(players: List<Any>) { // 360 0 0 is a full forward rotation. // Length of the velocity is the speed of the ball. val velocity = proxyService.toPosition(ball.getVelocity<Any>()) val length = if (ball.isOnGround) { PositionEntity(velocity.x, 0.0, velocity.z).length() } else { PositionEntity(velocity.x, velocity.y, velocity.z).length() } val angle = when { length > 1.0 -> PositionEntity(rotation.x - 30, 0.0, 0.0) length > 0.1 -> PositionEntity(rotation.x - 10, 0.0, 0.0) length > 0.08 -> PositionEntity(rotation.x - 5, 0.0, 0.0) else -> null } if (angle != null) { rotation = angle if (ball.meta.isSlimeVisible) { return } for (player in players) { packetService.sendEntityMetaDataPacket(player, entityId, EntityMetadataImpl { this.armorstandHeadRotation = rotation }) } } } }
apache-2.0
6bcd531846504173f294ab08494ccb68
30.446043
93
0.627774
4.260234
false
false
false
false
team401/2017-Robot-Code
src/main/java/org/team401/robot/ControlBoard.kt
1
1970
package org.team401.robot import org.strongback.components.Switch import org.strongback.hardware.Hardware object ControlBoard { private val drive = Hardware.HumanInterfaceDevices.logitechDualAction(Constants.DRIVER_GAMEPAD) private val mash = Hardware.HumanInterfaceDevices.logitechF310(Constants.MASHER_GAMEPAD) // drive fun getDrivePitch() = drive.getAxis(1).read() fun getDriveStrafe() = drive.getAxis(0).read() fun getDriveRotate() = drive.getAxis(2).read() // controls drive fun getShift() = drive.getButton(6) fun getToggleOpenLoop() = drive.getButton(1) fun getToggleHeading() = drive.getButton(5) fun getToggleGearProc() = drive.getButton(4) fun getGearOut() = drive.getButton(8) fun getGearIntake() = drive.getButton(7) fun getResetGyro() = drive.getButton(9) fun getToggleBrake() = drive.getButton(10) fun getGyroPadAngle() = drive.getDPad(0) // controls masher fun getToggleSentry() = mash.getButton(2) fun getToggleAuto() = mash.getButton(3) fun getToggleHood() = mash.getButton(6) fun getToggleTower() = mash.getButton(1) fun getInverseHopper() = mash.getButton(5) fun getInverseKicker() = mash.getButton(7) fun getCalibrateTurret() = mash.getButton(8) fun getDisableTurret() = Switch { mash.getDPad(0).direction == 90 } fun getToggleCamera() = mash.getButton(4) fun getTurretSnapLeft() = Switch { mash.getDPad(0).direction == 270 } fun getTurretSnapCenter() = Switch { mash.getDPad(0).direction == 0 } fun getTurretSnapRight() = Switch { mash.getDPad(0).direction == 90 } fun getIntakeThrottle() = mash.getAxis(2).read() fun getToggleIntake() = Switch { mash.getAxis(2).read() > .1 } fun getShootFuel() = Switch { mash.getAxis(3).read() > .1 } fun getTurretYaw() = mash.getAxis(0).read() fun getTurretThrottle() = mash.getAxis(5).read() fun getDriveController() = drive fun getMasherController() = mash }
gpl-3.0
d8ae33274c88cda6257ee603952a3261
39.22449
99
0.69797
3.367521
false
false
false
false
Freezerburn/Plus1Torch
src/com/ud/plus1torch/screen/AsciiScreen.kt
1
40492
package com.ud.plus1torch.screen import java.awt.Color import java.awt.geom.Line2D import java.util.* enum class ScreenLayer(val layer: Int) { BACKGROUND(0), PLAY(1), UI(2) } val TEXT_BLINKING_DELAY_ARG_NAME = "BlinkingDelayMilliseconds" private val TEXT_BLINKING_DELAY_DEFAULT: Int = 500 val TEXT_BLINKING = 0x0001 // Since this engine isn't ACTUALLY a terminal, we can do things that aren't possible to do in a terminal, such as put // borders around a character. // Can accept an extra attribute argument with the color a border should be drawn as. If not set, then the background // color will be used as the default. val TEXT_BORDER_COLOR_RIGHT_ARG_NAME = "BorderColorArgumentRight" val TEXT_BORDER_COLOR_LEFT_ARG_NAME = "BorderColorArgumentLeft" val TEXT_BORDER_COLOR_TOP_ARG_NAME = "BorderColorArgumentTop" val TEXT_BORDER_COLOR_BOTTOM_ARG_NAME = "BorderColorArgumentBottom" val TEXT_BORDER_COLOR_ALL_ARG_NAME = "BorderColorArgumentAll" private val TEXT_BORDER_COLOR_DEFAULT = Color.WHITE val TEXT_BORDER_RIGHT = 0x0002 val TEXT_BORDER_LEFT = 0x0004 val TEXT_BORDER_TOP = 0x0008 val TEXT_BORDER_BOTTOM = 0x0010 val TEXT_BORDER_ALL = TEXT_BORDER_RIGHT or TEXT_BORDER_LEFT or TEXT_BORDER_TOP or TEXT_BORDER_BOTTOM // TODO: Write code that automatically builds fancy walls when placing characters. // This is basically using the various wall-like code points in CP437 to create a nice-looking wall when placing // wall characters. This will automatically create the correct corners and direction of walls based on where each // wall is placed. e.g.: // ## -> ══ // // # ║ // # -> ║ // // # ║ // ## -> ╚═ // etc. val TEXT_AUTO_FANCY_WALL = 0x0020 val TEXT_FANCY_WALL_PREFER_SINGLE_ARG_NAME = "FancyWallPreferSingle" val TEXT_FANCY_WALL_PREFER_DOUBLE_ARG_NAME = "FancyWallPreferDouble" val TEXT_FANCY_WALL_ONLY_BORDERS_ARG_NAME = "FancyWallBorderOnly" val TEXT_FANCY_WALL_INCLUDE_BORDERS_ARG_NAME = "FancyWallIncludeBorders" /** * Every character in Code Page 437, in the order they are defined in. Excluding the first character, as there * didn't seem to be a unicode definition for it on wikipedia: * https://en.wikipedia.org/wiki/Code_page_437 * The first character is just a space, to make sure that all the rest of the characters line up correctly. This * should be used as a basis for building the UI/play area for a game. * TODO: Define some index values for commonly-used characters, such as walls and fancy walls. */ val CP437 = charArrayOf( ' ', '\u263A', '\u263B', '\u2665', '\u2666', '\u2663', '\u2660', '\u2022', '\u25D8', '\u25CB', '\u25D9', '\u2642', '\u2642', '\u2640', '\u266A', '\u266B', '\u263C', '\u25BA', '\u25C4', '\u2195', '\u203C', '\u00B6', '\u00A7', '\u25AC', '\u21A8', '\u2191', '\u2193', '\u2192', '\u2190', '\u221F', '\u2194', '\u25B2', '\u25BC', '\u0020', '\u0021', '\u0022', '\u0023', '\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029', '\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F', '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B', '\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041', '\u0043', '\u0043', '\u0044', '\u0045', '\u0056', '\u0047', '\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053', '\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F', '\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078', '\u0079', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D', '\u007D', '\u007E', '\u2302', '\u00C7', '\u00FC', '\u00E9', '\u00E2', '\u00E4', '\u00E0', '\u00E7', '\u00EA', '\u00EB', '\u00E8', '\u00EF', '\u00EE', '\u00EC', '\u00C4', '\u00C5', '\u00C9', '\u00E6', '\u00F4', '\u00F6', '\u00F2', '\u00FB', '\u00F9', '\u00FF', '\u00D6', '\u00DC', '\u00A2', '\u00A3', '\u00A5', '\u30A7', '\u0192', '\u00E1', '\u00ED', '\u00F3', '\u00FA', '\u00F1', '\u00D1', '\u00AA', '\u00BA', '\u00BF', '\u2310', '\u00AC', '\u00BD', '\u00BC', '\u00A1', '\u00AB', '\u00BB', '\u2591', '\u2592', '\u2593', '\u2502', '\u2524', '\u2561', '\u2562', '\u2556', '\u2555', '\u2563', '\u2551', '\u2557', '\u255D', '\u255C', '\u255B', '\u2510', '\u2514', '\u2534', '\u252C', '\u251C', '\u2500', '\u253C', '\u255E', '\u255F', '\u255A', '\u2554', '\u2569', '\u2566', '\u2560', '\u2550', '\u2550', '\u256C', '\u2567', '\u2568', '\u2564', '\u2565', '\u2559', '\u2558', '\u2552', '\u2553', '\u256B', '\u256A', '\u2518', '\u250C', '\u2588', '\u2584', '\u258C', '\u2590', '\u2580', '\u03B1', '\u00DF', '\u0393', '\u03C0', '\u03A3', '\u03C3', '\u00B5', '\u03C4', '\u03A6', '\u0398', '\u03A9', '\u03B4', '\u221E', '\u03C6', '\u03B5', '\u2229', '\u2261', '\u00B1', '\u2265', '\u2264', '\u2320', '\u2321', '\u00F7', '\u2248', '\u00B0', '\u2219', '\u00B7', '\u221A', '\u207F', '\u00B2', '\u25A0', '\u00A0' ) fun <T> ArrayList<T>.pop(): T? { return if (this.size > 0) this.removeAt(this.size - 1) else null } fun get1d(x: Int, y: Int, stride: Int): Int { return x + y * stride } infix fun Int.bitSet(other: Int): Boolean { return other and this == other } /** * Manages a field of ascii characters to be drawn to a window. Automatically figures out the correct font(s) to use * when drawing each character to make them look as good as possible, based on window size and the number of characters * being drawn to the screen at a time from the field. * * Once a field is initialized, it can no longer be changed. A new AsciiScreen object will need to be allocated. * * The size of the window can be changed on the fly as a user resizes it. The AsciiScreen will figure out new fonts * as necessary to handle the changing window. The same can be done for the number of characters being drawn to the * screen. * * The AsciiScreen can handle characters that are difference sizes. Meaning a single character can end up taking a * 2x2 space in the screen instead of just a 1x1 space like in a terminal. Oh the things we can do with modern * rendering! * * TODO: Calculate memory usage of this class and document it. * TODO: Create a "UI only" mode that allocates fewer objects. * The main motivation being that an AsciiScreen can theoretically be drawn anywhere in the game window, so it might * make sense to have a lower memory using mode for creating UI elements that don't just take up the entire window. * The design currently allows for any screen size to be given, and the rendering really only gives data inside of * itself and is completely agnostic to the rendering system, so it would be easily to have multiple screens that are * drawn at different places in the game window. Can even be used to "layer" multiple UIs on top of each other, just * by creating more AsciiScreen objects and drawing them instead of the others. (keep a stack even, so that when one * screen is left, the previous screen is drawn again) * TODO: Add in a way to control a camera that moves around the field. * TODO: Ability to tween camera. * This would be a couple things at least: ability to pan the camera by defining a tween from one location to another, * and ability to zoom camera by specifying new zoom level. This should probably include two modes: one mode does the * tweening smoothly like in a normal 2D game with graphics, and the other would be to tween by moving entire character * blocks at a time. * TODO: Change some ArrayLists to use pure arrays is if makes sense. * It makes sense if we don't need to expand the array at any point during runtime. This is likely to only apply to * the data in the field. Other lists need to be able to handle any number of things that change at runtime. * TODO: Add a way to query about what is in a location in any layer. * TODO: Add another layer that can be interacted with but doesn't cause collision. * This would be a kind of "floor" layer. Because the bottom layer is decorational and non-colliding, we need another * layer that things like items can be collected into. Maybe? Could that kind of thing be built into the current system * by just changing the visible icon of the decorational layer and then query about what's in it? * TODO: Add a user data object for any item? * TODO: Add a way to find the nearest place to a location that an item can be placed in a layer? * TODO: Add a method for finding a path from one location to another? * TODO: Add a method for drawing a line from one location to another of a given color? * Can an API be put together that supports any given shape in the Java standard library for drawing things? * TODO: Particle engine? * Never made a particle engine, might need some research into a good way to create one? * TODO: Good interop with Java. * This will possibly require using the annotations that Kotlin provides to make sure names and fields and whatnot * are all compiled in a way that works nicely with Java. Not sure if this will require all that much work, but it * would be a very good thing to have for people who don't want to/can't use Kotlin. * TODO: Load fonts in a framework-agnostic way. * How do I even do this? libgdx uses pre-created files to create BitmapFonts rather than using Java fonts, for * example. And it uses its own API to load the fonts from a resources folder, etc. * TODO: Keep an internal list of where all the characters are so we only iterate over actual items. * Current implementation of render is to just loop over every possible item, which can be quite a bit if the * width and height is pretty large. * * @param width: Number of characters that can be stored left to right across the field. * @param height: Number of characters that can be stored up to down across the field. * @param charactersDrawnX: The number of characters to draw left to right in the window. * @param charactersDrawnY: The number of characters to draw up to down in the window. * @param renderWidth: The width of the window being rendered into. * @param renderHeight: The height of the window being rendered into. * @param uiOnly: Whether or not to put this AsciiScreen into a mode that only has a single layer for the UI. Allocates * fewer object, but should not be used for a screen that has a play area. Defaults to false. * @param debug: Enables some extra checks/printing/exceptions such that improper use of the AsciiScreen or anything * returned from it will always indicate that it was used improperly. When not in this mode, the AsciiScreen and * anything it returns will do its best to "just work". Any behavior that changes when this mode is on will be * documented. Defaults to false. */ class AsciiScreen(internal var width: Int, internal var height: Int, charactersDrawnX: Int, charactersDrawnY: Int, renderWidth: Int, renderHeight: Int, val uiOnly: Boolean = false, internal val debug: Boolean = false) { /** * The number of characters that will be drawn from left to right in this AsciiScreen. */ var charactersDrawnX = charactersDrawnX /** * Change the number of characters that are drawn on the screen from left to right. This will change how * big each character gets drawn in the game window. */ set(value) { field = value } /** * The number of characters that will be drawn from top to bottom in this AsciiScreen. */ var charactersDrawnY = charactersDrawnY /** * Change the number of characters that are drawn on the screen from top to bottom. This will change how * big each character gets drawn in the game window. */ set(value) { field = value } /** * The width of the area of the screen that this AsciiScreen will be drawn into. This can be changed. */ var windowWidth = renderWidth /** * Change the width in pixels that this screen is drawing into. This will change how big each characters is * that gets drawn in the game window. */ set(value) { field = value } /** * The height of the area of the screen that this AsciiScreen will be drawn into. This can be changed. */ var windowHeight = renderHeight /** * Change the height in pixels that this screen is drawing into. This will change how big each characters is * that gets drawn in the game window. */ set(value) { field = value } /** * The total number of items that can be on the field at one time per layer. */ internal val itemsPerLayer = width * height /** * Amount of items and item wrappers to create immediately. */ internal val initialPooledItems = itemsPerLayer * (if (uiOnly) 1 else 3) + 1 /** * Allocated with enough capacity to hold 3 screens worth of items (if every item is 1x1) for every layer. Should * give a nice amount of items to work with at first. This value might need to be tuned going forward depending * on how many screens worth of items tend to be created. */ internal val pooledItems = ArrayList<ItemData>(initialPooledItems) /** * An allocated draw data that can be reused between every call to the render function. Instead of creating a new * object for ever render call. Save some CPU and GC cycles. */ internal val reusableDrawData = CharDrawData() /** * The actions that need to be resolved before rendering can take place. This includes things such as placing * new items, moving items, etc. The default size might need to be changed based on how many actions tend to * get queued for most frames to reduce GC pressure from an internal buffer being reallocated. */ internal val actionQueue = ArrayList<QueuedAction>(50) /** * Three layers: Background, Main ("play" area), UI * * Background generally has stuff that you don't interact with and is just there to add some flavor to a scene. It * is always below the other two layers. * * Main generally has the player, enemies, etc. Basically, stuff you interact with. * * UI is generally the bits of the screen that represent stuff like the inventory. You know, the UI :) This layer * will always be on top of the other layers. */ internal val layers = ArrayList<ArrayList<ItemData?>>(ScreenLayer.UI.layer) internal var cameraX = 0 internal var cameraY = 0 init { for(i in 0..initialPooledItems-1) { pooledItems.add(ItemData()) } if (uiOnly) { layers.add(ArrayList<ItemData?>(itemsPerLayer)) } else { for(i in 0..ScreenLayer.UI.layer) { val newLayer = ArrayList<ItemData?>(itemsPerLayer) layers.add(newLayer) for (j in 0..itemsPerLayer) { newLayer.add(null) } } } } /** * If this AsciiScreen is in UI-only mode and is not in debug mode, no matter what layer is passed in it will * always go to the single available layer. * * @throws IllegalArgumentException If marked for debug mode when constructed and is marked as a UI-only screen * and the layer argument is not the UI layer. */ fun place(c: Char, x: Int, y: Int, w: Int = 1, h: Int = 1, fg: Color = Color.WHITE, bg: Color = Color.BLACK, attributes: Int = 0, attributeArgs: Map<String, Any?> = HashMap<String, Any?>(), userData: Any? = null, layer: ScreenLayer = if (uiOnly) ScreenLayer.UI else ScreenLayer.PLAY): PlacedItem { if (debug && uiOnly && layer != ScreenLayer.UI) { throw IllegalArgumentException("A UI-only AsciiScreen got non-UI layer for placement: $layer") } // TODO: Handle attributes and their arguments. val item = pooledItems.pop() ?: ItemData() var wrapper = PlacedItem(this) val layerInt = if (uiOnly) 0 else layer.layer wrapper.item = item wrapper.layer = layerInt actionQueue.add(QueuedAction.PlacementAction( item(c, x, y, w, h, fg, bg, userData, attributes, attributeArgs, debug), layerInt )) return wrapper } fun clear() { if(actionQueue.isNotEmpty()) { actionQueue.clear() } layers.forEach { it.forEach { if (it != null) { pooledItems.add(it) } } it.clear() } } // TODO: Create a way to render without having the internal code call a handler. // This would be something like: resolve -> Iterable<ActionError> and render -> Iterable<DrawData> // Iterable could be used in any standard for loop, and it would allow the user to "pull" the errors // and data needed to render instead of having the code be a framework-style "I'll call you maybe" // kind of thing. This leaves the user in more control instead of having the framework infest their // code in ways that are much harder to detangle or wrap in a layer or something. It's pretty much // always preferable to leave the caller in control. // TODO: Change function parameter to be something that can handle multiple callbacks? // So it would have something like: render, actionFail, etc. // This would allow for an action such as movement to fail and communicate it back to the calling code. // Movement cannot be immediately checked, and has to be done via a deferred resolve due to there being // multiple things that could possibly be moving in a single frame. Resolving that will require something // slightly more sophisticated than just checking the moved-to square(s) for something inside them. (at least // I believe that to be the case, resolution of actions is yet to be implemented) // Is there a better way to handle this situation? fun render(handler: RenderHandler) { resolveActions(handler) val charW = windowWidth / charactersDrawnX val charH = windowHeight / charactersDrawnY layers.forEach { for (x in cameraX..charactersDrawnX-1) { for (y in cameraY..charactersDrawnY-1) { it[get1d(x, y, width)]?.let { handler.render(reusableDrawData(it, charW, charH)) } } } } } private fun resolveActions(handler: RenderHandler) { // TODO: Implement resolving queued actions for a screen. // What order do things need to be resolved in to make this work correctly? // What special considerations about actions need to be taken into account? // e.g.: If something is moved, it should be undone if it collides with something? // TODO: Apply all actions to a "virtual" screen and resolve anything odd by comparing actual vs virtual? // Sorta like double-buffering a screen, but instead we're doing it to a layer of characters. This could // potentially be used to let every action immediately go through, and then resolve the end state of everything // happening at once. (e.g.: two things move, and it can be inferred based on their new positions that they // went "through" each other, necessitating a collision) // Would it be better to do that, or would it indeed be better to look at the actual actions that have been // queued and resolve from those? // I'll leave this around for now, but the first attempt at resolving actions will be by just using the // queue instead of something potentially fancier like the virtual screen idea. for (action in actionQueue) { if (!action.attempt(this)) { handler.actionFailure(ActionFailure.Movement(CharDrawData(), CharDrawData())) } } actionQueue.clear() } } interface RenderHandler { fun render(data: CharDrawData): Unit fun actionFailure(failure: ActionFailure): Unit } class RenderHandlerAdapter : RenderHandler { override fun render(data: CharDrawData) { } override fun actionFailure(failure: ActionFailure) { } } class PlacedItem(private val screen: AsciiScreen) { lateinit internal var item: ItemData internal var layer: Int = -1 var x: Int get() = item.x set(v) = moveAbsolute(x = v) var y: Int get() = item.y set(v) = moveAbsolute(y = v) var w: Int get() = item.w set(v) = resize(dw = v - w) var h: Int get() = item.h set(v) = resize(dh = v - h) fun move(dx: Int = 0, dy: Int = 0) { screen.actionQueue.add(QueuedAction.MovementAction(item, layer, dx, dy)) } fun moveAbsolute(x: Int = item.x, y: Int = item.y) { screen.actionQueue.add(QueuedAction.MovementAction(item, layer, x, y, absolute = true)) } fun resize(dw: Int = 0, dh: Int = 0) { screen.actionQueue.add(QueuedAction.ResizeAction(item, layer, dw, dh)) } fun resizeAbsolute(w: Int = item.w, h: Int = item.h) { screen.actionQueue.add(QueuedAction.ResizeAction(item, layer, w, h, absolute = true)) } fun remove() { screen.actionQueue.add(QueuedAction.RemoveAction(item, layer)) } } class CharDrawData() { internal constructor(item: ItemData) : this() { this(item, 1, 1) } var c: Char = ' ' internal set var x: Int = 0 internal set var y: Int = 0 internal set var w: Int = 0 internal set var h: Int = 0 internal set var fg: Color = Color.WHITE internal set var bg: Color = Color.BLACK internal set var borders: Array<Line2D> = arrayOf() get() = field.copyOf() // Ensure internal array isn't mucked about with. internal set var userData: Any? = null internal set internal operator fun invoke(item: ItemData, w: Int, h: Int): CharDrawData { return this(item.toDraw, item.x, item.y, w * item.w, h * item.h, item.fg, item.bg, arrayOf<Line2D>(), item.userData) } internal operator fun invoke(newC: Char, newX: Int, newY: Int, newW: Int, newH: Int, newFg: Color, newBg: Color, newBorders: Array<Line2D>, newUserData: Any?): CharDrawData { c = newC x = newX y = newY w = newW h = newH fg = newFg bg = newBg borders = newBorders userData = newUserData return this } } // TODO: Put code into place that allows other code to react when movement fails. // TODO: Inform external code of various things that have happened (such as failing movement or placement) so it can react to it. // This is necessary for various things, such as if movement fails due to colliding with another item, then external // code will want to resolve that in some way. Such as dealing damage between two entities if one of them is the player // and the other is a monster. Placing would also be useful to be informed about, so that if doing so fails, it gets // a chance to put something into another location. (e.g.: if trying to generate a room or an item needs a location to // be placed, but has to do a couple iterations to figure out where it needs to be placed) internal sealed class QueuedAction { private var hasRun = false fun invoke(screen: AsciiScreen) { if(hasRun) { throw IllegalStateException("Cannot run an action that has already been run.") } run(screen) hasRun = true } fun undo(screen: AsciiScreen) { if(!hasRun) { throw IllegalStateException("Cannot undo an action that has not been run.") } undoInternal(screen) // We can run an action again after it has been undone, since it will be like it never happened. // Hopefully this doesn't have to be made use of very often. // But I could see a use in backing a change out temporarily for some reason. hasRun = false } abstract fun attempt(screen: AsciiScreen): Boolean abstract internal fun run(screen: AsciiScreen) abstract fun undoInternal(screen: AsciiScreen) abstract val pre: CharDrawData abstract val post: CharDrawData /** * Place a character into a layer. */ class PlacementAction(private val item: ItemData, private val layer: Int) : QueuedAction() { var previousItems: Array<ItemData?>? = null override fun attempt(screen: AsciiScreen): Boolean { val placeLayer = screen.layers[layer] // Make sure to check every position over all the width/height of the character when checking if something // can be placed. for (w in 0..item.w-1) { for (h in 0..item.h-1) { val loc = get1d(item.x + w, item.y + h, screen.width) // Make sure the location is within bounds of the field. if (placeLayer.size <= loc) { return false } // If something exists in the spot we're attempting to place something into, we can't place // another thing there. placeLayer[loc] ?: return false } } return true } override fun run(screen: AsciiScreen) { val placeLayer = screen.layers[layer] val newPreviousItemsArray = Array<ItemData?>(item.w * item.h) { null } previousItems = newPreviousItemsArray for (w in 0..item.w-1) { for (h in 0..item.h-1) { val loc = get1d(item.x + w, item.y + h, screen.width) newPreviousItemsArray[get1d(w, h, item.w)] = placeLayer[loc] placeLayer[loc] = item } } } override fun undoInternal(screen: AsciiScreen) { val placeLayer = screen.layers[layer] val previousItemsArray = previousItems ?: throw IllegalStateException("Cannot undo placement because previous items is somehow null.") for (w in 0..item.w-1) { for (h in 0..item.h-1) { placeLayer[get1d(item.x + w, item.y + h, screen.width)] = previousItemsArray[get1d(w, h, item.w)] } } } override val pre: CharDrawData get() = CharDrawData(item) override val post: CharDrawData get() = CharDrawData(item) } /** * Remove a character from a layer. */ class RemoveAction(private val item: ItemData, private val layer: Int) : QueuedAction() { override fun attempt(screen: AsciiScreen): Boolean { // TODO: Use the location of the item as a place to look for it in the layer return screen.layers[layer].any { it === item } } override fun run(screen: AsciiScreen) { var found = false screen.layers[layer].replaceAll { if (it === item) { found = true; null } else it } if(screen.debug && !found) { throw IllegalStateException("Cannot remove '$item' which does not exist.") } } override fun undoInternal(screen: AsciiScreen) { // TODO: Refactor placement's run method into something outside the object so we don't have to allocate one here? // Until then, hopefully the JVM will at least mostly optimize this. QueuedAction.PlacementAction(item, layer).run(screen) } override val pre: CharDrawData get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. override val post: CharDrawData get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. } class DrawableChangeAction(private val item: ItemData, private val newDraw: Char, private val oldDraw: Char) : QueuedAction() { override val pre: CharDrawData get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. override val post: CharDrawData get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. override fun attempt(screen: AsciiScreen): Boolean { return true } override fun run(screen: AsciiScreen) { item.toDraw = newDraw } override fun undoInternal(screen: AsciiScreen) { item.toDraw = oldDraw } } class MovementAction(private val item: ItemData, private val layer: Int, private val dx: Int, private val dy: Int, private val absolute: Boolean = false) : QueuedAction() { override val pre: CharDrawData get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. override val post: CharDrawData get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. val remove = RemoveAction(item, layer) val place = PlacementAction(item, layer) val oldX = item.x val oldY = item.y val newX = if (absolute) dx else item.x + dx val newY = if (absolute) dy else item.y + dy private fun setItemPosition() { item.x = newX item.y = newY } private fun resetItemPosition() { item.x = oldX item.y = oldY } override fun attempt(screen: AsciiScreen): Boolean { setItemPosition() return remove.attempt(screen) && place.attempt(screen) } override fun undoInternal(screen: AsciiScreen) { // Always make sure the position is in a consistent state before running any actions. We want to ensure // that any oddities in when the various methods are called does not change how the action is run. setItemPosition() place.undoInternal(screen) resetItemPosition() remove.undoInternal(screen) } override fun run(screen: AsciiScreen) { resetItemPosition() remove.run(screen) setItemPosition() place.run(screen) } } /** * Resizes an item. * * When an item is becoming bigger, it will always attempt to center the newly-sized item on the original * center. If it cannot be perfectly centered (e.g.: 1x1 to 2x2 cannot be perfectly centered, but a * 1x1 to 3x3 can be), it will expand the size right and down. So for example: * * 1x1 2x2 * .#. -> .## * ... .## * * 1x1 3x3 * ... ### * .#. -> ### * ... ### * * When an item is becoming smaller, it will do the same as larger except in reverse. For example: * * 2x2 1x2 * .## -> .#. * .## .#. * * 2x2 2x1 * .## -> .## * .## ... * * 3x3 2x2 * ### ##. * ### -> ##. * ### ... * * 3x3 1x1 * ### ... * ### -> .#. * ### ... * * This action can fail if it attempts to resize an item such that it attempts to replace another item * in the grid. When it's being resized, in essence the item is having itself placed in more/less spots * in the layer. */ class ResizeAction(private val item: ItemData, private val layer: Int, private val dw: Int, private val dh: Int, private val absolute: Boolean = false): QueuedAction() { override val pre: CharDrawData get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. override val post: CharDrawData get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. val remove = RemoveAction(item, layer) val place = PlacementAction(item, layer) val newW = if (absolute) dw else item.w + dw val newH = if (absolute) dh else item.h + dh val oldW = item.w val oldH = item.h val oldX = item.x val oldY = item.y val newX = oldX + (oldW - newW) / 2 val newY = oldY + (oldH - newH) / 2 private fun setItemPosition() { item.x = newX item.y = newY item.w = newW item.h = newH } private fun resetItemPosition() { item.x = oldX item.y = oldY item.w = oldW item.h = oldH } override fun attempt(screen: AsciiScreen): Boolean { resetItemPosition() val removeAttempt = remove.attempt(screen) setItemPosition() return place.attempt(screen) && removeAttempt } override fun undoInternal(screen: AsciiScreen) { setItemPosition() place.undoInternal(screen) resetItemPosition() remove.undoInternal(screen) } override fun run(screen: AsciiScreen) { resetItemPosition() remove.run(screen) setItemPosition() place.run(screen) } } } sealed class ActionFailure { class Movement(val pre: CharDrawData, val post: CharDrawData) : ActionFailure() } data class BorderLine(val x1: Int, val y1: Int, val x2: Int, val y2: Int) internal data class BorderData(val line: BorderLine, val color: Color) internal class ItemData(var toDraw: Char, var x: Int, var y: Int, var w: Int, var h: Int, var fg: Color, var bg: Color, var userData: Any?) { var blinkText = false var blinkTextRate = TEXT_BLINKING_DELAY_DEFAULT var drawBorder = false var borders: MutableList<BorderData>? = null var autoFancyWall = false var preferSingleLine = false var preferDoubleLine = false var fancyWallOnlyBorder = false var fancyWallIncludeBorder = false constructor() : this(' ', -1, -1, -1, -1, Color.WHITE, Color.BLACK, null) {} operator fun invoke(newDraw: Char, newX: Int, newY: Int, newW: Int, newH: Int, newFg: Color, newBg: Color, newUserData: Any?, attributes: Int, attributeArgs: Map<String, Any?>, debug: Boolean): ItemData { toDraw = newDraw x = newX y = newY w = newW h = newH fg = newFg bg = newBg userData = newUserData buildAttributes(attributes, attributeArgs, debug) return this } private fun buildAttributes(attributes: Int, attributeArgs: Map<String, Any?>, debug: Boolean) { if (attributes and TEXT_BLINKING == TEXT_BLINKING) { blinkText = true val rate = attributeArgs[TEXT_BLINKING_DELAY_ARG_NAME] blinkTextRate = if (rate is Int) rate else null ?: blinkTextRate } if (attributes bitSet TEXT_BORDER_LEFT) { addBorder(attributeArgs, TEXT_BORDER_COLOR_LEFT_ARG_NAME, BorderLine(x, y, x, y + h), debug) } if (attributes bitSet TEXT_BORDER_RIGHT) { addBorder(attributeArgs, TEXT_BORDER_COLOR_RIGHT_ARG_NAME, BorderLine(x + w, y, x + w, y + h), debug) } if (attributes bitSet TEXT_BORDER_TOP) { addBorder(attributeArgs, TEXT_BORDER_COLOR_TOP_ARG_NAME, BorderLine(x, y, x + w, y), debug) } if (attributes bitSet TEXT_BORDER_BOTTOM) { addBorder(attributeArgs, TEXT_BORDER_COLOR_BOTTOM_ARG_NAME, BorderLine(x, y + h, x + w, y + h), debug) } if (attributes bitSet TEXT_AUTO_FANCY_WALL) { autoFancyWall = true val single = attributeArgs[TEXT_FANCY_WALL_PREFER_SINGLE_ARG_NAME] var double = attributeArgs[TEXT_FANCY_WALL_PREFER_DOUBLE_ARG_NAME] var onlyBorder = attributeArgs[TEXT_FANCY_WALL_ONLY_BORDERS_ARG_NAME] var includeBorder = attributeArgs[TEXT_FANCY_WALL_INCLUDE_BORDERS_ARG_NAME] if (debug) { if (single != null && single !is Boolean) { throw IllegalArgumentException("Got a single wall preference argument that was not a boolean: $single") } if (double != null && double !is Boolean) { throw IllegalArgumentException("Got a double wall preference argument that was not a boolean: $double") } if (onlyBorder != null && onlyBorder !is Boolean) { throw IllegalArgumentException("Got an only border argument that was not a boolean: $onlyBorder") } if (includeBorder != null && includeBorder !is Boolean) { throw IllegalArgumentException("Got an include border argument that was not a boolean: $includeBorder") } if (single != null && double != null && single is Boolean && double is Boolean) { if (single && double) { throw IllegalArgumentException("Cannot prefer both single line and double line fancy walls.") } } if (onlyBorder != null && includeBorder != null && onlyBorder is Boolean && includeBorder is Boolean) { if (onlyBorder && includeBorder) { throw IllegalArgumentException("Cannot have fancy walls be only borders and include borders.") } } } if (single != null && single is Boolean && single) { preferSingleLine = single } else if (double != null && double is Boolean && double) { preferDoubleLine = double } if (onlyBorder != null && onlyBorder is Boolean && onlyBorder) { fancyWallOnlyBorder = onlyBorder } else if (includeBorder != null && includeBorder is Boolean && includeBorder) { fancyWallIncludeBorder = includeBorder } } } private fun addBorder(attributeArgs: Map<String, Any?>, arg: String, line: BorderLine, debug: Boolean) { if (debug) { if (attributeArgs[arg] != null && attributeArgs[arg] !is Color) { throw IllegalArgumentException("Got an argument for border '$arg' that was non-null and not a color: ${attributeArgs[arg]}") } if (attributeArgs[TEXT_BORDER_COLOR_ALL_ARG_NAME] != null && attributeArgs[TEXT_BORDER_COLOR_ALL_ARG_NAME] !is Color) { throw IllegalArgumentException("Got an argument for border 'ALL' that was non-null and not a color: ${attributeArgs[TEXT_BORDER_COLOR_ALL_ARG_NAME]}") } } if (borders == null) { borders = ArrayList(4) } drawBorder = true val color = attributeArgs[arg] ?: attributeArgs[TEXT_BORDER_COLOR_ALL_ARG_NAME] borders?.add(BorderData(line, if (color is Color) color else null ?: TEXT_BORDER_COLOR_DEFAULT)) } }
mit
98e1484f5b4cff0ea031e8fc1f691d84
43.579295
166
0.613346
3.983271
false
false
false
false
sepatel/tekniq
tekniq-jdbc/src/main/kotlin/io/tekniq/jdbc/TqConnectionExt.kt
1
3742
@file:Suppress("unused", "NOTHING_TO_INLINE") package io.tekniq.jdbc import java.sql.* import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.ZonedDateTime import java.util.* import java.util.Date import javax.sql.rowset.CachedRowSet import javax.sql.rowset.RowSetProvider inline fun Connection.select(sql: String, vararg params: Any?): CachedRowSet = prepareStatement(sql) .also { applyParams(it, *params) } .use { stmt -> stmt.executeQuery().use { rs -> RowSetProvider.newFactory() .createCachedRowSet() .also { it.populate(rs) } } } inline fun Connection.select(sql: String, vararg params: Any?, action: ResultSet.() -> Unit) = prepareStatement(sql) .also { applyParams(it, *params) } .use { stmt -> stmt.executeQuery().use { rs -> while (rs.next()) { action.invoke(rs) } } } inline fun <T> Connection.select(sql: String, vararg params: Any?, action: ResultSet.() -> T): List<T> { val list = mutableListOf<T>() prepareStatement(sql) .also { applyParams(it, *params) } .use { stmt -> stmt.executeQuery().use { rs -> while (rs.next()) { list.add(action.invoke(rs)) } } } return list } inline fun <T> Connection.selectOne(sql: String, vararg params: Any?, action: ResultSet.() -> T): T? { var value: T? = null prepareStatement(sql) .also { applyParams(it, *params) } .use { stmt -> params.forEachIndexed { i, any -> stmt.setObject(i + 1, any) } stmt.executeQuery().use { rs -> if (rs.next()) { value = action.invoke(rs) } } } return value } fun Connection.delete(sql: String, vararg params: Any?): Int = update(sql, *params) fun Connection.insert(sql: String, vararg params: Any?): Int = update(sql, *params) fun Connection.update(sql: String, vararg params: Any?): Int = prepareStatement(sql) .also { applyParams(it, *params) } .use { it.executeUpdate() } fun Connection.insertReturnKey(sql: String, vararg params: Any?): String? = prepareStatement(sql, Statement.RETURN_GENERATED_KEYS) .also { applyParams(it, *params) } .use { stmt -> val result = stmt.executeUpdate() var answer: String? = null if (result == 1) { stmt.generatedKeys.use { rs -> if (rs.next()) { answer = rs.getString(1) } } } return answer } inline fun <T> Connection.call(sql: String, action: CallableStatement.() -> T): T? = prepareCall(sql).use { action.invoke(it) } fun applyParams(stmt: PreparedStatement, vararg params: Any?) = stmt.also { params.forEachIndexed { i, any -> when (any) { is Time -> it.setTime(i + 1, any) // is also a java.util.Date so treat naturally instead is LocalTime -> it.setTime(i + 1, Time.valueOf(any)) is java.sql.Date -> it.setDate(i + 1, any) // is also a java.util.Date so treat naturally instead is LocalDate -> it.setDate(i + 1, java.sql.Date.valueOf(any)) is ZonedDateTime -> it.setTimestamp(i + 1, Timestamp(any.toInstant().toEpochMilli())) is LocalDateTime -> it.setTimestamp(i + 1, Timestamp.valueOf(any)) is Date -> it.setTimestamp(i + 1, Timestamp(any.time)) is Calendar -> it.setTimestamp(i + 1, Timestamp(any.timeInMillis)) else -> it.setObject(i + 1, any) } } }
mit
b3f2e4bad94eef4d68c5f690494489f0
34.980769
116
0.571619
3.918325
false
false
false
false
quarkusio/quarkus
integration-tests/resteasy-reactive-kotlin/standard/src/main/kotlin/io/quarkus/it/resteasy/reactive/kotlin/ScheduledEndpoint.kt
1
877
package io.quarkus.it.resteasy.reactive.kotlin import io.quarkus.scheduler.Scheduled import io.quarkus.scheduler.ScheduledExecution import kotlinx.coroutines.delay import java.util.concurrent.atomic.AtomicInteger import javax.ws.rs.GET import javax.ws.rs.Path import javax.ws.rs.core.Response @Path("scheduled") class ScheduledEndpoint { private val num1 = AtomicInteger(0) private val num2 = AtomicInteger(0) @Scheduled(every = "0.5s") suspend fun scheduled1() { delay(100) num1.compareAndSet(0, 1) } @Scheduled(every = "0.5s") suspend fun scheduled2(scheduledExecution: ScheduledExecution) { delay(100) num2.compareAndSet(0, 1) } @Path("num1") @GET fun num1() = Response.status(200 + num1.get()).build() @Path("num2") @GET fun num2() = Response.status(200 + num2.get()).build() }
apache-2.0
33829f8dd6261c71f1d08d670643c306
23.361111
68
0.68301
3.494024
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/ext/RsArrayType.kt
2
725
/* * 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 org.rust.lang.core.psi.RsArrayType import org.rust.lang.core.psi.RsExpr import org.rust.lang.core.psi.RsLitExpr import org.rust.lang.core.types.ty.TyInteger val RsArrayType.arraySize: Int? get() { val stub = stub if (stub != null) { return if (stub.arraySize == -1) null else stub.arraySize } return calculateArraySize(expr) } // TODO: support constants and compile time expressions fun calculateArraySize(expr: RsExpr?): Int? = (expr as? RsLitExpr) ?.integerLiteral ?.text ?.removeSuffix(TyInteger.Kind.usize.name) ?.toIntOrNull()
mit
2ddb96d4eee18a60b76be3b56b5a04cc
26.884615
69
0.710345
3.502415
false
false
false
false
backpaper0/syobotsum
core/src/syobotsum/actor/BlockResult.kt
1
1062
package syobotsum.actor import syobotsum.actor.Block.BlockType import com.badlogic.gdx.scenes.scene2d.Group import com.badlogic.gdx.scenes.scene2d.ui.Image import com.badlogic.gdx.scenes.scene2d.ui.Label import com.badlogic.gdx.scenes.scene2d.ui.Skin import com.badlogic.gdx.utils.Align class BlockResult(val skin: Skin, val styleName: String, val max: Block?, val blockType: BlockType) : Group() { init { var value = 0 var b: Block? = max while (b != null) { if (b.blockType == blockType) { value = value + 1 } b = b.under } val image = Image(skin, styleName) image.setPosition(0f, 0f) addActor(image) val format = " × %1$02d = %2$03d" val s = String.format(format, value, blockType.calc(value)) val text = Label(s, skin, "score") text.setPosition(image.getX(Align.right), image.height / 2f, Align.left or Align.center) addActor(text) setSize(image.width + text.width, image.height) } }
apache-2.0
7d5c583d07bd650d3925d3f79f96087c
29.257143
111
0.622285
3.483553
false
false
false
false
ShevaBrothers/easylib
src/core/trees/main/BinarySearchTree.kt
1
7743
/** * Implementation of BinarySearchTree Data Structure * * @author Yurii Yatsenko (@kyparus). * @since 0.1 * @param E type of elements which represents the data. */ class BinarySearchTree<E : Comparable<E>> : AbstractTree<E> { /** * Inner misc class for representation of container with data and children nodes. * * @author Yurii Yatsenko (@kyparus) * @since 0.1 * @param value valuable data object * @see BinarySearchTree . * @constructor creates object with value. */ internal class BSTNode<T>(val value: T) : Serializable { override fun serialize(): String { return "" } /** * Left and right children of the node. * * @author Yurii Yatsenko (@kyparus) * @since 0.1 */ var left: BSTNode<T>? = null var right: BSTNode<T>? = null } /** * Root of the tree. * * @author Yurii Yatsenko (@kyparus) * @since 0.1 */ private var root: BSTNode<E>? = null /** * Number of nodes in the tree * * @author Yurii Yatsenko (@kyparus) * @since 0.1 */ private var nodesNumber = 0 /** * @author Yurii Yatsenko (@kyparus) * @since 0.1 * @return number of nodes in the tree */ override var size: Int = 0 get() = nodesNumber /** * Remove all objects from collection. * * @author Yurii Yatsenko (@kyparus) * @since 0.1 * @see BinarySearchTree . */ override fun clear() { clear(root) root = null nodesNumber = 0 } private fun clear(node: BSTNode<E>?) { if (node != null) { clear(node.left) clear(node.right) node.left = null node.right = null } } override val isEmpty: Boolean get() = root == null /** * Function to insert element to the tree * * @author Yurii Yatsenko (@kyparus) * @since 0.1 * @param value Element to insert in this collection. * @see BinarySearchTree */ override fun insert(value: E) { val newNode = BSTNode(value) if (root == null) { root = newNode nodesNumber++ return } var current = root var parent: BSTNode<E>? = null while (true) { parent = current if (value < current!!.value) { current = current.left if (current == null) { parent!!.left = newNode nodesNumber++ return } } else { current = current.right if (current == null) { parent!!.right = newNode nodesNumber++ return } } } } /** * @author Yurii Yatsenko (@kyparus) * @since 0.1 * @param value Element to insert in this collection. * @see BinarySearchTree * @return 'true' if value is in the collection, otherwise 'false' */ override fun search(value: E): Boolean { var current = root while (current != null) { if (current.value == value) { return true } else if (current.value > value) { current = current.left } else { current = current.right } } return false } /** * Removes element by value from collection * * @author Yurii Yatsenko (@kyparus) * @since 0.1 * @param value Element to delete from this collection. * @see BinarySearchTree * @return 'true' if it was deleted, otherwise 'false' */ fun remove(value: E): Boolean { if(root == null) return false var parent = root var current = root var isLeftChild = false while (current?.value != value) { parent = current if (current!!.value > value) { isLeftChild = true current = current.left } else { isLeftChild = false current = current.right } if (current == null) { return false } } //if we are here that means we have found the node //Case 1: if node to be deleted has no children if (current?.left == null && current?.right == null) { if (current == root) { root = null; } if (isLeftChild == true) { parent?.left = null; } else { parent?.right = null; } } //Case 2 : if node to be deleted has only one child else if (current.right == null) { if (current == root) { root = current.left; } else if (isLeftChild) { parent?.left = current.left; } else { parent?.right = current.left; } } else if (current.left == null) { if (current == root) { root = current.right; } else if (isLeftChild) { parent?.left = current.right; } else { parent?.right = current.right; } } // Case 2 : if node to be deleted has two children else if (current.left != null && current.right != null) { //now we have found the minimum element in the right sub tree val successor = getSuccessor (current); if (current == root) { root = successor; } else if (isLeftChild) { parent?.left = successor; } else { parent?.right = successor; } successor?.left = current.left; } nodesNumber-- return true } /** * Get next node in ascending order * * @author Yurii Yatsenko (@kyparus) * @since 0.1 * @see BinarySearchTree */ private fun getSuccessor(node: BSTNode<E>?) : BSTNode<E>? { var successsor: BSTNode<E>? = null var successsorParent: BSTNode<E>? = null var current = node?.right while (current != null) { successsorParent = successsor successsor = current current = current!!.left } //check if successor has the right child, it cannot have left child for sure // if it does have the right child, add it to the left of successorParent. // successorParent if (successsor !== node?.right) { successsorParent!!.left = successsor!!.right successsor!!.right = node?.right } return successsor } /** * getMin/Max funcs to get min/max values from collection * * @author Yurii Yatsenko (@kyparus) * @since 0.1 * @see BinarySearchTree * @return min/max value */ fun getMin() : E? { return getEdgeValue(true) } fun getMax() : E? { return getEdgeValue(false) } /** * @author Yurii Yatsenko (@kyparus) * @since 0.1 * @param min defines what we want to get * @see BinarySearchTree * @return min value if param 'min' is true otherwise max value */ private fun getEdgeValue(min : Boolean) : E? { var current = root var lastValue = root?.value while (current != null) { lastValue = current.value if (min) current = current.left else current = current.right } return lastValue } }
mit
76a90fa3f6a8f733990b167339e6df28
26.657143
85
0.496965
4.347558
false
false
false
false
facebook/react-native
packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/ProjectUtilsTest.kt
1
4894
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.utils import com.facebook.react.TestReactExtension import com.facebook.react.model.ModelCodegenConfig import com.facebook.react.model.ModelPackageJson import com.facebook.react.tests.createProject import com.facebook.react.utils.ProjectUtils.isHermesEnabled import com.facebook.react.utils.ProjectUtils.isNewArchEnabled import com.facebook.react.utils.ProjectUtils.needsCodegenFromPackageJson import java.io.File import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder class ProjectUtilsTest { @get:Rule val tempFolder = TemporaryFolder() @Test fun isNewArchEnabled_returnsFalseByDefault() { assertFalse(createProject().isNewArchEnabled) } @Test fun isNewArchEnabled_withDisabled_returnsFalse() { val project = createProject() project.extensions.extraProperties.set("newArchEnabled", "false") assertFalse(project.isNewArchEnabled) } @Test fun isNewArchEnabled_withEnabled_returnsTrue() { val project = createProject() project.extensions.extraProperties.set("newArchEnabled", "true") assertTrue(project.isNewArchEnabled) } @Test fun isNewArchEnabled_withInvalid_returnsFalse() { val project = createProject() project.extensions.extraProperties.set("newArchEnabled", "¯\\_(ツ)_/¯") assertFalse(project.isNewArchEnabled) } @Test fun isHermesEnabled_returnsTrueByDefault() { assertTrue(createProject().isHermesEnabled) } @Test fun isNewArchEnabled_withDisabledViaProperty_returnsFalse() { val project = createProject() project.extensions.extraProperties.set("hermesEnabled", "false") assertFalse(project.isHermesEnabled) } @Test fun isHermesEnabled_withEnabledViaProperty_returnsTrue() { val project = createProject() project.extensions.extraProperties.set("hermesEnabled", "true") assertTrue(project.isHermesEnabled) } @Test fun isHermesEnabled_withInvalidViaProperty_returnsTrue() { val project = createProject() project.extensions.extraProperties.set("hermesEnabled", "¯\\_(ツ)_/¯") assertTrue(project.isHermesEnabled) } @Test fun isHermesEnabled_withDisabledViaExt_returnsFalse() { val project = createProject() val extMap = mapOf("enableHermes" to false) project.extensions.extraProperties.set("react", extMap) assertFalse(project.isHermesEnabled) } @Test fun isHermesEnabled_withEnabledViaExt_returnsTrue() { val project = createProject() val extMap = mapOf("enableHermes" to true) project.extensions.extraProperties.set("react", extMap) assertTrue(project.isHermesEnabled) } @Test fun isHermesEnabled_withDisabledViaExtAsString_returnsFalse() { val project = createProject() val extMap = mapOf("enableHermes" to "false") project.extensions.extraProperties.set("react", extMap) assertFalse(project.isHermesEnabled) } @Test fun isHermesEnabled_withInvalidViaExt_returnsTrue() { val project = createProject() val extMap = mapOf("enableHermes" to "¯\\_(ツ)_/¯") project.extensions.extraProperties.set("react", extMap) assertTrue(project.isHermesEnabled) } @Test fun needsCodegenFromPackageJson_withCodegenConfigInPackageJson_returnsTrue() { val project = createProject() val extension = TestReactExtension(project) File(tempFolder.root, "package.json").apply { writeText( // language=json """ { "name": "a-library", "codegenConfig": {} } """ .trimIndent()) } extension.root.set(tempFolder.root) assertTrue(project.needsCodegenFromPackageJson(extension)) } @Test fun needsCodegenFromPackageJson_withMissingCodegenConfigInPackageJson_returnsFalse() { val project = createProject() val extension = TestReactExtension(project) File(tempFolder.root, "package.json").apply { writeText( // language=json """ { "name": "a-library" } """ .trimIndent()) } extension.root.set(tempFolder.root) assertFalse(project.needsCodegenFromPackageJson(extension)) } @Test fun needsCodegenFromPackageJson_withCodegenConfigInModel_returnsTrue() { val project = createProject() val model = ModelPackageJson(ModelCodegenConfig(null, null, null, null)) assertTrue(project.needsCodegenFromPackageJson(model)) } @Test fun needsCodegenFromPackageJson_withMissingCodegenConfigInModel_returnsFalse() { val project = createProject() val model = ModelPackageJson(null) assertFalse(project.needsCodegenFromPackageJson(model)) } }
mit
6c466e827f0fc64fc53ad3aa41df0cd5
28.768293
88
0.729414
4.394239
false
true
false
false
matkoniecz/StreetComplete
app/src/test/java/de/westnordost/streetcomplete/data/osmnotes/NotesDownloaderTest.kt
1
870
package de.westnordost.streetcomplete.data.osmnotes import de.westnordost.streetcomplete.testutils.* import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import org.mockito.Mockito.anyInt import org.mockito.Mockito.verify class NotesDownloaderTest { private lateinit var noteController: NoteController private lateinit var notesApi: NotesApi @Before fun setUp() { noteController = mock() notesApi = mock() } @Test fun `calls controller with all notes coming from the notes api`() = runBlocking { val note1 = note() val bbox = bbox() on(notesApi.getAll(any(), anyInt(), anyInt())).thenReturn(listOf(note1)) val dl = NotesDownloader(notesApi, noteController) dl.download(bbox) verify(noteController).putAllForBBox(eq(bbox), eq(listOf(note1))) } }
gpl-3.0
ea8b0331beb87e6fa8872e27f98a7a7c
29
91
0.706897
4.285714
false
true
false
false
pdvrieze/ProcessManager
PE-common/src/jsMain/kotlin/nl/adaptivity/process/processModel/XPathHolder.kt
1
11701
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.processModel import kotlinx.browser.document import nl.adaptivity.process.engine.ProcessData import nl.adaptivity.process.util.Constants import nl.adaptivity.util.MyGatheringNamespaceContext import nl.adaptivity.util.multiplatform.assert import nl.adaptivity.util.xml.CombinedNamespaceContext import nl.adaptivity.xmlutil.util.CombiningNamespaceContext import nl.adaptivity.xmlutil.util.CompactFragment import nl.adaptivity.xmlutil.* import org.w3c.dom.Document import org.w3c.dom.DocumentFragment import org.w3c.dom.Node actual abstract class XPathHolder : XMLContainer { /** * @see nl.adaptivity.process.processModel.IXmlResultType#setName(java.lang.String) */ actual var _name: String? = null // @Volatile private var path: XPathExpression? = null // This is merely a cache. private var pathString: String? = null /* // TODO support a functionresolver @Volatile private var path: XPathExpression? = null get() { field?.let { return it } return if (pathString == null) { return SELF_PATH } else { XPathFactory.newInstance().newXPath().apply { if (originalNSContext != null) { namespaceContext = SimpleNamespaceContext.from(originalNSContext) } }.compile(pathString) }.apply { field = this } } val xPath: XPathExpression? get() = path */ actual constructor() : super() actual constructor( name: String?, path: String?, content: CharArray?, originalNSContext: Iterable<Namespace> ) : super(originalNSContext, content ?: CharArray(0)) { _name = name setPath(originalNSContext, path) } actual fun getName() = _name ?: throw NullPointerException("Name not set") actual fun setName(value: String) { _name = value } actual fun getPath(): String? { return pathString } actual fun setPath(namespaceContext: Iterable<Namespace>, value: String?) { if (pathString != null && pathString == value) { return } pathString = value updateNamespaceContext(namespaceContext) assert(value == null) } @OptIn(XmlUtilInternal::class) actual override fun deserializeChildren(reader: XmlReader) { super.deserializeChildren(reader) val namespaces = mutableMapOf<String, String>() val gatheringNamespaceContext = CombinedNamespaceContext( SimpleNamespaceContext.from(originalNSContext), MyGatheringNamespaceContext(namespaces, reader.namespaceContext) ) visitNamespaces(gatheringNamespaceContext) if (namespaces.isNotEmpty()) { addNamespaceContext(SimpleNamespaceContext(namespaces)) } } @OptIn(XmlUtilInternal::class) actual override fun serializeAttributes(out: XmlWriter) { super.serializeAttributes(out) if (pathString != null) { val namepaces = mutableMapOf<String, String>() // Have a namespace that gathers those namespaces that are not known already in the outer context val referenceContext = out.namespaceContext // TODO streamline this, the right context should not require the filtering on the output context later. val nsc = MyGatheringNamespaceContext(namepaces, referenceContext, SimpleNamespaceContext.from(originalNSContext)) visitXpathUsedPrefixes(pathString, nsc) for ((key, value) in namepaces) { if (value != referenceContext.getNamespaceURI(key)) { out.namespaceAttr(key, value) } } out.attribute(null, "xpath", null, pathString!!) } out.writeAttribute("name", _name) } actual override fun visitNamespaces(baseContext: NamespaceContext) { if (pathString != null) { visitXpathUsedPrefixes(pathString, baseContext) } super.visitNamespaces(baseContext) } actual override fun visitNamesInAttributeValue( referenceContext: NamespaceContext, owner: QName, attributeName: QName, attributeValue: CharSequence ) { if (Constants.MODIFY_NS_STR == owner.getNamespaceURI() && (XMLConstants.NULL_NS_URI == attributeName.getNamespaceURI() || XMLConstants.DEFAULT_NS_PREFIX == attributeName.getPrefix()) && "xpath" == attributeName.getLocalPart()) { visitXpathUsedPrefixes(attributeValue, referenceContext) } } private val namespaceResolver: NamespaceResolver = { prefix -> namespaces.getNamespaceURI(prefix) } fun applyData(payload: Node?): ProcessData = pathString.let { p -> when (p) { null -> ProcessData(_name!!, payload?.let { CompactFragment(it) } ?: CompactFragment("")) else -> { val realPayload = when (payload) { null -> { document.implementation.createDocument(null, "dummy").createDocumentFragment() } else -> payload } val result = realPayload.ownerDocument!!.evaluate( p, realPayload, namespaceResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE ) ProcessData(_name!!, CompactFragment(result.toDocumentFragment())) } } } actual override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class.js != other::class.js) return false if (!super.equals(other)) return false other as XPathHolder if (_name != other._name) return false if (pathString != other.pathString) return false return true } actual override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + (_name?.hashCode() ?: 0) result = 31 * result + (pathString?.hashCode() ?: 0) return result } } internal actual fun visitXpathUsedPrefixes(path: CharSequence?, namespaceContext: NamespaceContext) { if (path != null && path.isNotEmpty()) { try { val d = document.implementation.createDocument(null, "bar") // d.createExpression(path.toString(), { prefix -> namespaceContext.getNamespaceURI(prefix) } ) d.evaluate( path.toString(), d, { prefix -> namespaceContext.getNamespaceURI(prefix) }, XPathResult.ANY_TYPE ) } catch (e: Exception) { console.warn("The path used is not valid ($path) - ${e.message}", e) } } } typealias NamespaceResolver = (String) -> String? @Suppress("UnsafeCastFromDynamic") inline fun Document.createExpression( xpathText: String, noinline namespaceUrlMapper: NamespaceResolver? = null ): XPathExpression = asDynamic().createExpression( xpathText, namespaceUrlMapper ) @Suppress("UnsafeCastFromDynamic") inline fun Document.evaluate( xpathExpression: String, contextNode: Node, noinline namespaceResolver: NamespaceResolver?, resultType: Short ): XPathResult = asDynamic().evaluate(xpathExpression, contextNode, namespaceResolver, resultType, null) @Suppress("UnsafeCastFromDynamic") inline fun Document.evaluate( xpathExpression: String, contextNode: Node, noinline namespaceResolver: NamespaceResolver?, resultType: Short, result: XPathResult ): Unit = asDynamic().evaluate(xpathExpression, contextNode, namespaceResolver, resultType, result) external interface XPathExpression { fun evaluate(contextNode: Node, type: Short, result: Nothing?): XPathResult fun evaluate(contextNode: Node, type: Short, result: XPathResult) } external class XPathResult { val booleanValue: Boolean val invalidIteratorState: Boolean val numberValue: Float val resultType: Short val singleNodeValue: Node? val snapshotLength: Int val stringValue: String fun iterateNext(): Node? fun snapshotItem(index: Int): Node companion object { val ANY_TYPE: Short = definedExternally// = 0 val NUMBER_TYPE: Short = definedExternally// = 1 val STRING_TYPE: Short = definedExternally// = 2 val BOOLEAN_TYPE: Short = definedExternally// = 3 val UNORDERED_NODE_ITERATOR_TYPE: Short = definedExternally// = 4 val ORDERED_NODE_ITERATOR_TYPE: Short = definedExternally// = 5 val UNORDERED_NODE_SNAPSHOT_TYPE: Short = definedExternally// = 6 val ORDERED_NODE_SNAPSHOT_TYPE: Short = definedExternally// = 7 val ANY_UNORDERED_NODE_TYPE: Short = definedExternally// = 8 val FIRST_ORDERED_NODE_TYPE: Short = definedExternally// = 9 } } fun XPathResult.toDocumentFragment(): DocumentFragment { when (resultType) { XPathResult.BOOLEAN_TYPE -> return document.implementation.createDocument(null, "foo").let { d -> d.createDocumentFragment().apply { append(d.createTextNode(booleanValue.toString())) } } XPathResult.STRING_TYPE -> return document.implementation.createDocument(null, "foo").let { d -> d.createDocumentFragment().apply { textContent?.let { t -> append(d.createTextNode(t)) } } } XPathResult.NUMBER_TYPE -> return document.implementation.createDocument(null, "foo").let { d -> d.createDocumentFragment().apply { append(d.createTextNode(numberValue.toString())) } } XPathResult.UNORDERED_NODE_ITERATOR_TYPE, XPathResult.ORDERED_NODE_ITERATOR_TYPE -> iterateNext()?.let { first -> val df = first.ownerDocument!!.createDocumentFragment() var node: Node? = first while (node != null) { df.append(node) node = iterateNext() } return df } XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE -> if (snapshotLength > 0) { val df = snapshotItem(0).ownerDocument!!.createDocumentFragment() for (i in 0 until snapshotLength) { df.append(snapshotItem(i)) } return df } XPathResult.ANY_UNORDERED_NODE_TYPE, XPathResult.FIRST_ORDERED_NODE_TYPE -> singleNodeValue?.let { n -> return snapshotItem(0).ownerDocument!!.createDocumentFragment().apply { append(n) } } } return document.implementation.createDocument(null, "foo").createDocumentFragment() }
lgpl-3.0
6cbfe762da8f37558f4a09701836b0fc
37.617162
236
0.628066
4.979149
false
false
false
false
pdvrieze/ProcessManager
PE-common/src/commonMain/kotlin/org/w3/soapEnvelope/UpgradeType.kt
1
2002
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2009.09.24 at 08:12:58 PM CEST // package org.w3.soapEnvelope import nl.adaptivity.xmlutil.serialization.XmlSerialName /** * * * Java class for UpgradeType complex type. * * * The following schema fragment specifies the expected content contained within * this class. * * ``` * <complexType name="UpgradeType"> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <element name="SupportedEnvelope" type="{http://www.w3.org/2003/05/soap-envelope}SupportedEnvType" maxOccurs="unbounded"/> * </sequence> * </restriction> * </complexContent> * </complexType> * ``` */ class UpgradeType { @XmlSerialName("SupportedEnvelope", Envelope.NAMESPACE, Envelope.PREFIX) protected var _supportedEnvelope: MutableList<SupportedEnvType>? = null val supportedEnvelope: MutableList<SupportedEnvType> get() { return this._supportedEnvelope ?: mutableListOf<SupportedEnvType>().also { _supportedEnvelope = it } } }
lgpl-3.0
bbc527dbe4bf424e2f6e7fd386e0b0de
31.819672
125
0.724775
3.917808
false
false
false
false
wcaokaze/cac2er
src/main/kotlin/com/wcaokaze/cac2er/utils.kt
1
4527
package com.wcaokaze.cac2er import kotlinx.coroutines.experimental.launch import java.io.File import java.io.IOException /** * returns `true` if this file stores a [Cache]. * * @since 4.0.0 */ fun File.isCacheFile(): Boolean = Cacher.checkFileFormat(this) != null fun <T> Cache<T>.weakened() = WeakCache<T>(file) fun <T> Cache<T>.asLazy() = LazyCache<T>(file) /** * returns the content if it exists on JVM memory, otherwise `null`. * * @since 4.0.0 */ val <T> WeakCache<T>.content: T? get() { @Suppress("UNCHECKED_CAST") return Cache.find(file)?.content as T } /** @since 5.0.0 */ val <T> LazyCache<T>.content: T? get() { @Suppress("UNCHECKED_CAST") return Cache.find(file)?.content as T } /** * creates a new [Cache] and calls [WritableCache.save]. * * @since 4.0.0 */ fun <T> Cacher.save(file: File, content: T): WritableCache<T> { val cache = WritableCache(file, content) cache.save() return cache } /** * sets the content, and calls [Cacher.save] at some future time. * * @since 4.0.0 */ fun <T> WritableCache<T>.save(content: T) { this.content = content save() } /** @since 4.0.0 */ fun <T> WritableWeakCache<T>.save(content: T) { Cacher.save(file, content) } /** @since 5.0.0 */ fun <T> WritableLazyCache<T>.save(content: T) { Cacher.save(file, content) } private fun <T> Cache<T>.save() { launch { Cacher.transaction (file) { try { Cacher.save(this@save) } catch (e: IOException) { // ignore } } } } /** * loads a [cache][WritableCache] from the specified file or returns `null` if * an [IOException] occurred. When [Cache] has been loaded and it already exist * on JVM memory, then this function updates the [content][WritableCache.content] * and merges [circulationRecord][Cache.circulationRecord]. * * @since 4.0.0 */ suspend fun Cacher.loadCache(file: File): WritableCache<*>? { val (content, record) = transaction (file) { if (!file.exists()) return null try { return@transaction load(file) } catch (e: IOException) { return null } catch (e: ClassNotFoundException) { return null } } val cache = WritableCache(file, content) cache.circulationRecord += record return cache } /** * returns the [WritableCache] associated with the specified file if it exist on * JVM memory. Otherwise loads it from the file, or `null` if an [IOException] * occurred. * * @since 4.0.0 */ suspend fun Cacher.loadIfNecessary(file: File): WritableCache<*>? { return WritableCache.find(file) ?: loadCache(file) } /** * runs the [GC][Cacher.gc] for all files in the specified directory. * * @since 4.0.0 */ suspend fun Cacher.gcRecursively(directory: File, idealTotalFileSize: Long) { val files = directory.walk().toList() transaction (files) { val cacheFiles = files.asSequence().filter { it.isCacheFile() } try { gc(cacheFiles, idealTotalFileSize) } catch (e: Exception) { // ignore } } } /** * returns [content][Cache.content]. And calls * [circulationRecord.record][Cache.CirculationRecord.record] and * [Cacher.saveCirculationRecord] at some future time. * * @since 4.0.0 */ fun <T> Cache<T>.get(accessCount: Float = 1.0f): T { if (accessCount != .0f) { launch { circulationRecord.record(accessCount = accessCount) Cacher.saveCirculationRecord(this@get) } } return content } /** * calls [WeakCache.loadContent] or returns `null` if an [IOException] occurred. * And calls [circulationRecord.record][Cache.CirculationRecord.record] and * [Cacher.saveCirculationRecord] at some future time. * * @since 4.0.0 */ suspend fun <T> WeakCache<T>.load(accessCount: Float = 1.0f): T? { val content = try { loadContent() ?: return null } catch (e: IOException) { return null } catch (e: ClassNotFoundException) { return null } if (accessCount != .0f) { launch { circulationRecord.record(accessCount = accessCount) Cache.find(file)?.let { Cacher.saveCirculationRecord(it) } } } return content } /** @since 5.0.0 */ suspend fun <T> LazyCache<T>.load(accessCount: Float = 1.0f): T? { val content = try { loadContent() ?: return null } catch (e: IOException) { return null } catch (e: ClassNotFoundException) { return null } if (accessCount != .0f) { launch { circulationRecord.record(accessCount = accessCount) Cache.find(file)?.let { Cacher.saveCirculationRecord(it) } } } return content }
mit
394267b8551ee44cb785e1b095d54068
21.979695
81
0.651646
3.353333
false
false
false
false
youkai-app/Youkai
app/src/main/kotlin/app/youkai/ui/feature/media/summary/AnimeSummaryPresenter.kt
1
5727
package app.youkai.ui.feature.media.summary import app.youkai.App import app.youkai.R import app.youkai.data.models.Anime import app.youkai.data.models.StreamingLink import app.youkai.data.models.ext.releaseStatus import app.youkai.data.models.ext.season import app.youkai.data.models.ext.toCharactersList import app.youkai.util.ext.append import app.youkai.util.ext.stripToDate import app.youkai.util.ext.toMonthDayYearString import app.youkai.util.ext.toTimestamp /** * Media summary presenter that takes care of anime-specific functions. */ class AnimeSummaryPresenter : BaseSummaryPresenter() { override fun setLength() { val res = App.context.resources val episodeCount = (media as Anime).episodeCount ?: 0 val episodeLength = (media as Anime).episodeLength ?: 0 val totalHours = (episodeCount * episodeLength) / 60 val episodesText = res.getQuantityString(R.plurals.x_episodes, episodeCount, episodeCount) val lengthText = res.getQuantityString( R.plurals.x_minutes_each_y_hours_total, episodeCount, res.getQuantityString(R.plurals.x_minutes, episodeLength, episodeLength), res.getQuantityString(R.plurals.x_hours, totalHours, totalHours) ) view?.setLength(episodesText, lengthText, true) view?.setLengthIcon(R.drawable.ic_length_anime_36dp) } override fun setStreamers() { if (!onTablet) { val services = (media as Anime?)?.streamingLinks if (services != null) { view?.setStreamers(services) } else { view?.setNoStreamingServices() } } else { view?.setNoStreamingServices() } } /** * Does all the necessary calculations and decisions and figures out the best way to display * airing information of an anime. Plural strings are used to simplify otherwise * complex code with many nested if statements. * * Essentially, we have three main status cases. These are past, present, and future * (see [app.youkai.data.models.ext.ReleaseStatus]). These statuses have integer values which are used * to grab the relevant items from our plural values. * * Then, we have if statements covering all possible combinations of start and end dates * existing and not existing. We also have a bonus check for the current day. * * Finally, since our view is as dumb as possible, we simply pass two strings for the two lines * in our BarInfoView and an extra boolean flag for making the second line a link. */ override fun setReleaseInfo() { val res = App.context.resources val media = (media as Anime) val status = media.releaseStatus().value val start = media.startDate val end = media.endDate var airText = "" val startText = start?.toTimestamp()?.toMonthDayYearString() ?: "" val endText = end?.toTimestamp()?.toMonthDayYearString() ?: "" if (start != null && end != null) { if (start == end) { // Airing today??? if (start.toTimestamp() == System.currentTimeMillis().stripToDate()) { airText = res.getString(R.string.air_status_today) } else { airText = res.getQuantityString(R.plurals.air_status_x_to_x, status, startText) } } else { airText = res.getQuantityString( R.plurals.air_status_from_x_to_y, status, startText, endText ) } } else if (start != null && end == null) { airText = res.getQuantityString(R.plurals.air_status_on_x, status, startText) } else if (start == null && end != null) { airText = res.getQuantityString(R.plurals.air_status_to_y, status, endText) } else if (start == null && end == null) { airText = res.getString(R.string.air_status_no_date_info) } view?.setReleaseInfo(airText, if (start != null) { res.getString( media.season().valueWithYear, start.split("-")[0] ) } else { res.getString(R.string.air_status_no_season_info) }, true ) } override fun setProducers() { val media = (media as Anime) var producers = "" media.productions?.forEach { val name = it.producer?.name if (name != null) producers = producers.append(name, ", ") } view?.setProducers( if (producers.isNotEmpty()) { producers } else { App.context.resources.getString(R.string.no_producer_info) } ) view?.setProducersIcon(R.drawable.ic_producer_anime_36dp) } override fun setCharacters() { val media = (media as Anime) view?.setCharacters(media.animeCharacters?.toCharactersList() ?: arrayListOf()) view?.setMoreCharactersCount((media.animeCharacters?.size ?: 5) - 5) } override fun setRelated() { val related = (media as Anime?)?.medias if (related != null) { view?.setRelated(related) } else { view?.setRelatedVisible(false) } } override fun onLengthClicked() { view?.onLengthClicked() } override fun onReleaseInfoClicked() { view?.onReleaseInfoClicked() } }
gpl-3.0
e7d8fd18032160a114123d3b98d011a6
35.484076
106
0.585647
4.463757
false
false
false
false
googlecodelabs/play-billing-scalable-kotlin
codelab-02/app/src/main/java/com/example/playbilling/trivialdrive/kotlin/billingrepo/localdb/LocalBillingDb.kt
2
2049
/** * Copyright (C) 2018 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.playbilling.trivialdrive.kotlin.billingrepo.localdb import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database(entities = [CachedPurchase::class, GasTank::class, PremiumCar::class, GoldStatus::class, AugmentedSkuDetails::class], version = 1, exportSchema = false) abstract class LocalBillingDb : RoomDatabase() { abstract fun purchaseDao(): PurchaseDao abstract fun entitlementsDao(): EntitlementsDao abstract fun skuDetailsDao(): AugmentedSkuDetailsDao companion object { @Volatile private var INSTANCE: LocalBillingDb? = null fun getInstance(context: Context): LocalBillingDb { return INSTANCE ?: synchronized(this) { var instance = INSTANCE if (instance == null) { instance = Room.databaseBuilder( context.applicationContext, LocalBillingDb::class.java, "purchase_db") .fallbackToDestructiveMigration()//remote sources more reliable .build() INSTANCE = instance } instance!! } } } }
apache-2.0
d64985441051d7afbe9d5afbf464354e
38.403846
127
0.606637
5.30829
false
false
false
false
ekager/focus-android
app/src/main/java/org/mozilla/focus/search/RadioSearchEngineListPreference.kt
1
2167
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.search import android.content.Context import android.support.v7.preference.PreferenceViewHolder import android.util.AttributeSet import android.widget.CompoundButton import android.widget.RadioGroup import org.mozilla.focus.R import org.mozilla.focus.telemetry.TelemetryWrapper import org.mozilla.focus.utils.Settings class RadioSearchEngineListPreference : SearchEngineListPreference, RadioGroup.OnCheckedChangeListener { override val itemResId: Int get() = R.layout.search_engine_radio_button @Suppress("unused") constructor(context: Context, attrs: AttributeSet) : super(context, attrs) @Suppress("unused") constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) override fun onBindViewHolder(holder: PreferenceViewHolder?) { super.onBindViewHolder(holder) searchEngineGroup!!.setOnCheckedChangeListener(this) } override fun updateDefaultItem(defaultButton: CompoundButton) { defaultButton.isChecked = true } override fun onCheckedChanged(group: RadioGroup, checkedId: Int) { /* onCheckedChanged is called intermittently before the search engine table is full, so we must check these conditions to prevent crashes and inconsistent states. */ if (group.childCount != searchEngines.count() || group.getChildAt(checkedId) == null || !group.getChildAt(checkedId).isPressed) { return } val newDefaultEngine = searchEngines[checkedId] Settings.getInstance(group.context).setDefaultSearchEngineByName(newDefaultEngine.name) val source = if (CustomSearchEngineStore.isCustomSearchEngine(newDefaultEngine.identifier, context)) CustomSearchEngineStore.ENGINE_TYPE_CUSTOM else CustomSearchEngineStore.ENGINE_TYPE_BUNDLED TelemetryWrapper.setDefaultSearchEngineEvent(source) } }
mpl-2.0
3457564b7950d9b2fae1afcfcb687f2d
39.886792
111
0.741578
4.936219
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/kingdom/service/internal/testing/PublicKeysServiceTest.kt
1
9277
// Copyright 2022 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.measurement.kingdom.service.internal.testing import com.google.common.truth.Truth.assertThat import com.google.protobuf.ByteString import io.grpc.Status import io.grpc.StatusRuntimeException import java.time.Clock import kotlin.random.Random import kotlin.test.assertFailsWith import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.measurement.common.identity.IdGenerator import org.wfanet.measurement.common.identity.RandomIdGenerator import org.wfanet.measurement.internal.kingdom.AccountsGrpcKt.AccountsCoroutineImplBase import org.wfanet.measurement.internal.kingdom.CertificatesGrpcKt.CertificatesCoroutineImplBase import org.wfanet.measurement.internal.kingdom.DataProvidersGrpcKt.DataProvidersCoroutineImplBase import org.wfanet.measurement.internal.kingdom.MeasurementConsumersGrpcKt.MeasurementConsumersCoroutineImplBase import org.wfanet.measurement.internal.kingdom.PublicKeysGrpcKt.PublicKeysCoroutineImplBase import org.wfanet.measurement.internal.kingdom.getDataProviderRequest import org.wfanet.measurement.internal.kingdom.getMeasurementConsumerRequest import org.wfanet.measurement.internal.kingdom.updatePublicKeyRequest private const val RANDOM_SEED = 1 private const val API_VERSION = "v2alpha" private val PUBLIC_KEY = ByteString.copyFromUtf8("public key") private val PUBLIC_KEY_SIGNATURE = ByteString.copyFromUtf8("public key signature") @RunWith(JUnit4::class) abstract class PublicKeysServiceTest<T : PublicKeysCoroutineImplBase> { protected data class Services<T>( val publicKeysService: T, val measurementConsumersService: MeasurementConsumersCoroutineImplBase, val dataProvidersService: DataProvidersCoroutineImplBase, val certificatesService: CertificatesCoroutineImplBase, val accountsService: AccountsCoroutineImplBase, ) protected val clock: Clock = Clock.systemUTC() protected val idGenerator = RandomIdGenerator(clock, Random(RANDOM_SEED)) private val population = Population(clock, idGenerator) private lateinit var publicKeysService: T protected lateinit var measurementConsumersService: MeasurementConsumersCoroutineImplBase private set protected lateinit var dataProvidersService: DataProvidersCoroutineImplBase private set protected lateinit var certificatesService: CertificatesCoroutineImplBase private set protected lateinit var accountsService: AccountsCoroutineImplBase private set protected abstract fun newServices(idGenerator: IdGenerator): Services<T> @Before fun initService() { val services = newServices(idGenerator) publicKeysService = services.publicKeysService measurementConsumersService = services.measurementConsumersService dataProvidersService = services.dataProvidersService certificatesService = services.certificatesService accountsService = services.accountsService } @Test fun `updatePublicKey updates the public key info for a data provider`() = runBlocking { val dataProvider = population.createDataProvider(dataProvidersService) publicKeysService.updatePublicKey( updatePublicKeyRequest { externalDataProviderId = dataProvider.externalDataProviderId externalCertificateId = dataProvider.certificate.externalCertificateId apiVersion = API_VERSION publicKey = dataProvider.details.publicKey.concat(PUBLIC_KEY) publicKeySignature = dataProvider.details.publicKeySignature.concat(PUBLIC_KEY_SIGNATURE) } ) val updatedDataProvider = dataProvidersService.getDataProvider( getDataProviderRequest { externalDataProviderId = dataProvider.externalDataProviderId } ) assertThat(dataProvider.details.publicKey).isNotEqualTo(updatedDataProvider.details.publicKey) assertThat(dataProvider.details.publicKeySignature) .isNotEqualTo(updatedDataProvider.details.publicKeySignature) } @Test fun `updatePublicKey updates the public key info for a measurement consumer`() = runBlocking { val measurementConsumer = population.createMeasurementConsumer(measurementConsumersService, accountsService) publicKeysService.updatePublicKey( updatePublicKeyRequest { externalMeasurementConsumerId = measurementConsumer.externalMeasurementConsumerId externalCertificateId = measurementConsumer.certificate.externalCertificateId apiVersion = API_VERSION publicKey = measurementConsumer.details.publicKey.concat(PUBLIC_KEY) publicKeySignature = measurementConsumer.details.publicKeySignature.concat(PUBLIC_KEY_SIGNATURE) } ) val updatedMeasurementConsumer = measurementConsumersService.getMeasurementConsumer( getMeasurementConsumerRequest { externalMeasurementConsumerId = measurementConsumer.externalMeasurementConsumerId } ) assertThat(measurementConsumer.details.publicKey) .isNotEqualTo(updatedMeasurementConsumer.details.publicKey) assertThat(measurementConsumer.details.publicKeySignature) .isNotEqualTo(updatedMeasurementConsumer.details.publicKeySignature) } @Test fun `updatePublicKey throws NOT_FOUND when mc certificate not found`() = runBlocking { val measurementConsumer = population.createMeasurementConsumer(measurementConsumersService, accountsService) val exception = assertFailsWith<StatusRuntimeException> { publicKeysService.updatePublicKey( updatePublicKeyRequest { externalMeasurementConsumerId = measurementConsumer.externalMeasurementConsumerId externalCertificateId = measurementConsumer.certificate.externalCertificateId + 1L apiVersion = API_VERSION publicKey = measurementConsumer.details.publicKey.concat(PUBLIC_KEY) publicKeySignature = measurementConsumer.details.publicKeySignature.concat(PUBLIC_KEY_SIGNATURE) } ) } assertThat(exception.status.code).isEqualTo(Status.Code.FAILED_PRECONDITION) } @Test fun `updatePublicKey throws NOT_FOUND when data provider certificate not found`() = runBlocking { val dataProvider = population.createDataProvider(dataProvidersService) val exception = assertFailsWith<StatusRuntimeException> { publicKeysService.updatePublicKey( updatePublicKeyRequest { externalDataProviderId = dataProvider.externalDataProviderId externalCertificateId = dataProvider.certificate.externalCertificateId + 1L apiVersion = API_VERSION publicKey = dataProvider.details.publicKey.concat(PUBLIC_KEY) publicKeySignature = dataProvider.details.publicKeySignature.concat(PUBLIC_KEY_SIGNATURE) } ) } assertThat(exception.status.code).isEqualTo(Status.Code.FAILED_PRECONDITION) } @Test fun `updatePublicKey throws NOT_FOUND when measurement consumer not found`() = runBlocking { val measurementConsumer = population.createMeasurementConsumer(measurementConsumersService, accountsService) val exception = assertFailsWith<StatusRuntimeException> { publicKeysService.updatePublicKey( updatePublicKeyRequest { externalMeasurementConsumerId = measurementConsumer.externalMeasurementConsumerId + 1L externalCertificateId = measurementConsumer.certificate.externalCertificateId apiVersion = API_VERSION publicKey = measurementConsumer.details.publicKey.concat(PUBLIC_KEY) publicKeySignature = measurementConsumer.details.publicKeySignature.concat(PUBLIC_KEY_SIGNATURE) } ) } assertThat(exception.status.code).isEqualTo(Status.Code.NOT_FOUND) } @Test fun `updatePublicKey throws NOT_FOUND when data provider not found`() = runBlocking { val dataProvider = population.createDataProvider(dataProvidersService) val exception = assertFailsWith<StatusRuntimeException> { publicKeysService.updatePublicKey( updatePublicKeyRequest { externalDataProviderId = dataProvider.externalDataProviderId + 1L externalCertificateId = dataProvider.certificate.externalCertificateId apiVersion = API_VERSION publicKey = dataProvider.details.publicKey.concat(PUBLIC_KEY) publicKeySignature = dataProvider.details.publicKeySignature.concat(PUBLIC_KEY_SIGNATURE) } ) } assertThat(exception.status.code).isEqualTo(Status.Code.NOT_FOUND) } }
apache-2.0
3483bdff67143f54ea33d95260e74f0f
40.231111
111
0.771262
5.512181
false
true
false
false
aucd29/common
library/src/main/java/net/sarangnamu/common/BkDialog.kt
1
6664
/* * Copyright 2016 Burke Choi All rights reserved. * http://www.sarangnamu.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE", "unused") package net.sarangnamu.common import android.app.Activity import android.app.Dialog import android.app.ProgressDialog import android.content.DialogInterface import android.support.annotation.LayoutRes import android.support.annotation.StringRes import android.support.v4.app.Fragment import android.support.v7.app.AlertDialog import android.view.WindowManager import android.widget.FrameLayout // https://kotlinlang.org/docs/tutorials/android-plugin.html import kotlinx.android.synthetic.main.dlg_web.* import kotlinx.android.synthetic.main.dlg_web.view.* /** * Created by <a href="mailto:[email protected]">Burke Choi</a> on 2017. 11. 28.. <p/> * * 그냥 anko 를 쓸까? -_ -;; */ class DialogParam(@StringRes messageId: Int = 0, @StringRes titleId: Int = 0): DlgParam(messageId) { var title: String? = null var positive: ((DialogInterface) -> Unit)? = null var negative: ((DialogInterface) -> Unit)? = null var hideButton: Boolean = false init { if (titleId != 0) { title = BkApp.context().string(titleId) } } fun yesNo() { positiveText = android.R.string.yes negativeText = android.R.string.no } fun okCancel() { positiveText = android.R.string.ok negativeText = android.R.string.cancel } @StringRes var positiveText = android.R.string.ok @StringRes var negativeText = android.R.string.cancel } open class LoadingParam(@StringRes message: Int = 0): DlgParam(message) { var style_horizontal = false } open class DlgParam(@StringRes messageId: Int = 0) { var message: String? = null @LayoutRes var resid: Int = 0 init { if (messageId != 0) { message = BkApp.context().string(messageId) } } } inline fun Fragment.dialog(params: DialogParam): AlertDialog.Builder? { return activity?.dialog(params) } inline fun Activity.dialog(params: DialogParam): AlertDialog.Builder { val bd = AlertDialog.Builder(this) with (params) { with (bd) { if (!hideButton && resid == 0) { setPositiveButton(positiveText, { d, i -> d.dismiss(); positive?.invoke(d) }) negative?.let { setNegativeButton(negativeText, { d, i -> d.dismiss(); it(d) }) } } title?.let { setTitle(it) } message?.let { setMessage(it) } if (resid != 0) { setView(resid) } } } return bd } inline fun Activity.dialog(params: DialogParam, killTimeMillis: Long) { val dlg = dialog(params).show() window.decorView.postDelayed({ dlg.dismiss() }, killTimeMillis) } inline fun Fragment.loading(params: LoadingParam): ProgressDialog? { return activity?.loading(params) } inline fun Activity.loading(params: LoadingParam): ProgressDialog { val bd = ProgressDialog(this) if (params.style_horizontal) { bd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL) } else { bd.setProgressStyle(ProgressDialog.STYLE_SPINNER) } with (params) { with (bd) { message?.let { setMessage(it) } if (resid != 0) { setView(layoutInflater.inflate(resid, null)) } } } return bd } inline fun Activity.browser(url: String, @StringRes titleId: Int = 0) { dialog(DialogParam().apply { resid = R.layout.dlg_web if (titleId != 0) { title = string(titleId) } }).show().run { web.run { loadUrl(url) web.layoutParams = FrameLayout.LayoutParams(BkApp.screenX(), BkApp.screenY()) } fullscreen() } } inline fun Dialog.fullscreen() { window.run { val attr = attributes attr.run { width = WindowManager.LayoutParams.MATCH_PARENT height = WindowManager.LayoutParams.MATCH_PARENT } attributes = attr setBackgroundDrawableResource(android.R.color.transparent) } } //inline fun ProgressDialog.progressFileSize(unit: Int, value: Long) { // setProgress((value shr (10 * unit)).toInt()) // setProgressNumberFormat(value.toFileSizeString(unit)) //} class ProgressNumberFormat(val progress: ProgressDialog, val maxValue: Long) { var unitCount: Int = 0 var unitChar: Char var totalSize: String init { calUnitCount() var count = unitCount if (maxValue > 1024) { ++count } progress.max = calSize(maxValue).toInt() unitChar = " KMGTPE"[count] totalSize = String.format("%.1f%cB", progress.max.toFloat() / 1024f, unitChar) formatString(0) } private fun calUnitCount() { var size = maxValue while (size > 1024 * 1024) { unitCount++ size = size shr 10 } } private fun calSize(value: Long): Long { return (value shr (10 * unitCount)) } fun formatString(current: Long) { val value = calSize(current).toInt() val format = String.format("%.1f%cB/%s", value.toFloat() / 1024f, unitChar, totalSize) progress.progress = value progress.setProgressNumberFormat(format) } } interface IDialog { fun show(activity: Activity, message: String, title: String? = null) fun show(activity: Activity, @StringRes messageId: Int, @StringRes titleId: Int = 0) } //class BkDialog : IDialog { // override fun show(activity: Activity, @StringRes messageId: Int, @StringRes titleId: Int) { // activity.dialog(DialogParam().apply { // if (messageId != 0) { // this.message = activity.string(messageId) // } // // if (titleId != 0) { // this.title = activity.string(titleId) // } // }) // } // // override fun show(activity: Activity, message: String, title: String?) { // activity.dialog(DialogParam().apply { // this.title = title // this.message = message // }) // } //}
apache-2.0
097bcfcdb476e5eedac8b80dcb9381a7
27.314894
100
0.628644
3.927981
false
false
false
false
googlesamples/mlkit
android/material-showcase/app/src/main/java/com/google/mlkit/md/barcodedetection/BarcodeLoadingGraphic.kt
1
3472
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mlkit.md.barcodedetection import android.animation.ValueAnimator import android.graphics.Canvas import android.graphics.Path import android.graphics.Point import android.graphics.PointF import com.google.mlkit.md.camera.GraphicOverlay /** Draws the graphic to indicate the barcode result is in loading. */ internal class BarcodeLoadingGraphic(overlay: GraphicOverlay, private val loadingAnimator: ValueAnimator) : BarcodeGraphicBase(overlay) { private val boxClockwiseCoordinates: Array<PointF> = arrayOf( PointF(boxRect.left, boxRect.top), PointF(boxRect.right, boxRect.top), PointF(boxRect.right, boxRect.bottom), PointF(boxRect.left, boxRect.bottom) ) private val coordinateOffsetBits: Array<Point> = arrayOf( Point(1, 0), Point(0, 1), Point(-1, 0), Point(0, -1) ) private val lastPathPoint = PointF() override fun draw(canvas: Canvas) { super.draw(canvas) val boxPerimeter = (boxRect.width() + boxRect.height()) * 2 val path = Path() // The distance between the box's left-top corner and the starting point of white colored path. var offsetLen = boxPerimeter * loadingAnimator.animatedValue as Float % boxPerimeter var i = 0 while (i < 4) { val edgeLen = if (i % 2 == 0) boxRect.width() else boxRect.height() if (offsetLen <= edgeLen) { lastPathPoint.x = boxClockwiseCoordinates[i].x + coordinateOffsetBits[i].x * offsetLen lastPathPoint.y = boxClockwiseCoordinates[i].y + coordinateOffsetBits[i].y * offsetLen path.moveTo(lastPathPoint.x, lastPathPoint.y) break } offsetLen -= edgeLen i++ } // Computes the path based on the determined starting point and path length. var pathLen = boxPerimeter * 0.3f for (j in 0..3) { val index = (i + j) % 4 val nextIndex = (i + j + 1) % 4 // The length between path's current end point and reticle box's next coordinate point. val lineLen = Math.abs(boxClockwiseCoordinates[nextIndex].x - lastPathPoint.x) + Math.abs(boxClockwiseCoordinates[nextIndex].y - lastPathPoint.y) if (lineLen >= pathLen) { path.lineTo( lastPathPoint.x + pathLen * coordinateOffsetBits[index].x, lastPathPoint.y + pathLen * coordinateOffsetBits[index].y ) break } lastPathPoint.x = boxClockwiseCoordinates[nextIndex].x lastPathPoint.y = boxClockwiseCoordinates[nextIndex].y path.lineTo(lastPathPoint.x, lastPathPoint.y) pathLen -= lineLen } canvas.drawPath(path, pathPaint) } }
apache-2.0
a76d04490f7a3b6f1bc872f8defbac94
38.011236
107
0.639689
4.307692
false
false
false
false
FHannes/intellij-community
java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/UastCreateMethodFix.kt
2
2893
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.daemon.impl.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.JvmCommonIntentionActionsFactory import com.intellij.codeInspection.LocalQuickFixBase import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.psi.PsiModifier import com.intellij.psi.PsiType import com.intellij.psi.SmartPointerManager import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.util.PsiNavigateUtil import org.jetbrains.uast.UClass import org.jetbrains.uast.UMethod class UastCreateMethodFix(containingClass: UClass, private val createMethodAction: IntentionAction) : LocalQuickFixBase(createMethodAction.text, createMethodAction.familyName) { private val containingClass = SmartPointerManager.getInstance(containingClass.project).createSmartPsiElementPointer(containingClass) override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val file = containingClass.containingFile ?: return val methodsBefore = containingClass.element?.methods ?: return createMethodAction.invoke(project, null, file) val newMethod = containingClass.element?.methods?. firstOrNull { method -> methodsBefore.none { it.isEquivalentTo(method) } } ?: return reformatAndOpenCreatedMethod(newMethod) } private fun reformatAndOpenCreatedMethod(method: UMethod) { CodeStyleManager.getInstance(containingClass.project).reformat(method) PsiNavigateUtil.navigate(method.uastBody?.psi?.lastChild ?: method) } companion object { @JvmStatic fun createVoidMethodIfFixPossible(uClass: UClass, methodName: String, @PsiModifier.ModifierConstant modifier: String): UastCreateMethodFix? { if (!ModuleUtilCore.projectContainsFile(uClass.project, uClass.containingFile.virtualFile, false)) return null val actionsFactory = JvmCommonIntentionActionsFactory.forLanguage(uClass.language) ?: return null val action = actionsFactory.createAddMethodAction(uClass, methodName, modifier, PsiType.VOID) ?: return null return UastCreateMethodFix(uClass, action) } } }
apache-2.0
da4dda6eef0708746470f55b1ab1db8e
44.203125
134
0.777739
4.878583
false
false
false
false
RanKKI/PSNine
app/src/main/java/xyz/rankki/psnine/ui/topics/TopicsAdapter.kt
1
2413
@file:Suppress("UNCHECKED_CAST") package xyz.rankki.psnine.ui.topics import android.content.Context import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import org.jetbrains.anko.* import xyz.rankki.psnine.base.BaseTopicsModel import xyz.rankki.psnine.ui.anko.TopicsItemUI class TopicsAdapter<T>(private val mContext: Context) : RecyclerView.Adapter<TopicsAdapter.ViewHolder>() { private val ankoContext = AnkoContext.createReusable(mContext, this) private var data: ArrayList<T> = ArrayList() var clickListener: View.OnClickListener? = null fun updateData(newData: ArrayList<*>) { doAsync { val start: Int = data.size - 1 data.addAll(newData as Collection<T>) val end: Int = data.size uiThread { notifyItemRangeChanged(start, end) } } } fun getData(position: Int): BaseTopicsModel.BaseItem = data[position] as BaseTopicsModel.BaseItem override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view: View = TopicsItemUI<TopicsAdapter<T>>().createView(ankoContext) view.setOnClickListener(clickListener) return ViewHolder(view) } override fun getItemCount(): Int = data.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { val topic = data[position] as BaseTopicsModel.BaseItem holder.tvTitle.text = topic.getTitle() holder.tvUsername.text = topic.getUsername() holder.tvTime.text = topic.getTime() holder.tvReplySize.text = topic.getReplySize() doAsync { val avatar = Glide.with(mContext) .load(topic.getAvatar()) .submit(100, 100).get() uiThread { holder.ivAvatar.image = avatar } } } class ViewHolder(var view: View) : RecyclerView.ViewHolder(view) { val tvTitle: TextView = view.find(TopicsItemUI.ID_Title) val tvUsername: TextView = view.find(TopicsItemUI.ID_Username) val tvTime: TextView = view.find(TopicsItemUI.ID_Time) val tvReplySize: TextView = view.find(TopicsItemUI.ID_ReplySize) val ivAvatar: ImageView = view.find(TopicsItemUI.ID_Avatar) } }
apache-2.0
5643805d82c499cd6a97902f367bf7e6
33.985507
106
0.673021
4.293594
false
false
false
false
binkley/fibs
src/main/kotlin/hm/binkley/Q.kt
1
2439
package hm.binkley class Q private constructor(val a: Int, val b: Int, val c: Int, val d: Int, val n: Int) { companion object { /** The 0th Fibonacci */ val fib0 = Q(0, 1, 1, 1, 0) } operator fun invoke(n: Int): Q { val limit: Int val next: (Q) -> Q if (n < 0) { next = Q::dec limit = -n + 1 } else { next = Q::inc limit = n + 1 } return generateSequence(fib0) { next(it) }. take(limit). last() } /** The trace of Q */ fun trace() = a + d /** The determinant of Q */ fun det() = a * d + b * c /** Gets the element at position <var>i</var> and <var>j</var>. */ operator fun get(i: Int, j: Int) = when (i) { 0 -> when (j) { 0 -> a 1 -> b else -> throw IndexOutOfBoundsException(i.toString()) } 1 -> when (j) { 0 -> c 1 -> d else -> throw IndexOutOfBoundsException(i.toString()) } else -> throw IndexOutOfBoundsException(i.toString()) } /** Gets tne following Fibonacci. */ operator fun inc() = Q(b, d, d, b + d, n + 1) /** Gets the preceding Fibonacci. */ operator fun dec() = Q(b - a, a, a, b, n - 1) operator fun times(that: Q): Q { val a = this.a * that.a + this.b * that.c val b = this.a * that.b + this.b * that.d val c = this.c * that.a + this.d * that.c val d = this.c * that.b * this.d * that.d return Q(a, b, c, d, this.n + that.n) } fun pow(n: Int): Q { val m = n + this.n - 1 return fib0(m) } /** Primitive representation of the array */ override fun toString() = "[ $a $b\n $c $d ]" override fun equals(other: Any?) = when { this === other -> true other?.javaClass != javaClass -> false else -> { other as Q when { a != other.a -> false b != other.b -> false c != other.c -> false d != other.d -> false else -> true } } } override fun hashCode(): Int { var result = a.hashCode() result += 31 * result + b.hashCode() result += 31 * result + c.hashCode() result += 31 * result + d.hashCode() return result } }
unlicense
2d6251023ca25f49a95d9116b00dfc6a
26.1
75
0.448544
3.673193
false
false
false
false
jospint/Architecture-Components-DroidDevs
ArchitectureComponents/app/src/main/java/com/jospint/droiddevs/architecturecomponents/util/extension/Flowables.kt
1
1673
package com.jospint.droiddevs.architecturecomponents.util.extension import android.arch.lifecycle.* import com.jospint.droiddevs.architecturecomponents.util.Resource import io.reactivex.Flowable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers fun <T> Flowable<T>.enqueueToResource(): MutableLiveData<Resource<T>> { return enqueueToResource(null, null) } fun <T> Flowable<T>.enqueueToResource(errorMessage: String?): MutableLiveData<Resource<T>> { return enqueueToResource(errorMessage, null) } fun <T> Flowable<T>.enqueueToResource(errorMessage: String?, loadingMessage: String?): MutableLiveData<Resource<T>> { val result = MutableLiveData<Resource<T>>() result.value = Resource.loading(loadingMessage) this.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe( { response -> result.value = Resource.success(response); }, { e -> result.value = Resource.error(errorMessage ?: e.toString()) }) return result } fun <T> Flowable<T>.enqueueToResourceAlt(errorMessage: String?, loadingMessage: String?): MutableLiveData<Resource<T>> { val safeFlowable = this.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).doOnError {} val liveData = LiveDataReactiveStreams.fromPublisher(safeFlowable) val result = MediatorLiveData<Resource<T>>() result.value = Resource.loading(loadingMessage) result.addSource(liveData) { emittedValue -> result.value = if (emittedValue is T) Resource.success(emittedValue) else Resource.error(errorMessage ?: emittedValue.toString()); } return result }
apache-2.0
0baa829d6b8473192ea064fb6e569491
46.828571
138
0.760311
4.461333
false
false
false
false
arturbosch/detekt
detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/tooling/AnalysisFacade.kt
1
2979
package io.gitlab.arturbosch.detekt.core.tooling import io.github.detekt.tooling.api.AnalysisResult import io.github.detekt.tooling.api.Detekt import io.github.detekt.tooling.api.DetektError import io.github.detekt.tooling.api.InvalidConfig import io.github.detekt.tooling.api.MaxIssuesReached import io.github.detekt.tooling.api.UnexpectedError import io.github.detekt.tooling.api.spec.ProcessingSpec import io.github.detekt.tooling.internal.DefaultAnalysisResult import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Detektion import io.gitlab.arturbosch.detekt.core.ProcessingSettings import io.gitlab.arturbosch.detekt.core.config.MaxIssueCheck import io.gitlab.arturbosch.detekt.core.config.getOrComputeWeightedAmountOfIssues import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.BindingContext import java.nio.file.Path import java.nio.file.Paths class AnalysisFacade( private val spec: ProcessingSpec ) : Detekt { override fun run(): AnalysisResult = runAnalysis { DefaultLifecycle(it, inputPathsToKtFiles) } override fun run(path: Path): AnalysisResult = runAnalysis { DefaultLifecycle(it, pathToKtFile(path)) } override fun run(sourceCode: String, filename: String): AnalysisResult = runAnalysis { DefaultLifecycle(it, contentToKtFile(sourceCode, Paths.get(filename))) } override fun run(files: Collection<KtFile>, bindingContext: BindingContext): AnalysisResult = runAnalysis { DefaultLifecycle( it, parsingStrategy = { files.toList() }, bindingProvider = { bindingContext } ) } internal fun runAnalysis(createLifecycle: (ProcessingSettings) -> Lifecycle): AnalysisResult = spec.withSettings { val result = runCatching { createLifecycle(this).analyze() } when (val error = result.exceptionOrNull()) { null -> { val container = checkNotNull(result.getOrNull()) { "Result should not be null at this point." } DefaultAnalysisResult(container, checkMaxIssuesReachedReturningErrors(container, config)) } is InvalidConfig -> DefaultAnalysisResult(null, error) else -> DefaultAnalysisResult(null, UnexpectedError(error)) } } private fun checkMaxIssuesReachedReturningErrors(result: Detektion, config: Config): DetektError? { if (spec.baselineSpec.shouldCreateDuringAnalysis) { return null // never fail the build as on next run all current issues are suppressed via the baseline } val error = runCatching { val amount = result.getOrComputeWeightedAmountOfIssues(config) MaxIssueCheck(spec.rulesSpec, config).check(amount) }.exceptionOrNull() return when { error is MaxIssuesReached -> error error != null -> UnexpectedError(error) else -> null } } }
apache-2.0
5ea3753143da5c1e45570edc7c49dc2b
41.557143
118
0.711648
4.625776
false
true
false
false
ofalvai/BPInfo
app/src/main/java/com/ofalvai/bpinfo/repository/AlertsRepository.kt
1
4806
/* * Copyright 2019 Olivér Falvai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ofalvai.bpinfo.repository import android.content.Context import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.android.volley.NoConnectionError import com.android.volley.VolleyError import com.ofalvai.bpinfo.Config import com.ofalvai.bpinfo.api.AlertApiClient import com.ofalvai.bpinfo.model.Alert import com.ofalvai.bpinfo.model.Resource import com.ofalvai.bpinfo.model.Status import com.ofalvai.bpinfo.ui.alertlist.AlertListType import com.ofalvai.bpinfo.util.Analytics import com.ofalvai.bpinfo.util.hasNetworkConnection import org.json.JSONException import org.threeten.bp.Duration import org.threeten.bp.LocalDateTime import timber.log.Timber /** * Repository that is responsible for loading the 2 kinds of alert lists. It calls the currently * selected implementation of [AlertApiClient], handles caching, error handling, network detection. */ class AlertsRepository( private val alertApiClient: AlertApiClient, private val appContext: Context, private val analytics: Analytics ) { sealed class Error { class NetworkError(val volleyError: VolleyError) : Error() object DataError : Error() object GeneralError : Error() } val todayAlerts = MutableLiveData<List<Alert>>() val futureAlerts = MutableLiveData<List<Alert>>() val status = MutableLiveData<Status>() val error = MutableLiveData<Error>() private var lastUpdate: LocalDateTime? = null private val refreshThreshold = Duration.ofSeconds(Config.Behavior.REFRESH_THRESHOLD_SEC.toLong()) fun fetchAlerts() { if (shouldUpdate().not()) { if (status.value != Status.Loading) { status.value = Status.Success } return } if (!appContext.hasNetworkConnection()) { status.value = Status.Error error.value = Error.NetworkError(NoConnectionError()) return } status.value = Status.Loading alertApiClient.fetchAlertList(object : AlertApiClient.AlertListCallback { override fun onAlertListResponse(todayAlerts: List<Alert>, futureAlerts: List<Alert>) { lastUpdate = LocalDateTime.now() [email protected] = todayAlerts [email protected] = futureAlerts status.value = Status.Success } override fun onError(ex: Exception) { Timber.e(ex.toString()) status.value = Status.Error when (ex) { is VolleyError -> [email protected] = Error.NetworkError(ex) is JSONException -> { [email protected] = Error.DataError analytics.logException(ex) } else -> { [email protected] = Error.GeneralError analytics.logException(ex) } } } }) } fun fetchAlert(id: String, alertListType: AlertListType): LiveData<Resource<Alert>> { val liveData = MutableLiveData<Resource<Alert>>() liveData.value = Resource.Loading() alertApiClient.fetchAlert(id, alertListType, object : AlertApiClient.AlertDetailCallback { override fun onAlertResponse(alert: Alert) { liveData.value = Resource.Success(alert) } override fun onError(ex: Exception) { Timber.e(ex) analytics.logException(ex) liveData.value = Resource.Error(ex) } }) return liveData } private fun shouldUpdate(): Boolean { // TODO: rewrite to UNIX timestamps // Something like https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/util/RateLimiter.kt return if (lastUpdate == null) { true } else { LocalDateTime.now().isAfter(lastUpdate?.plus(refreshThreshold)) } } }
apache-2.0
8107750ce275b70455893396ba4754b5
34.865672
187
0.653278
4.8002
false
false
false
false
wiltonlazary/kotlin-native
backend.native/tests/objcexport/values.kt
1
34688
/* * 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 file. */ // All classes and methods should be used in tests @file:Suppress("UNUSED") package conversions import kotlin.native.concurrent.freeze import kotlin.native.concurrent.isFrozen import kotlin.native.internal.ObjCErrorException import kotlin.native.ref.WeakReference import kotlin.properties.ReadWriteProperty import kotlin.reflect.KClass import kotlin.reflect.KProperty import kotlin.test.* import kotlinx.cinterop.* // Ensure loaded function IR classes aren't ordered by arity: internal fun referenceFunction1(block: (Any?) -> Unit) {} // Constants const val dbl: Double = 3.14 const val flt: Float = 2.73F const val integer: Int = 42 const val longInt: Long = 1984 // Vars var intVar: Int = 451 var str = "Kotlin String" var strAsAny: Any = "Kotlin String as Any" // MIN/MAX values as Numbers var minDoubleVal: kotlin.Number = Double.MIN_VALUE var maxDoubleVal: kotlin.Number = Double.MAX_VALUE // Infinities and NaN val nanDoubleVal: Double = Double.NaN val nanFloatVal: Float = Float.NaN val infDoubleVal: Double = Double.POSITIVE_INFINITY val infFloatVal: Float = Float.NEGATIVE_INFINITY private fun <T> T.toNullable(): T? = this fun box(booleanValue: Boolean) = booleanValue.toNullable() fun box(byteValue: Byte) = byteValue.toNullable() fun box(shortValue: Short) = shortValue.toNullable() fun box(intValue: Int) = intValue.toNullable() fun box(longValue: Long) = longValue.toNullable() fun box(uByteValue: UByte) = uByteValue.toNullable() fun box(uShortValue: UShort) = uShortValue.toNullable() fun box(uIntValue: UInt) = uIntValue.toNullable() fun box(uLongValue: ULong) = uLongValue.toNullable() fun box(floatValue: Float) = floatValue.toNullable() fun box(doubleValue: Double) = doubleValue.toNullable() private inline fun <reified T> ensureEquals(actual: T?, expected: T) { if (actual !is T) error(T::class) if (actual != expected) error(T::class) } fun ensureEqualBooleans(actual: Boolean?, expected: Boolean) = ensureEquals(actual, expected) fun ensureEqualBytes(actual: Byte?, expected: Byte) = ensureEquals(actual, expected) fun ensureEqualShorts(actual: Short?, expected: Short) = ensureEquals(actual, expected) fun ensureEqualInts(actual: Int?, expected: Int) = ensureEquals(actual, expected) fun ensureEqualLongs(actual: Long?, expected: Long) = ensureEquals(actual, expected) fun ensureEqualUBytes(actual: UByte?, expected: UByte) = ensureEquals(actual, expected) fun ensureEqualUShorts(actual: UShort?, expected: UShort) = ensureEquals(actual, expected) fun ensureEqualUInts(actual: UInt?, expected: UInt) = ensureEquals(actual, expected) fun ensureEqualULongs(actual: ULong?, expected: ULong) = ensureEquals(actual, expected) fun ensureEqualFloats(actual: Float?, expected: Float) = ensureEquals(actual, expected) fun ensureEqualDoubles(actual: Double?, expected: Double) = ensureEquals(actual, expected) // Boolean val boolVal: Boolean = true val boolAnyVal: Any = false // Lists val numbersList: List<Number> = listOf(1.toByte(), 2.toShort(), 13) val anyList: List<Any> = listOf("Str", 42, 3.14, true) // lateinit lateinit var lateinitIntVar: Any // lazy val lazyVal: String by lazy { println("Lazy value initialization") "Lazily initialized string" } // Delegation var delegatedGlobalArray: Array<String> by DelegateClass() class DelegateClass: ReadWriteProperty<Nothing?, Array<String>> { private var holder: Array<String> = arrayOf("property") override fun getValue(thisRef: Nothing?, property: KProperty<*>): Array<String> { return arrayOf("Delegated", "global", "array") + holder } override fun setValue(thisRef: Nothing?, property: KProperty<*>, value: Array<String>) { holder = value } } // Getter with delegation val delegatedList: List<String> get() = delegatedGlobalArray.toList() // Null val nullVal: Any? = null var nullVar: String? = "" // Any var anyValue: Any = "Str" // Functions fun emptyFun() { } fun strFun(): String = "fooStr" fun argsFun(i: Int, l: Long, d: Double, s: String): Any = s + i + l + d fun funArgument(foo: () -> String): String = foo() // Generic functions fun <T, R> genericFoo(t: T, foo: (T) -> R): R = foo(t) fun <T : Number, R : T> fooGenericNumber(r: R, foo: (T) -> Number): Number = foo(r) fun <T> varargToList(vararg args: T): List<T> = args.toList() // Extensions fun String.subExt(i: Int): String { return if (i < this.length) this[i].toString() else "nothing" } fun Any?.toString(): String = this?.toString() ?: "null" fun Any?.print() = println(this.toString()) fun Char.boxChar(): Char? = this fun Char?.isA(): Boolean = (this == 'A') // Lambdas val sumLambda = { x: Int, y: Int -> x + y } // Inheritance interface I { fun iFun(): String = "I::iFun" } fun I.iFunExt() = iFun() private interface PI { fun piFun(): Any fun iFun(): String = "PI::iFun" } class DefaultInterfaceExt : I open class OpenClassI : I { override fun iFun(): String = "OpenClassI::iFun" } class FinalClassExtOpen : OpenClassI() { override fun iFun(): String = "FinalClassExtOpen::iFun" } open class MultiExtClass : OpenClassI(), PI { override fun piFun(): Any { return 42 } override fun iFun(): String = super<PI>.iFun() } open class ConstrClass(open val i: Int, val s: String, val a: Any = "AnyS") : OpenClassI() class ExtConstrClass(override val i: Int) : ConstrClass(i, "String") { override fun iFun(): String = "ExtConstrClass::iFun::$i-$s-$a" } // Enum enum class Enumeration(val enumValue: Int) { ANSWER(42), YEAR(1984), TEMPERATURE(451) } fun passEnum(): Enumeration { return Enumeration.ANSWER } fun receiveEnum(e: Int) { println("ENUM got: ${get(e).enumValue}") } fun get(value: Int): Enumeration { return Enumeration.values()[value] } // Data class values and generated properties: component# and toString() data class TripleVals<T>(val first: T, val second: T, val third: T) data class TripleVars<T>(var first: T, var second: T, var third: T) { override fun toString(): String { return "[$first, $second, $third]" } } open class WithCompanionAndObject { companion object { val str = "String" var named: I? = Named } object Named : OpenClassI() { override fun iFun(): String = "WithCompanionAndObject.Named::iFun" } } fun getCompanionObject() = WithCompanionAndObject.Companion fun getNamedObject() = WithCompanionAndObject.Named fun getNamedObjectInterface(): OpenClassI = WithCompanionAndObject.Named typealias EE = Enumeration fun EE.getAnswer() : EE = Enumeration.ANSWER inline class IC1(val value: Int) inline class IC2(val value: String) inline class IC3(val value: TripleVals<Any?>?) fun box(ic1: IC1): Any = ic1 fun box(ic2: IC2): Any = ic2 fun box(ic3: IC3): Any = ic3 fun concatenateInlineClassValues(ic1: IC1, ic1N: IC1?, ic2: IC2, ic2N: IC2?, ic3: IC3, ic3N: IC3?): String = "${ic1.value} ${ic1N?.value} ${ic2.value} ${ic2N?.value} ${ic3.value} ${ic3N?.value}" fun IC1.getValue1() = this.value fun IC1?.getValueOrNull1() = this?.value fun IC2.getValue2() = value fun IC2?.getValueOrNull2() = this?.value fun IC3.getValue3() = value fun IC3?.getValueOrNull3() = this?.value fun isFrozen(obj: Any): Boolean = obj.isFrozen fun kotlinLambda(block: (Any) -> Any): Any = block fun multiply(int: Int, long: Long) = int * long class MyException : Exception() class MyError : Error() @Throws(MyException::class, MyError::class) fun throwException(error: Boolean): Unit { throw if (error) MyError() else MyException() } interface SwiftOverridableMethodsWithThrows { @Throws(MyException::class) fun unit(): Unit @Throws(MyException::class) fun nothing(): Nothing @Throws(MyException::class) fun any(): Any @Throws(MyException::class) fun block(): () -> Int } interface MethodsWithThrows : SwiftOverridableMethodsWithThrows { @Throws(MyException::class) fun nothingN(): Nothing? @Throws(MyException::class) fun anyN(): Any? @Throws(MyException::class) fun blockN(): (() -> Int)? @Throws(MyException::class) fun pointer(): CPointer<*> @Throws(MyException::class) fun pointerN(): CPointer<*>? @Throws(MyException::class) fun int(): Int @Throws(MyException::class) fun longN(): Long? @Throws(MyException::class) fun double(): Double interface UnitCaller { @Throws(MyException::class) fun call(methods: MethodsWithThrows): Unit } } open class Throwing : MethodsWithThrows { @Throws(MyException::class) constructor(doThrow: Boolean) { if (doThrow) throw MyException() } override fun unit(): Unit = throw MyException() override fun nothing(): Nothing = throw MyException() override fun nothingN(): Nothing? = throw MyException() override fun any(): Any = throw MyException() override fun anyN(): Any? = throw MyException() override fun block(): () -> Int = throw MyException() override fun blockN(): (() -> Int)? = throw MyException() override fun pointer(): CPointer<*> = throw MyException() override fun pointerN(): CPointer<*>? = throw MyException() override fun int(): Int = throw MyException() override fun longN(): Long? = throw MyException() override fun double(): Double = throw MyException() } class NotThrowing : MethodsWithThrows { @Throws(MyException::class) constructor() {} override fun unit(): Unit {} override fun nothing(): Nothing = throw MyException() override fun nothingN(): Nothing? = null override fun any(): Any = Any() override fun anyN(): Any? = Any() override fun block(): () -> Int = { 42 } override fun blockN(): (() -> Int)? = null override fun pointer(): CPointer<*> = 1L.toCPointer<COpaque>()!! override fun pointerN(): CPointer<*>? = null override fun int(): Int = 42 override fun longN(): Long? = null override fun double(): Double = 3.14 } @Throws(Throwable::class) fun testSwiftThrowing(methods: SwiftOverridableMethodsWithThrows) = with(methods) { assertSwiftThrowing { unit() } assertSwiftThrowing { nothing() } assertSwiftThrowing { any() } assertSwiftThrowing { block() } } private inline fun assertSwiftThrowing(block: () -> Unit) = assertFailsWith<ObjCErrorException>(block = block) @Throws(Throwable::class) fun testSwiftNotThrowing(methods: SwiftOverridableMethodsWithThrows) = with(methods) { unit() assertEquals(42, any()) assertEquals(17, block()()) } @Throws(MyError::class) fun callUnit(methods: SwiftOverridableMethodsWithThrows) = methods.unit() @Throws(Throwable::class) fun callUnitCaller(caller: MethodsWithThrows.UnitCaller, methods: MethodsWithThrows) { assertFailsWith<MyException> { caller.call(methods) } } interface ThrowsWithBridgeBase { @Throws(MyException::class) fun plusOne(x: Int): Any } abstract class ThrowsWithBridge : ThrowsWithBridgeBase { abstract override fun plusOne(x: Int): Int } @Throws(Throwable::class) fun testSwiftThrowing(test: ThrowsWithBridgeBase, flag: Boolean) { assertFailsWith<ObjCErrorException> { if (flag) { test.plusOne(0) } else { val test1 = test as ThrowsWithBridge val ignore: Int = test1.plusOne(1) } } } @Throws(Throwable::class) fun testSwiftNotThrowing(test: ThrowsWithBridgeBase) { assertEquals(3, test.plusOne(2)) val test1 = test as ThrowsWithBridge assertEquals<Int>(4, test1.plusOne(3)) } fun Any.same() = this // https://github.com/JetBrains/kotlin-native/issues/2571 val PROPERTY_NAME_MUST_NOT_BE_ALTERED_BY_SWIFT = 111 // https://github.com/JetBrains/kotlin-native/issues/2667 class Deeply { class Nested { class Type { val thirtyTwo = 32 } interface IType } } class WithGenericDeeply() { class Nested { class Type<T> { val thirtyThree = 33 } } } // https://github.com/JetBrains/kotlin-native/issues/3167 class TypeOuter { class Type { val thirtyFour = 34 } } data class CKeywords(val float: Float, val `enum`: Int, var goto: Boolean) interface Base1 { fun same(value: Int?): Int? } interface ExtendedBase1 : Base1 { override fun same(value: Int?): Int? } interface Base2 { fun same(value: Int?): Int? } internal interface Base3 { fun same(value: Int?): Int } open class Base23 : Base2, Base3 { override fun same(value: Int?): Int = error("should not reach here") } fun call(base1: Base1, value: Int?) = base1.same(value) fun call(extendedBase1: ExtendedBase1, value: Int?) = extendedBase1.same(value) fun call(base2: Base2, value: Int?) = base2.same(value) fun call(base3: Any, value: Int?) = (base3 as Base3).same(value) fun call(base23: Base23, value: Int?) = base23.same(value) interface Transform<T, R> { fun map(value: T): R } interface TransformWithDefault<T> : Transform<T, T> { override fun map(value: T): T = value } class TransformInheritingDefault<T> : TransformWithDefault<T> interface TransformIntString { fun map(intValue: Int): String } abstract class TransformIntToString : Transform<Int, String>, TransformIntString { override abstract fun map(intValue: Int): String } open class TransformIntToDecimalString : TransformIntToString() { override fun map(intValue: Int): String = intValue.toString() } private class TransformDecimalStringToInt : Transform<String, Int> { override fun map(stringValue: String): Int = stringValue.toInt() } fun createTransformDecimalStringToInt(): Transform<String, Int> = TransformDecimalStringToInt() open class TransformIntToLong : Transform<Int, Long> { override fun map(value: Int): Long = value.toLong() } class GH2931 { class Data class Holder { val data = Data() init { freeze() } } } class GH2945(var errno: Int) { fun testErrnoInSelector(p: Int, errno: Int) = p + errno } class GH2830 { interface I private class PrivateImpl : I fun getI(): Any = PrivateImpl() } class GH2959 { interface I { val id: Int } private class PrivateImpl(override val id: Int) : I fun getI(id: Int): List<I> = listOf(PrivateImpl(id)) } fun runUnitBlock(block: () -> Unit): Boolean { val blockAny: () -> Any? = block return blockAny() === Unit } fun asUnitBlock(block: () -> Any?): () -> Unit = { block() } fun runNothingBlock(block: () -> Nothing) = try { block() false } catch (e: Throwable) { true } fun asNothingBlock(block: () -> Any?): () -> Nothing = { block() TODO() } fun getNullBlock(): (() -> Unit)? = null fun isBlockNull(block: (() -> Unit)?): Boolean = block == null interface IntBlocks<T> { fun getPlusOneBlock(): T fun callBlock(argument: Int, block: T): Int } object IntBlocksImpl : IntBlocks<(Int) -> Int> { override fun getPlusOneBlock(): (Int) -> Int = { it: Int -> it + 1 } override fun callBlock(argument: Int, block: (Int) -> Int): Int = block(argument) } interface UnitBlockCoercion<T : Any> { fun coerce(block: () -> Unit): T fun uncoerce(block: T): () -> Unit } object UnitBlockCoercionImpl : UnitBlockCoercion<() -> Unit> { override fun coerce(block: () -> Unit): () -> Unit = block override fun uncoerce(block: () -> Unit): () -> Unit = block } fun isFunction(obj: Any?): Boolean = obj is Function<*> fun isFunction0(obj: Any?): Boolean = obj is Function0<*> abstract class MyAbstractList : List<Any?> fun takeForwardDeclaredClass(obj: objcnames.classes.ForwardDeclaredClass) {} fun takeForwardDeclaredProtocol(obj: objcnames.protocols.ForwardDeclaredProtocol) {} class TestKClass { fun getKotlinClass(clazz: ObjCClass) = getOriginalKotlinClass(clazz) fun getKotlinClass(protocol: ObjCProtocol) = getOriginalKotlinClass(protocol) fun isTestKClass(kClass: KClass<*>): Boolean = (kClass == TestKClass::class) fun isI(kClass: KClass<*>): Boolean = (kClass == TestKClass.I::class) interface I } // https://kotlinlang.slack.com/archives/C3SGXARS6/p1560954372179300 interface ForwardI2 : ForwardI1 interface ForwardI1 { fun getForwardI2(): ForwardI2 } abstract class ForwardC2 : ForwardC1() abstract class ForwardC1 { abstract fun getForwardC2(): ForwardC2 } interface TestSR10177Workaround interface TestClashes1 { val clashingProperty: Int } interface TestClashes2 { val clashingProperty: Any val clashingProperty_: Any } class TestClashesImpl : TestClashes1, TestClashes2 { override val clashingProperty: Int get() = 1 override val clashingProperty_: Int get() = 2 } class TestInvalidIdentifiers { class `$Foo` class `Bar$` fun `a$d$d`(`$1`: Int, `2`: Int, `3`: Int): Int = `$1` + `2` + `3` var `$status`: String = "" enum class E(val value: Int) { `4$`(4), `5$`(5), `_`(6), `__`(7) } companion object `Companion$` { val `42` = 42 } val `$` = '$' val `_` = '_' } @Suppress("UNUSED_PARAMETER") open class TestDeprecation() { @Deprecated("hidden", level = DeprecationLevel.HIDDEN) open class OpenHidden : TestDeprecation() @Suppress("DEPRECATION_ERROR") class ExtendingHidden : OpenHidden() { class Nested } @Deprecated("hidden", level = DeprecationLevel.HIDDEN) interface HiddenInterface { fun effectivelyHidden(): Any } @Suppress("DEPRECATION_ERROR") open class ImplementingHidden : Any(), HiddenInterface { override fun effectivelyHidden(): Int = -1 } @Suppress("DEPRECATION_ERROR") fun callEffectivelyHidden(obj: Any): Int = (obj as HiddenInterface).effectivelyHidden() as Int @Deprecated("hidden", level = DeprecationLevel.HIDDEN) class Hidden : TestDeprecation() { open class Nested { class Nested inner class Inner } inner class Inner { inner class Inner } } @Suppress("DEPRECATION_ERROR") class ExtendingNestedInHidden : Hidden.Nested() @Suppress("DEPRECATION_ERROR") fun getHidden() = Hidden() @Deprecated("hidden", level = DeprecationLevel.HIDDEN) constructor(hidden: Byte) : this() @Deprecated("hidden", level = DeprecationLevel.HIDDEN) fun hidden() {} @Deprecated("hidden", level = DeprecationLevel.HIDDEN) val hiddenVal: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) var hiddenVar: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) open fun openHidden() {} @Deprecated("hidden", level = DeprecationLevel.HIDDEN) open val openHiddenVal: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) open var openHiddenVar: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) open class OpenError : TestDeprecation() @Suppress("DEPRECATION_ERROR") class ExtendingError : OpenError() @Deprecated("error", level = DeprecationLevel.ERROR) interface ErrorInterface @Suppress("DEPRECATION_ERROR") class ImplementingError : ErrorInterface @Deprecated("error", level = DeprecationLevel.ERROR) class Error : TestDeprecation() @Suppress("DEPRECATION_ERROR") fun getError() = Error() @Deprecated("error", level = DeprecationLevel.ERROR) constructor(error: Short) : this() @Deprecated("error", level = DeprecationLevel.ERROR) fun error() {} @Deprecated("error", level = DeprecationLevel.ERROR) val errorVal: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) var errorVar: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) open fun openError() {} @Deprecated("error", level = DeprecationLevel.ERROR) open val openErrorVal: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) open var openErrorVar: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) open class OpenWarning : TestDeprecation() @Suppress("DEPRECATION") class ExtendingWarning : OpenWarning() @Deprecated("warning", level = DeprecationLevel.WARNING) interface WarningInterface @Suppress("DEPRECATION") class ImplementingWarning : WarningInterface @Deprecated("warning", level = DeprecationLevel.WARNING) class Warning : TestDeprecation() @Suppress("DEPRECATION") fun getWarning() = Warning() @Deprecated("warning", level = DeprecationLevel.WARNING) constructor(warning: Int) : this() @Deprecated("warning", level = DeprecationLevel.WARNING) fun warning() {} @Deprecated("warning", level = DeprecationLevel.WARNING) val warningVal: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) var warningVar: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) open fun openWarning() {} @Deprecated("warning", level = DeprecationLevel.WARNING) open val openWarningVal: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) open var openWarningVar: Any? = null constructor(normal: Long) : this() fun normal() {} val normalVal: Any? = null var normalVar: Any? = null open fun openNormal(): Int = 1 open val openNormalVal: Any? = null open var openNormalVar: Any? = null class HiddenOverride() : TestDeprecation() { @Deprecated("hidden", level = DeprecationLevel.HIDDEN) constructor(hidden: Byte) : this() @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override fun openHidden() {} @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override val openHiddenVal: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override var openHiddenVar: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) constructor(error: Short) : this() @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override fun openError() {} @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override val openErrorVal: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override var openErrorVar: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) constructor(warning: Int) : this() @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override fun openWarning() {} @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override val openWarningVal: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override var openWarningVar: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) constructor(normal: Long) : this() @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override fun openNormal(): Int = 2 @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override val openNormalVal: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) override var openNormalVar: Any? = null } class ErrorOverride() : TestDeprecation() { @Deprecated("error", level = DeprecationLevel.ERROR) constructor(hidden: Byte) : this() @Deprecated("error", level = DeprecationLevel.ERROR) override fun openHidden() {} @Deprecated("error", level = DeprecationLevel.ERROR) override val openHiddenVal: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) override var openHiddenVar: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) constructor(error: Short) : this() @Deprecated("error", level = DeprecationLevel.ERROR) override fun openError() {} @Deprecated("error", level = DeprecationLevel.ERROR) override val openErrorVal: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) override var openErrorVar: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) constructor(warning: Int) : this() @Deprecated("error", level = DeprecationLevel.ERROR) override fun openWarning() {} @Deprecated("error", level = DeprecationLevel.ERROR) override val openWarningVal: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) override var openWarningVar: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) constructor(normal: Long) : this() @Deprecated("error", level = DeprecationLevel.ERROR) override fun openNormal(): Int = 3 @Deprecated("error", level = DeprecationLevel.ERROR) override val openNormalVal: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) override var openNormalVar: Any? = null } class WarningOverride() : TestDeprecation() { @Deprecated("warning", level = DeprecationLevel.WARNING) constructor(hidden: Byte) : this() @Deprecated("warning", level = DeprecationLevel.WARNING) override fun openHidden() {} @Deprecated("warning", level = DeprecationLevel.WARNING) override val openHiddenVal: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) override var openHiddenVar: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) constructor(error: Short) : this() @Deprecated("warning", level = DeprecationLevel.WARNING) override fun openError() {} @Deprecated("warning", level = DeprecationLevel.WARNING) override val openErrorVal: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) override var openErrorVar: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) constructor(warning: Int) : this() @Deprecated("warning", level = DeprecationLevel.WARNING) override fun openWarning() {} @Deprecated("warning", level = DeprecationLevel.WARNING) override val openWarningVal: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) override var openWarningVar: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) constructor(normal: Long) : this() @Deprecated("warning", level = DeprecationLevel.WARNING) override fun openNormal(): Int = 4 @Deprecated("warning", level = DeprecationLevel.WARNING) override val openNormalVal: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) override var openNormalVar: Any? = null } class NormalOverride() : TestDeprecation() { constructor(hidden: Byte) : this() override fun openHidden() {} override val openHiddenVal: Any? = null override var openHiddenVar: Any? = null constructor(error: Short) : this() override fun openError() {} override val openErrorVal: Any? = null override var openErrorVar: Any? = null constructor(warning: Int) : this() override fun openWarning() {} override val openWarningVal: Any? = null override var openWarningVar: Any? = null constructor(normal: Long) : this() override fun openNormal(): Int = 5 override val openNormalVal: Any? = null override var openNormalVar: Any? = null } @Suppress("DEPRECATION_ERROR") fun test(hiddenNested: Hidden.Nested) {} @Suppress("DEPRECATION_ERROR") fun test(hiddenNestedNested: Hidden.Nested.Nested) {} @Suppress("DEPRECATION_ERROR") fun test(hiddenNestedInner: Hidden.Nested.Inner) {} @Suppress("DEPRECATION_ERROR") fun test(hiddenInner: Hidden.Inner) {} @Suppress("DEPRECATION_ERROR") fun test(hiddenInnerInner: Hidden.Inner.Inner) {} @Suppress("DEPRECATION_ERROR") fun test(topLevelHidden: TopLevelHidden) {} @Suppress("DEPRECATION_ERROR") fun test(topLevelHiddenNested: TopLevelHidden.Nested) {} @Suppress("DEPRECATION_ERROR") fun test(topLevelHiddenNestedNested: TopLevelHidden.Nested.Nested) {} @Suppress("DEPRECATION_ERROR") fun test(topLevelHiddenNestedInner: TopLevelHidden.Nested.Inner) {} @Suppress("DEPRECATION_ERROR") fun test(topLevelHiddenInner: TopLevelHidden.Inner) {} @Suppress("DEPRECATION_ERROR") fun test(topLevelHiddenInnerInner: TopLevelHidden.Inner.Inner) {} @Suppress("DEPRECATION_ERROR") fun test(extendingHiddenNested: ExtendingHidden.Nested) {} @Suppress("DEPRECATION_ERROR") fun test(extendingNestedInHidden: ExtendingNestedInHidden) {} } @Deprecated("hidden", level = DeprecationLevel.HIDDEN) class TopLevelHidden { class Nested { class Nested inner class Inner } inner class Inner { inner class Inner } } @Deprecated("hidden", level = DeprecationLevel.HIDDEN) fun hidden() {} @Deprecated("hidden", level = DeprecationLevel.HIDDEN) val hiddenVal: Any? = null @Deprecated("hidden", level = DeprecationLevel.HIDDEN) var hiddenVar: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) fun error() {} @Deprecated("error", level = DeprecationLevel.ERROR) val errorVal: Any? = null @Deprecated("error", level = DeprecationLevel.ERROR) var errorVar: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) fun warning() {} @Deprecated("warning", level = DeprecationLevel.WARNING) val warningVal: Any? = null @Deprecated("warning", level = DeprecationLevel.WARNING) var warningVar: Any? = null fun gc() { kotlin.native.internal.GC.collect() } class TestWeakRefs(private val frozen: Boolean) { private var obj: Any? = Any().also { if (frozen) it.freeze() } fun getObj() = obj!! fun clearObj() { obj = null } fun createCycle(): List<Any> { val node1 = Node(null) val node2 = Node(node1) node1.next = node2 if (frozen) node1.freeze() return listOf(node1, node2) } private class Node(var next: Node?) } class SharedRefs { class MutableData { var x = 0 fun update() { x += 1 } } fun createRegularObject(): MutableData = create { MutableData() } fun createLambda(): () -> Unit = create { var mutableData = 0 { println(mutableData++) } } fun createCollection(): MutableList<Any> = create { mutableListOf() } fun createFrozenRegularObject() = createRegularObject().freeze() fun createFrozenLambda() = createLambda().freeze() fun createFrozenCollection() = createCollection().freeze() fun hasAliveObjects(): Boolean { kotlin.native.internal.GC.collect() return mustBeRemoved.any { it.get() != null } } private fun <T : Any> create(block: () -> T) = block() .also { mustBeRemoved += WeakReference(it) } private val mustBeRemoved = mutableListOf<WeakReference<*>>() } interface TestRememberNewObject { fun getObject(): Any fun waitForCleanup() } fun testRememberNewObject(test: TestRememberNewObject) { val obj = autoreleasepool { test.getObject() } test.waitForCleanup() assertNotEquals("", obj.toString()) // Likely crashes if object is removed. } open class ClassForTypeCheck fun testClassTypeCheck(x: Any) = x is ClassForTypeCheck interface InterfaceForTypeCheck fun testInterfaceTypeCheck(x: Any) = x is InterfaceForTypeCheck interface IAbstractInterface { fun foo(): Int } interface IAbstractInterface2 { fun foo() = 42 } fun testAbstractInterfaceCall(x: IAbstractInterface) = x.foo() fun testAbstractInterfaceCall2(x: IAbstractInterface2) = x.foo() abstract class AbstractInterfaceBase : IAbstractInterface { override fun foo() = bar() abstract fun bar(): Int } abstract class AbstractInterfaceBase2 : IAbstractInterface2 abstract class AbstractInterfaceBase3 : IAbstractInterface { abstract override fun foo(): Int } var gh3525BaseInitCount = 0 open class GH3525Base { init { gh3525BaseInitCount++ } } var gh3525InitCount = 0 object GH3525 : GH3525Base() { init { gh3525InitCount++ } } class TestStringConversion { lateinit var str: Any } fun foo(a: kotlin.native.concurrent.AtomicReference<*>) {} interface GH3825 { @Throws(MyException::class) fun call0(callback: () -> Boolean) @Throws(MyException::class) fun call1(doThrow: Boolean, callback: () -> Unit) @Throws(MyException::class) fun call2(callback: () -> Unit, doThrow: Boolean) } class GH3825KotlinImpl : GH3825 { override fun call0(callback: () -> Boolean) { if (callback()) throw MyException() } override fun call1(doThrow: Boolean, callback: () -> Unit) { if (doThrow) throw MyException() callback() } override fun call2(callback: () -> Unit, doThrow: Boolean) { if (doThrow) throw MyException() callback() } } @Throws(Throwable::class) fun testGH3825(gh3825: GH3825) { var count = 0 assertFailsWith<ObjCErrorException> { gh3825.call0({ true }) } gh3825.call0({ count += 1; false }) assertEquals(1, count) assertFailsWith<ObjCErrorException> { gh3825.call1(true, { fail() }) } gh3825.call1(false, { count += 1 }) assertEquals(2, count) assertFailsWith<ObjCErrorException> { gh3825.call2({ fail() }, true) } gh3825.call2({ count += 1 }, false) assertEquals(3, count) } fun mapBoolean2String(): Map<Boolean, String> = mapOf(Pair(false, "false"), Pair(true, "true")) fun mapByte2Short(): Map<Byte, Short> = mapOf(Pair(-1, 2)) fun mapShort2Byte(): Map<Short, Byte> = mapOf(Pair(-2, 1)) fun mapInt2Long(): Map<Int, Long> = mapOf(Pair(-4, 8)) fun mapLong2Long(): Map<Long, Long> = mapOf(Pair(-8, 8)) fun mapUByte2Boolean(): Map<UByte, Boolean> = mapOf(Pair(0x80U, true)) fun mapUShort2Byte(): Map<UShort, Byte> = mapOf(Pair(0x8000U, 1)) fun mapUInt2Long(): Map<UInt, Long> = mapOf(Pair(0x7FFF_FFFFU, 7), Pair(0x8000_0000U, 8)) fun mapULong2Long(): Map<ULong, Long> = mapOf(Pair(0x8000_0000_0000_0000UL, 8)) fun mapFloat2Float(): Map<Float, Float> = mapOf(Pair(3.14f, 100f)) fun mapDouble2String(): Map<Double, String> = mapOf(Pair(2.718281828459045, "2.718281828459045")) fun mutBoolean2String(): MutableMap<Boolean, String> = mutableMapOf(Pair(false, "false"), Pair(true, "true")) fun mutByte2Short(): MutableMap<Byte, Short> = mutableMapOf(Pair(-1, 2)) fun mutShort2Byte(): MutableMap<Short, Byte> = mutableMapOf(Pair(-2, 1)) fun mutInt2Long(): MutableMap<Int, Long> = mutableMapOf(Pair(-4, 8)) fun mutLong2Long(): MutableMap<Long, Long> = mutableMapOf(Pair(-8, 8)) fun mutUByte2Boolean(): MutableMap<UByte, Boolean> = mutableMapOf(Pair(128U, true)) fun mutUShort2Byte(): MutableMap<UShort, Byte> = mutableMapOf(Pair(32768U, 1)) fun mutUInt2Long(): MutableMap<UInt, Long> = mutableMapOf(Pair(0x8000_0000U, 8)) fun mutULong2Long(): MutableMap<ULong, Long> = mutableMapOf(Pair(0x8000_0000_0000_0000UL, 8)) fun mutFloat2Float(): MutableMap<Float, Float> = mutableMapOf(Pair(3.14f, 100f)) fun mutDouble2String(): MutableMap<Double, String> = mutableMapOf(Pair(2.718281828459045, "2.718281828459045"))
apache-2.0
529e31a3dc888d3f9a5e1a0432264117
33.209073
111
0.688855
3.843972
false
true
false
false
ibaton/3House
mobile/src/main/java/treehou/se/habit/ui/widget/WidgetSwitchFactory.kt
1
2530
package treehou.se.habit.ui.widget import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.Switch import se.treehou.ng.ohcommunicator.connector.models.OHItem import se.treehou.ng.ohcommunicator.connector.models.OHLinkedPage import se.treehou.ng.ohcommunicator.connector.models.OHServer import se.treehou.ng.ohcommunicator.connector.models.OHWidget import se.treehou.ng.ohcommunicator.services.IServerHandler import treehou.se.habit.R import treehou.se.habit.connector.Constants import treehou.se.habit.ui.adapter.WidgetAdapter import treehou.se.habit.ui.view.WidgetTextView import treehou.se.habit.util.logging.Logger import javax.inject.Inject class WidgetSwitchFactory @Inject constructor() : WidgetFactory { @Inject lateinit var logger: Logger @Inject lateinit var server: OHServer @Inject lateinit var page: OHLinkedPage @Inject lateinit var serverHandler: IServerHandler override fun createViewHolder(parent: ViewGroup): WidgetAdapter.WidgetViewHolder { val context = parent.context val view = LayoutInflater.from(context).inflate(R.layout.widget_switch, parent, false) return SwitchWidgetViewHolder(view) } inner class SwitchWidgetViewHolder(view: View) : WidgetBaseHolder(view, server, page) { private val switchView: Switch = view.findViewById(R.id.widgetSwitch) init { setupClickListener() } private fun setupClickListener() { itemView.setOnClickListener { val newState = !switchView.isChecked logger.d(TAG, "${widget.label} $newState") val item: OHItem? = widget.item if (item != null && item.stateDescription?.isReadOnly != true) { switchView.isChecked = newState serverHandler.sendCommand(item.name, if (newState) Constants.COMMAND_ON else Constants.COMMAND_OFF) } } } override fun bind(itemWidget: WidgetAdapter.WidgetItem) { super.bind(itemWidget) val item: OHItem? = widget.item if(item != null) { val isOn = item.state == Constants.COMMAND_ON switchView.isEnabled = item.stateDescription?.isReadOnly == false switchView.isChecked = isOn } } } companion object { const val TAG = "WidgetSwitchFactory" } }
epl-1.0
572a1ff070e4872d932ea5c6705f939c
35.157143
119
0.687747
4.650735
false
false
false
false
soywiz/korge
korge-dragonbones/src/commonMain/kotlin/com/dragonbones/event/EventObject.kt
1
7255
/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors * * 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.dragonbones.event import com.dragonbones.animation.* import com.dragonbones.armature.* import com.dragonbones.core.* import com.dragonbones.model.* /** * - The properties of the object carry basic information about an event, * which are passed as parameter or parameter's parameter to event listeners when an event occurs. * @version DragonBones 4.5 * @language en_US */ @Suppress("KDocUnresolvedReference") /** * - 事件对象,包含有关事件的基本信息,当发生事件时,该实例将作为参数或参数的参数传递给事件侦听器。 * @version DragonBones 4.5 * @language zh_CN */ class EventObject(pool: SingleObjectPool<EventObject>) : BaseObject(pool) { companion object { /** * - Animation start play. * @version DragonBones 4.5 * @language en_US */ /** * - 动画开始播放。 * @version DragonBones 4.5 * @language zh_CN */ val START: String = "start" /** * - Animation loop play complete once. * @version DragonBones 4.5 * @language en_US */ /** * - 动画循环播放完成一次。 * @version DragonBones 4.5 * @language zh_CN */ val LOOP_COMPLETE: String = "loopComplete" /** * - Animation play complete. * @version DragonBones 4.5 * @language en_US */ /** * - 动画播放完成。 * @version DragonBones 4.5 * @language zh_CN */ val COMPLETE: String = "complete" /** * - Animation fade in start. * @version DragonBones 4.5 * @language en_US */ /** * - 动画淡入开始。 * @version DragonBones 4.5 * @language zh_CN */ val FADE_IN: String = "fadeIn" /** * - Animation fade in complete. * @version DragonBones 4.5 * @language en_US */ /** * - 动画淡入完成。 * @version DragonBones 4.5 * @language zh_CN */ val FADE_IN_COMPLETE: String = "fadeInComplete" /** * - Animation fade out start. * @version DragonBones 4.5 * @language en_US */ /** * - 动画淡出开始。 * @version DragonBones 4.5 * @language zh_CN */ val FADE_OUT: String = "fadeOut" /** * - Animation fade out complete. * @version DragonBones 4.5 * @language en_US */ /** * - 动画淡出完成。 * @version DragonBones 4.5 * @language zh_CN */ val FADE_OUT_COMPLETE: String = "fadeOutComplete" /** * - Animation frame event. * @version DragonBones 4.5 * @language en_US */ /** * - 动画帧事件。 * @version DragonBones 4.5 * @language zh_CN */ val FRAME_EVENT: String = "frameEvent" /** * - Animation frame sound event. * @version DragonBones 4.5 * @language en_US */ /** * - 动画帧声音事件。 * @version DragonBones 4.5 * @language zh_CN */ val SOUND_EVENT: String = "soundEvent" /** * @internal * @private */ fun actionDataToInstance(data: ActionData, instance: EventObject, armature: Armature) { if (data.type == ActionType.Play) { instance.type = EventObject.FRAME_EVENT } else { instance.type = if (data.type == ActionType.Frame) EventObject.FRAME_EVENT else EventObject.SOUND_EVENT } instance.name = data.name instance.armature = armature instance.actionData = data instance.data = data.data if (data.bone != null) { instance.bone = armature.getBone(data.bone?.name) } if (data.slot != null) { instance.slot = armature.getSlot(data.slot?.name) } } } override fun toString(): String = "[class dragonBones.EventObject]" /** * - If is a frame event, the value is used to describe the time that the event was in the animation timeline. (In seconds) * @version DragonBones 4.5 * @language en_US */ /** * - 如果是帧事件,此值用来描述该事件在动画时间轴中所处的时间。(以秒为单位) * @version DragonBones 4.5 * @language zh_CN */ var time: Double = 0.0 /** * - The event type。 * @version DragonBones 4.5 * @language en_US */ /** * - 事件类型。 * @version DragonBones 4.5 * @language zh_CN */ var type: EventStringType = "" /** * - The event name. (The frame event name or the frame sound name) * @version DragonBones 4.5 * @language en_US */ /** * - 事件名称。 (帧事件的名称或帧声音的名称) * @version DragonBones 4.5 * @language zh_CN */ var name: String = "" /** * - The armature that dispatch the event. * @see dragonBones.Armature * @version DragonBones 4.5 * @language en_US */ /** * - 发出该事件的骨架。 * @see dragonBones.Armature * @version DragonBones 4.5 * @language zh_CN */ lateinit var armature: Armature /** * - The bone that dispatch the event. * @see dragonBones.Bone * @version DragonBones 4.5 * @language en_US */ /** * - 发出该事件的骨骼。 * @see dragonBones.Bone * @version DragonBones 4.5 * @language zh_CN */ var bone: Bone? = null /** * - The slot that dispatch the event. * @see dragonBones.Slot * @version DragonBones 4.5 * @language en_US */ /** * - 发出该事件的插槽。 * @see dragonBones.Slot * @version DragonBones 4.5 * @language zh_CN */ var slot: Slot? = null /** * - The animation state that dispatch the event. * @see dragonBones.AnimationState * @version DragonBones 4.5 * @language en_US */ /** * - 发出该事件的动画状态。 * @see dragonBones.AnimationState * @version DragonBones 4.5 * @language zh_CN */ lateinit var animationState: AnimationState /** * @private */ var actionData: ActionData? = null /** * @private */ /** * - The custom data. * @see dragonBones.CustomData * @version DragonBones 5.0 * @language en_US */ /** * - 自定义数据。 * @see dragonBones.CustomData * @version DragonBones 5.0 * @language zh_CN */ var data: UserData? = null override fun _onClear() { this.time = 0.0 this.type = "" this.name = "" //this.armature = null this.bone = null this.slot = null //this.animationState = null this.actionData = null this.data = null } }
apache-2.0
68325f135ba83a393d016f2126321a09
22.677083
124
0.644229
3.342647
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/particle/ParticleEmitterSimulator.kt
1
8081
package com.soywiz.korge.particle import com.soywiz.klock.* import com.soywiz.korma.geom.* import kotlin.math.* import kotlin.random.* class ParticleEmitterSimulator( private val emitter: ParticleEmitter, var emitterPos: IPoint = IPoint(), val seed: Long = Random.nextLong() ) { val random = Random(seed) var totalElapsedTime = 0.seconds var timeUntilStop = TimeSpan.NIL var emitting = true val textureWidth = emitter.texture?.width ?: 16 val particles = ParticleContainer(emitter.maxParticles).init() val aliveCount: Int get() { var count = 0 particles.fastForEach { if (it.alive) count++ } return count } val anyAlive: Boolean get() = aliveCount > 0 private fun randomVariance(base: Float, variance: Float): Float = base + variance * (random.nextFloat() * 2f - 1f) private fun randomVariance(base: Double, variance: Double): Double = base + variance * (random.nextDouble() * 2.0 - 1.0) private fun randomVariance(base: Angle, variance: Angle): Angle = randomVariance(base.degrees, variance.degrees).degrees fun ParticleContainer.init() = fastForEach { init(it, true) } fun ParticleContainer.init(particle: Particle, initialization: Boolean): Particle { val lifespan = randomVariance(emitter.lifeSpan, emitter.lifespanVariance).coerceAtLeast(0.001).toFloat() particle.totalTime = lifespan.coerceAtLeast(0f) if (initialization) { val ratio = particle.index.toFloat() / emitter.maxParticles.toFloat() particle.currentTime = -(emitter.lifeSpan + emitter.lifespanVariance.absoluteValue).toFloat() * ratio //println(particle.currentTime) } else { particle.currentTime = 0f } val emitterX = emitterPos.x.toFloat() val emitterY = emitterPos.y.toFloat() particle.x = randomVariance(emitterX, emitter.sourcePositionVariance.x.toFloat()) particle.y = randomVariance(emitterY, emitter.sourcePositionVariance.y.toFloat()) particle.startX = emitterX.toFloat() particle.startY = emitterY.toFloat() val angle = randomVariance(emitter.angle, emitter.angleVariance) val speed = randomVariance(emitter.speed, emitter.speedVariance).toFloat() particle.velocityX = speed * cos(angle).toFloat() particle.velocityY = speed * sin(angle).toFloat() val startRadius = randomVariance(emitter.maxRadius, emitter.maxRadiusVariance).toFloat() val endRadius = randomVariance(emitter.minRadius, emitter.minRadiusVariance).toFloat() particle.emitRadius = startRadius particle.emitRadiusDelta = (endRadius - startRadius) / lifespan particle.emitRotation = randomVariance(emitter.angle, emitter.angleVariance) particle.emitRotationDelta = randomVariance(emitter.rotatePerSecond, emitter.rotatePerSecondVariance) particle.radialAcceleration = randomVariance(emitter.radialAcceleration, emitter.radialAccelVariance).toFloat() particle.tangentialAcceleration = randomVariance(emitter.tangentialAcceleration, emitter.tangentialAccelVariance).toFloat() val startSize = randomVariance(emitter.startSize, emitter.startSizeVariance).coerceAtLeast(0.1).toFloat() val endSize = randomVariance(emitter.endSize, emitter.endSizeVariance).coerceAtLeast(0.1).toFloat() particle.scale = startSize / textureWidth particle.scaleDelta = ((endSize - startSize) / lifespan) / textureWidth particle.colorR = randomVariance(emitter.startColor.r, emitter.startColorVariance.r) particle.colorG = randomVariance(emitter.startColor.g, emitter.startColorVariance.g) particle.colorB = randomVariance(emitter.startColor.b, emitter.startColorVariance.b) particle.colorA = randomVariance(emitter.startColor.a, emitter.startColorVariance.a) val endColorR = randomVariance(emitter.endColor.r, emitter.endColorVariance.r) val endColorG = randomVariance(emitter.endColor.g, emitter.endColorVariance.g) val endColorB = randomVariance(emitter.endColor.b, emitter.endColorVariance.b) val endColorA = randomVariance(emitter.endColor.a, emitter.endColorVariance.a) particle.colorRdelta = ((endColorR - particle.colorR) / lifespan) particle.colorGdelta = ((endColorG - particle.colorG) / lifespan) particle.colorBdelta = ((endColorB - particle.colorB) / lifespan) particle.colorAdelta = ((endColorA - particle.colorA) / lifespan) val startRotation = randomVariance(emitter.rotationStart, emitter.rotationStartVariance) val endRotation = randomVariance(emitter.rotationEnd, emitter.rotationEndVariance) particle.rotation = startRotation particle.rotationDelta = (endRotation - startRotation) / lifespan return particle } fun ParticleContainer.advance(particle: Particle, _elapsedTime: Float) { val restTime = particle.totalTime - particle.currentTime val elapsedTime = if (restTime > _elapsedTime) _elapsedTime else restTime particle.currentTime += elapsedTime.toFloat() //if (particle.index == 0) { //println("currentTime=${particle.currentTime}, totalTime=${particle.totalTime}, emitting=$emitting, elapsedTime=$elapsedTime, alive=${particle.alive}") //3.253971163270661, 3.253971163270661, false //} if (particle.currentTime < 0.0) return if (!particle.alive && emitting) { init(particle, false) } if (!particle.alive) return when (emitter.emitterType) { ParticleEmitter.Type.RADIAL -> { particle.emitRotation += particle.emitRotationDelta * elapsedTime.toDouble() particle.emitRadius += (particle.emitRadiusDelta * elapsedTime).toFloat() particle.x = emitter.sourcePosition.xf - cos(particle.emitRotation).toFloat() * particle.emitRadius particle.y = emitter.sourcePosition.yf - sin(particle.emitRotation).toFloat() * particle.emitRadius } ParticleEmitter.Type.GRAVITY -> { val distanceX = particle.x - particle.startX val distanceY = particle.y - particle.startY val distanceScalar = sqrt(distanceX * distanceX + distanceY * distanceY).coerceAtLeast(0.01f) var radialX = distanceX / distanceScalar var radialY = distanceY / distanceScalar var tangentialX = radialX var tangentialY = radialY radialX *= particle.radialAcceleration radialY *= particle.radialAcceleration val newY = tangentialX tangentialX = -tangentialY * particle.tangentialAcceleration tangentialY = newY * particle.tangentialAcceleration particle.velocityX += elapsedTime * (emitter.gravity.x + radialX + tangentialX).toFloat() particle.velocityY += elapsedTime * (emitter.gravity.y + radialY + tangentialY).toFloat() particle.x += particle.velocityX * elapsedTime.toFloat() particle.y += particle.velocityY * elapsedTime.toFloat() } } particle.scale += particle.scaleDelta * elapsedTime particle.rotation += particle.rotationDelta * elapsedTime particle.colorR += (particle.colorRdelta * elapsedTime) particle.colorG += (particle.colorGdelta * elapsedTime) particle.colorB += (particle.colorBdelta * elapsedTime) particle.colorA += (particle.colorAdelta * elapsedTime) } fun simulate(time: TimeSpan) { if (emitting) { totalElapsedTime += time if (timeUntilStop != TimeSpan.NIL && totalElapsedTime >= timeUntilStop) emitting = false } val timeSeconds = time.seconds.toFloat() particles.fastForEach { p -> advance(p, timeSeconds) } } fun restart() { totalElapsedTime = 0.seconds emitting = true } }
apache-2.0
1e89f00fd05c7cc75010734da437bd59
46.816568
164
0.678134
4.459713
false
false
false
false
samtstern/quickstart-android
admob/app/src/main/java/com/google/samples/quickstart/admobexample/kotlin/MainActivity.kt
1
4835
package com.google.samples.quickstart.admobexample.kotlin import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Button import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.ads.AdListener import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.AdView import com.google.android.gms.ads.InterstitialAd import com.google.android.gms.ads.MobileAds import com.google.samples.quickstart.admobexample.R import com.google.samples.quickstart.admobexample.databinding.ActivityMainBinding // [SNIPPET load_banner_ad] // Load an ad into the AdView. // [START load_banner_ad] class MainActivity : AppCompatActivity() { // [START_EXCLUDE] private lateinit var binding: ActivityMainBinding private lateinit var interstitialAd: InterstitialAd private lateinit var adView: AdView private lateinit var loadInterstitialButton: Button // [END_EXCLUDE] override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // [START_EXCLUDE] binding = ActivityMainBinding.inflate(layoutInflater) adView = binding.adView loadInterstitialButton = binding.loadInterstitialButton val layout = binding.root // [END_EXCLUDE] setContentView(layout) checkIds() // Initialize the Google Mobile Ads SDK MobileAds.initialize(this, getString(R.string.admob_app_id)) val adRequest = AdRequest.Builder().build() adView.loadAd(adRequest) // [END load_banner_ad] // AdMob ad unit IDs are not currently stored inside the google-services.json file. // Developers using AdMob can store them as custom values in a string resource file or // simply use constants. Note that the ad units used here are configured to return only test // ads, and should not be used outside this sample. // [START instantiate_interstitial_ad] // Create an InterstitialAd object. This same object can be re-used whenever you want to // show an interstitial. interstitialAd = InterstitialAd(this) interstitialAd.adUnitId = getString(R.string.interstitial_ad_unit_id) // [END instantiate_interstitial_ad] // [START create_interstitial_ad_listener] interstitialAd.adListener = object : AdListener() { override fun onAdClosed() { requestNewInterstitial() beginSecondActivity() } override fun onAdLoaded() { // Ad received, ready to display // [START_EXCLUDE] loadInterstitialButton.isEnabled = true // [END_EXCLUDE] } override fun onAdFailedToLoad(i: Int) { // See https://goo.gl/sCZj0H for possible error codes. Log.w(TAG, "onAdFailedToLoad:$i") } } // [END create_interstitial_ad_listener] // [START display_interstitial_ad] loadInterstitialButton.setOnClickListener { if (interstitialAd.isLoaded) { interstitialAd.show() } else { beginSecondActivity() } } // [END display_interstitial_ad] // Disable button if an interstitial ad is not loaded yet. loadInterstitialButton.isEnabled = interstitialAd.isLoaded } /** * Load a new interstitial ad asynchronously. */ // [START request_new_interstitial] private fun requestNewInterstitial() { val adRequest = AdRequest.Builder() .build() interstitialAd.loadAd(adRequest) } // [END request_new_interstitial] private fun beginSecondActivity() { val intent = Intent(this, SecondActivity::class.java) startActivity(intent) } // [START add_lifecycle_methods] /** Called when leaving the activity */ public override fun onPause() { adView.pause() super.onPause() } /** Called when returning to the activity */ public override fun onResume() { super.onResume() adView.resume() if (!interstitialAd.isLoaded) { requestNewInterstitial() } } /** Called before the activity is destroyed */ public override fun onDestroy() { adView.destroy() super.onDestroy() } // [END add_lifecycle_methods] private fun checkIds() { if (TEST_APP_ID == getString(R.string.admob_app_id)) { Log.w(TAG, "Your admob_app_id is not configured correctly, please see the README") } } companion object { private const val TAG = "MainActivity" private const val TEST_APP_ID = "ca-app-pub-3940256099942544~3347511713" } }
apache-2.0
4dda832ec132babaeb08a9c270f9f9cd
32.576389
100
0.64302
4.635666
false
false
false
false
cashapp/sqldelight
dialects/mysql/src/main/kotlin/app/cash/sqldelight/dialects/mysql/ide/MySqlConnectionManager.kt
1
2804
package app.cash.sqldelight.dialects.mysql.ide import app.cash.sqldelight.dialect.api.ConnectionManager import app.cash.sqldelight.dialect.api.ConnectionManager.ConnectionProperties import com.intellij.openapi.project.Project import com.squareup.moshi.JsonClass import com.squareup.moshi.Moshi import java.sql.Connection import java.sql.DriverManager internal class MySqlConnectionManager : ConnectionManager { override fun createNewConnectionProperties( project: Project, prefilledProperties: ConnectionProperties?, ): ConnectionProperties? { val dialog = if (prefilledProperties == null) MySqlConnectionDialog(project) else { val properties = adapter.fromJson(prefilledProperties.serializedProperties)!! MySqlConnectionDialog( project = project, connectionName = prefilledProperties.key, host = properties.host, port = properties.port, databaseName = properties.databaseName ?: "", username = properties.username ?: "", password = properties.password ?: "", ) } if (!dialog.showAndGet()) return null return ConnectionProperties( key = dialog.connectionKey, serializedProperties = adapter.toJson( ConnectionSettings( host = dialog.host, port = dialog.port, databaseName = dialog.databaseName.ifEmpty { null }, username = dialog.username.ifEmpty { null }, password = dialog.password.ifEmpty { null }, ), ), ) } override fun getConnection(connectionProperties: ConnectionProperties): Connection { val settings = adapter.fromJson(connectionProperties.serializedProperties)!! var url = "jdbc:mysql://${settings.host}:${settings.port}" if (settings.databaseName != null) { url += "/${settings.databaseName}" } if (settings.username != null) { url += "?user=${settings.username}&password=${settings.password}" } val previousContextLoader = Thread.currentThread().contextClassLoader return try { // When it iterates the ServiceLoader we want to make sure its on the plugins classpath. Thread.currentThread().contextClassLoader = this::class.java.classLoader Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance() DriverManager.getConnection(url) } finally { Thread.currentThread().contextClassLoader = previousContextLoader } } @JsonClass(generateAdapter = true) internal data class ConnectionSettings( val host: String, val port: String, val databaseName: String?, val username: String?, val password: String?, ) companion object { private val adapter = Moshi.Builder().build() .adapter(ConnectionSettings::class.java) } }
apache-2.0
5e31d65c77df41c57fd410bd217e8c6e
33.617284
94
0.692582
5.0161
false
false
false
false
jitsi/jicofo
jicofo/src/main/kotlin/org/jitsi/jicofo/xmpp/MuteIqHandler.kt
1
5868
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2021 - present 8x8, 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 org.jitsi.jicofo.xmpp import org.jitsi.jicofo.ConferenceStore import org.jitsi.jicofo.TaskPools import org.jitsi.jicofo.conference.MuteResult import org.jitsi.jicofo.xmpp.IqProcessingResult.AcceptedWithNoResponse import org.jitsi.jicofo.xmpp.IqProcessingResult.RejectedWithError import org.jitsi.utils.MediaType import org.jitsi.utils.logging2.LoggerImpl import org.jitsi.xmpp.extensions.jitsimeet.MuteIq import org.jitsi.xmpp.extensions.jitsimeet.MuteVideoIq import org.jivesoftware.smack.AbstractXMPPConnection import org.jivesoftware.smack.iqrequest.IQRequestHandler import org.jivesoftware.smack.packet.IQ import org.jivesoftware.smack.packet.StanzaError import org.jxmpp.jid.Jid class AudioMuteIqHandler( connections: Set<AbstractXMPPConnection>, private val conferenceStore: ConferenceStore ) : AbstractIqHandler<MuteIq>( connections, MuteIq.ELEMENT, MuteIq.NAMESPACE, setOf(IQ.Type.set), IQRequestHandler.Mode.sync ) { override fun handleRequest(request: IqRequest<MuteIq>): IqProcessingResult { return handleRequest( MuteRequest( request.iq, request.connection, conferenceStore, request.iq.mute, request.iq.jid, MediaType.AUDIO ) ) } } class VideoMuteIqHandler( connections: Set<AbstractXMPPConnection>, private val conferenceStore: ConferenceStore ) : AbstractIqHandler<MuteVideoIq>( connections, MuteVideoIq.ELEMENT, MuteVideoIq.NAMESPACE, setOf(IQ.Type.set), IQRequestHandler.Mode.sync ) { override fun handleRequest(request: IqRequest<MuteVideoIq>): IqProcessingResult { return handleRequest( MuteRequest( request.iq, request.connection, conferenceStore, request.iq.mute, request.iq.jid, MediaType.VIDEO ) ) } } private val logger = LoggerImpl("org.jitsi.jicofo.xmpp.MuteIqHandler") private fun handleRequest(request: MuteRequest): IqProcessingResult { val jidToMute = request.jidToMute val doMute = request.doMute val mediaType = request.mediaType if (doMute == null || jidToMute == null) { logger.warn("Mute request missing required fields: ${request.iq.toXML()}") return RejectedWithError(request.iq, StanzaError.Condition.bad_request) } val conference = request.conferenceStore.getConference(request.iq.from.asEntityBareJidIfPossible()) ?: return RejectedWithError(request.iq, StanzaError.Condition.item_not_found).also { logger.warn("Mute request for unknown conference: ${request.iq.toXML()}") } TaskPools.ioPool.execute { try { when (conference.handleMuteRequest(request.iq.from, jidToMute, doMute, mediaType)) { MuteResult.SUCCESS -> { request.connection.tryToSendStanza(IQ.createResultIQ(request.iq)) // If this was a remote mute, notify the participant that was muted. if (request.iq.from != request.jidToMute) { request.connection.tryToSendStanza( if (request.mediaType == MediaType.AUDIO) MuteIq().apply { actor = request.iq.from type = IQ.Type.set to = request.jidToMute mute = request.doMute } else MuteVideoIq().apply { actor = request.iq.from type = IQ.Type.set to = request.jidToMute mute = request.doMute } ) } } MuteResult.NOT_ALLOWED -> request.connection.tryToSendStanza( IQ.createErrorResponse( request.iq, StanzaError.getBuilder(StanzaError.Condition.not_allowed).build() ) ) MuteResult.ERROR -> request.connection.tryToSendStanza( IQ.createErrorResponse( request.iq, StanzaError.getBuilder(StanzaError.Condition.internal_server_error).build() ) ) } } catch (e: Exception) { logger.warn("Failed to handle mute request: ${request.iq.toXML()}", e) request.connection.tryToSendStanza( IQ.createErrorResponse(request.iq, StanzaError.Condition.internal_server_error) ) } } return AcceptedWithNoResponse() } private data class MuteRequest( val iq: IQ, val connection: AbstractXMPPConnection, val conferenceStore: ConferenceStore, val doMute: Boolean?, val jidToMute: Jid?, val mediaType: MediaType )
apache-2.0
1870710ea4cf7e31cbf61eafc636d8ef
36.375796
103
0.595092
4.881864
false
false
false
false
niranjan94/show-java
app/src/main/kotlin/com/njlabs/showjava/activities/explorer/viewer/ImageViewerActivity.kt
1
3989
/* * Show Java - A java/apk decompiler for android * Copyright (c) 2018 Niranjan Rajendran * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.njlabs.showjava.activities.explorer.viewer import android.graphics.Color import android.os.Bundle import android.os.Environment import android.view.Menu import android.view.MenuItem import com.davemorrissey.labs.subscaleview.ImageSource import com.davemorrissey.labs.subscaleview.ImageViewState import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView import com.njlabs.showjava.R import com.njlabs.showjava.activities.BaseActivity import kotlinx.android.synthetic.main.activity_image_viewer.* import org.apache.commons.io.FilenameUtils class ImageViewerActivity : BaseActivity() { private var isBlack: Boolean = true private val bundleState = "ImageViewState" override fun init(savedInstanceState: Bundle?) { setupLayout(R.layout.activity_image_viewer) window.decorView.setBackgroundColor(Color.BLACK) toolbar.popupTheme = R.style.AppTheme_DarkPopupOverlay val extras = intent.extras extras?.let { var imageViewState: ImageViewState? = null if (savedInstanceState != null && savedInstanceState.containsKey(bundleState)) { imageViewState = savedInstanceState.getSerializable(bundleState) as ImageViewState } val filePath = it.getString("filePath") val packageName = it.getString("name") val fileName = FilenameUtils.getName(filePath) supportActionBar?.title = fileName val subtitle = FilenameUtils .getFullPath(filePath) .replace( "${Environment.getExternalStorageDirectory()}/show-java/sources/$packageName/", "" ) if (fileName.trim().equals("icon.png", true)) { setSubtitle(packageName) } else { setSubtitle(subtitle) } imageView.setImage(ImageSource.uri(filePath!!), imageViewState) imageView.orientation = SubsamplingScaleImageView.ORIENTATION_USE_EXIF imageView.setPanLimit(SubsamplingScaleImageView.PAN_LIMIT_CENTER) imageView.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CUSTOM) imageView.setMinimumDpi(100) imageView.setMaximumDpi(600) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_main, menu) menu.findItem(R.id.invert_colors).isVisible = true return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.invert_colors -> { if (isBlack) { window.decorView.setBackgroundColor(Color.WHITE) } else { window.decorView.setBackgroundColor(Color.BLACK) } isBlack = !isBlack return true } } return super.onOptionsItemSelected(item) } public override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) val state = imageView.state if (state != null) { outState.putSerializable(bundleState, imageView.state) } } }
gpl-3.0
2413ba4afe34408ae29973a5c4e7d5d8
36.28972
99
0.66533
4.949132
false
false
false
false
kjkrol/kotlin4fun-eshop-app
ordering-service/src/main/kotlin/kotlin4fun/eshop/ordering/order/util/Extensions.kt
1
924
package kotlin4fun.eshop.ordering.order.util import kotlin4fun.eshop.ordering.order.Order import kotlin4fun.eshop.ordering.order.OrderDto import kotlin4fun.eshop.ordering.order.create.PlaceOrderRequest import kotlin4fun.eshop.ordering.order.item.OrderItem import kotlin4fun.eshop.ordering.order.item.OrderItemDto import kotlin4fun.eshop.ordering.order.item.create.OrderItemRequest import java.util.UUID internal fun Order.toDto() = OrderDto(id = this.id, totalPrice = this.totalPrice, customerId = this.customerId) internal fun PlaceOrderRequest.toEntity(totalPrice: Double): Order = Order(customerId = this.customerId, totalPrice = totalPrice) internal fun OrderItemRequest.toEntity(orderId: UUID): OrderItem = OrderItem(orderId = orderId, productId = this.productId, quantity = this.quantity) internal fun OrderItem.toDto() = OrderItemDto(orderId = this.orderId, productId = this.productId, quantity = this.quantity)
apache-2.0
a49404a1277763c36e402e94bfe858c6
53.352941
149
0.822511
3.786885
false
false
false
false
matejdro/WearMusicCenter
wear/src/main/java/com/matejdro/wearmusiccenter/watch/communication/IconGetter.kt
1
1234
package com.matejdro.wearmusiccenter.watch.communication import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import androidx.core.content.res.ResourcesCompat import com.google.android.gms.wearable.DataClient import com.google.android.gms.wearable.DataItem import com.matejdro.wearmusiccenter.common.actions.StandardIcons import com.matejdro.wearutils.messages.getByteArrayAsset import com.matejdro.wearutils.miscutils.BitmapUtils suspend fun DataClient.getIcon(dataItem: DataItem, iconKey: String, actionKey: String): Drawable? { val resources = this.applicationContext.resources if (dataItem.assets.containsKey(iconKey)) { // We have override custom icon. Lets use that val iconAsset = dataItem.assets[iconKey] val iconBitmap = BitmapUtils.deserialize(iconAsset?.let { this.getByteArrayAsset(it) }) return BitmapDrawable(resources, iconBitmap) } // We did not receive icon via bluetooth. Check if it is one of the standard icons // that we have pre-stored on the watch val iconRes = StandardIcons.getIcon(actionKey) if (iconRes == 0) { return null } return ResourcesCompat.getDrawable(resources, iconRes, null) }
gpl-3.0
3a3a133350e672437dc467b33c2eea79
38.806452
99
0.769044
4.407143
false
false
false
false
exponent/exponent
packages/expo-dev-menu/android/src/main/java/expo/modules/devmenu/helpers/DevMenuReflectionExtensions.kt
2
710
package expo.modules.devmenu.helpers import java.lang.reflect.Field import java.lang.reflect.Modifier @Suppress("UNCHECKED_CAST") fun <T, R> Class<out T>.getPrivateDeclaredFieldValue(filedName: String, obj: T): R { val field = getDeclaredField(filedName) field.isAccessible = true return field.get(obj) as R } fun <T> Class<out T>.setPrivateDeclaredFieldValue(filedName: String, obj: T, newValue: Any) { val field = getDeclaredField(filedName) val modifiersField = Field::class.java.getDeclaredField("accessFlags") field.isAccessible = true modifiersField.isAccessible = true modifiersField.setInt( field, field.modifiers and Modifier.FINAL.inv() ) field.set(obj, newValue) }
bsd-3-clause
a983f97dd43e70f389e6a163d793ad93
26.307692
93
0.752113
3.659794
false
false
false
false
Code-Tome/hexameter
mixite.core/src/commonTest/kotlin/org/hexworks/mixite/core/internal/impl/layoutstrategy/HexagonalGridLayoutStrategyTest.kt
2
8895
package org.hexworks.mixite.core.internal.impl.layoutstrategy import org.hexworks.mixite.core.GridLayoutStrategyTestUtil.fetchDefaultBuilder import org.hexworks.mixite.core.api.CubeCoordinate import org.hexworks.mixite.core.api.CubeCoordinate.Companion.fromCoordinates import org.hexworks.mixite.core.api.HexagonOrientation.FLAT_TOP import org.hexworks.mixite.core.api.HexagonalGridBuilder import org.hexworks.mixite.core.api.contract.SatelliteData import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertFalse import kotlin.test.assertTrue class HexagonalGridLayoutStrategyTest { private lateinit var target: HexagonalGridLayoutStrategy private lateinit var builder: HexagonalGridBuilder<out SatelliteData> @BeforeTest fun setUp() { builder = fetchDefaultBuilder() target = HexagonalGridLayoutStrategy() } @Test fun shouldProperlyCreateHexagonsWithPointyOrientationWhenCreateHexagonsIsCalled() { val coordIter = target.fetchGridCoordinates(builder).iterator() val coords = ArrayList<CubeCoordinate>() while (coordIter.hasNext()) { coords.add(coordIter.next()) } assertTrue(coords.contains(fromCoordinates(1, 0))) assertTrue(coords.contains(fromCoordinates(2, 0))) assertTrue(coords.contains(fromCoordinates(2, 1))) assertTrue(coords.contains(fromCoordinates(1, 2))) assertTrue(coords.contains(fromCoordinates(0, 2))) assertTrue(coords.contains(fromCoordinates(0, 1))) assertTrue(!coords.contains(fromCoordinates(0, 0))) assertTrue(!coords.contains(fromCoordinates(1, -1))) assertTrue(!coords.contains(fromCoordinates(2, -1))) assertTrue(!coords.contains(fromCoordinates(3, -1))) assertTrue(!coords.contains(fromCoordinates(3, 0))) assertTrue(!coords.contains(fromCoordinates(3, 1))) assertTrue(!coords.contains(fromCoordinates(2, 2))) assertTrue(!coords.contains(fromCoordinates(1, 3))) assertTrue(!coords.contains(fromCoordinates(0, 3))) assertTrue(!coords.contains(fromCoordinates(-1, 3))) assertTrue(!coords.contains(fromCoordinates(-1, 2))) assertTrue(!coords.contains(fromCoordinates(-1, 1))) } @Test fun shouldProperlyCreateHexagonsWithPointyOrientationWhenCreateHexagonsIsCalledWithBiggerSize() { builder.setGridHeight(5).setGridWidth(5) val coordIter = target.fetchGridCoordinates(builder).iterator() val coords = ArrayList<CubeCoordinate>() while (coordIter.hasNext()) { coords.add(coordIter.next()) } assertTrue(coords.contains(fromCoordinates(1, 0))) assertTrue(coords.contains(fromCoordinates(2, 0))) assertTrue(coords.contains(fromCoordinates(3, 0))) assertTrue(coords.contains(fromCoordinates(3, 1))) assertTrue(coords.contains(fromCoordinates(3, 2))) assertTrue(coords.contains(fromCoordinates(2, 3))) assertTrue(coords.contains(fromCoordinates(1, 4))) assertTrue(coords.contains(fromCoordinates(0, 4))) assertTrue(coords.contains(fromCoordinates(-1, 4))) assertTrue(coords.contains(fromCoordinates(-1, 3))) assertTrue(coords.contains(fromCoordinates(-1, 2))) assertTrue(coords.contains(fromCoordinates(0, 1))) assertTrue(!coords.contains(fromCoordinates(0, 0))) assertTrue(!coords.contains(fromCoordinates(1, -1))) assertTrue(!coords.contains(fromCoordinates(2, -1))) assertTrue(!coords.contains(fromCoordinates(3, -1))) assertTrue(!coords.contains(fromCoordinates(4, -1))) assertTrue(!coords.contains(fromCoordinates(4, 0))) assertTrue(!coords.contains(fromCoordinates(4, 1))) assertTrue(!coords.contains(fromCoordinates(4, 2))) assertTrue(!coords.contains(fromCoordinates(3, 3))) assertTrue(!coords.contains(fromCoordinates(2, 4))) assertTrue(!coords.contains(fromCoordinates(1, 5))) assertTrue(!coords.contains(fromCoordinates(0, 5))) assertTrue(!coords.contains(fromCoordinates(-1, 5))) assertTrue(!coords.contains(fromCoordinates(-2, 5))) assertTrue(!coords.contains(fromCoordinates(-2, 4))) assertTrue(!coords.contains(fromCoordinates(-2, 3))) assertTrue(!coords.contains(fromCoordinates(-2, 2))) assertTrue(!coords.contains(fromCoordinates(-1, 1))) } @Test fun shouldProperlyCreateHexagonsWithFlatOrientationWhenCreateHexagonsIsCalled() { builder.setOrientation(FLAT_TOP) val coordIter = target.fetchGridCoordinates(builder).iterator() val coords = ArrayList<CubeCoordinate>() while (coordIter.hasNext()) { coords.add(coordIter.next()) } assertTrue(coords.contains(fromCoordinates(1, 0))) assertTrue(coords.contains(fromCoordinates(2, 0))) assertTrue(coords.contains(fromCoordinates(2, 1))) assertTrue(coords.contains(fromCoordinates(1, 2))) assertTrue(coords.contains(fromCoordinates(0, 2))) assertTrue(coords.contains(fromCoordinates(0, 1))) assertTrue(!coords.contains(fromCoordinates(0, 0))) assertTrue(!coords.contains(fromCoordinates(0, -1))) assertTrue(!coords.contains(fromCoordinates(2, -1))) assertTrue(!coords.contains(fromCoordinates(3, -1))) assertTrue(!coords.contains(fromCoordinates(3, 0))) assertTrue(!coords.contains(fromCoordinates(3, 1))) assertTrue(!coords.contains(fromCoordinates(2, 2))) assertTrue(!coords.contains(fromCoordinates(1, 3))) assertTrue(!coords.contains(fromCoordinates(0, 3))) assertTrue(!coords.contains(fromCoordinates(-1, 3))) assertTrue(!coords.contains(fromCoordinates(-1, 2))) assertTrue(!coords.contains(fromCoordinates(-1, 1))) } @Test fun shouldProperlyCreateHexagonsWithFlatOrientationWhenCreateHexagonsIsCalledWithBiggerSize() { builder.setGridHeight(5).setGridWidth(5).setOrientation(FLAT_TOP) val coordIter = target.fetchGridCoordinates(builder).iterator() val coords = ArrayList<CubeCoordinate>() while (coordIter.hasNext()) { coords.add(coordIter.next()) } assertTrue(coords.contains(fromCoordinates(2, -1))) assertTrue(coords.contains(fromCoordinates(3, -1))) assertTrue(coords.contains(fromCoordinates(4, -1))) assertTrue(coords.contains(fromCoordinates(4, 0))) assertTrue(coords.contains(fromCoordinates(4, 1))) assertTrue(coords.contains(fromCoordinates(3, 2))) assertTrue(coords.contains(fromCoordinates(2, 3))) assertTrue(coords.contains(fromCoordinates(1, 3))) assertTrue(coords.contains(fromCoordinates(0, 3))) assertTrue(coords.contains(fromCoordinates(0, 2))) assertTrue(coords.contains(fromCoordinates(0, 1))) assertTrue(coords.contains(fromCoordinates(1, 0))) assertTrue(!coords.contains(fromCoordinates(0, 0))) assertTrue(!coords.contains(fromCoordinates(1, -1))) assertTrue(!coords.contains(fromCoordinates(2, -2))) assertTrue(!coords.contains(fromCoordinates(3, -2))) assertTrue(!coords.contains(fromCoordinates(4, -2))) assertTrue(!coords.contains(fromCoordinates(5, -2))) assertTrue(!coords.contains(fromCoordinates(5, -1))) assertTrue(!coords.contains(fromCoordinates(5, 0))) assertTrue(!coords.contains(fromCoordinates(5, 1))) assertTrue(!coords.contains(fromCoordinates(4, 2))) assertTrue(!coords.contains(fromCoordinates(3, 3))) assertTrue(!coords.contains(fromCoordinates(2, 4))) assertTrue(!coords.contains(fromCoordinates(1, 4))) assertTrue(!coords.contains(fromCoordinates(0, 4))) assertTrue(!coords.contains(fromCoordinates(-1, 4))) assertTrue(!coords.contains(fromCoordinates(-1, 3))) assertTrue(!coords.contains(fromCoordinates(-1, 2))) assertTrue(!coords.contains(fromCoordinates(-1, 1))) } @Test fun testCheckParameters0() { val result = target.checkParameters(1, 1) // super: true, derived: true assertTrue(result) } @Test fun testCheckParameters1() { val result = target.checkParameters(1, 2) // super: true, derived: false assertFalse(result) } @Test fun testCheckParameters2() { val result = target.checkParameters(2, 2) // super: true, derived: false assertFalse(result) } @Test fun testCheckParameters3() { val result = target.checkParameters(0, 0) // super: false, derived: false; assertFalse(result) } @Test fun testCheckParameters4() { val result = target.checkParameters(-1, -1) // super: false, derived: true; assertFalse(result) } }
mit
b0cbb6d82e1ead011bccee27d56c7b0d
42.602941
101
0.687915
4.515228
false
true
false
false
vimeo/vimeo-networking-java
request/src/main/java/com/vimeo/networking2/internal/MutableVimeoApiClientDelegate.kt
1
39547
/* * Copyright (c) 2020 Vimeo (https://vimeo.com) * * 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.vimeo.networking2.internal import com.vimeo.networking2.Album import com.vimeo.networking2.AlbumList import com.vimeo.networking2.AlbumPrivacy import com.vimeo.networking2.AppConfiguration import com.vimeo.networking2.Capabilities import com.vimeo.networking2.Category import com.vimeo.networking2.CategoryList import com.vimeo.networking2.Channel import com.vimeo.networking2.ChannelList import com.vimeo.networking2.Comment import com.vimeo.networking2.CommentList import com.vimeo.networking2.ConnectedApp import com.vimeo.networking2.ConnectedAppList import com.vimeo.networking2.Document import com.vimeo.networking2.FeedList import com.vimeo.networking2.Folder import com.vimeo.networking2.FolderList import com.vimeo.networking2.LiveEvent import com.vimeo.networking2.LiveEventList import com.vimeo.networking2.LiveStats import com.vimeo.networking2.NotificationList import com.vimeo.networking2.NotificationSubscriptions import com.vimeo.networking2.PermissionPolicy import com.vimeo.networking2.PermissionPolicyList import com.vimeo.networking2.PictureCollection import com.vimeo.networking2.Product import com.vimeo.networking2.ProductList import com.vimeo.networking2.ProgrammedCinemaItemList import com.vimeo.networking2.ProjectItemList import com.vimeo.networking2.PublishJob import com.vimeo.networking2.RecommendationList import com.vimeo.networking2.SearchResultList import com.vimeo.networking2.SeasonList import com.vimeo.networking2.StreamPrivacy import com.vimeo.networking2.Team import com.vimeo.networking2.TeamEntity import com.vimeo.networking2.TeamList import com.vimeo.networking2.TeamMembership import com.vimeo.networking2.TeamMembershipList import com.vimeo.networking2.TeamPermission import com.vimeo.networking2.TeamPermissionCurrentPermissions import com.vimeo.networking2.TeamPermissionInteraction import com.vimeo.networking2.TeamPermissionList import com.vimeo.networking2.TextTrackList import com.vimeo.networking2.TvodItem import com.vimeo.networking2.TvodItemList import com.vimeo.networking2.User import com.vimeo.networking2.UserList import com.vimeo.networking2.UserSegmentSurveyList import com.vimeo.networking2.Video import com.vimeo.networking2.VideoList import com.vimeo.networking2.VideoStatus import com.vimeo.networking2.VimeoApiClient import com.vimeo.networking2.VimeoCallback import com.vimeo.networking2.VimeoRequest import com.vimeo.networking2.common.Followable import com.vimeo.networking2.enums.CommentPrivacyType import com.vimeo.networking2.enums.ConnectedAppType import com.vimeo.networking2.enums.EmbedPrivacyType import com.vimeo.networking2.enums.FolderViewPrivacyType import com.vimeo.networking2.enums.NotificationType import com.vimeo.networking2.enums.SlackLanguagePreferenceType import com.vimeo.networking2.enums.SlackUserPreferenceType import com.vimeo.networking2.enums.TeamEntityType import com.vimeo.networking2.enums.TeamRoleType import com.vimeo.networking2.enums.ViewPrivacyType import com.vimeo.networking2.params.BatchPublishToSocialMedia import com.vimeo.networking2.params.ModifyVideoInAlbumsSpecs import com.vimeo.networking2.params.ModifyVideosInAlbumSpecs import com.vimeo.networking2.params.SearchDateType import com.vimeo.networking2.params.SearchDurationType import com.vimeo.networking2.params.SearchFacetType import com.vimeo.networking2.params.SearchFilterType import com.vimeo.networking2.params.SearchSortDirectionType import com.vimeo.networking2.params.SearchSortType import okhttp3.CacheControl /** * A [VimeoApiClient] that delegates its implementation to an internal mutable instance [actual]. The purpose of this * class is to allow the [VimeoApiClient] instance to be re-initialized on the fly. It delegates to an underlying actual * implementation that can be changed dynamically. This allows the [VimeoApiClient.initialize] function to change the * implementation used without changing the reference returned by [VimeoApiClient.instance]. * * @param actual The actual implementation of [VimeoApiClient], defaults to null. */ @Suppress("LargeClass") internal class MutableVimeoApiClientDelegate(var actual: VimeoApiClient? = null) : VimeoApiClient { private val client: VimeoApiClient get() = actual ?: error("Must call VimeoApiClient.initialize() before calling VimeoApiClient.instance()") override fun createAlbum( uri: String, name: String, albumPrivacy: AlbumPrivacy, description: String?, bodyParams: Map<String, Any>?, callback: VimeoCallback<Album> ): VimeoRequest = client.createAlbum(uri, name, albumPrivacy, description, bodyParams, callback) override fun createAlbum( user: User, name: String, albumPrivacy: AlbumPrivacy, description: String?, bodyParams: Map<String, Any>?, callback: VimeoCallback<Album> ): VimeoRequest = client.createAlbum(user, name, albumPrivacy, description, bodyParams, callback) override fun editAlbum( album: Album, name: String, albumPrivacy: AlbumPrivacy, description: String?, bodyParams: Map<String, Any>?, callback: VimeoCallback<Album> ): VimeoRequest = client.editAlbum(album, name, albumPrivacy, description, bodyParams, callback) override fun editAlbum( uri: String, name: String, albumPrivacy: AlbumPrivacy, description: String?, bodyParams: Map<String, Any>?, callback: VimeoCallback<Album> ): VimeoRequest = client.editAlbum(uri, name, albumPrivacy, description, bodyParams, callback) override fun deleteAlbum(album: Album, callback: VimeoCallback<Unit>): VimeoRequest = client.deleteAlbum(album, callback) override fun addToAlbum(album: Album, video: Video, callback: VimeoCallback<Unit>): VimeoRequest = client.addToAlbum(album, video, callback) override fun addToAlbum(albumUri: String, videoUri: String, callback: VimeoCallback<Unit>): VimeoRequest = client.addToAlbum(albumUri, videoUri, callback) override fun removeFromAlbum(album: Album, video: Video, callback: VimeoCallback<Unit>): VimeoRequest = client.removeFromAlbum(album, video, callback) override fun removeFromAlbum(albumUri: String, videoUri: String, callback: VimeoCallback<Unit>): VimeoRequest = client.removeFromAlbum(albumUri, videoUri, callback) override fun modifyVideosInAlbum( album: Album, modificationSpecs: ModifyVideosInAlbumSpecs, callback: VimeoCallback<VideoList> ): VimeoRequest = client.modifyVideosInAlbum(album, modificationSpecs, callback) override fun modifyVideosInAlbum( uri: String, modificationSpecs: ModifyVideosInAlbumSpecs, callback: VimeoCallback<VideoList> ): VimeoRequest = client.modifyVideosInAlbum(uri, modificationSpecs, callback) override fun modifyVideoInAlbums( video: Video, modificationSpecs: ModifyVideoInAlbumsSpecs, callback: VimeoCallback<AlbumList> ): VimeoRequest = client.modifyVideoInAlbums(video, modificationSpecs, callback) override fun modifyVideoInAlbums( uri: String, modificationSpecs: ModifyVideoInAlbumsSpecs, callback: VimeoCallback<AlbumList> ): VimeoRequest = client.modifyVideoInAlbums(uri, modificationSpecs, callback) override fun editVideo( uri: String, title: String?, description: String?, password: String?, commentPrivacyType: CommentPrivacyType?, allowDownload: Boolean?, allowAddToCollections: Boolean?, embedPrivacyType: EmbedPrivacyType?, viewPrivacyType: ViewPrivacyType?, bodyParams: Map<String, Any>?, callback: VimeoCallback<Video> ): VimeoRequest = client.editVideo( uri, title, description, password, commentPrivacyType, allowDownload, allowAddToCollections, embedPrivacyType, viewPrivacyType, bodyParams, callback ) override fun editVideo( video: Video, title: String?, description: String?, password: String?, commentPrivacyType: CommentPrivacyType?, allowDownload: Boolean?, allowAddToCollections: Boolean?, embedPrivacyType: EmbedPrivacyType?, viewPrivacyType: ViewPrivacyType?, bodyParams: Map<String, Any>?, callback: VimeoCallback<Video> ): VimeoRequest = client.editVideo( video, title, description, password, commentPrivacyType, allowDownload, allowAddToCollections, embedPrivacyType, viewPrivacyType, bodyParams, callback ) override fun editUser( uri: String, name: String?, location: String?, bio: String?, callback: VimeoCallback<User> ): VimeoRequest = client.editUser(uri, name, location, bio, callback) override fun editUser( user: User, name: String?, location: String?, bio: String?, callback: VimeoCallback<User> ): VimeoRequest = client.editUser(user, name, location, bio, callback) override fun editSubscriptions( subscriptionMap: Map<NotificationType, Boolean>, callback: VimeoCallback<NotificationSubscriptions> ): VimeoRequest = client.editSubscriptions(subscriptionMap, callback) override fun fetchConnectedApps( fieldFilter: String?, cacheControl: CacheControl?, callback: VimeoCallback<ConnectedAppList> ): VimeoRequest = client.fetchConnectedApps(fieldFilter, cacheControl, callback) override fun fetchConnectedApp( type: ConnectedAppType, fieldFilter: String?, cacheControl: CacheControl?, callback: VimeoCallback<ConnectedApp> ): VimeoRequest = client.fetchConnectedApp(type, fieldFilter, cacheControl, callback) override fun createConnectedApp( type: ConnectedAppType, authorization: String, clientId: String, callback: VimeoCallback<ConnectedApp> ): VimeoRequest = client.createConnectedApp(type, authorization, clientId, callback) override fun deleteConnectedApp(type: ConnectedAppType, callback: VimeoCallback<Unit>): VimeoRequest = client.deleteConnectedApp(type, callback) override fun createFolder( uri: String, parentFolderUri: String?, name: String, privacy: FolderViewPrivacyType, slackWebhookId: String?, slackLanguagePreference: SlackLanguagePreferenceType?, slackUserPreference: SlackUserPreferenceType?, callback: VimeoCallback<Folder> ): VimeoRequest = client.createFolder( uri, parentFolderUri, name, privacy, slackWebhookId, slackLanguagePreference, slackUserPreference, callback ) override fun createFolder( user: User, parentFolder: Folder?, name: String, privacy: FolderViewPrivacyType, slackWebhookId: String?, slackLanguagePreference: SlackLanguagePreferenceType?, slackUserPreference: SlackUserPreferenceType?, callback: VimeoCallback<Folder> ): VimeoRequest = client.createFolder( user, parentFolder, name, privacy, slackWebhookId, slackLanguagePreference, slackUserPreference, callback ) override fun deleteFolder(folder: Folder, shouldDeleteClips: Boolean, callback: VimeoCallback<Unit>): VimeoRequest = client.deleteFolder(folder, shouldDeleteClips, callback) override fun editFolder( uri: String, name: String, privacy: FolderViewPrivacyType, slackWebhookId: String?, slackLanguagePreference: SlackLanguagePreferenceType?, slackUserPreference: SlackUserPreferenceType?, callback: VimeoCallback<Folder> ): VimeoRequest = client.editFolder( uri, name, privacy, slackWebhookId, slackLanguagePreference, slackUserPreference, callback ) override fun editFolder( folder: Folder, name: String, privacy: FolderViewPrivacyType, slackWebhookId: String?, slackLanguagePreference: SlackLanguagePreferenceType?, slackUserPreference: SlackUserPreferenceType?, callback: VimeoCallback<Folder> ): VimeoRequest = client.editFolder( folder, name, privacy, slackWebhookId, slackLanguagePreference, slackUserPreference, callback ) override fun addToFolder(folder: Folder, video: Video, callback: VimeoCallback<Unit>): VimeoRequest = client.addToFolder(folder, video, callback) override fun addToFolder(folderUri: String, videoUri: String, callback: VimeoCallback<Unit>): VimeoRequest = client.addToFolder(folderUri, videoUri, callback) override fun removeFromFolder(folder: Folder, video: Video, callback: VimeoCallback<Unit>): VimeoRequest = client.removeFromFolder(folder, video, callback) override fun removeFromFolder(folderUri: String, videoUri: String, callback: VimeoCallback<Unit>): VimeoRequest = client.removeFromFolder(folderUri, videoUri, callback) override fun fetchPublishJob( uri: String, fieldFilter: String?, cacheControl: CacheControl?, callback: VimeoCallback<PublishJob> ): VimeoRequest = client.fetchPublishJob(uri, fieldFilter, cacheControl, callback) override fun putPublishJob( uri: String, publishData: BatchPublishToSocialMedia, callback: VimeoCallback<PublishJob> ): VimeoRequest = client.putPublishJob(uri, publishData, callback) override fun putPublishJob( video: Video, publishData: BatchPublishToSocialMedia, callback: VimeoCallback<PublishJob> ): VimeoRequest = client.putPublishJob(video, publishData, callback) override fun fetchTermsOfService(cacheControl: CacheControl?, callback: VimeoCallback<Document>): VimeoRequest = client.fetchTermsOfService(cacheControl, callback) override fun fetchPrivacyPolicy(cacheControl: CacheControl?, callback: VimeoCallback<Document>): VimeoRequest = client.fetchPrivacyPolicy(cacheControl, callback) override fun fetchPaymentAddendum(cacheControl: CacheControl?, callback: VimeoCallback<Document>): VimeoRequest = client.fetchPaymentAddendum(cacheControl, callback) override fun fetchDocument( uri: String, cacheControl: CacheControl?, callback: VimeoCallback<Document> ): VimeoRequest = client.fetchDocument(uri, cacheControl, callback) override fun fetchFolder( uri: String, fieldFilter: String?, cacheControl: CacheControl?, callback: VimeoCallback<Folder> ): VimeoRequest = client.fetchFolder(uri, fieldFilter, cacheControl, callback) override fun fetchFolderList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<FolderList> ): VimeoRequest = client.fetchFolderList(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchTextTrackList( uri: String, fieldFilter: String?, cacheControl: CacheControl?, callback: VimeoCallback<TextTrackList> ): VimeoRequest = client.fetchTextTrackList(uri, fieldFilter, cacheControl, callback) override fun fetchVideoStatus( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<VideoStatus> ): VimeoRequest = client.fetchVideoStatus(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchTeamMembersList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<TeamMembershipList> ): VimeoRequest = client.fetchTeamMembersList(uri, fieldFilter, queryParams, cacheControl, callback) override fun acceptTeamInvite(code: String, callback: VimeoCallback<TeamMembership>): VimeoRequest = client.acceptTeamInvite(code, callback) override fun addUserToTeam( uri: String, email: String, permissionLevel: TeamRoleType, folderUri: String?, customMessage: String?, queryParams: Map<String, String>?, callback: VimeoCallback<TeamMembership> ): VimeoRequest = client.addUserToTeam(uri, email, permissionLevel, folderUri, customMessage, queryParams, callback) override fun addUserToTeam( team: Team, email: String, permissionLevel: TeamRoleType, folder: Folder?, customMessage: String?, queryParams: Map<String, String>?, callback: VimeoCallback<TeamMembership> ): VimeoRequest = client.addUserToTeam(team, email, permissionLevel, folder, customMessage, queryParams, callback) override fun addUserToVideoAsMember( team: Team, email: String, permissionLevel: TeamRoleType, videoUri: String?, customMessage: String?, queryParams: Map<String, String>?, callback: VimeoCallback<TeamMembership> ): VimeoRequest = client.addUserToVideoAsMember( team, email, permissionLevel, videoUri, customMessage, queryParams, callback ) override fun removeUserFromTeam( uri: String, queryParams: Map<String, String>?, callback: VimeoCallback<Unit> ): VimeoRequest = client.removeUserFromTeam(uri, queryParams, callback) override fun removeUserFromTeam( membership: TeamMembership, queryParams: Map<String, String>?, callback: VimeoCallback<Unit> ): VimeoRequest = client.removeUserFromTeam(membership, queryParams, callback) override fun changeUserRole( uri: String, role: TeamRoleType, folderUri: String?, queryParams: Map<String, String>?, callback: VimeoCallback<TeamMembership> ): VimeoRequest = client.changeUserRole(uri, role, folderUri, queryParams, callback) override fun changeUserRole( membership: TeamMembership, role: TeamRoleType, folder: Folder?, queryParams: Map<String, String>?, callback: VimeoCallback<TeamMembership> ): VimeoRequest = client.changeUserRole(membership, role, folder, queryParams, callback) override fun grantTeamMembersFolderAccess( uri: String, teamMemberIds: List<String>, queryParams: Map<String, String>?, callback: VimeoCallback<Unit> ): VimeoRequest = client.grantTeamMembersFolderAccess(uri, teamMemberIds, queryParams, callback) override fun fetchEmpty( uri: String, cacheControl: CacheControl?, callback: VimeoCallback<Unit> ): VimeoRequest = client.fetchEmpty(uri, cacheControl, callback) override fun grantTeamMembersFolderAccess( folder: Folder, teamMembers: List<TeamMembership>, queryParams: Map<String, String>?, callback: VimeoCallback<Unit> ): VimeoRequest = client.grantTeamMembersFolderAccess(folder, teamMembers, queryParams, callback) override fun search( query: String, searchFilterType: SearchFilterType, fieldFilter: String?, searchSortType: SearchSortType?, searchSortDirectionType: SearchSortDirectionType?, searchDateType: SearchDateType?, searchDurationType: SearchDurationType?, searchFacetTypes: List<SearchFacetType>?, category: String?, featuredVideoCount: Int?, containerFieldFilter: String?, queryParams: Map<String, String>?, callback: VimeoCallback<SearchResultList> ): VimeoRequest = client.search( query, searchFilterType, fieldFilter, searchSortType, searchSortDirectionType, searchDateType, searchDurationType, searchFacetTypes, category, featuredVideoCount, containerFieldFilter, queryParams, callback ) override fun createPictureCollection(uri: String, callback: VimeoCallback<PictureCollection>): VimeoRequest = client.createPictureCollection(uri, callback) override fun activatePictureCollection(uri: String, callback: VimeoCallback<PictureCollection>): VimeoRequest = client.activatePictureCollection(uri, callback) override fun activatePictureCollection( pictureCollection: PictureCollection, callback: VimeoCallback<PictureCollection> ): VimeoRequest = client.activatePictureCollection(pictureCollection, callback) override fun updateFollow(isFollowing: Boolean, uri: String, callback: VimeoCallback<Unit>): VimeoRequest = client.updateFollow(isFollowing, uri, callback) override fun updateFollow( isFollowing: Boolean, followable: Followable, callback: VimeoCallback<Unit> ): VimeoRequest = client.updateFollow(isFollowing, followable, callback) override fun updateVideoLike( isLiked: Boolean, uri: String, password: String?, callback: VimeoCallback<Unit> ): VimeoRequest = client.updateVideoLike(isLiked, uri, password, callback) override fun updateVideoLike( isLiked: Boolean, video: Video, password: String?, callback: VimeoCallback<Unit> ): VimeoRequest = client.updateVideoLike(isLiked, video, password, callback) override fun updateVideoWatchLater( isWatchLater: Boolean, uri: String, password: String?, callback: VimeoCallback<Unit> ): VimeoRequest = client.updateVideoWatchLater(isWatchLater, uri, password, callback) override fun updateVideoWatchLater( isWatchLater: Boolean, video: Video, password: String?, callback: VimeoCallback<Unit> ): VimeoRequest = client.updateVideoWatchLater(isWatchLater, video, password, callback) override fun createComment( uri: String, comment: String, password: String?, callback: VimeoCallback<Comment> ): VimeoRequest = client.createComment(uri, comment, password, callback) override fun createComment( video: Video, comment: String, password: String?, callback: VimeoCallback<Comment> ): VimeoRequest = client.createComment(video, comment, password, callback) override fun fetchProductList( fieldFilter: String?, cacheControl: CacheControl?, callback: VimeoCallback<ProductList> ): VimeoRequest = client.fetchProductList(fieldFilter, cacheControl, callback) override fun fetchProduct( uri: String, fieldFilter: String?, cacheControl: CacheControl?, callback: VimeoCallback<Product> ): VimeoRequest = client.fetchProduct(uri, fieldFilter, cacheControl, callback) override fun fetchCurrentUser( fieldFilter: String?, cacheControl: CacheControl?, callback: VimeoCallback<User> ): VimeoRequest = client.fetchCurrentUser(fieldFilter, cacheControl, callback) override fun fetchSurveyQuestionList( fieldFilter: String?, cacheControl: CacheControl?, callback: VimeoCallback<UserSegmentSurveyList> ): VimeoRequest = client.fetchSurveyQuestionList(fieldFilter, cacheControl, callback) override fun fetchVideo( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<Video> ): VimeoRequest = client.fetchVideo(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchLiveEvent( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<LiveEvent> ): VimeoRequest = client.fetchLiveEvent(uri, fieldFilter, queryParams, cacheControl, callback) override fun createLiveEvent( uri: String, title: String, privacy: StreamPrivacy?, bodyParams: Map<String, Any>?, callback: VimeoCallback<LiveEvent> ): VimeoRequest = client.createLiveEvent(uri, title, privacy, bodyParams, callback) override fun stopLiveEvent(uri: String, callback: VimeoCallback<Video>): VimeoRequest = client.stopLiveEvent(uri, callback) override fun fetchLiveEventList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<LiveEventList> ): VimeoRequest = client.fetchLiveEventList(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchLiveStats( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<LiveStats> ): VimeoRequest = client.fetchLiveStats(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchVideoList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<VideoList> ): VimeoRequest = client.fetchVideoList(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchFeedList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<FeedList> ): VimeoRequest = client.fetchFeedList(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchProjectItemList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<ProjectItemList> ): VimeoRequest = client.fetchProjectItemList(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchTeamList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<TeamList> ): VimeoRequest = client.fetchTeamList(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchProgrammedContentItemList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<ProgrammedCinemaItemList> ): VimeoRequest = client.fetchProgrammedContentItemList(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchRecommendationList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<RecommendationList> ): VimeoRequest = client.fetchRecommendationList(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchSearchResultList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<SearchResultList> ): VimeoRequest = client.fetchSearchResultList(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchSeasonList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<SeasonList> ): VimeoRequest = client.fetchSeasonList(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchNotificationList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<NotificationList> ): VimeoRequest = client.fetchNotificationList(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchUser( uri: String, fieldFilter: String?, cacheControl: CacheControl?, callback: VimeoCallback<User> ): VimeoRequest = client.fetchUser(uri, fieldFilter, cacheControl, callback) override fun fetchUserList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<UserList> ): VimeoRequest = client.fetchUserList(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchCategory( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<Category> ): VimeoRequest = client.fetchCategory(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchCategoryList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<CategoryList> ): VimeoRequest = client.fetchCategoryList(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchChannel( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<Channel> ): VimeoRequest = client.fetchChannel(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchChannelList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<ChannelList> ): VimeoRequest = client.fetchChannelList(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchAppConfiguration( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<AppConfiguration> ): VimeoRequest = client.fetchAppConfiguration(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchAlbum( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<Album> ): VimeoRequest = client.fetchAlbum(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchAlbumList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<AlbumList> ): VimeoRequest = client.fetchAlbumList(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchTvodItem( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<TvodItem> ): VimeoRequest = client.fetchTvodItem(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchTvodItemList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<TvodItemList> ): VimeoRequest = client.fetchTvodItemList(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchComment( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<Comment> ): VimeoRequest = client.fetchComment(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchCommentList( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<CommentList> ): VimeoRequest = client.fetchCommentList(uri, fieldFilter, queryParams, cacheControl, callback) override fun postContent( uri: String, bodyParams: List<Any>, callback: VimeoCallback<Unit> ): VimeoRequest = client.postContent(uri, bodyParams, callback) override fun emptyResponsePost( uri: String, bodyParams: Map<String, String>, callback: VimeoCallback<Unit> ): VimeoRequest = client.emptyResponsePost(uri, bodyParams, callback) override fun emptyResponsePatch( uri: String, queryParams: Map<String, String>, bodyParams: Any, callback: VimeoCallback<Unit> ): VimeoRequest = client.emptyResponsePatch(uri, queryParams, bodyParams, callback) override fun putContentWithUserResponse( uri: String, queryParams: Map<String, String>, bodyParams: Any?, callback: VimeoCallback<User> ): VimeoRequest = client.putContentWithUserResponse(uri, queryParams, bodyParams, callback) override fun putContent( uri: String, queryParams: Map<String, String>, bodyParams: Any?, callback: VimeoCallback<Unit> ): VimeoRequest = client.putContent(uri, queryParams, bodyParams, callback) override fun deleteContent( uri: String, queryParams: Map<String, String>, callback: VimeoCallback<Unit> ): VimeoRequest = client.deleteContent(uri, queryParams, callback) override fun fetchTeamPermissions( uri: String, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<TeamPermissionList> ): VimeoRequest = client.fetchTeamPermissions(uri, fieldFilter, queryParams, cacheControl, callback) override fun fetchTeamPermissions( folder: Folder, fieldFilter: String?, queryParams: Map<String, String>?, cacheControl: CacheControl?, callback: VimeoCallback<TeamPermissionList>, teamEntityQuery: String? ): VimeoRequest = client.fetchTeamPermissions( folder, fieldFilter, queryParams, cacheControl, callback, teamEntityQuery ) override fun fetchPermissionPolicyList( uri: String, fieldFilter: String?, cacheControl: CacheControl?, callback: VimeoCallback<PermissionPolicyList> ): VimeoRequest = client.fetchPermissionPolicyList(uri, fieldFilter, cacheControl, callback) override fun fetchPermissionPolicyList( user: User, fieldFilter: String?, cacheControl: CacheControl?, callback: VimeoCallback<PermissionPolicyList> ): VimeoRequest = client.fetchPermissionPolicyList(user, fieldFilter, cacheControl, callback) override fun fetchPermissionPolicy( uri: String, fieldFilter: String?, cacheControl: CacheControl?, callback: VimeoCallback<PermissionPolicy> ): VimeoRequest = client.fetchPermissionPolicy(uri, fieldFilter, cacheControl, callback) override fun fetchPermissionPolicy( permissionPolicy: PermissionPolicy, fieldFilter: String?, cacheControl: CacheControl?, callback: VimeoCallback<PermissionPolicy> ): VimeoRequest = client.fetchPermissionPolicy(permissionPolicy, fieldFilter, cacheControl, callback) override fun fetchPermissionPolicy( permissionPolicy: TeamPermissionCurrentPermissions, fieldFilter: String?, cacheControl: CacheControl?, callback: VimeoCallback<PermissionPolicy> ): VimeoRequest = client.fetchPermissionPolicy(permissionPolicy, fieldFilter, cacheControl, callback) override fun replaceTeamPermission( uri: String, permissionPolicyUri: String, teamEntityType: TeamEntityType, teamEntityUri: String, callback: VimeoCallback<Unit> ): VimeoRequest = client.replaceTeamPermission(uri, permissionPolicyUri, teamEntityType, teamEntityUri, callback) override fun replaceTeamPermission( teamPermission: TeamPermission, permissionPolicy: PermissionPolicy, teamEntity: TeamEntity, callback: VimeoCallback<Unit> ): VimeoRequest = client.replaceTeamPermission(teamPermission, permissionPolicy, teamEntity, callback) override fun replaceTeamPermission( teamPermissionInteraction: TeamPermissionInteraction, permissionPolicy: PermissionPolicy, teamEntity: TeamEntity, callback: VimeoCallback<Unit> ): VimeoRequest = client.replaceTeamPermission(teamPermissionInteraction, permissionPolicy, teamEntity, callback) override fun replaceTeamPermission( teamPermission: TeamPermission, permissionPolicy: TeamPermissionCurrentPermissions, teamEntity: TeamEntity, callback: VimeoCallback<Unit> ): VimeoRequest = replaceTeamPermission(teamPermission, permissionPolicy, teamEntity, callback) override fun replaceTeamPermission( teamPermissionInteraction: TeamPermissionInteraction, permissionPolicy: TeamPermissionCurrentPermissions, teamEntity: TeamEntity, callback: VimeoCallback<Unit> ): VimeoRequest = client.replaceTeamPermission(teamPermissionInteraction, permissionPolicy, teamEntity, callback) override fun deleteTeamPermission( uri: String, teamEntityType: TeamEntityType, teamEntityUri: String, callback: VimeoCallback<Unit> ): VimeoRequest = client.deleteTeamPermission(uri, teamEntityType, teamEntityUri, callback) override fun deleteTeamPermission( teamPermission: TeamPermission, teamEntity: TeamEntity, callback: VimeoCallback<Unit> ): VimeoRequest = client.deleteTeamPermission(teamPermission, teamEntity, callback) override fun deleteTeamPermission( teamPermissionInteraction: TeamPermissionInteraction, teamEntity: TeamEntity, callback: VimeoCallback<Unit> ): VimeoRequest = client.deleteTeamPermission(teamPermissionInteraction, teamEntity, callback) override fun fetchCapabilities( teamOwnerId: String, fieldFilter: String?, cacheControl: CacheControl?, callback: VimeoCallback<Capabilities> ): VimeoRequest = client.fetchCapabilities(teamOwnerId, fieldFilter, cacheControl, callback) }
mit
422a6bad386a12f2c1c17a276b21fccd
37.507303
120
0.709485
4.916335
false
false
false
false
jiangzehui/kotlindemo
app/src/main/java/com/jiangzehui/kotlindemo/MyAdapter.kt
1
1575
package com.jiangzehui.kotlindemo import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView /** * Created by jiangzehui on 17/6/9. */ class MyAdapter(internal var context:Context, internal var list: List<Any>) : BaseAdapter() { override fun getCount(): Int { return list.size } override fun getItem(i: Int): Any { return list[i] } override fun getItemId(i: Int): Long { return i.toLong() } override fun getView(i: Int, view: View?, viewGroup: ViewGroup?): View { var holder: Holder var rootView : View if (view == null) { rootView = LayoutInflater.from(context).inflate(R.layout.item, viewGroup, false) holder = Holder(rootView) rootView.tag = holder }else{ rootView = view holder = rootView.tag as Holder } if(list[i] is CityModel.ResultBean){ var item:CityModel.ResultBean = list[i] as CityModel.ResultBean holder.name.text = item.province }else{ var item:WeatherModel.ResultBean.FutureBean = list[i] as WeatherModel.ResultBean.FutureBean holder.name.text = item.date+ "\n" +item.dayTime+ "\n" +item.night+ "\n" +item.temperature+ "\n" +item.week+ "\n" +item.wind } return rootView } class Holder(itemView:View){ val name:TextView = itemView.findViewById(R.id.tv) as TextView } }
apache-2.0
7ffa71d50fe1e7f801f35546c31ae592
27.636364
136
0.628571
4.038462
false
false
false
false
noud02/Akatsuki
src/main/kotlin/moe/kyubey/akatsuki/commands/CreateTag.kt
1
2853
/* * Copyright (c) 2017-2019 Yui * * 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 moe.kyubey.akatsuki.commands import me.aurieh.ares.exposed.async.asyncTransaction import moe.kyubey.akatsuki.Akatsuki import moe.kyubey.akatsuki.annotations.Alias import moe.kyubey.akatsuki.annotations.Argument import moe.kyubey.akatsuki.annotations.Arguments import moe.kyubey.akatsuki.annotations.Load import moe.kyubey.akatsuki.db.schema.Tags import moe.kyubey.akatsuki.entities.Command import moe.kyubey.akatsuki.entities.Context import moe.kyubey.akatsuki.utils.I18n import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.select @Load @Arguments( Argument("name", "string"), Argument("content", "string") ) @Alias("createpasta", "createahh") class CreateTag : Command() { override val desc = "Create tags" override fun run(ctx: Context) { val name = ctx.args["name"] as String val content = ctx.args["content"] as String asyncTransaction(Akatsuki.pool) { if (Tags.select { Tags.tagName.eq(name) }.firstOrNull() != null) { return@asyncTransaction ctx.send( I18n.parse( ctx.lang.getString("tag_exists"), mapOf("username" to ctx.author.name) ) ) } Tags.insert { it[tagName] = name it[ownerId] = ctx.author.idLong it[tagContent] = content } ctx.send( I18n.parse( ctx.lang.getString("tag_created"), mapOf("name" to name) ) ) }.execute() } }
mit
c55406d9b0a077a88d25c697c5c1b27c
35.589744
78
0.640379
4.349085
false
false
false
false
Senspark/ee-x
src/android/core/src/main/java/com/ee/Logger.kt
1
986
package com.ee import android.util.Log /** * Created by enrevol on 4/13/16. */ class Logger @JvmOverloads constructor( private val _tag: String, private var _logLevel: Int = Log.VERBOSE) : ILogger { var logLevel: Int get() = _logLevel set(value) { _logLevel = value } override fun error(message: String) { if (_logLevel <= Log.ERROR) { Log.e(_tag, message) } } override fun error(message: String, th: Throwable) { if (_logLevel <= Log.ERROR) { Log.e(_tag, message, th) } } override fun warn(message: String) { if (_logLevel <= Log.WARN) { Log.w(_tag, message) } } override fun debug(message: String) { if (_logLevel <= Log.DEBUG) { Log.d(_tag, message) } } override fun info(message: String) { if (_logLevel <= Log.INFO) { Log.i(_tag, message) } } }
mit
847ce0b83924dcadfb2f8b54c4b7aa46
20.456522
57
0.513185
3.821705
false
false
false
false
Tapchicoma/ultrasonic
ultrasonic/src/main/kotlin/org/moire/ultrasonic/data/ActiveServerProvider.kt
1
6038
package org.moire.ultrasonic.data import android.content.Context import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.moire.ultrasonic.R import org.moire.ultrasonic.service.MusicServiceFactory.resetMusicService import org.moire.ultrasonic.util.Constants import org.moire.ultrasonic.util.Util import timber.log.Timber /** * This class can be used to retrieve the properties of the Active Server * It caches the settings read up from the DB to improve performance. */ class ActiveServerProvider( private val repository: ServerSettingDao, private val context: Context ) { private var cachedServer: ServerSetting? = null /** * Get the settings of the current Active Server * @return The Active Server Settings */ fun getActiveServer(): ServerSetting { val serverId = getActiveServerId(context) if (serverId > 0) { if (cachedServer != null && cachedServer!!.id == serverId) return cachedServer!! // Ideally this is the only call where we block the thread while using the repository runBlocking { withContext(Dispatchers.IO) { cachedServer = repository.findById(serverId) } Timber.d( "getActiveServer retrieved from DataBase, id: $serverId; " + "cachedServer: $cachedServer" ) } if (cachedServer != null) return cachedServer!! setActiveServerId(context, 0) } return ServerSetting( id = -1, index = 0, name = context.getString(R.string.main_offline), url = "http://localhost", userName = "", password = "", jukeboxByDefault = false, allowSelfSignedCertificate = false, ldapSupport = false, musicFolderId = "", minimumApiVersion = null ) } /** * Sets the Active Server by the Server Index in the Server Selector List * @param index: The index of the Active Server in the Server Selector List */ fun setActiveServerByIndex(index: Int) { Timber.d("setActiveServerByIndex $index") if (index < 1) { // Offline mode is selected setActiveServerId(context, 0) return } GlobalScope.launch(Dispatchers.IO) { val serverId = repository.findByIndex(index)?.id ?: 0 setActiveServerId(context, serverId) } } /** * Sets the minimum Subsonic API version of the current server. */ fun setMinimumApiVersion(apiVersion: String) { GlobalScope.launch(Dispatchers.IO) { if (cachedServer != null) { cachedServer!!.minimumApiVersion = apiVersion repository.update(cachedServer!!) } } } /** * Invalidates the Active Server Setting cache * This should be called when the Active Server or one of its properties changes */ fun invalidateCache() { Timber.d("Cache is invalidated") cachedServer = null } /** * Gets the Rest Url of the Active Server * @param method: The Rest resource to use * @return The Rest Url of the method on the server */ fun getRestUrl(method: String?): String? { val builder = StringBuilder(8192) val activeServer = getActiveServer() val serverUrl: String = activeServer.url val username: String = activeServer.userName var password: String = activeServer.password // Slightly obfuscate password password = "enc:" + Util.utf8HexEncode(password) builder.append(serverUrl) if (builder[builder.length - 1] != '/') { builder.append('/') } builder.append("rest/").append(method).append(".view") builder.append("?u=").append(username) builder.append("&p=").append(password) builder.append("&v=").append(Constants.REST_PROTOCOL_VERSION) builder.append("&c=").append(Constants.REST_CLIENT_ID) return builder.toString() } companion object { /** * Queries if the Active Server is the "Offline" mode of Ultrasonic * @return True, if the "Offline" mode is selected */ fun isOffline(context: Context?): Boolean { return context == null || getActiveServerId(context) < 1 } /** * Queries the Id of the Active Server */ fun getActiveServerId(context: Context): Int { val preferences = Util.getPreferences(context) return preferences.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, -1) } /** * Sets the Id of the Active Server */ fun setActiveServerId(context: Context, serverId: Int) { resetMusicService() val preferences = Util.getPreferences(context) val editor = preferences.edit() editor.putInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, serverId) editor.apply() } /** * Queries if Scrobbling is enabled */ fun isScrobblingEnabled(context: Context): Boolean { if (isOffline(context)) { return false } val preferences = Util.getPreferences(context) return preferences.getBoolean(Constants.PREFERENCES_KEY_SCROBBLE, false) } /** * Queries if Server Scaling is enabled */ fun isServerScalingEnabled(context: Context): Boolean { if (isOffline(context)) { return false } val preferences = Util.getPreferences(context) return preferences.getBoolean(Constants.PREFERENCES_KEY_SERVER_SCALING, false) } } }
gpl-3.0
dbff6f70c24ac4986ab3fce2c8baee20
32.359116
97
0.600696
4.969547
false
false
false
false
TeamWizardry/LibrarianLib
modules/albedo/src/main/kotlin/com/teamwizardry/librarianlib/albedo/base/buffer/FlatLinesRenderBuffer.kt
1
2876
package com.teamwizardry.librarianlib.albedo.base.buffer import com.teamwizardry.librarianlib.albedo.buffer.Primitive import com.teamwizardry.librarianlib.albedo.buffer.VertexBuffer import com.teamwizardry.librarianlib.albedo.shader.Shader import com.teamwizardry.librarianlib.albedo.shader.attribute.VertexLayoutElement import com.teamwizardry.librarianlib.albedo.shader.uniform.FloatUniform import com.teamwizardry.librarianlib.albedo.shader.uniform.FloatVec2Uniform import com.teamwizardry.librarianlib.albedo.shader.uniform.Uniform import com.teamwizardry.librarianlib.core.util.Client import net.minecraft.util.Identifier import java.lang.Math public class FlatLinesRenderBuffer(vbo: VertexBuffer) : BaseRenderBuffer<FlatLinesRenderBuffer>(vbo, Primitive.LINES_ADJACENCY, Primitive.LINE_STRIP_ADJACENCY), ColorBuffer<FlatLinesRenderBuffer> { private val color: VertexLayoutElement = +VertexLayoutElement("Color", VertexLayoutElement.FloatFormat.UNSIGNED_BYTE, 4, true) private val insetWidth: VertexLayoutElement = +VertexLayoutElement("InsetWidth", VertexLayoutElement.FloatFormat.FLOAT, 1, false) private val outsetWidth: VertexLayoutElement = +VertexLayoutElement("OutsetWidth", VertexLayoutElement.FloatFormat.FLOAT, 1, false) private val displaySize: FloatVec2Uniform = +Uniform.vec2.create("DisplaySize") init { bind(defaultShader) } public override fun color(r: Int, g: Int, b: Int, a: Int): FlatLinesRenderBuffer { start(color) putByte(r) putByte(g) putByte(b) putByte(a) return this } public fun inset(width: Float): FlatLinesRenderBuffer { start(insetWidth) putFloat(width) return this } public fun outset(width: Float): FlatLinesRenderBuffer { start(outsetWidth) putFloat(width) return this } /** * A shorthand for `inset(width/2).outset(width/2)` */ public fun width(width: Float): FlatLinesRenderBuffer { start(insetWidth) putFloat(-width / 2) start(outsetWidth) putFloat(width / 2) return this } override fun setupState() { super.setupState() displaySize.set(Client.window.framebufferWidth.toFloat(), Client.window.framebufferHeight.toFloat()) } public companion object { private val defaultShader: Shader = Shader.build("flat_lines") .vertex(Identifier("liblib-albedo:builtin/flat_lines.vert")) .geometry(Identifier("liblib-albedo:builtin/flat_lines.geom")) .fragment(Identifier("liblib-albedo:builtin/flat_lines.frag")) .build() @JvmStatic @get:JvmName("getShared") public val SHARED: FlatLinesRenderBuffer by lazy { FlatLinesRenderBuffer(VertexBuffer.SHARED) } } }
lgpl-3.0
6329b84d0455e09ff0ce1492bfa2c0e4
34.518519
108
0.70758
4.411043
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/subscriptions/SubscriptionOptionView.kt
1
4460
package com.habitrpg.android.habitica.ui.views.subscriptions import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import androidx.core.content.ContextCompat import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.PurchaseSubscriptionViewBinding import com.habitrpg.android.habitica.extensions.layoutInflater class SubscriptionOptionView(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) { private val binding = PurchaseSubscriptionViewBinding.inflate(context.layoutInflater, this, true) var sku: String? = null init { val a = context.theme.obtainStyledAttributes( attrs, R.styleable.SubscriptionOptionView, 0, 0 ) if (a.getBoolean(R.styleable.SubscriptionOptionView_isNonRecurring, false)) { binding.descriptionTextView.text = context.getString(R.string.subscription_duration_norenew, a.getText(R.styleable.SubscriptionOptionView_recurringText)) } else { binding.descriptionTextView.text = context.getString(R.string.subscription_duration, a.getText(R.styleable.SubscriptionOptionView_recurringText)) } binding.gemCapTextView.text = a.getText(R.styleable.SubscriptionOptionView_gemCapText) setFlagText(a.getText(R.styleable.SubscriptionOptionView_flagText)) val hourGlassCount = a.getInteger(R.styleable.SubscriptionOptionView_hourGlassCount, 0) if (hourGlassCount != 0) { binding.hourglassTextView.text = context.getString(R.string.subscription_hourglasses, hourGlassCount) binding.hourglassTextView.visibility = View.VISIBLE } else { binding.hourglassTextView.visibility = View.GONE } } fun setOnPurchaseClickListener(listener: OnClickListener) { this.setOnClickListener(listener) } fun setPriceText(text: String) { binding.priceLabel.text = text } fun setFlagText(text: CharSequence?) { if (text?.length ?: 0 == 0) { binding.flagFlap.visibility = View.GONE binding.flagTextview.visibility = View.GONE } else { binding.flagFlap.visibility = View.VISIBLE binding.flagTextview.visibility = View.VISIBLE binding.flagTextview.text = text } } fun setIsSelected(purchased: Boolean) { if (purchased) { binding.wrapper.setBackgroundResource(R.drawable.subscription_box_bg_selected) binding.subscriptionSelectedView.setBackgroundResource(R.drawable.subscription_selected) binding.gemCapTextView.setBackgroundResource(R.drawable.pill_bg_purple_400) binding.gemCapTextView.setTextColor(ContextCompat.getColor(context, R.color.white)) binding.hourglassTextView.setBackgroundResource(R.drawable.pill_bg_purple_400) binding.hourglassTextView.setTextColor(ContextCompat.getColor(context, R.color.white)) binding.priceLabel.setTextColor(ContextCompat.getColor(context, R.color.text_brand)) binding.descriptionTextView.setTextColor(ContextCompat.getColor(context, R.color.text_brand)) } else { binding.wrapper.setBackgroundResource(R.drawable.subscription_box_bg) binding.subscriptionSelectedView.setBackgroundResource(R.drawable.subscription_unselected) binding.gemCapTextView.setBackgroundResource(R.drawable.pill_bg_gray) binding.gemCapTextView.setTextColor(ContextCompat.getColor(context, R.color.text_secondary)) binding.hourglassTextView.setBackgroundResource(R.drawable.pill_bg_gray) binding.hourglassTextView.setTextColor(ContextCompat.getColor(context, R.color.text_secondary)) binding.priceLabel.setTextColor(ContextCompat.getColor(context, R.color.text_ternary)) binding.descriptionTextView.setTextColor(ContextCompat.getColor(context, R.color.text_ternary)) } val horizontalPadding = resources.getDimension(R.dimen.pill_horizontal_padding).toInt() val verticalPadding = resources.getDimension(R.dimen.pill_vertical_padding).toInt() binding.gemCapTextView.setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding) binding.hourglassTextView.setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding) } }
gpl-3.0
11792c66661574b47cb82acca37a28d5
50.860465
165
0.731839
4.640999
false
false
false
false
androidx/androidx
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/KspBasicAnnotationProcessor.kt
3
4100
/* * 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.room.compiler.processing.ksp import androidx.room.compiler.processing.CommonProcessorDelegate import androidx.room.compiler.processing.XBasicAnnotationProcessor import androidx.room.compiler.processing.XProcessingEnv import androidx.room.compiler.processing.XProcessingEnvConfig import com.google.devtools.ksp.processing.KSPLogger import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.processing.SymbolProcessor import com.google.devtools.ksp.processing.SymbolProcessorEnvironment import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSNode /** * KSP implementation of a [XBasicAnnotationProcessor] with built-in support for validating and * deferring symbols. */ abstract class KspBasicAnnotationProcessor @JvmOverloads constructor( symbolProcessorEnvironment: SymbolProcessorEnvironment, config: XProcessingEnvConfig = XProcessingEnvConfig.DEFAULT, ) : SymbolProcessor, XBasicAnnotationProcessor { private val logger = DelegateLogger(symbolProcessorEnvironment.logger) private val xEnv = KspProcessingEnv( options = symbolProcessorEnvironment.options, codeGenerator = symbolProcessorEnvironment.codeGenerator, logger = logger, config = config ) // Cache and lazily get steps during the initial process() so steps initialization is done once. private val steps by lazy { processingSteps().toList() } private val commonDelegate by lazy { CommonProcessorDelegate(this.javaClass, xEnv, steps) } private var initialized = false final override val xProcessingEnv: XProcessingEnv get() = xEnv final override fun process(resolver: Resolver): List<KSAnnotated> { xEnv.resolver = resolver // Set the resolver at the beginning of each round if (!initialized) { initialize(xEnv) initialized = true } val xRoundEnv = KspRoundEnv(xEnv, false) commonDelegate.processRound(xRoundEnv) postRound(xEnv, xRoundEnv) xEnv.clearCache() // Reset cache after every round to avoid leaking elements across rounds // TODO(b/201307003): Use KSP deferring API. // For now don't defer symbols since this impl of basic annotation processor mimics // javac's impl where elements are deferred by remembering the name of the closest enclosing // type element and later in a subsequent round finding the type element using the // Resolver and then searching it for annotations requested by the steps. return emptyList() } final override fun finish() { val xRoundEnv = KspRoundEnv(xEnv, true) val missingElements = commonDelegate.processLastRound() postRound(xEnv, xRoundEnv) if (!xProcessingEnv.config.disableAnnotatedElementValidation && !logger.hasError) { // Report missing elements if no error was raised to avoid being noisy. commonDelegate.reportMissingElements(missingElements) } } // KSPLogger delegate to keep track if an error was raised or not. private class DelegateLogger(val delegate: KSPLogger) : KSPLogger by delegate { var hasError = false override fun error(message: String, symbol: KSNode?) { hasError = true delegate.error(message, symbol) } override fun exception(e: Throwable) { hasError = true delegate.exception(e) } } }
apache-2.0
7253b1cb4424fb9a6e78a4c9f5d1b441
41.71875
100
0.728293
4.795322
false
true
false
false
Soya93/Extract-Refactoring
platform/script-debugger/backend/src/SuspendContextManager.kt
4
2562
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import org.jetbrains.concurrency.Promise interface SuspendContextManager<CALL_FRAME : CallFrame> { /** * Tries to suspend VM. If successful, [DebugEventListener.suspended] will be called. */ fun suspend(): Promise<*> val context: SuspendContext<CALL_FRAME>? val contextOrFail: SuspendContext<CALL_FRAME> fun isContextObsolete(context: SuspendContext<*>) = this.context !== context fun setOverlayMessage(message: String?) /** * Resumes the VM execution. This context becomes invalid until another context is supplied through the * [DebugEventListener.suspended] event. * @param stepAction to perform * * * @param stepCount steps to perform (not used if `stepAction == CONTINUE`) */ fun continueVm(stepAction: StepAction, stepCount: Int): Promise<*> val isRestartFrameSupported: Boolean /** * Restarts a frame (all frames above are dropped from the stack, this frame is started over). * for success the boolean parameter * is true if VM has been resumed and is expected to get suspended again in a moment (with * a standard 'resumed' notification), and is false if call frames list is already updated * without VM state change (this case presently is never actually happening) */ fun restartFrame(callFrame: CALL_FRAME): Promise<Boolean> /** * @return whether reset operation is supported for the particular callFrame */ fun canRestartFrame(callFrame: CallFrame): Boolean } enum class StepAction { /** * Resume the JavaScript execution. */ CONTINUE, /** * Step into the current statement. */ IN, /** * Step into first scheduled async handler. * @see <a href="https://groups.google.com/a/chromium.org/forum/#!topic/blink-reviews-bindings/LRAHGXErvOc">Chrome debugger suggestion</a> */ IN_ASYNC, /** * Step over the current statement. */ OVER, /** * Step out of the current function. */ OUT }
apache-2.0
0a47bc504c02eeaec032f800110d3b54
28.802326
140
0.714676
4.298658
false
false
false
false
codehz/container
app/src/main/java/one/codehz/container/App.kt
1
2293
package one.codehz.container import android.app.Application import android.content.Context import android.os.Build import com.lody.virtual.client.stub.StubManifest import mirror.RefStaticObject import one.codehz.container.delegate.* import one.codehz.container.ext.sharedPreferences import one.codehz.container.ext.virtualCore class App : Application() { companion object { private var app: App? = null val self: App get() = app!! } override fun attachBaseContext(base: Context?) { super.attachBaseContext(base) StubManifest.ENABLE_IO_REDIRECT = true virtualCore.startup(base) } fun RefStaticObject<String>?.setIfNotEmpty(value: String) = if (value.isNotEmpty()) this?.set(value) else Unit override fun onCreate() { super.onCreate() with(virtualCore) { when { isVAppProcess -> { componentDelegate = MyComponentDelegate(this@App) phoneInfoDelegate = MyPhoneInfoDelegate() taskDescriptionDelegate = MyTaskDescriptionDelegate() ioRedirectDelegate = MyIORedirectDelegate() uncheckedExceptionDelegate = MyUncheckedExceptionDelegate() mirror.android.os.Build.MODEL.setIfNotEmpty(sharedPreferences.getString("privacy_device_model", "")) mirror.android.os.Build.MANUFACTURER.setIfNotEmpty(sharedPreferences.getString("privacy_device_manufacturer", "")) mirror.android.os.Build.BRAND.setIfNotEmpty(sharedPreferences.getString("privacy_device_brand", "")) mirror.android.os.Build.PRODUCT.setIfNotEmpty(sharedPreferences.getString("privacy_device_product", "")) mirror.android.os.Build.DEVICE.setIfNotEmpty(sharedPreferences.getString("privacy_device_device", "")) Unit } isServerProcess -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) foregroundNotificationDelegate = MyForegroundNotificationDelegate(this@App) } else -> { setAppRequestListener(MyAppRequestListener()) } } } } }
gpl-3.0
a53d25e94d24bc096b8bdfe33953f935
39.245614
134
0.627998
5.084257
false
false
false
false
y2k/JoyReactor
android/src/main/kotlin/y2k/joyreactor/widget/TagComponent.kt
1
983
package y2k.joyreactor.widget import android.content.Context import android.view.View import android.widget.FrameLayout import android.widget.TextView import y2k.joyreactor.R import y2k.joyreactor.common.BindableComponent import y2k.joyreactor.common.property import y2k.joyreactor.common.setOnClick import y2k.joyreactor.common.view import y2k.joyreactor.model.Group /** * Created by y2k on 10/07/16. */ class TagComponent( context: Context?, val onSelect: (Group) -> Unit) : FrameLayout(context), BindableComponent<Group> { private val title by view<TextView>() private val icon by view<WebImageView>() override val value = property(Group.Undefined) init { View.inflate(context, R.layout.item_subscription, this) setOnClick(R.id.action) { onSelect(value.value) } value.subscribe { if (it !== Group.Undefined) { title.text = it.title icon.image = it.image } } } }
gpl-2.0
65a465d64ae57c7add44c59e93718594
27.114286
104
0.690743
3.839844
false
false
false
false
jonashao/next-kotlin
app/src/main/java/com/junnanhao/next/ui/MainActivity.kt
1
3191
package com.junnanhao.next.ui import android.annotation.SuppressLint import android.os.Bundle import android.os.Handler import android.support.v7.app.AppCompatActivity import android.view.View import com.junnanhao.next.R import kotlinx.android.synthetic.main.activity_fullscreen.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_fullscreen) supportActionBar?.setDisplayHomeAsUpEnabled(true) val playerFragment = PlayerFragment.instance() supportFragmentManager.beginTransaction() .add(R.id.fullscreen_content, playerFragment, "player-fragment") .commit() } override fun onPostResume() { super.onPostResume() // Trigger the initial hide() shortly after the activity has been // created, to briefly hint to the user that UI controls // are available. delayedHide(100) } private val mHideHandler = Handler() @SuppressLint("InlinedApi") private val mHidePart2Runnable = Runnable { // Delayed removal of status and navigation bar // Note that some of these constants are new as of API 16 (Jelly Bean) // and API 19 (KitKat). It is safe to use them, as they are inlined // at compile-time and do nothing on earlier devices. fullscreen_content?.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION } private val mHideRunnable = Runnable { hide() } private fun hide() { // Hide UI first supportActionBar?.hide() mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY.toLong()) } /** * Schedules a call to hide() in [delayMillis], canceling any * previously scheduled calls. */ private fun delayedHide(delayMillis: Int) { mHideHandler.removeCallbacks(mHideRunnable) mHideHandler.postDelayed(mHideRunnable, delayMillis.toLong()) } companion object { /** * Some older devices needs a small delay between UI widget updates * and a change of the status and navigation bar. */ private val UI_ANIMATION_DELAY = 300 private val SAVED_MEDIA_ID = "com.example.android.uamp.MEDIA_ID" private val FRAGMENT_TAG = "uamp_list_container" val EXTRA_START_FULLSCREEN = "com.example.android.uamp.EXTRA_START_FULLSCREEN" /** * Optionally used with [.EXTRA_START_FULLSCREEN] to carry a MediaDescription to * the [FullScreenPlayerActivity], speeding up the screen rendering * while the [android.support.v4.media.session.MediaControllerCompat] is connecting. */ val EXTRA_CURRENT_MEDIA_DESCRIPTION = "com.example.android.uamp.CURRENT_MEDIA_DESCRIPTION" } }
apache-2.0
56d308acf09e5993c4882a5e636d0ce2
34.853933
98
0.659041
4.672035
false
false
false
false
rhdunn/xquery-intellij-plugin
src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/psi/PsiElement.kt
1
4081
/* * Copyright (C) 2018-2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.core.psi import com.intellij.lang.ASTNode import com.intellij.psi.* import com.intellij.psi.impl.source.tree.LeafElement import com.intellij.psi.tree.IElementType import com.intellij.psi.util.PsiTreeUtil import uk.co.reecedunn.intellij.plugin.core.sequences.ancestorsAndSelf import uk.co.reecedunn.intellij.plugin.core.sequences.walkTree import uk.co.reecedunn.intellij.plugin.core.vfs.originalFile private fun PsiFile.resourcePath(): String { return ancestorsAndSelf().map { (it as PsiFileSystemItem).name }.toList().reversed().joinToString("/") } fun PsiElement.resourcePath(): String { val file = containingFile.virtualFile?.originalFile ?: return containingFile.resourcePath() return file.path.replace('\\', '/') } inline fun <reified T : PsiElement> PsiElement.contextOfType(strict: Boolean = true): T? { return PsiTreeUtil.getContextOfType(this, T::class.java, strict) } fun <T> PsiElement.createElement(text: String, `class`: Class<T>): T? { val file = PsiFileFactory.getInstance(project).createFileFromText(text, containingFile) return file?.walkTree()?.filterIsInstance(`class`)?.firstOrNull() } inline fun <reified T> PsiElement.createElement(text: String): T? = createElement(text, T::class.java) fun PsiElement.contains(type: IElementType): Boolean = node.findChildByType(type) != null private fun prettyPrintASTNode(prettyPrinted: StringBuilder, node: ASTNode, depth: Int) { for (i in 0 until depth) { prettyPrinted.append(" ") } val names = node.psi.javaClass.name.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() prettyPrinted.append(names[names.size - 1].replace("PsiImpl", "Impl")) prettyPrinted.append('[') prettyPrinted.append(node.elementType) prettyPrinted.append('(') prettyPrinted.append(node.textRange.startOffset) prettyPrinted.append(':') prettyPrinted.append(node.textRange.endOffset) prettyPrinted.append(')') prettyPrinted.append(']') if (node is LeafElement || node is PsiErrorElement) { prettyPrinted.append('(') prettyPrinted.append('\'') if (node is PsiErrorElement) { val error = node as PsiErrorElement prettyPrinted.append(error.errorDescription) } else { prettyPrinted.append(node.text.replace("\n", "\\n")) } prettyPrinted.append('\'') prettyPrinted.append(')') } prettyPrinted.append('\n') for (child in node.getChildren(null)) { prettyPrintASTNode(prettyPrinted, child, depth + 1) } } fun PsiElement.toPsiTreeString(): String { val prettyPrinted = StringBuilder() prettyPrintASTNode(prettyPrinted, node, 0) return prettyPrinted.toString() } fun PsiElement.nextSiblingIfSelf(predicate: (PsiElement) -> Boolean): PsiElement = when { predicate(this) -> nextSibling ?: this else -> this } fun PsiElement.nextSiblingWhileSelf(predicate: (PsiElement) -> Boolean): PsiElement { var next = this while (predicate(next)) { next = nextSibling ?: return next } return next } fun PsiElement.prevSiblingIfSelf(predicate: (PsiElement) -> Boolean): PsiElement = when { predicate(this) -> prevSibling ?: this else -> this } fun PsiElement.prevSiblingWhileSelf(predicate: (PsiElement) -> Boolean): PsiElement { var prev = this while (predicate(prev)) { prev = prevSibling ?: return prev } return prev }
apache-2.0
7137114f98b169fbb9233e770f708273
34.798246
108
0.708405
4.242204
false
false
false
false
HabitRPG/habitica-android
wearos/src/main/java/com/habitrpg/wearos/habitica/models/user/Outfit.kt
1
560
package com.habitrpg.wearos.habitica.models.user import com.habitrpg.shared.habitica.models.AvatarOutfit import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) class Outfit: AvatarOutfit { override var armor: String = "" override var back: String = "" override var body: String = "" override var head: String = "" override var shield: String = "" override var weapon: String = "" @Json(name = "eyewear") override var eyeWear: String = "" override var headAccessory: String = "" }
gpl-3.0
88175b273fcef08df0b6ebb4f1e84cac
32
61
0.7125
4
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/lang/FunctionsAndOperatorsSpec.kt
1
3389
/* * Copyright (C) 2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xpath.lang import com.intellij.navigation.ItemPresentation import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSpecificationType import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSpecificationVersion import uk.co.reecedunn.intellij.plugin.xpm.lang.impl.W3CSpecification import uk.co.reecedunn.intellij.plugin.xpm.resources.XpmIcons import javax.swing.Icon @Suppress("MemberVisibilityCanBePrivate") object FunctionsAndOperatorsSpec : ItemPresentation, XpmSpecificationType { // region ItemPresentation override fun getPresentableText(): String = "XQuery and XPath Functions and Operators" override fun getLocationString(): String? = null override fun getIcon(unused: Boolean): Icon = XpmIcons.W3.Product // endregion // region XpmSpecificationType override val id: String = "xpath-functions" override val presentation: ItemPresentation get() = this // endregion // region Versions val WD_1_0_20030502: XpmSpecificationVersion = W3CSpecification( this, "1.0-20030502", "1.0 (Working Draft 02 May 2003)", "https://www.w3.org/TR/2003/WD-xpath-functions-20030502/" ) val REC_1_0_20070123: XpmSpecificationVersion = W3CSpecification( this, "1.0-20070123", "1.0 (First Edition)", "https://www.w3.org/TR/2007/REC-xpath-functions-20070123/" ) val REC_1_0_20101214: XpmSpecificationVersion = W3CSpecification( this, "1.0-20101214", "1.0 (Second Edition)", "https://www.w3.org/TR/2010/REC-xpath-functions-20101214/" ) val WD_3_0_20111213: XpmSpecificationVersion = W3CSpecification( this, "3.0-20111213", "3.0 (Working Draft 13 Dec 2011)", "http://www.w3.org/TR/2011/WD-xpath-functions-30-20111213/" ) val REC_3_0_20140408: XpmSpecificationVersion = W3CSpecification( this, "3.0-20140408", "3.0", "https://www.w3.org/TR/2014/REC-xpath-functions-30-20140408/" ) val REC_3_1_20170321: XpmSpecificationVersion = W3CSpecification( this, "3.1-20170321", "3.1", "https://www.w3.org/TR/2017/REC-xpath-functions-31-20170321/" ) val ED_4_0_20210113: XpmSpecificationVersion = W3CSpecification( this, "4.0-20210113", "4.0 (Editor's Draft 13 January 2021)", "https://qt4cg.org/branch/master/xpath-functions-40/Overview.html" ) val versions: List<XpmSpecificationVersion> = listOf( WD_1_0_20030502, // MarkLogic 0.9-ml REC_1_0_20070123, REC_1_0_20101214, WD_3_0_20111213, // MarkLogic 1.0-ml REC_3_0_20140408, REC_3_1_20170321, ED_4_0_20210113 ) // endregion }
apache-2.0
9f7ba5f16ae6d888848c35abfa6e97d2
30.971698
90
0.67188
3.590042
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/ui/dialogs/VideoQualityDialogBase.kt
2
893
package org.stepic.droid.ui.dialogs import androidx.fragment.app.DialogFragment import java.util.HashMap abstract class VideoQualityDialogBase : DialogFragment() { protected val qualityToPositionMap: MutableMap<String, Int> = HashMap() protected val positionToQualityMap: MutableMap<Int, String> = HashMap() protected fun init() { injectDependencies() if (qualityToPositionMap.isEmpty() || positionToQualityMap.isEmpty()) { initMaps() } } abstract fun injectDependencies() private fun initMaps() { qualityToPositionMap["270"] = 0 qualityToPositionMap["360"] = 1 qualityToPositionMap["720"] = 2 qualityToPositionMap["1080"] = 3 positionToQualityMap[0] = "270" positionToQualityMap[1] = "360" positionToQualityMap[2] = "720" positionToQualityMap[3] = "1080" } }
apache-2.0
15793362756c00ede6f6d95362dce6ca
28.8
79
0.665174
4.356098
false
false
false
false
spkingr/50-android-kotlin-projects-in-100-days
ProjectBasicMVP/app/src/main/java/me/liuqingwen/android/projectbasicmvp/view/LoginActivity.kt
1
3566
package me.liuqingwen.android.projectbasicmvp.view import android.annotation.SuppressLint import android.os.Bundle import android.support.annotation.IdRes import android.support.v7.app.AppCompatActivity import android.view.KeyEvent import android.view.inputmethod.EditorInfo import android.widget.EditText import android.widget.TextView import me.liuqingwen.android.projectbasicmvp.presenter.LoginPresenter import me.liuqingwen.android.projectbasicmvp.ui.* import me.liuqingwen.kotlinandroidviewbindings.* import org.jetbrains.anko.* class LoginActivity : AppCompatActivity(), ILoginView { override var isProgressBarVisible by bindToLoadings(ID_PROGRESS_BAR, ID_BUTTON_LOGIN) override var username by bindToEditText(ID_TEXT_USERNAME) override var password by bindToEditText(ID_TEXT_PASSWORD) override val textUsernameRequestFocus by bindToRequestFocus(ID_TEXT_USERNAME) override val textPasswordRequestFocus by bindToRequestFocus(ID_TEXT_PASSWORD) override var usernameErrorId by bindToErrorId(ID_TEXT_USERNAME, this) override var passwordErrorId:Int? by bindToErrorId(ID_TEXT_PASSWORD, this) override var onPasswordEnterAction by bindToEditorActions(ID_TEXT_PASSWORD) {actionId, eventCode -> actionId == EditorInfo.IME_ACTION_DONE || eventCode == KeyEvent.KEYCODE_ENTER } override var onLoginButtonClickAction by bindToClickEvent(ID_BUTTON_LOGIN) private val presenter by lazy(LazyThreadSafetyMode.NONE) { LoginPresenter(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) LoginUI().setContentView(this) this.init() this.presenter.onCreate() } private fun init() { val labelUsername = this.find<TextView>(ID_LABEL_USERNAME) val labelPassword = this.find<TextView>(ID_LABEL_PASSWORD) val textUsername = this.find<EditText>(ID_TEXT_USERNAME) val textPassword = this.find<EditText>(ID_TEXT_PASSWORD) textUsername.setOnFocusChangeListener { _, isFocused -> if (this.username.isEmpty()) { if(isFocused) labelUsername.animate().setDuration(300).translationY(-68f).scaleX(0.8f).scaleY(0.8f).start() else labelUsername.animate().setDuration(300).translationY(0f).scaleX(1.0f).scaleY(1.0f).start() } } textPassword.setOnFocusChangeListener { _, isFocused -> if (this.password.isEmpty()) { if(isFocused) labelPassword.animate().setDuration(300).translationY(-68f).scaleX(0.8f).scaleY(0.8f).start() else labelPassword.animate().setDuration(300).translationY(0f).scaleX(1.0f).scaleY(1.0f).start() } } } override fun onDestroy() { super.onDestroy() this.presenter.onDestroy() } override fun doLoginSuccess() { this.toast("Login succeed!") this.startActivity<MovieActivity>() this.overridePendingTransition(me.liuqingwen.android.projectbasicmvp.R.anim.anim_enter, me.liuqingwen.android.projectbasicmvp.R.anim.anim_exit) this.finish() } @SuppressLint("ResourceType") override fun showHintByToast(@IdRes id:Int) { this.longToast(this.getString(id)) } override fun doLoginError(error:Throwable) { alert { title = "Error!" message = "Error while login, please try it later, information: ${error.message}" negativeButton("Cancel") { } }.show() } }
mit
686978af4feb7c8ff961e83ac144079f
38.622222
220
0.696018
4.370098
false
false
false
false
UCSoftworks/LeafDb
leafdb-core/src/main/java/com/ucsoftworks/leafdb/LeafDb.kt
1
13664
package com.ucsoftworks.leafdb import com.ucsoftworks.leafdb.dsl.AggregateFunction import com.ucsoftworks.leafdb.dsl.Condition import com.ucsoftworks.leafdb.dsl.Field import com.ucsoftworks.leafdb.querying.* import com.ucsoftworks.leafdb.querying.internal.LeafDbModificationBlockQuery import com.ucsoftworks.leafdb.querying.internal.LeafDbModificationQuery import com.ucsoftworks.leafdb.querying.internal.LeafDbStringListQuery import com.ucsoftworks.leafdb.querying.internal.LeafDbStringQuery import com.ucsoftworks.leafdb.serializer.NullMergeStrategy import com.ucsoftworks.leafdb.serializer.Serializer import com.ucsoftworks.leafdb.wrapper.ILeafDbProvider import querying.SelectQueryBuilder /** * Created by Pasenchuk Victor on 11/08/2017 */ class LeafDb(internal val leafDbProvider: ILeafDbProvider) { private val serializer = Serializer() fun random(): ILeafDbQuery<Long> = LeafDbStringQuery(getRandomQuery(), leafDbProvider).map(Long::class.java) fun engineVersion(): ILeafDbQuery<String?> = LeafDbStringQuery(getEngineVersionQuery(), leafDbProvider) fun isJson(doc: String): Boolean { val valid = LeafDbStringQuery(getJsonValidQuery(doc), leafDbProvider).execute() if (valid == "1") return true return false } fun getInnerDocument(json: String, path: Field): ILeafDbQuery<String?> = LeafDbStringQuery(getInnerDocumentSql(path, json), leafDbProvider) fun getInnerArray(json: String, path: Field): ILeafDbQuery<List<String>> = LeafDbStringListQuery(getInnerArrayQuery(path, json), leafDbProvider) fun select(table: String) = SelectQueryBuilder(table, leafDbProvider) @JvmOverloads fun count(table: String, condition: Condition? = null) = LeafDbStringQuery(getCountQuery(table, condition), leafDbProvider).map(Long::class.java) @JvmOverloads fun aggregate(table: String, field: Field, aggregateFunction: AggregateFunction, condition: Condition? = null): ILeafDbQuery<Double> = LeafDbStringQuery(getAggregationQuery(aggregateFunction, field, table, condition), leafDbProvider).map(Double::class.java) @JvmOverloads fun <T> aggregate(table: String, field: Field, aggregateFunction: AggregateFunction, clazz: Class<T>, condition: Condition? = null): ILeafDbQuery<T> = LeafDbStringQuery(getAggregationQuery(aggregateFunction, field, table, condition), leafDbProvider).map(clazz) @JvmOverloads fun delete(table: String, condition: Condition? = null, notifySubscribers: Boolean = true): ILeafDbQuery<Unit> = LeafDbModificationQuery(table, getDeleteQuery(table, condition), leafDbProvider, notifySubscribers) @JvmOverloads fun insert(table: String, document: Any, innerDocument: Field? = null, notifySubscribers: Boolean = true): ILeafDbQuery<Unit> = entryUpdate(table, document, innerDocument, notifySubscribers, this::getInsertSql) private fun entryUpdate(table: String, document: Any, innerDocument: Field? = null, notifySubscribers: Boolean, sqlGenerator: (table: String, doc: String) -> String): ILeafDbQuery<Unit> { return LeafDbModificationBlockQuery { val doc = getDoc(document, innerDocument) LeafDbModificationQuery(table, sqlGenerator(table, doc), leafDbProvider, notifySubscribers).execute() } } private fun getDoc(document: Any, innerDocument: Field?): String { var doc = if (document is String && isJson(document)) document else serializer.getJsonFromObject(document) if (innerDocument != null) doc = getInnerDocument(doc, innerDocument).execute()!! return doc } @JvmOverloads fun update(table: String, document: Any, condition: Condition?, innerDocument: Field? = null, notifySubscribers: Boolean = true): ILeafDbQuery<Unit> = entryUpdate(table, document, innerDocument, notifySubscribers) { t, d -> getUpdateSql(t, d, condition) } //todo generalize @JvmOverloads fun update(table: String, document: Any, pKey: Field, innerDocument: Field? = null, notifySubscribers: Boolean = true): ILeafDbQuery<Unit> = entryUpdate(table, document, innerDocument, notifySubscribers) { t, d -> getUpdateSql(t, d, getInnerDocConditionSql(pKey, document, innerDocument)) } @JvmOverloads fun insertOrUpdate(table: String, document: Any, pKey: Field, innerDocument: Field? = null, notifySubscribers: Boolean = true): ILeafDbQuery<Unit> = LeafDbModificationBlockQuery { val count = LeafDbStringQuery(getDocCountQuery(table, pKey, document, innerDocument), leafDbProvider).map(Long::class.java).execute()!! if (count == 0L) entryUpdate(table, document, innerDocument, notifySubscribers, this::getInsertSql).execute() else entryUpdate(table, document, innerDocument, notifySubscribers) { t, d -> getUpdateSql(t, d, getInnerDocConditionSql(pKey, document, innerDocument)) }.execute() } //todo generalize @JvmOverloads fun partialUpdate(table: String, document: Any, condition: Condition?, innerDocument: Field? = null, notifySubscribers: Boolean = true, nullMergeStrategy: NullMergeStrategy = NullMergeStrategy.TAKE_DESTINATION): ILeafDbQuery<Unit> = LeafDbModificationBlockQuery { conditionalPartialUpdate(table, document, condition, innerDocument, notifySubscribers, nullMergeStrategy) } @JvmOverloads fun partialUpdate(table: String, document: Any, pKey: Field, innerDocument: Field? = null, notifySubscribers: Boolean = true, nullMergeStrategy: NullMergeStrategy = NullMergeStrategy.TAKE_DESTINATION): ILeafDbQuery<Unit> = LeafDbModificationBlockQuery { pKeyPartialUpdate(table, document, pKey, innerDocument, notifySubscribers, nullMergeStrategy) } @JvmOverloads fun insertAll(table: String, documents: Any, pathToArray: Field = Field(), innerDocument: Field? = null, notifySubscribers: Boolean = true): ILeafDbQuery<Unit> = bulkUpdate(table, extractDocuments(documents, pathToArray), { insert(table, it, innerDocument, false).execute() }, notifySubscribers) @JvmOverloads fun insertOrUpdateAll(table: String, documents: Any, pKey: Field, pathToArray: Field = Field(), innerDocument: Field? = null, notifySubscribers: Boolean = true): ILeafDbQuery<Unit> = bulkUpdate(table, extractDocuments(documents, pathToArray), { insertOrUpdate(table, it, pKey, innerDocument, false).execute() }, notifySubscribers) @JvmOverloads fun updateAll(table: String, documents: Any, pKey: Field, pathToArray: Field = Field(), innerDocument: Field? = null, notifySubscribers: Boolean = true): ILeafDbQuery<Unit> = bulkUpdate(table, extractDocuments(documents, pathToArray), { update(table, it, pKey, innerDocument, false).execute() }, notifySubscribers) @JvmOverloads fun <T : Any> updateAll(table: String, documents: Iterable<T>, predicate: (T) -> Condition?, innerDocument: Field? = null, notifySubscribers: Boolean = true): ILeafDbQuery<Unit> = bulkUpdate(table, { documents }, { update(table, it, predicate(it), innerDocument, false).execute() }, notifySubscribers) @JvmOverloads fun partialUpdateAll(table: String, documents: Any, pKey: Field, pathToArray: Field = Field(), innerDocument: Field? = null, notifySubscribers: Boolean = true, nullMergeStrategy: NullMergeStrategy = NullMergeStrategy.TAKE_DESTINATION): ILeafDbQuery<Unit> = bulkUpdate(table, extractDocuments(documents, pathToArray), { partialUpdate(table, it, pKey, innerDocument, false, nullMergeStrategy).execute() }, notifySubscribers) @JvmOverloads fun <T : Any> partialUpdateAll(table: String, documents: Iterable<T>, predicate: (T) -> Condition?, innerDocument: Field? = null, notifySubscribers: Boolean = true, nullMergeStrategy: NullMergeStrategy = NullMergeStrategy.TAKE_DESTINATION): ILeafDbQuery<Unit> = bulkUpdate(table, { documents }, { partialUpdate(table, it, predicate(it), innerDocument, false, nullMergeStrategy).execute() }, notifySubscribers) private fun pKeyPartialUpdate(table: String, document: Any, pKey: Field, innerDocument: Field?, notifySubscribers: Boolean = true, nullMergeStrategy: NullMergeStrategy = NullMergeStrategy.TAKE_DESTINATION) { val query = getInnerDocConditionSql(pKey, document, innerDocument) doPartialUpdate(query, table, document, innerDocument, notifySubscribers, nullMergeStrategy) } private fun conditionalPartialUpdate(table: String, document: Any, condition: Condition?, innerDocument: Field?, notifySubscribers: Boolean = true, nullMergeStrategy: NullMergeStrategy = NullMergeStrategy.TAKE_DESTINATION) { val query = getIndexedDocsQuery(table, condition) doPartialUpdate(query, table, document, innerDocument, notifySubscribers, nullMergeStrategy) } private fun doPartialUpdate(query: String, table: String, document: Any, innerDocument: Field?, notifySubscribers: Boolean, nullMergeStrategy: NullMergeStrategy) { val readableDb = leafDbProvider.readableDb val originals = readableDb.selectQuery(query).collectIndexedStrings(2) readableDb.close() originals.forEach { (first, second) -> entryUpdate(table, document, innerDocument, notifySubscribers) { t, d -> getUpdateByIdSql(t, serializer.merge(d, second, nullMergeStrategy), first) }.execute() } } private fun extractDocuments(documents: Any, pathToArray: Field) = { if (documents is String && isJson(documents)) getInnerArray(documents, pathToArray).execute() else getInnerArray(serializer.getJsonFromObject(documents), pathToArray).execute() } private fun <T : Any> bulkUpdate(table: String, docProvider: () -> Iterable<T>, queryRunner: (doc: T) -> Unit, notifySubscribers: Boolean = true) = LeafDbModificationBlockQuery { val docs = docProvider() docs.forEach(queryRunner) if (notifySubscribers) leafDbProvider.notifySubscribers(table) } //todo // fun getDocCountQuery(table: String, pKey: Field, document: Any, innerDocument: Field?) = // "SELECT COUNT(*) FROM $table ${getInnerDocConditionSql(pKey, document, innerDocument)};" // // fun getInnerDocConditionSql(pKey: Field, document: Any, innerDocument: Field?) = // "WHERE $pKey = (${getExtractSql(pKey, getDoc(document, innerDocument))})" // // fun getInnerArrayQuery(path: Field, json: String) = // "SELECT value FROM (SELECT json_each($path) FROM (SELECT ${json.sqlValue} as doc));" private fun getRandomQuery() = "SELECT random();" private fun getEngineVersionQuery() = "SELECT sqlite_version();" private fun getJsonValidQuery(doc: String) = "SELECT json_valid(${doc.sqlValue});" private fun getInnerDocumentSql(path: Field, json: String) = "${getExtractSql(path, json)};" private fun getDeleteQuery(table: String, condition: Condition?) = "DELETE FROM $table${getConditionBlock(condition)};" private fun getCountQuery(table: String, condition: Condition?) = "SELECT COUNT(*) FROM $table${getConditionBlock(condition)};" private fun getDocCountQuery(table: String, pKey: Field, document: Any, innerDocument: Field?) = "SELECT COUNT(*) FROM $table ${getInnerDocConditionSql(pKey, document, innerDocument)};" private fun getIndexedDocsQuery(table: String, condition: Condition?) = "SELECT id, doc FROM $table ${getConditionBlock(condition)};" private fun getInnerArrayQuery(path: Field, json: String) = "SELECT value FROM (SELECT json_each($path) FROM (SELECT ${json.sqlValue} as doc));" private fun getInsertSql(table: String, doc: String) = "INSERT into $table (timestamp, doc) values (strftime('%s','now'), ${doc.sqlValue});" private fun getUpdateSql(table: String, doc: String, condition: Condition? = null) = "UPDATE $table SET timestamp = strftime('%s','now'), doc = ${doc.sqlValue}${getConditionBlock(condition)};" private fun getUpdateByIdSql(table: String, doc: String, id: Long) = "UPDATE $table SET timestamp = strftime('%s','now'), doc = ${doc.sqlValue} WHERE id = $id;" private fun getUpdateSql(table: String, doc: String, conditionSql: String) = "UPDATE $table SET timestamp = strftime('%s','now'), doc = ${doc.sqlValue} $conditionSql;" private fun getAggregationQuery(aggregateFunction: AggregateFunction, field: Field, table: String, condition: Condition?) = "SELECT $aggregateFunction(f) FROM (SELECT $field AS f FROM $table${getConditionBlock(condition)});" //internal private fun getExtractSql(path: Field, json: String) = "SELECT $path FROM (SELECT ${json.sqlValue} as doc)" private fun getConditionBlock(condition: Condition?) = if (condition != null) " WHERE $condition" else "" private fun getInnerDocConditionSql(pKey: Field, document: Any, innerDocument: Field?) = "WHERE $pKey = (${getExtractSql(pKey, getDoc(document, innerDocument))})" }
lgpl-3.0
16bded4bc4596b4933e54e3c94fed9c6
54.096774
265
0.693648
4.422006
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/domain/library/model/LibraryDisplayMode.kt
1
1761
package eu.kanade.domain.library.model import eu.kanade.domain.category.model.Category sealed class LibraryDisplayMode( override val flag: Long, ) : FlagWithMask { override val mask: Long = 0b00000011L object CompactGrid : LibraryDisplayMode(0b00000000) object ComfortableGrid : LibraryDisplayMode(0b00000001) object List : LibraryDisplayMode(0b00000010) object CoverOnlyGrid : LibraryDisplayMode(0b00000011) object Serializer { fun deserialize(serialized: String): LibraryDisplayMode { return LibraryDisplayMode.deserialize(serialized) } fun serialize(value: LibraryDisplayMode): String { return value.serialize() } } companion object { val values = setOf(CompactGrid, ComfortableGrid, List, CoverOnlyGrid) val default = CompactGrid fun valueOf(flag: Long?): LibraryDisplayMode { if (flag == null) return default return values .find { mode -> mode.flag == flag and mode.mask } ?: default } fun deserialize(serialized: String): LibraryDisplayMode { return when (serialized) { "COMFORTABLE_GRID" -> ComfortableGrid "COMPACT_GRID" -> CompactGrid "COVER_ONLY_GRID" -> CoverOnlyGrid "LIST" -> List else -> default } } } fun serialize(): String { return when (this) { ComfortableGrid -> "COMFORTABLE_GRID" CompactGrid -> "COMPACT_GRID" CoverOnlyGrid -> "COVER_ONLY_GRID" List -> "LIST" } } } val Category.display: LibraryDisplayMode get() = LibraryDisplayMode.valueOf(flags)
apache-2.0
d4fb1c44dae4548f4f22689d59726d24
28.847458
77
0.605906
4.646438
false
false
false
false
k9mail/k-9
app/storage/src/main/java/com/fsck/k9/preferences/migrations/StorageMigrationTo7.kt
2
1547
package com.fsck.k9.preferences.migrations import android.database.sqlite.SQLiteDatabase /** * Rewrite settings to use enum names instead of ordinals. */ class StorageMigrationTo7( private val db: SQLiteDatabase, private val migrationsHelper: StorageMigrationsHelper ) { fun rewriteEnumOrdinalsToNames() { rewriteTheme() rewriteMessageViewTheme() rewriteMessageComposeTheme() } private fun rewriteTheme() { val theme = migrationsHelper.readValue(db, "theme")?.toInt() val newTheme = if (theme == THEME_ORDINAL_DARK) { THEME_DARK } else { THEME_LIGHT } migrationsHelper.writeValue(db, "theme", newTheme) } private fun rewriteMessageViewTheme() { rewriteScreenTheme("messageViewTheme") } private fun rewriteMessageComposeTheme() { rewriteScreenTheme("messageComposeTheme") } private fun rewriteScreenTheme(key: String) { val newTheme = when (migrationsHelper.readValue(db, key)?.toInt()) { THEME_ORDINAL_DARK -> THEME_DARK THEME_ORDINAL_USE_GLOBAL -> THEME_USE_GLOBAL else -> THEME_LIGHT } migrationsHelper.writeValue(db, key, newTheme) } companion object { private const val THEME_ORDINAL_DARK = 1 private const val THEME_ORDINAL_USE_GLOBAL = 2 private const val THEME_LIGHT = "LIGHT" private const val THEME_DARK = "DARK" private const val THEME_USE_GLOBAL = "USE_GLOBAL" } }
apache-2.0
f573d32ec8cd761ed685bb35fc23440e
27.648148
76
0.64512
4.604167
false
false
false
false