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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
smmribeiro/intellij-community
|
plugins/devkit/devkit-core/src/i18n/IntelliJProjectResourceBundleManager.kt
|
4
|
3210
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.devkit.i18n
import com.intellij.lang.properties.psi.I18nizedTextGenerator
import com.intellij.lang.properties.psi.PropertiesFile
import com.intellij.lang.properties.psi.ResourceBundleManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiShortNamesCache
import com.intellij.util.PathUtil
import org.jetbrains.idea.devkit.actions.generateDefaultBundleName
import org.jetbrains.idea.devkit.util.PsiUtil
class IntelliJProjectResourceBundleManager(project: Project) : ResourceBundleManager(project) {
override fun isActive(context: PsiFile): Boolean {
return PsiUtil.isIdeaProject(myProject)
}
override fun escapeValue(value: String): String {
return value.replace("&", "\\&")
}
override fun suggestPropertiesFiles(contextModules: MutableSet<Module>): MutableList<String> {
val preferredBundleNames = contextModules.mapTo(HashSet()) { generateDefaultBundleName(it) }
val files = super.suggestPropertiesFiles(contextModules)
val (preferredFiles, otherFiles) = files.partition {
FileUtil.getNameWithoutExtension(PathUtil.getFileName(it)) in preferredBundleNames
}
return (preferredFiles + otherFiles).toMutableList()
}
override fun getI18nizedTextGenerator(): I18nizedTextGenerator? {
return object : I18nizedTextGenerator() {
override fun getI18nizedText(propertyKey: String, propertiesFile: PropertiesFile?, context: PsiElement?): String {
return getI18nizedConcatenationText(propertyKey, "", propertiesFile, context)
}
override fun getI18nizedConcatenationText(propertyKey: String,
parametersString: String,
propertiesFile: PropertiesFile?,
context: PsiElement?): String {
val bundleClassName = suggestBundleClassName(propertiesFile, context)
val args = if (parametersString.isNotEmpty()) ", $parametersString" else ""
return "$bundleClassName.message(\"$propertyKey\"$args)"
}
private fun suggestBundleClassName(propertiesFile: PropertiesFile?, context: PsiElement?): String {
if (propertiesFile == null) return "UnknownBundle"
val bundleName = propertiesFile.virtualFile.nameWithoutExtension
val scope = context?.resolveScope ?: GlobalSearchScope.projectScope(myProject)
val classesByName = PsiShortNamesCache.getInstance(myProject).getClassesByName(bundleName, scope)
return classesByName.firstOrNull()?.qualifiedName ?: bundleName
}
}
}
override fun getResourceBundle(): PsiClass? = null
override fun getTemplateName(): String? = null
override fun getConcatenationTemplateName(): String? = null
override fun canShowJavaCodeInfo(): Boolean = false
}
|
apache-2.0
|
e9a782f023e96649e57baa9b264645cd
| 47.651515 | 140 | 0.740187 | 4.908257 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/ReplaceWithAnnotationAnalyzer.kt
|
2
|
11633
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.replaceWith
import com.intellij.openapi.diagnostic.ControlFlowException
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.analysis.analyzeInContext
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.codeInliner.CodeToInline
import org.jetbrains.kotlin.idea.codeInliner.CodeToInlineBuilder
import org.jetbrains.kotlin.idea.core.unwrapIfFakeOverride
import org.jetbrains.kotlin.idea.project.findAnalyzerServices
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.resolve.getLanguageVersionSettings
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtUserType
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.lazy.descriptors.ClassResolutionScopesSupport
import org.jetbrains.kotlin.resolve.scopes.*
import org.jetbrains.kotlin.resolve.scopes.utils.chainImportingScopes
import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices
data class ReplaceWith(val pattern: String, val imports: List<String>, val replaceInWholeProject: Boolean)
@OptIn(FrontendInternals::class)
object ReplaceWithAnnotationAnalyzer {
fun analyzeCallableReplacement(
annotation: ReplaceWith,
symbolDescriptor: CallableDescriptor,
resolutionFacade: ResolutionFacade,
reformat: Boolean
): CodeToInline? {
val originalDescriptor = symbolDescriptor.unwrapIfFakeOverride().original
return analyzeOriginal(annotation, originalDescriptor, resolutionFacade, reformat)
}
private fun analyzeOriginal(
annotation: ReplaceWith,
symbolDescriptor: CallableDescriptor,
resolutionFacade: ResolutionFacade,
reformat: Boolean
): CodeToInline? {
val psiFactory = KtPsiFactory(resolutionFacade.project)
val expression = psiFactory.createExpressionIfPossible(annotation.pattern) ?: return null
val module = resolutionFacade.moduleDescriptor
val scope = buildScope(resolutionFacade, annotation, symbolDescriptor) ?: return null
val expressionTypingServices = resolutionFacade.getFrontendService(module, ExpressionTypingServices::class.java)
fun analyzeExpression(ignore: KtExpression) = expression.analyzeInContext(
scope,
expressionTypingServices = expressionTypingServices
)
return CodeToInlineBuilder(symbolDescriptor, resolutionFacade, originalDeclaration = null).prepareCodeToInline(
expression,
emptyList(),
::analyzeExpression,
reformat,
)
}
fun analyzeClassifierReplacement(
annotation: ReplaceWith,
symbolDescriptor: ClassifierDescriptorWithTypeParameters,
resolutionFacade: ResolutionFacade
): KtUserType? {
val psiFactory = KtPsiFactory(resolutionFacade.project)
val typeReference = try {
psiFactory.createType(annotation.pattern)
} catch (e: Exception) {
if (e is ControlFlowException) throw e
return null
}
if (typeReference.typeElement !is KtUserType) return null
val scope = buildScope(resolutionFacade, annotation, symbolDescriptor) ?: return null
val typeResolver = resolutionFacade.getFrontendService(TypeResolver::class.java)
val bindingTrace = BindingTraceContext()
typeResolver.resolvePossiblyBareType(TypeResolutionContext(scope, bindingTrace, false, true, false), typeReference)
val typesToQualify = ArrayList<Pair<KtNameReferenceExpression, FqName>>()
typeReference.forEachDescendantOfType<KtNameReferenceExpression> { expression ->
val parentType = expression.parent as? KtUserType ?: return@forEachDescendantOfType
if (parentType.qualifier != null) return@forEachDescendantOfType
val targetClass = bindingTrace.bindingContext[BindingContext.REFERENCE_TARGET, expression] as? ClassDescriptor
?: return@forEachDescendantOfType
val fqName = targetClass.fqNameUnsafe
if (fqName.isSafe) {
typesToQualify.add(expression to fqName.toSafe())
}
}
for ((nameExpression, fqName) in typesToQualify) {
nameExpression.mainReference.bindToFqName(fqName, KtSimpleNameReference.ShorteningMode.NO_SHORTENING)
}
return typeReference.typeElement as KtUserType
}
private fun buildScope(
resolutionFacade: ResolutionFacade,
annotation: ReplaceWith,
symbolDescriptor: DeclarationDescriptor
): LexicalScope? {
val module = resolutionFacade.moduleDescriptor
val explicitImportsScope = buildExplicitImportsScope(annotation, resolutionFacade, module)
val languageVersionSettings = resolutionFacade.getLanguageVersionSettings()
val defaultImportsScopes = buildDefaultImportsScopes(resolutionFacade, module, languageVersionSettings)
return getResolutionScope(
symbolDescriptor, symbolDescriptor, listOf(explicitImportsScope), defaultImportsScopes, languageVersionSettings
)
}
private fun buildDefaultImportsScopes(
resolutionFacade: ResolutionFacade,
module: ModuleDescriptor,
languageVersionSettings: LanguageVersionSettings
): List<ImportingScope> {
val allDefaultImports =
resolutionFacade.frontendService<TargetPlatform>().findAnalyzerServices(resolutionFacade.project)
.getDefaultImports(languageVersionSettings, includeLowPriorityImports = true)
val (allUnderImports, aliasImports) = allDefaultImports.partition { it.isAllUnder }
// this solution doesn't support aliased default imports with a different alias
// TODO: Create import directives from ImportPath, create ImportResolver, create LazyResolverScope, see FileScopeProviderImpl
return listOf(buildExplicitImportsScope(aliasImports.map { it.fqName }, resolutionFacade, module)) +
allUnderImports.map { module.getPackage(it.fqName).memberScope.memberScopeAsImportingScope() }.asReversed()
}
private fun buildExplicitImportsScope(
annotation: ReplaceWith,
resolutionFacade: ResolutionFacade,
module: ModuleDescriptor
): ExplicitImportsScope {
return buildExplicitImportsScope(importFqNames(annotation), resolutionFacade, module)
}
private fun buildExplicitImportsScope(
importFqNames: List<FqName>,
resolutionFacade: ResolutionFacade,
module: ModuleDescriptor
): ExplicitImportsScope {
val importedSymbols = importFqNames.flatMap { resolutionFacade.resolveImportReference(module, it) }
return ExplicitImportsScope(importedSymbols)
}
private fun importFqNames(annotation: ReplaceWith): List<FqName> {
return annotation.imports
.asSequence()
.filter { FqNameUnsafe.isValid(it) }
.map(::FqNameUnsafe)
.filter(FqNameUnsafe::isSafe)
.map(FqNameUnsafe::toSafe)
.toList()
}
private fun getResolutionScope(
descriptor: DeclarationDescriptor,
ownerDescriptor: DeclarationDescriptor,
explicitScopes: Collection<ExplicitImportsScope>,
additionalScopes: Collection<ImportingScope>,
languageVersionSettings: LanguageVersionSettings
): LexicalScope? {
return when (descriptor) {
is PackageFragmentDescriptor -> {
val moduleDescriptor = descriptor.containingDeclaration
getResolutionScope(
moduleDescriptor.getPackage(descriptor.fqName),
ownerDescriptor,
explicitScopes,
additionalScopes,
languageVersionSettings
)
}
is PackageViewDescriptor -> {
val memberAsImportingScope = descriptor.memberScope.memberScopeAsImportingScope()
LexicalScope.Base(
chainImportingScopes(explicitScopes + listOf(memberAsImportingScope) + additionalScopes)!!,
ownerDescriptor
)
}
is ClassDescriptor -> {
val outerScope = getResolutionScope(
descriptor.containingDeclaration, ownerDescriptor, explicitScopes, additionalScopes, languageVersionSettings
) ?: return null
ClassResolutionScopesSupport(
descriptor,
LockBasedStorageManager.NO_LOCKS,
languageVersionSettings
) { outerScope }.scopeForMemberDeclarationResolution()
}
is TypeAliasDescriptor -> {
val outerScope = getResolutionScope(
descriptor.containingDeclaration, ownerDescriptor, explicitScopes, additionalScopes, languageVersionSettings
) ?: return null
LexicalScopeImpl(
outerScope,
descriptor,
false,
null,
LexicalScopeKind.TYPE_ALIAS_HEADER,
LocalRedeclarationChecker.DO_NOTHING
) {
for (typeParameter in descriptor.declaredTypeParameters) {
addClassifierDescriptor(typeParameter)
}
}
}
is FunctionDescriptor -> {
val outerScope = getResolutionScope(
descriptor.containingDeclaration, ownerDescriptor, explicitScopes, additionalScopes, languageVersionSettings
) ?: return null
FunctionDescriptorUtil.getFunctionInnerScope(outerScope, descriptor, LocalRedeclarationChecker.DO_NOTHING)
}
is PropertyDescriptor -> {
val outerScope = getResolutionScope(
descriptor.containingDeclaration, ownerDescriptor, explicitScopes, additionalScopes, languageVersionSettings
) ?: return null
val propertyHeader = ScopeUtils.makeScopeForPropertyHeader(outerScope, descriptor)
LexicalScopeImpl(
propertyHeader,
descriptor,
false,
descriptor.extensionReceiverParameter,
LexicalScopeKind.PROPERTY_ACCESSOR_BODY
)
}
else -> return null // something local, should not work with ReplaceWith
}
}
}
|
apache-2.0
|
7a79b0a27bdd50054886ad8cace07226
| 44.264591 | 158 | 0.694748 | 6.38124 | false | false | false | false |
smmribeiro/intellij-community
|
platform/platform-impl/src/com/intellij/presentation/impl/FilePresentationServiceImpl.kt
|
10
|
1895
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.presentation.impl
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.VfsPresentationUtil
import com.intellij.presentation.FilePresentationService
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiDirectoryContainer
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiUtilCore
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.concurrency.annotations.RequiresReadLock
import java.awt.Color
class FilePresentationServiceImpl(private val project: Project) : FilePresentationService {
@RequiresReadLock
@RequiresBackgroundThread
override fun getFileBackgroundColor(file: VirtualFile): Color? {
require(file.isValid)
return VfsPresentationUtil.getFileBackgroundColor(project, file)
}
@RequiresReadLock
@RequiresBackgroundThread
override fun getFileBackgroundColor(element: PsiElement): Color? {
PsiUtilCore.ensureValid(element)
val file = PsiUtilCore.getVirtualFile(element)
if (file != null) {
return getFileBackgroundColor(file)
}
else if (element is PsiDirectory) {
return getFileBackgroundColor(element.virtualFile)
}
else if (element is PsiDirectoryContainer) {
var result: Color? = null
for (dir in element.directories) {
val color = getFileBackgroundColor(dir.virtualFile) ?: continue
if (result == null) {
// color of the first directory
result = color
}
else if (result != color) {
// more than 1 directory with different colors
return null
}
}
return result
}
return null
}
}
|
apache-2.0
|
1bb0ecff3b92edc9d5026ef1cc8fed3c
| 34.754717 | 158 | 0.744063 | 4.749373 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/expectactual/AddActualFix.kt
|
3
|
4400
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.expectactual
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.toDescriptor
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.quickfix.TypeAccessibilityChecker
import org.jetbrains.kotlin.idea.refactoring.getExpressionShortText
import org.jetbrains.kotlin.idea.util.module
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class AddActualFix(
actualClassOrObject: KtClassOrObject,
missedDeclarations: List<KtDeclaration>
) : KotlinQuickFixAction<KtClassOrObject>(actualClassOrObject) {
private val missedDeclarationPointers = missedDeclarations.map { it.createSmartPointer() }
override fun getFamilyName() = text
override fun getText() = KotlinBundle.message("fix.create.missing.actual.members")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val factory = KtPsiFactory(element)
val codeStyleManager = CodeStyleManager.getInstance(project)
fun PsiElement.clean() {
ShortenReferences.DEFAULT.process(codeStyleManager.reformat(this) as KtElement)
}
val module = element.module ?: return
val checker = TypeAccessibilityChecker.create(project, module)
val errors = linkedMapOf<KtDeclaration, KotlinTypeInaccessibleException>()
for (missedDeclaration in missedDeclarationPointers.mapNotNull { it.element }) {
val actualDeclaration = try {
when (missedDeclaration) {
is KtClassOrObject -> factory.generateClassOrObject(project, false, missedDeclaration, checker)
is KtFunction, is KtProperty -> missedDeclaration.toDescriptor()?.safeAs<CallableMemberDescriptor>()?.let {
generateCallable(project, false, missedDeclaration, it, element, checker = checker)
}
else -> null
} ?: continue
} catch (e: KotlinTypeInaccessibleException) {
errors += missedDeclaration to e
continue
}
if (actualDeclaration is KtPrimaryConstructor) {
if (element.primaryConstructor == null)
element.addAfter(actualDeclaration, element.nameIdentifier).clean()
} else {
element.addDeclaration(actualDeclaration).clean()
}
}
if (errors.isNotEmpty()) {
val message = errors.entries.joinToString(
separator = "\n",
prefix = KotlinBundle.message("fix.create.declaration.error.some.types.inaccessible") + "\n"
) { (declaration, error) ->
getExpressionShortText(declaration) + " -> " + error.message
}
showInaccessibleDeclarationError(element, message, editor)
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val missedDeclarations = DiagnosticFactory.cast(diagnostic, Errors.NO_ACTUAL_CLASS_MEMBER_FOR_EXPECTED_CLASS).b.mapNotNull {
DescriptorToSourceUtils.descriptorToDeclaration(it.first) as? KtDeclaration
}.ifEmpty { return null }
return (diagnostic.psiElement as? KtClassOrObject)?.let {
AddActualFix(it, missedDeclarations)
}
}
}
}
|
apache-2.0
|
07ca3048ef5cc12713a5ffe99e7643f8
| 45.819149 | 158 | 0.704318 | 5.346294 | false | false | false | false |
fabmax/kool
|
kool-core/src/commonMain/kotlin/de/fabmax/kool/pipeline/deferred/Reflections.kt
|
1
|
1449
|
package de.fabmax.kool.pipeline.deferred
import de.fabmax.kool.KoolContext
import de.fabmax.kool.math.clamp
import de.fabmax.kool.pipeline.Texture2d
class Reflections(cfg: DeferredPipelineConfig) : DeferredPassSwapListener {
val reflectionPass = ReflectionPass(cfg.baseReflectionStep)
val denoisePass = ReflectionDenoisePass(reflectionPass)
val reflectionMap: Texture2d
get() = denoisePass.colorTexture!!
// reflection map size relative to screen resolution
var mapSize = 0.5f
var isEnabled: Boolean
get() = reflectionPass.isEnabled && denoisePass.isEnabled
set(value) {
reflectionPass.isEnabled = value
denoisePass.isEnabled = value
}
fun checkSize(viewportW: Int, viewportH: Int, ctx: KoolContext) {
if (isEnabled) {
val width = (viewportW * mapSize).toInt().clamp(1, 4096)
val height = (viewportH * mapSize).toInt().clamp(1, 4096)
if (isEnabled && (width != reflectionPass.width || height != reflectionPass.height)) {
reflectionPass.resize(width, height, ctx)
denoisePass.resize(width, height, ctx)
}
}
}
override fun onSwap(previousPasses: DeferredPasses, currentPasses: DeferredPasses) {
reflectionPass.setInput(currentPasses.lightingPass, currentPasses.materialPass)
denoisePass.setPositionInput(currentPasses.materialPass)
}
}
|
apache-2.0
|
3febcce2a92d0d3693e250359a0b3c72
| 35.25 | 98 | 0.681159 | 4.2 | false | false | false | false |
kohesive/kohesive-iac
|
cloudtrail-tool/src/main/kotlin/uy/kohesive/iac/model/aws/cloudtrail/FileSystemEventsProcessor.kt
|
1
|
1957
|
package uy.kohesive.iac.model.aws.cloudtrail
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import uy.kohesive.iac.model.aws.utils.CasePreservingJacksonNamingStrategy
import java.io.File
import java.io.FileInputStream
import java.util.zip.GZIPInputStream
class FileSystemEventsProcessor(
override val eventsFilter: EventsFilter = EventsFilter.Empty,
override val ignoreFailedRequests: Boolean = true,
val eventsDir: File,
val oneEventPerFile: Boolean,
val gzipped: Boolean
) : EventsProcessor {
companion object {
val JSON = jacksonObjectMapper()
.setPropertyNamingStrategy(CasePreservingJacksonNamingStrategy())
.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
}
override fun scrollEvents(): Sequence<CloudTrailEvent> = eventsDir.walkTopDown().filter { file ->
if (gzipped) {
file.name.endsWith(".json.gz")
} else {
file.name.endsWith(".json")
}
}.flatMap { file ->
FileInputStream(file).let { fis ->
when {
gzipped -> GZIPInputStream(fis)
else -> fis
}
}.use { inputStream ->
JSON.readValue<Map<String, Any>>(inputStream).let { jsonMap ->
parseEvents(jsonMap, file.nameWithoutExtension)
}
}
}
private fun parseEvents(jsonMap: Map<String, Any>, eventSourceFile: String): Sequence<CloudTrailEvent> =
if (oneEventPerFile) {
parseEvent(jsonMap, eventSourceFile)?.let { sequenceOf(it) } ?: emptySequence()
} else {
(jsonMap["Records"] as? List<Map<String, Any>>)?.mapIndexed { index, record ->
parseEvent(record, eventSourceUri = "${eventSourceFile}_$index")
}.orEmpty().filterNotNull().asSequence()
}
}
|
mit
|
1ed4dee8dbe113574d794baa3695cf1e
| 35.259259 | 108 | 0.654062 | 4.693046 | false | false | false | false |
vuyaniShabangu/now.next
|
Research/Tower-develop/Tower-develop/Android/src/org/droidplanner/android/fragments/widget/diagnostics/EkfStatusViewer.kt
|
7
|
4198
|
package org.droidplanner.android.fragments.widget.diagnostics
import android.graphics.Color
import android.os.Bundle
import android.support.annotation.StringRes
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.o3dr.services.android.lib.drone.property.EkfStatus
import com.o3dr.services.android.lib.util.SpannableUtils
import lecho.lib.hellocharts.formatter.SimpleAxisValueFormatter
import lecho.lib.hellocharts.formatter.SimpleColumnChartValueFormatter
import lecho.lib.hellocharts.model.*
import lecho.lib.hellocharts.view.ColumnChartView
import org.droidplanner.android.R
import org.droidplanner.android.fragments.helpers.ApiListenerFragment
import org.droidplanner.android.fragments.widget.diagnostics.BaseWidgetDiagnostic
import java.util.*
/**
* Created by Fredia Huya-Kouadio on 9/15/15.
*/
public class EkfStatusViewer : GraphDiagnosticViewer() {
companion object {
private val DECIMAL_DIGITS_NUMBER = 1
@StringRes public val LABEL_ID: Int = R.string.title_ekf_status_viewer
}
override fun getViewPort(refViewPort: Viewport?): Viewport {
val viewPort = refViewPort?: Viewport()
viewPort.bottom = 0f
viewPort.top = 1f
viewPort.left = -0.5f
viewPort.right = 4.5f
return viewPort
}
override fun getYAxis() = Axis.generateAxisFromRange(0f, 1f, 0.1f)
.setHasLines(true)
.setFormatter(SimpleAxisValueFormatter(DECIMAL_DIGITS_NUMBER))
override fun getXAxis() = Axis.generateAxisFromCollection(listOf(0f, 1f, 2f, 3f, 4f),
listOf("vel", "h. pos", "v. pos", "mag", "terrain"))
override fun getFormatter() = SimpleColumnChartValueFormatter(DECIMAL_DIGITS_NUMBER)
override fun getColumns(): ArrayList<Column> {
//Create a column for each variance
val varianceCols = ArrayList<Column>()
//Velocity column
varianceCols.add(generateDisabledColumn())
//Horizontal position column
varianceCols.add(generateDisabledColumn())
//Vertical position column
varianceCols.add(generateDisabledColumn())
//Compass variance
varianceCols.add(generateDisabledColumn())
//Terrain variance
varianceCols.add(generateDisabledColumn())
return varianceCols
}
override fun updateEkfView(ekfStatus: EkfStatus){
val variances = listOf(ekfStatus.velocityVariance,
ekfStatus.horizontalPositionVariance,
ekfStatus.verticalPositionVariance,
ekfStatus.compassVariance,
ekfStatus.terrainAltitudeVariance)
var maxVariance = 0f
val cols = chartData.columns
val colsCount = cols.size -1
for( i in 0..colsCount){
val variance = variances.get(i)
maxVariance = Math.max(maxVariance, variance)
val varianceColor = if (variance < BaseWidgetDiagnostic.GOOD_VARIANCE_THRESHOLD) goodStatusColor
else if (variance < BaseWidgetDiagnostic.WARNING_VARIANCE_THRESHOLD) warningStatusColor
else dangerStatusColor
val col = cols.get(i)
for (value in col.values) {
value.setTarget(variance)
value.setColor(varianceColor)
}
}
graph?.startDataAnimation()
val parentFragment = parentFragment
if(parentFragment is FullWidgetDiagnostics){
val label = getText(LABEL_ID)
val widgetTitle =
if (maxVariance < BaseWidgetDiagnostic.GOOD_VARIANCE_THRESHOLD) SpannableUtils.color(goodStatusColor, label)
else if (maxVariance < BaseWidgetDiagnostic.WARNING_VARIANCE_THRESHOLD) SpannableUtils.color(warningStatusColor, label)
else SpannableUtils.color(dangerStatusColor, label)
parentFragment.setAdapterViewTitle(0, widgetTitle)
}
}
override fun disableGraph(){
super.disableGraph()
val parentFragment = parentFragment
if(parentFragment is FullWidgetDiagnostics){
parentFragment.setAdapterViewTitle(0, getText(LABEL_ID))
}
}
}
|
mit
|
ba64b40cf4ea0d875649899cd51312b5
| 34.888889 | 139 | 0.686756 | 4.572985 | false | false | false | false |
siosio/intellij-community
|
platform/platform-impl/src/com/intellij/diagnostic/ErrorReportConfigurable.kt
|
2
|
3173
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.diagnostic
import com.intellij.credentialStore.CredentialAttributes
import com.intellij.credentialStore.Credentials
import com.intellij.credentialStore.SERVICE_NAME_PREFIX
import com.intellij.credentialStore.isFulfilled
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.components.*
import com.intellij.openapi.util.SimpleModificationTracker
import com.intellij.util.xmlb.annotations.Attribute
import com.intellij.util.xmlb.annotations.XCollection
@State(name = "ErrorReportConfigurable", storages = [Storage(StoragePathMacros.CACHE_FILE)])
internal class ErrorReportConfigurable : PersistentStateComponent<DeveloperList>, SimpleModificationTracker() {
companion object {
@JvmStatic
private val SERVICE_NAME = "$SERVICE_NAME_PREFIX — JetBrains Account"
@JvmStatic
fun getInstance() = service<ErrorReportConfigurable>()
@JvmStatic
fun getCredentials() = PasswordSafe.instance.get(CredentialAttributes(SERVICE_NAME))
@JvmStatic
fun saveCredentials(userName: String?, password: CharArray?) {
val credentials = Credentials(userName, password)
PasswordSafe.instance.set(CredentialAttributes(SERVICE_NAME, userName), credentials)
lastCredentialsState = credentialsState(credentials)
}
val userName: String?
get() = getCredentialsState().userName
val credentialsFulfilled: Boolean
get() = getCredentialsState().isFulfilled
private var lastCredentialsState: CredentialsState? = null
private fun getCredentialsState(): CredentialsState = lastCredentialsState ?: credentialsState(getCredentials())
}
var developerList = DeveloperList()
set(value) {
field = value
incModificationCount()
}
override fun getState() = developerList
override fun loadState(value: DeveloperList) {
developerList = value
}
}
private data class CredentialsState(val userName: String?, val isFulfilled: Boolean)
private fun credentialsState(credentials: Credentials?): CredentialsState =
CredentialsState(credentials?.userName ?: "", credentials.isFulfilled())
// 24 hours
private const val UPDATE_INTERVAL = 24L * 60 * 60 * 1000
internal class DeveloperList {
constructor() {
developers = mutableListOf()
timestamp = 0
}
constructor(list: MutableList<Developer>) {
developers = list
timestamp = System.currentTimeMillis()
}
@field:XCollection(style = XCollection.Style.v2)
val developers: List<Developer>
@field:Attribute
var timestamp: Long
private set
fun isUpToDateAt() = timestamp != 0L && (System.currentTimeMillis() - timestamp) < UPDATE_INTERVAL
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as DeveloperList
return developers == other.developers || timestamp == other.timestamp
}
override fun hashCode(): Int {
var result = developers.hashCode()
result = 31 * result + timestamp.hashCode()
return result
}
}
|
apache-2.0
|
ab9ecb64a8a5844867b6db928230f188
| 31.367347 | 140 | 0.749921 | 4.775602 | false | false | false | false |
rei-m/HBFav_material
|
app/src/main/kotlin/me/rei_m/hbfavmaterial/viewmodel/widget/fragment/FavoriteBookmarkFragmentViewModel.kt
|
1
|
5338
|
/*
* Copyright (c) 2017. Rei Matsushita
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package me.rei_m.hbfavmaterial.viewmodel.widget.fragment
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.databinding.Observable
import android.databinding.ObservableArrayList
import android.databinding.ObservableBoolean
import android.databinding.ObservableField
import android.view.View
import android.widget.AbsListView
import android.widget.AdapterView
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject
import me.rei_m.hbfavmaterial.model.FavoriteBookmarkModel
import me.rei_m.hbfavmaterial.model.UserModel
import me.rei_m.hbfavmaterial.model.entity.Bookmark
class FavoriteBookmarkFragmentViewModel(private val favoriteBookmarkModel: FavoriteBookmarkModel,
userModel: UserModel) : ViewModel() {
val bookmarkList: ObservableArrayList<Bookmark> = ObservableArrayList()
val hasNextPage: ObservableBoolean = ObservableBoolean(false)
val isVisibleEmpty: ObservableBoolean = ObservableBoolean(false)
val isVisibleProgress: ObservableBoolean = ObservableBoolean(false)
val isRefreshing: ObservableBoolean = ObservableBoolean(false)
val isVisibleError: ObservableBoolean = ObservableBoolean(false)
private var hasNextPageUpdatedEventSubject = BehaviorSubject.create<Boolean>()
val hasNextPageUpdatedEvent: io.reactivex.Observable<Boolean> = hasNextPageUpdatedEventSubject
private val onItemClickEventSubject = PublishSubject.create<Bookmark>()
val onItemClickEvent: io.reactivex.Observable<Bookmark> = onItemClickEventSubject
val onRaiseGetNextPageErrorEvent = favoriteBookmarkModel.isRaisedGetNextPageError
val onRaiseRefreshErrorEvent = favoriteBookmarkModel.isRaisedRefreshError
private val disposable: CompositeDisposable = CompositeDisposable()
private val userId: ObservableField<String> = ObservableField("")
private val userIdChangedCallback = object : Observable.OnPropertyChangedCallback() {
override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
favoriteBookmarkModel.getList(userId.get())
}
}
private val hasNextPageChangedCallback = object : Observable.OnPropertyChangedCallback() {
override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
hasNextPageUpdatedEventSubject.onNext(hasNextPage.get())
}
}
init {
userId.addOnPropertyChangedCallback(userIdChangedCallback)
hasNextPage.addOnPropertyChangedCallback(hasNextPageChangedCallback)
disposable.addAll(favoriteBookmarkModel.bookmarkList.subscribe {
if (it.isEmpty()) {
bookmarkList.clear()
} else {
bookmarkList.addAll(it - bookmarkList)
}
isVisibleEmpty.set(bookmarkList.isEmpty())
}, favoriteBookmarkModel.hasNextPage.subscribe {
hasNextPage.set(it)
}, favoriteBookmarkModel.isLoading.subscribe {
isVisibleProgress.set(it)
}, favoriteBookmarkModel.isRefreshing.subscribe {
isRefreshing.set(it)
}, favoriteBookmarkModel.isRaisedError.subscribe {
isVisibleError.set(it)
}, userModel.user.subscribe {
userId.set(it.id)
})
}
override fun onCleared() {
userId.removeOnPropertyChangedCallback(userIdChangedCallback)
hasNextPage.removeOnPropertyChangedCallback(hasNextPageChangedCallback)
disposable.dispose()
super.onCleared()
}
@Suppress("UNUSED_PARAMETER")
fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
onItemClickEventSubject.onNext(bookmarkList[position])
}
@Suppress("UNUSED_PARAMETER")
fun onScroll(listView: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
if (0 < totalItemCount && totalItemCount == firstVisibleItem + visibleItemCount) {
favoriteBookmarkModel.getNextPage(userId.get())
}
}
fun onRefresh() {
favoriteBookmarkModel.refreshList(userId.get())
}
class Factory(private val favoriteBookmarkModel: FavoriteBookmarkModel,
private val userModel: UserModel) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(FavoriteBookmarkFragmentViewModel::class.java)) {
return FavoriteBookmarkFragmentViewModel(favoriteBookmarkModel, userModel) as T
}
throw IllegalArgumentException("Unknown class name")
}
}
}
|
apache-2.0
|
41ca02bde687ef4a2dd0c2a75478c884
| 40.061538 | 112 | 0.731735 | 5.419289 | false | false | false | false |
androidx/androidx
|
room/room-compiler-processing-testing/src/main/java/androidx/room/compiler/processing/util/DiagnosticMessagesSubject.kt
|
3
|
4055
|
/*
* 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.util
import com.google.common.truth.Fact.simpleFact
import com.google.common.truth.FailureMetadata
import com.google.common.truth.Subject
import com.google.common.truth.Subject.Factory
import com.google.common.truth.Truth
/**
* Truth subject for diagnostic messages
*/
class DiagnosticMessagesSubject internal constructor(
failureMetadata: FailureMetadata,
private val diagnosticMessages: List<DiagnosticMessage>,
) : Subject<DiagnosticMessagesSubject, List<DiagnosticMessage>>(
failureMetadata, diagnosticMessages
) {
private val lineContents by lazy {
diagnosticMessages.mapNotNull {
it.location?.let { location ->
location.source?.contents?.lines()?.getOrNull(
location.line - 1
)
}
}
}
private val locations by lazy {
diagnosticMessages.mapNotNull { it.location }
}
/**
* Checks the location of the diagnostic message against the given [lineNumber].
*
* Note that if there are multiple messages, any match will be sufficient.
*/
fun onLine(lineNumber: Int) = apply {
if (locations.none {
it.line == lineNumber
}
) {
failWithActual(
simpleFact(
"expected line $lineNumber but it was " +
locations.joinToString(",")
)
)
}
}
/**
* Checks the number of messages in the subject.
*/
fun hasCount(expected: Int) = apply {
if (diagnosticMessages.size != expected) {
failWithActual(
simpleFact("expected $expected messages, found ${diagnosticMessages.size}")
)
}
}
/**
* Checks the contents of the line from the original file against the given [content].
*/
fun onLineContaining(content: String) = apply {
if (lineContents.isEmpty()) {
failWithActual(
simpleFact("Cannot validate line content due to missing location information")
)
}
if (lineContents.none {
it.contains(content)
}
) {
failWithActual(
simpleFact(
"expected line content with $content but was " +
lineContents.joinToString("\n")
)
)
}
}
/**
* Checks the contents of the source where the diagnostic message was reported on, against
* the given [source].
*/
fun onSource(source: Source) = apply {
if (locations.none { it.source == source }) {
failWithActual(
simpleFact(
"""
Expected diagnostic to be on $source but found it on
${locations.joinToString(",")}
""".trimIndent()
)
)
}
}
companion object {
private val FACTORY =
Factory<DiagnosticMessagesSubject, List<DiagnosticMessage>> { metadata, actual ->
DiagnosticMessagesSubject(metadata, actual)
}
fun assertThat(
diagnosticMessages: List<DiagnosticMessage>
): DiagnosticMessagesSubject {
return Truth.assertAbout(FACTORY).that(
diagnosticMessages
)
}
}
}
|
apache-2.0
|
fc2df02c085d3f28cba7df1e794b5746
| 29.727273 | 94 | 0.585943 | 5.06875 | false | false | false | false |
djkovrik/YapTalker
|
app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/userprofile/UserProfileFragment.kt
|
1
|
6467
|
package com.sedsoftware.yaptalker.presentation.feature.userprofile
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.View
import androidx.core.view.isGone
import com.arellomobile.mvp.presenter.InjectPresenter
import com.arellomobile.mvp.presenter.ProvidePresenter
import com.sedsoftware.yaptalker.R
import com.sedsoftware.yaptalker.common.annotation.LayoutResource
import com.sedsoftware.yaptalker.presentation.base.BaseFragment
import com.sedsoftware.yaptalker.presentation.base.enums.navigation.NavigationSection
import com.sedsoftware.yaptalker.presentation.extensions.loadFromUrl
import com.sedsoftware.yaptalker.presentation.extensions.orZero
import com.sedsoftware.yaptalker.presentation.extensions.string
import com.sedsoftware.yaptalker.presentation.model.base.UserProfileModel
import kotlinx.android.synthetic.main.fragment_user_profile.profile_bayans
import kotlinx.android.synthetic.main.fragment_user_profile.profile_birth_date
import kotlinx.android.synthetic.main.fragment_user_profile.profile_email
import kotlinx.android.synthetic.main.fragment_user_profile.profile_group
import kotlinx.android.synthetic.main.fragment_user_profile.profile_icq
import kotlinx.android.synthetic.main.fragment_user_profile.profile_interests
import kotlinx.android.synthetic.main.fragment_user_profile.profile_location
import kotlinx.android.synthetic.main.fragment_user_profile.profile_messages
import kotlinx.android.synthetic.main.fragment_user_profile.profile_messages_day
import kotlinx.android.synthetic.main.fragment_user_profile.profile_photo
import kotlinx.android.synthetic.main.fragment_user_profile.profile_photo_card
import kotlinx.android.synthetic.main.fragment_user_profile.profile_registered
import kotlinx.android.synthetic.main.fragment_user_profile.profile_rewards
import kotlinx.android.synthetic.main.fragment_user_profile.profile_sex
import kotlinx.android.synthetic.main.fragment_user_profile.profile_sign
import kotlinx.android.synthetic.main.fragment_user_profile.profile_status
import kotlinx.android.synthetic.main.fragment_user_profile.profile_time_zone
import kotlinx.android.synthetic.main.fragment_user_profile.profile_topics_today
import kotlinx.android.synthetic.main.fragment_user_profile.profile_uq
import kotlinx.android.synthetic.main.fragment_user_profile.profile_web_site
import org.jetbrains.anko.bundleOf
import java.util.Locale
import javax.inject.Inject
@LayoutResource(value = R.layout.fragment_user_profile)
class UserProfileFragment : BaseFragment(), UserProfileView {
companion object {
fun getNewInstance(userId: Int): UserProfileFragment =
UserProfileFragment().apply {
arguments = bundleOf(USER_ID_KEY to userId)
}
private const val USER_ID_KEY = "USER_ID_KEY"
}
@Inject
@InjectPresenter
lateinit var presenter: UserProfilePresenter
@ProvidePresenter
fun provideUserProfilePresenter() = presenter
private val userId by lazy {
arguments?.getInt(USER_ID_KEY).orZero()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
presenter.loadUserProfile(userId)
}
override fun showErrorMessage(message: String) {
messagesDelegate.showMessageError(message)
}
override fun updateCurrentUiState(title: String) {
setCurrentAppbarTitle(title)
setCurrentNavDrawerItem(NavigationSection.FORUMS)
}
override fun displayProfile(profile: UserProfileModel) {
profile_uq.text = profile.uq
profile_sign.text = profile.signature
profile_rewards.text = profile.rewards
context?.let { ctx ->
profile_group.text = String.format(
Locale.getDefault(),
ctx.string(R.string.profile_group), profile.group
)
profile_status.text = String.format(
Locale.getDefault(),
ctx.string(R.string.profile_status), profile.status
)
profile_registered.text = String.format(
Locale.getDefault(),
ctx.string(R.string.profile_registered), profile.registerDate
)
profile_time_zone.text = String.format(
Locale.getDefault(),
ctx.string(R.string.profile_time_zone), profile.timeZone
)
profile_birth_date.text = String.format(
Locale.getDefault(),
ctx.string(R.string.profile_birth_date), profile.birthDate
)
profile_location.text = String.format(
Locale.getDefault(),
ctx.string(R.string.profile_location), profile.location
)
profile_interests.text = String.format(
Locale.getDefault(),
ctx.string(R.string.profile_interests), profile.interests
)
profile_sex.text = String.format(
Locale.getDefault(),
ctx.string(R.string.profile_sex), profile.sex
)
profile_messages.text = String.format(
Locale.getDefault(),
ctx.string(R.string.profile_messages), profile.messagesCount
)
profile_messages_day.text = String.format(
Locale.getDefault(),
ctx.string(R.string.profile_messages_day), profile.messsagesPerDay
)
profile_bayans.text = String.format(
Locale.getDefault(),
ctx.string(R.string.profile_bayans), profile.bayans
)
profile_topics_today.text = String.format(
Locale.getDefault(),
ctx.string(R.string.profile_topics_today), profile.todayTopics
)
profile_email.text = String.format(
Locale.getDefault(),
ctx.string(R.string.profile_email), profile.email
)
profile_icq.text = String.format(
Locale.getDefault(),
ctx.string(R.string.profile_icq), profile.icq
)
}
profile_web_site.text = profile.website
profile_web_site.movementMethod = LinkMovementMethod.getInstance()
if (profile.photo.isNotEmpty()) {
profile_photo.loadFromUrl(profile.photo)
} else {
profile_photo_card.isGone = true
}
}
}
|
apache-2.0
|
dcebee0e883a3985ee9cb73398516cac
| 41.546053 | 85 | 0.690119 | 4.522378 | false | false | false | false |
djkovrik/YapTalker
|
data/src/main/java/com/sedsoftware/yaptalker/data/parsed/NewsPageParsed.kt
|
1
|
621
|
package com.sedsoftware.yaptalker.data.parsed
import pl.droidsonroids.jspoon.annotation.Selector
/**
* Class which represents parsed news page in data layer.
*/
class NewsPageParsed {
@Selector(value = "td[class=newshead][id^=topic_]")
var headers: List<NewsHead> = emptyList()
@Selector(value = "td[class=postcolor news-content][id^=news_]")
var contents: List<NewsContent> = emptyList()
@Selector(value = "td[class=holder newsbottom]")
var bottoms: List<NewsBottom> = emptyList()
@Selector(value = "*", regex = "var feedOffset = (.*);", attr = "outerHtml")
var offset: String = ""
}
|
apache-2.0
|
0423a7806f8b03891f4eea8d2b882797
| 35.529412 | 80 | 0.68277 | 3.652941 | false | false | false | false |
androidx/androidx
|
compose/material3/material3/samples/src/main/java/androidx/compose/material3/samples/NavigationBarSamples.kt
|
3
|
2331
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material3.samples
import androidx.annotation.Sampled
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.tooling.preview.Preview
@Preview
@Sampled
@Composable
fun NavigationBarSample() {
var selectedItem by remember { mutableStateOf(0) }
val items = listOf("Songs", "Artists", "Playlists")
NavigationBar {
items.forEachIndexed { index, item ->
NavigationBarItem(
icon = { Icon(Icons.Filled.Favorite, contentDescription = item) },
label = { Text(item) },
selected = selectedItem == index,
onClick = { selectedItem = index }
)
}
}
}
@Composable
fun NavigationBarWithOnlySelectedLabelsSample() {
var selectedItem by remember { mutableStateOf(0) }
val items = listOf("Songs", "Artists", "Playlists")
NavigationBar {
items.forEachIndexed { index, item ->
NavigationBarItem(
icon = { Icon(Icons.Filled.Favorite, contentDescription = item) },
label = { Text(item) },
selected = selectedItem == index,
onClick = { selectedItem = index },
alwaysShowLabel = false
)
}
}
}
|
apache-2.0
|
e5907202fab65617f4994ab68231ab24
| 33.279412 | 82 | 0.690691 | 4.662 | false | false | false | false |
GunoH/intellij-community
|
platform/lang-impl/src/com/intellij/codeInsight/codeVision/ui/popup/CodeVisionPopup.kt
|
8
|
5624
|
package com.intellij.codeInsight.codeVision.ui.popup
import com.intellij.codeInsight.codeVision.CodeVisionEntry
import com.intellij.codeInsight.codeVision.ui.model.CodeVisionListData
import com.intellij.codeInsight.codeVision.ui.model.RangeCodeVisionModel
import com.intellij.codeInsight.codeVision.ui.popup.layouter.*
import com.intellij.codeInsight.codeVision.ui.renderers.CodeVisionRenderer
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.project.Project
import com.intellij.ui.popup.AbstractPopup
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.lifetime.LifetimeDefinition
import com.jetbrains.rd.util.reactive.IProperty
import com.jetbrains.rd.util.reactive.map
import java.awt.Rectangle
class CodeVisionPopup {
enum class Disposition constructor(val list: List<Anchoring2D>) {
MOUSE_POPUP_DISPOSITION(listOf(
Anchoring2D(Anchoring.FarOutside, Anchoring.NearOutside),
Anchoring2D(Anchoring.NearOutside, Anchoring.NearOutside),
Anchoring2D(Anchoring.FarOutside, Anchoring.FarOutside),
Anchoring2D(Anchoring.NearOutside, Anchoring.FarOutside)
)),
CURSOR_POPUP_DISPOSITION(listOf(
Anchoring2D(Anchoring.FarOutside, Anchoring.FarOutside),
Anchoring2D(Anchoring.NearOutside, Anchoring.FarOutside),
Anchoring2D(Anchoring.FarOutside, Anchoring.NearOutside),
Anchoring2D(Anchoring.NearOutside, Anchoring.NearOutside)
));
}
companion object {
private var ltd: LifetimeDefinition? = null
fun createNested(lifetime: Lifetime? = null): LifetimeDefinition {
ltd?.terminate()
val lt = lifetime?.createNested() ?: LifetimeDefinition()
ltd = lt
return lt
}
fun showContextPopup(
lifetime: Lifetime,
inlay: Inlay<*>,
entry: CodeVisionEntry,
disposition: Disposition,
model: CodeVisionListData,
project: Project
) {
showPopup(lifetime, inlay, entry, disposition, model.projectModel.lensPopupActive) {
CodeVisionContextPopup.createLensList(entry, model, project)
}
}
fun showMorePopup(
lifetime: Lifetime,
inlay: Inlay<*>,
entry: CodeVisionEntry,
disposition: Disposition,
model: RangeCodeVisionModel,
project: Project
) {
showPopup(lifetime, inlay, entry, disposition, model.lensPopupActive()) {
CodeVisionListPopup.createLensList(model, project)
}
}
fun showMorePopup(
lifetime: Lifetime,
project: Project,
editor: Editor,
offset: Int,
disposition: Disposition,
model: RangeCodeVisionModel
) {
val ltd = createNested(lifetime)
val anchor = EditorAnchoringRect.createHorizontalSmartClipRect(ltd, offset, editor)
showPopup(ltd, project, editor, model.lensPopupActive(), anchor, disposition.list) {
CodeVisionListPopup.createLensList(model, project)
}
}
private fun showPopup(
ltd: LifetimeDefinition,
project: Project,
editor: Editor,
lensPopupActive: IProperty<Boolean>,
anchor: AnchoringRect,
disposition: List<Anchoring2D>,
popupFactory: (Lifetime) -> AbstractPopup
) {
val popupLayouter = SimplePopupLayouterSource({ lt ->
DockingLayouter(
lt, anchor, disposition, project
)
}, this::class.java.simpleName).createLayouter(ltd)
val pw = CodeVisionPopupWrapper(ltd, editor, popupFactory, popupLayouter, lensPopupActive)
//pw.show()
anchor.rectangle.map { it != null }.view(ltd) { lt, it ->
if (it) {
pw.show()
}
else {
pw.hide(lt)
}
}
}
private fun showPopup(
lifetime: Lifetime,
inlay: Inlay<*>,
entry: CodeVisionEntry,
disposition: Disposition,
lensPopupActive: IProperty<Boolean>,
popupFactory: (Lifetime) -> AbstractPopup
) {
val editor = inlay.editor
val project = editor.project ?: return
val offset = inlay.offset
val ltd = createNested(lifetime)
val shift = getPopupShift(inlay, entry) ?: return
val anchor = EditorAnchoringRect(ltd, editor, offset, shiftDelegate(editor, shift))
showPopup(ltd, project, editor, lensPopupActive, anchor, disposition.list, popupFactory)
}
private fun getPopupShift(inlay: Inlay<*>, entry: CodeVisionEntry): LensPopupLayoutingData? {
val inlayXY = inlay.bounds ?: return null
val editor = inlay.editor
val renderer = inlay.renderer as CodeVisionRenderer
val entryBounds = renderer.entryBounds(inlay, entry) ?: return null
val offsetXY = editor.offsetToXY(inlay.offset)
val shiftX = inlayXY.x - offsetXY.x + entryBounds.x - entryBounds.width
val shiftY = offsetXY.y - inlayXY.y
return LensPopupLayoutingData(shiftX, shiftY, entryBounds.width, inlayXY.height)
}
private class LensPopupLayoutingData(
val horizontalShift: Int,
val verticalShift: Int,
val width: Int,
val height: Int
)
private fun shiftDelegate(editor: Editor, shift: LensPopupLayoutingData): (Rectangle) -> Rectangle? = {
val rect = it.map { Rectangle(it.x + shift.horizontalShift, it.y - shift.verticalShift, shift.width, shift.height) }
if (rect == null) null else EditorAnchoringRect.horizontalSmartClipDelegate(editor).invoke(rect)
}
}
}
|
apache-2.0
|
22c8d8ef4f440bfe518acaf4140c3871
| 32.885542 | 122 | 0.673898 | 4.376654 | false | false | false | false |
GunoH/intellij-community
|
platform/lang-api/src/com/intellij/ide/bookmark/BookmarkType.kt
|
2
|
4011
|
// 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.ide.bookmark
import com.intellij.icons.AllIcons
import com.intellij.ide.ui.UISettings
import com.intellij.lang.LangBundle
import com.intellij.openapi.editor.colors.EditorColorsUtil
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.ui.IconReplacer
import com.intellij.ui.IconWrapperWithToolTip
import com.intellij.ui.JBColor
import com.intellij.util.ui.RegionPaintIcon
import com.intellij.util.ui.RegionPainter
import java.awt.Component
import java.awt.Graphics2D
import javax.swing.Icon
enum class BookmarkType(val mnemonic: Char) {
DIGIT_1('1'), DIGIT_2('2'), DIGIT_3('3'), DIGIT_4('4'), DIGIT_5('5'),
DIGIT_6('6'), DIGIT_7('7'), DIGIT_8('8'), DIGIT_9('9'), DIGIT_0('0'),
LETTER_A('A'), LETTER_B('B'), LETTER_C('C'), LETTER_D('D'),
LETTER_E('E'), LETTER_F('F'), LETTER_G('G'), LETTER_H('H'),
LETTER_I('I'), LETTER_J('J'), LETTER_K('K'), LETTER_L('L'),
LETTER_M('M'), LETTER_N('N'), LETTER_O('O'), LETTER_P('P'),
LETTER_Q('Q'), LETTER_R('R'), LETTER_S('S'), LETTER_T('T'),
LETTER_U('U'), LETTER_V('V'), LETTER_W('W'),
LETTER_X('X'), LETTER_Y('Y'), LETTER_Z('Z'),
DEFAULT(0.toChar());
val icon by lazy { createIcon(IconSize.REGULAR) }
val gutterIcon by lazy { createIcon(IconSize.GUTTER) }
private fun createIcon(size: IconSize): Icon = BookmarkIcon(mnemonic, size)
companion object {
@JvmStatic
fun get(mnemonic: Char) = values().firstOrNull { it.mnemonic == mnemonic } ?: DEFAULT
}
}
internal enum class IconSize {
GUTTER,
REGULAR,
}
private val MNEMONIC_ICON_FOREGROUND = EditorColorsUtil.createColorKey("Bookmark.Mnemonic.iconForeground", JBColor(0x000000, 0xBBBBBB))
private class MnemonicPainter(val icon: Icon, val mnemonic: String) : RegionPainter<Component?> {
override fun toString() = "BookmarkMnemonicIcon:$mnemonic"
override fun hashCode() = mnemonic.hashCode()
override fun equals(other: Any?): Boolean {
if (other === this) return true
val painter = other as? MnemonicPainter ?: return false
return painter.mnemonic == mnemonic
}
override fun paint(g: Graphics2D, x: Int, y: Int, width: Int, height: Int, c: Component?) {
icon.paintIcon(null, g, x, y)
val foreground = EditorColorsUtil.getColor(null, MNEMONIC_ICON_FOREGROUND)
g.paint = foreground
UISettings.setupAntialiasing(g)
val frc = g.fontRenderContext
val font = EditorFontType.PLAIN.globalFont
val size1 = .75f * height
val vector1 = font.deriveFont(size1).createGlyphVector(frc, mnemonic)
val bounds1 = vector1.visualBounds
val dx = x - bounds1.x + .5 * (width - bounds1.width)
val dy = y - bounds1.y + .5 * (height - bounds1.height)
g.drawGlyphVector(vector1, dx.toFloat(), dy.toFloat())
}
}
class BookmarkIcon : IconWrapperWithToolTip {
val mnemonic: Char
internal constructor(mnemonic: Char, size: IconSize) : this(mnemonic, createBookmarkIcon(mnemonic, size))
private constructor(mnemonic: Char, icon: Icon) : super(icon, LangBundle.messagePointer("tooltip.bookmarked")) {
this.mnemonic = mnemonic
}
override fun replaceBy(replacer: IconReplacer): BookmarkIcon {
return BookmarkIcon(mnemonic, replacer.replaceIcon(retrieveIcon()))
}
companion object {
@JvmStatic
private fun createBookmarkIcon(mnemonic: Char, size: IconSize): Icon {
if (mnemonic == 0.toChar()) {
return when (size) {
IconSize.GUTTER -> AllIcons.Gutter.Bookmark
else -> AllIcons.Nodes.Bookmark
}
}
val icon = when (size) {
IconSize.GUTTER -> AllIcons.Gutter.Mnemonic
else -> AllIcons.Nodes.Mnemonic
}
val painter = MnemonicPainter(icon, mnemonic.toString())
val paintSize = when (size) {
IconSize.GUTTER -> 12
else -> 16
}
return RegionPaintIcon(paintSize, paintSize, 0, painter).withIconPreScaled(false)
}
}
}
|
apache-2.0
|
8de192f65dcfbc7ce5a032ec44a6684c
| 34.8125 | 135 | 0.688856 | 3.52151 | false | false | false | false |
GunoH/intellij-community
|
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/parser/GFMCommentAwareMarkerProcessor.kt
|
7
|
3713
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.lang.parser
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.flavours.commonmark.CommonMarkMarkerProcessor
import org.intellij.markdown.flavours.gfm.GFMConstraints
import org.intellij.markdown.flavours.gfm.GFMTokenTypes
import org.intellij.markdown.flavours.gfm.table.GitHubTableMarkerProvider
import org.intellij.markdown.parser.LookaheadText
import org.intellij.markdown.parser.MarkerProcessor
import org.intellij.markdown.parser.MarkerProcessorFactory
import org.intellij.markdown.parser.ProductionHolder
import org.intellij.markdown.parser.constraints.MarkdownConstraints
import org.intellij.markdown.parser.constraints.getCharsEaten
import org.intellij.markdown.parser.markerblocks.MarkerBlockProvider
import org.intellij.markdown.parser.markerblocks.providers.AtxHeaderProvider
import org.intellij.markdown.parser.markerblocks.providers.HorizontalRuleProvider
import org.intellij.markdown.parser.markerblocks.providers.LinkReferenceDefinitionProvider
import org.intellij.markdown.parser.sequentialparsers.SequentialParser
import org.intellij.plugins.markdown.lang.parser.frontmatter.FrontMatterHeaderMarkerProvider
import kotlin.math.min
class GFMCommentAwareMarkerProcessor(
productionHolder: ProductionHolder,
constraintsBase: MarkdownConstraints
): CommonMarkMarkerProcessor(productionHolder, constraintsBase) {
override fun populateConstraintsTokens(
pos: LookaheadText.Position,
constraints: MarkdownConstraints,
productionHolder: ProductionHolder
) {
if (constraints !is GFMConstraints || !constraints.hasCheckbox()) {
super.populateConstraintsTokens(pos, constraints, productionHolder)
return
}
val line = pos.currentLine
var offset = pos.offsetInCurrentLine
while (offset < line.length && line[offset] != '[') {
offset++
}
if (offset == line.length) {
super.populateConstraintsTokens(pos, constraints, productionHolder)
return
}
check(constraints.types.isNotEmpty())
val type = when (constraints.types.last()) {
'>' -> MarkdownTokenTypes.BLOCK_QUOTE
'.', ')' -> MarkdownTokenTypes.LIST_NUMBER
else -> MarkdownTokenTypes.LIST_BULLET
}
val middleOffset = pos.offset - pos.offsetInCurrentLine + offset
val endOffset = min(pos.offset - pos.offsetInCurrentLine + constraints.getCharsEaten(pos.currentLine), pos.nextLineOrEofOffset)
productionHolder.addProduction(listOf(
SequentialParser.Node(pos.offset..middleOffset, type),
SequentialParser.Node(middleOffset..endOffset, GFMTokenTypes.CHECK_BOX)
))
}
override fun getMarkerBlockProviders(): List<MarkerBlockProvider<StateInfo>> {
val base = super.getMarkerBlockProviders().asSequence()
.filterNot { it is AtxHeaderProvider }
.filterNot { it is LinkReferenceDefinitionProvider }
.filterNot { it is HorizontalRuleProvider }
.toMutableList()
if (FrontMatterHeaderMarkerProvider.isFrontMatterSupportEnabled()) {
base.add(FrontMatterHeaderMarkerProvider())
}
val modified = listOf(
DefinitionListMarkerProvider(),
HorizontalRuleProvider(),
GitHubTableMarkerProvider(),
AtxHeaderProvider(),
CommentAwareLinkReferenceDefinitionProvider()
)
base.addAll(modified)
return base
}
object Factory: MarkerProcessorFactory {
override fun createMarkerProcessor(productionHolder: ProductionHolder): MarkerProcessor<*> {
return GFMCommentAwareMarkerProcessor(productionHolder, GFMConstraints.BASE)
}
}
}
|
apache-2.0
|
f557e6a9f7593164623ac0c55bc408bb
| 41.678161 | 140 | 0.781578 | 4.970549 | false | false | false | false |
JetBrains/xodus
|
environment/src/main/kotlin/jetbrains/exodus/io/LockingManager.kt
|
1
|
4922
|
/**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.io
import jetbrains.exodus.ExodusException
import jetbrains.exodus.OutOfDiskSpaceException
import jetbrains.exodus.system.JVMConstants
import java.io.File
import java.io.IOException
import java.io.RandomAccessFile
import java.lang.management.ManagementFactory
import java.nio.channels.FileLock
import java.nio.channels.OverlappingFileLockException
import java.util.*
internal class LockingManager internal constructor(private val dir: File, private val lockId: String?) {
private var lockFile: RandomAccessFile? = null
private var lock: FileLock? = null
val usableSpace: Long get() = dir.usableSpace
fun lock(timeout: Long): Boolean {
val started = System.currentTimeMillis()
do {
if (lock()) return true
if (timeout > 0) {
try {
Thread.sleep(100)
} catch (e: InterruptedException) {
Thread.currentThread().interrupt()
break
}
}
} while (System.currentTimeMillis() - started < timeout)
return false
}
fun release(): Boolean {
if (lockFile != null) {
try {
close()
return true
} catch (e: IOException) {
throw ExodusException("Failed to release lock file $LOCK_FILE_NAME", e)
}
}
return false
}
private fun lock(): Boolean {
if (lockFile != null) return false // already locked!
try {
val lockFileHandle = getLockFile()
val lockFile = RandomAccessFile(lockFileHandle, "rw")
this.lockFile = lockFile
val channel = lockFile.channel
lock = channel.tryLock()
if (lock != null) {
lockFile.setLength(0)
lockFile.writeBytes("Private property of Exodus: ")
if (lockId == null) {
if (!JVMConstants.IS_ANDROID) {
val bean = ManagementFactory.getRuntimeMXBean()
if (bean != null) {
// Got runtime system bean (try to get PID)
// Result of bean.getName() is unknown
lockFile.writeBytes(bean.name)
}
}
} else {
lockFile.writeBytes("$lockId")
}
lockFile.writeBytes("\n\n")
for (element in Throwable().stackTrace) {
lockFile.writeBytes(element.toString() + '\n')
}
channel.force(false)
}
} catch (e: IOException) {
try {
close()
} catch (_: IOException) {
//throw only first cause
}
return throwFailedToLock(e)
} catch (_: OverlappingFileLockException) {
try {
close()
} catch (_: IOException) {
//throw only first cause
}
}
if (lock == null) {
try {
close()
} catch (e: IOException) {
throwFailedToLock(e)
}
}
return lockFile != null
}
fun lockInfo(): String? {
try {
// "stupid scanner trick" for reading entire file in a string (https://community.oracle.com/blogs/pat/2004/10/23/stupid-scanner-tricks)
return with(Scanner(getLockFile()).useDelimiter("\\A")) {
if (hasNext()) next() else null
}
} catch (e: IOException) {
throw ExodusException("Failed to read contents of lock file $LOCK_FILE_NAME", e)
}
}
private fun getLockFile(): File {
return File(dir, LOCK_FILE_NAME)
}
private fun throwFailedToLock(e: IOException): Boolean {
if (usableSpace < 4096) {
throw OutOfDiskSpaceException(e)
}
throw ExodusException("Failed to lock file $LOCK_FILE_NAME", e)
}
private fun close() {
lock?.release()
lockFile?.apply {
close()
lockFile = null
}
}
companion object {
const val LOCK_FILE_NAME = "xd.lck"
}
}
|
apache-2.0
|
76c9428bd2ec19a64d83a5deb814f959
| 31.82 | 147 | 0.542666 | 4.834971 | false | false | false | false |
jwren/intellij-community
|
plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/MavenJavaNewProjectWizard.kt
|
4
|
3450
|
// 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.idea.maven.wizards
import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logAddSampleCodeChanged
import com.intellij.ide.projectWizard.NewProjectWizardConstants.BuildSystem.MAVEN
import com.intellij.ide.projectWizard.generators.BuildSystemJavaNewProjectWizard
import com.intellij.ide.projectWizard.generators.BuildSystemJavaNewProjectWizardData
import com.intellij.ide.projectWizard.generators.AssetsNewProjectWizardStep
import com.intellij.ide.projectWizard.generators.JavaNewProjectWizard
import com.intellij.ide.starters.local.StandardAssetsProvider
import com.intellij.ide.wizard.GitNewProjectWizardData.Companion.gitData
import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.name
import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.path
import com.intellij.ide.wizard.chain
import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManagerImpl
import com.intellij.openapi.observable.util.bindBooleanStorage
import com.intellij.openapi.project.Project
import com.intellij.ui.UIBundle
import com.intellij.ui.dsl.builder.Panel
import com.intellij.ui.dsl.builder.TopGap
import com.intellij.ui.dsl.builder.bindSelected
import com.intellij.ui.dsl.builder.whenStateChangedFromUi
import org.jetbrains.idea.maven.model.MavenId
class MavenJavaNewProjectWizard : BuildSystemJavaNewProjectWizard {
override val name = MAVEN
override val ordinal = 100
override fun createStep(parent: JavaNewProjectWizard.Step) = Step(parent).chain(::AssetsStep)
class Step(parent: JavaNewProjectWizard.Step) :
MavenNewProjectWizardStep<JavaNewProjectWizard.Step>(parent),
BuildSystemJavaNewProjectWizardData by parent {
private val addSampleCodeProperty = propertyGraph.property(false)
.bindBooleanStorage("NewProjectWizard.addSampleCodeState")
var addSampleCode by addSampleCodeProperty
override fun setupSettingsUI(builder: Panel) {
super.setupSettingsUI(builder)
builder.row {
checkBox(UIBundle.message("label.project.wizard.new.project.add.sample.code"))
.bindSelected(addSampleCodeProperty)
.whenStateChangedFromUi { logAddSampleCodeChanged(it) }
}.topGap(TopGap.SMALL)
}
override fun setupProject(project: Project) {
super.setupProject(project)
val builder = InternalMavenModuleBuilder().apply {
moduleJdk = sdk
name = parentStep.name
contentEntryPath = "${parentStep.path}/${parentStep.name}"
parentProject = parentData
aggregatorProject = parentData
projectId = MavenId(groupId, artifactId, version)
isInheritGroupId = parentData?.mavenId?.groupId == groupId
isInheritVersion = parentData?.mavenId?.version == version
}
ExternalProjectsManagerImpl.setupCreatedProject(project)
builder.commit(project)
}
}
private class AssetsStep(private val parent: Step) : AssetsNewProjectWizardStep(parent) {
override fun setupAssets(project: Project) {
outputDirectory = "$path/$name"
if (gitData?.git == true) {
addAssets(StandardAssetsProvider().getMavenIgnoreAssets())
}
if (parent.addSampleCode) {
withJavaSampleCodeAsset("src/main/java", parent.groupId)
}
}
}
}
|
apache-2.0
|
189fd81d272add6d0969fa58a9374629
| 41.085366 | 158 | 0.78 | 4.791667 | false | false | false | false |
stefanmedack/cccTV
|
app/src/main/java/de/stefanmedack/ccctv/ui/detail/DetailFragment.kt
|
1
|
13543
|
package de.stefanmedack.ccctv.ui.detail
import android.arch.lifecycle.ViewModelProvider
import android.arch.lifecycle.ViewModelProviders
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.support.v17.leanback.app.DetailsSupportFragment
import android.support.v17.leanback.app.DetailsSupportFragmentBackgroundController
import android.support.v17.leanback.widget.Action
import android.support.v17.leanback.widget.ArrayObjectAdapter
import android.support.v17.leanback.widget.ClassPresenterSelector
import android.support.v17.leanback.widget.DetailsOverviewRow
import android.support.v17.leanback.widget.FullWidthDetailsOverviewRowPresenter
import android.support.v17.leanback.widget.FullWidthDetailsOverviewSharedElementHelper
import android.support.v17.leanback.widget.HeaderItem
import android.support.v17.leanback.widget.ImageCardView
import android.support.v17.leanback.widget.ListRow
import android.support.v17.leanback.widget.ListRowPresenter
import android.support.v17.leanback.widget.OnItemViewClickedListener
import android.support.v4.content.ContextCompat
import android.view.KeyEvent
import android.view.View
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.core.widget.toast
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import dagger.android.support.AndroidSupportInjection
import de.stefanmedack.ccctv.R
import de.stefanmedack.ccctv.persistence.entities.Event
import de.stefanmedack.ccctv.ui.cards.EventCardPresenter
import de.stefanmedack.ccctv.ui.cards.SpeakerCardPresenter
import de.stefanmedack.ccctv.ui.detail.playback.ExoPlayerAdapter
import de.stefanmedack.ccctv.ui.detail.playback.VideoMediaPlayerGlue
import de.stefanmedack.ccctv.ui.detail.uiModels.DetailUiModel
import de.stefanmedack.ccctv.ui.detail.uiModels.SpeakerUiModel
import de.stefanmedack.ccctv.ui.events.EventsActivity
import de.stefanmedack.ccctv.util.DETAIL_ACTION_BOOKMARK
import de.stefanmedack.ccctv.util.DETAIL_ACTION_PLAY
import de.stefanmedack.ccctv.util.DETAIL_ACTION_RELATED
import de.stefanmedack.ccctv.util.DETAIL_ACTION_RESTART
import de.stefanmedack.ccctv.util.DETAIL_ACTION_SPEAKER
import de.stefanmedack.ccctv.util.EMPTY_STRING
import de.stefanmedack.ccctv.util.EVENT_ID
import de.stefanmedack.ccctv.util.EVENT_PICTURE
import de.stefanmedack.ccctv.util.SHARED_DETAIL_TRANSITION
import de.stefanmedack.ccctv.util.indexOf
import de.stefanmedack.ccctv.util.plusAssign
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.subscribeBy
import timber.log.Timber
import javax.inject.Inject
class DetailFragment : DetailsSupportFragment() {
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private val viewModel: DetailViewModel by lazy {
ViewModelProviders.of(this, viewModelFactory).get(DetailViewModel::class.java).apply {
init(arguments?.getString(EVENT_ID) ?: EMPTY_STRING)
}
}
private val disposables = CompositeDisposable()
private lateinit var detailsBackground: DetailsSupportFragmentBackgroundController
private lateinit var detailsOverview: DetailsOverviewRow
private var playerAdapter: ExoPlayerAdapter? = null
private val bookmarkAction by lazy {
Action(
DETAIL_ACTION_BOOKMARK,
getString(R.string.action_add_bookmark),
getString(R.string.action_bookmark_second_line))
}
override fun onCreate(savedInstanceState: Bundle?) {
AndroidSupportInjection.inject(this)
super.onCreate(savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupUi(view.context)
setupEventListeners()
bindViewModel()
}
override fun onPause() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N || activity?.isInPictureInPictureMode == false) {
val currentMillis = playerAdapter?.currentPosition
val durationMillis = playerAdapter?.duration
if (currentMillis != null && durationMillis != null) {
viewModel.inputs.savePlaybackPosition(
playedSeconds = (currentMillis / 1000).toInt(),
totalDurationSeconds = (durationMillis / 1000).toInt()
)
}
detailsBackground.playbackGlue?.pause()
}
super.onPause()
}
override fun onDestroy() {
disposables.clear()
super.onDestroy()
}
private fun setupUi(context: Context) {
detailsBackground = DetailsSupportFragmentBackgroundController(this)
detailsBackground.enableParallax()
// detail overview row - presents the detail, description and actions
val detailOverviewRowPresenter = FullWidthDetailsOverviewRowPresenter(DetailDescriptionPresenter())
detailOverviewRowPresenter.actionsBackgroundColor = ContextCompat.getColor(context, R.color.amber_800)
// init Shared Element Transition
detailOverviewRowPresenter.setListener(FullWidthDetailsOverviewSharedElementHelper().apply {
setSharedElementEnterTransition(activity, SHARED_DETAIL_TRANSITION)
})
detailOverviewRowPresenter.isParticipatingEntranceTransition = true
// Setup action and detail row.
detailsOverview = DetailsOverviewRow(Any())
showPoster(context, detailsOverview)
detailsOverview.actionsAdapter = ArrayObjectAdapter()
adapter = ArrayObjectAdapter(
// Setup PresenterSelector to distinguish between the different rows.
ClassPresenterSelector().apply {
addClassPresenter(DetailsOverviewRow::class.java, detailOverviewRowPresenter)
// Setup ListRow Presenter without shadows, to hide highlighting boxes for SpeakerCards
addClassPresenter(ListRow::class.java, ListRowPresenter().apply {
shadowEnabled = false
})
}
).apply {
add(detailsOverview)
}
}
private fun showPoster(context: Context, detailsOverview: DetailsOverviewRow) {
detailsOverview.imageDrawable = ContextCompat.getDrawable(context, R.drawable.voctocat)
Glide.with(this)
.load(arguments?.getString(EVENT_PICTURE))
.apply(RequestOptions()
.error(R.drawable.voctocat)
.centerCrop()
)
.into(object : SimpleTarget<Drawable>() {
override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
detailsOverview.imageDrawable = resource
}
})
}
private fun setupEventListeners() {
onItemViewClickedListener = OnItemViewClickedListener { itemViewHolder, item, _, _ ->
when (item) {
is Action -> when (item.id) {
DETAIL_ACTION_PLAY -> try {
detailsBackground.switchToVideo()
} catch (e: Exception) {
Timber.w(e, "Could not switch to video on detailsBackground - probably not initialized yet")
}
DETAIL_ACTION_RESTART -> {
playerAdapter?.simpleSeekTo(0)
(detailsOverview.actionsAdapter as ArrayObjectAdapter).removeItems(1, 1)
}
DETAIL_ACTION_BOOKMARK -> viewModel.inputs.toggleBookmark()
DETAIL_ACTION_SPEAKER -> setSelectedPosition(1)
DETAIL_ACTION_RELATED -> setSelectedPosition(2)
else -> Toast.makeText(activity, R.string.implement_me_toast, Toast.LENGTH_LONG).show()
}
is SpeakerUiModel -> activity?.let { EventsActivity.startWithSearch(it, item.name) }
is Event -> activity?.let { DetailActivity.start(it, item, (itemViewHolder.view as ImageCardView).mainImageView) }
}
}
}
private fun bindViewModel() {
disposables.addAll(
viewModel.outputs.detailData.subscribeBy(
onSuccess = ::render,
// TODO proper error handling
onError = { it.printStackTrace() }),
viewModel.outputs.isBookmarked.subscribeBy(
onNext = ::updateBookmarkState,
// TODO proper error handling
onError = { it.printStackTrace() })
)
}
private fun render(result: DetailUiModel) {
detailsOverview.item = result.event
activity?.let { activityContext ->
playerAdapter = ExoPlayerAdapter(activityContext).also { newAdapter ->
newAdapter.bindRecordings(viewModel.outputs.videoPlaybackData)
val mediaPlayerGlue = VideoMediaPlayerGlue(activityContext, newAdapter)
mediaPlayerGlue.isSeekEnabled = true
mediaPlayerGlue.title = result.event.title
mediaPlayerGlue.subtitle = result.event.subtitle
detailsBackground.setupVideoPlayback(mediaPlayerGlue)
}
}
val detailsOverviewAdapter = detailsOverview.actionsAdapter as ArrayObjectAdapter
(adapter as ArrayObjectAdapter).apply {
// add play-button to DetailOverviewRow on the very top
detailsOverviewAdapter.add(Action(
DETAIL_ACTION_PLAY,
getString(R.string.action_watch),
EMPTY_STRING,
context?.getDrawable(R.drawable.ic_watch)
))
// add restart-video-from-beginning Button
if (result.wasPlayed) {
detailsOverviewAdapter.add(Action(
DETAIL_ACTION_RESTART,
getString(R.string.action_restart),
EMPTY_STRING,
context?.getDrawable(R.drawable.ic_restart)
))
context?.toast(R.string.playback_resumed_toast)
}
// add bookmark-button to DetailOverviewRow on the very top
detailsOverviewAdapter.add(bookmarkAction)
// add speaker
if (!result.speaker.isEmpty()) {
val listRowAdapter = ArrayObjectAdapter(SpeakerCardPresenter())
listRowAdapter += result.speaker
add(ListRow(HeaderItem(0, getString(R.string.header_speaker)), listRowAdapter))
// add go-to-speaker-section-button to DetailOverviewRow on the very top
detailsOverviewAdapter.add(Action(
DETAIL_ACTION_SPEAKER,
getString(R.string.action_show_speaker),
EMPTY_STRING,
context?.getDrawable(R.drawable.ic_speaker)
))
}
// add related
if (!result.related.isEmpty()) {
val listRowAdapter = ArrayObjectAdapter(EventCardPresenter())
listRowAdapter += result.related
add(ListRow(HeaderItem(1, getString(R.string.header_related)), listRowAdapter))
// add go-to-related-section-button to DetailOverviewRow on the very top
detailsOverviewAdapter.add(Action(
DETAIL_ACTION_RELATED,
getString(R.string.action_show_related),
EMPTY_STRING,
context?.getDrawable(R.drawable.ic_related)
))
}
}
}
private fun updateBookmarkState(isBookmarked: Boolean) {
bookmarkAction.apply {
if (isBookmarked) {
label1 = getString(R.string.action_remove_bookmark)
icon = context?.getDrawable(R.drawable.ic_bookmark_check)
} else {
label1 = getString(R.string.action_add_bookmark)
icon = context?.getDrawable(R.drawable.ic_bookmark_plus)
}
}
detailsOverview.actionsAdapter.indexOf(bookmarkAction)?.let { indexOfBookmark ->
detailsOverview.actionsAdapter.notifyItemRangeChanged(indexOfBookmark, 1)
}
}
fun onKeyDown(keyCode: Int): Boolean =
(keyCode == KeyEvent.KEYCODE_DPAD_DOWN && shouldShowDetailsOnKeyDownEvent())
.also {
if (it) detailsBackground.switchToRows()
}
// Note: this is a workaround to find the current focus on the video playback screen
// -> we use this information to switch back to information on KEYCODE_DPAD_DOWN press
private fun shouldShowDetailsOnKeyDownEvent(): Boolean {
val playbackFragmentView = detailsBackground.findOrCreateVideoSupportFragment().view
val progressBarView = playbackFragmentView?.findViewById<View>(R.id.playback_progress)
return (playbackFragmentView?.hasFocus() == true && progressBarView?.hasFocus() == true)
}
companion object {
fun getBundle(eventId: String, eventThumbUrl: String?) = bundleOf(EVENT_ID to eventId, EVENT_PICTURE to eventThumbUrl)
}
}
|
apache-2.0
|
98435bf9446d6a1d6a8afc011b85ed15
| 42.828479 | 130 | 0.654877 | 5.245159 | false | false | false | false |
GunoH/intellij-community
|
platform/vcs-log/impl/src/com/intellij/vcs/log/data/AbstractDataGetter.kt
|
5
|
7030
|
// 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.vcs.log.data
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.*
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Consumer
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.vcs.log.*
import it.unimi.dsi.fastutil.ints.Int2ObjectMap
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap
import it.unimi.dsi.fastutil.ints.IntOpenHashSet
import it.unimi.dsi.fastutil.ints.IntSet
abstract class AbstractDataGetter<T : VcsShortCommitDetails> internal constructor(protected val storage: VcsLogStorage,
protected val logProviders: Map<VirtualFile, VcsLogProvider>,
parentDisposable: Disposable) :
Disposable, DataGetter<T> {
protected val disposableFlag = Disposer.newCheckedDisposable()
init {
Disposer.register(parentDisposable, this)
Disposer.register(this, disposableFlag)
}
override fun loadCommitsData(commits: List<Int>,
consumer: Consumer<in List<T>>,
errorConsumer: Consumer<in Throwable>,
indicator: ProgressIndicator?) {
val detailsFromCache = getCommitDataIfAvailable(commits)
if (detailsFromCache.size == commits.size) {
// client of this code expect start/stop methods to get called for the provided indicator
runInCurrentThread(indicator) {
consumer.consume(commits.mapNotNull { detailsFromCache[it] })
}
return
}
val toLoad = IntOpenHashSet(commits).apply { removeAll(detailsFromCache.keys) }
cacheCommits(toLoad)
val task = object : Task.Backgroundable(null,
VcsLogBundle.message("vcs.log.loading.selected.details.process"),
true, ALWAYS_BACKGROUND) {
override fun run(indicator: ProgressIndicator) {
indicator.checkCanceled()
try {
val detailsFromProvider = Int2ObjectOpenHashMap<T>()
doLoadCommitsData(toLoad) { metadata ->
val commitIndex = storage.getCommitIndex(metadata.id, metadata.root)
saveInCache(commitIndex, metadata)
detailsFromProvider[commitIndex] = metadata
}
val result = commits.mapNotNull { detailsFromCache[it] ?: detailsFromProvider[it] }
runInEdt(disposableFlag) {
notifyLoaded()
consumer.consume(result)
}
}
catch (_: ProcessCanceledException) {
}
catch (t: Throwable) {
if (t !is VcsException) LOG.error(t)
runInEdt(disposableFlag) { errorConsumer.consume(t) }
}
}
}
runInBackgroundThread(indicator, task)
}
@RequiresBackgroundThread
@Throws(VcsException::class)
fun loadCommitsDataSynchronously(commits: Iterable<Int>,
indicator: ProgressIndicator,
consumer: Consumer<in T>) {
val toLoad = IntOpenHashSet()
for (id in commits) {
val details = getCommitDataIfAvailable(id)
if (details == null || details is LoadingDetails) {
toLoad.add(id)
}
else {
consumer.consume(details)
}
}
if (!toLoad.isEmpty()) {
indicator.checkCanceled()
doLoadCommitsData(toLoad) { details ->
saveInCache(details)
consumer.consume(details)
}
notifyLoaded()
}
}
@RequiresBackgroundThread
@Throws(VcsException::class)
protected open fun doLoadCommitsData(commits: IntSet, consumer: Consumer<in T>) {
val hashesGroupedByRoot = commits.mapNotNull { storage.getCommitId(it) }
.groupBy<CommitId, VirtualFile, @NlsSafe String>({ it.root }) { it.hash.asString() }
for ((root, hashes) in hashesGroupedByRoot) {
val logProvider = logProviders[root]
if (logProvider == null) {
LOG.error("No log provider for root " + root.path + ". All known log providers " + logProviders)
continue
}
doLoadCommitsDataFromProvider(logProvider, root, hashes, consumer)
}
}
protected abstract fun getCommitDataIfAvailable(commits: List<Int>): Int2ObjectMap<T>
protected abstract fun saveInCache(commit: Int, details: T)
protected fun saveInCache(details: T) = saveInCache(storage.getCommitIndex(details.id, details.root), details)
protected open fun cacheCommits(commits: IntOpenHashSet) = Unit
@RequiresBackgroundThread
@Throws(VcsException::class)
protected abstract fun doLoadCommitsDataFromProvider(logProvider: VcsLogProvider,
root: VirtualFile,
hashes: List<String>,
consumer: Consumer<in T>)
protected open fun notifyLoaded() = Unit
companion object {
private val LOG = Logger.getInstance(AbstractDataGetter::class.java)
private fun runInCurrentThread(indicator: ProgressIndicator?, runnable: () -> Unit) {
if (indicator != null) {
ProgressManager.getInstance().runProcess(runnable, indicator)
}
else {
runnable.invoke()
}
}
private fun runInBackgroundThread(indicator: ProgressIndicator?, task: Task.Backgroundable) {
if (indicator != null) {
ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, indicator)
}
else {
ProgressManager.getInstance().run(task)
}
}
@RequiresBackgroundThread
@Throws(VcsException::class)
@JvmStatic
fun <T : VcsShortCommitDetails> AbstractDataGetter<T>.getCommitDetails(commits: List<Int>): List<T> {
val commitToDetailsMap = Int2ObjectOpenHashMap<T>()
loadCommitsDataSynchronously(commits, ProgressManager.getGlobalProgressIndicator() ?: EmptyProgressIndicator()) { details ->
commitToDetailsMap[storage.getCommitIndex(details.id, details.root)] = details
}
return commits.mapNotNull { commitToDetailsMap[it] }
}
@RequiresBackgroundThread
@Throws(VcsException::class)
@JvmStatic
fun <T : VcsShortCommitDetails> AbstractDataGetter<T>.getCommitDetails(hash: Hash, root: VirtualFile): T {
val commitDetailsList = getCommitDetails(listOf(storage.getCommitIndex(hash, root)))
return commitDetailsList.singleOrNull() ?: throw VcsException(VcsLogBundle.message("vcs.log.failed.loading.details",
hash.asString(), root.name))
}
}
}
|
apache-2.0
|
8d06877739fa1e0eaf4cc728b3c110ab
| 39.641618 | 143 | 0.645804 | 5.064841 | false | false | false | false |
GunoH/intellij-community
|
platform/lang-impl/src/com/intellij/ide/bookmark/actions/ToggleBookmarkTypeAction.kt
|
5
|
4331
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.bookmark.actions
import com.intellij.ide.bookmark.BookmarkBundle.messagePointer
import com.intellij.ide.bookmark.BookmarkType
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
internal open class ToggleBookmarkTypeAction(private val type: BookmarkType)
: DumbAwareAction(messagePointer("bookmark.type.toggle.action.text", type.mnemonic)/*, type.icon*/) {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun update(event: AnActionEvent) {
val manager = event.bookmarksManager
val bookmark = event.contextBookmark
event.presentation.isEnabledAndVisible = manager != null && bookmark != null
}
override fun actionPerformed(event: AnActionEvent) {
val manager = event.bookmarksManager ?: return
val bookmark = event.contextBookmark ?: return
manager.toggle(bookmark, type)
}
init {
isEnabledInModalContext = true
}
}
internal class ToggleBookmark1Action : ToggleBookmarkTypeAction(BookmarkType.DIGIT_1)
internal class ToggleBookmark2Action : ToggleBookmarkTypeAction(BookmarkType.DIGIT_2)
internal class ToggleBookmark3Action : ToggleBookmarkTypeAction(BookmarkType.DIGIT_3)
internal class ToggleBookmark4Action : ToggleBookmarkTypeAction(BookmarkType.DIGIT_4)
internal class ToggleBookmark5Action : ToggleBookmarkTypeAction(BookmarkType.DIGIT_5)
internal class ToggleBookmark6Action : ToggleBookmarkTypeAction(BookmarkType.DIGIT_6)
internal class ToggleBookmark7Action : ToggleBookmarkTypeAction(BookmarkType.DIGIT_7)
internal class ToggleBookmark8Action : ToggleBookmarkTypeAction(BookmarkType.DIGIT_8)
internal class ToggleBookmark9Action : ToggleBookmarkTypeAction(BookmarkType.DIGIT_9)
internal class ToggleBookmark0Action : ToggleBookmarkTypeAction(BookmarkType.DIGIT_0)
internal class ToggleBookmarkAAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_A)
internal class ToggleBookmarkBAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_B)
internal class ToggleBookmarkCAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_C)
internal class ToggleBookmarkDAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_D)
internal class ToggleBookmarkEAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_E)
internal class ToggleBookmarkFAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_F)
internal class ToggleBookmarkGAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_G)
internal class ToggleBookmarkHAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_H)
internal class ToggleBookmarkIAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_I)
internal class ToggleBookmarkJAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_J)
internal class ToggleBookmarkKAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_K)
internal class ToggleBookmarkLAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_L)
internal class ToggleBookmarkMAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_M)
internal class ToggleBookmarkNAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_N)
internal class ToggleBookmarkOAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_O)
internal class ToggleBookmarkPAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_P)
internal class ToggleBookmarkQAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_Q)
internal class ToggleBookmarkRAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_R)
internal class ToggleBookmarkSAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_S)
internal class ToggleBookmarkTAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_T)
internal class ToggleBookmarkUAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_U)
internal class ToggleBookmarkVAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_V)
internal class ToggleBookmarkWAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_W)
internal class ToggleBookmarkXAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_X)
internal class ToggleBookmarkYAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_Y)
internal class ToggleBookmarkZAction : ToggleBookmarkTypeAction(BookmarkType.LETTER_Z)
|
apache-2.0
|
572b9f83958a3b66ff17589c3c3e2637
| 62.691176 | 158 | 0.856846 | 5.01854 | false | false | false | false |
TachiWeb/TachiWeb-Server
|
Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/network/NetworkHelper.kt
|
1
|
4862
|
package eu.kanade.tachiyomi.network
import android.content.Context
import android.os.Build
import okhttp3.*
import java.io.File
import java.io.IOException
import java.net.InetAddress
import java.net.Socket
import java.net.UnknownHostException
import java.security.KeyManagementException
import java.security.KeyStore
import java.security.NoSuchAlgorithmException
import javax.net.ssl.*
class NetworkHelper(context: Context) {
private val cacheDir = File(context.cacheDir, "network_cache")
private val cacheSize = 5L * 1024 * 1024 // 5 MiB
private val cookieManager = PersistentCookieJar(context)
val client = OkHttpClient.Builder()
.cookieJar(cookieManager)
.cache(Cache(cacheDir, cacheSize))
.enableTLS12()
.build()
val cloudflareClient = client.newBuilder()
.addInterceptor(CloudflareInterceptor())
.build()
val cookies: PersistentCookieStore
get() = cookieManager.store
private fun OkHttpClient.Builder.enableTLS12(): OkHttpClient.Builder {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
return this
}
val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(null as KeyStore?)
val trustManagers = trustManagerFactory.trustManagers
if (trustManagers.size == 1 && trustManagers[0] is X509TrustManager) {
class TLSSocketFactory @Throws(KeyManagementException::class, NoSuchAlgorithmException::class)
constructor() : SSLSocketFactory() {
private val internalSSLSocketFactory: SSLSocketFactory
init {
val context = SSLContext.getInstance("TLS")
context.init(null, null, null)
internalSSLSocketFactory = context.socketFactory
}
override fun getDefaultCipherSuites(): Array<String> {
return internalSSLSocketFactory.defaultCipherSuites
}
override fun getSupportedCipherSuites(): Array<String> {
return internalSSLSocketFactory.supportedCipherSuites
}
@Throws(IOException::class)
override fun createSocket(): Socket? {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket())
}
@Throws(IOException::class)
override fun createSocket(s: Socket, host: String, port: Int, autoClose: Boolean): Socket? {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(s, host, port, autoClose))
}
@Throws(IOException::class, UnknownHostException::class)
override fun createSocket(host: String, port: Int): Socket? {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port))
}
@Throws(IOException::class, UnknownHostException::class)
override fun createSocket(host: String, port: Int, localHost: InetAddress, localPort: Int): Socket? {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port, localHost, localPort))
}
@Throws(IOException::class)
override fun createSocket(host: InetAddress, port: Int): Socket? {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port))
}
@Throws(IOException::class)
override fun createSocket(address: InetAddress, port: Int, localAddress: InetAddress, localPort: Int): Socket? {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(address, port, localAddress, localPort))
}
private fun enableTLSOnSocket(socket: Socket?): Socket? {
if (socket != null && socket is SSLSocket) {
socket.enabledProtocols = socket.supportedProtocols
}
return socket
}
}
sslSocketFactory(TLSSocketFactory(), trustManagers[0] as X509TrustManager)
}
val specCompat = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0)
.cipherSuites(
*ConnectionSpec.MODERN_TLS.cipherSuites().orEmpty().toTypedArray(),
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
)
.build()
val specs = listOf(specCompat, ConnectionSpec.CLEARTEXT)
connectionSpecs(specs)
return this
}
}
|
apache-2.0
|
8d703f9c240a4f143a6296f595e240ce
| 39.516667 | 128 | 0.624229 | 5.42029 | false | false | false | false |
Waboodoo/HTTP-Shortcuts
|
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/DialogActionType.kt
|
1
|
786
|
package ch.rmy.android.http_shortcuts.scripting.actions.types
import ch.rmy.android.http_shortcuts.scripting.ActionAlias
import ch.rmy.android.http_shortcuts.scripting.actions.ActionDTO
class DialogActionType : BaseActionType() {
override val type = TYPE
override fun fromDTO(actionDTO: ActionDTO) = DialogAction(
message = actionDTO.getString(0) ?: "",
title = actionDTO.getString(1) ?: "",
)
override fun getAlias() = ActionAlias(
functionName = FUNCTION_NAME,
functionNameAliases = setOf(FUNCTION_NAME_ALIAS),
parameters = 2,
)
companion object {
private const val TYPE = "show_dialog"
private const val FUNCTION_NAME = "showDialog"
private const val FUNCTION_NAME_ALIAS = "alert"
}
}
|
mit
|
253ef1856c63be7ff1dec2d7695fb36d
| 29.230769 | 64 | 0.681934 | 4.15873 | false | false | false | false |
sksamuel/ktest
|
kotest-tests/kotest-tests-core/src/jvmTest/kotlin/com/sksamuel/kotest/specs/describe/DescribeSpecNestedBeforeAfterEachTest.kt
|
1
|
1231
|
package com.sksamuel.kotest.specs.describe
import io.kotest.core.spec.style.DescribeSpec
import io.kotest.matchers.shouldBe
class DescribeSpecNestedBeforeAfterEachTest : DescribeSpec({
var a = ""
beforeSpec {
a shouldBe ""
a = "beforeSpec"
}
beforeEach {
a = "beforeEachRoot"
}
afterEach {
a = "afterEachRoot"
}
describe("foo") {
a shouldBe "beforeSpec"
beforeEach {
a shouldBe "beforeEachRoot"
a = "beforeEachFoo"
}
afterEach {
a = "afterEachFoo"
}
it("b") {
a shouldBe "beforeEachFoo"
a = "testB"
}
it("e") {
a shouldBe "beforeEachFoo"
a = "testE"
}
describe("bar") {
a shouldBe "afterEachFoo"
it("f") {
a shouldBe "beforeEachFoo"
a = "testF"
}
it("g") {
a shouldBe "beforeEachFoo"
a = "testG"
}
}
it("h") {
a shouldBe "beforeEachFoo"
a = "testH"
}
}
afterSpec {
a shouldBe "afterEachFoo"
}
})
|
mit
|
a4f2a9a2893215a6cc46fd434e1f0ba3
| 17.373134 | 60 | 0.45329 | 4.412186 | false | true | false | false |
atlarge-research/opendc-simulator
|
opendc-model-odc/jpa/src/main/kotlin/com/atlarge/opendc/model/odc/integration/jpa/schema/Job.kt
|
1
|
2179
|
/*
* MIT License
*
* Copyright (c) 2017 atlarge-research
*
* 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.atlarge.opendc.model.odc.integration.jpa.schema
import com.atlarge.opendc.model.odc.platform.workload.Job
import com.atlarge.opendc.model.odc.platform.workload.User
import javax.persistence.Entity
/**
* A [Job] backed by the JPA API and an underlying database connection.
*
* @property id The unique identifier of the job.
* @property tasks The collection of tasks the job consists of.
* @author Fabian Mastenbroek ([email protected])
*/
@Entity
class Job(
override val id: Int,
override val tasks: MutableSet<Task>
) : Job {
/**
* The owner of the job, which is a singleton, since the database has no
* concept of ownership yet.
*/
override val owner: User = object : User {
/**
* The unique identifier of the user.
*/
override val id: Int = 0
/**
* The name of this user.
*/
override val name: String = "admin"
}
override fun toString(): String = "Job(id=$id, tasks=$tasks, owner=$owner)"
}
|
mit
|
fa59238e1c07e17ebd4f116fbdd8a34e
| 35.316667 | 81 | 0.708123 | 4.206564 | false | false | false | false |
breadwallet/breadwallet-android
|
app/src/main/java/com/platform/jsbridge/NativeApisJs.kt
|
1
|
2091
|
/**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 1/15/20.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.platform.jsbridge
import android.webkit.JavascriptInterface
import android.webkit.WebView
interface JsApi
class NativeApisJs(
private val apis: List<JsApi>
) {
companion object {
private const val JS_NAME = "NativeApisJs"
fun with(vararg apis: JsApi) =
NativeApisJs(apis.toList())
}
@JavascriptInterface
fun getApiNamesJson(): String =
apis.joinToString(prefix = "[", postfix = "]") {
"\"${it::class.java.simpleName}_Native\""
}
fun attachToWebView(webView: WebView) {
webView.addJavascriptInterface(PromiseJs(webView, getApiNamesJson()), PromiseJs.JS_NAME)
apis.forEach { api ->
val name = "${api::class.java.simpleName}_Native"
webView.addJavascriptInterface(api, name)
}
webView.addJavascriptInterface(this, JS_NAME)
}
}
|
mit
|
a4c51ea4d97b31af4b60646b2380dd48
| 36.339286 | 96 | 0.70923 | 4.365344 | false | false | false | false |
fossasia/rp15
|
app/src/main/java/org/fossasia/openevent/general/utils/StringUtils.kt
|
1
|
3458
|
package org.fossasia.openevent.general.utils
import android.content.Context
import android.content.res.Resources
import android.text.Html
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.util.Patterns
import android.view.View
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import org.fossasia.openevent.general.R
fun String?.nullToEmpty(): String {
return this ?: ""
}
fun String?.emptyToNull(): String? {
return if (this == "") null else this
}
fun String?.stripHtml(): String? {
return if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY).toString()
} else {
Html.fromHtml(this)?.toString() ?: this
}
}
fun TextInputEditText.checkEmpty(): Boolean {
if (text.isNullOrBlank()) {
error = resources.getString(R.string.empty_field_error_message)
return false
}
return true
}
fun TextInputEditText.checkValidEmail(): Boolean {
if (text.isNullOrBlank()) return false
if (!Patterns.EMAIL_ADDRESS.matcher(text.toString()).matches()) {
error = resources.getString(R.string.invalid_email_message)
return false
}
return true
}
fun TextInputLayout.setRequired() {
if (hint?.takeLast(1) != "*")
hint = "$hint *"
}
fun TextInputEditText.checkValidURI(): Boolean {
if (text.isNullOrBlank()) return false
if (!Patterns.WEB_URL.matcher(text.toString()).matches()) {
error = resources.getString(R.string.invalid_url_message)
return false
}
return true
}
object StringUtils {
fun getTermsAndPolicyText(context: Context, resources: Resources): SpannableStringBuilder {
val paragraph = SpannableStringBuilder()
val startText = resources.getString(R.string.start_text)
val termsText = resources.getString(R.string.terms_text)
val middleText = resources.getString(R.string.middle_text)
val privacyText = resources.getString(R.string.privacy_text)
paragraph.append(startText)
paragraph.append(" $termsText")
paragraph.append(" $middleText")
paragraph.append(" $privacyText")
val termsSpan = object : ClickableSpan() {
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.isUnderlineText = false
}
override fun onClick(widget: View) {
Utils.openUrl(context, resources.getString(R.string.terms_of_service))
}
}
val privacyPolicySpan = object : ClickableSpan() {
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.isUnderlineText = false
}
override fun onClick(widget: View) {
Utils.openUrl(context, resources.getString(R.string.privacy_policy))
}
}
paragraph.setSpan(termsSpan, startText.length, startText.length + termsText.length + 2,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
paragraph.setSpan(privacyPolicySpan, paragraph.length - privacyText.length, paragraph.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) // -1 so that we don't include "." in the link
return paragraph
}
}
|
apache-2.0
|
1a2e0ba28996e7308a717f2418d4745d
| 31.622642 | 101 | 0.669173 | 4.371681 | false | false | false | false |
orgzly/orgzly-android
|
app/src/main/java/com/orgzly/android/ui/util/Extensions.kt
|
1
|
3039
|
package com.orgzly.android.ui.util
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.Context
import android.content.res.TypedArray
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import android.util.AttributeSet
import android.view.View
import androidx.annotation.StyleableRes
import androidx.core.view.ViewCompat
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.orgzly.android.sync.SyncRunner
import org.joda.time.Period
import org.joda.time.format.PeriodFormat
fun <R> Context.styledAttributes(@StyleableRes attrs: IntArray, f: (typedArray: TypedArray) -> R): R {
val typedArray = obtainStyledAttributes(attrs)
try {
return f(typedArray)
} finally {
typedArray.recycle()
}
}
fun <R> Context.styledAttributes(set: AttributeSet, @StyleableRes attrs: IntArray, f: (typedArray: TypedArray) -> R): R {
val typedArray = obtainStyledAttributes(set, attrs)
try {
return f(typedArray)
} finally {
typedArray.recycle()
}
}
/**
* Determines if there is internet connection available.
*/
fun Context.haveNetworkConnection(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
haveNetworkConnection(getConnectivityManager())
} else {
haveNetworkConnectionPreM(getConnectivityManager())
}
}
@TargetApi(Build.VERSION_CODES.M)
private fun haveNetworkConnection(cm: ConnectivityManager): Boolean {
val network = cm.activeNetwork
val capabilities = cm.getNetworkCapabilities(network)
return capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}
@Suppress("DEPRECATION")
private fun haveNetworkConnectionPreM(cm: ConnectivityManager): Boolean {
val networkInfo = cm.activeNetworkInfo
if (networkInfo != null) {
val type = networkInfo.type
return type == ConnectivityManager.TYPE_WIFI || type == ConnectivityManager.TYPE_MOBILE
}
return false
}
@SuppressLint("ResourceType")
fun SwipeRefreshLayout.setup() {
setOnRefreshListener {
SyncRunner.startSync()
isRefreshing = false
}
}
fun View.removeBackgroundKeepPadding() {
val paddingBottom = this.paddingBottom
val paddingStart = ViewCompat.getPaddingStart(this)
val paddingEnd = ViewCompat.getPaddingEnd(this)
val paddingTop = this.paddingTop
ViewCompat.setBackground(this, null)
ViewCompat.setPaddingRelative(this, paddingStart, paddingTop, paddingEnd, paddingBottom)
}
fun View.goneIf(condition: Boolean) {
visibility = if (condition) View.GONE else View.VISIBLE
}
fun View.goneUnless(condition: Boolean) = goneIf(!condition)
fun View.invisibleIf(condition: Boolean) {
visibility = if (condition) View.INVISIBLE else View.VISIBLE
}
fun View.invisibleUnless(condition: Boolean) = invisibleIf(!condition)
fun Long.userFriendlyPeriod(): String {
return PeriodFormat.getDefault().print(Period(this))
}
|
gpl-3.0
|
13555b8e9a0723442d937f883cf11c90
| 28.230769 | 121 | 0.750247 | 4.449488 | false | false | false | false |
matthieucoisne/LeagueChampions
|
features/champions/src/main/java/com/leaguechampions/features/champions/presentation/championdetails/ChampionDetailsViewModel.kt
|
1
|
2079
|
package com.leaguechampions.features.champions.presentation.championdetails
import androidx.annotation.StringRes
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.map
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import com.leaguechampions.features.champions.R
import com.leaguechampions.features.champions.domain.usecase.GetChampionDetailsUseCase
import com.leaguechampions.libraries.core.utils.Resource
import kotlinx.coroutines.Dispatchers
import javax.inject.Inject
class ChampionDetailsViewModel @Inject constructor(
private val getChampionDetailsUseCase: GetChampionDetailsUseCase
) : ViewModel() {
sealed class ViewState {
data class ShowLoading(val championDetails: ChampionDetailsUiModel?) : ViewState()
data class ShowChampionDetails(val championDetails: ChampionDetailsUiModel) : ViewState()
data class ShowError(@StringRes val errorStringId: Int) : ViewState()
}
private val _viewState: MutableLiveData<ViewState>
val viewState: LiveData<ViewState>
get() = _viewState
private val championId = MutableLiveData<String>()
init {
_viewState = championId.switchMap { championId ->
liveData(context = viewModelScope.coroutineContext + Dispatchers.Main) {
emitSource(getChampionDetailsUseCase.execute(championId))
}
}.map { resource ->
when (resource) {
is Resource.Loading -> ViewState.ShowLoading(resource.data?.toChampionDetailsUiModel())
is Resource.Error -> ViewState.ShowError(R.string.error_something_went_wrong)
is Resource.Success -> ViewState.ShowChampionDetails(resource.data.toChampionDetailsUiModel())
}
} as MutableLiveData<ViewState>
}
fun setChampionId(championId: String?) {
if (this.championId.value != championId) {
this.championId.value = championId
}
}
}
|
apache-2.0
|
2354f45128e36f2646c864a7669b69d8
| 38.980769 | 110 | 0.735931 | 4.914894 | false | false | false | false |
androidx/media
|
demos/session/src/main/java/androidx/media3/demo/session/PlayableFolderActivity.kt
|
1
|
6954
|
/*
* 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.media3.demo.session
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.LinearLayout
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.session.MediaBrowser
import androidx.media3.session.SessionToken
import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
import com.google.android.material.snackbar.BaseTransientBottomBar
import com.google.android.material.snackbar.Snackbar
import com.google.common.util.concurrent.ListenableFuture
class PlayableFolderActivity : AppCompatActivity() {
private lateinit var browserFuture: ListenableFuture<MediaBrowser>
private val browser: MediaBrowser?
get() = if (browserFuture.isDone) browserFuture.get() else null
private lateinit var mediaList: ListView
private lateinit var mediaListAdapter: PlayableMediaItemArrayAdapter
private val subItemMediaList: MutableList<MediaItem> = mutableListOf()
companion object {
private const val MEDIA_ITEM_ID_KEY = "MEDIA_ITEM_ID_KEY"
fun createIntent(context: Context, mediaItemID: String): Intent {
val intent = Intent(context, PlayableFolderActivity::class.java)
intent.putExtra(MEDIA_ITEM_ID_KEY, mediaItemID)
return intent
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_playable_folder)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
mediaList = findViewById(R.id.media_list_view)
mediaListAdapter =
PlayableMediaItemArrayAdapter(this, R.layout.playable_items, subItemMediaList)
mediaList.adapter = mediaListAdapter
mediaList.setOnItemClickListener { _, _, position, _ ->
run {
val browser = this.browser ?: return@run
browser.setMediaItems(
subItemMediaList,
/* startIndex= */ position,
/* startPositionMs= */ C.TIME_UNSET
)
browser.shuffleModeEnabled = false
browser.prepare()
browser.play()
val intent = Intent(this, PlayerActivity::class.java)
startActivity(intent)
}
}
findViewById<Button>(R.id.shuffle_button).setOnClickListener {
val browser = this.browser ?: return@setOnClickListener
browser.setMediaItems(subItemMediaList)
browser.shuffleModeEnabled = true
browser.prepare()
browser.play()
val intent = Intent(this, PlayerActivity::class.java)
startActivity(intent)
}
findViewById<Button>(R.id.play_button).setOnClickListener {
val browser = this.browser ?: return@setOnClickListener
browser.setMediaItems(subItemMediaList)
browser.shuffleModeEnabled = false
browser.prepare()
browser.play()
val intent = Intent(this, PlayerActivity::class.java)
startActivity(intent)
}
findViewById<ExtendedFloatingActionButton>(R.id.open_player_floating_button)
.setOnClickListener {
// display the playing media items
val intent = Intent(this, PlayerActivity::class.java)
startActivity(intent)
}
}
override fun onStart() {
super.onStart()
initializeBrowser()
}
override fun onStop() {
super.onStop()
releaseBrowser()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}
private fun initializeBrowser() {
browserFuture =
MediaBrowser.Builder(
this,
SessionToken(this, ComponentName(this, PlaybackService::class.java))
)
.buildAsync()
browserFuture.addListener({ displayFolder() }, ContextCompat.getMainExecutor(this))
}
private fun releaseBrowser() {
MediaBrowser.releaseFuture(browserFuture)
}
private fun displayFolder() {
val browser = this.browser ?: return
val id: String = intent.getStringExtra(MEDIA_ITEM_ID_KEY)!!
val mediaItemFuture = browser.getItem(id)
val childrenFuture =
browser.getChildren(id, /* page= */ 0, /* pageSize= */ Int.MAX_VALUE, /* params= */ null)
mediaItemFuture.addListener(
{
val title: TextView = findViewById(R.id.folder_description)
val result = mediaItemFuture.get()!!
title.text = result.value!!.mediaMetadata.title
},
ContextCompat.getMainExecutor(this)
)
childrenFuture.addListener(
{
val result = childrenFuture.get()!!
val children = result.value!!
subItemMediaList.clear()
subItemMediaList.addAll(children)
mediaListAdapter.notifyDataSetChanged()
},
ContextCompat.getMainExecutor(this)
)
}
private inner class PlayableMediaItemArrayAdapter(
context: Context,
viewID: Int,
mediaItemList: List<MediaItem>
) : ArrayAdapter<MediaItem>(context, viewID, mediaItemList) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val mediaItem = getItem(position)!!
val returnConvertView =
convertView ?: LayoutInflater.from(context).inflate(R.layout.playable_items, parent, false)
returnConvertView.findViewById<TextView>(R.id.media_item).text = mediaItem.mediaMetadata.title
returnConvertView.findViewById<TextView>(R.id.add_button).setOnClickListener {
val browser = [email protected] ?: return@setOnClickListener
browser.addMediaItem(mediaItem)
if (browser.playbackState == Player.STATE_IDLE) {
browser.prepare()
}
Snackbar.make(
findViewById<LinearLayout>(R.id.linear_layout),
getString(R.string.added_media_item_format, mediaItem.mediaMetadata.title),
BaseTransientBottomBar.LENGTH_SHORT
)
.show()
}
return returnConvertView
}
}
}
|
apache-2.0
|
79c292187f027fa34b19d2ba55874d1a
| 33.77 | 100 | 0.714697 | 4.651505 | false | false | false | false |
mniami/android.kotlin.benchmark
|
app/src/main/java/guideme/volunteers/ui/fragments/volunteer/details/users/VolunteerDetailsFragment.kt
|
2
|
6168
|
package guideme.volunteers.ui.fragments.volunteer.details.users
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentPagerAdapter
import android.text.Html
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import com.squareup.picasso.Picasso
import guideme.volunteers.R
import guideme.volunteers.domain.Privilege
import guideme.volunteers.domain.Volunteer
import guideme.volunteers.helpers.Container
import guideme.volunteers.helpers.dataservices.datasource.UserDataSource
import guideme.volunteers.helpers.dataservices.errors.ErrorMessage
import guideme.volunteers.helpers.dataservices.errors.ErrorType
import guideme.volunteers.ui.fragments.base.BaseFragment
import guideme.volunteers.ui.fragments.base.FragmentConfiguration
import guideme.volunteers.ui.fragments.volunteer.details.VolunteerProjectListFragment
import io.reactivex.rxkotlin.subscribeBy
import kotlinx.android.synthetic.main.volunteer_details_account.*
import kotlinx.android.synthetic.main.volunteer_details_fragment.*
class VolunteerDetailsFragment : BaseFragment<VolunteerDetailsPresenter>(), IVolunteerDetailsFragment {
companion object {
val VOLUNTEER_ARG = "volunteer"
}
private var actionEdit: MenuItem? = null
private var actionDelete: MenuItem? = null
init {
presenter = VolunteerDetailsPresenter(this)
configuration = FragmentConfiguration
.withLayout(R.layout.volunteer_details_fragment)
.withMenu(R.menu.volunteers_details_menu)
.showBackArrow()
.create()
}
override fun onStart() {
super.onStart()
val volunteer = presenter?.volunteer
if (volunteer == null){
return
}
Container.database.getVolunteers()
.filter { it -> it.id == volunteer.id }
.subscribeBy (
onNext = {
presenter?.volunteer = it
},
onComplete = {
updateView()
}
)
}
private fun updateView() {
actionBar.hideOptions()
val volunteer = presenter?.volunteer
if (volunteer == null) {
return
}
presenter?.volunteer?.let { v ->
val address = v.person.addresses.entries.firstOrNull()
var subHeader = v.person.email
if (address != null) {
subHeader += getString(R.string.person_short_description)
subHeader = subHeader.replace("%city", address.value.city).replace("%zip", address.value.zip).replace("%street", address.value.street)
}
actionBar.setTitle("${v.person.name} ${v.person.surname}")
tvSubHeader?.text = Html.fromHtml(subHeader)
tvHeader?.text = "${v.person.name} ${v.person.surname}"
if (v.person.avatarImageUri.isNotEmpty()) {
Picasso.with(context).load(v.person.avatarImageUri).into(ivImage)
}
tvShortDescription?.text = v.person.personalityDescription
tvDescription?.text = v.person.description
val userDataSource = Container.dataSourceContainer.getDataSource(UserDataSource.ID) as UserDataSource?
userDataSource?.let {
it.item.observable.subscribeBy(onNext = { currentUser ->
val visible = currentUser.person.privilege == Privilege.ADMIN
actionEdit?.isVisible = visible
actionDelete?.isVisible = visible
})
}
}
viewPager?.let {
it.adapter = object : FragmentPagerAdapter(childFragmentManager) {
override fun getCount(): Int {
return 1
}
override fun getItem(position: Int): Fragment? {
return presenter?.volunteer?.let { volunteer ->
var fragment: Fragment? = null
when (position) {
0 -> fragment = VolunteerDetailsAccountFragment()
1 -> fragment = VolunteerProjectListFragment()
}
val bundle = Bundle()
bundle.putSerializable("volunteer", volunteer)
fragment?.arguments = bundle
return@let fragment
}
}
override fun getPageTitle(position: Int): CharSequence {
when (position) {
0 -> return getString(R.string.details_label)
1 -> return getString(R.string.projects_label)
}
return ""
}
}
slidingTabLayout?.setViewPager(it)
}
}
override fun setArguments(args: Bundle?) {
super.setArguments(args)
presenter?.let {
it.volunteer = args?.get(VOLUNTEER_ARG) as Volunteer?
}
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
super.onCreateOptionsMenu(menu, inflater)
actionEdit = menu?.findItem(R.id.action_edit)
actionDelete = menu?.findItem(R.id.action_delete)
val v = presenter?.volunteer
if (v == null) {
return
}
actionDelete?.setOnMenuItemClickListener {
Container.database.deleteVolunteer(v)
.subscribeBy(
onSuccess = {
mainActivity.goBack()
},
onError = {
mainActivity.showError(ErrorMessage(ErrorType.DELETE_FAILED, "Delete Volunteer failed"))
})
return@setOnMenuItemClickListener true
}
actionEdit?.setOnMenuItemClickListener {
mainActivity.openEditUserDetails(v)
return@setOnMenuItemClickListener true
}
}
}
|
apache-2.0
|
2095525eec9cff55da31a5f6c7145163
| 36.846626 | 150 | 0.577659 | 5.205063 | false | false | false | false |
wizardofos/Protozoo
|
server/task/src/main/kotlin/org/protozoo/server/task/TaskResource.kt
|
1
|
1746
|
package org.protozoo.server.task
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import org.osgi.service.component.annotations.*
import org.protozoo.component.task.api.Task
import org.protozoo.component.task.api.TaskManager
import org.protozoo.server.core.RestService
import javax.ws.rs.GET
import javax.ws.rs.OPTIONS
import javax.ws.rs.Produces
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
@JsonIgnoreProperties(
value = "task"
)
@Component(
name = "TaskResource",
service = arrayOf(RestService::class),
enabled = true,
immediate = true
)
@Produces(MediaType.APPLICATION_JSON)
class TaskResource : RestService {
private lateinit var manager: TaskManager
@GET
fun getAll(): Response {
val task = manager.get(0)
return Response
.ok()
.entity(task)
.build()
}
@OPTIONS
fun getCors(): Response {
return Response
.ok()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE")
.header("Access-Control-Allow-Headers", "Access-Control-Allow-Origin, Content-Type")
.header("Access-Control-Max-Age", 86400)
.type("text/plain")
.build()
}
@Activate
fun activate() {
println("Task resource activated " + this)
}
@Deactivate
fun deactivate() {
println("Task resource deactivated " + this)
}
@Reference(
name = "manager",
service = TaskManager::class
)
fun setManager(mgr: TaskManager) {
this.manager = mgr
}
}
|
mit
|
ced72c227c041aead0c6c92773f57864
| 23.957143 | 100 | 0.609393 | 4.217391 | false | false | false | false |
fython/shadowsocks-android
|
mobile/src/main/java/com/github/shadowsocks/widget/ShrinkUpwardBehavior.kt
|
4
|
3437
|
/*******************************************************************************
* *
* Copyright (C) 2017 by Max Lv <[email protected]> *
* Copyright (C) 2017 by Mygod Studio <[email protected]> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
package com.github.shadowsocks.widget
import android.animation.ValueAnimator
import android.content.Context
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.Snackbar
import android.support.design.widget.SnackbarAnimation
import android.util.AttributeSet
import android.view.View
import android.view.accessibility.AccessibilityManager
/**
* Full credits go to: https://stackoverflow.com/a/35904421/2245107
*/
class ShrinkUpwardBehavior(context: Context, attrs: AttributeSet) : CoordinatorLayout.Behavior<View>(context, attrs) {
private val accessibility = context.getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager
override fun layoutDependsOn(parent: CoordinatorLayout, child: View, dependency: View): Boolean =
dependency is Snackbar.SnackbarLayout
override fun onDependentViewChanged(parent: CoordinatorLayout, child: View, dependency: View): Boolean {
child.layoutParams.height = dependency.y.toInt()
child.requestLayout()
return true
}
/**
* Based on BaseTransientBottomBar.animateViewOut (support lib 27.0.2).
*/
override fun onDependentViewRemoved(parent: CoordinatorLayout, child: View, dependency: View) {
if (accessibility.isEnabled) child.layoutParams.height = parent.height else {
val animator = ValueAnimator()
val start = child.height
animator.setIntValues(start, parent.height)
animator.interpolator = SnackbarAnimation.FAST_OUT_SLOW_IN_INTERPOLATOR
animator.duration = SnackbarAnimation.ANIMATION_DURATION
@Suppress("NAME_SHADOWING")
animator.addUpdateListener { animator ->
child.layoutParams.height = animator.animatedValue as Int
child.requestLayout()
}
animator.start()
}
}
}
|
gpl-3.0
|
4925562161ac7dc33256c490914a2dc4
| 51.876923 | 118 | 0.566773 | 5.4992 | false | false | false | false |
googlecodelabs/mdc-android-kotlin
|
complete/app/src/main/java/io/material/demo/codelab/buildingbeautifulapps/MainActivity.kt
|
1
|
5476
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.material.demo.codelab.buildingbeautifulapps
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.android.volley.toolbox.NetworkImageView
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.shr_main.*
import java.io.IOException
import java.util.*
/**
* Main activity for Shrine that displays a listing of available products.
*/
class MainActivity : AppCompatActivity() {
private var adapter: ProductAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.shr_main)
setSupportActionBar(app_bar)
val products = readProductsList()
val imageRequester = ImageRequester.getInstance(this)
val headerProduct = getHeaderProduct(products)
imageRequester.setImageFromUrl(app_bar_image, headerProduct.url)
product_list.setHasFixedSize(true)
product_list.layoutManager = GridLayoutManager(this, resources.getInteger(R.integer.shr_column_count))
adapter = ProductAdapter(products, imageRequester)
product_list.adapter = adapter
bottom_navigation.setOnNavigationItemSelectedListener {
val layoutManager = product_list.layoutManager as GridLayoutManager
layoutManager.scrollToPositionWithOffset(0, 0)
shuffleProducts()
true
}
bottom_navigation.setOnNavigationItemReselectedListener {
val layoutManager = product_list.layoutManager as GridLayoutManager
layoutManager.scrollToPositionWithOffset(0, 0)
}
if (savedInstanceState == null) {
bottom_navigation.selectedItemId = R.id.category_home
}
}
private fun getHeaderProduct(products: List<ProductEntry>): ProductEntry {
if (products.isEmpty()) {
throw IllegalArgumentException("There must be at least one product")
}
for (i in products.indices) {
if ("Perfect Goldfish Bowl" == products[i].title) {
return products[i]
}
}
return products[0]
}
private fun shuffleProducts() {
val products = readProductsList()
Collections.shuffle(products)
adapter?.setProducts(products)
}
private fun readProductsList(): ArrayList<ProductEntry> {
val inputStream = resources.openRawResource(R.raw.products)
val productListType = object : TypeToken<ArrayList<ProductEntry>>() {
}.type
try {
return JsonReader.readJsonStream<ArrayList<ProductEntry>>(inputStream, productListType)
} catch (e: IOException) {
Log.e(TAG, "Error reading JSON product list", e)
return ArrayList()
}
}
private class ProductAdapter internal constructor(private var products: List<ProductEntry>, private val imageRequester: ImageRequester) : RecyclerView.Adapter<ProductViewHolder>() {
internal fun setProducts(products: List<ProductEntry>) {
this.products = products
notifyDataSetChanged()
}
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ProductViewHolder {
return ProductViewHolder(viewGroup)
}
override fun onBindViewHolder(viewHolder: ProductViewHolder, i: Int) {
viewHolder.bind(products[i], imageRequester)
}
override fun getItemCount(): Int {
return products.size
}
}
private class ProductViewHolder internal constructor(parent: ViewGroup) : RecyclerView.ViewHolder(LayoutInflater.from(parent.context).inflate(
R.layout.shr_product_entry, parent, false)) {
private val imageView: NetworkImageView
private val priceView: TextView
private val clickListener = View.OnClickListener { v ->
val product = v.getTag(R.id.tag_product_entry) as ProductEntry
// TODO: show product details
}
init {
imageView = itemView.findViewById(R.id.image) as NetworkImageView
priceView = itemView.findViewById(R.id.price) as TextView
itemView.setOnClickListener(clickListener)
}
internal fun bind(product: ProductEntry, imageRequester: ImageRequester) {
itemView.setTag(R.id.tag_product_entry, product)
imageRequester.setImageFromUrl(imageView, product.url)
priceView.text = product.price
}
}
companion object {
private val TAG = MainActivity::class.java.simpleName
}
}
|
apache-2.0
|
ac803f3c215b3455e5cb21d74e159325
| 34.329032 | 185 | 0.685354 | 4.889286 | false | false | false | false |
AlmasB/FXGL
|
fxgl/src/main/kotlin/com/almasb/fxgl/dsl/effects/WobbleEffect.kt
|
1
|
2852
|
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.dsl.effects
import com.almasb.fxgl.core.math.FXGLMath
import com.almasb.fxgl.dsl.components.Effect
import com.almasb.fxgl.entity.Entity
import com.almasb.fxgl.texture.Texture
import javafx.geometry.Orientation
import javafx.geometry.Rectangle2D
import javafx.scene.Group
import javafx.util.Duration
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class WobbleEffect
@JvmOverloads constructor(
val texture: Texture,
duration: Duration,
val radius: Int = 2,
val numChunks: Int = 5,
val orientation: Orientation = Orientation.HORIZONTAL
) : Effect(duration) {
private val quads = arrayListOf<Texture>()
private val newView = Group()
private var tick = 0
init {
val chunkSize = getChunkSize()
val endVal = getMaxDimension()
var minVal = 0.0
while (minVal < endVal) {
val quad: Texture
val maxVal = if (minVal + chunkSize > endVal)
endVal
else
(minVal + chunkSize).toInt().toDouble()
if (orientation == Orientation.HORIZONTAL) {
quad = texture.subTexture(Rectangle2D(0.0, minVal, texture.image.width, maxVal - minVal))
quad.translateY = minVal
} else {
quad = texture.subTexture(Rectangle2D(minVal, 0.0, maxVal - minVal, texture.image.height))
quad.translateX = minVal
}
minVal = maxVal
quads.add(quad)
newView.children.add(quad)
}
}
private fun getMaxDimension(): Double {
return if (orientation == Orientation.HORIZONTAL)
texture.image.height
else
texture.image.width
}
private fun getChunkSize(): Double {
return if (orientation == Orientation.HORIZONTAL)
texture.image.height / numChunks
else
texture.image.width / numChunks
}
override fun onStart(entity: Entity) {
tick = 0
entity.viewComponent.children.forEach { it.isVisible = false }
entity.viewComponent.addChild(newView)
}
override fun onUpdate(entity: Entity, tpf: Double) {
tick += 1
quads.forEachIndexed { index, quad ->
val value = FXGLMath.sin((tick + index / 0.5)) * radius
if (orientation == Orientation.HORIZONTAL) {
quad.translateX = value
} else {
quad.translateY = value
}
}
}
override fun onEnd(entity: Entity) {
entity.viewComponent.removeChild(newView)
entity.viewComponent.children.forEach { it.isVisible = true }
}
}
|
mit
|
c95baa2c5679fefe9544cf7e6d541ab9
| 25.663551 | 106 | 0.601683 | 4.401235 | false | false | false | false |
NLPIE/BioMedICUS
|
biomedicus-core/src/test/kotlin/edu/umn/biomedicus/framework/RunnerFactoryTest.kt
|
1
|
2944
|
/*
* Copyright (c) 2018 Regents of the University of Minnesota.
*
* 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 edu.umn.biomedicus.framework
import com.google.inject.Guice
import com.google.inject.Stage
import edu.umn.nlpengine.*
import java.lang.System
import kotlin.concurrent.thread
import kotlin.test.Test
import kotlin.test.assertSame
import kotlin.test.assertTrue
private var processed: Document? = null
private var done = false
class DPStub : DocumentsProcessor {
override fun process(document: Document) {
processed = document
}
override fun done() {
done = true
}
}
class RunnerFactoryTest {
class TestArtifactsProcessor : ArtifactsProcessor {
override fun process(artifact: Artifact) {
}
override fun done() {
}
}
@Test
fun `processors shared across threads`() {
System.setProperty("biomedicus.paths.home", ".")
val application = Bootstrapper.create(Guice.createInjector(Stage.DEVELOPMENT))
val runnerFactory = application.getInstance(RunnerFactory::class.java)
val runner1 = runnerFactory.getRunner("test",
mapOf(Pair("pipelineComponent", TestArtifactsProcessor::class.java.name)),
emptyMap())
var runner2: Runner? = null
thread(start = true) {
runner2 = runnerFactory.getRunner("test",
mapOf(Pair("pipelineComponent", TestArtifactsProcessor::class.java.name)),
emptyMap())
}.join()
assertTrue(runner1 === runner2, "Runners should be shared across threads")
}
@Test
fun `document processor runner`() {
System.setProperty("biomedicus.paths.home", ".")
val application = Bootstrapper.create(Guice.createInjector(Stage.DEVELOPMENT))
val runnerFactory = application.getInstance(RunnerFactory::class.java)
val runner = runnerFactory.getRunner("test",
mapOf(Pair("pipelineComponent", DPStub::class.java.name),
Pair("documentName", "blah")),
emptyMap())
val artifact = StandardArtifact("blah")
val document = artifact.addDocument("blah", "some text")
runner.processArtifact(artifact)
runner.done()
assertSame(document, processed, "document passed to processor")
assertTrue(done, "done not called after finished")
}
}
|
apache-2.0
|
9ddd0566800ac461c03698c25a695737
| 30.319149 | 94 | 0.667459 | 4.607199 | false | true | false | false |
RP-Kit/RPKit
|
bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/command/character/set/CharacterSetProfileCommand.kt
|
1
|
10519
|
/*
* Copyright 2021 Ren 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.characters.bukkit.command.character.set
import com.rpkit.characters.bukkit.RPKCharactersBukkit
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.RPKProfileDiscriminator
import com.rpkit.players.bukkit.profile.RPKProfileName
import com.rpkit.players.bukkit.profile.RPKProfileService
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.conversations.*
import org.bukkit.entity.Player
/**
* Character set profile command.
* Transfers a character to another profile.
*/
class CharacterSetProfileCommand(private val plugin: RPKCharactersBukkit) : CommandExecutor {
private val conversationFactory: ConversationFactory
init {
conversationFactory = ConversationFactory(plugin)
.withModality(true)
.withFirstPrompt(ProfilePrompt())
.withEscapeSequence("cancel")
.thatExcludesNonPlayersWithMessage(plugin.messages["not-from-console"])
.addConversationAbandonedListener { event ->
if (!event.gracefulExit()) {
val conversable = event.context.forWhom
if (conversable is Player) {
conversable.sendMessage(plugin.messages["operation-cancelled"])
}
}
}
}
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean {
if (sender !is Player) {
sender.sendMessage(plugin.messages["not-from-console"])
return true
}
if (!sender.hasPermission("rpkit.characters.command.character.set.profile")) {
sender.sendMessage(plugin.messages["no-permission-character-set-player"])
return true
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile-service"])
return true
}
val characterService = Services[RPKCharacterService::class.java]
if (characterService == null) {
sender.sendMessage(plugin.messages["no-character-service"])
return true
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(sender)
if (minecraftProfile == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
return true
}
val character = characterService.getPreloadedActiveCharacter(minecraftProfile)
if (character == null) {
sender.sendMessage(plugin.messages["no-character"])
return true
}
if (args.isEmpty()) {
conversationFactory.buildConversation(sender).begin()
return true
}
val profileService = Services[RPKProfileService::class.java]
if (profileService == null) {
sender.sendMessage(plugin.messages["no-profile-service"])
return true
}
if (!args[0].contains("#")) {
sender.sendMessage(plugin.messages["character-set-profile-invalid-no-discriminator"])
return true
}
val (name, discriminatorString) = args[0].split("#")
val discriminator = discriminatorString.toIntOrNull()
if (discriminator == null) {
sender.sendMessage(plugin.messages["character-set-profile-invalid-discriminator"])
return true
}
profileService.getProfile(RPKProfileName(name), RPKProfileDiscriminator(discriminator)).thenAccept { newProfile ->
if (newProfile == null) {
sender.sendMessage(plugin.messages["character-set-profile-invalid-profile"])
return@thenAccept
}
character.profile = newProfile
characterService.updateCharacter(character).thenAccept { updatedCharacter ->
plugin.server.scheduler.runTask(plugin, Runnable {
characterService.setActiveCharacter(minecraftProfile, null).thenRun {
sender.sendMessage(plugin.messages["character-set-profile-valid"])
updatedCharacter?.showCharacterCard(minecraftProfile)
}
})
}
}
return true
}
private inner class ProfilePrompt : ValidatingPrompt() {
override fun getPromptText(context: ConversationContext): String {
return plugin.messages["character-set-profile-prompt"]
}
override fun acceptValidatedInput(context: ConversationContext, input: String): Prompt {
val conversable = context.forWhom
if (conversable !is Player) return END_OF_CONVERSATION
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return END_OF_CONVERSATION
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(conversable) ?: return END_OF_CONVERSATION
val characterService = Services[RPKCharacterService::class.java] ?: return END_OF_CONVERSATION
val character = characterService.getPreloadedActiveCharacter(minecraftProfile) ?: return END_OF_CONVERSATION
val profileService = Services[RPKProfileService::class.java] ?: return END_OF_CONVERSATION
val (name, discriminatorString) = input.split("#")
val discriminator = discriminatorString.toIntOrNull() ?: return END_OF_CONVERSATION
val newProfile = profileService.getPreloadedProfile(RPKProfileName(name), RPKProfileDiscriminator(discriminator)) ?: return END_OF_CONVERSATION
character.profile = newProfile
characterService.updateCharacter(character)
characterService.setActiveCharacter(minecraftProfile, null)
return ProfileSetPrompt()
}
override fun isInputValid(context: ConversationContext, input: String): Boolean {
val conversable = context.forWhom as? Player ?: return false
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return false
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(conversable) ?: return false
val characterService = Services[RPKCharacterService::class.java] ?: return false
characterService.getPreloadedActiveCharacter(minecraftProfile) ?: return false
val profileService = Services[RPKProfileService::class.java] ?: return false
if (!input.contains("#")) return false
val (name, discriminatorString) = input.split("#")
val discriminator = discriminatorString.toIntOrNull() ?: return false
profileService.getPreloadedProfile(RPKProfileName(name), RPKProfileDiscriminator(discriminator)) ?: return false
return true
}
override fun getFailedValidationText(context: ConversationContext, invalidInput: String): String {
val conversable = context.forWhom as? Player ?: return plugin.messages["not-from-console"]
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return plugin.messages["no-minecraft-profile-service"]
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(conversable)
?: return plugin.messages["no-minecraft-profile"]
val characterService = Services[RPKCharacterService::class.java] ?: return plugin.messages["no-character-service"]
characterService.getPreloadedActiveCharacter(minecraftProfile) ?: return plugin.messages["no-character"]
val profileService = Services[RPKProfileService::class.java] ?: return plugin.messages["character-set-profile-invalid-profile"]
if (!invalidInput.contains("#")) return plugin.messages["character-set-profile-invalid-no-discriminator"]
val (name, discriminatorString) = invalidInput.split("#")
val discriminator = discriminatorString.toIntOrNull() ?: return plugin.messages["character-set-profile-invalid-discriminator"]
profileService.getPreloadedProfile(RPKProfileName(name), RPKProfileDiscriminator(discriminator)) ?: return plugin.messages["character-set-profile-invalid-profile"]
return ""
}
}
private inner class ProfileSetPrompt : MessagePrompt() {
override fun getNextPrompt(context: ConversationContext): Prompt? {
val conversable = context.forWhom
if (conversable !is Player) return Prompt.END_OF_CONVERSATION
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
conversable.sendMessage(plugin.messages["no-minecraft-profile-service"])
return END_OF_CONVERSATION
}
val characterService = Services[RPKCharacterService::class.java]
if (characterService == null) {
conversable.sendMessage(plugin.messages["no-character-service"])
return END_OF_CONVERSATION
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(context.forWhom as Player)
if (minecraftProfile != null) {
characterService.getPreloadedActiveCharacter(minecraftProfile)?.showCharacterCard(minecraftProfile)
}
return END_OF_CONVERSATION
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages["character-set-profile-valid"]
}
}
}
|
apache-2.0
|
89e8281693ae8c69cc65aa77b8131bcd
| 51.333333 | 175 | 0.67649 | 5.504448 | false | false | false | false |
j2ghz/tachiyomi-extensions
|
src/en/mangago/src/eu/kanade/tachiyomi/extension/en/mangago/Mangago.kt
|
1
|
21311
|
package eu.kanade.tachiyomi.extension.en.mangago
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Rect
import android.net.Uri
import com.squareup.duktape.Duktape
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.*
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.MediaType
import okhttp3.Request
import okhttp3.ResponseBody
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.text.SimpleDateFormat
import java.util.*
/**
* Mangago source
*/
class Mangago : ParsedHttpSource() {
override val lang = "en"
override val supportsLatest = true
override val name = "Mangago"
override val baseUrl = "https://www.mangago.me"
override val client = network.cloudflareClient.newBuilder().addInterceptor { chain ->
val request = chain.request()
val response = chain.proceed(request)
if (!request.url().pathSegments().contains("cspiclink")) return@addInterceptor response
val res = response.body()!!.byteStream().use {
decodeImage(request.url().toString(), it)
}
val rb = ResponseBody.create(MediaType.parse("image/png"), res)
response.newBuilder().body(rb).build()
}.build()
//Hybrid selector that selects manga from either the genre listing or the search results
private val genreListingSelector = ".updatesli"
private val genreListingNextPageSelector = ".current+li > a"
private val dateFormat = SimpleDateFormat("MMM d, yyyy", Locale.ENGLISH)
override fun popularMangaSelector() = genreListingSelector
private fun mangaFromElement(element: Element) = SManga.create().apply {
val linkElement = element.select(".thm-effect")
setUrlWithoutDomain(linkElement.attr("href"))
title = linkElement.attr("title")
thumbnail_url = linkElement.first().child(0).attr("src")
}
override fun popularMangaFromElement(element: Element) = mangaFromElement(element)
override fun popularMangaNextPageSelector() = genreListingNextPageSelector
//Hybrid selector that selects manga from either the genre listing or the search results
override fun searchMangaSelector() = "$genreListingSelector, .pic_list .box"
override fun searchMangaFromElement(element: Element) = mangaFromElement(element)
override fun searchMangaNextPageSelector() = genreListingNextPageSelector
override fun popularMangaRequest(page: Int) = GET("$baseUrl/genre/all/$page/?f=1&o=1&sortby=view&e=")
override fun latestUpdatesSelector() = genreListingSelector
override fun latestUpdatesFromElement(element: Element) = mangaFromElement(element)
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
//If text search is active use text search, otherwise use genre search
val url = if (query.isNotBlank()) {
Uri.parse("$baseUrl/r/l_search/")
.buildUpon()
.appendQueryParameter("name", query)
.appendQueryParameter("page", page.toString())
.toString()
} else {
val uri = Uri.parse("$baseUrl/genre/").buildUpon()
val genres = filters.flatMap {
(it as? GenreGroup)?.stateList ?: emptyList()
}
//Append included genres
val activeGenres = genres.filter { it.isIncluded() }
uri.appendPath(if (activeGenres.isEmpty())
"all"
else
activeGenres.joinToString(",", transform = { it.name }))
//Append page number
uri.appendPath(page.toString())
//Append excluded genres
uri.appendQueryParameter("e",
genres.filter { it.isExcluded() }
.joinToString(",", transform = GenreFilter::name))
//Append uri filters
filters.forEach {
if (it is UriFilter)
it.addToUri(uri)
}
uri.toString()
}
return GET(url)
}
override fun latestUpdatesNextPageSelector() = genreListingNextPageSelector
override fun mangaDetailsParse(document: Document) = SManga.create().apply {
val coverElement = document.select(".left.cover > img")
title = coverElement.attr("alt")
thumbnail_url = coverElement.attr("src")
document.select(".manga_right td").forEach {
when (it.getElementsByTag("label").text().trim().toLowerCase()) {
"status:" -> {
status = when (it.getElementsByTag("span").first().text().trim().toLowerCase()) {
"ongoing" -> SManga.ONGOING
"completed" -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
}
"author:" -> {
author = it.getElementsByTag("a").first().text()
}
"genre(s):" -> {
genre = it.getElementsByTag("a").joinToString(transform = { it.text() })
}
}
}
description = document.getElementsByClass("manga_summary").first().ownText().trim()
}
override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/genre/all/$page/?f=1&o=1&sortby=update_date&e=")
override fun chapterListSelector() = "#chapter_table > tbody > tr"
override fun chapterFromElement(element: Element) = SChapter.create().apply {
val link = element.getElementsByTag("a")
setUrlWithoutDomain(link.attr("href"))
name = link.text().trim()
date_upload = dateFormat.parse(element.getElementsByClass("no").text().trim()).time
}
fun decodeImage(url: String,
img: InputStream): ByteArray {
val decoded = BitmapFactory.decodeStream(img)
val js = "var img = '$url';" +
"var width = ${decoded.width};" +
"var height = ${decoded.height};" +
IMAGE_DESCRAMBLER_JS
val strRes = Duktape.create().use {
it.evaluate(js) as String
}
val result = Bitmap.createBitmap(decoded.width,
decoded.height,
Bitmap.Config.ARGB_8888)
val canvas = Canvas(result)
val arrayRes = strRes.split(" ").filter(String::isNotBlank).map {
it.split(",").filter(String::isNotBlank).map(String::toInt)
}
arrayRes.forEach { (srcX, srcY, chunkWidth, chunkHeight, destX, destY) ->
canvas.drawBitmap(decoded,
Rect(srcX, srcY, srcX + chunkWidth, srcY + chunkHeight),
Rect(destX, destY, destX + chunkWidth, destY + chunkHeight),
null)
}
val output = ByteArrayOutputStream()
result.compress(Bitmap.CompressFormat.PNG, 100, output)
return output.toByteArray()
}
private val JS_BEGIN_MARKER = "var imgsrcs = '"
private val JS_END_MARKER = "';"
override fun pageListParse(document: Document): List<Page> {
val imgSrc = document.getElementsByTag("script").map {
it.data().trim()
}.find {
it.startsWith(JS_BEGIN_MARKER) && it.endsWith(JS_END_MARKER)
} ?: throw IllegalArgumentException("Cannot decode imgsrcs!")
val res = Duktape.create().use {
it.evaluate(getCryptoJSLib())
it.evaluate(getCryptoJSZeroPaddingLib())
it.evaluate(imgSrc + IMGSRCS_DECODE_JS) as String
}
return res.split(",").mapIndexed { i, s ->
Page(i, s, s)
}
}
override fun imageUrlParse(document: Document) = throw UnsupportedOperationException("Unused method called!")
override fun getFilterList() = FilterList(
//Mangago does not support genre filtering and text search at the same time
Filter.Header("NOTE: Ignored if using text search!"),
Filter.Separator(),
Filter.Header("Status"),
StatusFilter("Completed", "f"),
StatusFilter("Ongoing", "o"),
GenreGroup(),
SortFilter()
)
// Array.from(document.querySelectorAll('#genre_panel ul li:not(.genres_title) a')).map(a => `GenreFilter("${a.getAttribute('_id')}")`).sort().join(',\n')
// on http://www.mangago.me/genre/all/
private class GenreGroup : UriFilterGroup<GenreFilter>("Genres", listOf(
GenreFilter("Yaoi"),
GenreFilter("Doujinshi"),
GenreFilter("Shounen Ai"),
GenreFilter("Shoujo"),
GenreFilter("Yuri"),
GenreFilter("Romance"),
GenreFilter("Fantasy"),
GenreFilter("Comedy"),
GenreFilter("Smut"),
GenreFilter("Adult"),
GenreFilter("School Life"),
GenreFilter("Mystery"),
GenreFilter("One Shot"),
GenreFilter("Ecchi"),
GenreFilter("Shounen"),
GenreFilter("Martial Arts"),
GenreFilter("Shoujo Ai"),
GenreFilter("Supernatural"),
GenreFilter("Drama"),
GenreFilter("Action"),
GenreFilter("Adventure"),
GenreFilter("Harem"),
GenreFilter("Historical"),
GenreFilter("Horror"),
GenreFilter("Josei"),
GenreFilter("Mature"),
GenreFilter("Mecha"),
GenreFilter("Psychological"),
GenreFilter("Sci-fi"),
GenreFilter("Seinen"),
GenreFilter("Slice Of Life"),
GenreFilter("Sports"),
GenreFilter("Gender Bender"),
GenreFilter("Tragedy"),
GenreFilter("Bara"),
GenreFilter("Shotacon"),
GenreFilter("Webtoons")
))
private class GenreFilter(name: String) : Filter.TriState(name)
private class StatusFilter(name: String, val uriParam: String) : Filter.CheckBox(name, true), UriFilter {
override fun addToUri(uri: Uri.Builder) {
uri.appendQueryParameter(uriParam, if (state) "1" else "0")
}
}
private class SortFilter : UriSelectFilter("Sort", "sortby", arrayOf(
Pair("random", "Random"),
Pair("view", "Views"),
Pair("comment_count", "Comment Count"),
Pair("create_date", "Creation Date"),
Pair("update_date", "Update Date")
))
/**
* Class that creates a select filter. Each entry in the dropdown has a name and a display name.
* If an entry is selected it is appended as a query parameter onto the end of the URI.
* If `firstIsUnspecified` is set to true, if the first entry is selected, nothing will be appended on the the URI.
*/
//vals: <name, display>
private open class UriSelectFilter(displayName: String, val uriParam: String, val vals: Array<Pair<String, String>>,
val firstIsUnspecified: Boolean = true,
defaultValue: Int = 0) :
Filter.Select<String>(displayName, vals.map { it.second }.toTypedArray(), defaultValue), UriFilter {
override fun addToUri(uri: Uri.Builder) {
if (state != 0 || !firstIsUnspecified)
uri.appendQueryParameter(uriParam, vals[state].first)
}
}
/**
* Uri filter group
*/
private open class UriFilterGroup<V>(name: String, val stateList: List<V>) : Filter.Group<V>(name, stateList), UriFilter {
override fun addToUri(uri: Uri.Builder) {
stateList.forEach {
if (it is UriFilter)
it.addToUri(uri)
}
}
}
/**
* Represents a filter that is able to modify a URI.
*/
private interface UriFilter {
fun addToUri(uri: Uri.Builder)
}
private var libCryptoJS: String? = null
private fun getCryptoJSLib(): String {
if (libCryptoJS == null) {
libCryptoJS = client.newCall(GET("https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js", headers)).execute().body()!!.string()
}
return checkNotNull(libCryptoJS)
}
private var libCryptoJSZeroPadding: String? = null
private fun getCryptoJSZeroPaddingLib(): String {
if (libCryptoJSZeroPadding == null) {
libCryptoJSZeroPadding = client.newCall(GET("https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/pad-zeropadding-min.js", headers)).execute().body()!!.string()
}
return checkNotNull(libCryptoJSZeroPadding)
}
companion object {
// https://codepen.io/Th3-822/pen/BVVVGW/
private const val IMGSRCS_DECODE_JS = """
function replacePos(a, b, c) {
return (a.substr(0, b) + c) + a.substring((b + 1), a.length);
}
function dorder(a, b) {
for (j = (b.length - 1); j >= 0; j--) {
for (i = (a.length - 1); (i - b[j]) >= 0; i--) {
if ((i % 2) != 0) {
temp = a[i - b[j]];
a = replacePos(a, (i - b[j]), a[i]);
a = replacePos(a, i, temp);
}
}
}
return a;
}
function decrypt(a, b, c) {
return CryptoJS.AES.decrypt(a, b, {'iv': c, 'padding': CryptoJS.pad.ZeroPadding}).toString(CryptoJS.enc.Utf8);
}
(function() {
var aesKey = CryptoJS.enc.Hex.parse('e10adc3949ba59abbe56e057f20f883e');
var aesIV = CryptoJS.enc.Hex.parse('1234567890abcdef1234567890abcdef');
var decrypted = decrypt(imgsrcs, aesKey, aesIV);
var code = decrypted.charAt(19) + decrypted.charAt(23) + decrypted.charAt(31) + decrypted.charAt(39);
decrypted = decrypted.slice(0, 19) + decrypted.slice(20, 23) + decrypted.slice(24, 31) + decrypted.slice(32, 39) + decrypted.slice(40);
return dorder(decrypted, code);
})();
"""
private const val IMAGE_DESCRAMBLER_JS = """
(function() {
var _deskeys = [];
_deskeys["60a2b0ed56cd458c4633d04b1b76b7e9"] = "18a72a69a64a13a1a43a3aa42a23a66a26a19a51a54a78a34a17a31a35a15a58a29a61a48a73a74a44a52a60a24a63a20a32a7a45a53a75a55a62a59a41a76a68a2a36a21a10a38a33a71a40a67a22a4a50a80a65a27a37a47a70a14a28a16a6a56a30a57a5a11a79a9a77a46a39a25a49a8a12";
_deskeys["400df5e8817565e28b2e141c533ed7db"] = "61a74a10a45a3a37a72a22a57a39a25a56a52a29a70a60a67a41a63a55a27a28a43a18a5a9a8a40a17a48a44a79a38a47a32a73a4a6a13a34a33a49a2a42a50a76a54a36a35a14a58a7a69a46a16a30a21a11aa51a53a77a26a31a1a19a20a80a24a62a68a59a66a75a12a64a78a71a15a65a23";
_deskeys["84ba0d8098f405b14f4dbbcc04c93bac"] = "61a26a35a16a55a10a72a37a2a60a66a65a33a44a7a28a70a62a32a56a30a40a58a15a74a47aa36a78a75a11a6a77a67a39a23a9a31a64a59a13a24a80a14a38a45a21a63a19a51a17a34a50a46a5a29a73a8a57a69a48a68a49a71a41a12a52a18a79a76a54a42a22a4a1a3a53a20a25a43a27";
_deskeys["56665708741979f716e5bd64bf733c33"] = "23a7a41a48a57a27a69a36a76a62a40a75a26a2a51a6a10a65a43a24a1aa20a71a28a30a13a38a79a78a72a14a49a55a56a58a25a70a12a80a3a66a11a39a42a17a15a54a45a34a74a31a8a61a46a73a63a22a64a19a77a50a9a59a37a68a52a18a32a16a33a60a67a21a44a53a5a35a4a29a47";
_deskeys.a67e15ed870fe4aab0a502478a5c720f = "8a12a59a52a24a13a37a21a55a56a41a71a65a43a40a66a11a79a67a44a33a20a72a2a31a42a29a34a58a60a27a48a28a15a35a51a76a80a0a63a69a53a39a46a64a50a75a1a57a9a62a74a18a16a73a14a17a6a19a61a23a38a10a3a32a26a36a54a4a30a45a47a70a22a7a68a49a77a5a25a78";
_deskeys.b6a2f75185754b691e4dfe50f84db57c = "47a63a76a58a37a4a56a21a1a48a62a2a36a44a34a42a23a9a60a72a11a74a70a20a77a16a15a35a69a0a55a46a24a6a32a75a68a43a41a78a31a71a52a33a67a25a80a30a5a28a40a65a39a14a29a64a3a53a49a59a12a66a38a27a79a45a18a22a8a61a50a17a51a10a26a13a57a19a7a54a73";
_deskeys.db99689c5a26a09d126c7089aedc0d86 = "57a31a46a61a55a41a26a2a39a24a75a4a45a13a23a51a15a8a64a37a72a34a12a3a79a42a80a17a62a49a19a77a48a68a78a65a14a10a29a16a20a76a38a36a54a30a53a40a33a21a44a22a32a5a1a7a70a67a58a0a71a74a43a66a6a63a35a56a73a9a27a25a59a47a52a11a50a18a28a60a69";
_deskeys["37abcb7424ce8df47ccb1d2dd9144b49"] = "67a45a39a72a35a38a61a11a51a60a13a22a31a25a75a30a74a43a69a50a6a26a16a49a77a68a59a64a17a56a18a1a10a54a44a62a53a80a5a23a48a32a29a79a24a70a28a58a71a3a52a42a55a9a14a36a73a34a2a27a57a0a21a41a33a37a76a8a40a65a7a20a12a19a47a4a78a15a63a66a46";
_deskeys["874b83ba76a7e783d13abc2dabc08d76"] = "26a59a42a43a4a20a61a28a12a64a37a52a2a77a34a13a46a74a70a0a44a29a73a66a55a38a69a67a62a9a63a6a54a79a21a33a8a58a40a47a71a49a22a50a57a78a56a25a17a15a36a16a48a32a5a10a14a80a24a72a76a45a3a53a23a41a60a11a65a19a27a51a68a35a31a1a75a39a30a7a18";
_deskeys.d320d2647d70c068b89853e1a269c609 = "77a38a53a40a16a3a20a18a63a9a24a64a50a61a45a59a27a37a8a34a11a55a79a13a47a68a12a22a46a33a1a69a52a54a31a23a62a43a0a2a35a28a57a36a51a78a70a5a32a75a41a30a4a80a19a21a42a71a49a10a56a74a17a7a25a6a14a73a29a44a48a39a60a58a15a66a67a72a65a76a26";
_deskeys["930b87ad89c2e2501f90d0f0e92a6b97"] = "9a29a49a67a62a40a28a50a64a77a46a31a16a73a14a45a51a44a7a76a22a78a68a37a74a69a25a65a41a11a52aa18a36a10a38a12a15a2a58a48a8a27a75a20a4a80a61a55a42a13a43a47a39a35a60a26a30a63a66a57a33a72a24a71a34a23a3a70a54a56a32a79a5a21a6a59a53a17a1a19";
_deskeys.c587e77362502aaedad5b7cddfbe3a0d = "50aa59a70a68a30a56a10a49a43a45a29a23a28a61a15a40a71a14a44a32a34a17a26a63a76a75a33a74a12a11a21a67a31a19a80a7a64a8a3a51a53a38a18a6a42a27a9a52a20a41a60a1a22a77a16a54a47a79a24a78a2a46a37a73a65a36a35a39a5a4a25a72a13a62a55a57a58a69a66a48";
_deskeys["1269606c6c3d8bb6508426468216d6b1"] = "49a15a0a60a14a26a34a69a61a24a35a4a77a80a70a40a39a6a68a17a41a56a28a46a79a16a21a1a37a42a44a58a78a18a52a73a32a9a12a50a8a13a20a19a67a36a45a75a48a10a65a7a38a66a3a2a43a27a29a31a72a74a55a23a54a22a59a57a11a62a47a53a30a5a64a25a76a71a51a33a63";
_deskeys["33a3b21bb2d14a09d15f995224ae4284"] = "30a59a35a34a42a8a10a56a70a64a48a69a26a18a6a16a54a24a73a79a68a33a32a2a63a53a31a14a17a57a41a80a76a40a60a12a43a29a39a4a77a58a66a36a38a52a13a19a0a75a28a55a25a61a71a11a67a49a23a45a5a15a1a50a51a9a44a47a65a74a72a27a7a37a46a20a22a62a78a21a3";
_deskeys["9ae6640761b947e61624671ef841ee78"] = "62a25a21a75a42a61a73a59a23a19a66a38a71a70a6a55a3a16a43a32a53a37a41a28a49a63a47a17a7a30a78a46a20a67a56a79a65a14a69a60a8a52a22a9a24a2a4a13a36a27a0a18a33a12a44a5a76a26a29a40a1a11a64a48a39a51a80a72a68a10a58a35a77a54a34a74a57a31a50a45a15";
_deskeys.f4ab0903149b5d94baba796a5cf05938 = "40a37a55a73a18a42a15a59a50a13a22a63a52a58a6a80a47a17a38a71a74a70a30a11a10a19a0a31a36a21a51a68a1a3a14a66a45a2a79a7a76a75a8a67a20a78a25a69a43a28a35a60a4a23a65a54a34a9a5a39a27a57a26a33a12a24a46a72a56a44a49a61a64a29a53a48a32a62a41a16a77";
_deskeys.f5baf770212313f5e9532ec5e6103b61 = "55a69a78a75a38a25a20a60a6a80a46a5a48a18a23a24a17a67a64a70a63a57a22a10a49a19a8a16a11a12a61a76a34a27a54a73a44a0a56a3a15a29a28a13a4a2a7a77a74a35a37a26a30a58a9a71a50a1a43a79a47a32a14a53a52a66a72a59a68a31a42a45a62a51a40a39a33a65a41a36a21";
_deskeys.e2169a4bfd805e9aa21d3112d498d68c = "54a34a68a69a26a20a66a1a67a74a22a39a63a70a5a37a75a15a6a14a62a50a46a35a44a45a28a8a40a25a29a76a51a77a17a47a0a42a2a9a48a27a13a64a58a57a18a30a80a23a61a36a60a59a71a32a7a38a41a78a12a49a43a79a24a31a52a19a3a53a72a10a73a11a33a16a4a55a65a21a56";
_deskeys['1796550d20f64decb317f9b770ba0e78'] = '37a55a39a79a2a53a75a1a30a32a3a13a25a49a45a5a60a62a71a78a63a24a27a33a19a64a67a57a0a8a54a9a41a61a50a73a7a65a58a51a15a14a43a4a35a77a68a72a34a80a22a17a48a10a70a46a40a28a20a74a52a23a38a76a42a18a66a11a59a6a69a31a56a16a47a21a12a44a36a29a26';
_deskeys['bf53be6753a0037c6d80ca670f5d12d5'] = '55a41a18a19a4a13a36a12a56a69a64a80a30a39a57a50a48a26a46a73a17a52a49a66a11a25a61a51a68a24a70a7a67a53a43a8a29a75a65a42a38a58a9a28a0a78a54a31a22a5a15a3a79a77a59a23a45a40a47a44a6a2a1a35a14a62a63a76a20a16a32a21a71a10a74a60a34a37a33a72a27';
_deskeys['6c41ff7fbed622aa76e19f3564e5d52a'] = '40a3a13a59a68a34a66a43a67a14a26a46a8a24a33a73a69a31a2a57a10a51a62a77a74a41a47a35a64a52a15a53a6a80a76a50a28a75a56a79a17a45a25a49a48a65a78a27a9a63a12a55a32a21a58a38a0a71a44a30a61a36a16a23a20a70a22a37a4a19a7a60a11a5a18a39a1a54a72a29a42';
var l = "18a72a69a64a13a1a43a3aa42a23a66a26a19a51a54a78a34a17a31a35a15a58a29a61a48a73a74a44a52a60a24a63a20a32a7a45a53a75a55a62a59a41a76a68a2a36a21a10a38a33a71a40a67a22a4a50a80a65a27a37a47a70a14a28a16a6a56a30a57a5a11a79a9a77a46a39a25a49a8a12";
for (mk in _deskeys) {
if (img.indexOf(mk) > 0) {
l = _deskeys[mk];
break;
}
}
l = l.split("a");
var cols = heightnum = 9;
var w = width / cols;
var h = height / heightnum;
var r;
var y;
var x;
var py;
var canvasX;
var i = 0;
var result = "";
for (;i < cols * heightnum;i++) {
r = Math.floor(l[i] / heightnum);
y = r * h;
x = (l[i] - r * cols) * w;
r = Math.floor(i / cols);
py = r * h;
canvasX = (i - r * cols) * w;
result += " " + canvasX + "," + py + "," + w + "," + h + "," + x + "," + y;
}
return result;
})();
"""
// Allow destructuring up to 6 items for lists
private operator fun <T> List<T>.component6() = get(5)
}
}
|
apache-2.0
|
afe716ce0711c4b59044411203eaf5a2
| 48.675991 | 282 | 0.687814 | 2.824894 | false | false | false | false |
LorittaBot/Loritta
|
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/discord/ChannelInfoCommand.kt
|
1
|
2689
|
package net.perfectdreams.loritta.morenitta.commands.vanilla.discord
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.morenitta.utils.DateUtils
import net.dv8tion.jda.api.EmbedBuilder
import net.perfectdreams.loritta.common.commands.ArgumentType
import net.perfectdreams.loritta.common.commands.arguments
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordAbstractCommandBase
import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils
import net.perfectdreams.loritta.morenitta.utils.extensions.getGuildMessageChannelById
class ChannelInfoCommand(loritta: LorittaBot) : DiscordAbstractCommandBase(loritta, listOf("channelinfo", "channel"), net.perfectdreams.loritta.common.commands.CommandCategory.DISCORD) {
companion object {
private const val LOCALE_PREFIX = "commands.command"
}
override fun command() = create {
localizedDescription("$LOCALE_PREFIX.channelinfo.description")
arguments {
argument(ArgumentType.TEXT) {
optional = true
}
}
// TODO: Fix examples
/* examples {
listOf(
"",
"297732013006389252"
)
} */
canUseInPrivateChannel = false
executesDiscord {
OutdatedCommandUtils.sendOutdatedCommandMessage(this, locale, "server channel info")
val context = this
val channelId = args.getOrNull(0)
?.replace("<#", "")
?.replace(">", "")
?: context.discordMessage.channel.id
val channel = context.guild.getTextChannelById(channelId)!!
val builder = EmbedBuilder()
val channelTopic = if (channel.topic == null) {
"Tópico não definido!"
} else {
"```\n${channel.topic}```"
}
builder.setColor(Constants.DISCORD_BLURPLE)
builder.setTitle("\uD83D\uDC81 ${context.locale["$LOCALE_PREFIX.channelinfo.channelInfo", "#${channel.name}"]}")
builder.setDescription(channelTopic)
builder.addField("\uD83D\uDD39 ${context.locale["$LOCALE_PREFIX.channelinfo.channelMention"]}", "`${channel.asMention}`", true)
builder.addField("\uD83D\uDCBB ${context.locale["$LOCALE_PREFIX.userinfo.discordId"]}", "`${channel.id}`", true)
builder.addField("\uD83D\uDD1E NSFW", if (channel.isNSFW) context.locale["loritta.fancyBoolean.true"] else context.locale["loritta.fancyBoolean.false"], true)
builder.addField("\uD83D\uDCC5 ${context.locale["$LOCALE_PREFIX.channelinfo.channelCreated"]}", DateUtils.formatDateWithRelativeFromNowAndAbsoluteDifference(channel.timeCreated, context.locale), true)
builder.addField("\uD83D\uDD39 Guild", "`${channel.guild.name}`", true)
context.sendMessage(context.user.asMention, builder.build())
}
}
}
|
agpl-3.0
|
3aba5d4aeb17f771f34dc8a6a2e2381e
| 39.727273 | 203 | 0.756234 | 3.905523 | false | false | false | false |
LorittaBot/Loritta
|
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/social/xprank/XpRankExecutor.kt
|
1
|
6477
|
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.social.xprank
import dev.kord.common.entity.ButtonStyle
import dev.kord.common.entity.Snowflake
import dev.kord.core.entity.Guild
import dev.kord.rest.Image
import net.perfectdreams.discordinteraktions.common.builder.message.MessageBuilder
import net.perfectdreams.discordinteraktions.common.builder.message.actionRow
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
import net.perfectdreams.i18nhelper.core.I18nContext
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.InteractionContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.GuildApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.styled
import net.perfectdreams.loritta.cinnamon.discord.interactions.components.interactiveButtonWithHybridData
import net.perfectdreams.loritta.cinnamon.discord.interactions.components.loriEmoji
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.declarations.SonhosCommand
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.social.declarations.XpCommand
import net.perfectdreams.loritta.cinnamon.discord.utils.*
import net.perfectdreams.loritta.cinnamon.discord.utils.images.ImageFormatType
import net.perfectdreams.loritta.cinnamon.discord.utils.images.ImageUtils.toByteArray
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.cinnamon.pudding.tables.servers.GuildProfiles
import org.jetbrains.exposed.sql.SortOrder
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.update
import kotlin.math.ceil
class XpRankExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) {
inner class Options : LocalizedApplicationCommandOptions(loritta) {
val page = optionalInteger("page", XpCommand.XP_RANK_I18N_PREFIX.Options.Page.Text) {
range = RankingGenerator.VALID_RANKING_PAGES
}
}
companion object {
suspend fun createMessage(
loritta: LorittaBot,
context: InteractionContext,
guild: Guild,
page: Long
): suspend MessageBuilder.() -> (Unit) = {
styled(
context.i18nContext.get(SonhosCommand.TRANSACTIONS_I18N_PREFIX.Page(page + 1)),
Emotes.LoriReading
)
val (totalCount, profiles) = loritta.pudding.transaction {
val totalCount = GuildProfiles.select {
(GuildProfiles.guildId eq guild.id.toLong()) and
(GuildProfiles.isInGuild eq true)
}.count()
val profilesInTheQuery = GuildProfiles.select {
(GuildProfiles.guildId eq guild.id.toLong()) and
(GuildProfiles.isInGuild eq true)
}
.orderBy(GuildProfiles.xp to SortOrder.DESC)
.limit(5, page * 5)
.toList()
Pair(totalCount, profilesInTheQuery)
}
// Calculates the max page
val maxPage = ceil(totalCount / 5.0)
val maxPageZeroIndexed = maxPage - 1
addFile(
"rank.png",
RankingGenerator.generateRanking(
loritta,
page * 5,
guild.name,
guild.getIconUrl(Image.Format.PNG),
profiles.map {
val xp = it[GuildProfiles.xp]
val level = ExperienceUtils.getCurrentLevelForXp(xp)
RankingGenerator.UserRankInformation(
Snowflake(it[GuildProfiles.userId]),
context.i18nContext.get(XpCommand.XP_RANK_I18N_PREFIX.TotalXp(xp)),
context.i18nContext.get(XpCommand.XP_RANK_I18N_PREFIX.Level(level))
)
}
) {
loritta.pudding.transaction {
GuildProfiles.update({ GuildProfiles.id eq it.toLong() and (GuildProfiles.guildId eq guild.id.toLong()) }) {
it[isInGuild] = false
}
}
null
}.toByteArray(ImageFormatType.PNG).inputStream()
)
actionRow {
// The "page" variable is zero indexed, that's why in the "disabled" section the checks seems... "wonky"
// The "VALID_RANKING_PAGES" is not zero indexed!
interactiveButtonWithHybridData(
loritta,
ButtonStyle.Primary,
ChangeXpRankPageButtonExecutor,
ChangeXpRankPageData(context.user.id, page - 1)
) {
loriEmoji = Emotes.ChevronLeft
disabled = page !in RankingGenerator.VALID_RANKING_PAGES
}
interactiveButtonWithHybridData(
loritta,
ButtonStyle.Primary,
ChangeXpRankPageButtonExecutor,
ChangeXpRankPageData(context.user.id, page + 1)
) {
loriEmoji = Emotes.ChevronRight
disabled = page + 2 !in RankingGenerator.VALID_RANKING_PAGES || page >= maxPageZeroIndexed
}
}
}
}
override val options = Options()
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
if (context !is GuildApplicationCommandContext)
return
context.deferChannelMessage()
val guild = loritta.kord.getGuild(context.guildId)!!
val userPage = args[options.page] ?: 1L
val page = userPage - 1
val message = createMessage(loritta, context, guild, page)
context.sendMessage {
message()
}
}
}
|
agpl-3.0
|
bd6a819e397672c4244a667fbf02f027
| 43.668966 | 132 | 0.636097 | 5.112076 | false | false | false | false |
luiqn2007/miaowo
|
app/src/main/java/org/miaowo/miaowo/base/ListHolder.kt
|
1
|
2081
|
package org.miaowo.miaowo.base
import android.content.Context
import android.support.annotation.IdRes
import android.support.annotation.LayoutRes
import android.support.v7.widget.RecyclerView
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import org.miaowo.miaowo.App
import org.miaowo.miaowo.R
/**
* 带 ViewBinding 的 ViewHolder
* Created by luqin on 18-2-17.
*/
@Suppress("unused")
open class ListHolder(view: View, private val bundleMap: MutableMap<String, Any?>)
: RecyclerView.ViewHolder(view), MutableMap<String, Any?> by bundleMap {
private val mCacheViews = SparseArray<View?>()
constructor(view: View) : this(view, mutableMapOf())
constructor(@LayoutRes viewId: Int, parent: ViewGroup, context: Context = App.i, attach: Boolean = false) : this(
LayoutInflater.from(context).inflate(viewId, parent, attach)
)
fun find(@IdRes id: Int): View? {
if (mCacheViews[id] == null)
mCacheViews.put(id, itemView.findViewById(id))
return mCacheViews[id]
}
inline fun <reified T> find(@IdRes id: Int) = (find(id) as? T)
operator fun get(@IdRes id: Int) = find(id)
/**
* 使用反射,获取 id 名称对应的 View
*
* 例:
* R.id.text => text
* android:R.id.text => android:text
*/
fun find(idName: String): View? {
return try {
val isSystem = idName.startsWith("android:")
val rIdName =
if (!isSystem) idName
else idName.replaceFirst("android:", "")
val rClass =
if (!isSystem) R.id::class.java
else android.R.id::class.java
val field = rClass.getDeclaredField(rIdName)
if (field != null) {
field.isAccessible = true
val id = field.getInt(null)
this[id]
}
null
} catch (e: Exception) {
e.printStackTrace()
null
}
}
}
|
apache-2.0
|
dc516a2e912b53d81c781dde4cd64e8d
| 29.176471 | 117 | 0.60312 | 4.005859 | false | false | false | false |
sav007/apollo-android
|
apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/JavaTypeResolver.kt
|
1
|
2411
|
package com.apollographql.apollo.compiler
import com.apollographql.apollo.compiler.ClassNames.parameterizedGuavaOptional
import com.apollographql.apollo.compiler.ClassNames.parameterizedJavaOptional
import com.apollographql.apollo.compiler.ClassNames.parameterizedOptional
import com.apollographql.apollo.compiler.ir.CodeGenerationContext
import com.apollographql.apollo.compiler.ir.ScalarType
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.TypeName
class JavaTypeResolver(
private val context: CodeGenerationContext,
private val packageName: String,
private val deprecated: Boolean = false
) {
fun resolve(typeName: String, isOptional: Boolean = !typeName.endsWith("!"),
nullableValueType: NullableValueType? = null): TypeName {
val normalizedTypeName = typeName.removeSuffix("!")
val isList = normalizedTypeName.startsWith('[') && normalizedTypeName.endsWith(']')
val customScalarType = context.customTypeMap[normalizedTypeName]
val javaType = when {
isList -> ClassNames.parameterizedListOf(resolve(normalizedTypeName.removeSurrounding("[", "]"), false))
normalizedTypeName == ScalarType.STRING.name -> ClassNames.STRING
normalizedTypeName == ScalarType.INT.name -> if (isOptional) TypeName.INT.box() else TypeName.INT
normalizedTypeName == ScalarType.BOOLEAN.name -> if (isOptional) TypeName.BOOLEAN.box() else TypeName.BOOLEAN
normalizedTypeName == ScalarType.FLOAT.name -> if (isOptional) TypeName.DOUBLE.box() else TypeName.DOUBLE
customScalarType != null -> customScalarType.toJavaType()
else -> ClassName.get(packageName, normalizedTypeName)
}
return if (javaType.isPrimitive) {
javaType.let { if (deprecated) it.annotated(Annotations.DEPRECATED) else it }
} else if (isOptional) {
when (nullableValueType ?: context.nullableValueType) {
NullableValueType.APOLLO_OPTIONAL -> parameterizedOptional(javaType)
NullableValueType.GUAVA_OPTIONAL -> parameterizedGuavaOptional(javaType)
NullableValueType.JAVA_OPTIONAL -> parameterizedJavaOptional(javaType)
else -> javaType.annotated(Annotations.NULLABLE)
}.let {
if (deprecated) it.annotated(Annotations.DEPRECATED) else it
}
} else {
javaType.annotated(Annotations.NONNULL).let {
if (deprecated) it.annotated(Annotations.DEPRECATED) else it
}
}
}
}
|
mit
|
98db32d8691ff5ba2d9bbe361d715dd1
| 49.25 | 115 | 0.75197 | 4.78373 | false | false | false | false |
jvbreen1/task-track
|
app/src/main/java/com/johnvbreen/tasktrack/MainActivity.kt
|
1
|
5045
|
package com.johnvbreen.tasktrack
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.ContextMenu
import android.view.ContextMenu.ContextMenuInfo
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.AdapterContextMenuInfo
import android.widget.ListView
class MainActivity : AppCompatActivity() {
companion object {
val TASK_GOAL = "taskGoal"
val TASK_TIME_SPENT = "taskTimeSpent"
val TASK_DESC = "taskDesc"
val TASK_NAME = "taskName"
val NEW_TASK_REQUEST = 0
val ADD_HOURS_REQUEST = 1
val EDIT_TASK_REQUEST = 2
}
private val dbHelper: TaskTrackDbHelper = TaskTrackDbHelper(this)
private var tasks: List<Task>? = null
private var currentTask: Task? = null
private var listView: ListView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
listView = findViewById(R.id.task_list) as ListView?
registerForContextMenu(listView)
resetTaskView()
listView!!.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
currentTask = listView!!.adapter.getItem(position) as Task
val intent = Intent(this@MainActivity, AddHoursActivity::class.java)
startActivityForResult(intent, ADD_HOURS_REQUEST)
}
findViewById(R.id.add_task_button)!!.setOnClickListener { newTask() }
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
private fun newTask() {
val intent = Intent(this, NewTaskActivity::class.java)
startActivityForResult(intent, NEW_TASK_REQUEST)
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent) {
if (requestCode == NEW_TASK_REQUEST) {
} else if (requestCode == ADD_HOURS_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
if(currentTask != null) {
val hoursLogged = intent.getIntExtra(
AddHoursActivity.HOURS_LOGGED, 0)
val entryDescription = intent
.getStringExtra(AddHoursActivity.ENTRY_DESCRIPTION)
currentTask!!.addHours(hoursLogged)
dbHelper.updateTask(currentTask!!)
dbHelper.addEntry(Entry(currentTask!!.id,
entryDescription, hoursLogged, System
.currentTimeMillis(), System
.currentTimeMillis()))
}
}
} else if (requestCode == EDIT_TASK_REQUEST) {
if(currentTask != null) {
val name = intent.getStringExtra(TASK_NAME)
val description = intent.getStringExtra(TASK_DESC)
val timeSpent = intent.getIntExtra(TASK_TIME_SPENT, 0)
val goal = intent.getIntExtra(TASK_GOAL, 0)
currentTask!!.name = name
currentTask!!.description = description
currentTask!!.timeSpent = timeSpent
currentTask!!.goal = goal
dbHelper.updateTask(currentTask!!)
}
}
resetTaskView()
}
override fun onCreateContextMenu(menu: ContextMenu, v: View,
menuInfo: ContextMenuInfo) {
super.onCreateContextMenu(menu, v, menuInfo)
// Get the info on which item was selected
val info = menuInfo as AdapterContextMenuInfo
currentTask = listView!!.adapter.getItem(info.position) as Task
val inflater = menuInflater
inflater.inflate(R.menu.edit_item, menu)
}
override fun onContextItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.modify_item -> {
val intent = Intent(this, EditTaskActivity::class.java)
intent.putExtra(TASK_NAME, currentTask!!.name)
intent.putExtra(TASK_DESC, currentTask!!.description)
intent.putExtra(TASK_TIME_SPENT, currentTask!!.timeSpent)
intent.putExtra(TASK_GOAL, currentTask!!.goal)
startActivityForResult(intent, EDIT_TASK_REQUEST)
}
R.id.delete_item -> dbHelper.deleteTask(this.currentTask!!)
else -> Log.d("onContextItemSelected", "What Just Happened??")
}
resetTaskView()
return true
}
private fun resetTaskView() {
tasks = dbHelper.allTasks
val adapter = TaskAdapter(this, R.layout.listview_item_row,
tasks!!)
listView!!.adapter = adapter
}
}
|
gpl-2.0
|
838423c0d898999cc1a7af69f505e1b1
| 35.035714 | 95 | 0.615461 | 4.926758 | false | false | false | false |
kotlintest/kotlintest
|
kotest-assertions/src/commonMain/kotlin/io/kotest/matchers/ints/int.kt
|
1
|
2321
|
package io.kotest.matchers.ints
import io.kotest.matchers.comparables.gt
import io.kotest.matchers.comparables.gte
import io.kotest.matchers.comparables.lt
import io.kotest.matchers.comparables.lte
import io.kotest.matchers.Matcher
import io.kotest.matchers.MatcherResult
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNot
import io.kotest.matchers.shouldNotBe
fun Int.shouldBePositive() = this shouldBe positive()
fun positive() = object : Matcher<Int> {
override fun test(value: Int) = MatcherResult(value > 0, "$value should be > 0", "$value should not be > 0")
}
fun Int.shouldBeNegative() = this shouldBe negative()
fun negative() = object : Matcher<Int> {
override fun test(value: Int) = MatcherResult(value < 0, "$value should be < 0", "$value should not be < 0")
}
fun Int.shouldBeEven() = this should beEven()
fun Int.shouldNotBeEven() = this shouldNot beEven()
fun beEven() = object : Matcher<Int> {
override fun test(value: Int): MatcherResult =
MatcherResult(value % 2 == 0, "$value should be even", "$value should be odd")
}
fun Int.shouldBeOdd() = this should beOdd()
fun Int.shouldNotBeOdd() = this shouldNot beOdd()
fun beOdd() = object : Matcher<Int> {
override fun test(value: Int): MatcherResult =
MatcherResult(value % 2 == 1, "$value should be odd", "$value should be even")
}
fun Int.shouldBeBetween(a: Int, b: Int) = this shouldBe between(a, b)
fun Int.shouldNotBeBetween(a: Int, b: Int) = this shouldNot between(a, b)
infix fun Int.shouldBeLessThan(x: Int) = this shouldBe lt(x)
infix fun Int.shouldNotBeLessThan(x: Int) = this shouldNotBe lt(x)
infix fun Int.shouldBeLessThanOrEqual(x: Int) = this shouldBe lte(x)
infix fun Int.shouldNotBeLessThanOrEqual(x: Int) = this shouldNotBe lte(x)
infix fun Int.shouldBeGreaterThan(x: Int) = this shouldBe gt(x)
infix fun Int.shouldNotBeGreaterThan(x: Int) = this shouldNotBe gt(x)
infix fun Int.shouldBeGreaterThanOrEqual(x: Int) = this shouldBe gte(x)
infix fun Int.shouldNotBeGreaterThanOrEqual(x: Int) = this shouldNotBe gte(x)
infix fun Int.shouldBeExactly(x: Int) = this shouldBe exactly(x)
infix fun Int.shouldNotBeExactly(x: Int) = this shouldNotBe exactly(x)
fun Int.shouldBeZero() = this shouldBeExactly 0
fun Int.shouldNotBeZero() = this shouldNotBeExactly 0
|
apache-2.0
|
ca2aedbe9ef8b5f06e330e637a7e2139
| 39.719298 | 110 | 0.748815 | 3.666667 | false | true | false | false |
ngageoint/mage-android
|
mage/src/main/java/mil/nga/giat/mage/newsfeed/ObservationListAdapter.kt
|
1
|
13632
|
package mil.nga.giat.mage.newsfeed
import android.content.Context
import android.database.Cursor
import android.graphics.PorterDuff
import android.os.AsyncTask
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.google.android.gms.maps.model.LatLng
import com.j256.ormlite.android.AndroidDatabaseResults
import com.j256.ormlite.stmt.PreparedQuery
import mil.nga.giat.mage.R
import mil.nga.giat.mage.coordinate.CoordinateFormatter
import mil.nga.giat.mage.map.annotation.MapAnnotation
import mil.nga.giat.mage.observation.attachment.AttachmentGallery
import mil.nga.giat.mage.sdk.datastore.observation.*
import mil.nga.giat.mage.sdk.datastore.user.EventHelper
import mil.nga.giat.mage.sdk.datastore.user.User
import mil.nga.giat.mage.sdk.datastore.user.UserHelper
import mil.nga.giat.mage.sdk.exceptions.ObservationException
import mil.nga.giat.mage.sdk.exceptions.UserException
import mil.nga.giat.mage.utils.DateFormatFactory
import java.lang.ref.WeakReference
import java.sql.SQLException
import java.util.*
class ObservationListAdapter(
private val context: Context,
observationFeedState: ObservationFeedViewModel.ObservationFeedState,
private val attachmentGallery: AttachmentGallery,
private val observationActionListener: ObservationActionListener?
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
interface ObservationActionListener {
fun onObservationClick(observation: Observation)
fun onObservationDirections(observation: Observation)
fun onObservationLocation(observation: Observation)
}
private var cursor: Cursor = observationFeedState.cursor
private val query: PreparedQuery<Observation> = observationFeedState.query
private val filterText: String = observationFeedState.filterText
private var currentUser: User? = null
private inner class ObservationViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private val card: View = view.findViewById(R.id.card)
val markerView: ImageView = view.findViewById(R.id.observation_marker)
val primaryView: TextView = view.findViewById(R.id.primary)
val timeView: TextView = view.findViewById(R.id.time)
val secondaryView: TextView = view.findViewById(R.id.secondary)
val userView: TextView = view.findViewById(R.id.user)
val importantView: View = view.findViewById(R.id.important)
val importantOverline: TextView = view.findViewById(R.id.important_overline)
val importantDescription: TextView = view.findViewById(R.id.important_description)
val syncBadge: View = view.findViewById(R.id.sync_status)
val errorBadge: View = view.findViewById(R.id.error_status)
val attachmentLayout: LinearLayout = view.findViewById(R.id.image_gallery)
val locationView: TextView = view.findViewById(R.id.location)
val locationContainer: View = view.findViewById(R.id.location_container)
val favoriteButton: ImageView = view.findViewById(R.id.favorite_button)
val favoriteCount: TextView = view.findViewById(R.id.favorite_count)
val directionsButton: View = view.findViewById(R.id.directions_button)
var userTask: UserTask? = null
var primaryPropertyTask: PropertyTask? = null
var secondaryPropertyTask: PropertyTask? = null
fun bind(observation: Observation) {
card.setOnClickListener { observationActionListener?.onObservationClick(observation) }
}
}
private inner class FooterViewHolder(view: View) :
RecyclerView.ViewHolder(view) {
val footerText: TextView = view.findViewById(R.id.footer_text)
}
override fun getItemViewType(position: Int): Int {
return if (position == cursor.count) {
TYPE_FOOTER
} else {
TYPE_OBSERVATION
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (viewType == TYPE_OBSERVATION) {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.observation_list_item, parent, false)
ObservationViewHolder(itemView)
} else {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.feed_footer, parent, false)
FooterViewHolder(itemView)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is ObservationViewHolder -> bindObservation(holder, position)
else -> bindFooter(holder)
}
}
override fun getItemCount(): Int {
return cursor.count + 1
}
override fun onViewRecycled(holder: RecyclerView.ViewHolder) {
if (holder is ObservationViewHolder) {
if (holder.userTask != null) {
holder.userTask?.cancel(false)
}
if (holder.primaryPropertyTask != null) {
holder.primaryPropertyTask?.cancel(false)
}
if (holder.secondaryPropertyTask != null) {
holder.secondaryPropertyTask?.cancel(false)
}
}
}
private fun bindObservation(holder: RecyclerView.ViewHolder, position: Int) {
cursor.moveToPosition(position)
val vh = holder as ObservationViewHolder
try {
val observation = query.mapRow(AndroidDatabaseResults(cursor, null, false))
vh.bind(observation)
val markerPlaceholder = DrawableCompat.wrap(ContextCompat.getDrawable(context, R.drawable.ic_place_white_48dp)!!)
DrawableCompat.setTint(markerPlaceholder, ContextCompat.getColor(context, R.color.icon))
DrawableCompat.setTintMode(markerPlaceholder, PorterDuff.Mode.SRC_IN)
vh.markerView.setImageDrawable(markerPlaceholder)
Glide.with(context)
.asBitmap()
.load(MapAnnotation.fromObservation(observation, context))
.error(R.drawable.default_marker)
.into(vh.markerView)
vh.primaryView.text = ""
vh.primaryPropertyTask = PropertyTask(context, PropertyTask.Type.PRIMARY, vh.primaryView)
vh.primaryPropertyTask?.execute(observation)
vh.secondaryView.text = ""
vh.secondaryPropertyTask = PropertyTask(context, PropertyTask.Type.SECONDARY, vh.secondaryView)
vh.secondaryPropertyTask?.execute(observation)
vh.userView.text = ""
vh.userTask = UserTask(vh.userView)
vh.userTask?.execute(observation)
val timestamp = observation.timestamp
val dateFormat = DateFormatFactory.format("yyyy-MM-dd HH:mm zz", Locale.getDefault(), context)
vh.timeView.text = dateFormat.format(timestamp)
setImportantView(observation.important, vh)
val error = observation.error
if (error != null) {
vh.errorBadge.visibility = if (error.statusCode != null) View.VISIBLE else View.GONE
} else {
vh.syncBadge.visibility = if (observation.isDirty) View.VISIBLE else View.GONE
vh.errorBadge.visibility = View.GONE
}
vh.attachmentLayout.removeAllViews()
if (observation.attachments.isEmpty()) {
vh.attachmentLayout.visibility = View.GONE
} else {
vh.attachmentLayout.visibility = View.VISIBLE
attachmentGallery.addAttachments(vh.attachmentLayout, observation.attachments)
}
val centroid = observation.geometry.centroid
val coordinates = CoordinateFormatter(context).format(LatLng(centroid.y, centroid.x))
vh.locationView.text = coordinates
vh.locationContainer.setOnClickListener { onLocationClick(observation) }
vh.favoriteButton.setOnClickListener { toggleFavorite(observation, vh) }
setFavoriteImage(observation.favorites, vh, isFavorite(observation))
vh.directionsButton.setOnClickListener { getDirections(observation) }
} catch (e: SQLException) {
e.printStackTrace()
}
}
private fun bindFooter(holder: RecyclerView.ViewHolder) {
val vh = holder as FooterViewHolder
var footerText = "End of results"
if (filterText.isNotEmpty()) {
footerText = "End of results for $filterText"
}
vh.footerText.text = footerText
}
private fun setImportantView(important: ObservationImportant?, vh: ObservationViewHolder) {
val isImportant = important != null && important.isImportant
vh.importantView.visibility = if (isImportant) View.VISIBLE else View.GONE
if (isImportant) {
try {
val user = UserHelper.getInstance(context).read(important!!.userId)
vh.importantOverline.text = String.format("FLAGGED BY %s", user.displayName.uppercase(Locale.getDefault()))
} catch (e: UserException) {
e.printStackTrace()
}
vh.importantDescription.text = important!!.description
}
}
private fun setFavoriteImage(favorites: Collection<ObservationFavorite>, vh: ObservationViewHolder, isFavorite: Boolean) {
if (isFavorite) {
vh.favoriteButton.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_favorite_white_24dp))
vh.favoriteButton.setColorFilter(ContextCompat.getColor(context, R.color.observation_favorite_active))
} else {
vh.favoriteButton.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_favorite_border_white_24dp))
vh.favoriteButton.setColorFilter(ContextCompat.getColor(context, R.color.observation_favorite_inactive))
}
vh.favoriteCount.visibility = if (favorites.isNotEmpty()) View.VISIBLE else View.GONE
vh.favoriteCount.text = String.format(Locale.getDefault(), "%d", favorites.size)
}
private fun toggleFavorite(observation: Observation, vh: ObservationViewHolder) {
val observationHelper = ObservationHelper.getInstance(context)
val isFavorite = isFavorite(observation)
try {
if (isFavorite) {
observationHelper.unfavoriteObservation(observation, currentUser)
} else {
observationHelper.favoriteObservation(observation, currentUser)
}
setFavoriteImage(observation.favorites, vh, isFavorite)
} catch (e: ObservationException) {
Log.e(LOG_NAME, "Could not unfavorite observation", e)
}
}
private fun isFavorite(observation: Observation): Boolean {
var isFavorite = false
try {
currentUser = UserHelper.getInstance(context).readCurrentUser()
if (currentUser != null) {
val favorite = observation.favoritesMap[currentUser!!.remoteId]
isFavorite = favorite != null && favorite.isFavorite
}
} catch (e: UserException) {
Log.e(LOG_NAME, "Could not get user", e)
}
return isFavorite
}
private fun getDirections(observation: Observation) {
observationActionListener?.onObservationDirections(observation)
}
private fun onLocationClick(observation: Observation) {
observationActionListener?.onObservationLocation(observation)
}
internal inner class UserTask(textView: TextView) : AsyncTask<Observation?, Void?, User?>() {
private val reference: WeakReference<TextView> = WeakReference(textView)
override fun doInBackground(vararg observations: Observation?): User? {
var user: User? = null
try {
user = UserHelper.getInstance(context).read(observations[0]?.userId)
} catch (e: UserException) {
Log.e(LOG_NAME, "Could not get user", e)
}
return user
}
override fun onPostExecute(u: User?) {
val user = if (isCancelled) null else u
val textView = reference.get()
if (textView != null) {
if (user != null) {
textView.text = user.displayName
} else {
textView.text = "Unknown User"
}
}
}
}
private class PropertyTask(private val context: Context, private val type: Type, textView: TextView) : AsyncTask<Observation?, Void?, ObservationProperty>() {
enum class Type { PRIMARY, SECONDARY }
private val reference: WeakReference<TextView> = WeakReference(textView)
override fun doInBackground(vararg observations: Observation?): ObservationProperty? {
val field = observations[0]?.forms?.firstOrNull()?.let { observationForm ->
val form = EventHelper.getInstance(context).getForm(observationForm.formId)
val fieldName = if (type == Type.PRIMARY) form.primaryFeedField else form.secondaryFeedField
observationForm.properties.find { it.key == fieldName }
}
return field
}
override fun onPostExecute(p: ObservationProperty?) {
val property = if (isCancelled) null else p
val textView = reference.get()
if (textView != null) {
if (property == null || property.isEmpty) {
textView.visibility = View.GONE
} else {
textView.text = property.value.toString()
textView.visibility = View.VISIBLE
}
textView.requestLayout()
}
}
}
companion object {
private val LOG_NAME = ObservationListAdapter::class.java.name
private const val TYPE_OBSERVATION = 1
private const val TYPE_FOOTER = 2
}
}
|
apache-2.0
|
4cd81e36008f44190076c18cf0c3176b
| 39.93994 | 161 | 0.693809 | 4.59454 | false | false | false | false |
sampsonjoliver/Firestarter
|
app/src/main/java/com/sampsonjoliver/firestarter/views/channel/ChannelMessageRecyclerAdapter.kt
|
1
|
6897
|
package com.sampsonjoliver.firestarter.views.channel
import android.os.Handler
import android.support.v4.view.ViewCompat
import android.support.v7.widget.RecyclerView
import android.text.format.DateUtils
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import com.sampsonjoliver.firestarter.R
import com.sampsonjoliver.firestarter.models.Message
import com.sampsonjoliver.firestarter.utils.appear
import com.sampsonjoliver.firestarter.utils.inflate
import com.sampsonjoliver.firestarter.utils.setBackgroundResourcePreservePadding
import kotlinx.android.synthetic.main.row_chat.view.*
import kotlinx.android.synthetic.main.row_chat_message.view.*
class ChannelMessageRecyclerAdapter(val currentUserId: String, val listener: ChatListener) : RecyclerView.Adapter<ChannelMessageRecyclerAdapter.ChatHolder>() {
interface ChatListener {
fun onItemInsertedListener()
fun onMessageLongPress(message: Message)
fun onMessageClick(message: Message)
}
companion object {
const val USER_CHAT_COLOUR = R.color.chat_selector_1
const val OTHER_CHAT_COLOUR = R.color.chat_selector_2
const val MESSAGE_GROUP_TIME_OFFSET_MS = 1000 * 60
const val MAX_BLOCK_SIZE = 10
}
data class MessageBlock(
val userId: String,
val userImageUrl: String,
var startTime: Long,
var endTime: Long,
val messages: MutableList<Message> = mutableListOf()
) {
constructor(message: Message) : this(message.userId, message.userImageUrl, message.getTimestampLong(), message.getTimestampLong(), mutableListOf(message))
fun pushMessage(message: Message): Boolean {
if (messages.isEmpty()) {
messages.add(message)
startTime = message.getTimestampLong()
endTime = message.getTimestampLong()
return true
} else if (messages.size < MAX_BLOCK_SIZE && message.userId == userId && message.getTimestampLong() <= endTime + MESSAGE_GROUP_TIME_OFFSET_MS && message.getTimestampLong() >= startTime) {
messages.add(message)
endTime = message.getTimestampLong()
return true
}
return false
}
}
val messages: MutableList<MessageBlock> = mutableListOf()
fun addMessage(message: Message) {
if (messages.isEmpty() || messages[0].pushMessage(message).not()) {
messages.add(0, MessageBlock(message))
notifyItemInserted(0)
listener.onItemInsertedListener()
} else {
notifyItemChanged(0)
listener.onItemInsertedListener()
}
}
override fun getItemCount(): Int = messages.size
override fun onBindViewHolder(holder: ChatHolder?, position: Int) {
holder?.bind(messages[position],
isCurrentUser = messages[position].userId == currentUserId,
alignRight = messages[position].userId == currentUserId, listener = listener)
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ChatHolder = ChatHolder(parent?.inflate(R.layout.row_chat, false))
class ChatHolder(itemview: View?) : RecyclerView.ViewHolder(itemview) {
val MESSAGE_ID = 0
val UPDATE_INTERVAL_MS: Long = 1000 * 60
private val handler = object : Handler() {
fun start() {
removeMessages(MESSAGE_ID)
sendEmptyMessageDelayed(MESSAGE_ID, UPDATE_INTERVAL_MS)
}
override fun handleMessage(msg: android.os.Message?) {
[email protected] = DateUtils.getRelativeDateTimeString(itemView.context, messageGroup?.startTime ?: 0,
DateUtils.MINUTE_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_ABBREV_ALL)
removeMessages(MESSAGE_ID)
this.sendEmptyMessageDelayed(MESSAGE_ID, UPDATE_INTERVAL_MS)
}
}
var messageGroup: MessageBlock? = null
fun bind(messageGroup: MessageBlock, isCurrentUser: Boolean, alignRight: Boolean, listener: ChatListener) {
this.messageGroup = messageGroup
handler.start()
itemView.image.setImageURI(messageGroup.userImageUrl)
itemView.time.text = DateUtils.getRelativeDateTimeString(itemView.context, messageGroup.startTime,
DateUtils.MINUTE_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_ABBREV_ALL)
(itemView as ViewGroup?)?.layoutDirection = if (alignRight) LinearLayout.LAYOUT_DIRECTION_RTL else LinearLayout.LAYOUT_DIRECTION_LTR
itemView.messageGroup.removeAllViews()
messageGroup.messages.forEachIndexed { i, it ->
itemView.messageGroup.addView(inflateMessageView(it, isCurrentUser, alignRight, i != 0, i != messageGroup.messages.size - 1, itemView.messageGroup, listener))
}
}
fun inflateMessageView(message: Message, isCurrentUser: Boolean, alignRight: Boolean, hasPrevious: Boolean, hasNext: Boolean, parent: ViewGroup, listener: ChatListener): View {
val messageView = parent.inflate(R.layout.row_chat_message, false)
messageView.message.appear = message.message.isNullOrBlank().not()
messageView.message.text = message.message
messageView.messageContentImage.appear = message.contentThumbUri.isNullOrBlank().not()
messageView.messageContentImage.messageContentImage.setImageURI(message.contentThumbUri)
messageView.setBackgroundResourcePreservePadding(
if (hasPrevious && hasNext && alignRight) R.drawable.chat_bubble_right
else if (hasPrevious && hasNext && !alignRight) R.drawable.chat_bubble_left
else if (hasPrevious && !hasNext && alignRight) R.drawable.chat_bubble_topright
else if (hasPrevious && !hasNext && !alignRight) R.drawable.chat_bubble_topleft
else if (!hasPrevious && hasNext && alignRight) R.drawable.chat_bubble_bottomright
else if (!hasPrevious && hasNext && !alignRight) R.drawable.chat_bubble_bottomleft
else R.drawable.chat_bubble_single
)
ViewCompat.setBackgroundTintList(messageView, messageView.resources.getColorStateList(
if (isCurrentUser) USER_CHAT_COLOUR else OTHER_CHAT_COLOUR))
messageView.setOnLongClickListener {
listener.onMessageLongPress(message)
true
}
messageView.setOnClickListener {
listener.onMessageClick(message)
}
return messageView
}
}
}
|
apache-2.0
|
3932b9690e3ed00ae5162b8853c7a4ad
| 44.986667 | 199 | 0.664492 | 4.898438 | false | false | false | false |
Magneticraft-Team/Magneticraft
|
src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/ModuleFilter.kt
|
2
|
1314
|
package com.cout970.magneticraft.systems.tilemodules
import com.cout970.magneticraft.api.internal.pneumatic.PneumaticBuffer
import com.cout970.magneticraft.api.pneumatic.PneumaticBox
import com.cout970.magneticraft.api.pneumatic.PneumaticMode
import com.cout970.magneticraft.misc.world.isClient
import com.cout970.magneticraft.systems.tileentities.IModule
import com.cout970.magneticraft.systems.tileentities.IModuleContainer
import net.minecraft.util.EnumFacing
class ModuleFilter(
val input: PneumaticBuffer,
val output: PneumaticBuffer,
val itemFilter: ModuleItemFilter,
override val name: String = "module_filter"
) : IModule {
override lateinit var container: IModuleContainer
override fun update() {
if (world.isClient || input.getItems().isEmpty()) return
while (input.getItems().isNotEmpty()) {
output.add(input.pop())
}
}
@Suppress("UNUSED_PARAMETER")
fun canInsert(buff: PneumaticBuffer, box: PneumaticBox, mode: PneumaticMode, side: EnumFacing): Boolean {
if (buff == input) {
return mode == PneumaticMode.TRAVELING && !output.blocked && itemFilter.filterAllowStack(box.item)
}
if (buff == output) {
return mode == PneumaticMode.GOING_BACK
}
return false
}
}
|
gpl-2.0
|
c287c9c0c35aaefb167a6f9d456fd36a
| 34.540541 | 110 | 0.715373 | 4.28013 | false | false | false | false |
yschimke/oksocial
|
src/main/kotlin/com/baulsupp/okurl/util/FileContent.kt
|
1
|
931
|
package com.baulsupp.okurl.util
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.withContext
import org.apache.commons.io.IOUtils
import java.io.File
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
object FileContent {
suspend fun readParamBytes(param: String): ByteArray = coroutineScope {
when {
param == "@-" -> IOUtils.toByteArray(System.`in`)
param.startsWith("@") -> withContext(Dispatchers.IO) {
File(param.substring(1)).readBytes()
}
else -> param.toByteArray(StandardCharsets.UTF_8)
}
}
suspend fun readParamString(param: String): String = coroutineScope {
when {
param == "@-" -> IOUtils.toString(System.`in`, Charset.defaultCharset())
param.startsWith("@") -> withContext(Dispatchers.IO) {
File(param.substring(1)).readText()
}
else -> param
}
}
}
|
apache-2.0
|
73e9254cf9d98c13e5f8b4542541f5cf
| 29.032258 | 78 | 0.690655 | 4.270642 | false | false | false | false |
yuzumone/PokePortal
|
app/src/main/kotlin/net/yuzumone/pokeportal/fragment/CreatePortalFragment.kt
|
1
|
6878
|
/*
* Copyright (C) 2016 yuzumone
*
* 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 net.yuzumone.pokeportal.fragment
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.widget.Toolbar
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.widget.EditText
import android.widget.Toast
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.CameraPosition
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import io.realm.Realm
import net.yuzumone.pokeportal.R
import net.yuzumone.pokeportal.data.Gym
import net.yuzumone.pokeportal.data.PokeStop
import net.yuzumone.pokeportal.listener.OnCreatePortal
import java.util.*
class CreatePortalFragment : DialogFragment(), OnMapReadyCallback {
private lateinit var listener: OnCreatePortal
private lateinit var toolbar: Toolbar
private lateinit var editText: EditText
private lateinit var portalLocation: LatLng
/*
* true: PokeStop
* false: Gym
*/
private var portalType: Boolean = true
companion object {
val ARG_LOCATION = "location"
val ARG_TYPE = "bool"
fun newPokeStopInstance(location: LatLng): CreatePortalFragment {
val fragment = CreatePortalFragment()
val args = Bundle()
args.putParcelable(ARG_LOCATION, location)
args.putBoolean(ARG_TYPE, true)
fragment.arguments = args
return fragment
}
fun newGymInstance(location: LatLng): CreatePortalFragment {
val fragment = CreatePortalFragment()
val args = Bundle()
args.putParcelable(ARG_LOCATION, location)
args.putBoolean(ARG_TYPE, false)
fragment.arguments = args
return fragment
}
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context !is OnCreatePortal) {
throw ClassCastException("Don't implement Listener.")
}
listener = context
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
portalLocation = arguments.getParcelable(ARG_LOCATION)
portalType = arguments.getBoolean(ARG_TYPE)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = Dialog(activity)
dialog.window.requestFeature(Window.FEATURE_NO_TITLE)
dialog.setContentView(R.layout.fragment_create_portal)
dialog.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
dialog.window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT)
toolbar = dialog.findViewById(R.id.toolbar)
editText = dialog.findViewById(R.id.edit_name)
return dialog
}
override fun onMapReady(googleMap: GoogleMap?) {
googleMap?.let { map ->
map.addMarker(MarkerOptions().position(portalLocation).draggable(true))
val cameraPosition = CameraPosition
.builder()
.target(portalLocation)
.zoom(15f)
.build()
map.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
map.setOnMarkerDragListener(object : GoogleMap.OnMarkerDragListener {
override fun onMarkerDragEnd(marker: Marker?) {
marker?.let { marker ->
portalLocation = marker.position
}
}
override fun onMarkerDrag(marker: Marker?) {
}
override fun onMarkerDragStart(marker: Marker?) {
}
})
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val mapFragment = fragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
toolbar.setNavigationIcon(R.drawable.ic_action_back)
toolbar.setNavigationOnClickListener { dismiss() }
toolbar.inflateMenu(R.menu.menu_create_portal)
toolbar.setOnMenuItemClickListener { item ->
when (item?.itemId) {
R.id.menu_save -> savePortal()
}
false
}
if (portalType) {
toolbar.title = "PokeStop"
editText.hint = "PokeStop Name"
} else {
toolbar.title = "Gym"
editText.hint = "Gym Name"
}
}
private fun savePortal() {
Realm.getDefaultInstance().use { realm ->
realm.executeTransaction {
if (portalType) {
val uuid = UUID.randomUUID().toString()
val pokeStop = realm.createObject(PokeStop::class.java, uuid)
pokeStop.name = editText.text.toString()
pokeStop.latitude = portalLocation.latitude
pokeStop.longitude = portalLocation.longitude
listener.createPokeStop(pokeStop)
Toast.makeText(activity, "Create ${pokeStop.name}", Toast.LENGTH_LONG).show()
} else {
val uuid = UUID.randomUUID().toString()
val gym = realm.createObject(Gym::class.java, uuid)
gym.name = editText.text.toString()
gym.latitude = portalLocation.latitude
gym.longitude = portalLocation.longitude
listener.createGym(gym)
Toast.makeText(activity, "Create ${gym.name}", Toast.LENGTH_LONG).show()
}
}
}
dismiss()
}
override fun onDestroyView() {
super.onDestroyView()
val fragment = fragmentManager.findFragmentById(R.id.map) as SupportMapFragment
fragmentManager.beginTransaction().remove(fragment).commit()
}
}
|
apache-2.0
|
b10545fff0fa7ac2f60918d42912de04
| 35.983871 | 97 | 0.640302 | 4.78636 | false | false | false | false |
mplatvoet/kovenant
|
projects/jvm/src/test/kotlin/performance/perf02.kt
|
1
|
4309
|
/*
* Copyright (c) 2015 Mark Platvoet<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* THE SOFTWARE.
*/
package performance.perf02
import nl.komponents.kovenant.*
import support.fib
import java.text.DecimalFormat
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
val numberOfWorkerThreads = Runtime.getRuntime().availableProcessors()
val executorService = Executors.newFixedThreadPool(numberOfWorkerThreads)
val attempts = 10
val warmupRounds = 100000
val performanceRounds = 1000000
val napTimeSeconds = 3L
val fibN = 13
val cbDispatch = buildDispatcher {
concurrentTasks = 1
pollStrategy {
yielding()
blocking()
}
}
val workDispatch = buildDispatcher {
pollStrategy {
yielding()
blocking()
}
}
fun main(args: Array<String>) {
println(
"""Performance test
- samples: $attempts
- warmupRounds: $warmupRounds
- timingRounds: $performanceRounds
- workers: $numberOfWorkerThreads
- sleep: $napTimeSeconds seconds
""")
Kovenant.context {
callbackContext.dispatcher = cbDispatch
workerContext.dispatcher = workDispatch
}
val factors = ArrayList<Double>(attempts)
for (i in 1..attempts) {
validateFutures(warmupRounds)
val startExc = System.currentTimeMillis()
validateFutures(performanceRounds)
val deltaExc = System.currentTimeMillis() - startExc
napTime()
validatePromises(warmupRounds)
val startDis = System.currentTimeMillis()
validatePromises(performanceRounds)
val deltaDis = System.currentTimeMillis() - startDis
val factor = deltaExc.toDouble() / deltaDis.toDouble()
factors.add(factor)
println("[$i/$attempts] Callables: ${deltaExc}ms, Promises: ${deltaDis}ms. " +
"Promises are a factor ${fasterOrSlower(factor)}")
napTime()
}
val averageFactor = factors.sum() / attempts.toDouble()
println("On average with $attempts attempts, " +
"Promises where a factor ${fasterOrSlower(averageFactor)}")
executorService.shutdownNow()
workDispatch.stop()
cbDispatch.stop()
}
private fun napTime() {
if (napTimeSeconds > 0) {
System.gc()
Thread.sleep(TimeUnit.MILLISECONDS.convert(napTimeSeconds, TimeUnit.SECONDS))
}
}
fun validatePromises(n: Int) {
val promises = Array(n) { _ ->
task {
Pair(fibN, fib(fibN))
}
}
await(*promises)
}
fun validateFutures(n: Int) {
val futures = Array(n) { _ ->
executorService.submit(Callable {
Pair(fibN, fib(fibN))
})
}
futures.forEach {
it.get()
}
}
private fun await(vararg promises: Promise<*, *>) {
val latch = CountDownLatch(promises.size)
promises.forEach {
p ->
p always { latch.countDown() }
}
latch.await()
}
private fun Double.format(pattern: String): String = DecimalFormat(pattern).format(this)
private fun fasterOrSlower(value: Double): String {
if (value == 0.0) {
return "<undetermined>"
}
if (value < 1.0) {
return "${(1.0 / value).format("##0.00")} slower"
}
return "${value.format("##0.00")} faster"
}
|
mit
|
17f2640d63ff68b5a53eb0e3de3794f2
| 27.169935 | 88 | 0.675795 | 4.262117 | false | false | false | false |
toastkidjp/Jitte
|
app/src/main/java/jp/toastkid/yobidashi/appwidget/search/RemoteViewsFactory.kt
|
1
|
2773
|
package jp.toastkid.yobidashi.appwidget.search
import android.content.Context
import android.widget.RemoteViews
import androidx.annotation.ColorInt
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.libs.intent.PendingIntentFactory
/**
* App Widget's RemoteViews factory.
*
* @author toastkidjp
*/
internal class RemoteViewsFactory {
/**
* Make RemoteViews.
*
* @param context
*
* @return RemoteViews
*/
fun make(context: Context): RemoteViews {
val remoteViews = RemoteViews(context.packageName, APPWIDGET_LAYOUT_ID)
setTapActions(context, remoteViews)
val preferenceApplier = PreferenceApplier(context)
setBackgroundColor(remoteViews, preferenceApplier.color)
setFontColor(remoteViews, preferenceApplier.fontColor)
return remoteViews
}
/**
* Set background color to remote views.
*
* @param remoteViews
* @param backgroundColor
*/
private fun setBackgroundColor(
remoteViews: RemoteViews,
@ColorInt backgroundColor: Int
) {
remoteViews.setInt(
R.id.widget_background, METHOD_NAME_SET_BACKGROUND_COLOR, backgroundColor)
}
/**
* Set font color to remote views.
*
* @param remoteViews
* @param fontColor
*/
private fun setFontColor(
remoteViews: RemoteViews,
@ColorInt fontColor: Int
) {
remoteViews.setInt(R.id.widget_search_border, METHOD_NAME_SET_BACKGROUND_COLOR, fontColor)
remoteViews.setInt(R.id.widget_search_image, METHOD_NAME_SET_COLOR_FILTER, fontColor)
remoteViews.setInt(R.id.widget_barcode_reader, METHOD_NAME_SET_COLOR_FILTER, fontColor)
remoteViews.setTextColor(R.id.widget_search_text, fontColor)
}
/**
* Set pending intents.
*
* @param context
* @param remoteViews
*/
private fun setTapActions(context: Context, remoteViews: RemoteViews) {
val pendingIntentFactory = PendingIntentFactory()
remoteViews.setOnClickPendingIntent(
R.id.widget_search, pendingIntentFactory.makeSearchLauncher(context))
remoteViews.setOnClickPendingIntent(
R.id.widget_barcode_reader, pendingIntentFactory.barcode(context))
}
companion object {
/**
* Method name.
*/
private const val METHOD_NAME_SET_COLOR_FILTER = "setColorFilter"
/**
* Method name.
*/
private const val METHOD_NAME_SET_BACKGROUND_COLOR = "setBackgroundColor"
/**
* Layout ID.
*/
private const val APPWIDGET_LAYOUT_ID = R.layout.appwidget_layout
}
}
|
epl-1.0
|
cf4da4657e4023439057c65ae25dc11e
| 26.465347 | 98 | 0.653083 | 4.756432 | false | false | false | false |
owncloud/android
|
owncloudApp/src/main/java/com/owncloud/android/presentation/ui/security/passcode/NumberKeyboard.kt
|
2
|
2751
|
/**
* ownCloud Android client application
*
* @author David Crespo Ríos
* Copyright (C) 2022 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.presentation.ui.security.passcode
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import com.owncloud.android.R
import java.util.*
/**
* Number keyboard to enter the passcode.
*/
class NumberKeyboard(context: Context, attrs: AttributeSet) : ConstraintLayout(context, attrs) {
private lateinit var numericKeys: MutableList<TextView>
private lateinit var backspaceBtn: ImageView
private var listener: NumberKeyboardListener? = null
init {
inflateView()
}
/**
* Sets keyboard listener.
*/
fun setListener(listener: NumberKeyboardListener?) {
this.listener = listener
}
/**
* Inflates layout.
*/
private fun inflateView() {
val view = View.inflate(context, R.layout.numberkeyboard_layout, this)
numericKeys = ArrayList(10)
numericKeys.add(view.findViewById(R.id.key0))
numericKeys.add(view.findViewById(R.id.key1))
numericKeys.add(view.findViewById(R.id.key2))
numericKeys.add(view.findViewById(R.id.key3))
numericKeys.add(view.findViewById(R.id.key4))
numericKeys.add(view.findViewById(R.id.key5))
numericKeys.add(view.findViewById(R.id.key6))
numericKeys.add(view.findViewById(R.id.key7))
numericKeys.add(view.findViewById(R.id.key8))
numericKeys.add(view.findViewById(R.id.key9))
backspaceBtn = view.findViewById(R.id.backspaceBtn)
// Set listeners
setupListeners()
}
/**
* Setup on click listeners.
*/
private fun setupListeners() {
for (i in numericKeys.indices) {
val key = numericKeys[i]
key.setOnClickListener {
listener?.onNumberClicked(i)
}
}
backspaceBtn.setOnClickListener {
listener?.onBackspaceButtonClicked()
}
}
}
|
gpl-2.0
|
5a87ddd60813357d6731d42570759803
| 29.21978 | 96 | 0.684364 | 4.160363 | false | false | false | false |
Kotlin/dokka
|
plugins/kotlin-as-java/src/test/kotlin/JvmOverloadsTest.kt
|
1
|
1871
|
package kotlinAsJavaPlugin
import org.jetbrains.dokka.base.testApi.testRunner.BaseAbstractTest
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class JvmOverloadsTest : BaseAbstractTest() {
private val configuration = dokkaConfiguration {
sourceSets {
sourceSet {
sourceRoots = listOf("src/")
classpath += jvmStdlibPath!!
}
}
}
@Test
fun `should generate multiple functions`() {
testInline(
"""
|/src/main/kotlin/kotlinAsJavaPlugin/sample.kt
|package kotlinAsJavaPlugin
|@JvmOverloads
|fun sample(a: Int = 0, b: String, c: Int = 0): String = ""
""".trimMargin(),
configuration,
) {
documentablesTransformationStage = { module ->
val functions = module.packages.flatMap { it.classlikes }.flatMap { it.functions }
assertEquals(3, functions.size)
assertEquals(3, functions[0].parameters.size)
assertEquals(2, functions[1].parameters.size)
assertEquals(1, functions[2].parameters.size)
}
}
}
@Test
fun `should do nothing if there is no default values`() {
testInline(
"""
|/src/main/kotlin/kotlinAsJavaPlugin/sample.kt
|package kotlinAsJavaPlugin
|@JvmOverloads
|fun sample(a: Int, b: String, c: Int): String = ""
""".trimMargin(),
configuration,
) {
documentablesTransformationStage = { module ->
val functions = module.packages.flatMap { it.classlikes }.flatMap { it.functions }
assertEquals(1, functions.size)
assertEquals(3, functions[0].parameters.size)
}
}
}
}
|
apache-2.0
|
8eae69a9c7c4906e7bfa91a2ed04a5cb
| 32.428571 | 98 | 0.559059 | 5.043127 | false | true | false | false |
google/ksp
|
test-utils/src/main/kotlin/com/google/devtools/ksp/processor/GetAnnotationByTypeProcessor.kt
|
1
|
1370
|
package com.google.devtools.ksp.processor
import com.google.devtools.ksp.KspExperimental
import com.google.devtools.ksp.getAnnotationsByType
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSClassDeclaration
annotation class KotlinAnnotationWithInnerDefaults(
val innerAnnotationVal: InnerAnnotation = InnerAnnotation(innerAnnotationDefault = 7)
) {
annotation class InnerAnnotation(
val innerAnnotationDefault: Int,
val moreInnerAnnotation: MoreInnerAnnotation = MoreInnerAnnotation("OK")
) {
annotation class MoreInnerAnnotation(val moreInnerAnnotationDefault: String)
}
}
class GetAnnotationByTypeProcessor : AbstractTestProcessor() {
val results = mutableListOf<String>()
private val annotationKClass = KotlinAnnotationWithInnerDefaults::class
override fun toResult(): List<String> {
return results
}
@OptIn(KspExperimental::class)
override fun process(resolver: Resolver): List<KSAnnotated> {
val decl = resolver.getAllFiles().single().declarations
.single { it.simpleName.asString() == "A" } as KSClassDeclaration
val anno = decl.getAnnotationsByType(annotationKClass).first()
results.add(anno.innerAnnotationVal.toString())
return emptyList()
}
}
|
apache-2.0
|
62f19a3f5277e9bfdf808a9dc3905084
| 37.055556 | 89 | 0.753285 | 4.79021 | false | false | false | false |
vsch/idea-multimarkdown
|
src/main/java/com/vladsch/md/nav/editor/resources/PrismHtmlCssProvider.kt
|
1
|
1008
|
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.editor.resources
import com.vladsch.md.nav.MdBundle
import com.vladsch.md.nav.MdPlugin
import com.vladsch.md.nav.editor.javafx.JavaFxHtmlPanelProvider
import com.vladsch.md.nav.editor.util.HtmlCssResource
import com.vladsch.md.nav.editor.util.HtmlCssResourceProvider
object PrismHtmlCssProvider : HtmlCssResourceProvider() {
val NAME = MdBundle.message("editor.prismjs.html.css.provider.name")
val ID = "com.vladsch.md.nav.editor.prismjs.html.css"
override val HAS_PARENT = true
override val INFO = Info(ID, NAME)
override val COMPATIBILITY = JavaFxHtmlPanelProvider.COMPATIBILITY
override val cssResource: HtmlCssResource = HtmlCssResource(INFO
, MdPlugin.PREVIEW_FX_PRISM_JS_STYLESHEET_DARK
, MdPlugin.PREVIEW_FX_PRISM_JS_STYLESHEET_LIGHT
, null)
}
|
apache-2.0
|
bd76f7f15c2664a49950b88858820394
| 44.818182 | 177 | 0.772817 | 3.665455 | false | false | false | false |
weibaohui/korm
|
src/main/kotlin/com/sdibt/korm/core/mapping/type/StringTypeHandler.kt
|
1
|
2070
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sdibt.korm.core.mapping.type
import java.sql.ResultSet
import java.sql.Types
class StringTypeHandler : TypeHandler {
override fun getValue(rs: ResultSet, index:Int): String? {
val type = rs.metaData.getColumnType(index)
when (type) {
Types.CHAR -> return rs.getString(index)
Types.VARCHAR -> return rs.getString(index)
Types.NVARCHAR -> return rs.getNString(index)
Types.LONGNVARCHAR, Types.CLOB -> {
val r = rs.getClob(index).characterStream
var sb = StringBuilder()
r.buffered().use {
sb.append(it.readText())
}
return sb.toString()
}
Types.NCLOB -> {
val r = rs.getNClob(index).characterStream
var sb = StringBuilder()
r.buffered().use {
sb.append(it.readText())
}
return sb.toString()
}
Types.NCHAR -> return rs.getNString(index)
else -> return rs.getString(index)
}
}
}
|
apache-2.0
|
6df772a6d7be8061c0410268e317acbe
| 34.689655 | 76 | 0.575845 | 4.630872 | false | false | false | false |
stoman/CompetitiveProgramming
|
problems/2021adventofcode22a/submissions/accepted/Stefan.kt
|
2
|
725
|
import java.util.*
@ExperimentalStdlibApi
fun main() {
val s = Scanner(System.`in`).useDelimiter("""\sx=|\.\.|,y=|,z=|\n""")
val status = mutableMapOf<Triple<Int, Int, Int>, Boolean>()
while (s.hasNext()) {
val newStatus = s.next() == "on"
val xMin = s.nextInt().coerceAtLeast(-50)
val xMax = s.nextInt().coerceAtMost(50)
val yMin = s.nextInt().coerceAtLeast(-50)
val yMax = s.nextInt().coerceAtMost(50)
val zMin = s.nextInt().coerceAtLeast(-50)
val zMax = s.nextInt().coerceAtMost(50)
for (x in xMin..xMax) {
for (y in yMin..yMax) {
for (z in zMin..zMax) {
status[Triple(x, y, z)] = newStatus
}
}
}
}
println(status.count { it.value })
}
|
mit
|
c7a186e9aa872779eb101b41f3db133c
| 28 | 71 | 0.58069 | 3.310502 | false | false | false | false |
victorrentea/training
|
kata/kata-parking-java/src/main/java/victor/kata/parking/Parking.kt
|
1
|
3440
|
package victor.kata.parking
import kotlin.math.abs
class Parking(
private val squareSize: Int,
private val pedestrianSlots: List<Int>,
private val disabledSlots: List<Int>
) {
private val parkedSlots = mutableMapOf<Int, Char>();
/**
* @return the number of available parking bays left
*/
fun getAvailableBays(): Int =
squareSize * squareSize - pedestrianSlots.size - parkedSlots.size
/**
* Park the car of the given type ('D' being dedicated to disabled people) in closest -to pedestrian exit- and first (starting from the parking's entrance)
* available bay. Disabled people can only park on dedicated bays.
*
*
* @param carType
* the car char representation that has to be parked
* @return bay index of the parked car, -1 if no applicable bay found
*/
fun parkCar(carType: Char): Int {
val bestIndex = findBestSlot(carType)
if (bestIndex < 0) {
return bestIndex
}
parkedSlots.put(bestIndex, carType)
return bestIndex
}
private fun findBestSlot(carType: Char): Int =
if (carType == 'D')
closestToPedestrian(disabledSlots)
else
closestToPedestrian(regularSlots())
private fun regularSlots() =
(0 until squareSize * squareSize)
.filterNot(disabledSlots::contains)
private fun closestToPedestrian(options: List<Int>) = options
.filterNot(pedestrianSlots::contains)
.filterNot(parkedSlots::contains)
.minByOrNull(this::distanceToClosestPedestrian)?:-1
private fun distanceToClosestPedestrian(index: Int): Int =
pedestrianSlots.map { abs(it - index) }.minOrNull()!!
/**
* Unpark the car from the given index
*
* @param index
* @return true if a car was parked in the bay, false otherwise
*/
fun unparkCar(index: Int): Boolean =
parkedSlots.remove(index) != null
/**
* Print a 2-dimensional representation of the parking with the following rules:
*
* * '=' is a pedestrian exit
* * '@' is a disabled-only empty bay
* * 'U' is a non-disabled empty bay
* * 'D' is a disabled-only occupied bay
* * the char representation of a parked vehicle for non-empty bays.
*
* U, D, @ and = can be considered as reserved chars.
*
* Once an end of lane is reached, then the next lane is reversed (to represent the fact that cars need to turn around)
*
* @return the string representation of the parking as a 2-dimensional square. Note that cars do a U turn to continue to the next lane.
*/
override fun toString(): String {
return __toString("") { index ->
if (parkedSlots.containsKey(index)) parkedSlots.get(index).toString()
else if (disabledSlots.contains(index)) "@"
else if (pedestrianSlots.contains(index)) "="
else "U"
}
}
fun indexToString(): String =
__toString(" ", Int::toString);
fun __toString(separator: String, f: (Int) -> String): String =
(0 until squareSize).joinToString("\n")
{ generateRow(it, f).joinToString(separator) }
private fun generateRow(row: Int, f: (Int) -> String): List<String> {
val result = (0 until squareSize).map { it + row * squareSize }.map(f)
return if (row % 2 == 0) result else result.reversed()
}
}
|
mit
|
b431de00a77ab09c8aefa0a793bd34c2
| 33.4 | 159 | 0.626163 | 4.032825 | false | false | false | false |
Aptoide/aptoide-client-v8
|
app/src/main/java/cm/aptoide/pt/download/view/DownloadViewStatusHelper.kt
|
1
|
4269
|
package cm.aptoide.pt.download.view
import android.content.Context
import android.view.View
import android.widget.Button
import cm.aptoide.aptoideviews.downloadprogressview.DownloadEventListener
import cm.aptoide.aptoideviews.downloadprogressview.DownloadProgressView
import cm.aptoide.pt.R
import rx.subjects.PublishSubject
/**
* Used to help updating a Download button + DownloadProgressView combo when using a [Download] model
*/
class DownloadViewStatusHelper(val context: Context) {
/**
* This is useful in case of RecyclerViews where event listeners + subjects must be used.
*/
fun setupListeners(download: Download, downloadClickSubject: PublishSubject<DownloadClick>,
installButton: Button,
downloadProgressView: DownloadProgressView) {
installButton.setOnClickListener {
downloadClickSubject.onNext(DownloadClick(download, DownloadEvent.INSTALL))
}
download.downloadModel?.let { downloadModel ->
if (downloadModel.downloadState == DownloadStatusModel.DownloadState.GENERIC_ERROR) {
downloadClickSubject.onNext(
DownloadClick(download, DownloadEvent.GENERIC_ERROR))
} else if (downloadModel.downloadState == DownloadStatusModel.DownloadState.NOT_ENOUGH_STORAGE_ERROR) {
downloadClickSubject.onNext(DownloadClick(download, DownloadEvent.OUT_OF_SPACE_ERROR))
}
}
downloadProgressView.setEventListener(object : DownloadEventListener {
override fun onActionClick(action: DownloadEventListener.Action) {
when (action.type) {
DownloadEventListener.Action.Type.CANCEL -> downloadClickSubject.onNext(
DownloadClick(download, DownloadEvent.CANCEL))
DownloadEventListener.Action.Type.RESUME -> downloadClickSubject.onNext(
DownloadClick(download, DownloadEvent.RESUME))
DownloadEventListener.Action.Type.PAUSE -> downloadClickSubject.onNext(
DownloadClick(download, DownloadEvent.PAUSE))
}
}
})
}
fun setDownloadStatus(download: Download, installButton: Button,
downloadProgressView: DownloadProgressView) {
download.downloadModel?.let { downloadModel ->
if (downloadModel.isDownloadingOrInstalling()) {
setDownloadState(downloadProgressView, downloadModel.progress, downloadModel.downloadState)
installButton.visibility = View.GONE
downloadProgressView.visibility = View.VISIBLE
} else {
setDownloadButtonText(downloadModel.action, installButton)
downloadProgressView.visibility = View.GONE
installButton.visibility = View.VISIBLE
}
}
}
private fun setDownloadButtonText(
action: DownloadStatusModel.Action,
installButton: Button) {
when (action) {
DownloadStatusModel.Action.UPDATE -> installButton.text =
context.getString(R.string.appview_button_update)
DownloadStatusModel.Action.INSTALL -> installButton.text =
context.getString(R.string.appview_button_install)
DownloadStatusModel.Action.OPEN -> installButton.text =
context.getString(R.string.appview_button_open)
DownloadStatusModel.Action.DOWNGRADE -> installButton.text =
context.getString(R.string.appview_button_downgrade)
DownloadStatusModel.Action.MIGRATE -> installButton.text =
context.getString(R.string.promo_update2appc_appview_update_button)
}
}
private fun setDownloadState(
downloadProgressView: DownloadProgressView,
progress: Int,
downloadState: DownloadStatusModel.DownloadState) {
when (downloadState) {
DownloadStatusModel.DownloadState.ACTIVE ->
downloadProgressView.startDownload()
DownloadStatusModel.DownloadState.INSTALLING ->
downloadProgressView.startInstallation()
DownloadStatusModel.DownloadState.PAUSE ->
downloadProgressView.pauseDownload()
DownloadStatusModel.DownloadState.IN_QUEUE,
DownloadStatusModel.DownloadState.STANDBY ->
downloadProgressView.reset()
DownloadStatusModel.DownloadState.GENERIC_ERROR,
DownloadStatusModel.DownloadState.NOT_ENOUGH_STORAGE_ERROR -> {
}
}
downloadProgressView.setProgress(progress)
}
}
|
gpl-3.0
|
504c849e07e06b17ff13b4dc1c5add4e
| 41.7 | 109 | 0.730382 | 5.112575 | false | false | false | false |
Aptoide/aptoide-client-v8
|
app/src/main/java/cm/aptoide/pt/notification/NotificationWorker.kt
|
1
|
1434
|
package cm.aptoide.pt.notification
import android.content.Context
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
import cm.aptoide.pt.crashreports.CrashReport
import cm.aptoide.pt.sync.Sync
import cm.aptoide.pt.sync.SyncScheduler
import cm.aptoide.pt.sync.alarm.AlarmSyncScheduler
import cm.aptoide.pt.sync.alarm.SyncStorage
class NotificationWorker(context: Context, workerParameters: WorkerParameters,
private val scheduler: SyncScheduler,
private val storage: SyncStorage,
private val crashReport: CrashReport) :
Worker(context, workerParameters) {
override fun doWork(): Result {
if (AlarmSyncScheduler.ACTION_SYNC == inputData.getString("action")) {
val syncId = inputData.getString("sync_id")
val sync: Sync = storage.get(syncId)
val reschedule: Boolean =
inputData.getBoolean(AlarmSyncScheduler.EXTRA_RESCHEDULE, false)
if (sync != null) {
sync.execute()
.doOnTerminate {
Log.d("CampaignWorker", "Got notification from $syncId")
if (reschedule) {
scheduler.reschedule(sync)
}
}
.subscribe({}
) { throwable: Throwable? -> crashReport.log(throwable) }
} else {
scheduler.cancel(syncId)
}
}
return Result.success()
}
}
|
gpl-3.0
|
4ef125463d04ccdf9c2679008c1a7d5d
| 31.613636 | 78 | 0.645049 | 4.596154 | false | false | false | false |
mehulsbhatt/emv-bertlv
|
src/main/java/io/github/binaryfoo/DecodedData.kt
|
1
|
9145
|
package io.github.binaryfoo
import java.util.Collections
import io.github.binaryfoo.hex.HexDumpElement
import io.github.binaryfoo.tlv.Tag
import org.apache.commons.lang.StringUtils
import org.apache.commons.lang.builder.EqualsBuilder
import org.apache.commons.lang.builder.HashCodeBuilder
import kotlin.platform.platformStatic
import java.util.ArrayList
import java.util.LinkedList
import io.github.binaryfoo.tlv.ISOUtil
import io.github.binaryfoo.tlv.BerTlv
import io.github.binaryfoo.decoders.annotator.BackgroundReading
/**
* A rather oddly named class that attempts to order a description of the bits (a decoding) into a hierarchy.
* Each instance represents a single level in the hierarchy. Leaf nodes have no children.
*
* Examples:
* <ul>
* <li>A TLV object with children</li>
* <li>A primitive value interpreted as a bit string, like TVR, where the children are the "on" bits.</li>
* </ul>
*/
public data class DecodedData(
val tag: Tag?,
val rawData: String, // Not a great name. Used as a label for the decoded data.
val fullDecodedData: String,
val startIndex: Int = 0, // in bytes
val endIndex: Int = 0, // in bytes
kids: List<DecodedData> = listOf(),
var backgroundReading: Map<String, String?>? = null, // wordy explanation. Eg to show in tooltip/popover,
val tlv: BerTlv? = null,
var category: String = ""
) {
public var hexDump: List<HexDumpElement>? = null
private val _children: MutableList<DecodedData> = ArrayList(kids)
public val children: List<DecodedData>
get() {
return _children
}
/**
* Position within the #hexDump of the bytes this decoding represents.
* For a decoding of a TLV this will include the T, L and V components. The whole kit and caboodle.
*/
public val positionInHexDump: Range<Int>
get() {
return startIndex..endIndex-1
}
/**
* Position within the #hexDump of the bytes comprising the T (tag) in the TLV this decoding represents.
* Null if this decoding didn't come from a TLV.
*/
public val tagPositionInHexDump: Range<Int>?
get() {
return if (tlv != null) startIndex..(startIndex + tlv.tag.bytes.size - 1) else null
}
/**
* Position within the #hexDump of the bytes comprising the L (length) in the TLV this decoding represents.
* Null if this decoding didn't come from a TLV.
*/
public val lengthPositionInHexDump: Range<Int>?
get() {
return if (tlv != null) {
val firstLengthByte = tagPositionInHexDump!!.end + 1
firstLengthByte..(firstLengthByte + tlv.lengthInBytesOfEncodedLength - 1)
} else {
null
}
}
private fun trim(decodedData: String): String {
return if (decodedData.length() >= 60) decodedData.substring(0, 56) + "..." + StringUtils.right(decodedData, 4) else decodedData
}
/**
* For an element with children this is usually the hex value (ie the real raw data).
* For an element without children this is the decoded value: ascii, numeric, enumerated or even just hex.
*/
public fun getDecodedData(): String {
return if (isComposite()) trim(fullDecodedData) else fullDecodedData
}
public fun getChild(index: Int): DecodedData {
return children.get(index)
}
public fun isComposite(): Boolean {
return !children.isEmpty()
}
/**
* For values that can't be decoded in the first pass. Like decrypted ones.
*/
public fun addChildren(child: List<DecodedData>) {
_children.addAll(child)
}
override fun toString(): String {
var s = "raw=[${rawData}] decoded=[${fullDecodedData}] indexes=[${startIndex},${endIndex}]"
if (backgroundReading != null) {
s += " background=[$backgroundReading]"
}
if (tag != null) {
s += " tag=$tag"
}
if (tlv != null) {
s += " tlv=$tlv"
}
if (isComposite()) {
for (d in children) {
s += "\n" + d
}
}
return s
}
class object {
platformStatic public fun primitive(rawData: String, decodedData: String, startIndex: Int = 0, endIndex: Int = 0): DecodedData {
return DecodedData(null, rawData, decodedData, startIndex, endIndex, backgroundReading = BackgroundReading.readingFor(rawData))
}
platformStatic public fun byteRange(rawData: String, bytes: ByteArray, startIndexWithinBytes: Int, length: Int, startIndexWithinFullDecoding: Int): DecodedData {
val decodedData = ISOUtil.hexString(bytes, startIndexWithinBytes, length)
return DecodedData(null, rawData, decodedData, startIndexWithinFullDecoding + startIndexWithinBytes, startIndexWithinFullDecoding + startIndexWithinBytes + length, listOf<DecodedData>())
}
platformStatic public fun byteRange(rawData: String, decodedData: String, startIndexWithinBytes: Int, length: Int, startIndexWithinFullDecoding: Int): DecodedData {
return DecodedData(null, rawData, decodedData, startIndexWithinFullDecoding + startIndexWithinBytes, startIndexWithinFullDecoding + startIndexWithinBytes + length, listOf<DecodedData>())
}
platformStatic public fun constructed(rawData: String, decodedData: String, startIndex: Int = 0, endIndex: Int = 0, children: List<DecodedData>): DecodedData {
return DecodedData(null, rawData, decodedData, startIndex, endIndex, children, BackgroundReading.readingFor(rawData))
}
/**
* Attach a Tag but the data wasn't actually encoded as TLV. Eg a bunch of values are concatenated in a stream.
*/
platformStatic public fun withTag(tag: Tag, metadata: TagMetaData, decodedData: String, startIndex: Int, endIndex: Int, children: List<DecodedData> = listOf()): DecodedData {
val tagInfo = metadata.get(tag)
return DecodedData(tag, tag.toString(tagInfo), decodedData, startIndex, endIndex, children, tagInfo.backgroundReading)
}
/**
* Decoded from a TLV.
*/
platformStatic public fun fromTlv(tlv: BerTlv, metadata: TagMetaData, decodedData: String, startIndex: Int, endIndex: Int, children: List<DecodedData> = listOf()): DecodedData {
val tag = tlv.tag
val tagInfo = metadata.get(tag)
return DecodedData(tag, tag.toString(tagInfo), decodedData, startIndex, endIndex, children, tagInfo.backgroundReading, tlv)
}
platformStatic public fun findForTag(tag: Tag, decoded: List<DecodedData>): DecodedData? {
val matches = decoded.findAllForTag(tag)
return if (matches.empty) null else matches[0]
}
platformStatic public fun findAllForTag(tag: Tag, decoded: List<DecodedData>): List<DecodedData> {
var matches = ArrayList<DecodedData>()
decoded.forEach {
if (it.tag == tag) {
matches.add(it)
}
matches.addAll(it.children.findAllForTag(tag))
}
return matches
}
platformStatic public fun findForValue(value: String, decoded: List<DecodedData>): DecodedData? {
val matches = decoded.findAllForValue(value)
return if (matches.empty) null else matches[0]
}
platformStatic public fun findAllForValue(value: String, decoded: List<DecodedData>): List<DecodedData> {
var matches = ArrayList<DecodedData>()
decoded.forEach {
if (it.fullDecodedData == value) {
matches.add(it)
}
matches.addAll(it.children.findAllForValue(value))
}
return matches
}
}
}
public fun List<DecodedData>.findForTag(tag: Tag): DecodedData? {
return DecodedData.findForTag(tag, this)
}
public fun List<DecodedData>.findTlvForTag(tag: Tag): BerTlv? {
return DecodedData.findAllForTag(tag, this).last?.tlv
}
public fun List<DecodedData>.findValueForTag(tag: Tag): String? {
return DecodedData.findAllForTag(tag, this).last?.tlv?.valueAsHexString
}
public fun List<DecodedData>.findAllForTag(tag: Tag): List<DecodedData> {
return DecodedData.findAllForTag(tag, this)
}
public fun List<DecodedData>.findForValue(value: String): DecodedData? {
return DecodedData.findForValue(value, this)
}
public fun List<DecodedData>.findAllForValue(value: String): List<DecodedData> {
return DecodedData.findAllForValue(value, this)
}
public fun List<DecodedData>.toSimpleString(indent: String = ""): String {
val b = StringBuilder()
for (d in this) {
b.append(indent)
val decodedData = d.getDecodedData()
if ("" != d.rawData) {
b.append(d.rawData).append(":")
if ("" != decodedData) {
b.append(" ")
}
}
b.append(decodedData).append("\n")
b.append(d.children.toSimpleString(indent + " "))
}
return b.toString()
}
|
mit
|
75288b9070a713e5a4494745bc998a09
| 38.081197 | 198 | 0.648442 | 4.422147 | false | false | false | false |
kgtkr/mhxx-switch-cis
|
src/main/kotlin/Main.kt
|
1
|
1035
|
package com.github.kgtkr.mhxxSwitchCIS
import javax.imageio.*
import java.io.*
import org.apache.commons.io.*
import java.awt.Color
import java.awt.image.BufferedImage
fun main(args: Array<String>) {
if(args.size==0){
analysisCmd()
}else if(args[0]=="t"||args[0]=="trimming"){
trimmingCmd()
}else if(args[0]=="c"||args[0]=="check"){
checkCmd()
}else if(args[0]=="p"||args[0]=="param"){
paramCmd()
}else if(args[0]=="d"||args[0]=="data"){
dataCmd()
}
}
fun readImages(dir:String):List<Rows>{
return File(dir)
.listFiles()
.sorted()
.map{file->ImageIO.read(file)}
.map{image->ImageTrimming.trimmingImage(image)}
.map{table->ImageTrimming.trimmingTable(table)}
.flatten()
.map{row->ImageTrimming.trimmingRow(row)}
}
data class Goseki(val goseki:String,
val skill1:Pair<String,Int>,
val skill2:Pair<String,Int>?,
val slot:Int)
|
gpl-3.0
|
96bb75cfcde5f672a1a570fe8021109b
| 24.9 | 59 | 0.56715 | 3.254717 | false | false | false | false |
matkoniecz/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/user/AchievementIconView.kt
|
1
|
2206
|
package de.westnordost.streetcomplete.user
import android.content.Context
import android.graphics.Outline
import android.graphics.Path
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewOutlineProvider
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.isInvisible
import de.westnordost.streetcomplete.databinding.ViewAchievementIconBinding
/** Shows an achievement icon with its frame and level indicator */
class AchievementIconView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
private val binding = ViewAchievementIconBinding.inflate(LayoutInflater.from(context), this)
var icon: Drawable?
set(value) { binding.iconView.setImageDrawable(value) }
get() = binding.iconView.drawable
var level: Int
set(value) {
binding.levelText.text = value.toString()
binding.levelText.isInvisible = value < 2
}
get() = binding.levelText.text.toString().toIntOrNull() ?: 0
init {
outlineProvider = AchievementFrameOutlineProvider
}
}
object AchievementFrameOutlineProvider : ViewOutlineProvider() {
private val points = arrayOf(
0.45,0.98,
0.47,0.99,
0.50,1.00,
0.53,0.99,
0.55,0.98,
0.98,0.55,
0.99,0.53,
1.00,0.50,
0.99,0.47,
0.98,0.45,
0.55,0.02,
0.53,0.01,
0.50,0.00,
0.47,0.01,
0.45,0.02,
0.02,0.45,
0.01,0.47,
0.00,0.50,
0.01,0.53,
0.02,0.55,
0.45,0.98
)
override fun getOutline(view: View, outline: Outline) {
val w = view.width
val h = view.height
if (w == 0 || h == 0) return
val p = Path()
p.moveTo((points[0] * w).toFloat(), (points[1] * h).toFloat())
for (i in 2 until points.size step 2) {
p.lineTo((points[i] * w).toFloat(), (points[i+1] * h).toFloat())
}
outline.setConvexPath(p)
}
}
|
gpl-3.0
|
7cdf86770ac3d35818d915d330c0cc8f
| 26.234568 | 96 | 0.623753 | 3.634267 | false | false | false | false |
tomatrocho/insapp-android
|
app/src/main/java/fr/insapp/insapp/utility/Utils.kt
|
2
|
4442
|
package fr.insapp.insapp.utility
import android.content.Context
import android.content.Intent
import android.text.SpannableString
import android.text.style.URLSpan
import android.widget.TextView
import android.widget.Toast
import androidx.preference.PreferenceManager
import com.google.gson.Gson
import fr.insapp.insapp.App
import fr.insapp.insapp.R
import fr.insapp.insapp.activities.IntroActivity
import fr.insapp.insapp.http.ServiceGenerator
import fr.insapp.insapp.models.User
import fr.insapp.insapp.notifications.MyFirebaseMessagingService
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*
object Utils {
val user: User?
get() {
return Gson().fromJson(App.getAppContext().getSharedPreferences("User", Context.MODE_PRIVATE).getString("user", ""), User::class.java)
}
fun clearAndDisconnect() {
val context = App.getAppContext()
if (user != null) {
val call = ServiceGenerator.client.logoutUser()
call.enqueue(object : Callback<Void> {
override fun onResponse(call: Call<Void>, response: Response<Void>) {
if (!response.isSuccessful) {
Toast.makeText(context, "Utils", Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Void>, t: Throwable) {
Toast.makeText(context, "Utils", Toast.LENGTH_LONG).show()
}
})
MyFirebaseMessagingService.subscribeToTopic("posts-android", false)
MyFirebaseMessagingService.subscribeToTopic("events-android", false)
if (user != null) {
context.getSharedPreferences("User", Context.MODE_PRIVATE).edit().clear().apply()
PreferenceManager.getDefaultSharedPreferences(context).edit().clear().apply()
}
}
val intent = Intent(context, IntroActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
context.startActivity(intent)
}
fun convertToLinkSpan(context: Context?, textView: TextView) {
val s = SpannableString(textView.text)
val spans = s.getSpans(0, s.length, URLSpan::class.java)
for (span in spans) {
val start = s.getSpanStart(span)
val end = s.getSpanEnd(span)
s.removeSpan(span)
s.setSpan(LinkSpan(context, span.url), start, end, 0)
}
textView.text = s
}
fun displayedDate(date: Date): String {
val atm = Calendar.getInstance().time
val diff = atm.time - date.time
val diffMinutes = diff / (60 * 1000) % 60
val diffHours = diff / (60 * 60 * 1000)
val diffInDays = (diff / (1000 * 60 * 60 * 24)).toInt()
val ago = App.getAppContext().getString(R.string.ago)
// at least 1 week
if (diffInDays >= 7) {
return ago + " " + (diffInDays / 7).toString() + " " + App.getAppContext().getString(R.string.ago_week)
}
// at least 1 day
if (diffInDays >= 1) {
return ago + " " + diffInDays.toLong().toString() + " " + App.getAppContext().getString(R.string.ago_day)
}
// at least 1 hour
if (diffHours >= 1) {
return ago + " " + diffHours.toString() + " " + App.getAppContext().getString(R.string.ago_hour)
}
// at least 1 minute
return if (diffMinutes >= 1) {
ago + " " + diffMinutes.toString() + " " + App.getAppContext().getString(R.string.ago_minute)
} else App.getAppContext().getString(R.string.ago_now)
// now
}
fun drawableProfileName(promo: String?, gender: String?): String {
var drawableString = "avatar"
if (promo != null && promo != "" && gender != null && gender != "") {
var userPromotion = promo.toLowerCase(Locale.FRANCE)
if (userPromotion.contains("staff")) {
userPromotion = "staff"
} else if (!userPromotion.contains("stpi") && Character.isDigit(userPromotion[0])) {
userPromotion = userPromotion.substring(1)
}
drawableString += "_$userPromotion"
drawableString += "_$gender"
} else {
drawableString = "avatar_default"
}
return drawableString
}
}
|
mit
|
04090c7dbc690481189cc711f3073d5f
| 32.406015 | 146 | 0.599505 | 4.342131 | false | false | false | false |
ccomeaux/boardgamegeek4android
|
app/src/main/java/com/boardgamegeek/repository/UserRepository.kt
|
1
|
4390
|
package com.boardgamegeek.repository
import android.content.SharedPreferences
import androidx.core.content.contentValuesOf
import com.boardgamegeek.BggApplication
import com.boardgamegeek.auth.Authenticator
import com.boardgamegeek.db.UserDao
import com.boardgamegeek.entities.CollectionItemEntity
import com.boardgamegeek.entities.UserEntity
import com.boardgamegeek.extensions.AccountPreferences
import com.boardgamegeek.extensions.preferences
import com.boardgamegeek.extensions.set
import com.boardgamegeek.io.Adapter
import com.boardgamegeek.io.BggService
import com.boardgamegeek.mappers.mapToEntities
import com.boardgamegeek.mappers.mapToEntity
import com.boardgamegeek.pref.SyncPrefs
import com.boardgamegeek.pref.clearBuddyListTimestamps
import com.boardgamegeek.provider.BggContract.Buddies
import com.boardgamegeek.provider.BggContract.Companion.INVALID_ID
import com.boardgamegeek.service.SyncService
import com.google.firebase.crashlytics.FirebaseCrashlytics
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import timber.log.Timber
class UserRepository(val application: BggApplication) {
private val userDao = UserDao(application)
private val prefs: SharedPreferences by lazy { application.preferences() }
private val syncPrefs: SharedPreferences by lazy { SyncPrefs.getPrefs(application) }
suspend fun load(username: String): UserEntity? = withContext(Dispatchers.IO) {
userDao.loadUser(username)
}
suspend fun refresh(username: String): UserEntity = withContext(Dispatchers.IO) {
val response = Adapter.createForXml().user(username)
val user = response.mapToEntity()
userDao.saveUser(user)
}
suspend fun refreshCollection(username: String, status: String): List<CollectionItemEntity> =
withContext(Dispatchers.IO) {
val items = mutableListOf<CollectionItemEntity>()
val response = Adapter.createForXml().collectionC(
username, mapOf(
status to "1",
BggService.COLLECTION_QUERY_KEY_BRIEF to "1"
)
)
response.items?.forEach {
items += it.mapToEntities().first
}
items
}
suspend fun loadBuddies(sortBy: UserDao.UsersSortBy = UserDao.UsersSortBy.USERNAME): List<UserEntity> = withContext(Dispatchers.IO) {
userDao.loadBuddies(sortBy)
}
suspend fun loadAllUsers(): List<UserEntity> = withContext(Dispatchers.IO) {
userDao.loadBuddies(buddiesOnly = false)
}
suspend fun refreshBuddies(timestamp: Long): Pair<Int, Int> = withContext(Dispatchers.IO) {
val accountName = Authenticator.getAccount(application)?.name
if (accountName.isNullOrBlank()) return@withContext 0 to 0
val response = Adapter.createForXml().user(accountName, 1, 1)
val upsertedCount = response.buddies?.buddies?.size ?: 0
response.buddies?.buddies.orEmpty()
.map { it.mapToEntity(timestamp) }
.filter { it.id != INVALID_ID && it.userName.isNotBlank() }
.forEach {
userDao.saveBuddy(it)
}
val deletedCount = userDao.deleteUsersAsOf(timestamp)
Timber.d("Deleted $deletedCount users")
upsertedCount to deletedCount
}
suspend fun updateNickName(username: String, nickName: String) {
if (username.isNotBlank()) {
userDao.upsert(contentValuesOf(Buddies.Columns.PLAY_NICKNAME to nickName), username)
}
}
fun updateSelf(user: UserEntity?) {
Authenticator.putUserId(application, user?.id ?: INVALID_ID)
if (!user?.userName.isNullOrEmpty()) FirebaseCrashlytics.getInstance().setUserId(user?.userName.hashCode().toString())
prefs[AccountPreferences.KEY_USERNAME] = user?.userName.orEmpty()
prefs[AccountPreferences.KEY_FULL_NAME] = user?.fullName.orEmpty()
prefs[AccountPreferences.KEY_AVATAR_URL] = user?.avatarUrl.orEmpty()
}
suspend fun deleteUsers(): Int {
syncPrefs.clearBuddyListTimestamps()
val count = userDao.deleteUsers()
Timber.i("Removed %d users", count)
return count
}
suspend fun resetUsers() {
deleteUsers()
//TODO remove buddy colors
SyncService.sync(application, SyncService.FLAG_SYNC_BUDDIES)
}
}
|
gpl-3.0
|
40da2677773f3bc01f45a13068894a73
| 38.909091 | 137 | 0.706378 | 4.700214 | false | false | false | false |
McGars/percents
|
feature/home/src/main/java/com/gars/percents/home/mvi/HomeFeature.kt
|
1
|
2121
|
package com.gars.percents.home.mvi
import com.badoo.mvicore.element.Reducer
import com.badoo.mvicore.feature.ReducerFeature
import com.gars.percents.home.mvi.HomeFeature.*
class HomeFeature : ReducerFeature<Wish, State, Nothing>(
initialState = State(),
reducer = ReducerImpl()
) {
// Define immutable state
data class State(
val percent: Float = 10f,
val deposit: Float = 0f,
val monthAdd: Int = 0,
val monthAddBreak: Int = 0,
val years: Int = 1,
val portion: Int = 1,
val takeOff: Float = 0f,
val takeOffEndMonth: Int = 0,
val takeOffCount: Float = 0f
)
// Define the ways it could be affected
sealed class Wish {
class PercentsUpdate(val value: Float) : Wish()
class DepositUpdate(val value: Float) : Wish()
class MonthAddUpdate(val value: Int) : Wish()
class MonthAddBreakUpdate(val value: Int) : Wish()
class YearsUpdate(val value: Int) : Wish()
class PortionUpdate(val value: Int) : Wish()
class TakeOffUpdate(val value: Float) : Wish()
class TakeOffEndMonthUpdate(val value: Int) : Wish()
class TakeOffCountUpdate(val value: Float) : Wish()
}
// Define your reducer
class ReducerImpl : Reducer<State, Wish> {
override fun invoke(state: State, wish: Wish): State =
when (wish) {
is Wish.PercentsUpdate -> state.copy(percent = wish.value)
is Wish.DepositUpdate -> state.copy(deposit = wish.value)
is Wish.MonthAddUpdate -> state.copy(monthAdd = wish.value)
is Wish.MonthAddBreakUpdate -> state.copy(monthAddBreak = wish.value)
is Wish.YearsUpdate -> state.copy(years = wish.value)
is Wish.PortionUpdate -> state.copy(portion = wish.value)
is Wish.TakeOffUpdate -> state.copy(takeOff = wish.value)
is Wish.TakeOffEndMonthUpdate -> state.copy(takeOffEndMonth = wish.value)
is Wish.TakeOffCountUpdate -> state.copy(takeOffCount = wish.value)
}
}
}
|
apache-2.0
|
5be0195c743440db40681cfd53e36978
| 36.892857 | 89 | 0.620462 | 3.920518 | false | false | false | false |
debop/debop4k
|
debop4k-core/src/main/kotlin/debop4k/core/utils/Base64Long.kt
|
1
|
2231
|
/*
* Copyright (c) 2016. KESTI co, ltd
* 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 debop4k.core.utils
/**
* @author [email protected]
*/
object Base64Long {
private val standardBase64Alphabet: CharArray by lazy {
charArrayOf(
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/')
}
private const val digitWidth: Int = 6
private const val digitMask: Long = (1L shr digitWidth) - 1L
private const val startingBitPosition: Int = 60
private val threadLocalBuilder = object : ThreadLocal<StringBuilder>() {
override fun initialValue(): StringBuilder = StringBuilder()
}
fun toBase64(n: Long): String {
val builder: StringBuilder = threadLocalBuilder.get()
builder.setLength(0)
setBase64(builder, n)
return builder.toString()
}
private fun setBase64(builder: StringBuilder, n: Long, alphabet: CharArray = standardBase64Alphabet): Unit {
if (n == 0L) {
builder.append(alphabet[0])
} else {
var bitPosition = startingBitPosition
do {
val position = n shl bitPosition
if (position == 0L)
bitPosition -= digitWidth
} while (position == 0L)
while (bitPosition >= 0L) {
val shifted = n shl bitPosition
val digitValue = (shifted and digitMask).toInt()
builder.append(alphabet[digitValue])
bitPosition -= digitWidth
}
}
}
}
|
apache-2.0
|
2ea4f405d1df09d58a600903e5492ce5
| 31.347826 | 110 | 0.593904 | 3.475078 | false | false | false | false |
ykrank/S1-Next
|
app/src/main/java/me/ykrank/s1next/view/dialog/ProgressDialogFragment.kt
|
1
|
3170
|
package me.ykrank.s1next.view.dialog
import android.app.Activity
import android.app.ProgressDialog
import android.os.Bundle
import androidx.annotation.CallSuper
import com.google.android.material.snackbar.Snackbar
import androidx.fragment.app.DialogFragment
import android.widget.Toast
import com.github.ykrank.androidtools.ui.dialog.LibProgressDialogFragment
import io.reactivex.Single
import me.ykrank.s1next.App
import me.ykrank.s1next.data.User
import me.ykrank.s1next.data.api.ApiFlatTransformer
import me.ykrank.s1next.data.api.S1Service
import me.ykrank.s1next.data.api.UserValidator
import me.ykrank.s1next.view.activity.BaseActivity
import me.ykrank.s1next.view.fragment.BaseRecyclerViewFragment
/**
* A dialog shows [ProgressDialog].
* Also wraps some related methods to request data.
*
*
* This [DialogFragment] is retained in orde
* to retain request when configuration changes.
* @param <D> The data we want to request.
</D> */
abstract class ProgressDialogFragment<D> : LibProgressDialogFragment<D>() {
internal lateinit var mS1Service: S1Service
internal lateinit var mUserValidator: UserValidator
internal lateinit var mUser: User
private var dialogNotCancelableOnTouchOutside: Boolean = false
@CallSuper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val appComponent = App.appComponent
mS1Service = appComponent.s1Service
mUser = appComponent.user
mUserValidator = appComponent.userValidator
}
/**
* @see BaseRecyclerViewFragment.getSourceObservable
*/
protected abstract fun getSourceObservable(): Single<D>
override fun getLibSourceObservable(): Single<D> {
return getSourceObservable()
.compose(ApiFlatTransformer.apiErrorTransformer<D>())
}
/**
* @see ApiFlatTransformer.flatMappedWithAuthenticityToken
*/
protected fun flatMappedWithAuthenticityToken(func: (String) -> Single<D>): Single<D> {
return ApiFlatTransformer.flatMappedWithAuthenticityToken(mS1Service, mUserValidator, mUser, func)
}
/**
* If current [android.app.Activity] is visible, sets result message to [Activity]
* in order to show a short [Snackbar] for message during [.onActivityResult],
* otherwise show a short [android.widget.Toast].
* @param text The text to show.
* *
* @see BaseActivity.onActivityResult
*/
protected fun showShortTextAndFinishCurrentActivity(text: CharSequence?) {
val activity = activity ?: return
val app = activity.applicationContext as App
// Because Activity#onActivityResult(int, int, Intent) is always invoked when current app
// is running in the foreground (so we are unable to set result message to Activity to
// let BaseActivity to show a Toast if our app is running in the background).
// So we need to handle it by ourselves.
if (app.isAppVisible) {
BaseActivity.setResultMessage(activity, text)
} else {
Toast.makeText(app, text, Toast.LENGTH_SHORT).show()
}
activity.finish()
}
}
|
apache-2.0
|
843358dc9b3be541e49f82e2b95ec044
| 35.436782 | 106 | 0.725552 | 4.396671 | false | false | false | false |
FHannes/intellij-community
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/highlighter/util.kt
|
7
|
2031
|
/*
* 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.jetbrains.plugins.groovy.highlighter
import com.intellij.codeHighlighting.TextEditorHighlightingPass
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.codeInsight.daemon.impl.HighlightInfoType
import com.intellij.codeInsight.daemon.impl.UpdateHighlightersUtil
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.plugins.groovy.GroovyLanguage
import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase
internal fun PsiFile.getGroovyFile(): GroovyFileBase? = viewProvider.getPsi(GroovyLanguage) as? GroovyFileBase
internal abstract class GroovyHighlightingPass(val myFile: PsiFile, document: Document)
: TextEditorHighlightingPass(myFile.project, document) {
protected val myInfos = mutableListOf<HighlightInfo>()
override fun doApplyInformationToEditor() {
if (myDocument == null || myInfos.isEmpty()) return
UpdateHighlightersUtil.setHighlightersToEditor(
myProject, myDocument, 0, myFile.textLength, myInfos, colorsScheme, id
)
}
protected fun addInfo(element: PsiElement, attribute: TextAttributesKey) {
val builder = HighlightInfo.newHighlightInfo(HighlightInfoType.INFORMATION)
builder.range(element).needsUpdateOnTyping(false).textAttributes(attribute).create()?.let {
myInfos.add(it)
}
}
}
|
apache-2.0
|
55442d2d0a8191b5184b320ab649d364
| 40.469388 | 110 | 0.792221 | 4.434498 | false | false | false | false |
xamoom/xamoom-android-sdk
|
xamoomsdk/src/main/java/com/xamoom/android/xamoomsdk/Helpers/GeofenceBroadcastReceiver.kt
|
1
|
1129
|
package com.xamoom.android.xamoomsdk.Helpers
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.google.android.gms.location.LocationResult
import com.xamoom.android.xamoomsdk.EnduserApi
import com.xamoom.android.xamoomsdk.PushDevice.PushDeviceUtil
class GeofenceBroadcastReceiver: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
if (intent != null) {
val action = intent.action
val name = context.packageName
if (name.equals(action)) {
val result = LocationResult.extractResult(intent)
if (result != null) {
val locations = result.locations
val sharedPref = context!!.getSharedPreferences(PushDeviceUtil.PREFES_NAME,
Context.MODE_PRIVATE)
val util = PushDeviceUtil(sharedPref)
util.storeLocation(locations[0])
EnduserApi.getSharedInstance(context).pushDevice(util, false)
}
}
}
}
}
|
mit
|
935cf6436508254794558168dc9d121d
| 36.666667 | 95 | 0.633304 | 4.723849 | false | false | false | false |
QuickBlox/quickblox-android-sdk
|
sample-chat-kotlin/app/src/main/java/com/quickblox/sample/chat/kotlin/utils/imagepick/GetFilepathFromUriTask.kt
|
1
|
5217
|
package com.quickblox.sample.chat.kotlin.utils.imagepick
import android.content.ContentResolver
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import android.webkit.MimeTypeMap
import androidx.fragment.app.FragmentManager
import com.quickblox.sample.chat.kotlin.App
import com.quickblox.sample.chat.kotlin.async.BaseAsyncTask
import com.quickblox.sample.chat.kotlin.ui.dialog.ProgressDialogFragment
import java.io.*
import java.lang.ref.WeakReference
import java.net.URLConnection
import java.net.URLDecoder
private const val BUFFER_SIZE_2_MB = 2048
class GetFilepathFromUriTask(fragmentManager: FragmentManager,
private val listener: OnImagePickedListener?,
private val requestCode: Int) : BaseAsyncTask<Intent, Void, File>() {
private val fragmentManagerWeakRef: WeakReference<FragmentManager> = WeakReference(fragmentManager)
override fun onPreExecute() {
super.onPreExecute()
fragmentManagerWeakRef.get()?.let {
ProgressDialogFragment.show(it)
}
}
@Throws(Exception::class)
override fun performInBackground(vararg params: Intent): File? {
val fileUri = params[0].data
var file: File? = null
fileUri?.let { uri ->
file = getFile(uri)
}
return file
}
@Throws(Exception::class)
private fun getFile(uri: Uri): File {
val fileExtension = getFileExtension(uri)
if (TextUtils.isEmpty(fileExtension)) {
throw Exception("Didn't get file extension")
}
val decodedFilePath = URLDecoder.decode(uri.toString(), "UTF-8")
var fileName = decodedFilePath.substring(decodedFilePath.lastIndexOf("/") + 1)
if (!fileName.contains(fileExtension!!)) {
fileName = "$fileName.$fileExtension"
}
var resultFile = getFileFromCache(fileName)
if (resultFile == null) {
resultFile = createAndWriteFileToCache(fileName, uri)
}
return resultFile
}
@Throws(Exception::class)
private fun getFileExtension(uri: Uri): String? {
var fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri.toString())
val isUriSchemeContent = uri.scheme != null && uri.scheme == ContentResolver.SCHEME_CONTENT
if (TextUtils.isEmpty(fileExtension) && isUriSchemeContent) {
val contentResolver = App.getInstance().contentResolver
val mimeTypeMap = MimeTypeMap.getSingleton()
fileExtension = mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri))
}
val isUriSchemeFile = uri.scheme != null && uri.scheme == ContentResolver.SCHEME_FILE
if (TextUtils.isEmpty(fileExtension) && isUriSchemeFile) {
val path: String = uri.path as String
val fis = FileInputStream(File(path))
val bis = BufferedInputStream(fis)
val sourceFileType = URLConnection.guessContentTypeFromStream(bis)
fileExtension = sourceFileType.substring(sourceFileType.lastIndexOf("/") + 1)
}
return fileExtension
}
private fun getFileFromCache(fileName: String): File? {
var foundFile: File? = null
val dir = File(App.getInstance().cacheDir.absolutePath)
if (dir.exists()) {
for (file in dir.listFiles()) {
if (file.name == fileName) {
foundFile = file
break
}
}
}
return foundFile
}
@Throws(Exception::class)
private fun createAndWriteFileToCache(fileName: String, uri: Uri): File {
val resultFile = File(App.getInstance().cacheDir, fileName)
val parcelFileDescriptor = App.getInstance().contentResolver.openFileDescriptor(uri, "r")
val fileDescriptor = parcelFileDescriptor!!.fileDescriptor
val inputStream: InputStream = FileInputStream(fileDescriptor)
val bis = BufferedInputStream(inputStream)
val bos = BufferedOutputStream(FileOutputStream(resultFile))
try {
val buf = ByteArray(BUFFER_SIZE_2_MB)
var length: Int
while (bis.read(buf).also { length = it } > 0) {
bos.write(buf, 0, length)
}
} catch (e: Exception) {
throw Exception("Error create and write file in a cache")
} finally {
parcelFileDescriptor.close()
bis.close()
bos.close()
}
return resultFile
}
override fun onResult(result: File?) {
hideProgress()
Log.w(GetFilepathFromUriTask::class.java.simpleName, "onResult listener = $listener")
result?.let {
listener?.onImagePicked(requestCode, result)
}
}
override fun onException(e: Exception) {
hideProgress()
Log.w(GetFilepathFromUriTask::class.java.simpleName, "onException listener = $listener")
listener?.onImagePickError(requestCode, e)
}
private fun hideProgress() {
fragmentManagerWeakRef.get()?.let {
ProgressDialogFragment.hide(it)
}
}
}
|
bsd-3-clause
|
111d74e08f84df0eae4efc6b72e54601
| 34.256757 | 103 | 0.641556 | 4.893996 | false | false | false | false |
tasks/tasks
|
app/src/test/java/org/tasks/makers/TaskContainerMaker.kt
|
1
|
1498
|
package org.tasks.makers
import com.natpryce.makeiteasy.Instantiator
import com.natpryce.makeiteasy.MakeItEasy.with
import com.natpryce.makeiteasy.Property
import com.natpryce.makeiteasy.Property.newProperty
import com.natpryce.makeiteasy.PropertyLookup
import com.natpryce.makeiteasy.PropertyValue
import com.todoroo.astrid.data.Task.Companion.NO_ID
import org.tasks.data.TaskContainer
import org.tasks.date.DateTimeUtils.newDateTime
import org.tasks.makers.Maker.make
import org.tasks.makers.TaskMaker.newTask
import org.tasks.time.DateTime
object TaskContainerMaker {
val ID: Property<TaskContainer, Long> = newProperty()
val PARENT: Property<TaskContainer, TaskContainer> = newProperty()
val CREATED: Property<TaskContainer, DateTime> = newProperty()
private val instantiator = Instantiator { lookup: PropertyLookup<TaskContainer> ->
val container = TaskContainer()
val parent = lookup.valueOf(PARENT, null as TaskContainer?)
val taskId = lookup.valueOf(ID, NO_ID)
val created = lookup.valueOf(CREATED, newDateTime())
container.task = newTask(
with(TaskMaker.ID, taskId),
with(TaskMaker.CREATION_TIME, created),
with(TaskMaker.PARENT, parent?.id ?: 0L))
container.indent = parent?.indent?.plus(1) ?: 0
container
}
fun newTaskContainer(vararg properties: PropertyValue<in TaskContainer?, *>): TaskContainer {
return make(instantiator, *properties)
}
}
|
gpl-3.0
|
c6c26bcdc3f8a16f69e15d5493e9124d
| 39.513514 | 97 | 0.733645 | 4.231638 | false | false | false | false |
daugeldauge/NeePlayer
|
app/src/main/java/com/neeplayer/model/Database.kt
|
1
|
3875
|
package com.neeplayer.model
import android.provider.MediaStore.Audio.Artists
import android.provider.MediaStore.Audio.Artists.Albums
import android.provider.MediaStore.Audio.Media
import com.pushtorefresh.storio.contentresolver.StorIOContentResolver
import com.pushtorefresh.storio.contentresolver.queries.Query
class Database(private val storIOContentResolver: StorIOContentResolver, private val artistResolver: ArtistResolver) {
fun getArtists(): List<Artist> {
return storIOContentResolver
.get()
.listOfObjects(Artist::class.java)
.withQuery(Query.builder()
.uri(Artists.EXTERNAL_CONTENT_URI)
.columns(Artists._ID, Artists.ARTIST, Artists.NUMBER_OF_TRACKS, Artists.NUMBER_OF_ALBUMS).build())
.withGetResolver(artistResolver)
.prepare()
.executeAsBlocking()
}
fun getAlbums(artist: Artist): List<Album> {
return storIOContentResolver
.get()
.listOfObjects(Album::class.java)
.withQuery(Query.builder()
.uri(Albums.getContentUri("external", artist.id))
.columns(Albums.ALBUM_ID, Albums.ALBUM, Albums.FIRST_YEAR)
.sortOrder(Albums.FIRST_YEAR)
.build())
.withGetResolver(AlbumResolver(artist))
.prepare()
.executeAsBlocking()
}
fun getSongs(album: Album): List<Song> {
return storIOContentResolver
.get()
.listOfObjects(Song::class.java)
.withQuery(Query.builder()
.uri(Media.EXTERNAL_CONTENT_URI)
.columns(Media._ID, Media.TITLE, Media.DURATION, Media.TRACK)
.where(Media.ALBUM_ID + "=?")
.whereArgs(album.id)
.sortOrder(Media.TRACK)
.build())
.withGetResolver(SongResolver(album))
.prepare()
.executeAsBlocking()
}
fun restorePlaylist(songId: Long?): Playlist? {
songId ?: return null
val artistId = getArtistId(songId) ?: return null
val artist = getArtist(artistId) ?: return null
val albums = getAlbums(artist)
val songs = albums.flatMap { getSongs(it) }
val index = songs.indexOfFirst { it.id == songId }
return if (index < 0) null
else Playlist(songs, index, true)
}
fun getArtist(artistId: Long): Artist? {
return storIOContentResolver
.get()
.`object`(Artist::class.java)
.withQuery(Query.builder()
.uri(Artists.EXTERNAL_CONTENT_URI)
.columns(Artists._ID, Artists.ARTIST, Artists.NUMBER_OF_TRACKS, Artists.NUMBER_OF_ALBUMS)
.where(Artists._ID + "=?")
.whereArgs(artistId)
.build())
.withGetResolver(artistResolver)
.prepare()
.executeAsBlocking()
}
fun getArtistId(songId: Long): Long? {
val cursor = storIOContentResolver
.get()
.cursor()
.withQuery(Query.builder()
.uri(Media.EXTERNAL_CONTENT_URI)
.columns(Media.ARTIST_ID)
.where(Media._ID + "=?")
.whereArgs(songId)
.build())
.prepare()
.executeAsBlocking()
val artistId = if (cursor.moveToFirst()) {
cursor.getLong(Media.ARTIST_ID)
} else {
null
}
cursor.close()
return artistId
}
}
|
mit
|
b922f2dd63a42f1973f653a22969eaf9
| 36.259615 | 122 | 0.52671 | 5.152926 | false | false | false | false |
soniccat/android-taskmanager
|
taskmanager/src/main/java/com/example/alexeyglushkov/taskmanager/rx/TasksRx.kt
|
1
|
2353
|
package com.example.alexeyglushkov.taskmanager.rx
import com.example.alexeyglushkov.taskmanager.task.Task
import com.example.alexeyglushkov.taskmanager.task.TaskBase
import com.example.alexeyglushkov.taskmanager.pool.TaskPool
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Single
object TasksRx {
fun <T> fromSingle(single: Single<T>): TaskBase {
return SingleTask(single)
}
fun <T> toSingle(task: Task, taskPool: TaskPool): Single<T> {
return Single.create { emitter ->
val callback = task.finishCallback
emitter.setCancellable {
taskPool.cancelTask(task, null)
}
task.finishCallback = object : Task.Callback {
override fun onCompleted(cancelled: Boolean) {
callback?.onCompleted(cancelled)
val error = task.taskError
if (error != null) {
emitter.onError(error)
} else {
try {
val result = task.taskResult as T
emitter.onSuccess(result)
} catch (e: Exception) {
emitter.onError(e)
}
}
}
}
taskPool.addTask(task)
}
}
fun <T> fromMaybe(maybe: Maybe<T>): TaskBase {
return MaybeTask(maybe)
}
fun fromCompletable(completable: Completable): TaskBase {
return CompletableTask(completable)
}
fun toCompletable(task: Task, taskPool: TaskPool): Completable {
return Completable.create { emitter ->
val callback = task.finishCallback
emitter.setCancellable {
taskPool.cancelTask(task, null)
}
task.finishCallback = object : Task.Callback {
override fun onCompleted(cancelled: Boolean) {
callback?.onCompleted(cancelled)
val error = task.taskError
if (error != null) {
emitter.onError(error)
} else {
emitter.onComplete()
}
}
}
taskPool.addTask(task)
}
}
}
|
mit
|
4c689a53e87dc530b92cb7e24e728b5a
| 30.386667 | 68 | 0.520612 | 5.263982 | false | false | false | false |
adrcotfas/Goodtime
|
app/src/main/java/com/apps/adrcotfas/goodtime/database/Profile.kt
|
1
|
1687
|
/*
* Copyright 2016-2021 Adrian Cotfas
*
* 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.apps.adrcotfas.goodtime.database
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
@Entity
class Profile {
@Ignore
constructor(
name: String, durationWork: Int, durationBreak: Int
) {
this.name = name
this.durationWork = durationWork
this.durationBreak = durationBreak
enableLongBreak = false
durationLongBreak = 15
sessionsBeforeLongBreak = 4
}
constructor(
name: String,
durationWork: Int,
durationBreak: Int,
durationLongBreak: Int,
sessionsBeforeLongBreak: Int
) {
this.name = name
this.durationWork = durationWork
this.durationBreak = durationBreak
enableLongBreak = true
this.durationLongBreak = durationLongBreak
this.sessionsBeforeLongBreak = sessionsBeforeLongBreak
}
@PrimaryKey
var name: String
var durationWork: Int
var durationBreak: Int
var enableLongBreak: Boolean
var durationLongBreak: Int
var sessionsBeforeLongBreak: Int
}
|
apache-2.0
|
0e8e72274388ba155e208e84b1323491
| 29.690909 | 128 | 0.700059 | 4.486702 | false | false | false | false |
rsiebert/TVHClient
|
app/src/main/java/org/tvheadend/tvhclient/ui/features/playback/external/CastSessionManagerListener.kt
|
1
|
1883
|
package org.tvheadend.tvhclient.ui.features.playback.external
import android.app.Activity
import com.google.android.gms.cast.framework.CastSession
import com.google.android.gms.cast.framework.SessionManagerListener
import timber.log.Timber
class CastSessionManagerListener(private val activity: Activity, private var castSession: CastSession?) : SessionManagerListener<CastSession> {
override fun onSessionEnded(session: CastSession, error: Int) {
Timber.d("Cast session ended with error $error")
if (session === castSession) {
castSession = null
}
activity.invalidateOptionsMenu()
}
override fun onSessionResumed(session: CastSession, wasSuspended: Boolean) {
Timber.d("Cast session resumed, was suspended $wasSuspended")
castSession = session
activity.invalidateOptionsMenu()
}
override fun onSessionStarted(session: CastSession, sessionId: String) {
Timber.d("Cast session started with id $sessionId")
castSession = session
activity.invalidateOptionsMenu()
}
override fun onSessionStarting(session: CastSession) {
Timber.d("Cast session is starting")
}
override fun onSessionStartFailed(session: CastSession, error: Int) {
Timber.d("Cast session failed with error $error")
}
override fun onSessionEnding(session: CastSession) {
Timber.d("Cast session is ending")
}
override fun onSessionResuming(session: CastSession, sessionId: String) {
Timber.d("Cast session is resuming with id $sessionId")
}
override fun onSessionResumeFailed(session: CastSession, error: Int) {
Timber.d("Cast session resume failed with error $error")
}
override fun onSessionSuspended(session: CastSession, reason: Int) {
Timber.d("Cast session suspended with reason $reason")
}
}
|
gpl-3.0
|
e47a5efec8b5526cf891d44053deec54
| 33.236364 | 143 | 0.707913 | 4.767089 | false | false | false | false |
FFlorien/AmpachePlayer
|
app/src/main/java/be/florien/anyflow/player/PlayerService.kt
|
1
|
4310
|
package be.florien.anyflow.player
import android.app.PendingIntent
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.map
import androidx.media.session.MediaButtonReceiver
import be.florien.anyflow.AnyFlowApp
import be.florien.anyflow.CrashReportingTree
import be.florien.anyflow.data.toSong
import timber.log.Timber
import javax.inject.Inject
/**
* Service used to handle the media player.
*/
class PlayerService : LifecycleService() {
/**
* Injection
*/
@Inject
internal lateinit var playerController: PlayerController
@Inject
internal lateinit var playingQueue: PlayingQueue
/**
* Fields
*/
private val iBinder = LocalBinder()
private val pendingIntent: PendingIntent by lazy { //todo inject ?
val intent = packageManager?.getLaunchIntentForPackage(packageName)
PendingIntent.getActivity(this@PlayerService, 0, intent, PendingIntent.FLAG_IMMUTABLE)
}
private val mediaSession: MediaSessionCompat by lazy {
MediaSessionCompat(this, MEDIA_SESSION_NAME).apply {
setSessionActivity(pendingIntent)
setCallback(object : MediaSessionCompat.Callback() {
override fun onSeekTo(pos: Long) {
playerController.seekTo(pos)
}
override fun onSkipToPrevious() {
playingQueue.listPosition--
}
override fun onPlay() {
playerController.resume()
}
override fun onSkipToNext() {
playingQueue.listPosition++
}
override fun onPause() {
playerController.pause()
}
})
isActive = true
}
}
private val notificationBuilder: PlayerNotificationBuilder by lazy { PlayerNotificationBuilder(this, mediaSession, pendingIntent) }
private val isPlaying
get() = playerController.isPlaying()
private val hasPrevious
get() = playingQueue.listPosition > 0
private val hasNext
get() = playingQueue.listPosition < playingQueue.queueSize - 1
/**
* Lifecycle
*/
override fun onCreate() {
super.onCreate()
(application as AnyFlowApp).userComponent?.inject(this)
Timber.plant(CrashReportingTree())
playerController.stateChangeNotifier.observe(this) {
if (!isPlaying) {
stopForeground(false)
}
val playbackState = when (it) {
PlayerController.State.BUFFER -> PlaybackStateCompat.STATE_BUFFERING
PlayerController.State.RECONNECT -> PlaybackStateCompat.STATE_BUFFERING
PlayerController.State.PLAY -> PlaybackStateCompat.STATE_PLAYING
PlayerController.State.PAUSE -> PlaybackStateCompat.STATE_PAUSED
else -> PlaybackStateCompat.STATE_NONE
}
notificationBuilder.lastPlaybackState = playbackState
notificationBuilder.updateNotification(isPlaying, hasPrevious, hasNext)
}
playerController.playTimeNotifier.observe(this) {
notificationBuilder.lastPosition = it
}
playingQueue.currentSong.map { it.toSong() }.observe(this) {
notificationBuilder.updateMediaSession(it)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent != null && intent.action == "ALARM") {
playerController.playForAlarm()
}
MediaButtonReceiver.handleIntent(mediaSession, intent)
return super.onStartCommand(intent, flags, startId)
}
override fun onBind(intent: Intent): IBinder {
super.onBind(intent)
return iBinder
}
/**
* Inner classes
*/
inner class LocalBinder : Binder() {
val service: PlayerController
get() = playerController
}
/**
* Private Methods
*/
companion object {
const val MEDIA_SESSION_NAME = "AnyFlow player"
}
}
|
gpl-3.0
|
120da77d1d6127ba69a0fc9424da9625
| 29.574468 | 135 | 0.637123 | 5.50447 | false | false | false | false |
goodwinnk/intellij-community
|
platform/platform-tests/testSrc/com/intellij/internal/statistics/FeatureEventLogTestUtil.kt
|
2
|
1414
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistics
import com.intellij.internal.statistic.eventLog.*
fun newEvent(recorderId: String,
type: String,
time: Long = System.currentTimeMillis(),
session: String = "session-id",
build: String = "999.999",
recorderVersion: String = "1",
bucket: String = "-1",
count: Int = 1,
data: Map<String, Any> = emptyMap()): LogEvent {
val event = newLogEvent(session, build, bucket, time, recorderId, recorderVersion, type, false)
(event.event as LogEventAction).count = count
for (datum in data) {
event.event.addData(datum.key, datum.value)
}
return event
}
fun newStateEvent(recorderId: String,
type: String,
time: Long = System.currentTimeMillis(),
session: String = "session-id",
build: String = "999.999",
recorderVersion: String = "1",
bucket: String = "-1",
data: Map<String, Any> = emptyMap()): LogEvent {
val event = newLogEvent(session, build, bucket, time, recorderId, recorderVersion, type, true)
for (datum in data) {
event.event.addData(datum.key, datum.value)
}
return event
}
|
apache-2.0
|
411eb3172f72c54c72e970ad0794c806
| 38.305556 | 140 | 0.603253 | 4.310976 | false | false | false | false |
olonho/carkot
|
translator/src/main/kotlin/org/kotlinnative/translator/llvm/types/LLVMFunctionType.kt
|
1
|
1217
|
package org.kotlinnative.translator.llvm.types
import org.jetbrains.kotlin.types.KotlinType
import org.kotlinnative.translator.TranslationState
import org.kotlinnative.translator.llvm.LLVMInstanceOfStandardType
import org.kotlinnative.translator.llvm.LLVMVariable
class LLVMFunctionType(type: KotlinType, state: TranslationState) : LLVMType() {
override val defaultValue = ""
override val align: Int = 4
override var size: Int = 4
override val mangle: String
override val typename = "FunctionType"
val arguments: List<LLVMVariable>
val returnType: LLVMVariable
init {
val types = type.arguments.map { LLVMInstanceOfStandardType("", it.type, state = state) }.toList()
returnType = types.last()
arguments = types.dropLast(1)
mangle = "F.${LLVMType.mangleFunctionArguments(arguments)}.EF"
}
fun mangleArgs() = LLVMType.mangleFunctionArguments(arguments)
override fun toString() =
"${returnType.type} (${arguments.map { it.pointedType }.joinToString()})"
override fun equals(other: Any?) =
(other is LLVMFunctionType) && (mangle == other.mangle)
override fun hashCode() =
mangle.hashCode()
}
|
mit
|
d268524e436767d3cb2579f548f5d7ca
| 31.918919 | 106 | 0.703369 | 4.457875 | false | false | false | false |
daviddenton/databob.kotlin
|
src/main/kotlin/io/github/databob/DateTimeGenerator.kt
|
1
|
2824
|
package io.github.databob
import java.lang.reflect.Type
import java.sql.Timestamp
import java.time.Duration
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.Period
import java.time.Year
import java.time.ZoneId
import java.time.ZonedDateTime
import java.util.Date
class DateTimeGenerator : Generator {
/**
* Pre-packed generator instances
*/
object instances {
private val defaults = CompositeGenerator(
Generators.ofType { -> ZoneId.systemDefault() },
Generators.ofType { d -> Year.of(d.mk<LocalDateTime>().year) },
Generators.ofType { d -> d.mk<LocalDateTime>().dayOfWeek },
Generators.ofType { d -> d.mk<LocalDateTime>().month },
Generators.ofType { d -> LocalDateTime.of(d.mk(), d.mk()) },
Generators.ofType { d -> ZonedDateTime.of(d.mk(), d.mk()) },
Generators.ofType { d -> java.sql.Date(d.mk<Date>().time) },
Generators.ofType { d -> Timestamp.valueOf(d.mk<LocalDateTime>()) },
Generators.ofType { d -> Duration.ofMillis(d.mk()) },
Generators.ofType { d -> Period.between(d.mk(), d.mk()) }
)
val random = CompositeGenerator(
Generators.ofType { d -> Date(d.mk<Long>()) },
Generators.ofType { d -> LocalTime.ofNanoOfDay(d.mk<Int>().toLong()) },
Generators.ofType { d -> LocalDate.ofEpochDay(d.mk<Int>().toLong()) }
).with(defaults)
val now = CompositeGenerator(
Generators.ofType { -> Date() },
Generators.ofType { d -> LocalTime.now(d.mk<ZoneId>()) },
Generators.ofType { d -> LocalDate.now(d.mk<ZoneId>()) }
).with(defaults)
val epoch = CompositeGenerator(
Generators.ofType { -> Date(0) },
Generators.ofType { -> LocalTime.ofSecondOfDay(0) },
Generators.ofType { -> LocalDate.ofEpochDay(0) }
).with(defaults)
}
private val generator = CompositeGenerator(
Generators.ofType { -> ZoneId.systemDefault() },
Generators.ofType { d -> Date(d.mk<Long>()) },
Generators.ofType { d -> LocalTime.ofNanoOfDay(d.mk<Int>().toLong()) },
Generators.ofType { d -> LocalDate.ofEpochDay(d.mk<Short>().toLong()) },
Generators.ofType { d -> LocalDateTime.of(d.mk(), d.mk()) },
Generators.ofType { d -> ZonedDateTime.of(d.mk(), d.mk()) },
Generators.ofType { d -> java.sql.Date(d.mk<Date>().time) },
Generators.ofType { d -> Timestamp.valueOf(d.mk<LocalDateTime>()) },
Generators.ofType { d -> Duration.ofMillis(d.mk()) },
Generators.ofType { d -> Period.between(d.mk(), d.mk()) }
)
override fun mk(type: Type, databob: Databob): Any? = generator.mk(type, databob)
}
|
apache-2.0
|
0cafe9dc27b827d5f5a8c9409ddbc8bd
| 41.164179 | 85 | 0.600212 | 3.988701 | false | false | false | false |
material-components/material-components-android-examples
|
Owl/app/src/main/java/com/materialstudies/owl/ui/onboarding/TopicsAdapter.kt
|
1
|
3082
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.materialstudies.owl.ui.onboarding
import android.content.Context
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.ColorInt
import androidx.annotation.Px
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.materialstudies.owl.R
import com.materialstudies.owl.databinding.OnboardingTopicItemBinding
import com.materialstudies.owl.model.Topic
import com.materialstudies.owl.model.TopicDiff
class TopicsAdapter(context: Context) : ListAdapter<Topic, TopicsViewHolder>(TopicDiff) {
private val selectedTint = context.getColor(R.color.topic_tint)
private val selectedTopLeftCornerRadius =
context.resources.getDimensionPixelSize(R.dimen.small_component_top_left_radius)
private val selectedDrawable = context.getDrawable(R.drawable.ic_checkmark)!!
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TopicsViewHolder {
val binding = OnboardingTopicItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
).apply {
root.setOnClickListener {
it.isActivated = !it.isActivated
}
}
return TopicsViewHolder(binding)
}
override fun onBindViewHolder(holder: TopicsViewHolder, position: Int) {
holder.bind(getItem(position), selectedTint, selectedTopLeftCornerRadius, selectedDrawable)
}
override fun onViewRecycled(holder: TopicsViewHolder) {
holder.itemView.rotation = 0f
}
}
class TopicsViewHolder(
private val binding: OnboardingTopicItemBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(
topic: Topic,
@ColorInt selectedTint: Int,
@Px selectedTopLeftCornerRadius: Int,
selectedDrawable: Drawable
) {
binding.run {
this.topic = topic
Glide.with(topicImage)
.asBitmap()
.load(topic.imageUrl)
.placeholder(R.drawable.course_image_placeholder)
.into(
TopicThumbnailTarget(
topicImage,
selectedTint,
selectedTopLeftCornerRadius,
selectedDrawable
)
)
executePendingBindings()
}
}
}
|
apache-2.0
|
eff81717f1e5e82ce178cf78e2681473
| 32.879121 | 99 | 0.6817 | 4.884311 | false | false | false | false |
DemonWav/IntelliJBukkitSupport
|
src/main/kotlin/platform/mixin/handlers/injectionPoint/ConstantStringMethodInjectionPoint.kt
|
1
|
5195
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.handlers.injectionPoint
import com.demonwav.mcdev.platform.mixin.reference.MixinSelector
import com.demonwav.mcdev.platform.mixin.util.fakeResolve
import com.demonwav.mcdev.platform.mixin.util.findOrConstructSourceMethod
import com.demonwav.mcdev.util.MemberReference
import com.demonwav.mcdev.util.constantStringValue
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiMethodCallExpression
import com.intellij.psi.PsiType
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.LdcInsnNode
import org.objectweb.asm.tree.MethodInsnNode
import org.objectweb.asm.tree.MethodNode
class ConstantStringMethodInjectionPoint : AbstractMethodInjectionPoint() {
override fun createNavigationVisitor(
at: PsiAnnotation,
target: MixinSelector?,
targetClass: PsiClass
): NavigationVisitor? {
return target?.let { MyNavigationVisitor(targetClass, it, AtResolver.getArgs(at)["ldc"]) }
}
override fun doCreateCollectVisitor(
at: PsiAnnotation,
target: MixinSelector?,
targetClass: ClassNode,
mode: CollectVisitor.Mode
): CollectVisitor<PsiMethod>? {
if (mode == CollectVisitor.Mode.COMPLETION) {
return MyCollectVisitor(mode, at.project, MemberReference(""), null)
}
return target?.let { MyCollectVisitor(mode, at.project, it, AtResolver.getArgs(at)["ldc"]) }
}
private class MyNavigationVisitor(
private val targetClass: PsiClass,
private val selector: MixinSelector,
private val ldc: String?
) : NavigationVisitor() {
private fun isConstantStringMethodCall(expression: PsiMethodCallExpression): Boolean {
// Must return void
if (expression.type != PsiType.VOID) {
return false
}
val arguments = expression.argumentList
val argumentTypes = arguments.expressionTypes
val javaStringType = PsiType.getJavaLangString(
expression.manager,
expression.resolveScope
)
if (argumentTypes.size != 1 || argumentTypes[0] != javaStringType) {
// Must have one String parameter
return false
}
// Expression must be constant
val constantValue = arguments.expressions[0].constantStringValue ?: return false
return ldc == null || ldc == constantValue
}
override fun visitMethodCallExpression(expression: PsiMethodCallExpression) {
if (isConstantStringMethodCall(expression)) {
expression.resolveMethod()?.let { method ->
val matches = selector.matchMethod(
method,
QualifiedMember.resolveQualifier(expression.methodExpression) ?: targetClass
)
if (matches) {
addResult(expression)
}
}
}
super.visitMethodCallExpression(expression)
}
}
private class MyCollectVisitor(
mode: Mode,
private val project: Project,
private val selector: MixinSelector,
private val ldc: String?
) : CollectVisitor<PsiMethod>(mode) {
override fun accept(methodNode: MethodNode) {
val insns = methodNode.instructions ?: return
var seenStringConstant: String? = null
insns.iterator().forEachRemaining { insn ->
if (insn is MethodInsnNode) {
// make sure we're coming from a string constant
if (seenStringConstant != null) {
if (ldc == null || ldc == seenStringConstant) {
processMethodInsn(insn)
}
}
}
val cst = (insn as? LdcInsnNode)?.cst
if (cst is String) {
seenStringConstant = cst
} else if (insn.opcode != -1) {
seenStringConstant = null
}
}
}
private fun processMethodInsn(insn: MethodInsnNode) {
// must take a string and return void
if (insn.desc != "(Ljava/lang/String;)V") return
if (mode != Mode.COMPLETION) {
// ensure we match the target
if (!selector.matchMethod(insn.owner, insn.name, insn.desc)) {
return
}
}
val fakeMethod = insn.fakeResolve()
addResult(
insn,
fakeMethod.method.findOrConstructSourceMethod(
fakeMethod.clazz,
project,
canDecompile = false
),
qualifier = insn.owner.replace('/', '.')
)
}
}
}
|
mit
|
6d2c2e7da9157cdf3f1b9120ae2711c4
| 34.827586 | 100 | 0.585948 | 5.263425 | false | false | false | false |
openHPI/android-app
|
app/src/main/java/de/xikolo/views/DateTextView.kt
|
1
|
3307
|
package de.xikolo.views
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.AppCompatTextView
import androidx.fragment.app.FragmentActivity
import de.xikolo.R
import de.xikolo.controllers.dialogs.DateInfoDialog
import de.xikolo.utils.extensions.localString
import de.xikolo.utils.extensions.utcString
import java.util.*
class DateTextView : AppCompatTextView, View.OnClickListener {
companion object {
private val TAG = DateTextView::class.java.simpleName
}
private var startDate: Date? = null
private var endDate: Date? = null
private var infoTitle: String = resources.getString(R.string.dialog_date_info_default_title)
constructor(context: Context) : super(context) {
setOnClickListener(this)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
setOnClickListener(this)
updateAttributes(context, attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
setOnClickListener(this)
updateAttributes(context, attrs)
}
fun setDate(date: Date) {
startDate = date
endDate = null
updateView()
}
fun setDateSpan(startDate: Date, endDate: Date) {
this.startDate = startDate
this.endDate = endDate
updateView()
}
private fun updateAttributes(context: Context, attrs: AttributeSet) {
val attributes = context.obtainStyledAttributes(attrs, R.styleable.DateTextView)
infoTitle = attributes.getString(R.styleable.DateTextView_infoTitle)
?: resources.getString(R.string.dialog_date_info_default_title)
attributes.recycle()
}
private fun updateView() {
if (valid) {
isClickable = true
setCompoundDrawablesWithIntrinsicBounds(
compoundDrawables[0],
compoundDrawables[1],
compoundDrawables[2],
resources.getDrawable(R.drawable.line_dotted, context.theme)
)
} else {
isClickable = false
setCompoundDrawables(null, null, null, null)
}
}
private val localText: String
get() {
return startDate?.let { start ->
endDate?.let { end ->
"${start.localString} - \n${end.localString}"
} ?: run {
start.localString
}
} ?: run {
""
}
}
private val utcText: String
get() {
return startDate?.let { start ->
endDate?.let { end ->
"${start.utcString} - \n${end.utcString}"
} ?: run {
start.utcString
}
} ?: run {
""
}
}
private val valid: Boolean
get() {
return localText.isNotEmpty() && utcText.isNotEmpty()
}
override fun onClick(v: View?) {
if (valid) {
(context as? FragmentActivity)?.let {
DateInfoDialog(infoTitle, localText, utcText).show(it.supportFragmentManager, DateInfoDialog.TAG)
}
}
}
}
|
bsd-3-clause
|
f5bf4a94d35c200bb5b63349ec1c5f2a
| 28.265487 | 113 | 0.587542 | 4.79971 | false | false | false | false |
devmpv/chan-reactor
|
src/main/kotlin/com/devmpv/repositories/MessageRepository.kt
|
1
|
1205
|
package com.devmpv.repositories
import com.devmpv.model.Message
import com.devmpv.model.Projections.InlineAttachments
import com.devmpv.model.Thread
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.repository.PagingAndSortingRepository
import org.springframework.data.repository.query.Param
import org.springframework.data.rest.core.annotation.RepositoryRestResource
import org.springframework.data.rest.core.annotation.RestResource
/**
* Message repository.
*
* @author devmpv
*/
@RepositoryRestResource(excerptProjection = InlineAttachments::class)
interface MessageRepository : PagingAndSortingRepository<Message, Long> {
@RestResource(path = "count", rel = "messages")
fun countByThreadId(@Param("id") id: Long?): Long?
@RestResource(path = "thread", rel = "messages")
fun findByThreadIdOrderByIdAsc(@Param("id") id: Long?, page: Pageable): Page<Message>
@RestResource(path = "preview", rel = "messages")
fun findTop3ByThreadIdOrderByIdDesc(@Param("id") id: Long?): List<Message>
@RestResource(exported = false)
fun findByThreadAndIdIn(thread: Thread, ids: Set<Long>): Set<Message>
}
|
mit
|
fb1c044729c45f3addb84038969a234c
| 36.65625 | 89 | 0.776763 | 4.003322 | false | false | false | false |
cashapp/sqldelight
|
drivers/native-driver/src/nativeMain/kotlin/app/cash/sqldelight/driver/native/util/BasicMutableMap.kt
|
1
|
3264
|
package app.cash.sqldelight.driver.native.util
import kotlin.native.concurrent.AtomicReference
import kotlin.native.concurrent.freeze
/**
* Basic map functionality, implemented differently by memory model. Both are safe to use with
* multiple threads.
*/
internal interface BasicMutableMap<K : Any, V : Any> {
fun getOrPut(key: K, block: () -> V): V
fun put(key: K, value: V)
fun get(key: K): V?
fun remove(key: K)
val keys: Collection<K>
val values: Collection<V>
fun cleanUp(block: (V) -> Unit)
}
internal fun <K : Any, V : Any> basicMutableMap(): BasicMutableMap<K, V> =
if (Platform.memoryModel == MemoryModel.STRICT) {
BasicMutableMapStrict()
} else {
BasicMutableMapShared()
}
/**
* New memory model only. May be able to remove the lock or use a more optimized version of a concurrent
* map, but relative to where it's being used, there isn't likely to be much of a performance hit.
*/
private class BasicMutableMapShared<K : Any, V : Any> : BasicMutableMap<K, V> {
private val lock = PoolLock(reentrant = true)
private val data = mutableMapOf<K, V>()
override fun getOrPut(key: K, block: () -> V): V = lock.withLock { data.getOrPut(key, block) }
override val values: Collection<V>
get() = lock.withLock { data.values }
override fun put(key: K, value: V) {
lock.withLock { data[key] = value }
}
override fun get(key: K): V? = lock.withLock { data[key] }
override fun remove(key: K) {
lock.withLock { data.remove(key) }
}
override val keys: Collection<K>
get() = lock.withLock { data.keys }
override fun cleanUp(block: (V) -> Unit) {
lock.withLock {
data.values.forEach(block)
}
}
}
/**
* Slow, but compatible with the strict memory model.
*/
private class BasicMutableMapStrict<K : Any, V : Any> : BasicMutableMap<K, V> {
private val lock = PoolLock(reentrant = true)
private val mapReference = AtomicReference(mutableMapOf<K, V>().freeze())
override fun getOrPut(key: K, block: () -> V): V = lock.withLock {
val result = mapReference.value[key]
if (result == null) {
val created = block()
_put(key, created)
created
} else {
result
}
}
override val values: Collection<V>
get() = lock.withLock { mapReference.value.values }
override fun put(key: K, value: V) {
lock.withLock {
_put(key, value)
}
}
private fun _put(key: K, value: V) {
mapReference.value = mutableMapOf(
Pair(key, value),
*mapReference.value.map { entry ->
Pair(entry.key, entry.value)
}.toTypedArray(),
).freeze()
}
override fun get(key: K): V? = lock.withLock { mapReference.value[key] }
override fun remove(key: K) {
lock.withLock {
val sourceMap = mapReference.value
val resultMap = mutableMapOf<K, V>()
sourceMap.keys.subtract(listOf(key)).forEach { key ->
val value = sourceMap[key]
if (value != null) {
resultMap[key] = value
}
}
mapReference.value = resultMap.freeze()
}
}
override val keys: Collection<K>
get() = lock.withLock { mapReference.value.keys }
override fun cleanUp(block: (V) -> Unit) {
lock.withLock {
mapReference.value.values.forEach(block)
}
}
}
|
apache-2.0
|
8effd69eb0504d3def96154353f1a152
| 26.2 | 104 | 0.641238 | 3.618625 | false | false | false | false |
varpeti/Suli
|
Android/work/varpe8/homeworks/02/HF02/app/src/main/java/ml/varpeti/hf02/MainActivity.kt
|
1
|
5950
|
package ml.varpeti.hf02
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.content.Intent
import android.content.BroadcastReceiver
import android.content.Context
import android.widget.ProgressBar
import android.content.IntentFilter
import java.util.*
import android.os.AsyncTask
class MainActivity : AppCompatActivity() {
lateinit var buttons: Array<Button>
lateinit var progressBars: Array<ProgressBar>
lateinit var time: Array<Long>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
buttons = arrayOf(
findViewById<Button>(R.id.b1),
findViewById<Button>(R.id.b2),
findViewById<Button>(R.id.b3),
findViewById<Button>(R.id.b4)
)
progressBars = arrayOf(
findViewById<ProgressBar>(R.id.pb1),
findViewById<ProgressBar>(R.id.pb2),
findViewById<ProgressBar>(R.id.pb3),
findViewById<ProgressBar>(R.id.pb4)
)
time = arrayOf(0, 0, 0, 0)
//Service
buttons[0].setOnClickListener {
val int = Intent(this@MainActivity, UUIDService::class.java)
startService(int)
time[0] = System.currentTimeMillis()
// Elindít a háttérben egy Servicet,
// aminek az élete nem függ a Main Activitytől,
// még egy indítás esetén felstackeleődik (utánna indul el)
// hozzá lehet bindelni egy activityhez
}
//AsyncTask
buttons[1].setOnClickListener {
UUIDAsyncTask().execute(99999)
time[1] = System.currentTimeMillis()
// Elindít a háttérben egy AsyncTaskot,
// aminek az élete nem függ a Main Activitytől,
// de a progresst és az eredményt az eredetinek küldi vissza
// még egy indítás esetén felstackeleődik (utánna indul el)
// Le lehet lőni (cancel),
// le lehet lérdezi a státuszát (status),
// lehet várni a végeredményre (get), akár timeouttal
}
//AsyncTaskLoader
buttons[2].setOnClickListener {
val atlic = UUIDAsyncTaskLoaderIC(this)
atlic.startLoading()
time[2] = System.currentTimeMillis()
// Elindít a háttérben egy "AsyncTaskot",
// aminek az élete nem függ a Main Activitytől,
// még egy indítás esetén elindul még egy
// le lehet lérdezi a státuszát (hasResult),
// és a végeredményét (result)
}
//Thread
buttons[3].setOnClickListener {
var thread = Thread(UUIDThread(), "UUIDThread")
thread.start()
time[3] = System.currentTimeMillis()
// Elindít a háttérben egy Threadet,
// aminek az élete nem függ a Main Activitytől,
// még egy indítás esetén elindul még egy
// Nem lehet elérni a vieweket
}
//Broadcast üzenetek elkapása
val filter = IntentFilter("ml.varpeti.hf02.MainActivity")
this.registerReceiver(Receiver(), filter)
}
//Ez kapja el a progress üzeneteket.
private inner class Receiver : BroadcastReceiver() {
override fun onReceive(con: Context, int: Intent) {
val name = int.extras!!.getInt("name")
val progress = int.extras!!.getInt("progress")
progressBars[name].setProgress(progress)
buttons[name].text = (System.currentTimeMillis() - time[name]).toString()
//Annak letiltása hogy még 1x elinduljon közben/utánna.
buttons[name].setOnClickListener {}
}
}
//Thread, inner class mert külön classba kötülményes contextet rakni
private inner class UUIDThread : Runnable
{
override fun run()
{
for (p in 1..100)
{
for (i in 0..99999)
{
UUID.randomUUID()
}
//Only the original thread that created a view hierarchy can touch its views.
val data = Intent()
data.putExtra("name", 3)
data.putExtra("progress", p)
data.action = "ml.varpeti.hf02.MainActivity"
sendBroadcast(data)
}
}
}
//AsyncTask
private inner class UUIDAsyncTask : AsyncTask<Int,Int,Int>()
{
override fun doInBackground(vararg params: Int?): Int
{
for(p in 1..100)
{
for (i in 0..99999)
{
UUID.randomUUID()
}
publishProgress(p)
}
return 100
}
override fun onProgressUpdate(vararg values: Int?)
{
//szintaxis csemege
values[0]?.let {
progressBars[1].setProgress(it)
buttons[1].text = (System.currentTimeMillis() - time[1]).toString()
}
}
override fun onPreExecute()
{
buttons[1].setOnClickListener {}
super.onPreExecute()
}
}
//AsyncTaskLoader
private class UUIDAsyncTaskLoaderIC(context: Context) : UUIDAsyncTaskLoader<Int>(context)
{
override fun loadInBackground(): Int
{
for (p in 1..100)
{
for (i in 0..99999)
{
UUID.randomUUID()
}
val data = Intent()
data.putExtra("name", 2)
data.putExtra("progress", p)
data.action = "ml.varpeti.hf02.MainActivity"
context.sendBroadcast(data)
}
return 100
}
}
}
|
unlicense
|
9fad089838f858eaacd7327410573576
| 31.263736 | 93 | 0.558413 | 4.089136 | false | false | false | false |
codeka/wwmmo
|
server/src/main/kotlin/au/com/codeka/warworlds/server/html/account/AccountsHandler.kt
|
1
|
3169
|
package au.com.codeka.warworlds.server.html.account
import au.com.codeka.warworlds.common.Log
import au.com.codeka.warworlds.common.proto.Account
import au.com.codeka.warworlds.common.proto.Empire
import au.com.codeka.warworlds.common.proto.NewAccountRequest
import au.com.codeka.warworlds.common.proto.NewAccountResponse
import au.com.codeka.warworlds.server.Configuration
import au.com.codeka.warworlds.server.handlers.ProtobufRequestHandler
import au.com.codeka.warworlds.server.handlers.RequestException
import au.com.codeka.warworlds.server.store.DataStore
import au.com.codeka.warworlds.server.util.CookieHelper
import au.com.codeka.warworlds.server.util.NameValidator
import au.com.codeka.warworlds.server.world.EmpireManager
import au.com.codeka.warworlds.server.world.WatchableObject
/** Accounts servlet for creating new accounts on the server. */
class AccountsHandler : ProtobufRequestHandler() {
private val log = Log("EmpiresHandler")
public override fun post() {
val req = readProtobuf(NewAccountRequest::class.java)
log.info("Creating new account: %s", req.empire_name)
// Make sure the name is valid, unique, etc etc.
if (req.empire_name.trim { it <= ' ' } == "") {
writeProtobuf(NewAccountResponse(message = "You must give your empire a name."))
return
}
val nameStatus = NameValidator.validate(
req.empire_name,
Configuration.i.limits!!.maxEmpireNameLength)
if (!nameStatus.isValid) {
writeProtobuf(NewAccountResponse(message = nameStatus.errorMsg))
return
}
val existingEmpires = EmpireManager.i.search(nameStatus.name)
// The parameter to search is a query, so it'll find non-exact matches, but that's all we care
// about, so we'll have to check manually.
for (existingEmpire in existingEmpires) {
if (existingEmpire.get().display_name.compareTo(nameStatus.name, ignoreCase = true) == 0) {
writeProtobuf(NewAccountResponse(message = "An empire with that name already exists."))
return
}
}
// If they've give us an idToken, we'll immediately associate this empire with that account.
// In that case, tokenInfo will be non-null.
val tokenInfo = if (req.id_token != null) {
TokenVerifier.verify(req.id_token!!)
} else {
null
}
// Generate a cookie for the user to authenticate with in the future.
val cookie = CookieHelper.generateCookie()
// Create the empire itself.
val empire: WatchableObject<Empire>? = EmpireManager.i.createEmpire(nameStatus.name)
if (empire == null) {
// Some kind of unexpected error creating the empire.
writeProtobuf(
NewAccountResponse(
message = "An error occurred while creating your empire, please try again."))
return
}
// Make a new account with all the details.
var account = Account(empire_id = empire.get().id)
if (tokenInfo != null) {
account = account.copy(
email = tokenInfo.email,
email_status = Account.EmailStatus.VERIFIED)
}
DataStore.i.accounts().put(cookie, account)
writeProtobuf(NewAccountResponse(cookie = cookie))
}
}
|
mit
|
e6987f750e32b94402fe16ea865716a1
| 38.6125 | 98 | 0.714105 | 4.073265 | false | false | false | false |
erickok/borefts2015
|
android/app/src/main/java/nl/brouwerijdemolen/borefts2013/gui/CachingInterceptor.kt
|
1
|
2287
|
package nl.brouwerijdemolen.borefts2013.gui
import nl.brouwerijdemolen.borefts2013.ext.div
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.ResponseBody.Companion.asResponseBody
import okio.buffer
import okio.sink
import okio.source
import java.io.File
class CachingInterceptor(private val cacheDir: File, private val maxAgeInMillis: Long) : Interceptor {
private val mediaTypeJson = "application/json; charset=utf-8".toMediaTypeOrNull()
private val cacheNameDisallowCharacters = "[^a-zA-Z0-9.\\-]".toRegex()
override fun intercept(chain: Interceptor.Chain): Response {
val cacheName = chain.request().url.cacheName()
val cacheFile = cacheDir / cacheName
if (!cacheFile.exists() || cacheFile.lastModified() < (System.currentTimeMillis() - maxAgeInMillis)) {
// Nothing cached or old
return performAndCache(cacheFile, chain)
}
// Fresh enough cache file available
return responseFromCache(cacheFile, chain.request())
}
private fun responseFromCache(cacheFile: File, chain: Request): Response {
val cacheSource = cacheFile.source().buffer()
return Response.Builder()
.request(chain)
.protocol(Protocol.HTTP_1_1)
.code(200)
.message("Cached")
.body(cacheSource.asResponseBody(mediaTypeJson, -1))
.build()
}
private fun performAndCache(cacheFile: File, chain: Interceptor.Chain): Response {
val request = chain.request()
val freshResponse = chain.proceed(request)
val responseBody = freshResponse.body
if (!freshResponse.isSuccessful || responseBody == null) {
// Failed request: use (old) cache if available, or return the error
return if (cacheFile.exists()) responseFromCache(cacheFile, request) else freshResponse
}
// Data received: cache it
val cacheSink = cacheFile.sink().buffer()
cacheSink.writeAll(responseBody.source())
cacheSink.close()
return responseFromCache(cacheFile, request)
}
private fun HttpUrl.cacheName(): String {
return this.toString().replace(cacheNameDisallowCharacters, "_")
}
}
|
gpl-3.0
|
fa9fda7bd54c912acc06a8cea1854e15
| 35.887097 | 110 | 0.668561 | 4.73499 | false | false | false | false |
vincentvalenlee/nineshop
|
src/main/kotlin/org/open/openstore/file/FilePlatform.kt
|
1
|
19274
|
package org.open.openstore.file
import org.open.openstore.file.contributors.FileNameParser
import org.apache.commons.configuration2.builder.fluent.Configurations
import java.io.File
import java.util.*
/**
* 文件平台,是x文件系统全局的对象,负责创建各类信息、配置等
*/
object FilePlatform {
val CONF = Configurations().properties("application.properties")
val URL_STYPE: Boolean = CONF.getBoolean("uriStyle")?: false
val NAMESPACE_CORE = "org.xctrl.xfilesystem"
val POINT_NAME_CORE_FILE = "file.context"
val POINT_NAME_CONFIG_BUILDER = "config.builders"
val POINT_NAME_FILE_OPERA = "file.operations"
/**
* 核心模块定义的文件系统FileContributor扩展点id,应用从此扩展点提供自己的
*/
val CONTRIBUT_POINT_CORE_FILE = NAMESPACE_CORE + "." + POINT_NAME_CORE_FILE
/**
* 核心模块定义的FileSystemConfigBuilder的扩展点id
*/
val CONTRIBUT_POINT_CONFIG_BUILDER = NAMESPACE_CORE + "." + POINT_NAME_CONFIG_BUILDER
/**
* 文件对象上操作的扩展点(文件操作是基于文件内容类型的,例如doc上的操作或者pdf上的操作)
*/
val CONTRIBUT_POINT_FILE_OPERA = NAMESPACE_CORE + "." + POINT_NAME_FILE_OPERA
fun getContributRegistry():IContributRegistry {
TODO("从平台中[osgi运行环境]获取贡献注册表")
}
/**
* RFC 2396规范,处理URI的解析器
*/
object UriParser {
val TRANS_SEPARATOR = '\\'
private val SEPARATOR_CHAR = IFileName.SEPARATOR_CHAR
private val HEX_BASE = 16
private val BITS_IN_HALF_BYTE = 4
private val LOW_MASK: Char = 0x0F.toChar()
/**
* 解析路径的第一个元素
*/
fun extractFirstElement(name: StringBuilder): String? {
val len = name.length
if (len < 1) {
return null
}
var startPos = 0
if (name[0] == SEPARATOR_CHAR) {
startPos = 1
}
for (pos in startPos..len - 1) {
if (name[pos] == SEPARATOR_CHAR) {
// Found a separator
val elem = name.substring(startPos, pos)
name.delete(startPos, pos + 1)
return elem
}
}
// No separator
val elem = name.substring(startPos)
name.setLength(0)
return elem
}
/**
* 规范化路径:
* 1.删除空路径元素
* 2.处理.以及..元素
* 3.删除尾部的分隔符
*/
fun normalisePath(path: StringBuilder): FileType {
var fileType = FileType.FOLDER
if (path.length == 0) {
return fileType
}
if (path[path.length - 1] != '/') {
fileType = FileType.FILE
}
// Adjust separators
// fixSeparators(path);
// Determine the start of the first element
var startFirstElem = 0
if (path[0] == SEPARATOR_CHAR) {
if (path.length == 1) {
return fileType
}
startFirstElem = 1
}
// Iterate over each element
var startElem = startFirstElem
var maxlen = path.length
while (startElem < maxlen) {
// Find the end of the element
var endElem = startElem
while (endElem < maxlen && path[endElem] != SEPARATOR_CHAR) {
endElem++
}
val elemLen = endElem - startElem
if (elemLen == 0) {
// An empty element - axe it
path.delete(endElem, endElem + 1)
maxlen = path.length
continue
}
if (elemLen == 1 && path[startElem] == '.') {
// A '.' element - axe it
path.delete(startElem, endElem + 1)
maxlen = path.length
continue
}
if (elemLen == 2 && path[startElem] == '.' && path[startElem + 1] == '.') {
// A '..' element - remove the previous element
if (startElem == startFirstElem) {
// Previous element is missing
throw FileSystemException("无效的相对路径")
}
// Find start of previous element
var pos = startElem - 2
while (pos >= 0 && path[pos] != SEPARATOR_CHAR) {
pos--
}
startElem = pos + 1
path.delete(startElem, endElem + 1)
maxlen = path.length
continue
}
// A regular element
startElem = endElem + 1
}
// Remove trailing separator
if (!FilePlatform.URL_STYPE && maxlen > 1 && path[maxlen - 1] == SEPARATOR_CHAR) {
path.delete(maxlen - 1, maxlen)
}
return fileType
}
/**
* 规范化分隔符
*/
fun fixSeparators(name: StringBuilder): Boolean {
var changed = false
val maxlen = name.length
for (i in 0..maxlen - 1) {
val ch = name[i]
if (ch == TRANS_SEPARATOR) {
name.setCharAt(i, SEPARATOR_CHAR)
changed = true
}
}
return changed
}
/**
* 从URI中解析scheme
*/
fun extractScheme(uri: String): String? {
return extractScheme(uri, null)
}
/**
* 解析URI中的scheme,从URI删除schem以及:分隔符
*/
fun extractScheme(uri: String, buffer: StringBuilder?): String? {
if (buffer != null) {
buffer.setLength(0)
buffer.append(uri)
}
val maxPos = uri.length
for (pos in 0..maxPos - 1) {
val ch = uri[pos]
if (ch == ':') {
// Found the end of the scheme
val scheme = uri.substring(0, pos)
if (scheme.length <= 1 && Os.isFamily(Os.OS_FAMILY_WINDOWS)) {
// This is not a scheme, but a Windows drive letter
return null
}
buffer?.delete(0, pos + 1)
return scheme.intern()
}
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
// A scheme character
continue
}
if (pos > 0 && (ch >= '0' && ch <= '9' || ch == '+' || ch == '-' || ch == '.')) {
// A scheme character (these are not allowed as the first
// character of the scheme, but can be used as subsequent
// characters.
continue
}
// Not a scheme character
break
}
// No scheme in URI
return null
}
fun decode(encodedStr: String?): String? {
if (encodedStr == null) {
return null
}
if (encodedStr.indexOf('%') < 0) {
return encodedStr
}
val buffer = StringBuilder(encodedStr)
decode(buffer, 0, buffer.length)
return buffer.toString()
}
/**
* 从字符中删除%nn编码
* @param buffer 包含编码的字符缓存
* @param offset 开始编码的字符位置
* @param length 编码的字符数目
*/
fun decode(buffer: StringBuilder, offset: Int, length: Int) {
var index = offset
var count = length
while (count > 0) {
val ch = buffer[index]
if (ch != '%') {
count--
index++
continue
}
if (count < 3) {
throw FileSystemException("无效的编码序列", null,
arrayOf(buffer.substring(index, index + count)))
}
// Decode
val dig1 = Character.digit(buffer[index + 1], HEX_BASE)
val dig2 = Character.digit(buffer[index + 2], HEX_BASE)
if (dig1 == -1 || dig2 == -1) {
throw FileSystemException("无效的编码序列", null,
arrayOf(buffer.substring(index, index + 3)))
}
val value = (dig1 shl BITS_IN_HALF_BYTE or dig2).toChar()
// Replace
buffer.setCharAt(index, value)
buffer.delete(index + 1, index + 3)
count -= 2
count--
index++
}
}
fun appendEncoded(buffer: StringBuilder, unencodedValue: String, reserved: CharArray) {
val offset = buffer.length
buffer.append(unencodedValue)
encode(buffer, offset, unencodedValue.length, reserved)
}
fun encode(buffer: StringBuilder, offset: Int, length: Int, reserved: CharArray?) {
var index = offset
var count = length
while (count > 0) {
val ch = buffer[index]
var match = ch == '%'
if (reserved != null) {
var i = 0
while (!match && i < reserved.size) {
if (ch == reserved[i]) {
match = true
}
i++
}
}
if (match) {
// Encode
val digits = charArrayOf(Character.forDigit(ch.toInt() shr BITS_IN_HALF_BYTE and LOW_MASK.toInt(), HEX_BASE), Character.forDigit(ch.toInt() and LOW_MASK.toInt(), HEX_BASE))
buffer.setCharAt(index, '%')
buffer.insert(index + 1, digits)
index += 2
}
index++
count--
}
}
fun encode(decodedStr: String): String {
return encode(decodedStr, null)!!
}
/**
* 转换特殊的字符到%nn值
*/
fun encode(decodedStr: String?, reserved: CharArray?): String? {
if (decodedStr == null) {
return null
}
val buffer = StringBuilder(decodedStr)
encode(buffer, 0, buffer.length, reserved)
return buffer.toString()
}
fun encode(strings: Array<String>?): Array<String>? {
if (strings == null) {
return null
}
for (i in strings.indices) {
strings[i] = encode(strings[i])
}
return strings
}
fun checkUriEncoding(uri: String) {
decode(uri)
}
fun canonicalizePath(buffer: StringBuilder, offset: Int, length: Int, fileNameParser: FileNameParser) {
var index = offset
var count = length
while (count > 0) {
val ch = buffer[index]
if (ch == '%') {
if (count < 3) {
throw FileSystemException("无效的占位序列",null,
arrayOf(buffer.substring(index, index + count)))
}
// Decode
val dig1 = Character.digit(buffer[index + 1], HEX_BASE)
val dig2 = Character.digit(buffer[index + 2], HEX_BASE)
if (dig1 == -1 || dig2 == -1) {
throw FileSystemException("无效的占位序列",null,
arrayOf(buffer.substring(index, index + 3)))
}
val value = (dig1 shl BITS_IN_HALF_BYTE or dig2).toChar()
val match = value == '%' || fileNameParser.encodeCharacter(value)
if (match) {
// this is a reserved character, not allowed to decode
index += 2
count -= 2
count--
index++
continue
}
// Replace
buffer.setCharAt(index, value)
buffer.delete(index + 1, index + 3)
count -= 2
} else if (fileNameParser.encodeCharacter(ch)) {
// Encode
val digits = charArrayOf(Character.forDigit(ch.toInt() shr BITS_IN_HALF_BYTE and LOW_MASK.toInt(), HEX_BASE), Character.forDigit(ch.toInt() and LOW_MASK.toInt(), HEX_BASE))
buffer.setCharAt(index, '%')
buffer.insert(index + 1, digits)
index += 2
}
count--
index++
}
}
fun extractQueryString(name: StringBuilder): String? {
for (pos in 0..name.length - 1) {
if (name[pos] == '?') {
val queryString = name.substring(pos + 1)
name.delete(pos, name.length)
return queryString
}
}
return null
}
}
data class OsFamily(val name:String, val families: Array<OsFamily> = arrayOf<OsFamily>())
object Os {
val OS_FAMILY_WINDOWS = OsFamily("windows")
val OS_FAMILY_DOS = OsFamily("dos")
val OS_FAMILY_WINNT = OsFamily("nt", arrayOf(OS_FAMILY_WINDOWS))
val OS_FAMILY_WIN9X = OsFamily("win9x",arrayOf(OS_FAMILY_WINDOWS, OS_FAMILY_DOS))
val OS_FAMILY_OS2 = OsFamily("os/2", arrayOf(OS_FAMILY_DOS))
val OS_FAMILY_NETWARE = OsFamily("netware")
val OS_FAMILY_UNIX = OsFamily("unix")
val OS_FAMILY_MAC = OsFamily("mac")
val OS_FAMILY_OSX = OsFamily("osx", arrayOf(OS_FAMILY_UNIX, OS_FAMILY_MAC))
private val OS_NAME = System.getProperty("os.name").toLowerCase(Locale.US)
private val OS_ARCH = System.getProperty("os.arch").toLowerCase(Locale.US)
private val OS_VERSION = System.getProperty("os.version").toLowerCase(Locale.US)
private val PATH_SEP = File.pathSeparator
private var OS_FAMILY: OsFamily? = null
private var OS_ALL_FAMILIES: Array<OsFamily>? = null
private val ALL_FAMILIES = arrayOf(OS_FAMILY_DOS, OS_FAMILY_MAC, OS_FAMILY_NETWARE, OS_FAMILY_OS2, OS_FAMILY_OSX, OS_FAMILY_UNIX, OS_FAMILY_WINDOWS, OS_FAMILY_WINNT, OS_FAMILY_WIN9X)
init {
OS_FAMILY = determineOsFamily()
OS_ALL_FAMILIES = determineAllFamilies()
}
fun isVersion(version: String): Boolean {
return isOs(null as OsFamily?, null, null, version)
}
fun isArch(arch: String): Boolean {
return isOs(null as OsFamily?, null, arch, null)
}
fun isFamily(family: String): Boolean {
return isOs(family, null, null, null)
}
fun isFamily(family: OsFamily): Boolean {
return isOs(family, null, null, null)
}
fun isName(name: String): Boolean {
return isOs(null as OsFamily?, name, null, null)
}
fun isOs(family: String, name: String?, arch: String?, version: String?): Boolean {
return isOs(getFamily(family), name, arch, version)
}
fun isOs(family: OsFamily?, name: String?, arch: String?, version: String?): Boolean {
if (family != null || name != null || arch != null || version != null) {
val isFamily = familyMatches(family)
val isName = nameMatches(name)
val isArch = archMatches(arch)
val isVersion = versionMatches(version)
return isFamily && isName && isArch && isVersion
}
return false
}
fun getFamily(name: String): OsFamily? {
for (osFamily in ALL_FAMILIES) {
if (osFamily.name.equals(name, ignoreCase = true)) {
return osFamily
}
}
return null
}
private fun versionMatches(version: String?): Boolean {
var isVersion = true
if (version != null) {
isVersion = version.equals(OS_VERSION, ignoreCase = true)
}
return isVersion
}
private fun archMatches(arch: String?): Boolean {
var isArch = true
if (arch != null) {
isArch = arch.equals(OS_ARCH, ignoreCase = true)
}
return isArch
}
private fun nameMatches(name: String?): Boolean {
var isName = true
if (name != null) {
isName = name.equals(OS_NAME, ignoreCase = true)
}
return isName
}
private fun familyMatches(family: OsFamily?): Boolean {
return family?.let {
OS_ALL_FAMILIES!!.any {
it === family
}
} ?: false
}
private fun determineAllFamilies():Array<OsFamily> {
var allFamilies:Set<OsFamily> = mutableSetOf()
if (OS_FAMILY != null) {
var queue = mutableListOf<OsFamily>()
queue + OS_FAMILY
while (queue.size > 0) {
val family = queue.removeAt(0)
allFamilies + family
val families = family.families
families.forEach {
queue + it
}
}
}
return allFamilies.toTypedArray()
}
private fun determineOsFamily(): OsFamily? {
// Determine the most specific OS family
if (OS_NAME.indexOf("windows") > -1) {
if (OS_NAME.indexOf("xp") > -1 || OS_NAME.indexOf("2000") > -1 || OS_NAME.indexOf("nt") > -1) {
return OS_FAMILY_WINNT
}
return OS_FAMILY_WIN9X
} else if (OS_NAME.indexOf("os/2") > -1) {
return OS_FAMILY_OS2
} else if (OS_NAME.indexOf("netware") > -1) {
return OS_FAMILY_NETWARE
} else if (OS_NAME.indexOf("mac") > -1) {
if (OS_NAME.endsWith("x")) {
return OS_FAMILY_OSX
}
return OS_FAMILY_MAC
} else if (PATH_SEP.equals(":")) {
return OS_FAMILY_UNIX
} else {
return null
}
}
}
}
|
gpl-3.0
|
70d5653629b44fb479b695ab15f3542d
| 31.478336 | 192 | 0.462113 | 4.630591 | false | false | false | false |
androidx/androidx
|
window/window-core/src/test/java/androidx/window/core/layout/WindowSizeClassTest.kt
|
3
|
2004
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.window.core.layout
import org.junit.Assert.assertEquals
import org.junit.Test
public class WindowSizeClassTest {
@Test
public fun testWidthSizeClass_construction() {
val expected = listOf(
WindowWidthSizeClass.COMPACT,
WindowWidthSizeClass.MEDIUM,
WindowWidthSizeClass.EXPANDED
)
val actual = listOf(100f, 700f, 900f).map { width ->
WindowSizeClass.compute(dpWidth = width, dpHeight = 100f)
}.map { sizeClass ->
sizeClass.windowWidthSizeClass
}
assertEquals(expected, actual)
}
@Test
public fun testHeightSizeClass_construction() {
val expected = listOf(
WindowHeightSizeClass.COMPACT,
WindowHeightSizeClass.MEDIUM,
WindowHeightSizeClass.EXPANDED
)
val actual = listOf(100f, 500f, 900f).map { height ->
WindowSizeClass.compute(dpHeight = height, dpWidth = 100f)
}.map { sizeClass ->
sizeClass.windowHeightSizeClass
}
assertEquals(expected, actual)
}
@Test
public fun testEqualsImpliesHashCode() {
val first = WindowSizeClass.compute(100f, 500f)
val second = WindowSizeClass.compute(100f, 500f)
assertEquals(first, second)
assertEquals(first.hashCode(), second.hashCode())
}
}
|
apache-2.0
|
1774c9c169b4fc3d1d4440a0613ae386
| 29.363636 | 75 | 0.663174 | 4.704225 | false | true | false | false |
smichel17/simpletask-android
|
app/src/main/java/nl/mpcjanssen/simpletask/HelpScreen.kt
|
1
|
6159
|
/**
* @copyright 2014- Mark Janssen)
*/
package nl.mpcjanssen.simpletask
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import android.view.Menu
import android.view.MenuItem
import android.webkit.WebView
import android.webkit.WebViewClient
import nl.mpcjanssen.simpletask.util.markdownAssetAsHtml
import nl.mpcjanssen.simpletask.util.Config
import java.util.*
class HelpScreen : ThemedActionBarActivity() {
private val history = Stack<String>()
private var wvHelp: WebView? = null
private fun loadDesktop(wv: WebView, url: String) {
wv.settings.userAgentString = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.45 Safari/535.19"
wv.loadUrl(url)
}
override fun onBackPressed() {
Log.d(TAG, "History " + history + "empty: " + history.empty())
history.pop()
if (!history.empty()) {
showMarkdownAsset(wvHelp!!, this, history.pop())
} else {
super.onBackPressed()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var page = "index." + getText(R.string.help_locale).toString() + ".md"
val i = intent
if (i.hasExtra(Constants.EXTRA_HELP_PAGE)) {
page = i.getStringExtra(Constants.EXTRA_HELP_PAGE) + "." + getText(R.string.help_locale).toString() + ".md"
}
setContentView(R.layout.help)
val actionBar = supportActionBar
actionBar?.setDisplayHomeAsUpEnabled(true)
wvHelp = findViewById<WebView>(R.id.help_view)
// Prevent brief flash of white when loading WebView.
if (Config.isDarkTheme || Config.isBlackTheme) {
val tv = TypedValue()
theme.resolveAttribute(android.R.attr.windowBackground, tv, true)
if (tv.type >= TypedValue.TYPE_FIRST_COLOR_INT && tv.type <= TypedValue.TYPE_LAST_COLOR_INT) {
val windowBackgroundColor = tv.data
wvHelp!!.setBackgroundColor(windowBackgroundColor)
}
}
wvHelp!!.webViewClient = object : WebViewClient() {
// Replacement is API >= 21 only
@Suppress("OverridingDeprecatedMember")
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
Log.d(TAG, "Loading url: " + url)
if (url.startsWith("https://www.paypal.com")) {
// Paypal links don't work in the mobile browser so this hack is needed
loadDesktop(view, url)
// Don't store paypal redirects in history
if (history.peek() != "paypal") {
history.push("paypal")
}
return true
}
if (url.startsWith("http://") || url.startsWith("https://")) {
view.settings.userAgentString = null
openUrl(url)
return true
} else if (url.endsWith(".md")) {
showMarkdownAsset(view, this@HelpScreen, url.replace(BASE_URL, ""))
return true
} else {
return false
}
}
}
showMarkdownAsset(wvHelp!!, this, page)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.help, menu)
return true
}
fun openUrl(url: String) {
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(browserIntent)
}
fun showMarkdownAsset(wv: WebView, ctxt: Context, name: String) {
Log.d(TAG, "Loading asset $name into $wv($ctxt)")
val html = markdownAssetAsHtml(ctxt, name)
history.push(name)
wv.loadDataWithBaseURL(BASE_URL, html, "text/html", "UTF-8", "file:///android_asset/index." + getText(R.string.help_locale) + ".md")
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
// Respond to the action bar's Up/Home button
R.id.menu_simpletask -> {
showMarkdownAsset(wvHelp!!, this, "index." + getText(R.string.help_locale) + ".md")
return true
}
// Changelog is English only
R.id.menu_changelog -> {
showMarkdownAsset(wvHelp!!, this, "changelog.en.md")
return true
}
R.id.menu_myn -> {
showMarkdownAsset(wvHelp!!, this, "MYN." + getText(R.string.help_locale) + ".md")
return true
}
R.id.menu_script -> {
showMarkdownAsset(wvHelp!!, this, "script." + getText(R.string.help_locale) + ".md")
return true
}
R.id.menu_intents -> {
showMarkdownAsset(wvHelp!!, this, "intents." + getText(R.string.help_locale) + ".md")
return true
}
R.id.menu_ui -> {
showMarkdownAsset(wvHelp!!, this, "ui." + getText(R.string.help_locale) + ".md")
return true
}
R.id.menu_donate -> {
val i = Intent(Intent.ACTION_VIEW)
i.data = Uri.parse("https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=mpc%2ejanssen%40gmail%2ecom&lc=NL&item_name=mpcjanssen%2enl&item_number=Simpletask¤cy_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted")
startActivity(i)
return true
}
R.id.menu_tracker -> {
openUrl("https://github.com/mpcjanssen/simpletask-android")
return true
}
}
return super.onOptionsItemSelected(item)
}
companion object {
internal val TAG = HelpScreen::class.java.simpleName
internal val BASE_URL = "file:///android_asset/"
}
}
|
gpl-3.0
|
6c41d2d28dc6bb99f0fef436835a6061
| 37.49375 | 256 | 0.572658 | 4.291986 | false | false | false | false |
veyndan/reddit-client
|
app/src/main/java/com/veyndan/paper/reddit/FilterFragment.kt
|
2
|
3561
|
package com.veyndan.paper.reddit
import android.content.Intent
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.support.annotation.ColorInt
import android.support.design.widget.TabLayout
import android.support.v4.app.DialogFragment
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import android.support.v4.content.ContextCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.jakewharton.rxbinding2.support.design.widget.selectionEvents
import com.jakewharton.rxbinding2.view.clicks
import com.veyndan.paper.reddit.api.reddit.Reddit
import com.veyndan.paper.reddit.databinding.FragmentFilterBinding
class FilterFragment : DialogFragment() {
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val binding: FragmentFilterBinding = FragmentFilterBinding.inflate(inflater, container, false)
val fragments: Array<Fragment> = arrayOf(TimePeriodFilterFragment.newInstance(), SubredditFilterFragment.newInstance(), UserFilterFragment.newInstance())
binding.filterDone.clicks()
.subscribe {
val intent: Intent = Intent(context, MainActivity::class.java)
for (fragment in fragments) {
intent.putExtra(Reddit.FILTER, (fragment as Filter).requestFilter())
}
startActivity(intent)
dismiss()
}
val fragmentManager: FragmentManager = childFragmentManager
binding.filterViewPager.adapter = FilterSectionAdapter(fragmentManager, fragments)
binding.filterTabs.setupWithViewPager(binding.filterViewPager)
var tab: TabLayout.Tab = binding.filterTabs.getTabAt(0)!!
tab.setIcon(R.drawable.ic_schedule_black_24dp)
tab = binding.filterTabs.getTabAt(1)!!
tab.text = "r/"
tab = binding.filterTabs.getTabAt(2)!!
tab.setIcon(R.drawable.ic_person_black_24dp)
@ColorInt val colorAccent: Int = ContextCompat.getColor(activity, R.color.colorAccent)
binding.filterTabs.selectionEvents()
.filter { selectionEvent -> selectionEvent.tab().icon != null }
.subscribe { selectionEvent ->
val tab1: TabLayout.Tab = selectionEvent.tab()
val icon: Drawable = tab1.icon!!.mutate()
if (tab1.isSelected) {
icon.setColorFilter(colorAccent, PorterDuff.Mode.SRC_IN)
icon.alpha = 255
} else {
icon.setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_IN)
icon.alpha = (0.54 * 255).toInt()
}
}
return binding.root
}
private class FilterSectionAdapter internal constructor(fm: FragmentManager, private val fragments: Array<Fragment>) : FragmentStatePagerAdapter(fm) {
private val tabCount: Int = fragments.size
override fun getItem(position: Int): Fragment {
return fragments[position]
}
override fun getCount(): Int {
return tabCount
}
}
companion object {
fun newInstance(): FilterFragment {
return FilterFragment()
}
}
}
|
mit
|
f77b4cba805e976c97ca5e1377d02a9f
| 36.882979 | 161 | 0.6574 | 4.987395 | false | false | false | false |
wordpress-mobile/AztecEditor-Android
|
aztec/src/main/kotlin/org/wordpress/aztec/watchers/event/sequence/known/space/API26PrependNewLineOnStyledSpecialTextEvent.kt
|
1
|
4290
|
package org.wordpress.aztec.watchers.event.sequence.known.space
import org.wordpress.aztec.Constants
import org.wordpress.aztec.watchers.event.sequence.EventSequence
import org.wordpress.aztec.watchers.event.sequence.UserOperationEvent
import org.wordpress.aztec.watchers.event.sequence.known.space.steps.TextWatcherEventDeleteText
import org.wordpress.aztec.watchers.event.sequence.known.space.steps.TextWatcherEventInsertText
import org.wordpress.aztec.watchers.event.sequence.known.space.steps.TextWatcherEventInsertTextDelAfter
import org.wordpress.aztec.watchers.event.text.AfterTextChangedEventData
import org.wordpress.aztec.watchers.event.text.TextWatcherEvent
/*
This case implements the behavior observed in https://github.com/wordpress-mobile/AztecEditor-Android/issues/610
special case for block formated text like HEADING, LIST, etc.
*/
class API26PrependNewLineOnStyledSpecialTextEvent : UserOperationEvent() {
init {
// here we populate our model of reference (which is the sequence of events we expect to find)
// note we don' populate the TextWatcherEvents with actual data, but rather we just want
// to instantiate them so we can populate them later and test whether data holds true to their
// validation.
// 1 generic delete, followed by 1 special insert, then 1 generic insert
val builder = TextWatcherEventDeleteText.Builder()
val step1 = builder.build()
val builderStep2 = TextWatcherEventInsertTextDelAfter.Builder()
val step2 = builderStep2.build()
val builderStep3 = TextWatcherEventInsertText.Builder()
val step3 = builderStep3.build()
// add each of the steps that make up for the identified API26InWordSpaceInsertionEvent here
clear()
addSequenceStep(step1)
addSequenceStep(step2)
addSequenceStep(step3)
}
override fun isUserOperationObservedInSequence(sequence: EventSequence<TextWatcherEvent>): ObservedOperationResultType {
/* here check:
If we have 1 delete followed by 2 inserts AND:
1) checking the first BEFORETEXTCHANGED and
2) checking the LAST AFTERTEXTCHANGED
text length is longer by 1, and the item that is now located start of AFTERTEXTCHANGED is a NEWLINE character.
*/
if (this.sequence.size == sequence.size) {
// populate data in our own sequence to be able to run the comparator checks
if (!isUserOperationPartiallyObservedInSequence(sequence)) {
return ObservedOperationResultType.SEQUENCE_NOT_FOUND
}
// ok all events are good individually and match the sequence we want to compare against.
// now let's make sure the BEFORE / AFTER situation is what we are trying to identify
val firstEvent = sequence.first()
val lastEvent = sequence.last()
val midEvent = sequence[1]
// if new text length is equal as original text length
if (firstEvent.beforeEventData.textBefore?.length == lastEvent.afterEventData.textAfter!!.length) {
//but, middle event has a new line at the start index of change
if (midEvent.onEventData.textOn!![midEvent.onEventData.start] == Constants.NEWLINE) {
return ObservedOperationResultType.SEQUENCE_FOUND
}
}
}
return ObservedOperationResultType.SEQUENCE_NOT_FOUND
}
override fun buildReplacementEventWithSequenceData(sequence: EventSequence<TextWatcherEvent>): TextWatcherEvent {
val builder = TextWatcherEventInsertText.Builder()
// here make it all up as a unique event that does the insert as usual, as we'd get it on older APIs
val firstEvent = sequence.first()
val (oldText) = firstEvent.beforeEventData
val indexWhereToInsertNewLine = firstEvent.beforeEventData.start
oldText?.insert(indexWhereToInsertNewLine, Constants.NEWLINE_STRING)
builder.afterEventData = AfterTextChangedEventData(oldText)
val replacementEvent = builder.build()
replacementEvent.insertionStart = indexWhereToInsertNewLine
replacementEvent.insertionLength = 1
return replacementEvent
}
}
|
mpl-2.0
|
c1c15796e0a32bc25d612bd7ac2f8be6
| 45.630435 | 124 | 0.717483 | 4.777283 | false | false | false | false |
valery-labuzhsky/EditorTools
|
IDEA/src/main/java/ksp/kos/ideaplugin/psi/KerboScriptNamedElement.kt
|
2
|
4515
|
package ksp.kos.ideaplugin.psi
import com.intellij.openapi.util.Key
import com.intellij.psi.util.CachedValue
import ksp.kos.ideaplugin.dataflow.FlowParser
import ksp.kos.ideaplugin.dataflow.ReferenceFlow
import ksp.kos.ideaplugin.reference.PsiSelfResolvable
import ksp.kos.ideaplugin.reference.ReferableType
import ksp.kos.ideaplugin.reference.Reference
import ksp.kos.ideaplugin.reference.ReferenceType
import ksp.kos.ideaplugin.reference.context.LocalContext
import com.intellij.psi.PsiElement
import ksp.kos.ideaplugin.reference.*
import ksp.kos.ideaplugin.reference.context.PsiDuality
import java.util.function.Supplier
/**
* Created on 02/01/16.
*
* @author ptasha
*/
interface KerboScriptNamedElement : KerboScriptBase, PsiSelfResolvable {
var type: ReferenceType
// TODO duality can be pure virtual
@JvmDefault
val cachedFlow: ReferenceFlow<*>
get() {
var cached = getUserData(FLOW_KEY)
if (cached == null) {
cached = createCachedValue(Supplier { FlowParser.INSTANCE.apply(this) })
putUserData(FLOW_KEY, cached)
}
return cached.value
}
@JvmDefault
override fun getKingdom(): LocalContext = scope.cachedScope
@JvmDefault
override fun getReferableType(): ReferableType = type.type
@JvmDefault
val isDeclaration: Boolean
get() = type.occurrenceType.isDeclaration
@JvmDefault
override fun resolve(): KerboScriptNamedElement = if (isDeclaration) this else super.resolve()
@JvmDefault
override fun matches(declaration: Reference): Boolean {
val declarationElement = when (declaration) {
is PsiDuality -> declaration.syntax
is KerboScriptNamedElement -> declaration
else -> null
}
return (
// If we're not even dealing with another named element, just kinda ignore it, call it good
declarationElement !is KerboScriptNamedElement
// Otherwise verify it's either global, or a local that's used after the declaration
|| isDeclarationVisibleToUsage(this, declarationElement)
)
}
companion object {
val FLOW_KEY = Key<CachedValue<ReferenceFlow<*>>>("ksp.kos.ideaplugin.semantics")
}
}
private fun isDeclarationVisibleToUsage(usage: PsiElement, declaration: KerboScriptNamedElement?): Boolean {
if (declaration?.type?.occurrenceType != OccurrenceType.LOCAL) {
// Consider globals to always be visible
return true
}
if (usage.containingFile != declaration.containingFile) {
// The declaration is local, but they don't share a file, no way it's visible.
return false
}
// If usage is inside a function declaration (relative to the common ancestor) then all bets on ordering are
// off, and we'll let this fly.
val hasFunctionBetweenUsageAndDeclaration =
doesTypeExistBetweenCurrentAndClosestCommonAncestor<KerboScriptDeclareFunctionClause>(
current = usage,
other = declaration
)
if (hasFunctionBetweenUsageAndDeclaration) {
return true
}
// Otherwise, make sure the declaration is before the usage.
return declaration.textOffset <= usage.textOffset
}
/**
* Finds the common ancestor of the two elements, then returns whether an element of the given type exists between
* the "current" node and that common ancestor.
*/
private inline fun <reified T : PsiElement> doesTypeExistBetweenCurrentAndClosestCommonAncestor(
current: PsiElement,
other: PsiElement,
): Boolean {
val currentAncestors = getAncestors(current)
val otherAncestors = getAncestors(other)
val closestCommonAncestorIndex =
otherAncestors.zip(currentAncestors).indexOfLast { (a, b) -> a == b }
if (closestCommonAncestorIndex == -1) {
// They don't even share an ancestor, so the type can't exist between them.
return false
}
val closestTypeIndex = currentAncestors.indexOfLast { it is T }
return closestCommonAncestorIndex < closestTypeIndex
}
/**
* Returns all ancestors of the element, with the oldest ancestor first and the element itself last.
*/
private fun getAncestors(element: PsiElement): List<PsiElement> {
val ancestors = mutableListOf(element)
var next = element.parent
while (next != null) {
ancestors.add(next)
next = next.parent
}
return ancestors.reversed()
}
|
gpl-3.0
|
528fbe7f186b64f649c224a50a478d14
| 34 | 114 | 0.69546 | 4.569838 | false | false | false | false |
felipebz/sonar-plsql
|
zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/UnnecessaryAliasInQueryCheck.kt
|
1
|
3451
|
/**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plsqlopen.checks
import com.felipebz.flr.api.AstNode
import com.felipebz.flr.api.AstNodeType
import org.sonar.plugins.plsqlopen.api.DmlGrammar
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.annotations.*
import java.util.*
@Rule(priority = Priority.MINOR)
@ConstantRemediation("1min")
@RuleInfo(scope = RuleInfo.Scope.ALL)
class UnnecessaryAliasInQueryCheck : AbstractBaseCheck() {
@RuleProperty(key = "acceptedLength", defaultValue = "" + DEFAULT_ACCEPTED_LENGTH)
var acceptedLength = DEFAULT_ACCEPTED_LENGTH
private val dmlStatements = arrayOf<AstNodeType>(
DmlGrammar.QUERY_BLOCK,
PlSqlGrammar.UPDATE_STATEMENT,
PlSqlGrammar.DELETE_STATEMENT)
override fun init() {
subscribeTo(*dmlStatements)
}
override fun visitNode(node: AstNode) {
if (node.hasAncestor(*dmlStatements)) {
// if the current node is inside another DML statement (i.e. subquery), the node should be
// ignored because it is considered in the analysis of the outer statement
return
}
val tableReferences = hashMapOf<String, MutableList<TableReference>>()
for (fromClause in node.getDescendants(DmlGrammar.DML_TABLE_EXPRESSION_CLAUSE)) {
val table = fromClause.getFirstChildOrNull(DmlGrammar.TABLE_REFERENCE)
val alias = fromClause.getFirstChildOrNull(DmlGrammar.ALIAS)
if (table != null) {
tableReferences.getOrPut(table.tokenOriginalValue.lowercase(Locale.getDefault())) { mutableListOf() }
.add(TableReference(table, alias))
}
}
for (references in tableReferences.values) {
checkReference(references)
}
}
private fun checkReference(references: MutableList<TableReference>) {
if (references.size == 1) {
val reference: TableReference = references[0]
var alias: String? = null
if (reference.alias != null) {
alias = reference.alias.tokenOriginalValue
}
if (alias != null && reference.alias != null && alias.length < acceptedLength) {
addIssue(reference.alias, getLocalizedMessage(),
reference.table.tokenOriginalValue,
reference.alias.tokenOriginalValue)
}
}
}
internal class TableReference(val table: AstNode, val alias: AstNode?)
companion object {
private const val DEFAULT_ACCEPTED_LENGTH = 3
}
}
|
lgpl-3.0
|
503caca2fdc74f51f9e1bf90c3b64d18
| 36.107527 | 117 | 0.675746 | 4.613636 | false | false | false | false |
kaskasi/VocabularyTrainer
|
app/src/main/java/de/fluchtwege/vocabulary/lessons/LessonAdapter.kt
|
1
|
1551
|
package de.fluchtwege.vocabulary.lessons
import android.content.Context
import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import de.fluchtwege.vocabulary.databinding.ItemLessonBinding
import de.fluchtwege.vocabulary.questions.QuestionsActivity
import de.fluchtwege.vocabulary.questions.QuestionsFragment
class LessonAdapter(val viewModel: LessonsViewModel, val context: Context) : RecyclerView.Adapter<LessonAdapter.LessonViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LessonViewHolder {
val inflater = LayoutInflater.from(context)
val binding = ItemLessonBinding.inflate(inflater, parent, false)
return LessonViewHolder(binding)
}
override fun onBindViewHolder(holder: LessonViewHolder, position: Int) {
val lessonViewModel = viewModel.getLessonViewModel(position)
holder.binding.viewModel = lessonViewModel
holder.binding.root.setOnClickListener { openQuestions(position) }
}
private fun openQuestions(position: Int) {
val openQuestions = Intent(context, QuestionsActivity::class.java)
val lessonName = viewModel.getLessonName(position)
openQuestions.putExtra(QuestionsFragment.KEY_LESSON_NAME, lessonName)
context.startActivity(openQuestions)
}
override fun getItemCount() = viewModel.getNumberOfLessons()
class LessonViewHolder(val binding: ItemLessonBinding) : RecyclerView.ViewHolder(binding.root)
}
|
mit
|
180d2bc03434879ef0cb8f2863257ba0
| 42.111111 | 133 | 0.782076 | 4.846875 | false | false | false | false |
mapbox/mapbox-java
|
services-cli/src/main/kotlin/com.mapbox.services.cli/MapboxJavaCli.kt
|
1
|
1881
|
package com.mapbox.services.cli
import com.google.gson.Gson
import com.mapbox.services.cli.validator.DirectionsResponseValidator
import org.apache.commons.cli.CommandLine
import org.apache.commons.cli.DefaultParser
import org.apache.commons.cli.HelpFormatter
import org.apache.commons.cli.Option
import org.apache.commons.cli.Options
import org.apache.commons.cli.ParseException
/**
* Entry point for the command line interface.
*/
object MapboxJavaCli {
private const val COMMAND_FILE_INPUT = "f"
private const val COMMAND_HELP = "h"
@JvmStatic
fun main(args: Array<String>) {
val options = Options()
.addOption(Option.builder(COMMAND_HELP)
.longOpt("help")
.desc("Shows this help message")
.build())
.addOption(Option.builder(COMMAND_FILE_INPUT)
.longOpt("file")
.hasArg(true)
.desc("Path to a json file or directory")
.required()
.build())
try {
val commandLine = DefaultParser().parse(options, args)
parseCommands(commandLine, options)
} catch (pe: ParseException) {
println(pe.message)
printHelp(options)
}
}
private fun parseCommands(commandLine: CommandLine, options: Options) {
if (commandLine.hasOption(COMMAND_HELP)) {
printHelp(options)
}
val fileInput = commandLine.getOptionValue(COMMAND_FILE_INPUT)
val directionsResponseValidator = DirectionsResponseValidator()
val results = directionsResponseValidator.parse(fileInput)
print(Gson().toJson(results))
}
private fun printHelp(options: Options) {
val syntax = "java -jar services-cli/build/libs/services-cli-all.jar"
HelpFormatter().printHelp(syntax, options)
}
}
|
mit
|
5953557f2a7e1eb275a25c6e560b758e
| 31.431034 | 77 | 0.640617 | 4.405152 | false | false | false | false |
jiaminglu/kotlin-native
|
backend.native/tests/runtime/memory/var4.kt
|
1
|
341
|
fun main(args : Array<String>) {
var x = Error()
for (i in 0..1) {
val c = Error()
if (i == 0) x = c
}
// x refcount is 1.
try {
try {
throw x
} finally {
x = Error()
}
} catch (e: Error) {
e.use()
}
}
fun Any?.use() {
var x = this
}
|
apache-2.0
|
89450be20e7d5e41cedf2afbf4b05dae
| 13.25 | 32 | 0.360704 | 3.247619 | false | false | false | false |
andrewoma/kwery
|
example/src/main/kotlin/com/github/andrewoma/kwery/example/film/dao/LanguageDao.kt
|
1
|
2015
|
/*
* Copyright (c) 2015 Andrew O'Malley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.andrewoma.kwery.example.film.dao
import com.github.andrewoma.kwery.core.Session
import com.github.andrewoma.kwery.mapper.AbstractDao
import com.github.andrewoma.kwery.mapper.Table
import com.github.andrewoma.kwery.mapper.Value
import com.github.andrewoma.kwery.mapper.VersionedWithInt
import com.github.andrewoma.kwery.example.film.model.Language as L
object languageTable : Table<L, Int>("language", tableConfig), VersionedWithInt {
// @formatter:off
val Id by col(L::id, id = true)
val Name by col(L::name)
val Version by col(L::version, version = true)
// @formatter:on
override fun idColumns(id: Int) = setOf(Id of id)
override fun create(value: Value<L>) = L(value.of(Id), value.of(Name), value.of(Version))
}
class LanguageDao(session: Session) : AbstractDao<L, Int>(session, languageTable, { it.id }, "int", defaultId = 0)
|
mit
|
56e5c98fa77eca7bcf97f249be774c04
| 45.860465 | 114 | 0.747891 | 3.966535 | false | false | false | false |
patm1987/lwjgl_test
|
src/main/kotlin/com/pux0r3/lwjgltest/HalfEdgeModel.kt
|
1
|
10141
|
package com.pux0r3.lwjgltest
import org.joml.Vector3f
import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GL15.*
import org.lwjgl.opengl.GL20.glVertexAttribPointer
import org.lwjgl.opengl.GL32.GL_TRIANGLES_ADJACENCY
import org.lwjgl.system.MemoryStack.stackPush
import org.lwjgl.system.NativeResource
fun halfEdgeModel(cb: HalfEdgeModel.Builder.() -> Unit): HalfEdgeModel {
val builder = HalfEdgeModel.Builder()
builder.cb()
return builder.build()
}
class HalfEdgeModel(val edges: Array<HalfEdge>, val vertices: Array<Vertex>, val faces: Array<Face>) : NativeResource {
val vertexBufferObject: Int = glGenBuffers()
// TODO: one or the other. I don't need indices and adjacencies!
val indexBufferObject: Int = glGenBuffers()
val adjacencyBufferObject: Int = glGenBuffers()
val transform = Transform()
/**
* This object allows a shader (or any caller) to render this model. It is made private so that you MUST invoke [use]
* to bind the proper vertex attributes
*/
private val activeModel = ActiveModel()
init {
stackPush().use {
// write each edge into an index buffer
val indexBuffer = it.mallocShort(edges.size)
edges.forEach { halfEdge ->
indexBuffer.put(halfEdge.vertexIndex.toShort())
}
indexBuffer.flip()
// build an adjacency triangle list
val adjacencyIndexBuffer = it.mallocShort(edges.size * 2)
edges.forEach { halfEdge ->
adjacencyIndexBuffer.put(halfEdge.vertexIndex.toShort())
if (halfEdge.oppositeEdgeIndex != INVALID_EDGE_INDEX) {
val oppositeEdge = oppositeEdge(halfEdge)
assert(oppositeEdge(oppositeEdge) == halfEdge)
val outlier = nextEdge(nextEdge(oppositeEdge))
assert(!vertexInFace(outlier.vertexIndex, halfEdge.faceIndex))
adjacencyIndexBuffer.put(outlier.vertexIndex.toShort())
} else {
adjacencyIndexBuffer.put(halfEdge.vertexIndex.toShort())
}
}
adjacencyIndexBuffer.flip()
// write each triangle into an attribute buffer
val vertexBuffer = it.malloc(Vertex.VERTEX_SIZE * vertices.size)
vertices.forEachIndexed { index, vertex ->
val startIndex = index * Vertex.VERTEX_SIZE
vertex.position.get(startIndex, vertexBuffer)
vertex.normal.get(startIndex + Vertex.VECTOR_3_SIZE, vertexBuffer)
vertexBuffer.putInt(startIndex + 2 * Vertex.VECTOR_3_SIZE, vertex.edgeIndex)
}
use {
glBufferData(GL_ARRAY_BUFFER, vertexBuffer, GL_STATIC_DRAW)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexBuffer, GL_STATIC_DRAW)
}
useAdjacency {
// TODO: I'm double binding GL_ARRAY_BUFFER, fix this!
glBufferData(GL_ELEMENT_ARRAY_BUFFER, adjacencyIndexBuffer, GL_STATIC_DRAW)
}
}
}
fun oppositeEdge(edge: HalfEdge): HalfEdge {
return edges[edge.oppositeEdgeIndex]
}
fun nextEdge(edge: HalfEdge): HalfEdge {
return edges[edge.nextEdgeIndex]
}
fun vertexInFace(vertexIndex: Int, faceIndex: Int): Boolean {
val startEdge = faces[faceIndex].halfEdgeIndex
var currentEdge = startEdge
do {
if (edges[currentEdge].vertexIndex == vertexIndex) {
return true
}
currentEdge = edges[currentEdge].nextEdgeIndex
} while (currentEdge != startEdge)
return false
}
fun use(callback: HalfEdgeModel.ActiveModel.() -> Unit) {
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferObject)
activeModel.callback()
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
glBindBuffer(GL_ARRAY_BUFFER, 0)
}
fun useAdjacency(callback: HalfEdgeModel.ActiveModel.() -> Unit) {
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, adjacencyBufferObject)
activeModel.callback()
glBindBuffer(GL_ARRAY_BUFFER, 0)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
}
override fun free() {
glDeleteBuffers(vertexBufferObject)
glDeleteBuffers(indexBufferObject)
}
/**
* Class to aid in rendering a model. Even though the model has some number of attributes, a shader might not want
* to use all of them. When you call [use], you are operating as a function in this class to guarantee that the
* buffers have been properly bound
*/
inner class ActiveModel {
fun loadPositions(positionAttributeLocation: Int) {
glVertexAttribPointer(positionAttributeLocation, 3, GL_FLOAT, false, Vertex.VERTEX_SIZE, 0)
}
fun loadNormals(normalAttributeLocation: Int) {
glVertexAttribPointer(normalAttributeLocation, 3, GL_FLOAT, true, Vertex.VERTEX_SIZE, Vertex.VECTOR_3_SIZE.toLong())
}
fun drawElements() {
glDrawElements(GL_TRIANGLES, edges.size, GL_UNSIGNED_SHORT, 0)
}
fun drawElementsAdjacency() {
glDrawElements(GL_TRIANGLES_ADJACENCY, edges.size * 2, GL_UNSIGNED_SHORT, 0)
}
}
data class HalfEdge(val vertexIndex: Int, val nextEdgeIndex: Int, val oppositeEdgeIndex: Int, val faceIndex: Int)
data class Vertex(val position: Vector3f, val normal: Vector3f, val edgeIndex: Int) {
companion object {
const val FLOAT_SIZE = 4
const val INT_SIZE = 4
const val VECTOR_3_SIZE = 3 * FLOAT_SIZE
const val VERTEX_SIZE = 2 * VECTOR_3_SIZE + INT_SIZE
}
}
data class Face(val halfEdgeIndex: Int)
class Builder {
val vertices = mutableListOf<VertexBuilder>()
val faces = mutableListOf<FaceBuilder>()
fun vertex(cb: VertexBuilder.() -> Unit): Builder {
val builder = VertexBuilder()
builder.cb()
vertices.add(builder)
return this
}
fun face(i0: Int, i1: Int, i2: Int): Builder {
val builder = FaceBuilder(i0, i1, i2)
faces.add(builder)
return this
}
fun build(): HalfEdgeModel {
val edges = mutableListOf<EdgeBuilder>()
// create the face array, also generating the edges
val faceArray: Array<Face> = faces.mapIndexed { index, faceBuilder ->
// the index of the first edge
val startIndex = edges.size
// build the edges
val e0 = EdgeBuilder(faceBuilder.v0, index, startIndex + 1)
val e1 = EdgeBuilder(faceBuilder.v1, index, startIndex + 2)
val e2 = EdgeBuilder(faceBuilder.v2, index, startIndex)
// cache the edges in the edge list
edges.add(e0)
edges.add(e1)
edges.add(e2)
// add this edge to the vertex list
vertices[faceBuilder.v0].edges.add(startIndex)
vertices[faceBuilder.v1].edges.add(startIndex + 1)
vertices[faceBuilder.v2].edges.add(startIndex + 2)
// create the face
Face(startIndex)
}.toTypedArray()
// generate edges
val edgeArray: Array<HalfEdge> = edges.mapIndexed { index, edgeBuilder ->
// the edge opposite us starts at the vertex our next edge starts at and ends at our vertex
val oppositeStartVertexIndex = edges[edgeBuilder.nextEdgeIndex].vertexIndex
val oppositeStartVertex = vertices[oppositeStartVertexIndex]
val oppositeEdgeIndex = oppositeStartVertex.edges.firstOrNull { edgeIndex ->
val testEdge = edges[edgeIndex]
val testNextEdge = edges[testEdge.nextEdgeIndex]
testNextEdge.vertexIndex == edgeBuilder.vertexIndex
} ?: INVALID_EDGE_INDEX
assert(index != oppositeEdgeIndex)
HalfEdge(edgeBuilder.vertexIndex, edgeBuilder.nextEdgeIndex, oppositeEdgeIndex, edgeBuilder.faceIndex)
}.toTypedArray()
// vertices should be ready for generation
val vertexArray: Array<Vertex> = vertices.map { vertexBuilder ->
assert(!vertexBuilder.edges.isEmpty())
Vertex(vertexBuilder.position, vertexBuilder.normal, vertexBuilder.edges.first())
}.toTypedArray()
// make sure all the edges belong to this triangle and their opposites don't
assert(faceArray.all { face ->
val startEdgeIndex = face.halfEdgeIndex
var edge = edgeArray[startEdgeIndex]
while(edge.nextEdgeIndex != startEdgeIndex) {
if (faceArray[edge.faceIndex] != face) {
return@all false
}
if (edge.oppositeEdgeIndex != INVALID_EDGE_INDEX && faceArray[edgeArray[edge.oppositeEdgeIndex].faceIndex] == face) {
return@all false
}
edge = edgeArray[edge.nextEdgeIndex]
}
return@all true
})
return HalfEdgeModel(edgeArray, vertexArray, faceArray)
}
}
class VertexBuilder {
var position: Vector3f = Vector3f()
var normal: Vector3f = Vector3f()
val edges = mutableListOf<Int>()
}
class FaceBuilder(val v0: Int, val v1: Int, val v2: Int)
/**
* @param vertexIndex the index of the vertex that starts this edge
* @param faceIndex the face that this edge belongs to
* @param nextEdgeIndex the next edge in the list
*/
class EdgeBuilder(val vertexIndex: Int, val faceIndex: Int, val nextEdgeIndex: Int)
companion object {
const val INVALID_EDGE_INDEX = -1
}
}
|
mit
|
bd4c2ddffed2dd6d47457cb64ef7aa6b
| 38.158301 | 137 | 0.608323 | 4.541424 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.