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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/AutoImportProjectTracker.kt | 1 | 15069 | // 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.openapi.externalSystem.autoimport
import com.intellij.ide.file.BatchFileChangeListener
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.StoragePathMacros.CACHE_FILE
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemModificationType.*
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemProjectTrackerSettings.AutoReloadType
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemRefreshStatus.SUCCESS
import com.intellij.openapi.externalSystem.autoimport.update.PriorityEatUpdate
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.observable.operation.core.AtomicOperationTrace
import com.intellij.openapi.observable.operation.core.isOperationInProgress
import com.intellij.openapi.observable.operation.core.whenOperationFinished
import com.intellij.openapi.observable.operation.core.whenOperationStarted
import com.intellij.openapi.observable.properties.*
import com.intellij.openapi.observable.util.whenDisposed
import com.intellij.openapi.progress.impl.CoreProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.registry.Registry
import com.intellij.util.LocalTimeCounter.currentTime
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.ui.update.MergingUpdateQueue
import org.jetbrains.annotations.TestOnly
import java.util.concurrent.ConcurrentHashMap
import kotlin.streams.asStream
@State(name = "ExternalSystemProjectTracker", storages = [Storage(CACHE_FILE)])
class AutoImportProjectTracker(
private val project: Project
) : ExternalSystemProjectTracker,
Disposable.Default,
PersistentStateComponent<AutoImportProjectTracker.State> {
private val serviceDisposable: Disposable = this
private val settings get() = AutoImportProjectTrackerSettings.getInstance(project)
private val notificationAware get() = ExternalSystemProjectNotificationAware.getInstance(project)
private val projectStates = ConcurrentHashMap<State.Id, State.Project>()
private val projectDataMap = ConcurrentHashMap<ExternalSystemProjectId, ProjectData>()
private val projectChangeOperation = AtomicOperationTrace(name = "Project change operation")
private val projectReloadOperation = AtomicOperationTrace(name = "Project reload operation")
private val dispatcher = MergingUpdateQueue("AutoImportProjectTracker.dispatcher", 300, false, null, serviceDisposable)
private val backgroundExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor("AutoImportProjectTracker.backgroundExecutor", 1)
private fun createProjectChangesListener() =
object : ProjectBatchFileChangeListener(project) {
override fun batchChangeStarted(activityName: String?) =
projectChangeOperation.traceStart()
override fun batchChangeCompleted() =
projectChangeOperation.traceFinish()
}
private fun createProjectReloadListener(projectData: ProjectData) =
object : ExternalSystemProjectListener {
override fun onProjectReloadStart() {
projectReloadOperation.traceStart()
projectData.status.markSynchronized(currentTime())
projectData.isActivated = true
}
override fun onProjectReloadFinish(status: ExternalSystemRefreshStatus) {
if (status != SUCCESS) projectData.status.markBroken(currentTime())
projectReloadOperation.traceFinish()
}
}
override fun scheduleProjectRefresh() {
LOG.debug("Schedule project reload", Throwable())
schedule(priority = 0, dispatchIterations = 1) { reloadProject(smart = false) }
}
override fun scheduleChangeProcessing() {
LOG.debug("Schedule change processing")
schedule(priority = 1, dispatchIterations = 1) { processChanges() }
}
/**
* ```
* dispatcher.mergingTimeSpan = 300 ms
* dispatchIterations = 9
* We already dispatched processChanges
* So delay is equal to (1 + 9) * 300 ms = 3000 ms = 3 s
* ```
*/
private fun scheduleDelayedSmartProjectReload() {
LOG.debug("Schedule delayed project reload")
schedule(priority = 2, dispatchIterations = 9) { reloadProject(smart = true) }
}
private fun schedule(priority: Int, dispatchIterations: Int, action: () -> Unit) {
dispatcher.queue(PriorityEatUpdate(priority) {
if (dispatchIterations - 1 > 0) {
schedule(priority, dispatchIterations - 1, action)
}
else {
action()
}
})
}
private fun processChanges() {
when (settings.autoReloadType) {
AutoReloadType.ALL -> when (getModificationType()) {
INTERNAL -> scheduleDelayedSmartProjectReload()
EXTERNAL -> scheduleDelayedSmartProjectReload()
UNKNOWN -> updateProjectNotification()
}
AutoReloadType.SELECTIVE -> when (getModificationType()) {
INTERNAL -> updateProjectNotification()
EXTERNAL -> scheduleDelayedSmartProjectReload()
UNKNOWN -> updateProjectNotification()
}
AutoReloadType.NONE -> updateProjectNotification()
}
}
private fun reloadProject(smart: Boolean) {
LOG.debug("Incremental project reload")
val projectsToReload = projectDataMap.values
.filter { (!smart || it.isActivated) && !it.isUpToDate() }
if (isDisabledAutoReload() || projectsToReload.isEmpty()) {
LOG.debug("Skipped all projects reload")
updateProjectNotification()
return
}
for (projectData in projectsToReload) {
LOG.debug("${projectData.projectAware.projectId.debugName}: Project reload")
val hasUndefinedModifications = !projectData.status.isUpToDate()
val settingsContext = projectData.settingsTracker.getSettingsContext()
val context = ProjectReloadContext(!smart, hasUndefinedModifications, settingsContext)
projectData.projectAware.reloadProject(context)
}
}
private fun updateProjectNotification() {
LOG.debug("Notification status update")
val isDisabledAutoReload = isDisabledAutoReload()
for ((projectId, data) in projectDataMap) {
when (isDisabledAutoReload || data.isUpToDate()) {
true -> notificationAware.notificationExpire(projectId)
else -> notificationAware.notificationNotify(data.projectAware)
}
}
}
private fun isDisabledAutoReload(): Boolean {
return Registry.`is`("external.system.auto.import.disabled") ||
!isEnabledAutoReload ||
projectChangeOperation.isOperationInProgress() ||
projectReloadOperation.isOperationInProgress()
}
private fun getModificationType(): ExternalSystemModificationType {
return projectDataMap.values
.asSequence()
.map { it.getModificationType() }
.asStream()
.reduce(ProjectStatus::merge)
.orElse(UNKNOWN)
}
override fun register(projectAware: ExternalSystemProjectAware) {
val projectId = projectAware.projectId
val projectIdName = projectId.debugName
val activationProperty = AtomicBooleanProperty(false)
val projectStatus = ProjectStatus(debugName = projectIdName)
val parentDisposable = Disposer.newDisposable(serviceDisposable, projectIdName)
val settingsTracker = ProjectSettingsTracker(project, this, backgroundExecutor, projectAware, parentDisposable)
val projectData = ProjectData(projectStatus, activationProperty, projectAware, settingsTracker, parentDisposable)
projectDataMap[projectId] = projectData
settingsTracker.beforeApplyChanges(parentDisposable) { projectReloadOperation.traceStart() }
settingsTracker.afterApplyChanges(parentDisposable) { projectReloadOperation.traceFinish() }
activationProperty.whenPropertySet(parentDisposable) { LOG.debug("$projectIdName is activated") }
activationProperty.whenPropertySet(parentDisposable) { scheduleChangeProcessing() }
projectAware.subscribe(createProjectReloadListener(projectData), parentDisposable)
parentDisposable.whenDisposed { notificationAware.notificationExpire(projectId) }
loadState(projectId, projectData)
}
override fun activate(id: ExternalSystemProjectId) {
val projectData = projectDataMap(id) { get(it) } ?: return
projectData.isActivated = true
}
override fun remove(id: ExternalSystemProjectId) {
val projectData = projectDataMap.remove(id) ?: return
Disposer.dispose(projectData.parentDisposable)
}
override fun markDirty(id: ExternalSystemProjectId) {
val projectData = projectDataMap(id) { get(it) } ?: return
projectData.status.markDirty(currentTime())
}
override fun markDirtyAllProjects() {
val modificationTimeStamp = currentTime()
projectDataMap.forEach { it.value.status.markDirty(modificationTimeStamp) }
}
private fun projectDataMap(
id: ExternalSystemProjectId,
action: MutableMap<ExternalSystemProjectId, ProjectData>.(ExternalSystemProjectId) -> ProjectData?
): ProjectData? {
val projectData = projectDataMap.action(id)
if (projectData == null) {
LOG.warn(String.format("Project isn't registered by id=%s", id), Throwable())
}
return projectData
}
override fun getState(): State {
val projectSettingsTrackerStates = projectDataMap.asSequence()
.map { (id, data) -> id.getState() to data.getState() }
.toMap()
return State(projectSettingsTrackerStates)
}
override fun loadState(state: State) {
projectStates.putAll(state.projectSettingsTrackerStates)
projectDataMap.forEach { (id, data) -> loadState(id, data) }
}
private fun loadState(projectId: ExternalSystemProjectId, projectData: ProjectData) {
val projectState = projectStates.remove(projectId.getState())
val settingsTrackerState = projectState?.settingsTracker
if (settingsTrackerState == null || projectState.isDirty) {
projectData.status.markDirty(currentTime(), EXTERNAL)
scheduleChangeProcessing()
return
}
projectData.settingsTracker.loadState(settingsTrackerState)
projectData.settingsTracker.refreshChanges()
}
override fun initializeComponent() {
LOG.debug("Project tracker initialization")
ApplicationManager.getApplication().messageBus.connect(serviceDisposable)
.subscribe(BatchFileChangeListener.TOPIC, createProjectChangesListener())
dispatcher.setRestartTimerOnAdd(true)
dispatcher.isPassThrough = !asyncChangesProcessingProperty.get()
dispatcher.activate()
}
@TestOnly
fun getActivatedProjects() =
projectDataMap.values
.filter { it.isActivated }
.map { it.projectAware.projectId }
.toSet()
@TestOnly
fun setDispatcherMergingSpan(delay: Int) {
dispatcher.setMergingTimeSpan(delay)
}
init {
projectReloadOperation.whenOperationStarted(serviceDisposable) { notificationAware.notificationExpire() }
projectReloadOperation.whenOperationFinished(serviceDisposable) { scheduleChangeProcessing() }
projectChangeOperation.whenOperationStarted(serviceDisposable) { notificationAware.notificationExpire() }
projectChangeOperation.whenOperationFinished(serviceDisposable) { scheduleChangeProcessing() }
settings.autoReloadTypeProperty.whenPropertyChanged(serviceDisposable) { scheduleChangeProcessing() }
asyncChangesProcessingProperty.whenPropertyChanged(serviceDisposable) { dispatcher.isPassThrough = !it }
projectReloadOperation.whenOperationStarted(serviceDisposable) { LOG.debug("Detected project reload start event") }
projectReloadOperation.whenOperationFinished(serviceDisposable) { LOG.debug("Detected project reload finish event") }
projectChangeOperation.whenOperationStarted(serviceDisposable) { LOG.debug("Detected project change start event") }
projectChangeOperation.whenOperationFinished(serviceDisposable) { LOG.debug("Detected project change finish event") }
}
private fun ProjectData.getState() = State.Project(status.isDirty(), settingsTracker.getState())
private fun ProjectSystemId.getState() = id
private fun ExternalSystemProjectId.getState() = State.Id(systemId.getState(), externalProjectPath)
private data class ProjectData(
val status: ProjectStatus,
val activationProperty: MutableBooleanProperty,
val projectAware: ExternalSystemProjectAware,
val settingsTracker: ProjectSettingsTracker,
val parentDisposable: Disposable
) {
var isActivated by activationProperty
fun isUpToDate() = status.isUpToDate() && settingsTracker.isUpToDate()
fun getModificationType(): ExternalSystemModificationType {
return ProjectStatus.merge(status.getModificationType(), settingsTracker.getModificationType())
}
}
data class State(var projectSettingsTrackerStates: Map<Id, Project> = emptyMap()) {
data class Id(var systemId: String? = null, var externalProjectPath: String? = null)
data class Project(
var isDirty: Boolean = false,
var settingsTracker: ProjectSettingsTracker.State? = null
)
}
private data class ProjectReloadContext(
override val isExplicitReload: Boolean,
override val hasUndefinedModifications: Boolean,
override val settingsFilesContext: ExternalSystemSettingsFilesReloadContext
) : ExternalSystemProjectReloadContext
companion object {
val LOG = Logger.getInstance("#com.intellij.openapi.externalSystem.autoimport")
@TestOnly
@JvmStatic
fun getInstance(project: Project): AutoImportProjectTracker {
return ExternalSystemProjectTracker.getInstance(project) as AutoImportProjectTracker
}
private val enableAutoReloadProperty = AtomicBooleanProperty(
!ApplicationManager.getApplication().isUnitTestMode
)
private val asyncChangesProcessingProperty = AtomicBooleanProperty(
!ApplicationManager.getApplication().isHeadlessEnvironment
|| CoreProgressManager.shouldKeepTasksAsynchronousInHeadlessMode()
)
private val isEnabledAutoReload by enableAutoReloadProperty
val isAsyncChangesProcessing get() = asyncChangesProcessingProperty.get()
/**
* Enables auto-import in tests
* Note: project tracker automatically enabled out of tests
*/
@TestOnly
@JvmStatic
fun enableAutoReloadInTests(parentDisposable: Disposable) {
enableAutoReloadProperty.set(true, parentDisposable)
}
@TestOnly
@JvmStatic
fun enableAsyncAutoReloadInTests(parentDisposable: Disposable) {
asyncChangesProcessingProperty.set(true, parentDisposable)
}
private fun <T> ObservableMutableProperty<T>.set(value: T, parentDisposable: Disposable) {
val oldValue = get()
set(value)
parentDisposable.whenDisposed {
set(oldValue)
}
}
}
} | apache-2.0 | df1a09944a301d462a6700b045509080 | 39.951087 | 158 | 0.763753 | 5.438109 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/breakpoints/KotlinFieldBreakpointType.kt | 1 | 8339 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
// The package directive doesn't match the file location to prevent API breakage
package org.jetbrains.kotlin.idea.debugger.breakpoints
import com.intellij.debugger.JavaDebuggerBundle
import com.intellij.debugger.ui.breakpoints.Breakpoint
import com.intellij.debugger.ui.breakpoints.BreakpointManager
import com.intellij.debugger.ui.breakpoints.BreakpointWithHighlighter
import com.intellij.debugger.ui.breakpoints.JavaBreakpointType
import com.intellij.icons.AllIcons
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.xdebugger.XDebuggerManager
import com.intellij.xdebugger.breakpoints.XBreakpoint
import com.intellij.xdebugger.breakpoints.XLineBreakpoint
import com.intellij.xdebugger.breakpoints.XLineBreakpointType
import com.intellij.xdebugger.breakpoints.ui.XBreakpointCustomPropertiesPanel
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.classes.KtLightClassForSourceDeclaration
import org.jetbrains.kotlin.idea.debugger.core.KotlinDebuggerCoreBundle
import org.jetbrains.kotlin.idea.debugger.core.breakpoints.*
import org.jetbrains.kotlin.idea.debugger.core.breakpoints.dialog.AddFieldBreakpointDialog
import com.intellij.openapi.application.runWriteAction
import org.jetbrains.kotlin.psi.KtDeclarationContainer
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtProperty
import javax.swing.Icon
import javax.swing.JComponent
class KotlinFieldBreakpointType :
JavaBreakpointType<KotlinPropertyBreakpointProperties>,
XLineBreakpointType<KotlinPropertyBreakpointProperties>(
"kotlin-field", KotlinDebuggerCoreBundle.message("property.watchpoint.tab.title")
),
KotlinBreakpointType
{
override fun createJavaBreakpoint(
project: Project,
breakpoint: XBreakpoint<KotlinPropertyBreakpointProperties>
): Breakpoint<KotlinPropertyBreakpointProperties> {
return KotlinFieldBreakpoint(project, breakpoint)
}
override fun canPutAt(file: VirtualFile, line: Int, project: Project): Boolean {
return isBreakpointApplicable(file, line, project) { element ->
when (element) {
is KtProperty -> ApplicabilityResult.definitely(!element.isLocal)
is KtParameter -> ApplicabilityResult.definitely(element.hasValOrVar())
else -> ApplicabilityResult.UNKNOWN
}
}
}
override fun getPriority() = 120
override fun createBreakpointProperties(file: VirtualFile, line: Int): KotlinPropertyBreakpointProperties {
return KotlinPropertyBreakpointProperties()
}
override fun addBreakpoint(project: Project, parentComponent: JComponent?): XLineBreakpoint<KotlinPropertyBreakpointProperties>? {
var result: XLineBreakpoint<KotlinPropertyBreakpointProperties>? = null
val dialog = object : AddFieldBreakpointDialog(project) {
override fun validateData(): Boolean {
val className = className
if (className.isEmpty()) {
reportError(project, JavaDebuggerBundle.message("error.field.breakpoint.class.name.not.specified"))
return false
}
val psiClass = JavaPsiFacade.getInstance(project).findClass(className, GlobalSearchScope.allScope(project))
if (psiClass !is KtLightClass) {
reportError(project, KotlinDebuggerCoreBundle.message("property.watchpoint.error.couldnt.find.0.class", className))
return false
}
val fieldName = fieldName
if (fieldName.isEmpty()) {
reportError(project, JavaDebuggerBundle.message("error.field.breakpoint.field.name.not.specified"))
return false
}
result = when (psiClass) {
is KtLightClassForFacade -> psiClass.files.asSequence().mapNotNull {
createBreakpointIfPropertyExists(it, it, className, fieldName)
}.firstOrNull()
is KtLightClassForSourceDeclaration -> {
val ktClassOrObject = psiClass.kotlinOrigin
createBreakpointIfPropertyExists(ktClassOrObject, ktClassOrObject.containingKtFile, className, fieldName)
}
else -> null
}
if (result == null) {
reportError(
project,
JavaDebuggerBundle.message("error.field.breakpoint.field.not.found", className, fieldName, fieldName)
)
}
return result != null
}
}
dialog.show()
return result
}
private fun createBreakpointIfPropertyExists(
declaration: KtDeclarationContainer,
file: KtFile,
className: String,
fieldName: String
): XLineBreakpoint<KotlinPropertyBreakpointProperties>? {
val project = file.project
val property = declaration.declarations.firstOrNull { it is KtProperty && it.name == fieldName } ?: return null
val document = PsiDocumentManager.getInstance(project).getDocument(file) ?: return null
val line = document.getLineNumber(property.textOffset)
return runWriteAction {
XDebuggerManager.getInstance(project).breakpointManager.addLineBreakpoint(
this,
file.virtualFile.url,
line,
KotlinPropertyBreakpointProperties(fieldName, className)
)
}
}
private fun reportError(project: Project, @NlsContexts.DialogMessage message: String) {
Messages.showMessageDialog(project, message, JavaDebuggerBundle.message("add.field.breakpoint.dialog.title"), Messages.getErrorIcon())
}
override fun isAddBreakpointButtonVisible() = true
override fun getMutedEnabledIcon(): Icon = AllIcons.Debugger.Db_muted_field_breakpoint
override fun getDisabledIcon(): Icon = AllIcons.Debugger.Db_disabled_field_breakpoint
override fun getEnabledIcon(): Icon = AllIcons.Debugger.Db_field_breakpoint
override fun getMutedDisabledIcon(): Icon = AllIcons.Debugger.Db_muted_disabled_field_breakpoint
override fun canBeHitInOtherPlaces() = true
override fun getShortText(breakpoint: XLineBreakpoint<KotlinPropertyBreakpointProperties>): String {
val properties = breakpoint.properties
val className = properties.myClassName
@Suppress("HardCodedStringLiteral")
return if (className.isNotEmpty()) className + "." + properties.myFieldName else properties.myFieldName
}
override fun createProperties(): KotlinPropertyBreakpointProperties = KotlinPropertyBreakpointProperties()
override fun createCustomPropertiesPanel(project: Project): XBreakpointCustomPropertiesPanel<XLineBreakpoint<KotlinPropertyBreakpointProperties>> {
return KotlinFieldBreakpointPropertiesPanel()
}
override fun getDisplayText(breakpoint: XLineBreakpoint<KotlinPropertyBreakpointProperties>): String? {
val kotlinBreakpoint = BreakpointManager.getJavaBreakpoint(breakpoint) as? BreakpointWithHighlighter
return kotlinBreakpoint?.description ?: super.getDisplayText(breakpoint)
}
override fun getEditorsProvider(
breakpoint: XLineBreakpoint<KotlinPropertyBreakpointProperties>,
project: Project,
): XDebuggerEditorsProvider? = null
override fun createCustomRightPropertiesPanel(project: Project): XBreakpointCustomPropertiesPanel<XLineBreakpoint<KotlinPropertyBreakpointProperties>> {
return KotlinBreakpointFiltersPanel(project)
}
override fun isSuspendThreadSupported() = true
}
| apache-2.0 | c5f4c0808ca09a1185c3aeb2f625ce72 | 44.320652 | 156 | 0.718791 | 5.758978 | false | false | false | false |
GunoH/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/table/VcsLogIconCellRenderer.kt | 8 | 1350 | // 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.vcs.log.ui.table
import com.intellij.ui.ColoredTableCellRenderer
import com.intellij.util.ui.EmptyIcon
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JBUI.Borders
import com.intellij.vcs.log.ui.render.GraphCommitCellRenderer.VcsLogTableCellState
import javax.swing.JTable
private val PADDING: JBInsets = JBUI.insets(0, 7, 0, 13)
abstract class VcsLogIconCellRenderer : ColoredTableCellRenderer(), VcsLogCellRenderer {
init {
cellState = VcsLogTableCellState()
myBorder = Borders.empty()
ipad = PADDING
iconTextGap = 0
isTransparentIconBackground = true
}
final override fun customizeCellRenderer(table: JTable, value: Any?, selected: Boolean, hasFocus: Boolean, row: Int, column: Int) {
table as VcsLogGraphTable
table.applyHighlighters(this, row, column, hasFocus, selected)
customize(table, value, selected, hasFocus, row, column)
}
protected abstract fun customize(table: VcsLogGraphTable, value: Any?, selected: Boolean, hasFocus: Boolean, row: Int, column: Int)
override fun getPreferredWidth(table: JTable): Int = EmptyIcon.ICON_16.iconWidth + PADDING.width()
} | apache-2.0 | b334cdc3106f7eeb3be1cb335e58aab9 | 38.735294 | 158 | 0.771111 | 4.029851 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/projectTemplates/ProjectTemplate.kt | 1 | 23593 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.projectTemplates
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.Versions
import org.jetbrains.kotlin.tools.projectWizard.core.buildList
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.*
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.*
import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.gradle.GradlePlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.KotlinPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModuleSubType
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModuleType
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ProjectKind
import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.*
import org.jetbrains.kotlin.tools.projectWizard.templates.*
import org.jetbrains.kotlin.tools.projectWizard.templates.compose.ComposeAndroidTemplate
import org.jetbrains.kotlin.tools.projectWizard.templates.compose.ComposeJvmDesktopTemplate
import org.jetbrains.kotlin.tools.projectWizard.templates.compose.ComposeMppModuleTemplate
import org.jetbrains.kotlin.tools.projectWizard.templates.mpp.MobileMppTemplate
abstract class ProjectTemplate : DisplayableSettingItem {
abstract val title: String
override val text: String get() = title
abstract val description: String
abstract val suggestedProjectName: String
abstract val projectKind: ProjectKind
abstract val id: String
private val setsDefaultValues: List<SettingWithValue<*, *>>
get() = listOf(KotlinPlugin.projectKind.reference withValue projectKind)
protected open val setsPluginSettings: List<SettingWithValue<*, *>> = emptyList()
protected open val setsModules: List<Module> = emptyList()
private val setsAdditionalSettingValues = mutableListOf<SettingWithValue<*, *>>()
val setsValues: List<SettingWithValue<*, *>>
get() = buildList {
setsModules.takeIf { it.isNotEmpty() }?.let { modules ->
+(KotlinPlugin.modules.reference withValue modules)
}
+setsDefaultValues
+setsPluginSettings
+setsAdditionalSettingValues
}
protected fun <T : Template> Module.withTemplate(
template: T,
createSettings: TemplateSettingsBuilder<T>.() -> Unit = {}
) = apply {
this.template = template
with(TemplateSettingsBuilder(this, template)) {
createSettings()
setsAdditionalSettingValues += setsSettings
}
}
protected fun <C : ModuleConfigurator> Module.withConfiguratorSettings(
configurator: C,
createSettings: ConfiguratorSettingsBuilder<C>.() -> Unit = {}
) = apply {
assert(this.configurator === configurator)
with(ConfiguratorSettingsBuilder(this, configurator)) {
createSettings()
setsAdditionalSettingValues += setsSettings
}
}
companion object {
val ALL = listOf(
ConsoleApplicationProjectTemplate,
MultiplatformMobileApplicationProjectTemplate,
MultiplatformMobileLibraryProjectTemplate,
MultiplatformApplicationProjectTemplate,
MultiplatformLibraryProjectTemplate,
NativeApplicationProjectTemplate,
FrontendApplicationProjectTemplate,
ReactApplicationProjectTemplate,
FullStackWebApplicationProjectTemplate,
NodeJsApplicationProjectTemplate,
ComposeDesktopApplicationProjectTemplate,
ComposeMultiplatformApplicationProjectTemplate,
)
fun byId(id: String): ProjectTemplate? = ALL.firstOrNull {
it.id.equals(id, ignoreCase = true)
}
}
}
class TemplateSettingsBuilder<Q : Template>(
val module: Module,
val template: Q
) : TemplateEnvironment by ModuleBasedTemplateEnvironment(template, module) {
private val settings = mutableListOf<SettingWithValue<*, *>>()
val setsSettings: List<SettingWithValue<*, *>>
get() = settings
infix fun <V : Any, T : SettingType<V>> TemplateSetting<V, T>.withValue(value: V) {
settings += SettingWithValue(reference, value)
}
}
class ConfiguratorSettingsBuilder<C : ModuleConfigurator>(
val module: Module,
val configurator: C
) : ModuleConfiguratorContext by ModuleBasedConfiguratorContext(configurator, module) {
init {
assert(module.configurator === configurator)
}
private val settings = mutableListOf<SettingWithValue<*, *>>()
val setsSettings: List<SettingWithValue<*, *>>
get() = settings
infix fun <V : Any, T : SettingType<V>> ModuleConfiguratorSetting<V, T>.withValue(value: V) {
settings += SettingWithValue(reference, value)
}
}
data class SettingWithValue<V : Any, T : SettingType<V>>(val setting: SettingReference<V, T>, val value: V)
infix fun <V : Any, T : SettingType<V>> PluginSettingReference<V, T>.withValue(value: V): SettingWithValue<V, T> =
SettingWithValue(this, value)
inline infix fun <V : Any, reified T : SettingType<V>> PluginSetting<V, T>.withValue(value: V): SettingWithValue<V, T> =
SettingWithValue(reference, value)
private fun createDefaultSourcesets() =
SourcesetType.values().map { sourcesetType ->
Sourceset(
sourcesetType,
dependencies = emptyList()
)
}
private fun ModuleType.createDefaultTarget(
name: String = this.name
) = MultiplatformTargetModule(name, defaultTarget, createDefaultSourcesets())
object MultiplatformApplicationProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.empty.mpp.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.empty.mpp.description")
override val id = "multiplatformApplication"
@NonNls
override val suggestedProjectName = "myKotlinMultiplatformProject"
override val projectKind = ProjectKind.Multiplatform
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
KotlinPlugin.modules.reference withValue listOf(
MultiplatformModule("mainModule", targets = listOf(
ModuleType.common.createDefaultTarget(), ModuleType.jvm.createDefaultTarget()))
)
)
}
object ConsoleApplicationProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.empty.jvm.console.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.empty.jvm.console.description")
override val id = "consoleApplication"
@NonNls
override val suggestedProjectName = "myConsoleApplication"
override val projectKind = ProjectKind.Singleplatform
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
KotlinPlugin.modules.reference withValue listOf(
SinglePlatformModule(
"consoleApp",
createDefaultSourcesets()
).apply {
withTemplate(ConsoleJvmApplicationTemplate())
}
)
)
}
object MultiplatformLibraryProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.mpp.lib.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.mpp.lib.description")
override val id = "multiplatformLibrary"
@NonNls
override val suggestedProjectName = "myMultiplatformLibrary"
override val projectKind = ProjectKind.Multiplatform
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
KotlinPlugin.modules.reference withValue listOf(
MultiplatformModule(
"library",
targets = listOf(
ModuleType.common.createDefaultTarget(),
ModuleType.jvm.createDefaultTarget(),
ModuleType.js.createDefaultTarget().withConfiguratorSettings(JsBrowserTargetConfigurator) {
JSConfigurator.kind withValue JsTargetKind.LIBRARY
},
ModuleType.native.createDefaultTarget()
)
)
)
)
}
object FullStackWebApplicationProjectTemplate : ProjectTemplate() {
override val title: String = KotlinNewProjectWizardBundle.message("project.template.full.stack.title")
override val description: String = KotlinNewProjectWizardBundle.message("project.template.full.stack.description")
override val id = "fullStackWebApplication"
@NonNls
override val suggestedProjectName: String = "myFullStackApplication"
override val projectKind: ProjectKind = ProjectKind.Multiplatform
override val setsPluginSettings: List<SettingWithValue<*, *>> = listOf(
KotlinPlugin.modules.reference withValue listOf(
MultiplatformModule(
"application",
targets = listOf(
ModuleType.common.createDefaultTarget(),
ModuleType.jvm.createDefaultTarget().apply {
withTemplate(KtorServerTemplate()) {
}
},
ModuleType.js.createDefaultTarget().apply {
withTemplate(ReactJsClientTemplate())
}
)
)
)
)
}
object NativeApplicationProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.native.console.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.native.console.description")
override val id = "nativeApplication"
@NonNls
override val suggestedProjectName = "myNativeConsoleApp"
override val projectKind = ProjectKind.Multiplatform
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
KotlinPlugin.modules.reference withValue listOf(
Module(
"app",
MppModuleConfigurator,
template = null,
sourceSets = emptyList(),
subModules = listOf(
ModuleType.native.createDefaultTarget("native").apply {
withTemplate(NativeConsoleApplicationTemplate())
}
)
)
)
)
}
object FrontendApplicationProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.browser.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.browser.description")
override val id = "frontendApplication"
@NonNls
override val suggestedProjectName = "myKotlinJsApplication"
override val projectKind = ProjectKind.Js
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
KotlinPlugin.modules.reference withValue listOf(
Module(
"browser",
BrowserJsSinglePlatformModuleConfigurator,
template = SimpleJsClientTemplate(),
sourceSets = SourcesetType.ALL.map { type ->
Sourceset(type, dependencies = emptyList())
},
subModules = emptyList()
)
)
)
}
object ReactApplicationProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.react.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.react.description")
override val id = "reactApplication"
@NonNls
override val suggestedProjectName = "myKotlinJsApplication"
override val projectKind = ProjectKind.Js
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
KotlinPlugin.modules.reference withValue listOf(
Module(
"react",
BrowserJsSinglePlatformModuleConfigurator,
template = ReactJsClientTemplate(),
sourceSets = SourcesetType.ALL.map { type ->
Sourceset(type, dependencies = emptyList())
},
subModules = emptyList()
)
)
)
}
object MultiplatformMobileApplicationProjectTemplate : MultiplatformMobileApplicationProjectTemplateBase() {
override val id = "multiplatformMobileApplication"
override fun androidAppModule(shared: Module) = Module(
"androidApp",
AndroidSinglePlatformModuleConfigurator,
template = null,
sourceSets = createDefaultSourcesets(),
subModules = emptyList(),
dependencies = mutableListOf(ModuleReference.ByModule(shared))
)
override fun iosAppModule(shared: Module) = Module(
"iosApp",
IOSSinglePlatformModuleConfigurator,
template = null,
sourceSets = createDefaultSourcesets(),
subModules = emptyList(),
dependencies = mutableListOf(ModuleReference.ByModule(shared))
)
}
abstract class MultiplatformMobileApplicationProjectTemplateBase : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.mpp.mobile.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.mpp.mobile.description")
@NonNls
override val suggestedProjectName = "myIOSApplication"
override val projectKind = ProjectKind.Multiplatform
override val setsModules: List<Module> = buildList {
val shared = MultiplatformModule(
"shared",
template = MobileMppTemplate(),
targets = listOf(
ModuleType.common.createDefaultTarget(),
Module(
"android",
AndroidTargetConfigurator,
null,
sourceSets = createDefaultSourcesets(),
subModules = emptyList()
).withConfiguratorSettings(AndroidTargetConfigurator) {
configurator.androidPlugin withValue AndroidGradlePlugin.LIBRARY
},
Module(
"ios",
RealNativeTargetConfigurator.configuratorsByModuleType.getValue(ModuleSubType.ios),
null,
sourceSets = createDefaultSourcesets(),
subModules = emptyList()
)
)
)
+iosAppModule(shared)
+androidAppModule(shared)
+shared // shared module must be the last so dependent modules could create actual files
}
protected abstract fun iosAppModule(shared: Module): Module
protected abstract fun androidAppModule(shared: Module): Module
}
object MultiplatformMobileLibraryProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.mpp.mobile.lib.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.mpp.mobile.lib.description")
override val id = "multiplatformMobileLibrary"
@NonNls
override val suggestedProjectName = "myMppMobileLibrary"
override val projectKind = ProjectKind.Multiplatform
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
KotlinPlugin.modules.reference withValue listOf(
MultiplatformModule(
"library",
template = MobileMppTemplate(),
targets = listOf(
ModuleType.common.createDefaultTarget(),
Module(
"android", AndroidTargetConfigurator,
sourceSets = SourcesetType.ALL.map { type ->
Sourceset(type, dependencies = emptyList())
}
).withConfiguratorSettings(AndroidTargetConfigurator) {
configurator.androidPlugin withValue AndroidGradlePlugin.LIBRARY
},
Module(
"ios", RealNativeTargetConfigurator.configuratorsByModuleType.getValue(ModuleSubType.iosX64),
sourceSets = SourcesetType.ALL.map { type ->
Sourceset(type, dependencies = emptyList())
}
)
)
)
)
)
}
object NodeJsApplicationProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.nodejs.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.nodejs.description")
override val id = "nodejsApplication"
@NonNls
override val suggestedProjectName = "myKotlinJsApplication"
override val projectKind = ProjectKind.Js
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
KotlinPlugin.modules.reference withValue listOf(
Module(
"nodejs",
NodeJsSinglePlatformModuleConfigurator,
template = SimpleNodeJsTemplate(),
sourceSets = SourcesetType.ALL.map { type ->
Sourceset(type, dependencies = emptyList())
},
subModules = emptyList()
)
)
)
}
object ComposeDesktopApplicationProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.compose.desktop.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.compose.desktop.description")
override val id = "composeDesktopApplication"
@NonNls
override val suggestedProjectName = "myComposeDesktopApplication"
override val projectKind = ProjectKind.COMPOSE
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
GradlePlugin.gradleVersion withValue Versions.GRADLE_VERSION_FOR_COMPOSE,
StructurePlugin.version withValue "1.0",
)
override val setsModules: List<Module>
get() = listOf(
Module(
"compose",
JvmSinglePlatformModuleConfigurator,
template = ComposeJvmDesktopTemplate(),
sourceSets = SourcesetType.ALL.map { type ->
Sourceset(type, dependencies = emptyList())
},
subModules = emptyList()
).withConfiguratorSettings(JvmSinglePlatformModuleConfigurator) {
ModuleConfiguratorWithTests.testFramework withValue KotlinTestFramework.NONE
JvmModuleConfigurator.targetJvmVersion withValue TargetJvmVersion.JVM_11
}
)
}
object ComposeMultiplatformApplicationProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.compose.multiplatform.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.compose.multiplatform.description")
override val id = "composeMultiplatformApplication"
@NonNls
override val suggestedProjectName = "myComposeMultiplatformApplication"
override val projectKind = ProjectKind.COMPOSE
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
GradlePlugin.gradleVersion withValue Versions.GRADLE_VERSION_FOR_COMPOSE,
StructurePlugin.version withValue "1.0",
)
override val setsModules: List<Module>
get() = buildList {
val common = MultiplatformModule(
"common",
template = ComposeMppModuleTemplate(),
listOf(
ModuleType.common.createDefaultTarget().withConfiguratorSettings(CommonTargetConfigurator) {
ModuleConfiguratorWithTests.testFramework withValue KotlinTestFramework.NONE
},
Module(
"android",
AndroidTargetConfigurator,
template = null,
sourceSets = createDefaultSourcesets(),
subModules = emptyList()
).withConfiguratorSettings(AndroidTargetConfigurator) {
configurator.androidPlugin withValue AndroidGradlePlugin.LIBRARY
ModuleConfiguratorWithTests.testFramework withValue KotlinTestFramework.NONE
},
Module(
"desktop",
JvmTargetConfigurator,
template = null,
sourceSets = createDefaultSourcesets(),
subModules = emptyList()
).withConfiguratorSettings(JvmTargetConfigurator) {
ModuleConfiguratorWithTests.testFramework withValue KotlinTestFramework.NONE
JvmModuleConfigurator.targetJvmVersion withValue TargetJvmVersion.JVM_11
}
)
)
+Module(
"android",
AndroidSinglePlatformModuleConfigurator,
template = ComposeAndroidTemplate(),
sourceSets = createDefaultSourcesets(),
subModules = emptyList(),
dependencies = mutableListOf(ModuleReference.ByModule(common))
).withConfiguratorSettings(AndroidSinglePlatformModuleConfigurator) {
ModuleConfiguratorWithTests.testFramework withValue KotlinTestFramework.NONE
}
+Module(
"desktop",
MppModuleConfigurator,
template = null,
sourceSets = createDefaultSourcesets(),
subModules = listOf(
Module(
"jvm",
JvmTargetConfigurator,
template = ComposeJvmDesktopTemplate(),
sourceSets = createDefaultSourcesets(),
subModules = emptyList(),
dependencies = mutableListOf(ModuleReference.ByModule(common))
).withConfiguratorSettings(JvmTargetConfigurator) {
ModuleConfiguratorWithTests.testFramework withValue KotlinTestFramework.NONE
JvmModuleConfigurator.targetJvmVersion withValue TargetJvmVersion.JVM_11
}
),
)
+common
}
} | apache-2.0 | edda591f6605a67d5b8282dd49c5ccfc | 41.742754 | 158 | 0.641207 | 6.126461 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/facet/KotlinVersionInfoProvider.kt | 1 | 3931 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.facet
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ModuleRootModel
import org.jetbrains.kotlin.config.KotlinFacetSettingsProvider
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.platform.IdePlatformKind
import org.jetbrains.kotlin.platform.idePlatformKind
import org.jetbrains.kotlin.platform.orDefault
interface KotlinVersionInfoProvider {
companion object {
val EP_NAME: ExtensionPointName<KotlinVersionInfoProvider> = ExtensionPointName("org.jetbrains.kotlin.versionInfoProvider")
}
fun getCompilerVersion(module: Module): IdeKotlinVersion?
fun getLibraryVersions(
module: Module,
platformKind: IdePlatformKind,
rootModel: ModuleRootModel?
): Collection<IdeKotlinVersion>
}
fun getRuntimeLibraryVersions(
module: Module,
rootModel: ModuleRootModel?,
platformKind: IdePlatformKind
): Collection<IdeKotlinVersion> {
return KotlinVersionInfoProvider.EP_NAME.extensionList.asSequence()
.map { it.getLibraryVersions(module, platformKind, rootModel) }
.firstOrNull { it.isNotEmpty() } ?: emptyList()
}
fun getLibraryLanguageLevel(
module: Module,
rootModel: ModuleRootModel?,
platformKind: IdePlatformKind?,
coerceRuntimeLibraryVersionToReleased: Boolean = true
): LanguageVersion = getLibraryVersion(module, rootModel, platformKind, coerceRuntimeLibraryVersionToReleased).languageVersion
fun getLibraryVersion(
module: Module,
rootModel: ModuleRootModel?,
platformKind: IdePlatformKind?,
coerceRuntimeLibraryVersionToReleased: Boolean = true
): IdeKotlinVersion {
val minVersion = getRuntimeLibraryVersions(module, rootModel, platformKind.orDefault())
.addReleaseVersionIfNecessary(coerceRuntimeLibraryVersionToReleased)
.minOrNull()
return getDefaultVersion(module, minVersion, coerceRuntimeLibraryVersionToReleased)
}
fun getDefaultVersion(
module: Module,
explicitVersion: IdeKotlinVersion? = null,
coerceRuntimeLibraryVersionToReleased: Boolean = true
): IdeKotlinVersion {
if (explicitVersion != null) {
return explicitVersion
}
val libVersion = KotlinVersionInfoProvider.EP_NAME.extensions
.mapNotNull { it.getCompilerVersion(module) }
.addReleaseVersionIfNecessary(coerceRuntimeLibraryVersionToReleased)
.minOrNull()
return libVersion ?: KotlinPluginLayout.instance.standaloneCompilerVersion
}
fun getDefaultLanguageLevel(
module: Module,
explicitVersion: IdeKotlinVersion? = null,
coerceRuntimeLibraryVersionToReleased: Boolean = true
): LanguageVersion = getDefaultVersion(module, explicitVersion, coerceRuntimeLibraryVersionToReleased).languageVersion
private fun Iterable<IdeKotlinVersion>.addReleaseVersionIfNecessary(shouldAdd: Boolean): Iterable<IdeKotlinVersion> =
if (shouldAdd) this + KotlinPluginLayout.instance.standaloneCompilerVersion else this
fun getRuntimeLibraryVersion(module: Module): IdeKotlinVersion? {
val settingsProvider = KotlinFacetSettingsProvider.getInstance(module.project) ?: return null
val targetPlatform = settingsProvider.getInitializedSettings(module).targetPlatform
val versions = getRuntimeLibraryVersions(module, null, targetPlatform.orDefault().idePlatformKind)
return versions.toSet().singleOrNull()
}
fun getRuntimeLibraryVersionOrDefault(module: Module): IdeKotlinVersion {
return getRuntimeLibraryVersion(module) ?: KotlinPluginLayout.instance.standaloneCompilerVersion
} | apache-2.0 | fd28c9f6fd6b39ea6c977249a25d47ff | 41.27957 | 158 | 0.796998 | 5.370219 | false | false | false | false |
jwren/intellij-community | images/src/org/intellij/images/actions/EditExternalImageEditorAction.kt | 6 | 2175 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.images.actions
import com.intellij.ide.IdeBundle
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.layout.*
import org.intellij.images.ImagesBundle
import javax.swing.JComponent
/**
* @author Konstantin Bulenkov
*/
class EditExternalImageEditorAction: DumbAwareAction() {
companion object {
const val EXT_PATH_KEY = "Images.ExternalEditorPath"
fun showDialog(project: Project?) {
EditExternalImageEditorDialog(project).show()
}
}
override fun actionPerformed(e: AnActionEvent) {
showDialog(e.project)
}
class EditExternalImageEditorDialog(val project: Project?): DialogWrapper(project) {
init {
title = ImagesBundle.message("edit.external.editor.path.dialog.title")
setOKButtonText(IdeBundle.message("button.save"))
init()
}
override fun createCenterPanel(): JComponent {
val fileDescriptor = FileChooserDescriptor(true, SystemInfo.isMac, false, false, false, false)
fileDescriptor.isShowFileSystemRoots = true
fileDescriptor.title = ImagesBundle.message("select.external.executable.title")
fileDescriptor.description = ImagesBundle.message("select.external.executable.message")
return panel() {
row(ImagesBundle.message("external.editor.executable.path")) {
textFieldWithBrowseButton({PropertiesComponent.getInstance().getValue(EXT_PATH_KEY, "")},
{PropertiesComponent.getInstance().setValue(EXT_PATH_KEY, it)},
project = project,
fileChooserDescriptor = fileDescriptor,
fileChosen = {it.path})
}
}
}
}
} | apache-2.0 | ed11c9b29ec704859dc06c7ec27adea5 | 37.175439 | 140 | 0.708046 | 4.833333 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/template/expressions/StringParameterNameExpression.kt | 19 | 1370 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.template.expressions
import com.intellij.codeInsight.template.ExpressionContext
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.codeStyle.SuggestedNameInfo
import com.intellij.psi.codeStyle.VariableKind
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter
class StringParameterNameExpression(private val myDefaultName: String?) : ParameterNameExpression() {
override fun getNameInfo(context: ExpressionContext): SuggestedNameInfo? {
val project = context.project
val editor = context.editor ?: return null
val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return null
val elementAt = file.findElementAt(context.startOffset)
val parameter = PsiTreeUtil.getParentOfType(elementAt, GrParameter::class.java) ?: return null
val manager = JavaCodeStyleManager.getInstance(project)
return manager.suggestVariableName(VariableKind.PARAMETER, myDefaultName, null, parameter.typeGroovy)
}
companion object {
val EMPTY: ParameterNameExpression = StringParameterNameExpression(null)
}
}
| apache-2.0 | 16f4c67d0ce5b1a9c99e04afed3b3024 | 49.740741 | 140 | 0.810949 | 4.724138 | false | false | false | false |
smmribeiro/intellij-community | python/python-features-trainer/src/com/jetbrains/python/ift/lesson/essensial/PythonOnboardingTour.kt | 1 | 29512 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.ift.lesson.essensial
import com.intellij.codeInsight.template.impl.TemplateManagerImpl
import com.intellij.execution.ExecutionBundle
import com.intellij.execution.RunManager
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereManagerImpl
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereUI
import com.intellij.ide.ui.UISettings
import com.intellij.ide.util.PropertiesComponent
import com.intellij.ide.util.gotoByName.GotoActionModel
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.ex.ComboBoxAction
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.ActionMenuItem
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.editor.actions.ToggleCaseAction
import com.intellij.openapi.editor.impl.EditorComponentImpl
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.openapi.util.WindowStateService
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.impl.FocusManagerImpl
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.openapi.wm.impl.StripeButton
import com.intellij.openapi.wm.impl.status.TextPanel
import com.intellij.ui.ScreenUtil
import com.intellij.ui.UIBundle
import com.intellij.ui.components.fields.ExtendableTextField
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.dsl.builder.Panel
import com.intellij.ui.tree.TreeVisitor
import com.intellij.util.Alarm
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.tree.TreeUtil
import com.jetbrains.python.PyBundle
import com.jetbrains.python.PyPsiBundle
import com.jetbrains.python.configuration.PyConfigurableInterpreterList
import com.jetbrains.python.ift.PythonLessonsBundle
import com.jetbrains.python.ift.PythonLessonsUtil
import com.jetbrains.python.newProject.steps.ProjectSpecificSettingsStep
import com.jetbrains.python.sdk.findBaseSdks
import com.jetbrains.python.sdk.pythonSdk
import kotlinx.serialization.json.JsonObjectBuilder
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.put
import org.intellij.lang.annotations.Language
import org.jetbrains.annotations.Nls
import training.FeaturesTrainerIcons
import training.dsl.*
import training.dsl.LessonUtil.checkExpectedStateOfEditor
import training.dsl.LessonUtil.restoreIfModified
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.dsl.LessonUtil.restorePopupPosition
import training.learn.LearnBundle
import training.learn.LessonsBundle
import training.learn.course.KLesson
import training.learn.course.LessonProperties
import training.learn.lesson.LessonManager
import training.learn.lesson.general.run.clearBreakpoints
import training.learn.lesson.general.run.toggleBreakpointTask
import training.project.ProjectUtils
import training.ui.LearningUiHighlightingManager
import training.ui.LearningUiManager
import training.util.*
import java.awt.Point
import java.awt.Rectangle
import java.awt.event.KeyEvent
import java.util.concurrent.CompletableFuture
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.JTree
import javax.swing.JWindow
import javax.swing.tree.TreePath
class PythonOnboardingTour :
KLesson("python.onboarding", PythonLessonsBundle.message("python.onboarding.lesson.name")) {
private lateinit var openLearnTaskId: TaskContext.TaskId
private var useDelay: Boolean = false
private val demoConfigurationName: String = "welcome"
private val demoFileName: String = "$demoConfigurationName.py"
private val uiSettings get() = UISettings.instance
override val properties = LessonProperties(
canStartInDumbMode = true,
openFileAtStart = false
)
override val testScriptProperties = TaskTestContext.TestScriptProperties(skipTesting = true)
private var backupPopupLocation: Point? = null
private var hideToolStripesPreference = false
private var showNavigationBarPreference = true
val sample: LessonSample = parseLessonSample("""
def find_average(values)<caret id=3/>:
result = 0
for v in values:
result += v
<caret>return result<caret id=2/>
print("AVERAGE", find_average([5,6, 7, 8]))
""".trimIndent())
override val lessonContent: LessonContext.() -> Unit = {
prepareRuntimeTask {
useDelay = true
configurations().forEach { runManager().removeConfiguration(it) }
val root = ProjectUtils.getProjectRoot(project)
if (root.findChild(demoFileName) == null) invokeLater {
runWriteAction {
root.createChildData(this, demoFileName)
}
}
}
clearBreakpoints()
checkUiSettings()
projectTasks()
prepareSample(sample)
openLearnToolwindow()
showInterpreterConfiguration()
waitIndexingTasks()
runTasks()
debugTasks()
completionSteps()
waitBeforeContinue(500)
contextActions()
waitBeforeContinue(500)
searchEverywhereTasks()
task {
text(PythonLessonsBundle.message("python.onboarding.epilog",
getCallBackActionId("CloseProject"),
LessonUtil.returnToWelcomeScreenRemark(),
LearningUiManager.addCallback { LearningUiManager.resetModulesView() }))
}
}
override fun onLessonEnd(project: Project, lessonEndInfo: LessonEndInfo) {
prepareFeedbackData(project, lessonEndInfo)
restorePopupPosition(project, SearchEverywhereManagerImpl.LOCATION_SETTINGS_KEY, backupPopupLocation)
backupPopupLocation = null
uiSettings.hideToolStripes = hideToolStripesPreference
uiSettings.showNavigationBar = showNavigationBarPreference
uiSettings.fireUISettingsChanged()
if (!lessonEndInfo.lessonPassed) {
LessonUtil.showFeedbackNotification(this, project)
return
}
val dataContextPromise = DataManager.getInstance().dataContextFromFocusAsync
invokeLater {
val result = MessageDialogBuilder.yesNoCancel(PythonLessonsBundle.message("python.onboarding.finish.title"),
PythonLessonsBundle.message("python.onboarding.finish.text",
LessonUtil.returnToWelcomeScreenRemark()))
.yesText(PythonLessonsBundle.message("python.onboarding.finish.exit"))
.noText(PythonLessonsBundle.message("python.onboarding.finish.modules"))
.icon(FeaturesTrainerIcons.Img.PluginIcon)
.show(project)
when (result) {
Messages.YES -> invokeLater {
LessonManager.instance.stopLesson()
val closeAction = getActionById("CloseProject")
dataContextPromise.onSuccess { context ->
invokeLater {
val event = AnActionEvent.createFromAnAction(closeAction, null, ActionPlaces.LEARN_TOOLWINDOW, context)
ActionUtil.performActionDumbAwareWithCallbacks(closeAction, event)
}
}
}
Messages.NO -> invokeLater {
LearningUiManager.resetModulesView()
}
}
if (result != Messages.YES) {
LessonUtil.showFeedbackNotification(this, project)
}
}
}
private fun prepareFeedbackData(project: Project, lessonEndInfo: LessonEndInfo) {
val configPropertyName = "ift.pycharm.onboarding.feedback.proposed"
if (PropertiesComponent.getInstance().getBoolean(configPropertyName, false)) {
return
}
val primaryLanguage = module.primaryLanguage
if (primaryLanguage == null) {
thisLogger().error("Onboarding lesson has no language support for some magical reason")
return
}
val allExistingSdks = listOf(*PyConfigurableInterpreterList.getInstance(null).model.sdks)
val existingSdks = ProjectSpecificSettingsStep.getValidPythonSdks(allExistingSdks)
val interpreterVersions = CompletableFuture<List<String>>()
ApplicationManager.getApplication().executeOnPooledThread {
val context = UserDataHolderBase()
val baseSdks = findBaseSdks(existingSdks, null, context)
interpreterVersions.complete(baseSdks.mapNotNull { it.sdkType.getVersionString(it) }.sorted().distinct())
}
val usedInterpreter = project.pythonSdk?.versionString ?: "none"
primaryLanguage.onboardingFeedbackData = object : OnboardingFeedbackData("PyCharm Onboarding Tour Feedback", lessonEndInfo) {
override val feedbackReportId = "pycharm_onboarding_tour"
override val additionalFeedbackFormatVersion: Int = 0
val interpreters: List<String>? by lazy {
if (interpreterVersions.isDone) interpreterVersions.get() else null
}
override val addAdditionalSystemData: JsonObjectBuilder.() -> Unit = {
put("current_interpreter", usedInterpreter)
put("found_interpreters", buildJsonArray {
for (i in interpreters ?: emptyList()) {
add(JsonPrimitive(i))
}
})
}
override val addRowsForUserAgreement: Panel.() -> Unit = {
row(PythonLessonsBundle.message("python.onboarding.feedback.system.found.interpreters")) {
@Suppress("HardCodedStringLiteral")
val interpreters: @NlsSafe String? = interpreters?.toString()
label(interpreters ?: PythonLessonsBundle.message("python.onboarding.feedback.system.no.interpreters"))
}
row(PythonLessonsBundle.message("python.onboarding.feedback.system.used.interpreter")) {
label(usedInterpreter)
}
}
override val possibleTechnicalIssues: Map<String, @Nls String> = mapOf(
"interpreter_issues" to PythonLessonsBundle.message("python.onboarding.option.interpreter.issues")
)
override fun feedbackHasBeenProposed() {
PropertiesComponent.getInstance().setValue(configPropertyName, true, false)
}
}
}
private fun getCallBackActionId(@Suppress("SameParameterValue") actionId: String): Int {
val action = getActionById(actionId)
return LearningUiManager.addCallback { invokeActionForFocusContext(action) }
}
private fun LessonContext.debugTasks() {
var logicalPosition = LogicalPosition(0, 0)
prepareRuntimeTask {
logicalPosition = editor.offsetToLogicalPosition(sample.startOffset)
}
caret(sample.startOffset)
toggleBreakpointTask(sample, { logicalPosition }, checkLine = false) {
text(PythonLessonsBundle.message("python.onboarding.balloon.click.here"),
LearningBalloonConfig(Balloon.Position.below, width = 0, duplicateMessage = false))
text(PythonLessonsBundle.message("python.onboarding.toggle.breakpoint.1",
code("6.5"), code("find_average"), code("26")))
text(PythonLessonsBundle.message("python.onboarding.toggle.breakpoint.2"))
}
highlightButtonByIdTask("Debug")
actionTask("Debug") {
buttonBalloon(PythonLessonsBundle.message("python.onboarding.balloon.start.debugging"))
restoreIfModified(sample)
PythonLessonsBundle.message("python.onboarding.start.debugging", icon(AllIcons.Actions.StartDebugger))
}
highlightDebugActionsToolbar()
task {
text(PythonLessonsBundle.message("python.onboarding.balloon.about.debug.panel",
strong(UIBundle.message("tool.window.name.debug")),
if (Registry.`is`("debugger.new.tool.window.layout")) 0 else 1,
strong(LessonsBundle.message("debug.workflow.lesson.name"))))
proceedLink()
restoreIfModified(sample)
}
highlightButtonByIdTask("Stop")
actionTask("Stop") {
buttonBalloon(
PythonLessonsBundle.message("python.onboarding.balloon.stop.debugging")) { list -> list.minByOrNull { it.locationOnScreen.y } }
restoreIfModified(sample)
PythonLessonsBundle.message("python.onboarding.stop.debugging", icon(AllIcons.Actions.Suspend))
}
prepareRuntimeTask {
LearningUiHighlightingManager.clearHighlights()
}
}
private fun LessonContext.highlightButtonByIdTask(actionId: String) {
val highlighted = highlightButtonById(actionId)
task {
addStep(highlighted)
}
}
private fun TaskContext.buttonBalloon(@Language("HTML") @Nls message: String,
chooser: (List<JComponent>) -> JComponent? = { it.firstOrNull() }) {
val highlightingComponent = chooser(LearningUiHighlightingManager.highlightingComponents.filterIsInstance<JComponent>())
val useBalloon = LearningBalloonConfig(Balloon.Position.below,
width = 0,
highlightingComponent = highlightingComponent,
duplicateMessage = false)
text(message, useBalloon)
}
private fun LessonContext.waitIndexingTasks() {
task {
triggerByUiComponentAndHighlight(highlightInside = false) { progress: NonOpaquePanel ->
progress.javaClass.name.contains("InlineProgressPanel")
}
}
task {
text(PythonLessonsBundle.message("python.onboarding.indexing.description"))
waitSmartModeStep()
}
waitBeforeContinue(300)
prepareRuntimeTask {
LearningUiHighlightingManager.clearHighlights()
}
}
private fun LessonContext.runTasks() {
task {
triggerByUiComponentAndHighlight(highlightInside = false) { ui: EditorComponentImpl ->
ui.text.contains("find_average")
}
}
val runItem = ExecutionBundle.message("default.runner.start.action.text").dropMnemonic() + " '$demoConfigurationName'"
task {
text(PythonLessonsBundle.message("python.onboarding.context.menu"))
triggerByUiComponentAndHighlight(usePulsation = true) { ui: ActionMenuItem ->
ui.text.isToStringContains(runItem)
}
restoreIfModified(sample)
}
task {
text(PythonLessonsBundle.message("python.onboarding.run.sample", strong(runItem), action("RunClass")))
checkToolWindowState("Run", true)
timerCheck {
configurations().isNotEmpty()
}
restoreIfModified(sample)
rehighlightPreviousUi = true
}
task {
val stopAction = getActionById("Stop")
triggerByPartOfComponent(highlightInside = true, usePulsation = true) { ui: ActionToolbarImpl ->
ui.takeIf { (ui.place == ActionPlaces.NAVIGATION_BAR_TOOLBAR || ui.place == ActionPlaces.MAIN_TOOLBAR) }?.let {
val configurations = ui.components.find { it is JPanel && it.components.any { b -> b is ComboBoxAction.ComboBoxButton } }
val stop = ui.components.find { it is ActionButton && it.action == stopAction }
if (configurations != null && stop != null) {
val x = configurations.x
val y = configurations.y
val width = stop.x + stop.width - x
val height = stop.y + stop.height - y
Rectangle(x, y, width, height)
}
else null
}
}
}
task {
text(PythonLessonsBundle.message("python.onboarding.temporary.configuration.description",
icon(AllIcons.Actions.Execute),
icon(AllIcons.Actions.StartDebugger),
icon(AllIcons.Actions.Profile),
icon(AllIcons.General.RunWithCoverage)))
proceedLink()
restoreIfModified(sample)
}
}
private fun LessonContext.openLearnToolwindow() {
task {
triggerByUiComponentAndHighlight(usePulsation = true) { stripe: StripeButton ->
stripe.windowInfo.id == "Learn"
}
}
task {
openLearnTaskId = taskId
text(PythonLessonsBundle.message("python.onboarding.balloon.open.learn.toolbar", strong(LearnBundle.message("toolwindow.stripe.Learn"))),
LearningBalloonConfig(Balloon.Position.atRight, width = 0, duplicateMessage = true))
stateCheck {
ToolWindowManager.getInstance(project).getToolWindow("Learn")?.isVisible == true
}
restoreIfModified(sample)
}
prepareRuntimeTask {
LearningUiHighlightingManager.clearHighlights()
requestEditorFocus()
}
}
private fun LessonContext.checkUiSettings() {
hideToolStripesPreference = uiSettings.hideToolStripes
showNavigationBarPreference = uiSettings.showNavigationBar
if (!hideToolStripesPreference && (showNavigationBarPreference || uiSettings.showMainToolbar)) {
// a small hack to have same tasks count. It is needed to track statistics result.
task { }
task { }
return
}
task {
text(PythonLessonsBundle.message("python.onboarding.change.ui.settings"))
proceedLink()
}
prepareRuntimeTask {
uiSettings.hideToolStripes = false
uiSettings.showNavigationBar = true
uiSettings.fireUISettingsChanged()
}
}
private fun LessonContext.projectTasks() {
prepareRuntimeTask {
LessonUtil.hideStandardToolwindows(project)
}
task {
triggerByUiComponentAndHighlight(usePulsation = true) { stripe: StripeButton ->
stripe.windowInfo.id == "Project"
}
}
task {
var collapsed = false
text(PythonLessonsBundle.message("python.onboarding.project.view.description",
action("ActivateProjectToolWindow")))
text(PythonLessonsBundle.message("python.onboarding.balloon.project.view"),
LearningBalloonConfig(Balloon.Position.atRight, width = 0))
triggerByFoundPathAndHighlight { tree: JTree, path: TreePath ->
val result = path.pathCount >= 1 && path.getPathComponent(0).isToStringContains("PyCharmLearningProject")
if (result) {
if (!collapsed) {
invokeLater {
tree.collapsePath(path)
}
}
collapsed = true
}
result
}
}
fun isDemoFilePath(path: TreePath) =
path.pathCount >= 3 && path.getPathComponent(2).isToStringContains(demoFileName)
task {
text(PythonLessonsBundle.message("python.onboarding.balloon.project.directory"),
LearningBalloonConfig(Balloon.Position.atRight, duplicateMessage = true, width = 0))
triggerByFoundPathAndHighlight { _: JTree, path: TreePath ->
isDemoFilePath(path)
}
restoreByUi()
}
task {
text(PythonLessonsBundle.message("python.onboarding.balloon.open.file", strong(demoFileName)),
LearningBalloonConfig(Balloon.Position.atRight, duplicateMessage = true, width = 0))
stateCheck l@{
if (FileEditorManager.getInstance(project).selectedTextEditor == null) return@l false
virtualFile.name == demoFileName
}
restoreState {
(previous.ui as? JTree)?.takeIf { tree ->
TreeUtil.visitVisibleRows(tree, TreeVisitor { path ->
if (isDemoFilePath(path)) TreeVisitor.Action.INTERRUPT else TreeVisitor.Action.CONTINUE
}) != null
}?.isShowing?.not() ?: true
}
}
}
private fun LessonContext.completionSteps() {
prepareRuntimeTask {
setSample(sample.insertAtPosition(2, " / len(<caret>)"))
FocusManagerImpl.getInstance(project).requestFocusInProject(editor.contentComponent, project)
}
task {
text(PythonLessonsBundle.message("python.onboarding.type.division",
code(" / len()")))
text(PythonLessonsBundle.message("python.onboarding.invoke.completion",
code("values"),
code("()"),
action("CodeCompletion")))
triggerByListItemAndHighlight(highlightBorder = true, highlightInside = false) { // no highlighting
it.isToStringContains("values")
}
proposeRestoreForInvalidText("values")
}
task {
text(PythonLessonsBundle.message("python.onboarding.choose.values.item",
code("values"), action("EditorChooseLookupItem")))
stateCheck {
checkEditorModification(sample.getPosition(2), "/len(values)")
}
restoreByUi()
}
}
private fun TaskRuntimeContext.checkEditorModification(completionPosition: LessonSamplePosition, needChange: String): Boolean {
val startOfChange = completionPosition.startOffset
val sampleText = sample.text
val prefix = sampleText.substring(0, startOfChange)
val suffix = sampleText.substring(startOfChange, sampleText.length)
val current = editor.document.text
if (!current.startsWith(prefix)) return false
if (!current.endsWith(suffix)) return false
val indexOfSuffix = current.indexOf(suffix)
if (indexOfSuffix < startOfChange) return false
val change = current.substring(startOfChange, indexOfSuffix)
return change.replace(" ", "") == needChange
}
private fun LessonContext.contextActions() {
val reformatMessage = PyBundle.message("QFIX.reformat.file")
caret(",6")
task("ShowIntentionActions") {
text(PythonLessonsBundle.message("python.onboarding.invoke.intention.for.warning.1"))
text(PythonLessonsBundle.message("python.onboarding.invoke.intention.for.warning.2", action(it)))
triggerByListItemAndHighlight(highlightBorder = true, highlightInside = false) { item ->
item.isToStringContains(reformatMessage)
}
restoreIfModifiedOrMoved()
}
task {
text(PythonLessonsBundle.message("python.onboarding.select.fix", strong(reformatMessage)))
stateCheck {
// TODO: make normal check
previous.sample.text != editor.document.text
}
restoreByUi(delayMillis = defaultRestoreDelay)
}
fun returnTypeMessage(project: Project) =
if (PythonLessonsUtil.isPython3Installed(project)) PyPsiBundle.message("INTN.specify.return.type.in.annotation")
else PyPsiBundle.message("INTN.specify.return.type.in.docstring")
caret("find_average")
task("ShowIntentionActions") {
text(PythonLessonsBundle.message("python.onboarding.invoke.intention.for.code",
code("find_average"), action(it)))
triggerByListItemAndHighlight(highlightBorder = true, highlightInside = false) { item ->
item.isToStringContains(returnTypeMessage(project))
}
restoreIfModifiedOrMoved()
}
task {
text(PythonLessonsBundle.message("python.onboarding.apply.intention", strong(returnTypeMessage(project)), LessonUtil.rawEnter()))
stateCheck {
val text = editor.document.text
previous.sample.text != text && text.contains("object") && !text.contains("values: object")
}
restoreByUi(delayMillis = defaultRestoreDelay)
}
task {
lateinit var forRestore: LessonSample
before {
val text = previous.sample.text
val toReplace = "object"
forRestore = LessonSample(text.replace(toReplace, ""), text.indexOf(toReplace).takeIf { it != -1 } ?: 0)
}
text(PythonLessonsBundle.message("python.onboarding.complete.template", code("float"), LessonUtil.rawEnter()))
stateCheck {
// TODO: make normal check
val activeTemplate = TemplateManagerImpl.getInstance(project).getActiveTemplate(editor)
editor.document.text.contains("float") && activeTemplate == null
}
proposeRestore {
checkExpectedStateOfEditor(forRestore) {
"object".contains(it) || "float".contains(it)
}
}
}
}
private fun LessonContext.searchEverywhereTasks() {
val toggleCase = ActionsBundle.message("action.EditorToggleCase.text")
caret("AVERAGE", select = true)
task("SearchEverywhere") {
text(PythonLessonsBundle.message("python.onboarding.invoke.search.everywhere.1",
strong(toggleCase), code("AVERAGE")))
text(PythonLessonsBundle.message("python.onboarding.invoke.search.everywhere.2",
LessonUtil.rawKeyStroke(KeyEvent.VK_SHIFT), LessonUtil.actionName(it)))
triggerByUiComponentAndHighlight(highlightInside = false) { ui: ExtendableTextField ->
UIUtil.getParentOfType(SearchEverywhereUI::class.java, ui) != null
}
restoreIfModifiedOrMoved()
}
task {
transparentRestore = true
before {
if (backupPopupLocation != null) return@before
val ui = previous.ui ?: return@before
val popupWindow = UIUtil.getParentOfType(JWindow::class.java, ui) ?: return@before
val oldPopupLocation = WindowStateService.getInstance(project).getLocation(SearchEverywhereManagerImpl.LOCATION_SETTINGS_KEY)
if (adjustSearchEverywherePosition(popupWindow) || LessonUtil.adjustPopupPosition(project, popupWindow)) {
backupPopupLocation = oldPopupLocation
}
}
text(PythonLessonsBundle.message("python.onboarding.search.everywhere.description",
strong("AVERAGE"), strong(PythonLessonsBundle.message("toggle.case.part"))))
triggerByListItemAndHighlight { item ->
val value = (item as? GotoActionModel.MatchedValue)?.value
(value as? GotoActionModel.ActionWrapper)?.action is ToggleCaseAction
}
restoreByUi()
restoreIfModifiedOrMoved()
}
actionTask("EditorToggleCase") {
restoreByUi(delayMillis = defaultRestoreDelay)
PythonLessonsBundle.message("python.onboarding.apply.action", strong(toggleCase), LessonUtil.rawEnter())
}
text(PythonLessonsBundle.message("python.onboarding.case.changed"))
}
private fun LessonContext.showInterpreterConfiguration() {
task {
addFutureStep {
if (useDelay) {
Alarm().addRequest({ completeStep() }, 500)
}
else {
completeStep()
}
}
}
task {
triggerByUiComponentAndHighlight(highlightInside = false) { info: TextPanel.WithIconAndArrows ->
info.toolTipText.isToStringContains(PyBundle.message("current.interpreter", ""))
}
}
task {
before {
useDelay = false
}
text(PythonLessonsBundle.message("python.onboarding.interpreter.description"))
text(PythonLessonsBundle.message("python.onboarding.interpreter.tip"),
LearningBalloonConfig(Balloon.Position.above, width = 0))
restoreState(restoreId = openLearnTaskId) {
learningToolWindow(project)?.isVisible?.not() ?: true
}
restoreIfModified(sample)
proceedLink()
}
prepareRuntimeTask {
LearningUiHighlightingManager.clearHighlights()
}
}
private fun TaskRuntimeContext.runManager() = RunManager.getInstance(project)
private fun TaskRuntimeContext.configurations() =
runManager().allSettings.filter { it.name.contains(demoConfigurationName) }
private fun TaskRuntimeContext.adjustSearchEverywherePosition(popupWindow: JWindow): Boolean {
val indexOf = 4 + (editor.document.charsSequence.indexOf("8]))").takeIf { it > 0 } ?: return false)
val endOfEditorText = editor.offsetToXY(indexOf)
val locationOnScreen = editor.contentComponent.locationOnScreen
val leftBorder = Point(locationOnScreen.x + endOfEditorText.x, locationOnScreen.y + endOfEditorText.y)
val screenRectangle = ScreenUtil.getScreenRectangle(leftBorder)
val learningToolWindow = learningToolWindow(project) ?: return false
if (learningToolWindow.anchor != ToolWindowAnchor.LEFT) return false
val popupBounds = popupWindow.bounds
if (popupBounds.x > leftBorder.x) return false // ok, no intersection
val rightScreenBorder = screenRectangle.x + screenRectangle.width
if (leftBorder.x + popupBounds.width > rightScreenBorder) {
val mainWindow = UIUtil.getParentOfType(IdeFrameImpl::class.java, editor.contentComponent) ?: return false
val offsetFromBorder = leftBorder.x - mainWindow.x
val needToShiftWindowX = rightScreenBorder - offsetFromBorder - popupBounds.width
if (needToShiftWindowX < screenRectangle.x) return false // cannot shift the window back
mainWindow.location = Point(needToShiftWindowX, mainWindow.location.y)
popupWindow.location = Point(needToShiftWindowX + offsetFromBorder, popupBounds.y)
}
else {
popupWindow.location = Point(leftBorder.x, popupBounds.y)
}
return true
}
}
| apache-2.0 | 710005ead47ce93fc6f9a7fbdc4a46db | 37.934037 | 143 | 0.702426 | 5.124501 | false | false | false | false |
xmartlabs/bigbang | core/src/main/java/com/xmartlabs/bigbang/core/helper/ui/CircleTransform.kt | 2 | 2450 | /*
* Copyright 2014 Julian Shen
*
* 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.xmartlabs.bigbang.core.helper.ui
import android.graphics.Bitmap
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Shader
import com.squareup.picasso.Transformation
/**
* Transforms a [Bitmap] rounding its content.
* There's an option to add an outer border of any size and color.
*/
class CircleTransform(private val strokeWidth: Float = 0f, private val strokeColor: Int = 0) : Transformation {
companion object {
val KEY = "circle"
}
/**
* Rounds the given `source` into a circle and crops out the data outside of it.
*
* @param source the [Bitmap] instance to be rounded
* *
* @return a new [Bitmap] instance, the rounded representation of the `source`
*/
override fun transform(source: Bitmap): Bitmap {
val size = Math.min(source.width, source.height)
val x = (source.width - size) / 2
val y = (source.height - size) / 2
val squaredBitmap = Bitmap.createBitmap(source, x, y, size, size)
if (squaredBitmap != source) {
source.recycle()
}
val bitmap = Bitmap.createBitmap(size, size, source.config)
val canvas = Canvas(bitmap)
val paint = Paint()
val shader = BitmapShader(squaredBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
paint.shader = shader
paint.isAntiAlias = true
val center = size / 2f
val radius = center - strokeWidth
canvas.drawCircle(center, center, radius, paint)
if (strokeWidth > 0) {
val strokePaint = Paint()
strokePaint.color = strokeColor
strokePaint.style = Paint.Style.STROKE
strokePaint.isAntiAlias = true
strokePaint.strokeWidth = strokeWidth
canvas.drawCircle(center, center, radius, strokePaint)
}
squaredBitmap.recycle()
return bitmap
}
override fun key() = KEY
}
| apache-2.0 | 61edeb43992dce08ef5486ed8ab68bdf | 30.012658 | 111 | 0.70449 | 4.152542 | false | false | false | false |
sybila/terminal-components | src/main/java/com/github/sybila/Count.kt | 1 | 1631 | package com.github.sybila
import com.github.sybila.checker.Solver
import java.util.*
/**
* Count is a special data structure that allows us to keep the number of components
* for specific colors.
*/
class Count<T: Any>(private val solver: Solver<T>) {
private var data: List<T> = ArrayList<T>().apply {
this.add(solver.tt)
}
val size: Int
get() {
synchronized(this) {
return data.size
}
}
val max: Int
get() {
synchronized(this) {
return data.indexOfLast { solver.run { it.isSat() } } + 1
}
}
val min: Int
get() {
synchronized(this) {
return data.indexOfFirst { solver.run { it.isSat() } } + 1
}
}
private val default = solver.ff
operator fun get(index: Int): T {
synchronized(this) {
return if (index < data.size) data[index] else default
}
}
fun push(params: T) {
synchronized(this) {
solver.run {
val new = ArrayList<T>()
for (i in data.indices) {
addOrUnion(new, i, data[i] and params.not())
addOrUnion(new, i+1, data[i] and params)
}
[email protected] = new.dropLastWhile { it.isNotSat() }
}
}
}
private fun Solver<T>.addOrUnion(data: ArrayList<T>, index: Int, params: T) {
if (index < data.size) {
data[index] = (data[index] or params)
} else {
data.add(params)
}
}
} | gpl-3.0 | 99ccf09e8132b0a0d4cd2bb2a3509cb9 | 23 | 84 | 0.494175 | 4.02716 | false | false | false | false |
fkorotkov/k8s-kotlin-dsl | DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/rbac/ClassBuilders.kt | 1 | 2926 | // GENERATE
package com.fkorotkov.kubernetes.rbac
import io.fabric8.kubernetes.api.model.rbac.AggregationRule as rbac_AggregationRule
import io.fabric8.kubernetes.api.model.rbac.ClusterRole as rbac_ClusterRole
import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding as rbac_ClusterRoleBinding
import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBindingList as rbac_ClusterRoleBindingList
import io.fabric8.kubernetes.api.model.rbac.ClusterRoleList as rbac_ClusterRoleList
import io.fabric8.kubernetes.api.model.rbac.PolicyRule as rbac_PolicyRule
import io.fabric8.kubernetes.api.model.rbac.Role as rbac_Role
import io.fabric8.kubernetes.api.model.rbac.RoleBinding as rbac_RoleBinding
import io.fabric8.kubernetes.api.model.rbac.RoleBindingList as rbac_RoleBindingList
import io.fabric8.kubernetes.api.model.rbac.RoleList as rbac_RoleList
import io.fabric8.kubernetes.api.model.rbac.RoleRef as rbac_RoleRef
import io.fabric8.kubernetes.api.model.rbac.Subject as rbac_Subject
fun newAggregationRule(block : rbac_AggregationRule.() -> Unit = {}): rbac_AggregationRule {
val instance = rbac_AggregationRule()
instance.block()
return instance
}
fun newClusterRole(block : rbac_ClusterRole.() -> Unit = {}): rbac_ClusterRole {
val instance = rbac_ClusterRole()
instance.block()
return instance
}
fun newClusterRoleBinding(block : rbac_ClusterRoleBinding.() -> Unit = {}): rbac_ClusterRoleBinding {
val instance = rbac_ClusterRoleBinding()
instance.block()
return instance
}
fun newClusterRoleBindingList(block : rbac_ClusterRoleBindingList.() -> Unit = {}): rbac_ClusterRoleBindingList {
val instance = rbac_ClusterRoleBindingList()
instance.block()
return instance
}
fun newClusterRoleList(block : rbac_ClusterRoleList.() -> Unit = {}): rbac_ClusterRoleList {
val instance = rbac_ClusterRoleList()
instance.block()
return instance
}
fun newPolicyRule(block : rbac_PolicyRule.() -> Unit = {}): rbac_PolicyRule {
val instance = rbac_PolicyRule()
instance.block()
return instance
}
fun newRole(block : rbac_Role.() -> Unit = {}): rbac_Role {
val instance = rbac_Role()
instance.block()
return instance
}
fun newRoleBinding(block : rbac_RoleBinding.() -> Unit = {}): rbac_RoleBinding {
val instance = rbac_RoleBinding()
instance.block()
return instance
}
fun newRoleBindingList(block : rbac_RoleBindingList.() -> Unit = {}): rbac_RoleBindingList {
val instance = rbac_RoleBindingList()
instance.block()
return instance
}
fun newRoleList(block : rbac_RoleList.() -> Unit = {}): rbac_RoleList {
val instance = rbac_RoleList()
instance.block()
return instance
}
fun newRoleRef(block : rbac_RoleRef.() -> Unit = {}): rbac_RoleRef {
val instance = rbac_RoleRef()
instance.block()
return instance
}
fun newSubject(block : rbac_Subject.() -> Unit = {}): rbac_Subject {
val instance = rbac_Subject()
instance.block()
return instance
}
| mit | 12a5e0b7dfe65869951a2751d3d538f5 | 28.26 | 113 | 0.750171 | 3.402326 | false | false | false | false |
alexstyl/Memento-Namedays | android_mobile/src/main/java/com/alexstyl/specialdates/events/peopleevents/AndroidPeopleEventsPersister.kt | 3 | 4664 | package com.alexstyl.specialdates.events.peopleevents
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteException
import android.database.sqlite.SQLiteOpenHelper
import com.alexstyl.specialdates.CrashAndErrorTracker
import com.alexstyl.specialdates.contact.Contact
import com.alexstyl.specialdates.contact.ContactSource
import com.alexstyl.specialdates.date.ContactEvent
import com.alexstyl.specialdates.events.database.DatabaseContract.AnnualEventsContract
import com.alexstyl.specialdates.events.database.EventColumns
import com.alexstyl.specialdates.events.database.EventTypeId.TYPE_NAMEDAY
class AndroidPeopleEventsPersister(private val helper: SQLiteOpenHelper,
private val marshaller: ContactEventsMarshaller,
private val tracker: CrashAndErrorTracker)
: PeopleEventsPersister {
override fun deleteAllNamedays() {
helper.writableDatabase
.executeTransaction {
delete(
AnnualEventsContract.TABLE_NAME,
"${AnnualEventsContract.EVENT_TYPE} == $TYPE_NAMEDAY",
null)
}
}
override fun deleteAllEventsOfSource(@ContactSource source: Int) {
helper.writableDatabase
.executeTransaction {
delete(AnnualEventsContract.TABLE_NAME,
AnnualEventsContract.SOURCE + "==" + source,
null)
}
}
override fun deleteAllDeviceEvents() {
helper.writableDatabase
.executeTransaction {
delete(AnnualEventsContract.TABLE_NAME,
"${EventColumns.SOURCE} == ${ContactSource.SOURCE_DEVICE}" +
" AND ${EventColumns.EVENT_TYPE} != ${StandardEventType.NAMEDAY.id}"
, null)
}
}
override fun insertAnnualEvents(events: List<ContactEvent>) {
helper.writableDatabase
.executeTransaction {
marshaller
.marshall(events)
.forEach { contentValues ->
insert(AnnualEventsContract.TABLE_NAME, null, contentValues)
}
}
}
override fun markContactAsVisible(contact: Contact) {
helper.writableDatabase
.executeTransaction {
update(
AnnualEventsContract.TABLE_NAME,
visible(),
AnnualEventsContract.CONTACT_ID + " = " + contact.contactID
+ " AND " + AnnualEventsContract.SOURCE + " = " + contact.source, null)
}
}
private fun visible(): ContentValues {
return ContentValues(1).apply {
put(AnnualEventsContract.VISIBLE, 1)
}
}
override fun markContactAsHidden(contact: Contact) {
helper.writableDatabase
.executeTransaction {
update(AnnualEventsContract.TABLE_NAME,
hidden(),
AnnualEventsContract.CONTACT_ID + " = " + contact.contactID
+ " AND " + AnnualEventsContract.SOURCE + " = " + contact.source, null)
}
}
private fun hidden(): ContentValues {
val values = ContentValues(1)
values.put(AnnualEventsContract.VISIBLE, 0)
return values
}
override fun getVisibilityFor(contact: Contact): Boolean {
val database = helper.writableDatabase
// TODO just COUNT() events the contact has
val query = database.query(
AnnualEventsContract.TABLE_NAME, null,
AnnualEventsContract.CONTACT_ID + " == " + contact.contactID
+ " AND " + AnnualEventsContract.SOURCE + " == " + contact.source
+ " AND " + AnnualEventsContract.VISIBLE + " = 1", null, null, null, null
)
val count = query.count
query.close()
return count > 0
}
private inline fun SQLiteDatabase.executeTransaction(function: SQLiteDatabase.() -> Unit) {
try {
this.beginTransaction()
function(this)
this.setTransactionSuccessful()
} catch (e: SQLiteException) {
tracker.track(e)
} finally {
this.endTransaction()
}
}
}
| mit | 9d50e4737300ba7b246cde4078a13100 | 36.918699 | 107 | 0.561964 | 5.5 | false | false | false | false |
deviant-studio/energy-meter-scanner | app/src/main/java/ds/meterscanner/mvvm/view/AlarmsActivity.kt | 1 | 1423 | package ds.meterscanner.mvvm.view
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutCompat.VERTICAL
import ds.bindingtools.withBindable
import ds.meterscanner.R
import ds.meterscanner.adapter.AlarmsAdapter
import ds.meterscanner.mvvm.AlarmsView
import ds.meterscanner.mvvm.BindableActivity
import ds.meterscanner.mvvm.viewmodel.AlarmsViewModel
import ds.meterscanner.ui.DatePickers
import kotlinx.android.synthetic.main.activity_alarms.*
import kotlinx.android.synthetic.main.toolbar.*
import java.util.*
class AlarmsActivity : BindableActivity<AlarmsViewModel>(), AlarmsView {
override fun pickTime(time: Date, callback: (hour: Int, minute: Int) -> Unit) =
DatePickers.pickTime(this, time, callback)
override fun provideViewModel(): AlarmsViewModel = defaultViewModelOf()
override fun getLayoutId(): Int = R.layout.activity_alarms
override fun bindView() {
super.bindView()
toolbar.title = getString(R.string.alarms)
val adapter = AlarmsAdapter(
{ viewModel.onEditAlarm(this, it) },
viewModel::onDeleteAlarm
)
recyclerView.adapter = adapter
recyclerView.addItemDecoration(DividerItemDecoration(this, VERTICAL))
fab.setOnClickListener { viewModel.onNewAlarm(this) }
withBindable(viewModel) {
bind(::listItems, adapter::data)
}
}
} | mit | 7443795caf3a1672b84f05b9d5b70591 | 34.6 | 83 | 0.73858 | 4.312121 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-skills-bukkit/src/main/kotlin/com/rpkit/skills/bukkit/listener/PlayerInteractListener.kt | 1 | 4293 | /*
* Copyright 2019 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.skills.bukkit.listener
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import com.rpkit.skills.bukkit.RPKSkillsBukkit
import com.rpkit.skills.bukkit.skills.RPKSkillProvider
import com.rpkit.skills.bukkit.skills.canUse
import com.rpkit.skills.bukkit.skills.use
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerInteractEvent
class PlayerInteractListener(private val plugin: RPKSkillsBukkit): Listener {
@EventHandler
fun onPlayerInteract(event: PlayerInteractEvent) {
if (event.player.hasPermission("rpkit.skills.command.skill")) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val skillProvider = plugin.core.serviceManager.getServiceProvider(RPKSkillProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(event.player)
if (minecraftProfile != null) {
val character = characterProvider.getActiveCharacter(minecraftProfile)
if (character != null) {
val item = event.item
if (item != null) {
val skill = skillProvider.getSkillBinding(character, item)
if (skill != null) {
if (character.canUse(skill)) {
if (character.mana >= skill.manaCost) {
if (skillProvider.getSkillCooldown(character, skill) <= 0) {
character.use(skill)
skillProvider.setSkillCooldown(character, skill, skill.cooldown)
character.mana -= skill.manaCost
characterProvider.updateCharacter(character)
event.player.sendMessage(plugin.messages["skill-valid", mapOf(
Pair("skill", skill.name)
)])
} else {
event.player.sendMessage(plugin.messages["skill-invalid-on-cooldown", mapOf(
Pair("skill", skill.name),
Pair("cooldown", skillProvider.getSkillCooldown(character, skill).toString())
)])
}
} else {
event.player.sendMessage(plugin.messages["skill-invalid-not-enough-mana", mapOf(
Pair("skill", skill.name),
Pair("mana-cost", skill.manaCost.toString()),
Pair("mana", character.mana.toString()),
Pair("max-mana", character.maxMana.toString())
)])
}
} else {
event.player.sendMessage(plugin.messages["skill-invalid-unmet-prerequisites", mapOf(
Pair("skill", skill.name)
)])
}
}
}
}
}
}
}
} | apache-2.0 | 4e9937b4f9d7f2b7d500de532d9fbf56 | 51.365854 | 125 | 0.532728 | 5.872777 | false | false | false | false |
siosio/nablarch-helper | src/main/java/siosio/repository/converter/RepositoryRefConverter.kt | 1 | 2590 | package siosio.repository.converter
import com.intellij.codeInsight.lookup.*
import com.intellij.psi.*
import com.intellij.psi.util.*
import com.intellij.psi.xml.*
import com.intellij.util.xml.*
import siosio.repository.xml.*
/**
* propertyタグのref属性のコンポーネントを解決するコンバータ
*/
class RepositoryRefConverter : ResolvingConverter<XmlTag>() {
override fun getVariants(context: ConvertContext?): MutableCollection<out XmlTag> {
val element = context?.referenceXmlElement
return if (element is XmlAttributeValue) {
ComponentCreator(element).findAll(context).map {
it.component.xmlTag
}.toMutableList()
} else {
mutableListOf()
}
}
override fun createLookupElement(t: XmlTag): LookupElement? {
return LookupElementBuilder.create(t, t.getAttributeValue("name")!!)
.withIcon(t.getIcon(0))
.withTypeText(t.containingFile.name)
.withAutoCompletionPolicy(AutoCompletionPolicy.ALWAYS_AUTOCOMPLETE)
}
override fun fromString(name: String?, context: ConvertContext?): XmlTag? {
// todo 複数あるのか(´・ω・`)
return XmlHelper.findNamedElement(context).lastOrNull {
it.name.value == name
}?.xmlTag
}
override fun toString(component: XmlTag?, context: ConvertContext?): String? {
return component?.getAttributeValue("name")
}
class ComponentCreator(private val xmlAttributeValue: XmlAttributeValue) {
fun findAll(context: ConvertContext): Array<NamedElementHolder> {
val namedElements = XmlHelper.findNamedElement(context)
.filterIsInstance(Component::class.java)
.map { component ->
component.componentClass.value?.let {
NamedElementHolder(component, it)
}
}.filterNotNull()
val propertyTag = DomUtil.getDomElement(PsiTreeUtil.getParentOfType(xmlAttributeValue, XmlTag::class.java)) as? Property ?: return emptyArray()
val parameterList = propertyTag.name.value?.parameterList ?: return emptyArray()
return if (parameterList.parametersCount == 1) {
parameterList.parameters.firstOrNull()?.type
} else {
null
}?.let { type ->
namedElements.asSequence().filter {
XmlHelper.isAssignableFrom(type, it.componentType)
}.toList().toTypedArray()
} ?: emptyArray()
}
data class NamedElementHolder(
val component: Component,
val componentClass: PsiClass
) {
val componentType: PsiClassType = PsiTypesUtil.getClassType(componentClass)
}
}
}
| apache-2.0 | 1bbad30127c011257116889e2762cd1f | 32.236842 | 149 | 0.689628 | 4.609489 | false | false | false | false |
everis-innolab/interledger-ledger | src/main/java/com/everis/everledger/handlers/TransferHandlers.kt | 1 | 28655 | package com.everis.everledger.handlers
/*
* TODO:(?) Remove debitor/creditor for code. Use TX_src/TX_dst or imilar to avoid confusion with debit/credit terms.
* TODO:(?) For blockchains ai.isAdmin doesn't make any sense => There is no "root" admin user.
*/
import com.everis.everledger.AuthInfo
import com.everis.everledger.ifaces.account.IfaceAccount
import com.everis.everledger.util.Config
import com.everis.everledger.ifaces.account.IfaceLocalAccountManager
import com.everis.everledger.ifaces.transfer.ILocalTransfer
import com.everis.everledger.ifaces.transfer.IfaceTransferManager
import com.everis.everledger.ifaces.transfer.TransferStatus
import com.everis.everledger.impl.*
import com.everis.everledger.impl.manager.SimpleAccountManager
import com.everis.everledger.impl.manager.SimpleTransferManager
import com.everis.everledger.util.*
import io.netty.handler.codec.http.HttpResponseStatus
import io.vertx.core.http.HttpHeaders
import io.vertx.core.http.HttpMethod
import io.vertx.core.json.JsonArray
import io.vertx.core.json.JsonObject
import io.vertx.core.logging.LoggerFactory
import io.vertx.ext.web.RoutingContext
import org.interledger.Condition
import org.interledger.Fulfillment
import org.interledger.ilp.InterledgerProtocolError
import org.javamoney.moneta.Money
import java.net.URI
import java.security.MessageDigest
import java.time.ZonedDateTime
import java.util.*
import javax.money.Monetary
import javax.money.MonetaryAmount
private val AM : IfaceLocalAccountManager = SimpleAccountManager;
private val TM : IfaceTransferManager = SimpleTransferManager;
private val currencyUnit /* local ledger currency */ = Monetary.getCurrency(Config.ledgerCurrencyCode)
class TransferHandler
// GET|PUT /transfers/3a2a1d9e-8640-4d2d-b06c-84f2cd613204
private constructor() : RestEndpointHandler(
arrayOf(HttpMethod.GET, HttpMethod.PUT, HttpMethod.POST), arrayOf("transfers/:" + transferUUID )) {
override fun handlePut(context: RoutingContext) {
val ai = AuthManager.authenticate(context)
val requestBody = RestEndpointHandler.getBodyAsJson(context)
log.trace(this.javaClass.name + "handlePut invoqued ")
log.trace(context.bodyAsString)
/*
* REQUEST: PUT /transfers/3a2a1d9e-8640-4d2d-b06c-84f2cd613204 HTTP/1.1
* Authorization: Basic YWxpY2U6YWxpY2U=
* {"id":"http://localhost/transfers/3a2a1d9e-8640-4d2d-b06c-84f2cd613204"
* , "ledger":"http://localhost", "debits":[
* {"account":"http://localhost/accounts/alice","amount":"50"},
* {"account":"http://localhost/accounts/candice","amount":"20"}],
* "credits":[
* {"account":"http://localhost/accounts/bob","amount":"30"},
* {"account":"http://localhost/accounts/dave","amount":"40"}],
* "execution_condition"
* :"cc:0:3:Xk14jPQJs7vrbEZ9FkeZPGBr0YqVzkpOYjFp_tIZMgs:7",
* "expires_at":"2015-06-16T00:00:01.000Z", "state":"prepared"} ANSWER:
* HTTP/1.1 201 Created
* {"id":"http://localhost/transfers/3a2a1d9e-8640-4d2d-b06c-84f2cd613204"
* , "ledger":..., "debits":[ ... ] "credits":[ ... ]
* "execution_condition":"...", "expires_at":..., "state":"proposed",
* "timeline":{"proposed_at":"2015-06-16T00:00:00.000Z"} }
*/
val ilpTransferID: UUID
try {
ilpTransferID = UUID.fromString(context.request().getParam(transferUUID))
} catch (e: Exception) {
throw ILPExceptionSupport.createILPBadRequestException(
"'" + context.request().getParam(transferUUID) + "' is not a valid UUID")
}
val transferID : ILocalTransfer.LocalTransferID = ILPSpec2LocalTransferID(ilpTransferID)
// TODO: Check requestBody.getString("ledger") match ledger host/port
// TODO: Check state is 'proposed' for new transactions?
// TODO:(?) mark as "Tainted" object
val debits = requestBody.getJsonArray("debits") ?: throw ILPExceptionSupport.createILPBadRequestException("debits not found")
if (debits.size() != 1) {
throw ILPExceptionSupport.createILPBadRequestException("Only one debitor supported by ledger")
}
val jsonDebit = debits.getJsonObject(0)
// debit0 will be similar to
// {"account":"http://localhost/accounts/alice","amount":"50"}
var input_account_id = jsonDebit.getString("account")
if (input_account_id.lastIndexOf('/') > 0) {
input_account_id = input_account_id.substring(input_account_id.lastIndexOf('/') + 1)
}
val debit_ammount: MonetaryAmount = try {
val auxDebit = java.lang.Double.parseDouble(jsonDebit.getString("amount"))
Money.of(auxDebit, currencyUnit)
} catch (e: Exception) {
println(e.toString())
throw ILPExceptionSupport.createILPBadRequestException("unparseable amount")
}
if ( debit_ammount.number.toFloat().toDouble() == 0.0) {
throw ILPExceptionSupport.createILPException(422, InterledgerProtocolError.ErrorCode.F00_BAD_REQUEST, "debit is zero")
}
val debitor = AM.getAccountById(input_account_id)
_assertAuthInfoMatchTXDebitorOrThrow(debitor, ai)
val jsonMemo = requestBody.getJsonObject("memo")
val sMemo = if (jsonMemo == null) "" else jsonMemo.encode()
// REF: JsonArray ussage:
// http://www.programcreek.com/java-api-examples/index.php?api=io.vertx.core.json.JsonArray
val credits = requestBody.getJsonArray("credits")
val sExpiresAt = requestBody.getString("expires_at") // can be null
val DTTM_expires: ZonedDateTime
try {
DTTM_expires = if (sExpiresAt == null) TimeUtils.future else ZonedDateTime.parse(sExpiresAt)
} catch (e: Exception) {
throw ILPExceptionSupport.createILPBadRequestException("unparseable expires_at")
}
val execution_condition = requestBody.getString("execution_condition")
val URIExecutionCond: Condition = if (execution_condition != null)
ConversionUtil.parseURI(URI.create(execution_condition))
else CC_NOT_PROVIDED
val jsonCredit = credits.getJsonObject(0)
/* { "account":"http://localhost:3002/accounts/ilpconnector",
* "amount":"1.01", "memo":{ "ilp_header":{
* "account":"ledger3.eur.alice.fe773626-81fb-4294-9a60-dc7b15ea841e"
* , "amount":"1", "data":{"expires_at":"2016-11-10T15:51:27.134Z"}
* } } } */
// JsonObject jsonMemoILPHeader = jsonCredit.getJsonObject("memo")
// COMMENTED OLD API .getJsonObject("ilp_header");
var credit_account_id = jsonCredit.getString("account")
if (credit_account_id.lastIndexOf('/') > 0) {
credit_account_id = credit_account_id.substring(credit_account_id.lastIndexOf('/') + 1)
}
val credit_ammount: MonetaryAmount = try {
val auxCredit = java.lang.Double.parseDouble(jsonCredit.getString("amount"))
Money.of(auxCredit, currencyUnit)
} catch (e: Exception) {
throw ILPExceptionSupport.createILPBadRequestException("unparseable amount")
}
if (credit_ammount.getNumber().toFloat().toDouble() == 0.0) {
throw ILPExceptionSupport.createILPException(422,
InterledgerProtocolError.ErrorCode.F00_BAD_REQUEST, "credit is zero")
}
val creditor = AM.getAccountById(credit_account_id)
if (!credit_ammount.equals(debit_ammount)) {
throw ILPExceptionSupport.createILPException(422,
InterledgerProtocolError.ErrorCode.F00_BAD_REQUEST, "total credits do not match total debits")
}
val data = "" // Not yet used
val noteToSelf = "" // Not yet used
val DTTM_proposed = ZonedDateTime.now() // TODO:(?) Add proposed -> prepared support
val DTTM_prepared = ZonedDateTime.now() // TODO:(?) Add proposed -> prepared support
val cancelation_condition = requestBody.getString("cancellation_condition")
val URICancelationCond = if (cancelation_condition != null)
ConversionUtil.parseURI(URI.create(cancelation_condition)) else CC_NOT_PROVIDED
val status = TransferStatus.PROPOSED // By default
// if (requestBody.getString("state") != null) {
// // TODO: Must status change be allowed or must we force it to be
// // 'prepared'?
// // (only Execution|Cancellation Fulfillments will change the state)
// // At this moment it's allowed (to make it compliant with
// // five-bells-ledger tests)
// status = TransferStatus.parse(requestBody.getString("state"));
// log.debug("transfer status " + status);
// }
val receivedTransfer = SimpleTransferIfaceILP(
transferID as LocalTransferID,
TXInputImpl(debitor, debit_ammount),
TXOutputImpl(creditor, credit_ammount/*, memo_ph*/),
URIExecutionCond, URICancelationCond,
DTTM_proposed, DTTM_prepared, DTTM_expires, TimeUtils.future, TimeUtils.future,
data, noteToSelf,
status,
sMemo,
FF_NOT_PROVIDED, FF_NOT_PROVIDED )
// TODO:(0) Next logic must be on the Manager, not in the HTTP-protocol related handler
val isNewTransfer = !TM.doesTransferExists(ilpTransferID)
log.debug("is new transfer?: " + isNewTransfer)
val effectiveTransfer = if (isNewTransfer) receivedTransfer else TM.getTransferById(transferID)
if (!isNewTransfer) {
// Check that received json data match existing transaction.
// TODO: Recheck (Multitransfer active now)
if ( effectiveTransfer.txInput != receivedTransfer.txInput
|| effectiveTransfer.txInput != receivedTransfer.txInput) {
throw ILPExceptionSupport.createILPBadRequestException(
"data for credits and/or debits doesn't match existing registry")
}
} else {
TM.prepareILPTransfer(receivedTransfer)
}
try { // TODO:(?) Refactor Next code for notification (next two loops) are
// duplicated in FulfillmentHandler
val resource = (effectiveTransfer as SimpleTransferIfaceILP).toILPJSONStringifiedFormat()
// Notify affected accounts:
val eventType = if (receivedTransfer.transferStatus == TransferStatus.PREPARED)
TransferWSEventHandler.EventType.TRANSFER_CREATE
else TransferWSEventHandler.EventType.TRANSFER_UPDATE
val setAffectedAccounts = HashSet<String>()
setAffectedAccounts.add(receivedTransfer.txOutput.localAccount.localID)
setAffectedAccounts.add(receivedTransfer.txInput .localAccount.localID)
TransferWSEventHandler.notifyListener(setAffectedAccounts, eventType, resource, null)
} catch (e: Exception) {
log.warn("transaction created correctly but ilp-connector couldn't be notified due to " + e.toString())
}
val response = (effectiveTransfer as SimpleTransferIfaceILP).toILPJSONStringifiedFormat().encode()
context.response()
.putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.putHeader(HttpHeaders.CONTENT_LENGTH, "" + response.length)
.setStatusCode( if (isNewTransfer)
HttpResponseStatus.CREATED.code()
else HttpResponseStatus.OK.code()).
end(response)
}
override fun handleGet(context: RoutingContext) {
log.debug(this.javaClass.name + "handleGet invoqued ")
val ai = AuthManager.authenticate(context)
val ilpTransferID = UUID.fromString(context.request().getParam(transferUUID))
val transfer = TM.getTransferById(ILPSpec2LocalTransferID(ilpTransferID))
val debitor = AM.getAccountById(transfer.txInput.localAccount.localID)
_assertAuthInfoMatchTXDebitorOrThrow(debitor, ai)
response( context, HttpResponseStatus.OK, (transfer as SimpleTransferIfaceILP).toILPJSONStringifiedFormat())
}
private fun _assertAuthInfoMatchTXDebitorOrThrow(debitor: IfaceAccount, ai : AuthInfo){
var transferMatchUser = AM.authInfoMatchAccount(debitor, ai)
if (!ai.isAdmin && !transferMatchUser) {
log.error("transferMatchUser false and user is not ADMIN: "
+ "\n ai.id :" + ai.id
+ "\n transfer.txInput.localAccount.localID:" + debitor)
throw ILPExceptionSupport.createILPForbiddenException()
}
}
companion object {
private val log = LoggerFactory.getLogger(AccountsHandler::class.java)
private val transferUUID = "transferUUID";
fun create(): TransferHandler = TransferHandler()
}
}
// GET /transfers/byExecutionCondition/cc:0:3:vmvf6B7EpFalN6RGDx9F4f4z0wtOIgsIdCmbgv06ceI:7
class TransfersHandler : RestEndpointHandler(arrayOf(HttpMethod.GET), arrayOf("transfers/byExecutionCondition/:" + execCondition)) {
override fun handleGet(context: RoutingContext) {
/*
* GET /transfers/byExecutionCondition/cc:0:3:vmvf6B7EpFalN...I:7 HTTP/1.1
* HTTP/1.1 200 OK
* [{"ledger":"http://localhost",
* "execution_condition":"cc:0:3:vmvf6B7EpFalN...I:7",
* "cancellation_condition":"cc:0:3:I3TZF5S3n0-...:6",
* "id":"http://localhost/transfers/9e97a403-f604-44de-9223-4ec36aa466d9",
* "state":"executed",
* "debits":[
* {"account":"http://localhost/accounts/alice","amount":"10","authorized":true}],
* "credits":[{"account":"http://localhost/accounts/bob","amount":"10"}]}]
*/
log.trace(this.javaClass.name + "handleGet invoqued ")
val ai = AuthManager.authenticate(context)
// Condition condition = CryptoConditionUri.parse(URI.create(testVector.getConditionUri()));
val sExecCond = context.request().getParam(execCondition)
val executionCondition: Condition
executionCondition = ConversionUtil.parseURI(URI.create(sExecCond))
val transferList = TM.getTransfersByExecutionCondition(executionCondition)
val ja = JsonArray()
for (transfer in transferList) {
val debitor = AM.getAccountById(transfer.txInput .localAccount.localID)
val creditor = AM.getAccountById(transfer.txOutput.localAccount.localID)
if ( !ai.isAdmin &&
!( AM.authInfoMatchAccount(debitor , ai) ||
AM.authInfoMatchAccount(creditor , ai) ) ) continue
ja.add((transfer as SimpleTransferIfaceILP).toILPJSONStringifiedFormat())
}
val response = ja.encode()
context.response()
.putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.putHeader(HttpHeaders.CONTENT_LENGTH, "" + response.length)
.setStatusCode(HttpResponseStatus.OK.code())
.end(response)
}
companion object {
private val log = org.slf4j.LoggerFactory.getLogger(TransfersHandler::class.java)
private val execCondition = "execCondition"
fun create(): TransfersHandler = TransfersHandler()
}
}// REF: https://github.com/interledger/five-bells-ledger/blob/master/src/lib/app.js
// GET /transfers/25644640-d140-450e-b94b-badbe23d3389/state|state?type=sha256
class TransferStateHandler : RestEndpointHandler(
arrayOf(HttpMethod.GET), arrayOf("transfers/:$transferUUID/state")) {
override fun handleGet(context: RoutingContext) {
/* GET transfer by UUID & type
* *****************************
* GET /transfers/3a2a1d9e-8640-4d2d-b06c-84f2cd613204/state?type=sha256 HTTP/1.1
* {"type":"sha256",
* "message":{
* "id":"http:.../transfers/3a2a1d9e-8640-4d2d-b06c-84f2cd613204",
* "state":"proposed",
* "token":"xy9kB4n......Cg=="
* },
* "signer":"http://localhost",
* "digest":"P6K2HEaZxAthBeGmbjeyPau0BIKjgkaPqW781zmSvf4="
* } */
log.debug(this.javaClass.name + "handleGet invoqued ")
val ai = AuthManager.authenticate(context)
val transferId = context.request().getParam(transferUUID)
val transferID = LocalTransferID(transferId)
if (!TM.doesTransferExists(transferID))
throw ILPExceptionSupport.createILPNotFoundException()
val transfer = TM.getTransferById(transferID)
var status = transfer.transferStatus
val debitor = AM.getAccountById(transfer.txInput .localAccount.localID)
var transferMatchUser = AM.authInfoMatchAccount(debitor , ai)
if (!ai.isAdmin && !transferMatchUser) throw ILPExceptionSupport.createILPForbiddenException()
// REF: getStateResource @ transfers.js
var receiptType: String? = context.request().getParam("type")
// REF: getTransferStateReceipt(id, receiptType, conditionState) @ five-bells-ledger/src/models/transfers.js
if (receiptType == null) {
receiptType = RECEIPT_TYPE_ED25519
}
if (receiptType != RECEIPT_TYPE_ED25519 &&
receiptType != RECEIPT_TYPE_SHA256 &&
true) {
throw ILPExceptionSupport.createILPBadRequestException(
"type not in := $RECEIPT_TYPE_ED25519* | $RECEIPT_TYPE_SHA256 "
)
}
val jo = JsonObject()
val signer = "" // FIXME: config.getIn(['server', 'base_uri']),
if (receiptType == RECEIPT_TYPE_ED25519) {
// REF: makeEd25519Receipt(transferId, transferState) @
// @ five-bells-ledger/src/models/transfers.js
val message = makeTransferStateMessage(transferID, status, RECEIPT_TYPE_ED25519)
val signature = "" // FIXME: sign(hashJSON(message))
jo.put("type", RECEIPT_TYPE_ED25519)
jo.put("message", message)
jo.put("signer", signer)
jo.put("public_key", DSAPrivPubKeySupport.savePublicKey(Config.ilpLedgerInfo.notificationSignPublicKey))
jo.put("signature", signature)
} else {
// REF: makeSha256Receipt(transferId, transferState, conditionState) @
// @ five-bells-ledger/src/models/transfers.js
val message = makeTransferStateMessage(transferID, status, RECEIPT_TYPE_SHA256)
val digest = sha256(message.encode())
jo.put("type", RECEIPT_TYPE_SHA256)
jo.put("message", message)
jo.put("signer", signer)
jo.put("digest", digest)
val conditionState = context.request().getParam("condition_state")
if (conditionState != null) {
val conditionMessage = makeTransferStateMessage(transferID, status, RECEIPT_TYPE_SHA256)
val condition_digest = sha256(conditionMessage.encode())
jo.put("condition_state", conditionState)
jo.put("condition_digest", condition_digest)
}
}
val response = jo.encode()
context.response()
.putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.putHeader(HttpHeaders.CONTENT_LENGTH, "" + response.length)
.setStatusCode(HttpResponseStatus.OK.code())
.end(response)
}
companion object {
private val log = org.slf4j.LoggerFactory.getLogger(TransferStateHandler::class.java)
private val transferUUID = "transferUUID"
private val RECEIPT_TYPE_ED25519 = "ed25519-sha512"
private val RECEIPT_TYPE_SHA256 = "sha256"
private val md256: MessageDigest
init {
md256 = MessageDigest.getInstance("SHA-256")
}
fun create(): TransferStateHandler = TransferStateHandler()
private fun makeTransferStateMessage(transferId: LocalTransferID, state: TransferStatus, receiptType: String): JsonObject {
val jo = JsonObject()
// <-- TODO:(0) Move URI logic to Iface ILPTransferSupport and add iface to SimpleLedgerTransferManager
jo.put("id", Config.publicURL.toString() + "transfers/" + transferId.transferID)
jo.put("state", state.toString())
if (receiptType == RECEIPT_TYPE_SHA256) {
val token = "" // FIXME: sign(sha512(transferId + ':' + state))
jo.put("token", token)
}
return jo
}
private fun sha256(input: String): String {
md256.reset()
md256.update(input.toByteArray())
return String(md256.digest())
}
}
}// REF: https://github.com/interledger/five-bells-ledger/blob/master/src/lib/app.js
/*
* GET|PUT /transfers/25644640-d140-450e-b94b-badbe23d3389/fulfillment
* fulfillment can be execution or cancellation
* Note: Rejection != cancellation. Rejection in five-bells-ledger refers
* to the rejection in the proposed (not-yet prepared) transfer (or part of the
* transfer).
* In the java-vertx-ledger there is not yet (2017-05) concept of proposed
* state.
*/
class FulfillmentHandler : RestEndpointHandler(arrayOf(HttpMethod.GET, HttpMethod.PUT), arrayOf("transfers/:$transferUUID/fulfillment")) {
override fun handlePut(context: RoutingContext) {
// val ai = AuthManager.authenticate(context)
log.trace(this.javaClass.name + "handlePut invoqued ")
/* (request from ILP Connector)
* PUT /transfers/25644640-d140-450e-b94b-badbe23d3389/fulfillment HTTP/1.1 */
val ilpTransferID = UUID.fromString(context.request().getParam(transferUUID))
val transferID = ILPSpec2LocalTransferID(ilpTransferID)
/*
* REF: https://gitter.im/interledger/Lobby
* Enrique Arizon Benito @earizon 17:51 2016-10-17
* Hi, I'm trying to figure out how the five-bells-ledger implementation validates fulfillments.
* Following the node.js code I see the next route:
*
* router.put('/transfers/:id/fulfillment', transfers.putFulfillment)
*
* I understand the fulfillment is validated at this (PUT) point against the stored condition
* in the existing ":id" transaction.
* Following the stack for this request it looks to me that the method
*
* (/five-bells-condition/index.js)validateFulfillment (serializedFulfillment, serializedCondition, message)
*
* is always being called with an undefined message and so an empty one is being used.
* I'm missing something or is this the expected behaviour?
*
* Stefan Thomas @justmoon 18:00 2016-10-17
* @earizon Yes, this is expected. We're using crypto conditions as a trigger, not to verify the
* authenticity of a message!
* Note that the actual cryptographic signature might still be against a message - via prefix
* conditions (which append a prefix to this empty message)
**/
val transfer = TM.getTransferById(transferID)
if (transfer.executionCondition === CC_NOT_PROVIDED) {
throw ILPExceptionSupport.createILPUnprocessableEntityException(
this.javaClass.name + "Transfer is not conditional")
}
val sFulfillmentInput = context.bodyAsString
val fulfillmentBytes = Base64.getDecoder().decode(sFulfillmentInput)
// // REF: http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java
// byte[] fulfillmentBytes = DatatypeConverter.parseHexBinary(sFulfillment);
val inputFF = Fulfillment.of(fulfillmentBytes)
// val message = byteArrayOf()
var ffExisted = false // TODO:(0) Recheck usage
log.trace("transfer.getExecutionCondition():" + transfer.executionCondition.toString())
// log.trace("transfer.getCancellationCondition():"+transfer.getCancellationCondition().toString());
log.trace("request hexFulfillment:" + sFulfillmentInput)
log.trace("request ff.getCondition():" + inputFF.condition.toString())
if (transfer.executionCondition == inputFF.condition) {
if (!inputFF.validate(inputFF.condition))
throw ILPExceptionSupport.createILPUnprocessableEntityException("execution fulfillment doesn't validate")
if (transfer.ilpExpiresAt.compareTo(ZonedDateTime.now()) < 0 && Config.unitTestsActive == false)
throw ILPExceptionSupport.createILPUnprocessableEntityException("transfer expired")
if (transfer.transferStatus != TransferStatus.EXECUTED)
TM.executeILPTransfer(transfer, inputFF)
// } else if (transfer.getCancellationCondition().equals(inputFF.getCondition()) ){
// if ( transfer.getTransferStatus() == TransferStatus.EXECUTED) {
// throw ILPExceptionSupport.createILPBadRequestException("Already executed");
// }
// ffExisted = transfer.getCancellationFulfillment().equals(inputFF);
// if (!ffExisted) {
// if (!inputFF.verify(inputFF.getCondition(), message)){
// throw ILPExceptionSupport.createILPUnprocessableEntityException("cancelation fulfillment doesn't validate");
// }
// TM.cancelILPTransfer(transfer, inputFF);
// }
} else {
throw ILPExceptionSupport.createILPUnprocessableEntityException(
"Fulfillment does not match any condition")
}
val response = ConversionUtil.fulfillmentToBase64(inputFF)
if (sFulfillmentInput != response) {
throw ILPExceptionSupport.createILPBadRequestException(
"Assert exception. Input '$sFulfillmentInput'doesn't match output '$response' ")
}
context.response()
.putHeader(HttpHeaders.CONTENT_TYPE, "text/plain")
.putHeader(HttpHeaders.CONTENT_LENGTH, "" + response.length)
.setStatusCode(if (!ffExisted) HttpResponseStatus.CREATED.code() else HttpResponseStatus.OK.code())
.end(response)
}
override fun handleGet(context: RoutingContext) {
// GET /transfers/25644640-d140-450e-b94b-badbe23d3389/fulfillment
val ai = AuthManager.authenticate(context)
val ilpTransferID = UUID.fromString(context.request().getParam(transferUUID))
val transferID = ILPSpec2LocalTransferID(ilpTransferID)
val transfer = TM.getTransferById(transferID)
val debitor = AM.getAccountById(transfer.txInput .localAccount.localID)
val creditor = AM.getAccountById(transfer.txOutput.localAccount.localID)
var transferMatchUser = AM.authInfoMatchAccount(debitor , ai)
|| AM.authInfoMatchAccount(creditor, ai)
if (!ai.isAdmin && !(ai.isConnector && transferMatchUser))
throw ILPExceptionSupport.createILPForbiddenException()
val fulfillment = transfer.executionFulfillment
if (fulfillment === FF_NOT_PROVIDED) {
if (transfer.ilpExpiresAt.compareTo(ZonedDateTime.now()) < 0) {
throw ILPExceptionSupport.createILPNotFoundException("This transfer expired before it was fulfilled")
}
throw ILPExceptionSupport.createILPUnprocessableEntityException("Unprocessable Entity")
}
val response = ConversionUtil.fulfillmentToBase64(fulfillment)
context.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/plain")
.putHeader(HttpHeaders.CONTENT_LENGTH, "" + response.length)
.setStatusCode(HttpResponseStatus.OK.code()).end(response)
}
companion object {
private val log = org.slf4j.LoggerFactory.getLogger(FulfillmentHandler::class.java)
private val transferUUID = "transferUUID"
fun create(): FulfillmentHandler = FulfillmentHandler()
}
}
| apache-2.0 | e88144a7a9f02192e0c848fb015860c1 | 49.716814 | 142 | 0.644914 | 4.120058 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/utils/view/swipebutton/SwipeTextButton.kt | 1 | 4386 | /*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.utils.view.swipebutton
import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatButton
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.legacy.action.manager.ActionController
import jp.hazuki.yuzubrowser.legacy.action.manager.ActionIconManager
import jp.hazuki.yuzubrowser.legacy.action.manager.SoftButtonActionFile
import jp.hazuki.yuzubrowser.ui.extensions.ellipsizeUrl
import jp.hazuki.yuzubrowser.ui.theme.ThemeData
import jp.hazuki.yuzubrowser.ui.widget.swipebutton.SwipeController
open class SwipeTextButton @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : AppCompatButton(context, attrs), SwipeController.OnChangeListener {
private val mController = SwipeSoftButtonController(getContext().applicationContext)
private var content: CharSequence = ""
private var visibleText: CharSequence? = null
private var typeUrl: Boolean = false
fun setActionData(action_list: SoftButtonActionFile, controller: ActionController, iconManager: ActionIconManager) {
mController.setActionData(action_list, controller, iconManager)
mController.setOnChangeListener(this)
onSetNormalBackground()
}
fun notifyChangeState() {
mController.notifyChangeState()
visibility = if (mController.shouldShow()) VISIBLE else GONE
}
fun setSense(sense: Int) {
mController.setSense(sense)
}
fun setTypeUrl(typeUrl: Boolean) {
this.typeUrl = typeUrl
}
override fun onTouchEvent(event: MotionEvent): Boolean {
mController.onTouchEvent(event)
return super.onTouchEvent(event)
}
override fun onLongPress() {}
override fun onEventOutSide(): Boolean {
onSetNormalBackground()
return false
}
override fun onEventCancel(): Boolean {
onSetNormalBackground()
return false
}
override fun onEventActionUp(whatNo: Int): Boolean {
onSetNormalBackground()
return false
}
override fun onEventActionDown(): Boolean {
onSetPressedBackground()
return false
}
protected open fun onSetNormalBackground() {
setBackgroundResource(R.drawable.swipebtn_text_background_normal)
}
protected open fun onSetPressedBackground() {
val theme = ThemeData.getInstance()
if (theme?.toolbarTextButtonBackgroundPress != null) {
background = theme.toolbarTextButtonBackgroundPress
} else {
setBackgroundResource(R.drawable.swipebtn_text_background_pressed)
}
}
override fun onChangeState(whatNo: Int) {}
override fun setText(text: CharSequence?, type: BufferType) {
content = text ?: ""
contentDescription = content
updateVisibleText(measuredWidth - paddingLeft - paddingRight)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val availWidth = MeasureSpec.getSize(widthMeasureSpec) - paddingLeft - paddingRight
updateVisibleText(availWidth)
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
private fun getTruncatedText(availWidth: Int): CharSequence {
return if (typeUrl) {
content.ellipsizeUrl(paint, availWidth.toFloat())
} else {
TextUtils.ellipsize(content, paint, availWidth.toFloat(), TextUtils.TruncateAt.END)
}
}
private fun updateVisibleText(availWidth: Int) {
val newText = getTruncatedText(availWidth)
if (newText != visibleText) {
visibleText = newText
super.setText(visibleText, BufferType.SPANNABLE)
}
}
}
| apache-2.0 | 948c3d5891dc65b036d5ee533332dad0 | 32.480916 | 169 | 0.713862 | 4.78821 | false | false | false | false |
Adven27/Exam | exam-files/src/main/java/io/github/adven27/concordion/extensions/exam/files/commands/FilesCheckCommand.kt | 1 | 7427 | package io.github.adven27.concordion.extensions.exam.files.commands
import io.github.adven27.concordion.extensions.exam.core.ContentVerifier
import io.github.adven27.concordion.extensions.exam.core.XmlVerifier
import io.github.adven27.concordion.extensions.exam.core.html.codeXml
import io.github.adven27.concordion.extensions.exam.core.html.div
import io.github.adven27.concordion.extensions.exam.core.html.divCollapse
import io.github.adven27.concordion.extensions.exam.core.html.generateId
import io.github.adven27.concordion.extensions.exam.core.html.html
import io.github.adven27.concordion.extensions.exam.core.html.table
import io.github.adven27.concordion.extensions.exam.core.html.td
import io.github.adven27.concordion.extensions.exam.core.html.tr
import io.github.adven27.concordion.extensions.exam.core.prettyXml
import io.github.adven27.concordion.extensions.exam.core.resolveToObj
import io.github.adven27.concordion.extensions.exam.files.FilesLoader
import io.github.adven27.concordion.extensions.exam.files.FilesResultRenderer
import org.concordion.api.CommandCall
import org.concordion.api.Element
import org.concordion.api.Evaluator
import org.concordion.api.Fixture
import org.concordion.api.Result
import org.concordion.api.ResultRecorder
import org.concordion.api.listener.AssertEqualsListener
import org.concordion.api.listener.AssertFailureEvent
import org.concordion.api.listener.AssertSuccessEvent
import org.concordion.internal.util.Announcer
import org.slf4j.LoggerFactory
import java.io.File
class FilesCheckCommand(name: String?, tag: String?, filesLoader: FilesLoader) : BaseCommand(name, tag) {
private val listeners = Announcer.to(AssertEqualsListener::class.java)
private val filesLoader: FilesLoader
@Suppress("LongMethod", "NestedBlockDepth", "SpreadOperator")
override fun verify(
commandCall: CommandCall,
evaluator: Evaluator,
resultRecorder: ResultRecorder,
fixture: Fixture
) {
val root = commandCall.html().css("table-responsive")
val table = table()
root.moveChildrenTo(table)
root.invoke(table)
val path = root.takeAwayAttr("dir", evaluator)
if (path != null) {
val evalPath = evaluator.evaluate(path).toString()
val names = filesLoader.getFileNames(evalPath)
val surplusFiles: MutableList<String> = if (names.isEmpty()) ArrayList() else ArrayList(listOf(*names))
table.invoke(flCaption(evalPath))
addHeader(table, HEADER, FILE_CONTENT)
var empty = true
for (f in table.childs()) {
if ("file" == f.localName()) {
val (name1, content1, autoFormat, lineNumbers) = filesLoader.readFileTag(f, evaluator)
val resolvedName = evaluator.resolveToObj(name1)
val expectedName = resolvedName?.toString() ?: name1!!
val fileNameTD = td(expectedName)
var pre = codeXml("")
if (!filesLoader.fileExists(evalPath + File.separator + expectedName)) {
resultRecorder.record(Result.FAILURE)
announceFailure(fileNameTD.el(), "", null)
} else {
resultRecorder.record(Result.SUCCESS)
announceSuccess(fileNameTD.el())
surplusFiles.remove(expectedName)
if (content1 == null) {
val id = generateId()
val content = filesLoader.readFile(evalPath, expectedName)
if (!content.isEmpty()) {
pre = div().style("position: relative").invoke(
divCollapse("", id),
div("id".to(id)).css("collapse show").invoke(
pre.text(content)
)
)
}
} else {
checkContent(
evalPath + File.separator + expectedName,
content1,
resultRecorder,
pre.el()
)
}
}
table.invoke(
tr().invoke(
fileNameTD,
td().invoke(
pre.attrs(
"autoFormat".to(autoFormat.toString()),
"lineNumbers".to(lineNumbers.toString())
)
)
)
).remove(f)
empty = false
}
}
for (file in surplusFiles) {
resultRecorder.record(Result.FAILURE)
val td = td()
val tr = tr().invoke(
td,
td().invoke(
codeXml(filesLoader.readFile(evalPath, file))
)
)
table.invoke(tr)
announceFailure(td.el(), null, file)
}
if (empty) {
addRow(table, EMPTY, "")
}
}
}
private fun checkContent(path: String, expected: String?, resultRecorder: ResultRecorder, element: Element) {
if (!filesLoader.fileExists(path)) {
xmlDoesNotEqual(resultRecorder, element, "(not set)", expected)
return
}
val prettyActual = filesLoader.documentFrom(path).prettyXml()
try {
XmlVerifier().verify(expected!!, prettyActual)
.onFailure { f ->
when (f) {
is ContentVerifier.Fail -> xmlDoesNotEqual(resultRecorder, element, f.actual, f.expected)
else -> throw f
}
}
.onSuccess {
element.appendText(prettyActual)
xmlEquals(resultRecorder, element)
}
} catch (ignore: Exception) {
LOG.debug("Got exception on xml checking: {}", ignore.message)
xmlDoesNotEqual(resultRecorder, element, prettyActual, expected)
}
}
private fun xmlEquals(resultRecorder: ResultRecorder, element: Element) {
resultRecorder.record(Result.SUCCESS)
announceSuccess(element)
}
private fun xmlDoesNotEqual(resultRecorder: ResultRecorder, element: Element, actual: String, expected: String?) {
resultRecorder.record(Result.FAILURE)
announceFailure(element, expected, actual)
}
private fun announceSuccess(element: Element) {
listeners.announce().successReported(AssertSuccessEvent(element))
}
private fun announceFailure(element: Element, expected: String?, actual: Any?) {
listeners.announce().failureReported(AssertFailureEvent(element, expected, actual))
}
companion object {
private val LOG = LoggerFactory.getLogger(FilesCheckCommand::class.java)
}
init {
listeners.addListener(FilesResultRenderer())
this.filesLoader = filesLoader
}
}
| mit | 6db8c26f6e5998100786f771096e79e3 | 42.946746 | 118 | 0.566447 | 5.008092 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/settings/pluginssettings/PluginsListAdapter.kt | 1 | 2746 | package cx.ring.settings.pluginssettings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import cx.ring.R
import cx.ring.settings.pluginssettings.PluginsListAdapter.PluginViewHolder
class PluginsListAdapter(private var mList: List<PluginDetails>, private val listener: PluginListItemListener) :
RecyclerView.Adapter<PluginViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PluginViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.frag_plugins_list_item, parent, false)
return PluginViewHolder(view, listener)
}
override fun onBindViewHolder(holder: PluginViewHolder, position: Int) {
holder.setDetails(mList[position])
}
override fun getItemCount(): Int {
return mList.size
}
fun updatePluginsList(listPlugins: List<PluginDetails>) {
mList = listPlugins
notifyDataSetChanged()
}
class PluginViewHolder(itemView: View, listener: PluginListItemListener) : RecyclerView.ViewHolder(itemView) {
private val pluginIcon: ImageView = itemView.findViewById(R.id.plugin_item_icon)
private val pluginNameTextView: TextView = itemView.findViewById(R.id.plugin_item_name)
private val pluginItemEnableCheckbox: CheckBox = itemView.findViewById(R.id.plugin_item_enable_checkbox)
private var details: PluginDetails? = null
fun setDetails(details: PluginDetails) {
this.details = details
update(details)
}
// update the viewHolder view
fun update(details: PluginDetails) {
pluginNameTextView.text = details.name
pluginItemEnableCheckbox.isChecked = details.isEnabled
// Set the plugin icon
val icon = details.icon
if (icon != null) {
pluginIcon.setImageDrawable(icon)
}
}
init {
itemView.setOnClickListener {
details?.let { details -> listener.onPluginItemClicked(details) }
}
pluginItemEnableCheckbox.setOnClickListener {
details?.let { details ->
details.isEnabled = !details.isEnabled
listener.onPluginEnabled(details)
}
}
}
}
interface PluginListItemListener {
fun onPluginItemClicked(pluginDetails: PluginDetails)
fun onPluginEnabled(pluginDetails: PluginDetails)
}
companion object {
val TAG = PluginsListAdapter::class.simpleName!!
}
} | gpl-3.0 | 571e4e07e70e8b79f6a0788baafb3db9 | 35.626667 | 114 | 0.676985 | 4.983666 | false | false | false | false |
gradle/gradle | build-logic/binary-compatibility/src/main/kotlin/gradlebuild/binarycompatibility/sources/SourcesRepository.kt | 3 | 4132 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gradlebuild.binarycompatibility.sources
import com.github.javaparser.JavaParser
import com.github.javaparser.ast.CompilationUnit
import com.github.javaparser.ast.visitor.GenericVisitor
import org.gradle.util.internal.TextUtil.normaliseFileSeparators
import org.jetbrains.kotlin.psi.KtFile
import gradlebuild.basics.util.KotlinSourceParser
import java.io.File
internal
sealed class ApiSourceFile {
internal
abstract val currentFile: File
internal
abstract val currentSourceRoot: File
data class Java internal constructor(
override val currentFile: File,
override val currentSourceRoot: File
) : ApiSourceFile()
data class Kotlin internal constructor(
override val currentFile: File,
override val currentSourceRoot: File
) : ApiSourceFile()
}
internal
data class JavaSourceQuery<T : Any?>(
val defaultValue: T,
val visitor: GenericVisitor<T, Unit?>
)
internal
class SourcesRepository(
private
val sourceRoots: List<File>,
private
val compilationClasspath: List<File>
) : AutoCloseable {
private
val openJavaCompilationUnitsByFile = mutableMapOf<File, CompilationUnit>()
private
val openKotlinCompilationUnitsByRoot = mutableMapOf<File, KotlinSourceParser.ParsedKotlinFiles>()
fun <T : Any?> executeQuery(apiSourceFile: ApiSourceFile.Java, query: JavaSourceQuery<T>): T =
openJavaCompilationUnitsByFile
.computeIfAbsent(apiSourceFile.currentFile) { JavaParser().parse(it).getResult().get() }
.accept(query.visitor, null)
?: query.defaultValue
fun <T : Any?> executeQuery(apiSourceFile: ApiSourceFile.Kotlin, transform: (KtFile) -> T): T =
apiSourceFile.normalizedPath.let { sourceNormalizedPath ->
openKotlinCompilationUnitsByRoot
.computeIfAbsent(apiSourceFile.currentSourceRoot) {
KotlinSourceParser().parseSourceRoots(
listOf(apiSourceFile.currentSourceRoot),
compilationClasspath
)
}
.ktFiles
.first { it.normalizedPath == sourceNormalizedPath }
.let(transform)
}
override fun close() {
val errors = mutableListOf<Exception>()
openKotlinCompilationUnitsByRoot.values.forEach { unit ->
try {
unit.close()
} catch (ex: Exception) {
errors.add(ex)
}
}
openJavaCompilationUnitsByFile.clear()
openKotlinCompilationUnitsByRoot.clear()
if (errors.isNotEmpty()) {
throw Exception("Sources repository did not close cleanly").apply {
errors.forEach(this::addSuppressed)
}
}
}
/**
* @return the source file and it's source root
*/
fun sourceFileAndSourceRootFor(sourceFilePath: String): Pair<File, File> =
sourceRoots.asSequence()
.map { it.resolve(sourceFilePath) to it }
.firstOrNull { it.first.isFile }
?: throw IllegalStateException("Source file '$sourceFilePath' not found, searched in source roots:\n${sourceRoots.joinToString("\n - ")}")
private
val KtFile.normalizedPath: String?
get() = virtualFile.canonicalPath?.let { normaliseFileSeparators(it) }
private
val ApiSourceFile.normalizedPath: String
get() = normaliseFileSeparators(currentFile.canonicalPath)
}
| apache-2.0 | 5ad51e284113c2a60407a3d915ae26a0 | 29.835821 | 151 | 0.669894 | 4.872642 | false | false | false | false |
facebook/fresco | imagepipeline/src/main/java/com/facebook/imagepipeline/memory/BitmapPoolType.kt | 1 | 552 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.memory
annotation class BitmapPoolType {
companion object {
const val LEGACY = "legacy"
const val LEGACY_DEFAULT_PARAMS = "legacy_default_params"
const val DUMMY = "dummy"
const val DUMMY_WITH_TRACKING = "dummy_with_tracking"
const val EXPERIMENTAL = "experimental"
const val DEFAULT = LEGACY
}
}
| mit | bec9870ed0925f54b5346313ef2c7625 | 28.052632 | 66 | 0.717391 | 4.088889 | false | false | false | false |
alexmonthy/lttng-scope | lttng-scope/src/main/kotlin/org/lttng/scope/application/ScopeApplication.kt | 1 | 2146 | /*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.lttng.scope.application
import javafx.application.Application
import javafx.application.Application.launch
import javafx.application.Platform
import javafx.scene.Scene
import javafx.stage.Stage
import org.lttng.scope.common.jfx.JfxImageFactory
private const val INITIAL_WINDOW_WIDTH = 1500.0
fun main(args: Array<String>) {
launch(ScopeApplication::class.java, *args)
}
/**
* Main application launcher
*/
class ScopeApplication : Application() {
override fun start(primaryStage: Stage?) {
primaryStage ?: return
Platform.setImplicitExit(true)
/* Do our part in preventing eye cancer. */
System.setProperty("prism.lcdtext", "false")
try {
/* Create the application window */
val root = ScopeMainWindow()
with(primaryStage) {
scene = Scene(root)
title = "LTTng Scope"
/* Add the window icons */
listOf(16, 32, 48, 64, 128, 256)
.map { "/appicons/png/scope_icon_${it}x$it.png" }
.mapNotNull { JfxImageFactory.getImageFromResource(it) }
.let { icons.addAll(it) }
/* Ensure initial window has proper size and subdivisions. */
width = INITIAL_WINDOW_WIDTH
setOnShown { Platform.runLater { root.onShownCB() } }
setOnHidden { Platform.runLater { root.onHiddenCB() } }
show()
}
} catch (e: Exception) {
/*
* Top-level exception handler.
* Without this, exceptions in the UI don't print their stack trace!
*/
e.printStackTrace()
}
}
override fun stop() {
System.exit(0)
}
} | epl-1.0 | 748af93cfb02096000b9e8ddf368ab47 | 28.013514 | 84 | 0.59972 | 4.443064 | false | false | false | false |
RedRoma/banana-java-client | src/main/java/tech/aroma/client/RequestImpl.kt | 3 | 4798 | /*
* Copyright 2018 RedRoma, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tech.aroma.client
import org.slf4j.LoggerFactory
import org.slf4j.helpers.MessageFormatter
import tech.aroma.thrift.application.service.ApplicationServiceConstants
import tech.sirwellington.alchemy.annotations.access.Internal
import tech.sirwellington.alchemy.annotations.arguments.NonEmpty
import tech.sirwellington.alchemy.annotations.arguments.Optional
import tech.sirwellington.alchemy.annotations.arguments.Required
import tech.sirwellington.alchemy.annotations.concurrency.Immutable
import tech.sirwellington.alchemy.arguments.Arguments.checkThat
import tech.sirwellington.alchemy.arguments.assertions.nonEmptyString
import tech.sirwellington.alchemy.arguments.assertions.notNull
import tech.sirwellington.alchemy.arguments.assertions.stringWithLengthGreaterThanOrEqualTo
import tech.sirwellington.alchemy.arguments.assertions.stringWithLengthLessThan
import java.io.IOException
import java.io.PrintWriter
import java.io.StringWriter
/**
* @author SirWellington
*/
@Immutable
@Internal
internal class RequestImpl : Aroma.Request
{
internal val aromaClient: AromaClient
internal val title: String
internal val text: String
internal val priority: Priority
constructor(@Required aromaClient: AromaClient,
@Required @NonEmpty title: String,
@Required @NonEmpty text: String,
@Required priority: Priority)
{
checkThat(aromaClient, title, text, priority)
.are(notNull())
this.aromaClient = aromaClient
this.title = title
this.text = text
this.priority = priority
}
override fun titled(title: String): Aroma.Request
{
checkThat(title)
.usingMessage("title cannot be empty")
.isA(nonEmptyString())
.usingMessage("title too short")
.isA(stringWithLengthGreaterThanOrEqualTo(3))
.usingMessage("title too long")
.isA(stringWithLengthLessThan(ApplicationServiceConstants.MAX_TITLE_LENGTH))
return RequestImpl(aromaClient, title, text, priority)
}
override fun withBody(message: String, @Optional vararg args: Any): Aroma.Request
{
checkThat(message)
.usingMessage("message cannot be null")
.isA(notNull())
val combinedMessage = combineStringAndArgs(message, *args)
return RequestImpl(aromaClient, title, combinedMessage, priority)
}
private fun combineStringAndArgs(message: String, vararg args: Any): String
{
if (args.isEmpty())
{
return message
}
val arrayFormat = MessageFormatter.arrayFormat(message, args)
val formattedMessage = arrayFormat.message
val ex = arrayFormat.throwable
if (ex == null)
{
return formattedMessage
}
else
{
return String.format("%s\n%s", formattedMessage, printThrowable(ex))
}
}
private fun printThrowable(ex: Throwable): String
{
try
{
StringWriter().use { stringWriter ->
PrintWriter(stringWriter).use { printWriter ->
ex.printStackTrace(printWriter)
return stringWriter.toString()
}
}
}
catch (ioex: IOException)
{
LOG.info("Failed to close String and Print Writers", ioex)
return ex.message ?: ""
}
}
@Throws(IllegalArgumentException::class)
override fun withPriority(@Required priority: Priority): Aroma.Request
{
checkThat(priority)
.usingMessage("priority cannot be null")
.isA(notNull())
return RequestImpl(aromaClient, title, text, priority)
}
@Throws(IllegalArgumentException::class)
override fun send()
{
aromaClient.sendMessage(this)
}
override fun toString(): String
{
return "RequestImpl{aromaClient=$aromaClient, priority=$priority, title=$title, text=$text}"
}
companion object
{
private val LOG = LoggerFactory.getLogger(RequestImpl::class.java)
}
}
| apache-2.0 | 45eb0ba4fd6dbd7f91229c149d8362a1 | 30.155844 | 100 | 0.666945 | 4.793207 | false | false | false | false |
android/user-interface-samples | People/app/src/main/java/com/example/android/people/ui/ViewBindingDelegates.kt | 1 | 2578 | /*
* Copyright (C) 2019 The Android Open Source Project
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.people.ui
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.viewbinding.ViewBinding
/**
* Retrieves a view binding handle in an Activity.
*
* ```
* private val binding by viewBindings(MainActivityBinding::bind)
*
* override fun onCreate(savedInstanceState: Bundle?) {
* super.onCreate(savedInstanceState)
* binding.someView.someField = ...
* }
* ```
*/
inline fun <reified BindingT : ViewBinding> FragmentActivity.viewBindings(
crossinline bind: (View) -> BindingT
) = object : Lazy<BindingT> {
private var cached: BindingT? = null
override val value: BindingT
get() = cached ?: bind(
findViewById<ViewGroup>(android.R.id.content).getChildAt(0)
).also {
cached = it
}
override fun isInitialized() = cached != null
}
/**
* Retrieves a view binding handle in a Fragment. The field is available only after
* [Fragment.onViewCreated].
*
* ```
* private val binding by viewBindings(HomeFragmentBinding::bind)
*
* override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
* binding.someView.someField = ...
* }
* ```
*/
inline fun <reified BindingT : ViewBinding> Fragment.viewBindings(
crossinline bind: (View) -> BindingT
) = object : Lazy<BindingT> {
private var cached: BindingT? = null
private val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_DESTROY) {
cached = null
}
}
override val value: BindingT
get() = cached ?: bind(requireView()).also {
viewLifecycleOwner.lifecycle.addObserver(observer)
cached = it
}
override fun isInitialized() = cached != null
}
| apache-2.0 | 4407fb75fc5aedffb9d422408c8633d8 | 29.329412 | 83 | 0.681148 | 4.332773 | false | false | false | false |
waicool20/SKrypton | src/main/kotlin/com/waicool20/skrypton/util/Logging.kt | 1 | 3583 | /*
* The MIT License (MIT)
*
* Copyright (c) SKrypton by waicool20
*
* 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.waicool20.skrypton.util
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* Gets a [KLogger] instance for a given class.
*/
inline fun <reified T> loggerFor(): KLogger = KLogger(LoggerFactory.getLogger(T::class.java))
/**
* Class that wraps a [Logger] instance, and adds logging functions which receive lambdas as their
* argument. These functions are lazily evaluated.
*
* @property logger [Logger] instance to wrap.
* @constructor Main constructor
* @param logger [Logger] instance to wrap.
*/
class KLogger(val logger: Logger) {
/**
* Just like [Logger.info]
*
* @param msg Message to log
*/
fun info(msg: String) = info { msg }
/**
* Executes given lambda and logs its result with [Logger.info].
* Allows lazy evaluation of logging message.
*
* @param msg Lambda to execute
*/
fun info(msg: () -> Any) = logger.info(msg().toString())
/**
* Just like [Logger.debug]
*
* @param msg Message to log
*/
fun debug(msg: String) = debug { msg }
/**
* Executes given lambda and logs its result with [Logger.debug].
* Allows lazy evaluation of logging message.
*
* @param msg Lambda to execute
*/
fun debug(msg: () -> Any) = logger.debug(msg().toString())
/**
* Just like [Logger.warn]
*
* @param msg Message to log
*/
fun warn(msg: String) = warn { msg }
/**
* Executes given lambda and logs its result with [Logger.warn].
* Allows lazy evaluation of logging message.
*
* @param msg Lambda to execute
*/
fun warn(msg: () -> Any) = logger.warn(msg().toString())
/**
* Just like [Logger.error]
*
* @param msg Message to log
*/
fun error(msg: String) = error { msg }
/**
* Executes given lambda and logs its result with [Logger.error].
* Allows lazy evaluation of logging message.
*
* @param msg Lambda to execute
*/
fun error(msg: () -> Any) = logger.error(msg().toString())
/**
* Just like [Logger.trace]
*
* @param msg Message to log
*/
fun trace(msg: String) = trace { msg }
/**
* Executes given lambda and logs its result with [Logger.trace].
* Allows lazy evaluation of logging message.
*
* @param msg Lambda to execute
*/
fun trace(msg: () -> Any) = logger.trace(msg().toString())
}
| mit | 2ac8639b51d5b6d20509a48f9326721c | 28.368852 | 98 | 0.648618 | 4.12313 | false | false | false | false |
android/user-interface-samples | WindowInsetsAnimation/app/src/main/java/com/google/android/samples/insetsanimation/TranslateDeferringInsetsAnimationCallback.kt | 1 | 3531 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.samples.insetsanimation
import android.view.View
import androidx.core.graphics.Insets
import androidx.core.view.WindowInsetsAnimationCompat
import androidx.core.view.WindowInsetsCompat
/**
* A [WindowInsetsAnimationCompat.Callback] which will translate/move the given view during any
* inset animations of the given inset type.
*
* This class works in tandem with [RootViewDeferringInsetsCallback] to support the deferring of
* certain [WindowInsetsCompat.Type] values during a [WindowInsetsAnimationCompat], provided in
* [deferredInsetTypes]. The values passed into this constructor should match those which
* the [RootViewDeferringInsetsCallback] is created with.
*
* @param view the view to translate from it's start to end state
* @param persistentInsetTypes the bitmask of any inset types which were handled as part of the
* layout
* @param deferredInsetTypes the bitmask of insets types which should be deferred until after
* any [WindowInsetsAnimationCompat]s have ended
* @param dispatchMode The dispatch mode for this callback.
* See [WindowInsetsAnimationCompat.Callback.getDispatchMode].
*/
class TranslateDeferringInsetsAnimationCallback(
private val view: View,
val persistentInsetTypes: Int,
val deferredInsetTypes: Int,
dispatchMode: Int = DISPATCH_MODE_STOP
) : WindowInsetsAnimationCompat.Callback(dispatchMode) {
init {
require(persistentInsetTypes and deferredInsetTypes == 0) {
"persistentInsetTypes and deferredInsetTypes can not contain any of " +
" same WindowInsetsCompat.Type values"
}
}
override fun onProgress(
insets: WindowInsetsCompat,
runningAnimations: List<WindowInsetsAnimationCompat>
): WindowInsetsCompat {
// onProgress() is called when any of the running animations progress...
// First we get the insets which are potentially deferred
val typesInset = insets.getInsets(deferredInsetTypes)
// Then we get the persistent inset types which are applied as padding during layout
val otherInset = insets.getInsets(persistentInsetTypes)
// Now that we subtract the two insets, to calculate the difference. We also coerce
// the insets to be >= 0, to make sure we don't use negative insets.
val diff = Insets.subtract(typesInset, otherInset).let {
Insets.max(it, Insets.NONE)
}
// The resulting `diff` insets contain the values for us to apply as a translation
// to the view
view.translationX = (diff.left - diff.right).toFloat()
view.translationY = (diff.top - diff.bottom).toFloat()
return insets
}
override fun onEnd(animation: WindowInsetsAnimationCompat) {
// Once the animation has ended, reset the translation values
view.translationX = 0f
view.translationY = 0f
}
}
| apache-2.0 | 98b2540c4258d32455380435a4df72fc | 41.035714 | 96 | 0.728689 | 4.714286 | false | false | false | false |
google/xplat | j2kt/jre/java/native/java/util/Arrays.kt | 1 | 25615 | /*
* Copyright 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package java.util
import java.util.function.BinaryOperator
import java.util.function.DoubleBinaryOperator
import java.util.function.IntBinaryOperator
import java.util.function.IntFunction
import java.util.function.IntToDoubleFunction
import java.util.function.IntToLongFunction
import java.util.function.IntUnaryOperator
import java.util.function.LongBinaryOperator
import java.util.stream.DoubleStream
import java.util.stream.IntStream
import java.util.stream.LongStream
import java.util.stream.Stream
import java.util.stream.StreamSupport
import javaemul.internal.Comparators
import javaemul.internal.InternalPreconditions.Companion.checkCriticalArrayBounds
import kotlin.Comparator as KotlinComparator
import kotlin.math.min
/**
* Utility methods related to native arrays. See <a
* href="https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html"> the official Java API
* doc</a> for details.
*/
object Arrays {
// TODO(b/239034072): Revisit set after varargs are fixed
fun <T> asList(vararg elements: T): MutableList<T> {
val array: Array<T> = elements as Array<T>
requireNotNull(array)
return object : AbstractMutableList<T>(), RandomAccess {
override val size: Int
get() = array.size
override fun isEmpty(): Boolean = array.isEmpty()
override fun contains(element: T): Boolean = array.contains(element)
override fun get(index: Int): T = array[index]
override fun indexOf(element: T): Int = this.indexOf(element)
override fun lastIndexOf(element: T): Int = this.lastIndexOf(element)
override fun set(index: Int, element: T): T {
val prevValue = array[index]
array[index] = element
return prevValue
}
override fun add(index: Int, element: T) = throw UnsupportedOperationException()
override fun removeAt(index: Int) = throw UnsupportedOperationException()
}
}
fun binarySearch(sortedArray: ByteArray?, fromIndex: Int, toIndex: Int, key: Byte): Int {
requireNotNull(sortedArray)
checkCriticalArrayBounds(fromIndex, toIndex, sortedArray.size)
return sortedArray.asList().binarySearch(key, fromIndex, toIndex)
}
fun binarySearch(sortedArray: ByteArray?, key: Byte): Int {
requireNotNull(sortedArray)
return sortedArray.asList().binarySearch(key)
}
fun binarySearch(sortedArray: CharArray?, fromIndex: Int, toIndex: Int, key: Char): Int {
requireNotNull(sortedArray)
checkCriticalArrayBounds(fromIndex, toIndex, sortedArray.size)
return sortedArray.asList().binarySearch(key, fromIndex, toIndex)
}
fun binarySearch(sortedArray: CharArray?, key: Char): Int {
requireNotNull(sortedArray)
return sortedArray.asList().binarySearch(key)
}
fun binarySearch(sortedArray: DoubleArray?, fromIndex: Int, toIndex: Int, key: Double): Int {
requireNotNull(sortedArray)
checkCriticalArrayBounds(fromIndex, toIndex, sortedArray.size)
return sortedArray.asList().binarySearch(key, fromIndex, toIndex)
}
fun binarySearch(sortedArray: DoubleArray?, key: Double): Int {
requireNotNull(sortedArray)
return sortedArray.asList().binarySearch(key)
}
fun binarySearch(sortedArray: FloatArray?, fromIndex: Int, toIndex: Int, key: Float): Int {
requireNotNull(sortedArray)
checkCriticalArrayBounds(fromIndex, toIndex, sortedArray.size)
return sortedArray.asList().binarySearch(key, fromIndex, toIndex)
}
fun binarySearch(sortedArray: FloatArray?, key: Float): Int {
requireNotNull(sortedArray)
return sortedArray.asList().binarySearch(key)
}
fun binarySearch(sortedArray: IntArray?, fromIndex: Int, toIndex: Int, key: Int): Int {
requireNotNull(sortedArray)
checkCriticalArrayBounds(fromIndex, toIndex, sortedArray.size)
return sortedArray.asList().binarySearch(key, fromIndex, toIndex)
}
fun binarySearch(sortedArray: IntArray?, key: Int): Int {
requireNotNull(sortedArray)
return sortedArray.asList().binarySearch(key)
}
fun binarySearch(sortedArray: LongArray?, fromIndex: Int, toIndex: Int, key: Long): Int {
requireNotNull(sortedArray)
checkCriticalArrayBounds(fromIndex, toIndex, sortedArray.size)
return sortedArray.asList().binarySearch(key, fromIndex, toIndex)
}
fun binarySearch(sortedArray: LongArray?, key: Long): Int {
requireNotNull(sortedArray)
return sortedArray.asList().binarySearch(key)
}
fun binarySearch(sortedArray: Array<Any?>?, fromIndex: Int, toIndex: Int, key: Any?): Int {
return binarySearch(sortedArray, fromIndex, toIndex, key, null)
}
fun binarySearch(sortedArray: Array<Any?>?, key: Any?): Int {
return binarySearch(sortedArray, key, null)
}
fun binarySearch(sortedArray: ShortArray?, fromIndex: Int, toIndex: Int, key: Short): Int {
requireNotNull(sortedArray)
checkCriticalArrayBounds(fromIndex, toIndex, sortedArray.size)
return sortedArray.toList().binarySearch(key, fromIndex, toIndex)
}
fun binarySearch(sortedArray: ShortArray?, key: Short): Int {
requireNotNull(sortedArray)
return sortedArray.toList().binarySearch(key)
}
fun <T> binarySearch(
sortedArray: Array<T>?,
fromIndex: Int,
toIndex: Int,
key: T,
comparator: KotlinComparator<in T>?
): Int {
requireNotNull(sortedArray)
checkCriticalArrayBounds(fromIndex, toIndex, sortedArray.size)
val comparator = Comparators.nullToNaturalOrder(comparator)
return sortedArray.asList().binarySearch(key, comparator, fromIndex, toIndex)
}
fun <T> binarySearch(sortedArray: Array<T>?, key: T, c: KotlinComparator<in T>?): Int {
requireNotNull(sortedArray)
val c = Comparators.nullToNaturalOrder(c)
return sortedArray.asList().binarySearch(key, c)
}
fun copyOf(original: BooleanArray, newLength: Int): BooleanArray = original.copyOf(newLength)
fun copyOf(original: ByteArray, newLength: Int): ByteArray = original.copyOf(newLength)
fun copyOf(original: CharArray, newLength: Int): CharArray = original.copyOf(newLength)
fun copyOf(original: DoubleArray, newLength: Int): DoubleArray = original.copyOf(newLength)
fun copyOf(original: FloatArray, newLength: Int): FloatArray = original.copyOf(newLength)
fun copyOf(original: IntArray, newLength: Int): IntArray = original.copyOf(newLength)
fun copyOf(original: LongArray, newLength: Int): LongArray = original.copyOf(newLength)
fun copyOf(original: ShortArray, newLength: Int): ShortArray = original.copyOf(newLength)
fun <T> copyOf(original: Array<T?>, newLength: Int): Array<T?> = original.copyOf(newLength)
fun <T, O> copyOf(original: Array<O?>, newLength: Int, newType: java.lang.Class<*>): Array<T?> =
copyOfRange(original, 0, newLength, newType)
fun checkCopyOfRangeArguments(originalSize: Int, from: Int, to: Int) {
if (from < 0 || from > originalSize) throw ArrayIndexOutOfBoundsException()
if (from > to) throw IllegalArgumentException()
}
fun copyOfRange(original: BooleanArray, from: Int, to: Int): BooleanArray {
checkCopyOfRangeArguments(original.size, from, to)
val copy = BooleanArray(to - from)
return original.copyInto(copy, startIndex = from, endIndex = min(to, original.size))
}
fun copyOfRange(original: ByteArray, from: Int, to: Int): ByteArray {
checkCopyOfRangeArguments(original.size, from, to)
val copy = ByteArray(to - from)
return original.copyInto(copy, startIndex = from, endIndex = min(to, original.size))
}
fun copyOfRange(original: CharArray, from: Int, to: Int): CharArray {
checkCopyOfRangeArguments(original.size, from, to)
val copy = CharArray(to - from)
return original.copyInto(copy, startIndex = from, endIndex = min(to, original.size))
}
fun copyOfRange(original: DoubleArray, from: Int, to: Int): DoubleArray {
checkCopyOfRangeArguments(original.size, from, to)
val copy = DoubleArray(to - from)
return original.copyInto(copy, startIndex = from, endIndex = min(to, original.size))
}
fun copyOfRange(original: FloatArray, from: Int, to: Int): FloatArray {
checkCopyOfRangeArguments(original.size, from, to)
val copy = FloatArray(to - from)
return original.copyInto(copy, startIndex = from, endIndex = min(to, original.size))
}
fun copyOfRange(original: IntArray, from: Int, to: Int): IntArray {
checkCopyOfRangeArguments(original.size, from, to)
val copy = IntArray(to - from)
return original.copyInto(copy, startIndex = from, endIndex = min(to, original.size))
}
fun copyOfRange(original: LongArray, from: Int, to: Int): LongArray {
checkCopyOfRangeArguments(original.size, from, to)
val copy = LongArray(to - from)
return original.copyInto(copy, startIndex = from, endIndex = min(to, original.size))
}
fun copyOfRange(original: ShortArray, from: Int, to: Int): ShortArray {
checkCopyOfRangeArguments(original.size, from, to)
val copy = ShortArray(to - from)
return original.copyInto(copy, startIndex = from, endIndex = min(to, original.size))
}
inline fun <reified T> copyOfRange(original: Array<T?>, from: Int, to: Int): Array<T?> {
checkCopyOfRangeArguments(original.size, from, to)
val copy = arrayOfNulls<T>(to - from)
return original.copyInto(copy, startIndex = from, endIndex = min(to, original.size))
}
// The type of array doesn't matter because the emulated java.util.Arrays is never used on the
// JVM.
fun <T, O> copyOfRange(
original: Array<O?>,
from: Int,
to: Int,
newType: java.lang.Class<*>
): Array<T?> {
checkCopyOfRangeArguments(original.size, from, to)
val copy = arrayOfNulls<Any?>(to - from)
@Suppress("UNCHECKED_CAST")
return original.copyInto(copy, startIndex = from, endIndex = min(to, original.size))
as Array<T?>
}
fun deepEquals(a1: Array<Any?>?, a2: Array<Any?>?): Boolean {
return a1.contentDeepEquals(a2)
}
fun deepHashCode(a: Array<Any?>?): Int {
return a.contentDeepHashCode()
}
fun deepToString(a: Array<Any?>?): String {
return a.contentDeepToString()
}
fun equals(array1: BooleanArray?, array2: BooleanArray?): Boolean {
return array1 contentEquals array2
}
fun equals(array1: ByteArray?, array2: ByteArray?): Boolean {
return array1 contentEquals array2
}
fun equals(array1: CharArray?, array2: CharArray?): Boolean {
return array1 contentEquals array2
}
fun equals(array1: DoubleArray?, array2: DoubleArray?): Boolean {
return array1 contentEquals array2
}
fun equals(array1: FloatArray?, array2: FloatArray?): Boolean {
return array1 contentEquals array2
}
fun equals(array1: IntArray?, array2: IntArray?): Boolean {
return array1 contentEquals array2
}
fun equals(array1: LongArray?, array2: LongArray?): Boolean {
return array1 contentEquals array2
}
fun equals(array1: Array<Any?>?, array2: Array<Any?>?): Boolean {
return array1 contentEquals array2
}
fun equals(array1: ShortArray?, array2: ShortArray?): Boolean {
return array1 contentEquals array2
}
fun fill(a: BooleanArray?, `val`: Boolean) {
requireNotNull(a)
a.fill(`val`)
}
fun fill(a: BooleanArray?, fromIndex: Int, toIndex: Int, `val`: Boolean) {
requireNotNull(a)
a.fill(`val`, fromIndex, toIndex)
}
fun fill(a: ByteArray?, `val`: Byte) {
requireNotNull(a)
a.fill(`val`)
}
fun fill(a: ByteArray?, fromIndex: Int, toIndex: Int, `val`: Byte) {
requireNotNull(a)
a.fill(`val`, fromIndex, toIndex)
}
fun fill(a: CharArray?, `val`: Char) {
requireNotNull(a)
a.fill(`val`)
}
fun fill(a: CharArray?, fromIndex: Int, toIndex: Int, `val`: Char) {
requireNotNull(a)
a.fill(`val`, fromIndex, toIndex)
}
fun fill(a: DoubleArray?, `val`: Double) {
requireNotNull(a)
a.fill(`val`)
}
fun fill(a: DoubleArray?, fromIndex: Int, toIndex: Int, `val`: Double) {
requireNotNull(a)
a.fill(`val`, fromIndex, toIndex)
}
fun fill(a: FloatArray?, `val`: Float) {
requireNotNull(a)
a.fill(`val`)
}
fun fill(a: FloatArray?, fromIndex: Int, toIndex: Int, `val`: Float) {
requireNotNull(a)
a.fill(`val`, fromIndex, toIndex)
}
fun fill(a: IntArray?, `val`: Int) {
requireNotNull(a)
a.fill(`val`)
}
fun fill(a: IntArray?, fromIndex: Int, toIndex: Int, `val`: Int) {
requireNotNull(a)
a.fill(`val`, fromIndex, toIndex)
}
fun fill(a: LongArray?, `val`: Long) {
requireNotNull(a)
a.fill(`val`)
}
fun fill(a: LongArray?, fromIndex: Int, toIndex: Int, `val`: Long) {
requireNotNull(a)
a.fill(`val`, fromIndex, toIndex)
}
fun fill(a: Array<Any?>?, `val`: Any?) {
requireNotNull(a)
a.fill(`val`)
}
fun fill(a: Array<Any?>?, fromIndex: Int, toIndex: Int, `val`: Any?) {
requireNotNull(a)
a.fill(`val`, fromIndex, toIndex)
}
fun fill(a: ShortArray?, `val`: Short) {
requireNotNull(a)
a.fill(`val`)
}
fun fill(a: ShortArray?, fromIndex: Int, toIndex: Int, `val`: Short) {
requireNotNull(a)
a.fill(`val`, fromIndex, toIndex)
}
fun hashCode(a: BooleanArray?): Int {
return a.contentHashCode()
}
fun hashCode(a: ByteArray?): Int {
return a.contentHashCode()
}
fun hashCode(a: CharArray?): Int {
return a.contentHashCode()
}
fun hashCode(a: DoubleArray?): Int {
return a.contentHashCode()
}
fun hashCode(a: FloatArray?): Int {
return a.contentHashCode()
}
fun hashCode(a: IntArray?): Int {
return a.contentHashCode()
}
fun hashCode(a: LongArray?): Int {
return a.contentHashCode()
}
fun hashCode(a: Array<Any?>?): Int {
return a.contentHashCode()
}
fun hashCode(a: ShortArray?): Int {
return a.contentHashCode()
}
fun toString(a: Array<*>?): String {
return a.contentToString()
}
fun toString(a: BooleanArray?): String {
return a.contentToString()
}
fun toString(a: ByteArray?): String {
return a.contentToString()
}
fun toString(a: CharArray?): String {
return a.contentToString()
}
fun toString(a: DoubleArray?): String {
return a.contentToString()
}
fun toString(a: FloatArray?): String {
return a.contentToString()
}
fun toString(a: IntArray?): String {
return a.contentToString()
}
fun toString(a: LongArray?): String {
return a.contentToString()
}
fun toString(a: ShortArray?): String {
return a.contentToString()
}
// TODO(b/238392635): Parallelize parallelPrefix, currently a single-threaded operation
fun parallelPrefix(array: DoubleArray?, op: DoubleBinaryOperator) {
requireNotNull(array)
parallelPrefix0(array, 0, array.size, op)
}
fun parallelPrefix(array: DoubleArray?, fromIndex: Int, toIndex: Int, op: DoubleBinaryOperator) {
requireNotNull(array)
checkCriticalArrayBounds(fromIndex, toIndex, array.size)
parallelPrefix0(array, fromIndex, toIndex, op)
}
private fun parallelPrefix0(
array: DoubleArray,
fromIndex: Int,
toIndex: Int,
op: DoubleBinaryOperator
) {
var acc: Double = array[fromIndex]
for (i in fromIndex + 1 until toIndex) {
acc = op.applyAsDouble(acc, array[i])
array[i] = acc
}
}
fun parallelPrefix(array: IntArray?, op: IntBinaryOperator) {
requireNotNull(array)
parallelPrefix0(array, 0, array.size, op)
}
fun parallelPrefix(array: IntArray?, fromIndex: Int, toIndex: Int, op: IntBinaryOperator) {
requireNotNull(array)
checkCriticalArrayBounds(fromIndex, toIndex, array.size)
parallelPrefix0(array, fromIndex, toIndex, op)
}
private fun parallelPrefix0(
array: IntArray,
fromIndex: Int,
toIndex: Int,
op: IntBinaryOperator
) {
requireNotNull(array)
var acc: Int = array[fromIndex]
for (i in fromIndex + 1 until toIndex) {
acc = op.applyAsInt(acc, array[i])
array[i] = acc
}
}
fun parallelPrefix(array: LongArray?, op: LongBinaryOperator) {
requireNotNull(array)
parallelPrefix0(array, 0, array.size, op)
}
fun parallelPrefix(array: LongArray?, fromIndex: Int, toIndex: Int, op: LongBinaryOperator) {
requireNotNull(array)
checkCriticalArrayBounds(fromIndex, toIndex, array.size)
parallelPrefix0(array, fromIndex, toIndex, op)
}
private fun parallelPrefix0(
array: LongArray,
fromIndex: Int,
toIndex: Int,
op: LongBinaryOperator
) {
requireNotNull(array)
var acc: Long = array[fromIndex]
for (i in fromIndex + 1 until toIndex) {
acc = op.applyAsLong(acc, array[i])
array[i] = acc
}
}
fun <T> parallelPrefix(array: Array<T>?, op: BinaryOperator<T>) {
requireNotNull(array)
parallelPrefix0(array, 0, array.size, op)
}
fun <T> parallelPrefix(array: Array<T>?, fromIndex: Int, toIndex: Int, op: BinaryOperator<T>) {
requireNotNull(array)
checkCriticalArrayBounds(fromIndex, toIndex, array.size)
parallelPrefix0(array, fromIndex, toIndex, op)
}
private fun <T> parallelPrefix0(
array: Array<T>,
fromIndex: Int,
toIndex: Int,
op: BinaryOperator<T>
) {
requireNotNull(op)
var acc = array[fromIndex]
for (i in fromIndex + 1 until toIndex) {
acc = op.apply(acc, array[i])!!
array[i] = acc
}
}
fun <T> setAll(array: Array<T>?, generator: IntFunction<out T>) {
requireNotNull(array)
requireNotNull(generator)
for (i in array.indices) {
array[i] = generator.apply(i)!!
}
}
fun setAll(array: DoubleArray?, generator: IntToDoubleFunction) {
requireNotNull(array)
for (i in array.indices) {
array[i] = generator.applyAsDouble(i)
}
}
fun setAll(array: IntArray?, generator: IntUnaryOperator) {
requireNotNull(array)
for (i in array.indices) {
array[i] = generator.applyAsInt(i)
}
}
fun setAll(array: LongArray?, generator: IntToLongFunction) {
requireNotNull(array)
for (i in array.indices) {
array[i] = generator.applyAsLong(i)
}
}
fun <T> parallelSetAll(array: Array<T>?, generator: IntFunction<out T>) {
requireNotNull(array)
setAll(array, generator)
}
fun parallelSetAll(array: DoubleArray?, generator: IntToDoubleFunction) {
requireNotNull(array)
setAll(array, generator)
}
fun parallelSetAll(array: IntArray?, generator: IntUnaryOperator) {
requireNotNull(array)
setAll(array, generator)
}
fun parallelSetAll(array: LongArray?, generator: IntToLongFunction) {
requireNotNull(array)
setAll(array, generator)
}
fun sort(array: ByteArray?) {
requireNotNull(array)
array.sort()
}
fun sort(array: ByteArray?, fromIndex: Int, toIndex: Int) {
requireNotNull(array)
array.sort(fromIndex, toIndex)
}
fun sort(array: CharArray?) {
requireNotNull(array)
array.sort()
}
fun sort(array: CharArray?, fromIndex: Int, toIndex: Int) {
requireNotNull(array)
array.sort(fromIndex, toIndex)
}
fun sort(array: DoubleArray?) {
requireNotNull(array)
array.sort()
}
fun sort(array: DoubleArray?, fromIndex: Int, toIndex: Int) {
requireNotNull(array)
array.sort(fromIndex, toIndex)
}
fun sort(array: FloatArray?) {
requireNotNull(array)
array.sort()
}
fun sort(array: FloatArray?, fromIndex: Int, toIndex: Int) {
requireNotNull(array)
array.sort(fromIndex, toIndex)
}
fun sort(array: IntArray?) {
requireNotNull(array)
array.sort()
}
fun sort(array: IntArray?, fromIndex: Int, toIndex: Int) {
requireNotNull(array)
array.sort(fromIndex, toIndex)
}
fun sort(array: LongArray?) {
requireNotNull(array)
array.sort()
}
fun sort(array: LongArray?, fromIndex: Int, toIndex: Int) {
requireNotNull(array)
array.sort(fromIndex, toIndex)
}
fun sort(array: ShortArray?) {
requireNotNull(array)
array.sort()
}
fun sort(array: ShortArray?, fromIndex: Int, toIndex: Int) {
requireNotNull(array)
array.sort(fromIndex, toIndex)
}
fun <T> sort(x: Array<T>, c: KotlinComparator<in T>?) {
val c = Comparators.nullToNaturalOrder(c)
x.sortWith(c)
}
fun <T> sort(x: Array<T>, fromIndex: Int, toIndex: Int, c: KotlinComparator<in T>?) {
val c = Comparators.nullToNaturalOrder(c)
x.sortWith(c, fromIndex, toIndex)
}
fun sort(x: Array<Any>) = (x as Array<Comparable<Any>>).sort()
fun sort(x: Array<Any>, fromIndex: Int, toIndex: Int) =
(x as Array<Comparable<Any>>).sort(fromIndex, toIndex)
fun parallelSort(array: ByteArray?) {
requireNotNull(array)
array.sort()
}
fun parallelSort(array: ByteArray?, fromIndex: Int, toIndex: Int) {
requireNotNull(array)
array.sort(fromIndex, toIndex)
}
fun parallelSort(array: CharArray?) {
requireNotNull(array)
array.sort()
}
fun parallelSort(array: CharArray?, fromIndex: Int, toIndex: Int) {
requireNotNull(array)
array.sort(fromIndex, toIndex)
}
fun parallelSort(array: DoubleArray?) {
requireNotNull(array)
array.sort()
}
fun parallelSort(array: DoubleArray?, fromIndex: Int, toIndex: Int) {
requireNotNull(array)
array.sort(fromIndex, toIndex)
}
fun parallelSort(array: FloatArray?) {
requireNotNull(array)
array.sort()
}
fun parallelSort(array: FloatArray?, fromIndex: Int, toIndex: Int) {
requireNotNull(array)
array.sort(fromIndex, toIndex)
}
fun parallelSort(array: IntArray?) {
requireNotNull(array)
array.sort()
}
fun parallelSort(array: IntArray?, fromIndex: Int, toIndex: Int) {
requireNotNull(array)
array.sort(fromIndex, toIndex)
}
fun parallelSort(array: LongArray?) {
requireNotNull(array)
array.sort()
}
fun parallelSort(array: LongArray?, fromIndex: Int, toIndex: Int) {
requireNotNull(array)
array.sort(fromIndex, toIndex)
}
fun parallelSort(array: ShortArray?) {
requireNotNull(array)
array.sort()
}
fun parallelSort(array: ShortArray?, fromIndex: Int, toIndex: Int) {
requireNotNull(array)
array.sort(fromIndex, toIndex)
}
fun <T : Comparable<T>> parallelSort(array: Array<T>?) {
requireNotNull(array)
array.sort()
}
fun <T> parallelSort(array: Array<T>?, c: KotlinComparator<in T>?) {
requireNotNull(array)
val c = Comparators.nullToNaturalOrder(c)
array.sortWith(c)
}
fun <T : Comparable<T>> parallelSort(array: Array<T>?, fromIndex: Int, toIndex: Int) {
requireNotNull(array)
array.sort(fromIndex, toIndex)
}
fun <T> parallelSort(array: Array<T>?, fromIndex: Int, toIndex: Int, c: KotlinComparator<in T>?) {
requireNotNull(array)
val c = Comparators.nullToNaturalOrder(c)
array.sortWith(c, fromIndex, toIndex)
}
fun spliterator(array: DoubleArray): Spliterator.OfDouble =
Spliterators.spliterator(array, Spliterator.IMMUTABLE or Spliterator.ORDERED)
fun spliterator(
array: DoubleArray,
startInclusive: Int,
endExclusive: Int
): Spliterator.OfDouble =
Spliterators.spliterator(
array,
startInclusive,
endExclusive,
Spliterator.IMMUTABLE or Spliterator.ORDERED
)
fun spliterator(array: IntArray): Spliterator.OfInt =
Spliterators.spliterator(array, Spliterator.IMMUTABLE or Spliterator.ORDERED)
fun spliterator(array: IntArray, startInclusive: Int, endExclusive: Int): Spliterator.OfInt =
Spliterators.spliterator(
array,
startInclusive,
endExclusive,
Spliterator.IMMUTABLE or Spliterator.ORDERED
)
fun spliterator(array: LongArray): Spliterator.OfLong =
Spliterators.spliterator(array, Spliterator.IMMUTABLE or Spliterator.ORDERED)
fun spliterator(array: LongArray, startInclusive: Int, endExclusive: Int): Spliterator.OfLong =
Spliterators.spliterator(
array,
startInclusive,
endExclusive,
Spliterator.IMMUTABLE or Spliterator.ORDERED
)
fun <T> spliterator(array: Array<T>): Spliterator<T> =
Spliterators.spliterator(array as Array<Any?>, Spliterator.IMMUTABLE or Spliterator.ORDERED)
fun <T> spliterator(array: Array<T>, startInclusive: Int, endExclusive: Int): Spliterator<T> =
Spliterators.spliterator(
array as Array<Any?>,
startInclusive,
endExclusive,
Spliterator.IMMUTABLE or Spliterator.ORDERED
)
fun stream(
array: DoubleArray,
startInclusive: Int = 0,
endExclusive: Int = array.size
): DoubleStream =
StreamSupport.doubleStream(spliterator(array, startInclusive, endExclusive), false)
fun stream(array: IntArray, startInclusive: Int = 0, endExclusive: Int = array.size): IntStream =
StreamSupport.intStream(spliterator(array, startInclusive, endExclusive), false)
fun stream(
array: LongArray,
startInclusive: Int = 0,
endExclusive: Int = array.size
): LongStream = StreamSupport.longStream(spliterator(array, startInclusive, endExclusive), false)
fun <T> stream(
array: Array<T>,
startInclusive: Int = 0,
endExclusive: Int = array.size
): Stream<T> = StreamSupport.stream(spliterator(array, startInclusive, endExclusive), false)
}
| apache-2.0 | 43a98c66edcc2768b6376e823a7e6e07 | 28.47641 | 100 | 0.692407 | 3.960878 | false | false | false | false |
raniejade/kspec | kspec-engine/src/test/kotlin/io/polymorphicpanda/kspec/engine/PendingTest.kt | 1 | 3591 | package io.polymorphicpanda.kspec.engine
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import io.polymorphicpanda.kspec.*
import io.polymorphicpanda.kspec.config.KSpecConfig
import io.polymorphicpanda.kspec.context.Context
import io.polymorphicpanda.kspec.engine.discovery.DiscoveryRequest
import io.polymorphicpanda.kspec.engine.execution.ExecutionListenerAdapter
import io.polymorphicpanda.kspec.engine.execution.ExecutionNotifier
import org.junit.Test
/**
* @author Ranie Jade Ramiso
*/
class PendingTest {
@Test
fun testPendingExample() {
val builder = StringBuilder()
val notifier = ExecutionNotifier()
notifier.addListener(object: ExecutionListenerAdapter() {
override fun exampleStarted(example: Context.Example) {
builder.appendln(example.description)
}
})
val engine = KSpecEngine(notifier)
class PendingSpec: KSpec() {
override fun spec() {
describe("group") {
xit("pending example") { }
xit("another pending example w/o a body", "reason")
it("not a pending example") { }
}
}
}
val result = engine.discover(DiscoveryRequest(listOf(PendingSpec::class), KSpecConfig()))
val expected = """
it: not a pending example
""".trimIndent()
engine.execute(result)
assertThat(builder.trimEnd().toString(), equalTo(expected))
}
@Test
fun testPendingExampleGroup() {
val builder = StringBuilder()
val notifier = ExecutionNotifier()
notifier.addListener(object: ExecutionListenerAdapter() {
override fun exampleStarted(example: Context.Example) {
builder.appendln(example.description)
}
})
val engine = KSpecEngine(notifier)
class PendingSpec: KSpec() {
override fun spec() {
describe("group") {
it("not a pending example") {
}
xcontext("pending group") {
it("pending example #1") {
}
xdescribe(String::class, "pending group with reason and subject", "the reason") {
it("pending example #2") {
}
}
xdescribe(String::class, "pending group with a subject") {
it("pending example #6") {
}
}
}
xdescribe("pending group using xdescribe") {
it("pending example #3") {
}
xcontext(String::class, "pending group with reason and subject", "the reason") {
it("pending example #4") {
}
}
xcontext(String::class, "pending group with a subject") {
it("pending example #5") {
}
}
}
}
}
}
val result = engine.discover(DiscoveryRequest(listOf(PendingSpec::class), KSpecConfig()))
val expected = """
it: not a pending example
""".trimIndent()
engine.execute(result)
assertThat(builder.trimEnd().toString(), equalTo(expected))
}
}
| mit | 7e716313dbe755ed1d537f227e18004e | 30.226087 | 105 | 0.517405 | 5.524615 | false | true | false | false |
daring2/fms | zabbix/core/src/main/kotlin/com/gitlab/daring/fms/zabbix/agent/active/AgentResponse.kt | 1 | 586 | package com.gitlab.daring.fms.zabbix.agent.active
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonInclude
import com.gitlab.daring.fms.zabbix.model.Item
@JsonInclude(JsonInclude.Include.NON_NULL)
data class AgentResponse(
val response: String,
val info: String? = null,
val data: Collection<Item>? = null,
val regexp: Collection<CheckRegexp>? = null
) {
val success @JsonIgnore get() = response == Success
companion object {
val Success = "success"
val Failed = "failed"
}
} | apache-2.0 | d029e4f0798fdb6074735cddfb1a305f | 25.681818 | 55 | 0.696246 | 4.041379 | false | false | false | false |
k0shk0sh/FastHub | app/src/main/java/com/fastaccess/ui/modules/repos/projects/details/ProjectPagerActivity.kt | 1 | 5457 | package com.fastaccess.ui.modules.repos.projects.details
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.viewpager.widget.ViewPager
import android.view.MenuItem
import android.view.View
import android.widget.ProgressBar
import butterknife.BindView
import com.evernote.android.state.State
import com.fastaccess.R
import com.fastaccess.data.dao.FragmentPagerAdapterModel
import com.fastaccess.data.dao.NameParser
import com.fastaccess.data.dao.ProjectColumnModel
import com.fastaccess.helper.BundleConstant
import com.fastaccess.helper.Bundler
import com.fastaccess.ui.adapter.FragmentsPagerAdapter
import com.fastaccess.ui.base.BaseActivity
import com.fastaccess.ui.modules.repos.RepoPagerActivity
import com.fastaccess.ui.modules.user.UserPagerActivity
import com.fastaccess.ui.widgets.CardsPagerTransformerBasic
/**
* Created by Hashemsergani on 11.09.17.
*/
class ProjectPagerActivity : BaseActivity<ProjectPagerMvp.View, ProjectPagerPresenter>(), ProjectPagerMvp.View {
@BindView(R.id.pager) lateinit var pager: ViewPager
@BindView(R.id.loading) lateinit var loading: ProgressBar
@State var isProgressShowing = false
override fun canBack(): Boolean = true
override fun isSecured(): Boolean = false
override fun providePresenter(): ProjectPagerPresenter = ProjectPagerPresenter()
override fun onInitPager(list: List<ProjectColumnModel>) {
hideProgress()
pager.adapter = FragmentsPagerAdapter(supportFragmentManager, FragmentPagerAdapterModel
.buildForProjectColumns(list, presenter.viewerCanUpdate))
}
override fun showMessage(titleRes: Int, msgRes: Int) {
hideProgress()
super.showMessage(titleRes, msgRes)
}
override fun showMessage(titleRes: String, msgRes: String) {
hideProgress()
super.showMessage(titleRes, msgRes)
}
override fun showErrorMessage(msgRes: String) {
hideProgress()
super.showErrorMessage(msgRes)
}
override fun showProgress(resId: Int) {
isProgressShowing = true
loading.visibility = View.VISIBLE
}
override fun hideProgress() {
isProgressShowing = false
loading.visibility = View.GONE
}
override fun layout(): Int = R.layout.projects_activity_layout
override fun isTransparent(): Boolean = true
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return when (item?.itemId) {
android.R.id.home -> {
val repoId = presenter.repoId
if (repoId != null && !repoId.isNullOrBlank()) {
if (!presenter.login.isBlank()) {
val nameParse = NameParser("")
nameParse.name = presenter.repoId
nameParse.username = presenter.login
nameParse.isEnterprise = isEnterprise
RepoPagerActivity.startRepoPager(this, nameParse)
}
} else if (!presenter.login.isBlank()) {
UserPagerActivity.startActivity(this, presenter.login, true, isEnterprise, 0)
}
finish()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (isProgressShowing) {
showProgress(0)
} else {
hideProgress()
}
pager.clipToPadding = false
val partialWidth = resources.getDimensionPixelSize(R.dimen.spacing_xs_large)
val pageMargin = resources.getDimensionPixelSize(R.dimen.spacing_normal)
val pagerPadding = partialWidth + pageMargin
pager.pageMargin = pageMargin
pager.setPageTransformer(true, CardsPagerTransformerBasic(4, 10))
pager.setPadding(pagerPadding, pagerPadding, pagerPadding, pagerPadding)
if (savedInstanceState == null) {
presenter.onActivityCreated(intent)
} else if (presenter.getColumns().isEmpty() && !presenter.isApiCalled) {
presenter.onRetrieveColumns()
} else {
onInitPager(presenter.getColumns())
}
if (presenter.repoId.isNullOrBlank()) {
toolbar?.subtitle = presenter.login
} else {
toolbar?.subtitle = "${presenter.login}/${presenter.repoId}"
}
}
override fun onDeletePage(model: ProjectColumnModel) {
presenter.getColumns().remove(model)
onInitPager(presenter.getColumns())
}
companion object {
fun startActivity(context: Context, login: String, repoId: String? = null, projectId: Long, isEnterprise: Boolean = false) {
context.startActivity(getIntent(context, login, repoId, projectId, isEnterprise))
}
fun getIntent(context: Context, login: String, repoId: String? = null, projectId: Long, isEnterprise: Boolean = false): Intent {
val intent = Intent(context, ProjectPagerActivity::class.java)
intent.putExtras(Bundler.start()
.put(BundleConstant.ID, projectId)
.put(BundleConstant.ITEM, repoId)
.put(BundleConstant.EXTRA, login)
.put(BundleConstant.IS_ENTERPRISE, isEnterprise)
.end())
return intent
}
}
} | gpl-3.0 | 97ba1abd3dde60e16ff2dd96f4a45c87 | 35.630872 | 136 | 0.657321 | 4.902965 | false | false | false | false |
JLLeitschuh/ktlint-gradle | plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintApplyToIdeaTask.kt | 1 | 1899 | package org.jlleitschuh.gradle.ktlint
import net.swiftzer.semver.SemVer
import org.gradle.api.DefaultTask
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Classpath
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
import javax.inject.Inject
@Suppress("UnstableApiUsage")
open class KtlintApplyToIdeaTask @Inject constructor(
objectFactory: ObjectFactory
) : DefaultTask() {
@get:Classpath
val classpath: ConfigurableFileCollection = project.files()
@get:Input
val android: Property<Boolean> = objectFactory.property()
@get:Input
val globally: Property<Boolean> = objectFactory.property()
@get:Input
val ktlintVersion: Property<String> = objectFactory.property()
@TaskAction
fun generate() {
project.javaexec {
it.classpath = classpath
it.main = "com.pinterest.ktlint.Main"
// Global flags
if (android.get()) {
it.args(
"--android"
)
}
// Subcommand
if (globally.get()) {
it.args(getApplyToIdeaCommand())
} else {
it.args(getApplyToProjectCommand())
}
// Subcommand parameters
// -y here to auto-overwrite existing IDEA code style
it.args("-y")
}
}
private fun getApplyToIdeaCommand() =
if (SemVer.parse(ktlintVersion.get()) >= SemVer(0, 35, 0)) {
"applyToIDEA"
} else {
"--apply-to-idea"
}
private fun getApplyToProjectCommand() =
if (SemVer.parse(ktlintVersion.get()) >= SemVer(0, 35, 0)) {
"applyToIDEAProject"
} else {
"--apply-to-idea-project"
}
}
| mit | bddf53b62ed9fb1f396ee4ed5e0db585 | 26.521739 | 68 | 0.602422 | 4.406032 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/ide/lineMarkers/RsImplsLineMarkerProvider.kt | 3 | 2694 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.lineMarkers
import com.intellij.codeInsight.daemon.LineMarkerInfo
import com.intellij.codeInsight.daemon.LineMarkerProvider
import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder
import com.intellij.openapi.util.NotNullLazyValue
import com.intellij.psi.PsiElement
import com.intellij.util.Query
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.psi.RsEnumItem
import org.rust.lang.core.psi.RsImplItem
import org.rust.lang.core.psi.RsStructItem
import org.rust.lang.core.psi.RsTraitItem
import org.rust.lang.core.psi.ext.searchForImplementations
import org.rust.lang.core.psi.ext.union
/**
* Annotates trait declaration with an icon on the gutter that allows to jump to
* its implementations.
*
* See [org.rust.ide.navigation.goto.RsImplsSearch]
*/
class RsImplsLineMarkerProvider : LineMarkerProvider {
override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<PsiElement>? = null
override fun collectSlowLineMarkers(elements: List<PsiElement>, result: MutableCollection<LineMarkerInfo<PsiElement>>) {
for (el in elements) {
// Ideally, we want to avoid showing an icon if there are no implementations,
// but that might be costly. To save time, we always show an icon, but calculate
// the actual icons only when the user clicks it.
// if (query.isEmptyQuery) return null
val query = implsQuery(el) ?: continue
val targets: NotNullLazyValue<Collection<PsiElement>> = NotNullLazyValue.createValue { query.findAll() }
val info = NavigationGutterIconBuilder
.create(RsIcons.IMPLEMENTED)
.setTargets(targets)
.setPopupTitle("Go to implementation")
.setTooltipText("Has implementations")
.createLineMarkerInfo(el)
result.add(info)
}
}
companion object {
fun implsQuery(psi: PsiElement): Query<RsImplItem>? {
val parent = psi.parent
return when {
// For performance reasons (see LineMarkerProvider.getLineMarkerInfo)
// we need to add the line marker only to leaf elements
parent is RsTraitItem && parent.identifier == psi -> parent.searchForImplementations()
parent is RsStructItem && parent.identifier == psi -> parent.searchForImplementations()
parent is RsEnumItem && parent.identifier == psi -> parent.searchForImplementations()
else -> return null
}
}
}
}
| mit | bcc092890d936b24dfc08bcffab8592f | 41.09375 | 124 | 0.687454 | 4.845324 | false | false | false | false |
xfournet/intellij-community | python/src/com/jetbrains/python/sdk/add/PyAddSystemWideInterpreterPanel.kt | 1 | 2304 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.sdk.add
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.FormBuilder
import com.jetbrains.python.sdk.PyDetectedSdk
import com.jetbrains.python.sdk.adminPermissionsNeeded
import com.jetbrains.python.sdk.detectSystemWideSdks
import com.jetbrains.python.sdk.setup
import java.awt.BorderLayout
/**
* @author vlan
*/
class PyAddSystemWideInterpreterPanel(private val existingSdks: List<Sdk>) : PyAddSdkPanel() {
override val panelName = "System interpreter"
private val sdkComboBox = PySdkPathChoosingComboBox(detectSystemWideSdks(existingSdks), null)
init {
layout = BorderLayout()
val permWarning = JBLabel(
"""|<html><strong>Note:</strong> You'll need admin permissions to install packages for this interpreter. Consider
|creating a per-project virtual environment instead.</html>""".trimMargin()).apply {
}
Runnable {
permWarning.isVisible = sdkComboBox.selectedSdk?.adminPermissionsNeeded() ?: false
}.apply {
run()
addChangeListener(this)
}
val formPanel = FormBuilder.createFormBuilder()
.addLabeledComponent("Interpreter:", sdkComboBox)
.addComponentToRightColumn(permWarning)
.panel
add(formPanel, BorderLayout.NORTH)
}
override fun validateAll() = listOfNotNull(validateSdkComboBox(sdkComboBox))
override fun getOrCreateSdk(): Sdk? {
val sdk = sdkComboBox.selectedSdk
return when (sdk) {
is PyDetectedSdk -> sdk.setup(existingSdks)
else -> sdk
}
}
override fun addChangeListener(listener: Runnable) {
sdkComboBox.childComponent.addItemListener { listener.run() }
}
} | apache-2.0 | 41c2e98681af762ae4b834c46535c9de | 33.924242 | 119 | 0.740885 | 4.48249 | false | false | false | false |
Kotlin/dokka | plugins/base/src/main/kotlin/parsers/factories/DocTagsFromIElementFactory.kt | 1 | 4137 | package org.jetbrains.dokka.base.parsers.factories
import org.jetbrains.dokka.model.doc.*
import org.intellij.markdown.IElementType
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.flavours.gfm.GFMElementTypes
import org.intellij.markdown.flavours.gfm.GFMTokenTypes
import org.jetbrains.dokka.base.translators.parseWithNormalisedSpaces
import org.jetbrains.dokka.links.DRI
import org.jetbrains.dokka.model.doc.DocTag.Companion.contentTypeParam
object DocTagsFromIElementFactory {
@Suppress("IMPLICIT_CAST_TO_ANY")
fun getInstance(type: IElementType, children: List<DocTag> = emptyList(), params: Map<String, String> = emptyMap(), body: String? = null, dri: DRI? = null, keepFormatting: Boolean = false) =
when(type) {
MarkdownElementTypes.SHORT_REFERENCE_LINK,
MarkdownElementTypes.FULL_REFERENCE_LINK,
MarkdownElementTypes.INLINE_LINK -> if(dri == null) A(children, params) else DocumentationLink(dri, children, params)
MarkdownElementTypes.STRONG -> B(children, params)
MarkdownElementTypes.BLOCK_QUOTE -> BlockQuote(children, params)
MarkdownElementTypes.CODE_SPAN -> CodeInline(children, params)
MarkdownElementTypes.CODE_BLOCK,
MarkdownElementTypes.CODE_FENCE -> CodeBlock(children, params)
MarkdownElementTypes.ATX_1 -> H1(children, params)
MarkdownElementTypes.ATX_2 -> H2(children, params)
MarkdownElementTypes.ATX_3 -> H3(children, params)
MarkdownElementTypes.ATX_4 -> H4(children, params)
MarkdownElementTypes.ATX_5 -> H5(children, params)
MarkdownElementTypes.ATX_6 -> H6(children, params)
MarkdownElementTypes.EMPH -> I(children, params)
MarkdownElementTypes.IMAGE -> Img(children, params)
MarkdownElementTypes.LIST_ITEM -> Li(children, params)
MarkdownElementTypes.ORDERED_LIST -> Ol(children, params)
MarkdownElementTypes.UNORDERED_LIST -> Ul(children, params)
MarkdownElementTypes.PARAGRAPH -> P(children, params)
MarkdownTokenTypes.TEXT -> if (keepFormatting) Text(
body.orEmpty(),
children,
params
) else {
// corner case: there are only spaces between two Markdown nodes
val containsOnlySpaces = body?.isNotEmpty() == true && body.all { it.isWhitespace() }
if (containsOnlySpaces) Text(" ", children, params)
else body?.parseWithNormalisedSpaces(renderWhiteCharactersAsSpaces = false).orEmpty()
}
MarkdownTokenTypes.HORIZONTAL_RULE -> HorizontalRule
MarkdownTokenTypes.HARD_LINE_BREAK -> Br
GFMElementTypes.STRIKETHROUGH -> Strikethrough(children, params)
GFMElementTypes.TABLE -> Table(children, params)
GFMElementTypes.HEADER -> Th(children, params)
GFMElementTypes.ROW -> Tr(children, params)
GFMTokenTypes.CELL -> Td(children, params)
MarkdownElementTypes.MARKDOWN_FILE -> CustomDocTag(children, params, MarkdownElementTypes.MARKDOWN_FILE.name)
MarkdownElementTypes.HTML_BLOCK,
MarkdownTokenTypes.HTML_TAG,
MarkdownTokenTypes.HTML_BLOCK_CONTENT -> Text(body.orEmpty(), params = params + contentTypeParam("html"))
else -> CustomDocTag(children, params, type.name)
}.let {
@Suppress("UNCHECKED_CAST")
when (it) {
is List<*> -> it as List<DocTag>
else -> listOf(it as DocTag)
}
}
}
| apache-2.0 | 838c74d8bde88f97f870b93c4fdbcfa8 | 60.746269 | 194 | 0.595842 | 5.263359 | false | false | false | false |
Shynixn/BlockBall | blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/service/LoggingUtilServiceImpl.kt | 1 | 2930 | package com.github.shynixn.blockball.core.logic.business.service
import com.github.shynixn.blockball.api.BlockBallApi
import com.github.shynixn.blockball.api.business.service.ConfigurationService
import com.github.shynixn.blockball.api.business.service.LoggingService
import java.util.logging.Level
import java.util.logging.Logger
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
class LoggingUtilServiceImpl(private val logger: Logger) : LoggingService {
private var configService: ConfigurationService? = null
/**
* Logs an debug text only if debug is enabled.
*/
override fun debug(text: String, e: Throwable?) {
if (configService == null) {
configService = BlockBallApi.resolve(ConfigurationService::class.java)
}
if (configService!!.containsValue("debug") && configService!!.findValue("debug")) {
if (e == null) {
logger.log(Level.INFO, text)
} else {
logger.log(Level.INFO, text, e)
}
}
}
/**
* Logs an info text.
*/
override fun info(text: String, e: Throwable?) {
if (e == null) {
logger.log(Level.INFO, text)
} else {
logger.log(Level.INFO, text, e)
}
}
/**
* Logs an warning text.
*/
override fun warn(text: String, e: Throwable?) {
if (e == null) {
logger.log(Level.WARNING, text)
} else {
logger.log(Level.WARNING, text, e)
}
}
/**
* Logs an error text.
*/
override fun error(text: String, e: Throwable?) {
if (e == null) {
logger.log(Level.WARNING, text)
} else {
logger.log(Level.WARNING, text, e)
}
}
} | apache-2.0 | 0e5621abf185701214242a61b1ba1537 | 32.306818 | 91 | 0.645051 | 4.173789 | false | true | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/command/executors/fun/CommandStarboard.kt | 1 | 4320 | package me.mrkirby153.KirBot.command.executors.`fun`
import com.mrkirby153.bfs.model.Model
import me.mrkirby153.KirBot.Bot
import me.mrkirby153.KirBot.command.CommandCategory
import me.mrkirby153.KirBot.command.CommandException
import me.mrkirby153.KirBot.command.annotations.Command
import me.mrkirby153.KirBot.command.annotations.CommandDescription
import me.mrkirby153.KirBot.command.annotations.LogInModlogs
import me.mrkirby153.KirBot.command.args.CommandContext
import me.mrkirby153.KirBot.database.models.guild.starboard.StarboardEntry
import me.mrkirby153.KirBot.modules.StarboardModule
import me.mrkirby153.KirBot.user.CLEARANCE_MOD
import me.mrkirby153.KirBot.utils.Context
import me.mrkirby153.KirBot.utils.nameAndDiscrim
import net.dv8tion.jda.api.sharding.ShardManager
import javax.inject.Inject
class CommandStarboard @Inject constructor(private val starboardModule: StarboardModule, private val shardManager: ShardManager) {
@Command(name = "update", clearance = CLEARANCE_MOD, arguments = ["<mid:snowflake>"],
parent = "starboard", category = CommandCategory.FUN)
@LogInModlogs
@CommandDescription("Forces an update of the starboard message")
fun update(context: Context, cmdContext: CommandContext) {
context.channel.sendMessage(
"Updating starboard for ${cmdContext.getNotNull<String>("mid")}").queue()
starboardModule.updateStarboardMessage(context.guild,
cmdContext.getNotNull("mid"))
}
@Command(name = "hide", clearance = CLEARANCE_MOD, arguments = ["<mid:snowflake>"],
parent = "starboard", category = CommandCategory.FUN)
@LogInModlogs
@CommandDescription("Hides an entry from the starboard")
fun hide(context: Context, cmdContext: CommandContext) {
val entry = Model.where(StarboardEntry::class.java, "id",
cmdContext.getNotNull("mid")).first()
?: throw CommandException("Message not found on the starboard")
entry.hidden = true
entry.save()
starboardModule.updateStarboardMessage(context.guild, entry.id)
context.send().success("Hidden ${cmdContext.getNotNull<String>("mid")} from the starboard",
hand = true).queue()
}
@Command(name = "unhide", clearance = CLEARANCE_MOD, arguments = ["<mid:snowflake>"],
parent = "starboard", category = CommandCategory.FUN)
@LogInModlogs
@CommandDescription("Unhides an entry from the starboard")
fun unhide(context: Context, cmdContext: CommandContext) {
val entry = Model.where(StarboardEntry::class.java, "id",
cmdContext.getNotNull("mid")).first()
?: throw CommandException("Message not found on the starboard")
entry.hidden = false
entry.save()
starboardModule.updateStarboardMessage(context.guild, entry.id)
context.send().success(
"Unhidden ${cmdContext.getNotNull<String>("mid")} from the starboard",
hand = true).queue()
}
@Command(name = "block", clearance = CLEARANCE_MOD, arguments = ["<user:snowflake>"],
parent = "starboard", category = CommandCategory.FUN)
@LogInModlogs
@CommandDescription(
"Blocks a user from the starboard. They cannot star messages and their messages cannot be starred")
fun blockUser(context: Context, cmdContext: CommandContext) {
val user = shardManager.getUserById(cmdContext.getNotNull<String>("user"))
?: throw CommandException("User not found")
starboardModule.block(context.guild, user)
context.send().success("Blocked ${user.nameAndDiscrim} from the starboard", true).queue()
}
@Command(name = "unblock", clearance = CLEARANCE_MOD, arguments = ["<user:snowflake>"],
parent = "starboard", category = CommandCategory.FUN)
@LogInModlogs
@CommandDescription("Unblocks a user from the starboard")
fun unblockUser(context: Context, cmdContext: CommandContext) {
val user = shardManager.getUserById(cmdContext.getNotNull<String>("user"))
?: throw CommandException("User not found")
starboardModule.unblock(context.guild, user)
context.send().success("Unblocked ${user.nameAndDiscrim} from the starboard", true).queue()
}
} | mit | eb181ac0a20226cf885e15b21d004019 | 49.835294 | 130 | 0.700694 | 4.285714 | false | false | false | false |
fnberta/PopularMovies | app/src/main/java/ch/berta/fabio/popularmovies/features/details/view/ReviewsItemDecoration.kt | 1 | 2756 | /*
* Copyright (c) 2017 Fabio Berta
*
* 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 ch.berta.fabio.popularmovies.features.details.view
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.support.v4.view.ViewCompat
import android.support.v7.widget.RecyclerView
import android.view.View
class ReviewsItemDecoration(
context: Context,
val dividerViewType: Int
) : RecyclerView.ItemDecoration() {
private val divider: Drawable
private val bounds = Rect()
init {
val a = context.obtainStyledAttributes(intArrayOf(android.R.attr.listDivider))
divider = a.getDrawable(0)
a.recycle()
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
if (parent.layoutManager == null) {
return
}
drawDivider(c, parent)
}
@SuppressLint("NewApi")
private fun drawDivider(canvas: Canvas, parent: RecyclerView) {
canvas.save()
val left: Int
val right: Int
if (parent.clipToPadding) {
left = parent.paddingLeft
right = parent.width - parent.paddingRight
canvas.clipRect(left, parent.paddingTop, right, parent.height - parent.paddingBottom)
} else {
left = 0
right = parent.width
}
(0..parent.childCount - 2)
.map { parent.getChildAt(it) }
.filter { parent.getChildViewHolder(it).itemViewType == dividerViewType }
.forEach {
parent.getDecoratedBoundsWithMargins(it, bounds)
val bottom = bounds.bottom + Math.round(ViewCompat.getTranslationY(it))
val top = bottom - divider.intrinsicHeight
divider.setBounds(left, top, right, bottom)
divider.draw(canvas)
}
canvas.restore()
}
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State?
) = outRect.set(0, 0, 0, divider.intrinsicHeight)
} | apache-2.0 | 12924f1d302c3c58914c2765c49834c6 | 31.435294 | 97 | 0.644049 | 4.608696 | false | false | false | false |
phillbarber/kotlin-maze-demo | src/main/kotlin/demo/Maze.kt | 1 | 3418 | package demo
private val NEW_LINE_DELIMETER = "\n"
class Maze(fileAsString: String) {
val rows: List<List<Cell>>
init {
var gridOfRows: List<List<Cell>> = fileAsString
.split(NEW_LINE_DELIMETER)
.mapIndexed { yIndex, line ->
createListOfCellsForARow(line, yIndex)
}
addDownUpLeftRightToCells(gridOfRows)
rows = gridOfRows
}
private fun addDownUpLeftRightToCells(gridOfRows: List<List<Cell>>) {
gridOfRows.forEach{ rowOnYAxis ->
rowOnYAxis.forEach { cell ->
cell.down = getCellByCoordinates(gridOfRows, cell.yAxis + 1, cell.xAxis)
cell.up = getCellByCoordinates(gridOfRows, cell.yAxis - 1, cell.xAxis)
cell.left = getCellByCoordinates(gridOfRows, cell.yAxis, cell.xAxis - 1)
cell.right = getCellByCoordinates(gridOfRows, cell.yAxis, cell.xAxis + 1)
}
}
}
private fun getCellByCoordinates(gridOfCells: List<List<Cell>>, yAxis: Int, xAxis: Int): Cell? {
if (yAxis > 0 && yAxis < gridOfCells.size){
val rowOnYAxis = gridOfCells.get(yAxis)
if (xAxis > 0 && xAxis<rowOnYAxis.size){
return rowOnYAxis.get(xAxis)
}
}
return null
}
private fun createListOfCellsForARow(line: String, yIndex: Int): List<Cell> {
return line.chars().toArray().mapIndexed { xIndex, character ->
Cell( type = fromChar(character.toChar()),
xAxis = xIndex,
yAxis = yIndex) }
}
fun getSolution(): List<Cell> {
val finish = getFinish(getStart(), mutableListOf())
return finish
}
private fun getFinish(cell: Cell?, route: MutableList<Cell>): List<Cell> {
if (route.filter { cell -> cell.type == Type.Finish }.any()){
return route;
}
if (cell != null){
route.add(cell)
if (cell.type == Type.Finish){
return route;
}
if (shouldVisitCell(cell.down, route)){
getFinish(cell.down, route);
}
if (shouldVisitCell(cell.right, route)){
getFinish(cell.right, route);
}
if (shouldVisitCell(cell.left, route)){
getFinish(cell.left, route);
}
if (shouldVisitCell(cell.up, route)){
getFinish(cell.up, route);
}
}
return route;
}
private fun shouldVisitCell(down: Cell?, route: List<Cell>) = down != null && down!!.type != Type.Wall && !route.contains(down)
fun getStart(): Cell? {
rows.forEach { cells ->
cells.forEach { cell ->
if (cell.type == Type.Start) {
return cell;
}
}
}
return null
}
fun getMazeAsStringWithRoute(route: List<Cell>) : String {
val result = StringBuffer()
this.rows.forEach {
it.forEach { cell ->
if (route.contains(cell) && cell.type == Type.Free){
result.append(TRAIL_CHARACTER)
}
else{
result.append(cell.type.value)
}
}
result.append("\n");
}
return result.toString();
}
}
| mit | b1155facd24e4b5120a8b6c54e4ff22f | 27.966102 | 131 | 0.519017 | 4.199017 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/RsWrongLifetimeParametersNumberInspection.kt | 4 | 1916 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
import com.intellij.codeInspection.ProblemsHolder
import org.rust.lang.core.psi.RsBaseType
import org.rust.lang.core.psi.RsRefLikeType
import org.rust.lang.core.psi.RsVisitor
import org.rust.lang.core.psi.ext.RsGenericDeclaration
import org.rust.lang.core.types.lifetimeElidable
class RsWrongLifetimeParametersNumberInspection : RsLocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
object : RsVisitor() {
override fun visitBaseType(type: RsBaseType) {
// Don't apply generic declaration checks to Fn-traits and `Self`
if (type.path?.valueParameterList != null) return
if (type.path?.cself != null) return
val paramsDecl = type.path?.reference?.resolve() as? RsGenericDeclaration ?: return
val expectedLifetimes = paramsDecl.typeParameterList?.lifetimeParameterList?.size ?: 0
val actualLifetimes = type.path?.typeArgumentList?.lifetimeList?.size ?: 0
if (expectedLifetimes == actualLifetimes) return
if (actualLifetimes == 0 && !type.lifetimeElidable) {
holder.registerProblem(type, "Missing lifetime specifier [E0106]")
} else if (actualLifetimes > 0) {
holder.registerProblem(type, "Wrong number of lifetime parameters: expected $expectedLifetimes, found $actualLifetimes [E0107]")
}
}
override fun visitRefLikeType(type: RsRefLikeType) {
if (type.mul == null && !type.lifetimeElidable && type.lifetime == null) {
holder.registerProblem(type.and ?: type, "Missing lifetime specifier [E0106]")
}
}
}
}
| mit | 6ffd7cbe6f3907de7036cf4ab4b251cb | 44.619048 | 148 | 0.649269 | 4.719212 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/sync/roster/SmashRosterStorageImpl.kt | 1 | 3600 | package com.garpr.android.sync.roster
import androidx.annotation.WorkerThread
import com.garpr.android.data.database.DbSmashCompetitor
import com.garpr.android.data.database.SmashCompetitorDao
import com.garpr.android.data.models.Endpoint
import com.garpr.android.data.models.Region
import com.garpr.android.data.models.SmashCompetitor
import com.garpr.android.misc.ThreadUtils
import com.garpr.android.misc.Timber
import com.garpr.android.preferences.KeyValueStoreProvider
import com.squareup.moshi.Moshi
class SmashRosterStorageImpl(
private val keyValueStoreProvider: KeyValueStoreProvider,
private val moshi: Moshi,
private val smashCompetitorDao: SmashCompetitorDao,
private val packageName: String,
private val threadUtils: ThreadUtils,
private val timber: Timber
) : SmashRosterStorage {
override fun clear() {
timber.d(TAG, "clearing smash roster storage...")
smashCompetitorDao.deleteAll()
}
override fun getSmashCompetitor(endpoint: Endpoint, playerId: String?): SmashCompetitor? {
if (playerId.isNullOrBlank()) {
return null
}
val dbSmashCompetitor = smashCompetitorDao.get(endpoint, playerId)
return dbSmashCompetitor?.toSmashCompetitor()
}
override fun getSmashCompetitor(region: Region, playerId: String?): SmashCompetitor? {
return getSmashCompetitor(region.endpoint, playerId)
}
override fun migrate() {
threadUtils.background.submit {
migrateFromKeyValueStoreToRoom()
}
}
@WorkerThread
private fun migrateFromKeyValueStoreToRoom() {
timber.d(TAG, "migrating smash roster from KeyValueStore to Room...")
val smashCompetitorAdapter = moshi.adapter(SmashCompetitor::class.java)
val dbSmashCompetitors = mutableListOf<DbSmashCompetitor>()
Endpoint.values().forEach { endpoint ->
val keyValueStore = keyValueStoreProvider.getKeyValueStore(
"$packageName.SmashRosterStorage.$endpoint")
keyValueStore.all?.mapNotNullTo(dbSmashCompetitors) { (_, json) ->
val smashCompetitor = if (json is String && json.isNotBlank()) {
smashCompetitorAdapter.fromJson(json)
} else {
null
}
if (smashCompetitor == null) {
null
} else {
DbSmashCompetitor(
smashCompetitor = smashCompetitor,
endpoint = endpoint
)
}
}
keyValueStore.clear()
}
if (dbSmashCompetitors.isEmpty()) {
timber.d(TAG, "smash roster storage has no competitors to migrate")
return
}
smashCompetitorDao.insertAll(dbSmashCompetitors)
timber.d(TAG, "finished migration process")
}
override fun writeToStorage(endpoint: Endpoint, smashRoster: Map<String, SmashCompetitor>?) {
val dbSmashCompetitors = smashRoster?.map { (_, smashCompetitor) ->
DbSmashCompetitor(
smashCompetitor = smashCompetitor,
endpoint = endpoint
)
}
if (!dbSmashCompetitors.isNullOrEmpty()) {
smashCompetitorDao.insertAll(dbSmashCompetitors)
}
timber.d(TAG, "added ${dbSmashCompetitors?.size ?: 0} $endpoint competitor(s) to Room")
}
companion object {
private const val TAG = "SmashRosterStorageImpl"
}
}
| unlicense | 007d9def2f267bdfd1ad967345784d67 | 32.962264 | 97 | 0.636111 | 5 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/features/tournament/TournamentMatchItemView.kt | 1 | 2613 | package com.garpr.android.features.tournament
import android.content.Context
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import androidx.annotation.ColorInt
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import com.garpr.android.R
import com.garpr.android.data.models.FullTournament
import com.garpr.android.extensions.getAttrColor
import kotlinx.android.synthetic.main.item_tournament_match.view.*
class TournamentMatchItemView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs), View.OnClickListener {
private val originalBackground: Drawable? = background
private var _match: FullTournament.Match? = null
val match: FullTournament.Match
get() = checkNotNull(_match)
@ColorInt
private val exclusionColor: Int = context.getAttrColor(android.R.attr.textColorSecondary)
@ColorInt
private val loseColor: Int = ContextCompat.getColor(context, R.color.lose)
@ColorInt
private val winColor: Int = ContextCompat.getColor(context, R.color.win)
var listener: Listener? = null
interface Listener {
fun onClick(v: TournamentMatchItemView)
}
init {
setOnClickListener(this)
}
override fun onClick(v: View) {
listener?.onClick(this)
}
fun setContent(match: FullTournament.Match, winnerIsIdentity: Boolean, loserIsIdentity: Boolean) {
_match = match
loserName.text = match.loser.name
winnerName.text = match.winner.name
if (match.excluded) {
loserName.setTextColor(exclusionColor)
winnerName.setTextColor(exclusionColor)
} else {
loserName.setTextColor(loseColor)
winnerName.setTextColor(winColor)
}
if (winnerIsIdentity) {
winnerName.typeface = Typeface.DEFAULT_BOLD
loserName.typeface = Typeface.DEFAULT
setBackgroundColor(ContextCompat.getColor(context, R.color.card_background))
} else if (loserIsIdentity) {
winnerName.typeface = Typeface.DEFAULT
loserName.typeface = Typeface.DEFAULT_BOLD
setBackgroundColor(ContextCompat.getColor(context, R.color.card_background))
} else {
winnerName.typeface = Typeface.DEFAULT
loserName.typeface = Typeface.DEFAULT
ViewCompat.setBackground(this, originalBackground)
}
}
}
| unlicense | 374a65ca50ac7bff5a090430ccf3c808 | 31.259259 | 102 | 0.707233 | 4.624779 | false | false | false | false |
MaisonWan/AppFileExplorer | FileExplorer/src/main/java/com/domker/app/explorer/FileExplorerActivity.kt | 1 | 5275 | package com.domker.app.explorer
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.domker.app.explorer.fragment.*
import com.domker.app.explorer.helper.KeyPressHelper
import com.domker.app.explorer.hostapp.HostApp
/**
* 查看文件和app信息,机型信息的总入口
*/
class FileExplorerActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
private lateinit var mFab: FloatingActionButton
private lateinit var mToolbar: Toolbar
private lateinit var mDrawerLayout: DrawerLayout
private lateinit var mNavView: NavigationView
private lateinit var mAppIcon: ImageView
private lateinit var mAppName: TextView
private lateinit var mPackageName: TextView
private lateinit var mBackPressHelper: KeyPressHelper
private lateinit var mFragmentScheduler: FragmentScheduler
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.fe_activity_file_explorer)
initViews()
setSupportActionBar(mToolbar)
initListener()
loadFragment(FileViewerFragment::class.java)
}
private fun initListener() {
val toggle = ActionBarDrawerToggle(
this, mDrawerLayout, mToolbar, R.string.fe_navigation_drawer_open,
R.string.fe_navigation_drawer_close)
mDrawerLayout.addDrawerListener(toggle)
toggle.syncState()
mNavView.setNavigationItemSelectedListener(this)
mBackPressHelper = KeyPressHelper(this)
mFragmentScheduler = FragmentScheduler(fragmentManager)
mFab.setOnClickListener { view ->
val currentFragment = fragmentManager.findFragmentById(R.id.fragment_content) as IActionFragment
currentFragment?.onAssistButtonClick(view)
}
}
private fun initViews() {
mFab = findViewById(R.id.fab)
mToolbar = findViewById(R.id.toolbar)
mDrawerLayout = findViewById(R.id.drawer_layout)
mNavView = findViewById(R.id.nav_view)
val headerView = mNavView.getHeaderView(0)
mAppIcon = headerView.findViewById(R.id.imageViewIcon)
mAppName = headerView.findViewById(R.id.textViewAppName)
mPackageName = headerView.findViewById(R.id.textViewPackage)
mAppIcon.setImageDrawable(HostApp.getHostAppIcon(this))
mAppName.text = HostApp.getHostAppName(baseContext)
mPackageName.text = HostApp.getHostAppPackage(baseContext)
}
/**
* 更新assist按钮状态
*/
private fun updateAssistButton(fragment: IActionFragment) {
val drawable = fragment.initAssistButtonDrawable(this)
if (drawable != null) {
mFab.visibility = View.VISIBLE
mFab.setImageDrawable(drawable)
} else {
mFab.visibility = View.GONE
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
// 抽屉打开的时候优先关闭
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START)
return true
}
if (mBackPressHelper.onKeyPressed(keyCode, event)) {
return true
}
return super.onKeyDown(keyCode, event)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.nav_app_info -> {
loadFragment(AppInfoFragment::class.java)
}
R.id.nav_file_explorer -> {
loadFragment(FileViewerFragment::class.java)
}
R.id.nav_phone_info -> {
loadFragment(PhoneInfoFragment::class.java)
}
R.id.nav_settings -> {
loadFragment(SettingsFragment::class.java)
}
R.id.nav_share -> {
}
R.id.nav_send -> {
}
}
mDrawerLayout.closeDrawer(GravityCompat.START)
return true
}
private fun loadFragment(clazz: Class<*>) {
val fragment = mFragmentScheduler.loadFragment(clazz)
if (fragment is IActionFragment) {
// 初始化按钮的显示
updateAssistButton(fragment)
}
}
//
// private fun testCreateDatabase() {
// (0..5).map { SQLHelper(this, "test_$it.db", null, 1) }
// .forEach { it.readableDatabase.close() }
// }
}
| apache-2.0 | 3e5e51cb1524aa5ed2fb44779772fbf9 | 32.503226 | 108 | 0.665896 | 4.599646 | false | false | false | false |
Fitbit/MvRx | launcher/src/main/java/com/airbnb/mvrx/launcher/views/TextRow.kt | 1 | 1297 | package com.airbnb.mvrx.launcher.views
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.isGone
import com.airbnb.epoxy.CallbackProp
import com.airbnb.epoxy.ModelView
import com.airbnb.epoxy.TextProp
import com.airbnb.mvrx.launcher.R
@ModelView(autoLayout = ModelView.Size.MATCH_WIDTH_WRAP_HEIGHT)
class TextRow @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
private val titleView: TextView
private val subtitleView: TextView
init {
inflate(context, R.layout.mavericks_text_row, this)
titleView = findViewById(R.id.title)
subtitleView = findViewById(R.id.subtitle)
orientation = VERTICAL
}
@TextProp
fun setTitle(title: CharSequence) {
titleView.text = title
}
@TextProp
fun setSubtitle(subtitle: CharSequence?) {
subtitleView.isGone = subtitle.isNullOrBlank()
subtitleView.text = subtitle
}
@CallbackProp
fun onClickListener(listener: View.OnClickListener?) {
isClickable = listener != null
setOnClickListener(listener)
}
}
| apache-2.0 | fa99f93f8c1fa19cb36fd4910bdc762c | 26.595745 | 63 | 0.722436 | 4.294702 | false | false | false | false |
sangcomz/FishBun | FishBun/src/main/java/com/sangcomz/fishbun/ui/album/ui/AlbumActivity.kt | 1 | 12646 | package com.sangcomz.fishbun.ui.album.ui
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.constraintlayout.widget.Group
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar
import com.sangcomz.fishbun.BaseActivity
import com.sangcomz.fishbun.FishBun
import com.sangcomz.fishbun.Fishton
import com.sangcomz.fishbun.R
import com.sangcomz.fishbun.adapter.image.ImageAdapter
import com.sangcomz.fishbun.datasource.CameraDataSourceImpl
import com.sangcomz.fishbun.datasource.FishBunDataSourceImpl
import com.sangcomz.fishbun.ui.album.model.Album
import com.sangcomz.fishbun.ui.album.model.repository.AlbumRepositoryImpl
import com.sangcomz.fishbun.datasource.ImageDataSourceImpl
import com.sangcomz.fishbun.ui.album.AlbumContract
import com.sangcomz.fishbun.ui.album.mvp.AlbumPresenter
import com.sangcomz.fishbun.ui.album.adapter.AlbumListAdapter
import com.sangcomz.fishbun.ui.album.listener.AlbumClickListener
import com.sangcomz.fishbun.ui.album.model.AlbumViewData
import com.sangcomz.fishbun.ui.picker.PickerActivity
import com.sangcomz.fishbun.util.MainUiHandler
import com.sangcomz.fishbun.util.SingleMediaScanner
import com.sangcomz.fishbun.util.isLandscape
import com.sangcomz.fishbun.util.setStatusBarColor
import java.io.File
import kotlin.collections.ArrayList
class AlbumActivity : BaseActivity(),
AlbumContract.View, AlbumClickListener {
private val albumPresenter: AlbumContract.Presenter by lazy {
AlbumPresenter(
this,
AlbumRepositoryImpl(
ImageDataSourceImpl(contentResolver),
FishBunDataSourceImpl(Fishton),
CameraDataSourceImpl(this)
),
MainUiHandler()
)
}
private var groupEmptyView: Group? = null
private var recyclerAlbumList: RecyclerView? = null
private var adapter: AlbumListAdapter? = null
private var txtAlbumMessage: TextView? = null
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_photo_album)
initView()
albumPresenter.getDesignViewData()
if (checkPermission()) albumPresenter.loadAlbumList()
}
override fun onResume() {
super.onResume()
albumPresenter.onResume()
}
override fun onDestroy() {
super.onDestroy()
albumPresenter.release()
}
private fun initView() {
groupEmptyView = findViewById(R.id.group_album_empty)
recyclerAlbumList = findViewById(R.id.recycler_album_list)
txtAlbumMessage = findViewById(R.id.txt_album_msg)
findViewById<ImageView>(R.id.iv_album_camera).setOnClickListener {
albumPresenter.takePicture()
}
}
override fun setRecyclerView(albumViewData: AlbumViewData) {
val layoutManager =
if (this.isLandscape()) GridLayoutManager(this, albumViewData.albumLandscapeSpanCount)
else GridLayoutManager(this, albumViewData.albumPortraitSpanCount)
recyclerAlbumList?.layoutManager = layoutManager
}
override fun setToolBar(albumViewData: AlbumViewData) {
val toolbar = findViewById<Toolbar>(R.id.toolbar_album_bar)
txtAlbumMessage?.setText(R.string.msg_loading_image)
setSupportActionBar(toolbar)
toolbar.setBackgroundColor(albumViewData.colorActionBar)
toolbar.setTitleTextColor(albumViewData.colorActionBarTitle)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
this.setStatusBarColor(albumViewData.colorStatusBar)
}
supportActionBar?.let {
it.title = albumViewData.titleActionBar
it.setDisplayHomeAsUpEnabled(true)
if (albumViewData.drawableHomeAsUpIndicator != null) {
it.setHomeAsUpIndicator(albumViewData.drawableHomeAsUpIndicator)
}
}
if (albumViewData.isStatusBarLight && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
toolbar.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
albumPresenter.getAlbumMenuViewData { albumMenuViewData ->
if (albumMenuViewData.hasButtonInAlbumActivity) {
menuInflater.inflate(R.menu.menu_photo_album, menu)
val menuDoneItem = menu.findItem(R.id.action_done)
menu.findItem(R.id.action_all_done).isVisible = false
if (albumMenuViewData.drawableDoneButton != null) {
menuDoneItem.icon = albumMenuViewData.drawableDoneButton
} else if (albumMenuViewData.strDoneMenu != null) {
if (albumMenuViewData.colorTextMenu != Int.MAX_VALUE) {
val spanString = SpannableString(albumMenuViewData.strDoneMenu)
spanString.setSpan(
ForegroundColorSpan(albumMenuViewData.colorTextMenu),
0,
spanString.length,
0
) //fi
menuDoneItem.title = spanString
} else {
menuDoneItem.title = albumMenuViewData.strDoneMenu
}
menuDoneItem.icon = null
}
}
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == android.R.id.home) {
finish()
} else if (id == R.id.action_done) {
if (adapter != null) {
albumPresenter.onClickMenuDone()
}
}
return super.onOptionsItemSelected(item)
}
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
ENTER_ALBUM_REQUEST_CODE -> {
if (resultCode == Activity.RESULT_OK) {
albumPresenter.finish()
} else if (resultCode == TAKE_A_NEW_PICTURE_RESULT_CODE) {
albumPresenter.loadAlbumList()
}
}
TAKE_A_PICTURE_REQUEST_CODE -> {
if (resultCode == Activity.RESULT_OK) {
albumPresenter.onSuccessTakePicture()
} else {
cameraUtil.savedPath?.let {
File(it).delete()
}
}
}
}
}
override fun scanAndRefresh() {
val savedPath = cameraUtil.savedPath ?: return
SingleMediaScanner(this, File(savedPath)) {
albumPresenter.loadAlbumList()
}
}
override fun showNothingSelectedMessage(nothingSelectedMessage: String) {
recyclerAlbumList?.let {
it.post {
Snackbar.make(it, nothingSelectedMessage, Snackbar.LENGTH_SHORT).show()
}
}
}
override fun showMinimumImageMessage(currentSelectedCount: Int) {
recyclerAlbumList?.let {
it.post {
Snackbar
.make(
it,
getString(R.string.msg_minimum_image, currentSelectedCount),
Snackbar.LENGTH_SHORT
)
.show()
}
}
}
override fun takePicture(saveDir: String) {
if (checkCameraPermission()) {
cameraUtil.takePicture(this@AlbumActivity, saveDir, TAKE_A_PICTURE_REQUEST_CODE)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>, grantResults: IntArray
) {
when (requestCode) {
PERMISSION_STORAGE -> {
if (grantResults.isNotEmpty()) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay!
albumPresenter.loadAlbumList()
} else {
permissionCheck.showPermissionDialog()
finish()
}
}
}
PERMISSION_CAMERA -> {
if (grantResults.isNotEmpty()) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay!
albumPresenter.takePicture()
} else {
permissionCheck.showPermissionDialog()
}
}
}
}
}
override fun showAlbumList(
albumList: List<Album>,
imageAdapter: ImageAdapter,
albumViewData: AlbumViewData
) {
recyclerAlbumList?.visibility = View.VISIBLE
groupEmptyView?.visibility = View.GONE
setAlbumListAdapter(albumList, imageAdapter, albumViewData)
}
override fun onAlbumClick(position: Int, album: Album) {
PickerActivity.getPickerActivityIntent(this, album.id, album.displayName, position)
.also { startActivityForResult(it, ENTER_ALBUM_REQUEST_CODE) }
}
override fun changeToolbarTitle(selectedImageCount: Int, albumViewData: AlbumViewData) {
supportActionBar?.apply {
title =
if (albumViewData.maxCount == 1 || !albumViewData.isShowCount) albumViewData.titleActionBar
else getString(
R.string.title_toolbar,
albumViewData.titleActionBar,
selectedImageCount,
albumViewData.maxCount
)
}
}
override fun finishActivityWithResult(selectedImages: List<Uri>) {
val i = Intent()
i.putParcelableArrayListExtra(FishBun.INTENT_PATH, ArrayList(selectedImages))
setResult(Activity.RESULT_OK, i)
finish()
}
private fun checkPermission(): Boolean {
return permissionCheck.checkStoragePermission(PERMISSION_STORAGE)
}
private fun checkCameraPermission(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
permissionCheck.checkCameraPermission(PERMISSION_CAMERA)
} else true
}
override fun setRecyclerViewSpanCount(albumViewData: AlbumViewData) {
val recyclerView = recyclerAlbumList ?: return
val gridLayoutManager = recyclerView.layoutManager as? GridLayoutManager ?: return
gridLayoutManager.spanCount =
if (isLandscape()) albumViewData.albumLandscapeSpanCount
else albumViewData.albumPortraitSpanCount
}
override fun refreshAlbumItem(position: Int, imagePath: ArrayList<Uri>) {
val thumbnailPath = imagePath[imagePath.size - 1].toString()
val addedCount = imagePath.size
adapter?.updateAlbumMeta(0, addedCount, thumbnailPath)
adapter?.updateAlbumMeta(position, addedCount, thumbnailPath)
}
override fun saveImageForAndroidQOrHigher() {
val savedPath = cameraUtil.savedPath ?: return
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
cameraUtil.saveImageForAndroidQOrHigher(contentResolver, File(savedPath))
}
}
private fun setAlbumListAdapter(
albumList: List<Album>,
imageAdapter: ImageAdapter,
albumViewData: AlbumViewData
) {
if (adapter == null) {
adapter = AlbumListAdapter(this, albumViewData.albumThumbnailSize, imageAdapter).also {
recyclerAlbumList?.adapter = it
}
}
adapter?.let {
it.setAlbumList(albumList)
it.notifyDataSetChanged()
}
}
override fun showEmptyView() {
groupEmptyView?.visibility = View.VISIBLE
recyclerAlbumList?.visibility = View.INVISIBLE
txtAlbumMessage?.setText(R.string.msg_no_image)
}
} | apache-2.0 | 44cf8e43469211df85ade46cfc8cfc41 | 35.237822 | 107 | 0.625573 | 5.034236 | false | false | false | false |
moltendorf/IntelliDoors | src/main/kotlin/net/moltendorf/bukkit/intellidoors/controller/SimpleDoor.kt | 1 | 829 | package net.moltendorf.bukkit.intellidoors.controller
import net.moltendorf.bukkit.intellidoors.*
import net.moltendorf.bukkit.intellidoors.controller.Door.Flag.*
import net.moltendorf.bukkit.intellidoors.controller.Door.Mask.*
import net.moltendorf.bukkit.intellidoors.settings.*
import org.bukkit.block.*
/**
* Created by moltendorf on 16/5/2.
*/
abstract class SimpleDoor(val block : Block, settings : Settings) : Door(settings) {
val state = block.state!!
override val location get() = state.location!!
override val powered get() = block.isBlockIndirectlyPowered
override val type get() = state.type!!
override var open = state.intData and 4 == 4
override fun update() : Bool {
when {
open -> state.apply(OPEN)
else -> state.apply(CLOSED)
}
return state.update(false, false)
}
}
| mit | 9d560b0a8128c7a410a65e8340bb42af | 27.586207 | 84 | 0.72497 | 3.42562 | false | false | false | false |
valich/intellij-markdown | src/commonMain/kotlin/org/intellij/markdown/parser/markerblocks/impl/ListItemMarkerBlock.kt | 1 | 2158 | package org.intellij.markdown.parser.markerblocks.impl
import org.intellij.markdown.IElementType
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.lexer.Compat.assert
import org.intellij.markdown.parser.LookaheadText
import org.intellij.markdown.parser.ProductionHolder
import org.intellij.markdown.parser.constraints.MarkdownConstraints
import org.intellij.markdown.parser.constraints.applyToNextLineAndAddModifiers
import org.intellij.markdown.parser.constraints.extendsPrev
import org.intellij.markdown.parser.markerblocks.MarkdownParserUtil
import org.intellij.markdown.parser.markerblocks.MarkerBlock
import org.intellij.markdown.parser.markerblocks.MarkerBlockImpl
class ListItemMarkerBlock(myConstraints: MarkdownConstraints,
marker: ProductionHolder.Marker) : MarkerBlockImpl(myConstraints, marker) {
override fun allowsSubBlocks(): Boolean = true
override fun isInterestingOffset(pos: LookaheadText.Position): Boolean = pos.offsetInCurrentLine == -1
override fun getDefaultAction(): MarkerBlock.ClosingAction {
return MarkerBlock.ClosingAction.DONE
}
override fun calcNextInterestingOffset(pos: LookaheadText.Position): Int {
return pos.nextLineOffset ?: -1
}
override fun doProcessToken(pos: LookaheadText.Position, currentConstraints: MarkdownConstraints): MarkerBlock.ProcessingResult {
assert(pos.offsetInCurrentLine == -1)
val eolN = MarkdownParserUtil.calcNumberOfConsequentEols(pos, constraints)
if (eolN >= 3) {
return MarkerBlock.ProcessingResult.DEFAULT
}
val nonemptyPos = MarkdownParserUtil.getFirstNonWhitespaceLinePos(pos, eolN)
?: return MarkerBlock.ProcessingResult.DEFAULT
val nextLineConstraints = constraints.applyToNextLineAndAddModifiers(nonemptyPos)
if (!nextLineConstraints.extendsPrev(constraints)) {
return MarkerBlock.ProcessingResult.DEFAULT
}
return MarkerBlock.ProcessingResult.CANCEL
}
override fun getDefaultNodeType(): IElementType {
return MarkdownElementTypes.LIST_ITEM
}
}
| apache-2.0 | 101377ab805d43d98258b4710e8fda83 | 42.16 | 133 | 0.771548 | 5.302211 | false | false | false | false |
square/duktape-android | zipline-bytecode/src/main/kotlin/app/cash/zipline/bytecode/applySourceMap.kt | 1 | 3068 | /*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 app.cash.zipline.bytecode
import okio.Buffer
/**
* Combines QuickJS bytecode with a JavaScript source map to produce new QuickJS bytecode that
* bakes in the source map. Exceptions thrown will have the stack traces as if the original sources
* were compiled.
*
* We use this to get Kotlin line numbers in our QuickJS bytecode.
*/
fun applySourceMapToBytecode(jsBytecode: ByteArray, sourceMap: String): ByteArray {
val jsReader = JsObjectReader(jsBytecode)
val jsObject = jsReader.use {
jsReader.readJsObject()
}
val atoms = jsReader.atoms.toMutableAtomSet()
val rewriter = SourceMapBytecodeRewriter(
sourceMap = SourceMap.parse(sourceMap),
atoms = atoms
)
val ktObject = with(rewriter) {
jsObject.jsToKt()
}
val result = Buffer()
JsObjectWriter(atoms, result).use { writer ->
writer.writeJsObject(ktObject)
}
return result.readByteArray()
}
private class SourceMapBytecodeRewriter(
val sourceMap: SourceMap,
val atoms: MutableAtomSet,
) {
fun JsObject.jsToKt(): JsObject {
return when (this) {
is JsFunctionBytecode -> {
copy(
debug = debug?.jsToKt(),
constantPool = constantPool.map { it.jsToKt() }
)
}
else -> this
}
}
fun Debug.jsToKt(): Debug {
val ktPc2LineBuffer = Buffer()
val jsReader = LineNumberReader(
functionLineNumber = lineNumber,
source = Buffer().write(pc2Line)
)
var ktFileName: String? = null
var functionKtLineNumber: Int = -1
lateinit var ktWriter: LineNumberWriter
while (jsReader.next()) {
val segment = sourceMap.find(jsReader.line)
val instructionKtLineNumber = segment?.sourceLine?.toInt() ?: jsReader.line
// If we haven't initialized declaration-level data, do that now. We'd prefer to map from the
// source declaration line number, but we can't because that information isn't in the source
// map. (It maps instructions, not declarations).
if (ktFileName == null) {
ktFileName = segment?.source?.also {
atoms.add(it)
}
functionKtLineNumber = instructionKtLineNumber
ktWriter = LineNumberWriter(functionKtLineNumber, ktPc2LineBuffer)
}
ktWriter.next(jsReader.pc, instructionKtLineNumber)
}
return Debug(
fileName = ktFileName ?: fileName,
lineNumber = functionKtLineNumber,
pc2Line = ktPc2LineBuffer.readByteString(),
)
}
}
| apache-2.0 | f5d220ba5bd90b1313deb0fb654ff8bf | 29.376238 | 99 | 0.687419 | 4.123656 | false | false | false | false |
valich/intellij-markdown | src/commonMain/kotlin/org/intellij/markdown/lexer/MarkdownLexer.kt | 1 | 2481 | package org.intellij.markdown.lexer
import org.intellij.markdown.IElementType
import org.intellij.markdown.MarkdownTokenTypes
open class MarkdownLexer(private val baseLexer: GeneratedLexer) {
var type: IElementType? = null
private set
private var nextType: IElementType? = null
var originalText: CharSequence = ""
private set
var bufferStart: Int = 0
private set
var bufferEnd: Int = 0
private set
var tokenStart: Int = 0
private set
var tokenEnd: Int = 0
private set
val state = baseLexer.state
// fun lex(originalText: CharSequence, bufferStart: Int = 0,
// bufferEnd: Int = originalText.length) : Stream
fun start(originalText: CharSequence,
bufferStart: Int = 0,
bufferEnd: Int = originalText.length,
state: Int = 0) {
reset(originalText, bufferStart, bufferEnd, state)
calcNextType()
}
fun advance(): Boolean {
return locateToken()
}
private fun locateToken(): Boolean {
`type` = nextType
tokenStart = tokenEnd
if (`type` == null) {
return false
}
calcNextType()
return true
}
private fun calcNextType() {
do {
tokenEnd = baseLexer.tokenEnd
nextType = advanceBase()
} while (type.let { nextType == it && it != null && it in TOKENS_TO_MERGE })
}
private fun advanceBase(): IElementType? {
try {
return baseLexer.advance()
} catch (e: Exception) {
throw AssertionError("This could not be!")
}
}
fun reset(buffer: CharSequence, start: Int, end: Int, initialState: Int) {
this.originalText = buffer
this.bufferStart = start
this.bufferEnd = end
baseLexer.reset(buffer, start, end, initialState)
type = advanceBase()
tokenStart = baseLexer.tokenStart
}
companion object {
private val TOKENS_TO_MERGE = setOf(
MarkdownTokenTypes.TEXT,
MarkdownTokenTypes.WHITE_SPACE,
MarkdownTokenTypes.CODE_LINE,
MarkdownTokenTypes.LINK_ID,
MarkdownTokenTypes.LINK_TITLE,
MarkdownTokenTypes.URL,
MarkdownTokenTypes.AUTOLINK,
MarkdownTokenTypes.EMAIL_AUTOLINK,
MarkdownTokenTypes.BAD_CHARACTER)
}
}
| apache-2.0 | e121f09e8ee4f3aa50d38224eea343ab | 27.193182 | 84 | 0.583636 | 4.798839 | false | false | false | false |
joan-domingo/Podcasts-RAC1-Android | app/src/rac1/java/cat/xojan/random1/domain/model/ProgramData.kt | 1 | 1860 | package cat.xojan.random1.domain.model
import com.squareup.moshi.Json
class ProgramData(
@Json(name = "result") val programs: List<ProgramRac1> = listOf()
): ProgramInterface {
override fun toPrograms(): List<Program> {
return programs
.filter { p -> p.active }
.map { p ->
Program(
p.id,
p.title,
p.images?.smallImageUrl,
p.images?.bigImageUrl,
toSections(p.sectionsRac1, p.id, p.images?.smallImageUrl)
)
}
}
private fun toSections(sectionsRac1: List<SectionRac1>, programId: String, imageUrl: String?)
: List<Section> {
return sectionsRac1
.filter { s -> s.active }
.filter { s -> s.type == "SECTION"}
.map { s ->
Section(
s.id,
s.title,
imageUrl,
programId
)
}
}
}
class ProgramRac1(
@Json(name = "id") val id: String,
@Json(name = "title") var title: String? = null,
@Json(name = "sections") var sectionsRac1: List<SectionRac1> = listOf(),
@Json(name = "images") var images: ImagesRac1? = null,
@Json(name = "active") val active: Boolean
)
class ImagesRac1(
@Json(name = "person-small") val smallImageUrl: String? = null,
@Json(name = "app") val bigImageUrl: String? = null
)
class SectionRac1(
@Json(name = "id") val id: String,
@Json(name = "title") val title: String? = null,
@Json(name = "active") val active: Boolean,
@Json(name = "type") var type: String
)
enum class SectionTypeRac1 {
HOUR,
SECTION,
GENERIC
} | mit | 467292f7510b320f580efd1b415af76b | 28.539683 | 97 | 0.496237 | 3.974359 | false | false | false | false |
ShaneHD/Miscellaneous-Small-Projects | Misc Small Projects/src/com/github/shanehd/CsgoSettingsCopier.kt | 1 | 2043 | package com.github.shanehd
import com.github.shanehd.utilities.kotlin.quote
import java.io.File
private const val CSGO_CFG_LOCATION = "730/local/cfg/"
/**
* @author https://www.github.com/ShaneHD
* Created by Shane on 08/10/2016.
*/
fun main(args: Array<String>) {
if(args.size < 2)
throw IllegalArgumentException("Missing required arguments!")
val steamDir = File(args[0])
val user = args[1]
var blacklist: Array<String?> = arrayOf()
if(args.size > 2) {
blacklist = kotlin.arrayOfNulls<String>(args.size - 2)
for(i in 0..args.size - 3) {
blacklist[i] = args[i + 2]
}
}
copy(steamDir, user, *blacklist)
print("Done!")
}
private fun print(line: String) {
println("> $line")
}
private fun iprint(line: String) {
print(" $line")
}
private fun copy(steam: File, from: String, vararg blacklist: String?) {
try {
print("Attempting to copy settings from user ${from.quote}")
val base = File(steam, "userdata/")
val copyFrom = File(base, "$from/$CSGO_CFG_LOCATION")
for(user in base.listFiles()) {
if(!user.isDirectory || blacklist.contains(user.name) || user.name == from) {
print("Skipping ${user.name.quote}")
continue
}
print("Copying files to user ${user.name.quote}")
for(file in copyFrom.listFiles()) {
if(file.isDirectory)
continue
try {
val new = File(user, "$CSGO_CFG_LOCATION/${file.name}")
file.copyTo(new, true)
if(!file.canWrite())
new.setReadOnly()
iprint("Copied file ${file.quote}")
} catch(e: Throwable) {
e.printStackTrace()
iprint("Failed...")
}
}
print("Finished with this user")
}
} catch(e: Throwable) {
e.printStackTrace()
}
} | mpl-2.0 | 666daa8d9e61dc6a25b37c1784ac0320 | 25.205128 | 89 | 0.531082 | 4.045545 | false | false | false | false |
rock3r/detekt | detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/UtilityClassWithPublicConstructorSpec.kt | 2 | 2146 | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Finding
import io.gitlab.arturbosch.detekt.rules.Case
import io.gitlab.arturbosch.detekt.test.lint
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class UtilityClassWithPublicConstructorSpec : Spek({
val subject by memoized { UtilityClassWithPublicConstructor(Config.empty) }
describe("UtilityClassWithPublicConstructor rule") {
context("several UtilityClassWithPublicConstructor rule violations") {
lateinit var findings: List<Finding>
beforeEachTest {
findings = subject.lint(Case.UtilityClassesPositive.path())
}
it("reports utility classes with a public constructor") {
assertThat(findings).hasSize(6)
}
it("reports utility classes which are marked as open") {
val count = findings.count { it.message.contains("The utility class OpenUtilityClass should be final.") }
assertThat(count).isEqualTo(1)
}
}
context("several classes which adhere to the UtilityClassWithPublicConstructor rule") {
it("does not report given classes") {
val findings = subject.lint(Case.UtilityClassesNegative.path())
assertThat(findings).isEmpty()
}
}
context("annotations class") {
it("should not get triggered for utility class") {
val code = """
@Retention(AnnotationRetention.SOURCE)
@StringDef(
Gender.MALE,
Gender.FEMALE
)
annotation class Gender {
companion object {
const val MALE = "male"
const val FEMALE = "female"
}
}
"""
assertThat(subject.lint(code)).isEmpty()
}
}
}
})
| apache-2.0 | a8ef3f65e071dfdae2836cdc30013308 | 33.612903 | 121 | 0.591333 | 5.259804 | false | false | false | false |
bertilxi/Chilly_Willy_Delivery | mobile/app/src/main/java/dam/isi/frsf/utn/edu/ar/delivery/adapter/LocateOrderAdapter.kt | 1 | 1249 | package dam.isi.frsf.utn.edu.ar.delivery.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import dam.isi.frsf.utn.edu.ar.delivery.R
import dam.isi.frsf.utn.edu.ar.delivery.model.Order
class LocateOrderAdapter(context: Context, orders: List<Order>) : ArrayAdapter<Order>(context, R.layout.listview_row_order_item, orders) {
var inflater: LayoutInflater = LayoutInflater.from(context)
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var row = convertView
if (row == null) {
row = inflater.inflate(R.layout.listview_row_order, parent, false)
}
var holder: OrderHolder? = row!!.tag as OrderHolder?
if (holder == null) {
holder = OrderHolder(row)
row.tag = holder
}
holder.dateTextView!!.text = getItem(position).requestTime
return row
}
internal inner class OrderHolder(row: View) {
var dateTextView: TextView? = null
init {
this.dateTextView = row.findViewById(R.id.textview_order_date) as TextView
}
}
} | mit | af81f71662346e165cb1927c56bab2a7 | 28.761905 | 138 | 0.677342 | 3.843077 | false | false | false | false |
rock3r/detekt | detekt-generator/src/main/kotlin/io/gitlab/arturbosch/detekt/generator/collection/DetektCollector.kt | 1 | 2383 | package io.gitlab.arturbosch.detekt.generator.collection
import io.gitlab.arturbosch.detekt.generator.collection.exception.InvalidDocumentationException
import io.gitlab.arturbosch.detekt.generator.printer.rulesetpage.RuleSetPage
import org.jetbrains.kotlin.psi.KtFile
class DetektCollector : Collector<RuleSetPage> {
private val ruleSetProviderCollector = RuleSetProviderCollector()
private val ruleCollector = RuleCollector()
private val multiRuleCollector = MultiRuleCollector()
private val collectors = listOf(
ruleSetProviderCollector,
multiRuleCollector,
ruleCollector
)
override val items: List<RuleSetPage>
get() = buildRuleSetPages()
private fun buildRuleSetPages(): List<RuleSetPage> {
val multiRules = multiRuleCollector.items
val rules = resolveMultiRuleRelations(ruleCollector.items, multiRules)
val multiRuleNameToRules = multiRules.associateBy({ it.name }, { it.rules })
val ruleSets = ruleSetProviderCollector.items
return ruleSets.map { ruleSet ->
val consolidatedRules = ruleSet.rules
.flatMap { ruleName -> multiRuleNameToRules[ruleName] ?: listOf(ruleName) }
.map { rules.findRuleByName(it) }
.sortedBy { rule -> rule.name }
consolidatedRules.resolveParentRule(rules)
RuleSetPage(ruleSet, consolidatedRules)
}
}
private fun resolveMultiRuleRelations(
rules: List<Rule>,
multiRules: List<MultiRule>
): List<Rule> = rules.onEach { rule ->
multiRules.find { rule.name in it }?.apply { rule.inMultiRule = this.name }
}
private fun List<Rule>.findRuleByName(ruleName: String): Rule {
return find { it.name == ruleName }
?: throw InvalidDocumentationException("Rule $ruleName was specified in a provider but it was not defined.")
}
private fun List<Rule>.resolveParentRule(rules: List<Rule>) {
this.filter { it.debt.isEmpty() && it.severity.isEmpty() }
.forEach {
val parentRule = rules.findRuleByName(it.parent)
it.debt = parentRule.debt
it.severity = parentRule.severity
}
}
override fun visit(file: KtFile) {
collectors.forEach {
it.visit(file)
}
}
}
| apache-2.0 | 44687404a1328b20edb84dddbc8ad9bd | 36.234375 | 120 | 0.655896 | 4.609284 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/map/components/PinsMapComponent.kt | 1 | 4549 | package de.westnordost.streetcomplete.map.components
import android.content.Context
import android.graphics.PointF
import android.graphics.drawable.BitmapDrawable
import androidx.annotation.DrawableRes
import com.mapzen.tangram.MapData
import com.mapzen.tangram.geometry.Point
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.mapdata.LatLon
import de.westnordost.streetcomplete.ktx.getBitmapDrawable
import de.westnordost.streetcomplete.ktx.toDp
import de.westnordost.streetcomplete.map.tangram.KtMapController
import de.westnordost.streetcomplete.map.tangram.Marker
import de.westnordost.streetcomplete.map.tangram.toLngLat
/** Takes care of displaying pins on the map and displaying pins as selected */
class PinsMapComponent(private val ctx: Context, private val ctrl: KtMapController) {
private val pinsLayer: MapData
private val selectedPinsLayer: MapData
private val pinSelectionMarkers: MutableList<Marker> = mutableListOf()
private val selectionDrawable: BitmapDrawable
private val selectionDrawableSize: PointF
init {
selectionDrawable = ctx.resources.getBitmapDrawable(R.drawable.pin_selection_ring)
selectionDrawableSize = PointF(
selectionDrawable.intrinsicWidth.toFloat().toDp(ctx),
selectionDrawable.intrinsicHeight.toFloat().toDp(ctx)
)
pinsLayer = ctrl.addDataLayer(PINS_LAYER)
selectedPinsLayer = ctrl.addDataLayer(SELECTED_PINS_LAYER)
}
fun clear() {
clearPins()
clearSelectedPins()
}
/* ------------------------------------------ Pins ----------------------------------------- */
/** Show given pins. Previously shown pins are replaced with these. */
fun showPins(pins: Collection<Pin>) {
pinsLayer.setFeatures(pins.map { pin ->
Point(pin.position.toLngLat(), mapOf(
"type" to "point",
"kind" to pin.iconName,
"importance" to pin.importance.toString()
) + pin.properties)
})
}
/** Hide pins */
private fun clearPins() {
pinsLayer.clear()
}
/* ------------------------------------- Selected pins ------------------------------------- */
/** Show selected pins with the given icon at the given positions. "Selected pins" are not
* related to pins, they are just visuals that are displayed on top of the normal pins and look
* highlighted/selected. */
fun showSelectedPins(@DrawableRes iconResId: Int, pinPositions: Collection<LatLon>) {
putSelectedPins(iconResId, pinPositions)
showPinSelectionMarkers(pinPositions)
}
/** Clear the display of any selected pins */
fun clearSelectedPins() {
selectedPinsLayer.clear()
clearPinSelectionMarkers()
}
private fun putSelectedPins(@DrawableRes iconResId: Int, pinPositions: Collection<LatLon>) {
val points = pinPositions.map { position ->
Point(position.toLngLat(), mapOf(
"type" to "point",
"kind" to ctx.resources.getResourceEntryName(iconResId)
))
}
selectedPinsLayer.setFeatures(points)
}
private fun showPinSelectionMarkers(positions: Collection<LatLon>) {
clearPinSelectionMarkers()
for (position in positions) {
pinSelectionMarkers.add(createPinSelectionMarker(position))
}
}
private fun clearPinSelectionMarkers() {
pinSelectionMarkers.forEach { ctrl.removeMarker(it) }
pinSelectionMarkers.clear()
}
private fun createPinSelectionMarker(pos: LatLon): Marker =
ctrl.addMarker().also {
it.setStylingFromString("""
{
style: 'pin-selection',
color: 'white',
size: [${selectionDrawableSize.x}px, ${selectionDrawableSize.y}px],
flat: false,
collide: false,
offset: ['0px', '-38px']
}""".trimIndent())
it.setDrawable(selectionDrawable)
it.isVisible = true
it.setPoint(pos)
}
companion object {
// see streetcomplete.yaml for the definitions of the below layers
private const val PINS_LAYER = "streetcomplete_pins"
private const val SELECTED_PINS_LAYER = "streetcomplete_selected_pins"
}
}
data class Pin(
val position: LatLon,
val iconName: String,
val properties: Map<String, String> = emptyMap(),
val importance: Int = 0
)
| gpl-3.0 | aa5196d6392c74948885e502fd7250ae | 34.539063 | 100 | 0.640361 | 4.758368 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/entities/RefreshableResource.kt | 1 | 1927 | package com.boardgamegeek.entities
import android.app.Application
import androidx.annotation.StringRes
import com.boardgamegeek.R
import retrofit2.HttpException
import java.net.SocketTimeoutException
enum class Status {
SUCCESS,
ERROR,
REFRESHING
}
data class RefreshableResource<out T>(val status: Status, val data: T?, val message: String = "") {
companion object {
fun <T> success(data: T?): RefreshableResource<T> {
return RefreshableResource(Status.SUCCESS, data)
}
fun <T> error(msg: String, data: T? = null): RefreshableResource<T> {
return RefreshableResource(Status.ERROR, data, msg)
}
fun <T> error(t: Throwable?, application: Application, data: T? = null): RefreshableResource<T> {
val message = when (t) {
is HttpException -> {
@StringRes val resId: Int = when {
t.code() >= 500 -> R.string.msg_sync_response_500
t.code() == 429 -> R.string.msg_sync_response_429
t.code() == 202 -> R.string.msg_sync_response_202
else -> R.string.msg_sync_error_http_code
}
application.getString(resId, t.code().toString())
}
is SocketTimeoutException -> application.getString(R.string.msg_sync_error_timeout)
else -> t?.localizedMessage ?: application.getString(R.string.msg_sync_error)
}
return RefreshableResource(Status.ERROR, data, message)
}
fun <T> refreshing(data: T? = null): RefreshableResource<T> {
return RefreshableResource(Status.REFRESHING, data)
}
fun <T> map(source: RefreshableResource<*>, data: T? = null): RefreshableResource<T> {
return RefreshableResource(source.status, data, source.message)
}
}
}
| gpl-3.0 | e61d4e02d7a0a604d7669d6d039722d9 | 37.54 | 105 | 0.591593 | 4.369615 | false | false | false | false |
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/ui/person/PersonFragment.kt | 1 | 10608 | /*
* Copyright (C) 2016 Simon Vig Therkildsen
*
* 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.simonvt.cathode.ui.person
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import butterknife.BindView
import butterknife.OnClick
import net.simonvt.cathode.R
import net.simonvt.cathode.api.enumeration.Department
import net.simonvt.cathode.api.enumeration.ItemType
import net.simonvt.cathode.api.util.TraktUtils
import net.simonvt.cathode.common.ui.fragment.RefreshableAppBarFragment
import net.simonvt.cathode.common.util.Ids
import net.simonvt.cathode.common.util.Intents
import net.simonvt.cathode.common.util.guava.Preconditions
import net.simonvt.cathode.common.widget.RemoteImageView
import net.simonvt.cathode.ui.CathodeViewModelFactory
import net.simonvt.cathode.ui.LibraryType
import net.simonvt.cathode.ui.NavigationListener
import javax.inject.Inject
class PersonFragment @Inject constructor(
private val viewModelFactory: CathodeViewModelFactory
) : RefreshableAppBarFragment() {
private var personId: Long = -1L
private lateinit var viewModel: PersonViewModel
private var person: Person? = null
private var itemCount: Int = 0
@BindView(R.id.headshot)
@JvmField
var headshot: RemoteImageView? = null
@BindView(R.id.bornTitle)
@JvmField
var bornTitle: View? = null
@BindView(R.id.birthday)
@JvmField
var birthday: TextView? = null
@BindView(R.id.birthplace)
@JvmField
var birthplace: TextView? = null
@BindView(R.id.deathTitle)
@JvmField
var deathTitle: View? = null
@BindView(R.id.death)
@JvmField
var death: TextView? = null
@BindView(R.id.biography)
@JvmField
var biography: TextView? = null
@BindView(R.id.cast_header)
@JvmField
var castHeader: LinearLayout? = null
@BindView(R.id.cast_items)
@JvmField
var castItems: LinearLayout? = null
@BindView(R.id.production_header)
@JvmField
var productionHeader: LinearLayout? = null
@BindView(R.id.production_items)
@JvmField
var productionItems: LinearLayout? = null
@BindView(R.id.art_header)
@JvmField
var artHeader: LinearLayout? = null
@BindView(R.id.art_items)
@JvmField
var artItems: LinearLayout? = null
@BindView(R.id.crew_header)
@JvmField
var crewHeader: LinearLayout? = null
@BindView(R.id.crew_items)
@JvmField
var crewItems: LinearLayout? = null
@BindView(R.id.costume_makeup_header)
@JvmField
var costumeMakeupHeader: LinearLayout? = null
@BindView(R.id.costume_makeup_items)
@JvmField
var costumeMakeupItems: LinearLayout? = null
@BindView(R.id.directing_header)
@JvmField
var directingHeader: LinearLayout? = null
@BindView(R.id.directing_items)
@JvmField
var directingItems: LinearLayout? = null
@BindView(R.id.writing_header)
@JvmField
var writingHeader: LinearLayout? = null
@BindView(R.id.writing_items)
@JvmField
var writingItems: LinearLayout? = null
@BindView(R.id.sound_header)
@JvmField
var soundHeader: LinearLayout? = null
@BindView(R.id.sound_items)
@JvmField
var soundItems: LinearLayout? = null
@BindView(R.id.camera_header)
@JvmField
var cameraHeader: LinearLayout? = null
@BindView(R.id.camera_items)
@JvmField
var cameraItems: LinearLayout? = null
@BindView(R.id.viewOnTrakt)
@JvmField
var viewOnTrakt: TextView? = null
lateinit var navigationListener: NavigationListener
override fun onAttach(context: Context) {
super.onAttach(context)
navigationListener = requireActivity() as NavigationListener
}
override fun onCreate(inState: Bundle?) {
super.onCreate(inState)
personId = requireArguments().getLong(ARG_PERSON_ID)
itemCount = resources.getInteger(R.integer.personCreditColumns)
viewModel = ViewModelProviders.of(this, viewModelFactory).get(PersonViewModel::class.java)
viewModel.setPersonId(personId)
viewModel.loading.observe(this, Observer { loading -> setRefreshing(loading) })
viewModel.person.observe(this, Observer { person -> updateView(person) })
}
override fun onRefresh() {
viewModel.refresh()
}
override fun createView(inflater: LayoutInflater, container: ViewGroup?, inState: Bundle?): View {
return inflater.inflate(R.layout.fragment_person, container, false)
}
override fun onViewCreated(view: View, inState: Bundle?) {
super.onViewCreated(view, inState)
val linkDrawable = VectorDrawableCompat.create(resources, R.drawable.ic_link_black_24dp, null)
viewOnTrakt!!.setCompoundDrawablesWithIntrinsicBounds(linkDrawable, null, null, null)
updateView(person)
}
@OnClick(R.id.cast_header)
fun onDisplayCastCredits() {
navigationListener.onDisplayPersonCredit(personId, Department.CAST)
}
@OnClick(R.id.production_header)
fun onDisplayProductionCredits() {
navigationListener.onDisplayPersonCredit(personId, Department.PRODUCTION)
}
@OnClick(R.id.art_header)
fun onDisplayArtCredits() {
navigationListener.onDisplayPersonCredit(personId, Department.ART)
}
@OnClick(R.id.crew_header)
fun onDisplayCrewCredits() {
navigationListener.onDisplayPersonCredit(personId, Department.CREW)
}
@OnClick(R.id.costume_makeup_header)
fun onDisplayCostumeMakeUpCredits() {
navigationListener.onDisplayPersonCredit(personId, Department.COSTUME_AND_MAKEUP)
}
@OnClick(R.id.directing_header)
fun onDisplayDirectingCredits() {
navigationListener.onDisplayPersonCredit(personId, Department.DIRECTING)
}
@OnClick(R.id.writing_header)
fun onDisplayWritingCredits() {
navigationListener.onDisplayPersonCredit(personId, Department.WRITING)
}
@OnClick(R.id.sound_header)
fun onDisplaySoundCredits() {
navigationListener.onDisplayPersonCredit(personId, Department.SOUND)
}
@OnClick(R.id.camera_header)
fun onDisplayCameraCredits() {
navigationListener.onDisplayPersonCredit(personId, Department.CAMERA)
}
private fun updateView(person: Person?) {
this.person = person
if (person != null && view != null) {
setTitle(person.name)
setBackdrop(person.screenshot)
headshot!!.setImage(person.headshot)
if (!TextUtils.isEmpty(person.birthday)) {
bornTitle!!.visibility = View.VISIBLE
birthday!!.visibility = View.VISIBLE
birthplace!!.visibility = View.VISIBLE
birthday!!.text = person.birthday
birthplace!!.text = person.birthplace
} else {
bornTitle!!.visibility = View.GONE
birthday!!.visibility = View.GONE
birthplace!!.visibility = View.GONE
}
if (!TextUtils.isEmpty(person.death)) {
deathTitle!!.visibility = View.VISIBLE
death!!.visibility = View.VISIBLE
death!!.text = person.death
} else {
deathTitle!!.visibility = View.GONE
death!!.visibility = View.GONE
}
biography!!.text = person.biography
updateItems(castHeader, castItems!!, person.credits.cast)
updateItems(productionHeader, productionItems!!, person.credits.production)
updateItems(artHeader, artItems!!, person.credits.art)
updateItems(crewHeader, crewItems!!, person.credits.crew)
updateItems(
costumeMakeupHeader, costumeMakeupItems!!,
person.credits.costumeAndMakeUp
)
updateItems(directingHeader, directingItems!!, person.credits.directing)
updateItems(writingHeader, writingItems!!, person.credits.writing)
updateItems(soundHeader, soundItems!!, person.credits.sound)
updateItems(cameraHeader, cameraItems!!, person.credits.camera)
viewOnTrakt!!.setOnClickListener {
Intents.openUrl(
requireContext(),
TraktUtils.getTraktPersonUrl(person.traktId)
)
}
}
}
private fun updateItems(header: View?, items: ViewGroup, credits: List<PersonCredit>?) {
items.removeAllViews()
val size = credits?.size ?: 0
if (size > 0) {
header!!.visibility = View.VISIBLE
items.visibility = View.VISIBLE
var i = 0
while (i < size && i < itemCount) {
val credit = credits!![i]
val view =
LayoutInflater.from(requireContext()).inflate(R.layout.person_item_credit, items, false)
val poster = view.findViewById<RemoteImageView>(R.id.poster)
val title = view.findViewById<TextView>(R.id.title)
val job = view.findViewById<TextView>(R.id.job)
poster.setImage(credit.getPoster())
title.text = credit.getTitle()
if (credit.getJob() != null) {
job.text = credit.getJob()
} else {
job.text = credit.getCharacter()
}
view.setOnClickListener {
if (credit.getItemType() === ItemType.SHOW) {
navigationListener.onDisplayShow(
credit.getItemId(),
credit.getTitle(),
credit.getOverview(),
LibraryType.WATCHED
)
} else {
navigationListener.onDisplayMovie(
credit.getItemId(),
credit.getTitle(),
credit.getOverview()
)
}
}
items.addView(view)
i++
}
} else {
header!!.visibility = View.GONE
items.visibility = View.GONE
}
}
companion object {
private const val TAG = "net.simonvt.cathode.ui.person.PersonFragment"
private const val ARG_PERSON_ID = "net.simonvt.cathode.ui.person.PersonFragment.personId"
@JvmStatic
fun getTag(personId: Long): String {
return TAG + "/" + personId + "/" + Ids.newId()
}
@JvmStatic
fun getArgs(personId: Long): Bundle {
Preconditions.checkArgument(personId >= 0, "personId must be >= 0")
val args = Bundle()
args.putLong(ARG_PERSON_ID, personId)
return args
}
}
}
| apache-2.0 | ffbaed687b0f6b036bc3f9afb5fa92a9 | 29.136364 | 100 | 0.707202 | 4.166536 | false | false | false | false |
jeffersonvenancio/BarzingaNow | android/app/src/main/java/com/barzinga/view/adapter/ProductCartAdapter.kt | 1 | 3093 | package com.barzinga.view.adapter
import android.content.Context
import android.databinding.DataBindingUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.animation.AlphaAnimation
import com.barzinga.R
import com.barzinga.databinding.ItemCartProductBinding
import com.barzinga.model.Product
import com.barzinga.view.adapter.ProductCartAdapter.ProductViewHolder
import com.barzinga.viewmodel.ProductListViewModel
import com.barzinga.viewmodel.ProductViewModel
import com.bumptech.glide.Glide
class ProductCartAdapter(val context: Context, products: ArrayList<Product>, val listener: ProductListViewModel.ProductsListener): RecyclerView.Adapter<ProductViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ProductViewHolder {
val binding = DataBindingUtil.inflate<ItemCartProductBinding>(
LayoutInflater.from(parent?.context),
R.layout.item_cart_product,
parent,
false
)
return ProductViewHolder(binding)
}
override fun getItemCount(): Int = mProducts.size
override fun onBindViewHolder(holder: ProductViewHolder?, position: Int) {
val binding = holder?.binding
val product = mProducts[position]
val viewModel = product.let { ProductViewModel(it) }
binding?.viewModel = viewModel
Glide.with(context).load(binding?.viewModel?.product?.image_url).into(binding?.mProductImage)
}
companion object {
var mProducts = ArrayList<Product>()
var mListener: ProductListViewModel.ProductsListener? = null
}
init {
mProducts.clear()
mProducts.addAll(products)
mListener = listener
}
inner class ProductViewHolder(val binding: ItemCartProductBinding) : RecyclerView.ViewHolder(binding.root) {
var animation1 = AlphaAnimation(0.2f, 1.0f)
init {
binding.deleteButton.setOnClickListener({
binding.deleteButton.startAnimation(animation1)
mProducts.removeAt(position)
updateList(position)
mListener?.onProductsQuantityChanged()
})
}
}
fun updateList(position: Int) {
notifyItemRemoved(position)
}
fun getChosenProducts(): List<Product> {
val extraProducts = ArrayList<Product>()
for (product in mProducts) {
if ((product.quantityOrdered ?: 0) > 0) {
for (i in 0 until (product.quantityOrdered ?: 0)) {
extraProducts.add(product)
}
}
}
return extraProducts
}
fun getCurrentOrderPrice(): Double {
val products = getChosenProducts()
var currentOrderPrice = 0.0
for (product in products) {
product.price?.let { currentOrderPrice = currentOrderPrice.plus(it) }
}
return currentOrderPrice
}
fun getCartProducts(): ArrayList<Product> {
return mProducts
}
} | apache-2.0 | 34bc1bd25c345b9dc854aad03d21d37e | 31.229167 | 175 | 0.667637 | 4.925159 | false | false | false | false |
actorapp/actor-bots | actor-bots/src/main/java/im/actor/bots/framework/MagicBotEntities.kt | 1 | 6294 | package im.actor.bots.framework
import im.actor.bots.BotMessages
import org.json.JSONObject
//
// Magic Bot Messages
//
public abstract class MagicBotMessage(val peer: OutPeer, val sender: BotMessages.UserOutPeer?,
val rid: Long) {
}
public class MagicBotTextMessage(peer: OutPeer, sender: BotMessages.UserOutPeer?, rid: Long,
val text: String) : MagicBotMessage(peer, sender, rid) {
var command: String? = null
var commandArgs: String? = null
}
public class MagicBotJsonMessage(peer: OutPeer, sender: BotMessages.UserOutPeer?, rid: Long,
val json: JSONObject) : MagicBotMessage(peer, sender, rid) {
}
public class MagicBotDocMessage(peer: OutPeer, sender: BotMessages.UserOutPeer?, rid: Long,
val doc: BotMessages.DocumentMessage) : MagicBotMessage(peer, sender, rid) {
}
public class MagicBotStickerMessage(peer: OutPeer, sender: BotMessages.UserOutPeer?, rid: Long,
val sticker: BotMessages.StickerMessage) : MagicBotMessage(peer, sender, rid) {
}
//
// User Extensions
//
var BotMessages.User.isEnterprise: Boolean
get() {
return this.emailContactRecords.size > 0
}
private set(v) {
}
//
// Peers and OutPeers
//
public fun peerFromJson(json: JSONObject): Peer {
val type = json.getString("type")
when (type) {
"group" -> {
return Peer(PeerType.GROUP, json.getInt("id"))
}
"private" -> {
return Peer(PeerType.PRIVATE, json.getInt("id"))
}
else -> {
throw RuntimeException("Unknown type $type")
}
}
}
public class Peer(val type: PeerType, val id: Int) {
var isGroup: Boolean
get() {
return type == PeerType.GROUP
}
private set(v) {
}
var isPrivate: Boolean
get() {
return type == PeerType.PRIVATE
}
private set(v) {
}
fun toJson(): JSONObject {
val res = JSONObject()
res.put("id", id)
when (type) {
PeerType.GROUP -> {
res.put("type", "group")
}
PeerType.PRIVATE -> {
res.put("type", "private")
}
}
return res
}
fun toKit(): BotMessages.Peer {
when (type) {
PeerType.PRIVATE -> {
return BotMessages.UserPeer(id)
}
PeerType.GROUP -> {
return BotMessages.GroupPeer(id)
}
}
}
fun toUniqueId(): String {
when (type) {
PeerType.PRIVATE -> {
return "PRIVATE_$id"
}
PeerType.GROUP -> {
return "GROUP_$id"
}
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as Peer
if (type != other.type) return false
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
var result = type.hashCode()
result += 31 * result + id
return result
}
}
public fun outPeerFromJson(json: JSONObject): OutPeer {
val type = json.getString("type")
when (type) {
"group" -> {
return OutPeer(PeerType.GROUP, json.getInt("id"), json.getString("accessHash").toLong())
}
"private" -> {
return OutPeer(PeerType.PRIVATE, json.getInt("id"), json.getString("accessHash").toLong())
}
else -> {
throw RuntimeException("Unknown type $type")
}
}
}
public fun BotMessages.OutPeer.toUsable(): OutPeer {
if (this is BotMessages.UserOutPeer) {
return OutPeer(PeerType.PRIVATE, id(), accessHash())
} else if (this is BotMessages.GroupOutPeer) {
return OutPeer(PeerType.GROUP, id(), accessHash())
} else {
throw RuntimeException("Unknown type")
}
}
public class OutPeer(val type: PeerType, val id: Int, val accessHash: Long) {
var isGroup: Boolean
get() {
return type == PeerType.GROUP
}
private set(v) {
}
var isPrivate: Boolean
get() {
return type == PeerType.PRIVATE
}
private set(v) {
}
fun toJson(): JSONObject {
val res = JSONObject()
res.put("id", id)
res.put("accessHash", "$accessHash")
when (type) {
PeerType.GROUP -> {
res.put("type", "group")
}
PeerType.PRIVATE -> {
res.put("type", "private")
}
}
return res
}
fun toPeer(): Peer {
return Peer(type, id)
}
fun toKit(): BotMessages.OutPeer {
when (type) {
PeerType.PRIVATE -> {
return BotMessages.UserOutPeer(id, accessHash)
}
PeerType.GROUP -> {
return BotMessages.GroupOutPeer(id, accessHash)
}
}
}
fun toUniqueId(): String {
when (type) {
PeerType.PRIVATE -> {
return "PRIVATE_$id"
}
PeerType.GROUP -> {
return "GROUP_$id"
}
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as OutPeer
if (type != other.type) return false
if (id != other.id) return false
if (accessHash != other.accessHash) return false
return true
}
override fun hashCode(): Int {
var result = type.hashCode()
result += 31 * result + id
result += 31 * result + accessHash.hashCode()
return result
}
}
public enum class PeerType(val id: Int) {
PRIVATE(0), GROUP(1)
}
public fun BotMessages.Peer.toUsable(): Peer {
if (this is BotMessages.UserPeer) {
return Peer(PeerType.PRIVATE, id())
} else if (this is BotMessages.GroupPeer) {
return Peer(PeerType.GROUP, id())
} else {
throw RuntimeException("Unknown type")
}
}
| apache-2.0 | 9ee5586de90534dcbbe7dab8706de1ad | 23.779528 | 115 | 0.530505 | 4.215673 | false | false | false | false |
hartwigmedical/hmftools | cider/src/main/java/com/hartwig/hmftools/cider/layout/LayoutTreeBuilder.kt | 1 | 2285 | package com.hartwig.hmftools.cider.layout
import org.apache.logging.log4j.LogManager
import java.util.*
import kotlin.collections.ArrayList
/*
class LayoutTreeBuilder(inputReads: List<LayoutTree.Read>,
minBaseQuality: Int,
minOverlapBases: Int,
minBaseHighQualCount: Int)
{
val minBaseQuality: Byte = minBaseQuality.toByte()
val minOverlapBases: Int = minOverlapBases
val minBaseHighQualCount: Int = minBaseHighQualCount
val inputReadList: List<LayoutTree.Read>
init
{
val readDataMutableList = ArrayList<LayoutTree.Read>()
readDataMutableList.addAll(inputReads)
// we want to sort them by the end of the sequence in the layout
// left to right, i.e starting from the root
readDataMutableList.sortWith(
Comparator.comparingInt({ r: LayoutTree.Read -> r.layoutPosition + r.sequence.length })
.thenComparingDouble({ r: LayoutTree.Read -> r.baseQualities.average() }) // handle the highest quality ones first
.thenComparingInt({ r: LayoutTree.Read -> r.layoutPosition })
.thenComparing({ r: LayoutTree.Read -> r.readKey.readName }) // just the final catch all
)
inputReadList = readDataMutableList
}
fun build(): LayoutTree
{
sLogger.info("building layout tree from {} reads", inputReadList.size)
val layoutTree = LayoutTree(minBaseQuality, minOverlapBases)
val retryReads = ArrayList<LayoutTree.Read>()
// go through the read data list, and add one by one to the list of clusters
// if there are multiple clusters that matches, we choose the highest one
for (read in inputReadList)
{
// add it to the layout tree
if (!layoutTree.tryAddRead(read))
{
retryReads.add(read)
}
}
for (read in retryReads)
{
layoutTree.tryAddRead(read)
}
sLogger.info("layout tree complete, num levels: {}", layoutTree.numLevels)
return layoutTree
}
companion object
{
private val sLogger = LogManager.getLogger(LayoutTreeBuilder::class.java)
}
}
*/ | gpl-3.0 | ea707a3e65b34899beb3d96c8295e496 | 30.315068 | 134 | 0.623632 | 4.498031 | false | false | false | false |
GeoffreyMetais/vlc-android | application/moviepedia/src/main/java/org/videolan/moviepedia/ui/MediaScrapingActivity.kt | 1 | 4253 | /*
* ************************************************************************
* NextActivity.kt
* *************************************************************************
* Copyright © 2019 VLC authors and VideoLAN
* Author: Nicolas POMEPUY
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* **************************************************************************
*
*
*/
package org.videolan.moviepedia.ui
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.moviepedia.R
import org.videolan.moviepedia.databinding.MoviepediaActivityBinding
import org.videolan.moviepedia.models.resolver.ResolverMedia
import org.videolan.moviepedia.viewmodel.MediaScrapingModel
import org.videolan.resources.MOVIEPEDIA_MEDIA
import org.videolan.vlc.gui.BaseActivity
import org.videolan.vlc.gui.helpers.UiTools
import org.videolan.vlc.gui.helpers.applyTheme
open class MediaScrapingActivity : BaseActivity(), TextWatcher, TextView.OnEditorActionListener {
private lateinit var mediaScrapingResultAdapter: MediaScrapingResultAdapter
private lateinit var viewModel: MediaScrapingModel
private lateinit var media: MediaWrapper
private lateinit var binding: MoviepediaActivityBinding
private val clickHandler = ClickHandler()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
applyTheme()
val intent = intent
binding = DataBindingUtil.setContentView(this, R.layout.moviepedia_activity)
binding.handler = clickHandler
mediaScrapingResultAdapter = MediaScrapingResultAdapter(layoutInflater)
mediaScrapingResultAdapter.clickHandler = clickHandler
binding.nextResults.adapter = mediaScrapingResultAdapter
binding.nextResults.layoutManager = GridLayoutManager(this, 2)
media = intent.getParcelableExtra(MOVIEPEDIA_MEDIA)
binding.searchEditText.addTextChangedListener(this)
binding.searchEditText.setOnEditorActionListener(this)
viewModel = ViewModelProviders.of(this).get(media.uri.path
?: "", MediaScrapingModel::class.java)
viewModel.apiResult.observe(this, Observer {
mediaScrapingResultAdapter.setItems(it.getAllResults())
})
viewModel.search(media.uri)
binding.searchEditText.setText(media.title)
}
private fun performSearh(query: String) {
viewModel.search(query)
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable?) {}
override fun onEditorAction(v: TextView, actionId: Int, event: KeyEvent): Boolean {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
UiTools.setKeyboardVisibility(binding.root, false)
performSearh(v.text.toString())
return true
}
return false
}
inner class ClickHandler {
fun onBack(v: View) {
finish()
}
fun onItemClick(item: ResolverMedia) {
//todo
finish()
}
}
}
| gpl-2.0 | 833658265624dab33b72b05ecc6ae456 | 36.964286 | 97 | 0.699436 | 4.949942 | false | false | false | false |
TeamAmaze/AmazeFileManager | app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/compress/AbstractCommonsArchiveHelperCallable.kt | 1 | 4164 | /*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager 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.amaze.filemanager.asynchronous.asynctasks.compress
import android.content.Context
import com.amaze.filemanager.R
import com.amaze.filemanager.adapters.data.CompressedObjectParcelable
import com.amaze.filemanager.application.AppConfig
import com.amaze.filemanager.filesystem.compressed.CompressedHelper
import org.apache.commons.compress.archivers.ArchiveEntry
import org.apache.commons.compress.archivers.ArchiveException
import org.apache.commons.compress.archivers.ArchiveInputStream
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream
import java.lang.ref.WeakReference
import java.util.*
abstract class AbstractCommonsArchiveHelperCallable(
context: Context,
private val filePath: String,
private val relativePath: String,
goBack: Boolean
) : CompressedHelperCallable(goBack) {
private val context: WeakReference<Context> = WeakReference(context)
/**
* Subclasses implement this method to create [ArchiveInputStream] instances with given archive
* as [InputStream].
*
* @param inputStream archive as [InputStream]
*/
abstract fun createFrom(inputStream: InputStream): ArchiveInputStream
@Throws(ArchiveException::class)
@Suppress("LabeledExpression")
public override fun addElements(elements: ArrayList<CompressedObjectParcelable>) {
try {
createFrom(FileInputStream(filePath)).use { tarInputStream ->
var entry: ArchiveEntry?
while (tarInputStream.nextEntry.also { entry = it } != null) {
entry?.run {
var name = name
if (!CompressedHelper.isEntryPathValid(name)) {
AppConfig.toast(
context.get(),
context.get()!!.getString(R.string.multiple_invalid_archive_entries)
)
return@run
}
if (name.endsWith(CompressedHelper.SEPARATOR)) {
name = name.substring(0, name.length - 1)
}
val isInBaseDir =
(relativePath == "" && !name.contains(CompressedHelper.SEPARATOR))
val isInRelativeDir = (
name.contains(CompressedHelper.SEPARATOR) &&
name.substring(0, name.lastIndexOf(CompressedHelper.SEPARATOR))
== relativePath
)
if (isInBaseDir || isInRelativeDir) {
elements.add(
CompressedObjectParcelable(
name,
lastModifiedDate.time,
size,
isDirectory
)
)
}
}
}
}
} catch (e: IOException) {
throw ArchiveException(String.format("Tarball archive %s is corrupt", filePath), e)
}
}
}
| gpl-3.0 | 71b83bcc100ca283d8ab0ad95e20fee9 | 41.927835 | 107 | 0.59414 | 5.372903 | false | false | false | false |
Anizoptera/BacKT_SQL | src/main/kotlin/azadev/backt/sql/utils/resultSet.kt | 1 | 1177 | package azadev.backt.sql.utils
import java.sql.ResultSet
import java.util.*
inline fun <T> ResultSet.single(creator: (ResultSet)->T): T? {
if (next())
return creator(this)
return null
}
inline fun <T> ResultSet.toList(size: Int = 100, creator: (ResultSet)->T): List<T> {
val list = ArrayList<T>(size)
while (next())
list.add(creator(this))
return list
}
inline fun <T> ResultSet.toList(creator: (ResultSet)->T) = toList(2, creator)
inline fun <K, V> ResultSet.toMap(size: Int = 100, creator: (ResultSet)->Pair<K, V>): Map<K, V> {
val map = HashMap<K, V>(size)
while (next())
creator(this).run { map.put(first, second) }
return map
}
inline fun <K, V> ResultSet.toMap(creator: (ResultSet)->Pair<K, V>) = toMap(2, creator)
val ResultSet?.count: Int
get() = if (this != null && next()) getInt(1) else 0
val ResultSet?.countByte: Byte
get() = if (this != null && next()) getByte(1) else 0
val ResultSet?.countLong: Long
get() = if (this != null && next()) getLong(1) else 0L
val ResultSet?.countFloat: Float
get() = if (this != null && next()) getFloat(1) else 0f
val ResultSet?.countDouble: Double
get() = if (this != null && next()) getDouble(1) else .0
| mit | 233667d895e5a70158687d1bc359d23f | 29.973684 | 97 | 0.661852 | 2.972222 | false | false | false | false |
didi/DoraemonKit | Android/app/src/main/java/com/didichuxing/doraemondemo/MapActivity.kt | 1 | 12257 | //package com.didichuxing.doraemondemo
//
//import android.location.Location
//import android.os.Bundle
//import android.os.Looper
//import android.widget.Toast
//import androidx.appcompat.app.AppCompatActivity
//import com.amap.api.location.AMapLocationClient
//import com.amap.api.location.AMapLocationClientOption
//import com.amap.api.maps.AMap
//import com.amap.api.maps.CameraUpdateFactory
//import com.amap.api.maps.model.LatLng
//import com.amap.api.maps.model.MarkerOptions
//import com.amap.api.maps.model.MyLocationStyle
//import com.amap.api.services.route.*
//import com.baidu.location.*
//import com.baidu.mapapi.map.*
//import com.tencent.map.geolocation.TencentLocation
//import com.tencent.map.geolocation.TencentLocationListener
//import com.tencent.map.geolocation.TencentLocationManager
//import com.tencent.map.geolocation.TencentLocationRequest
//import com.tencent.tencentmap.mapsdk.maps.LocationSource
//import com.tencent.tencentmap.mapsdk.maps.TencentMap
//import kotlinx.android.synthetic.main.activity_amap_path.*
//import kotlinx.android.synthetic.main.activity_map.*
//
//
///**
// * 高德地图路径规划
// */
//class MapActivity : AppCompatActivity() {
//
//
// companion object {
// val TAG = "MapActivity"
// const val ZOOM_INDEX = 14.0
// const val BD_ZOOM_INDEX = 18.0
// }
//
// private lateinit var aMap: AMap
//
//
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// setContentView(R.layout.activity_map)
// amap_view.onCreate(savedInstanceState)
// aMap = amap_view.map
// aMap.minZoomLevel = ZOOM_INDEX.toFloat()
// initAMapLocation()
// initTencentMapLocation()
// initBDMapLocation()
// }
//
//
//// lateinit var aMapLocationClient: AMapLocationClient
//// lateinit var aMapLocationClientOption: AMapLocationClientOption
//
// /**
// * 初始化高德地图的定位
// */
// private fun initAMapLocation() {
//// aMapLocationClient = AMapLocationClient(this)
//// aMapLocationClientOption = AMapLocationClientOption()
//// aMapLocationClientOption.locationMode =
//// AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
//// aMapLocationClientOption.interval = 2000
//// aMapLocationClient.setLocationOption(aMapLocationClientOption)
//// aMapLocationClient.setLocationListener {
//// val options = MarkerOptions().position(LatLng(it.latitude, it.longitude))
//// options.draggable(true).icon(
//// com.amap.api.maps.model.BitmapDescriptorFactory.fromResource(
//// R.mipmap.ic_navi_map_gps_locked
//// )
//// )
////
//// aMap.addMarker(options)
//// aMap.clear()
//// aMap.animateCamera(CameraUpdateFactory.newLatLng(LatLng(it.latitude, it.longitude)))
//// }
//// aMapLocationClient.startLocation()
//
// //初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点,定位点依照设备方向旋转,并且会跟随设备移动。(1秒1次定位)如果不设置myLocationType,默认也会执行此种模式。
// val myLocationStyle = MyLocationStyle()
// //设置连续定位模式下的定位间隔,只在连续定位模式下生效,单次定位模式下不会生效。单位为毫秒
// myLocationStyle.interval(2000)
// myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE)
// myLocationStyle.myLocationIcon(
// com.amap.api.maps.model.BitmapDescriptorFactory.fromResource(
// R.mipmap.ic_navi_map_gps_locked
// )
// )
// ////设置是否显示定位小蓝点,用于满足只想使用定位,不想使用定位小蓝点的场景,设置false以后图面上不再有定位蓝点的概念,但是会持续回调位置信息。
// myLocationStyle.showMyLocation(true)
// aMap.myLocationStyle = myLocationStyle //设置定位蓝点的Style
//
// //aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示,非必需设置。
// // 设置为true表示启动显示定位蓝点,false表示隐藏定位蓝点并不进行定位,默认是false。
// aMap.isMyLocationEnabled = true
//
// }
//
// /**
// * 百度地图回调
// */
// private lateinit var mBDLocationClient: LocationClient
//
// private val mBDLocationListener: BDLocationListener =
// BDLocationListener { location ->
// location?.let {
// val locData: MyLocationData = MyLocationData.Builder()
// .accuracy(location.radius) // 此处设置开发者获取到的方向信息,顺时针0-360
// .direction(location.direction)
// .latitude(location.latitude)
// .longitude(location.longitude)
// .build()
// bdmap_view.map.setMyLocationData(locData)
// }
// }
//
//
// lateinit var mBDMap: BaiduMap
//
// /**
// * 初始化百度地图的定位
// */
// private fun initBDMapLocation() {
// mBDMap = bdmap_view.map
// mBDMap.isMyLocationEnabled = true
// val mapStatus: MapStatus = MapStatus.Builder()
// .zoom(BD_ZOOM_INDEX.toFloat())
// .build()
// mBDMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(mapStatus))
// mBDMap.setMyLocationConfiguration(
// MyLocationConfiguration(
// MyLocationConfiguration.LocationMode.FOLLOWING,
// false,
// BitmapDescriptorFactory.fromResource(R.mipmap.ic_navi_map_gps_locked)
// )
// )
// //定位初始化
// mBDLocationClient = LocationClient(this)
//
// //通过LocationClientOption设置LocationClient相关参数
// val option = LocationClientOption()
// option.isOpenGps = true // 打开gps
// option.setCoorType("bd09ll") // 设置坐标类型
//// option.setScanSpan(5000)
//
// //设置locationClientOption
// mBDLocationClient.locOption = option
// //注册LocationListener监听器
// mBDLocationClient.registerLocationListener(mBDLocationListener)
// //开启地图定位图层
// mBDLocationClient.start()
//
//
// }
//
//
// /**
// * ========腾讯地图========
// */
//
// //用于访问腾讯定位服务的类, 周期性向客户端提供位置更新
// var mTencentLocationManager: TencentLocationManager? = null
//
// //创建定位请求
// var mTencentLocationRequest: TencentLocationRequest? = TencentLocationRequest.create()
// var mTencentOnLocationChangedListener: LocationSource.OnLocationChangedListener? = null
// val mTencentLocationListener: TencentLocationListener by lazy {
// object : TencentLocationListener {
// override fun onLocationChanged(
// tencentLocation: TencentLocation?,
// code: Int,
// s: String?
// ) {
// tencentLocation?.let {
// if (code == TencentLocation.ERROR_OK) {
// val location = Location(tencentLocation.provider)
// //设置经纬度
// //设置经纬度
// location.latitude = tencentLocation.latitude
// location.longitude = tencentLocation.longitude
// //设置精度,这个值会被设置为定位点上表示精度的圆形半径
// //设置精度,这个值会被设置为定位点上表示精度的圆形半径
// location.accuracy = tencentLocation.accuracy
// //设置定位标的旋转角度,注意 tencentLocation.getBearing() 只有在 gps 时才有可能获取
// //设置定位标的旋转角度,注意 tencentLocation.getBearing() 只有在 gps 时才有可能获取
// location.bearing = tencentLocation.bearing
// //将位置信息返回给地图
// //将位置信息返回给地图
// mTencentOnLocationChangedListener?.onLocationChanged(location)
// }
// }
// }
//
// override fun onStatusUpdate(p0: String?, p1: Int, p2: String?) {
// }
//
// }
// }
//
// /**
// * ========腾讯地图========
// */
//
//
// lateinit var mTencentMap: TencentMap
//
// /**
// * 初始化腾讯地图的定位
// */
// private fun initTencentMapLocation() {
// mTencentLocationManager = TencentLocationManager.getInstance(this)
// mTencentMap = tencentmap_view.map
// mTencentMap.setLocationSource(object : LocationSource {
// override fun activate(locationChangedListener: LocationSource.OnLocationChangedListener?) {
// locationChangedListener?.let {
// mTencentOnLocationChangedListener = it
// //开启定位
// //开启定位
// val err: Int? = mTencentLocationManager?.requestLocationUpdates(
// mTencentLocationRequest, mTencentLocationListener, Looper.myLooper()
// )
// when (err) {
// 1 -> Toast.makeText(
// this@MapActivity,
// "设备缺少使用腾讯定位服务需要的基本条件",
// Toast.LENGTH_SHORT
// ).show()
// 2 -> Toast.makeText(
// this@MapActivity,
// "manifest 中配置的 key 不正确", Toast.LENGTH_SHORT
// ).show()
// 3 -> Toast.makeText(
// this@MapActivity,
// "自动加载libtencentloc.so失败", Toast.LENGTH_SHORT
// ).show()
// else -> {
// }
// }
// }
// }
//
// override fun deactivate() {
// //当不需要展示定位点时,需要停止定位并释放相关资源
// mTencentLocationManager?.removeUpdates(mTencentLocationListener);
// mTencentLocationManager = null;
// mTencentLocationRequest = null;
// mTencentLocationManager = null;
// }
//
// })
// mTencentMap.isMyLocationEnabled = true
// mTencentMap.setMinZoomLevel(ZOOM_INDEX.toInt())
//
// //设置定位周期(位置监听器回调周期)为3s
//// mTencentLocationRequest?.interval = 3000
// mTencentLocationManager?.requestSingleFreshLocation(
// mTencentLocationRequest,
// mTencentLocationListener, Looper.myLooper()
// )
// }
//
// override fun onStart() {
// tencentmap_view.onStart()
// super.onStart()
// }
//
// override fun onResume() {
// tencentmap_view.onResume()
// amap_view.onResume()
// bdmap_view.onResume()
// super.onResume()
//
// }
//
// override fun onPause() {
// tencentmap_view.onPause()
// amap_view.onPause()
// bdmap_view.onPause()
// super.onPause()
// }
//
// override fun onStop() {
// tencentmap_view.onStop()
// super.onStop()
// }
//
// override fun onDestroy() {
// tencentmap_view.onDestroy()
// amap_view.onDestroy()
// mBDLocationClient.stop()
// bdmap_view.onDestroy()
// bdmap_view.map.isMyLocationEnabled = false
// super.onDestroy()
//
// }
//
// override fun onSaveInstanceState(outState: Bundle) {
// amap_view.onSaveInstanceState(outState)
// super.onSaveInstanceState(outState)
// }
//}
| apache-2.0 | 1703c307b00b157f6c4849181afa4260 | 35.4375 | 181 | 0.577052 | 3.646149 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-indicators/src/test/java/net/nemerosa/ontrack/extension/indicators/imports/IndicatorImportsIT.kt | 1 | 15018 | package net.nemerosa.ontrack.extension.indicators.imports
import net.nemerosa.ontrack.extension.indicators.AbstractIndicatorsTestSupport
import net.nemerosa.ontrack.extension.indicators.IndicatorConfigProperties
import net.nemerosa.ontrack.extension.indicators.model.IndicatorSource
import net.nemerosa.ontrack.extension.indicators.model.IndicatorSourceProviderDescription
import net.nemerosa.ontrack.extension.indicators.values.BooleanIndicatorValueType
import net.nemerosa.ontrack.extension.indicators.values.BooleanIndicatorValueTypeConfig
import net.nemerosa.ontrack.test.TestUtils.uid
import net.nemerosa.ontrack.test.assertIs
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
class IndicatorImportsIT : AbstractIndicatorsTestSupport() {
@Autowired
private lateinit var indicatorImportsService: IndicatorImportsService
@Autowired
private lateinit var indicatorConfigProperties: IndicatorConfigProperties
@Test
fun `Importing categories and types`() {
val source = uid("S")
val prefix = uid("P")
val data = IndicatorImports(
source = source,
categories = listOf(
IndicatorImportCategory(
id = "$prefix-cat-one",
name = "Category 1",
types = listOf(
IndicatorImportsType(
id = "$prefix-type-one",
name = "Type 1",
link = null,
required = false
),
IndicatorImportsType(
id = "$prefix-type-two",
name = "Type 2",
link = "https://github.com/nemerosa/ontrack",
required = true
)
)
)
)
)
asAdmin {
indicatorImportsService.imports(data)
}
val expectedSource = IndicatorSource(
name = source,
provider = IndicatorSourceProviderDescription(
id = ImportsIndicatorSourceProvider::class.java.name,
name = "Import"
)
)
// Checks category
assertNotNull(indicatorCategoryService.findCategoryById("$prefix-cat-one")) { category ->
assertEquals("$prefix-cat-one", category.id)
assertEquals("Category 1", category.name)
assertEquals(expectedSource, category.source)
}
// Check types
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-one")) { type ->
assertEquals("$prefix-type-one", type.id)
assertEquals("Type 1", type.name)
assertEquals(null, type.link)
assertIs<BooleanIndicatorValueType>(type.valueType) {}
assertEquals(BooleanIndicatorValueTypeConfig(false), type.valueConfig)
assertEquals(expectedSource, type.source)
}
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-two")) { type ->
assertEquals("$prefix-type-two", type.id)
assertEquals("Type 2", type.name)
assertEquals("https://github.com/nemerosa/ontrack", type.link)
assertIs<BooleanIndicatorValueType>(type.valueType) {}
assertEquals(BooleanIndicatorValueTypeConfig(true), type.valueConfig)
assertEquals(expectedSource, type.source)
}
}
@Test
fun `Management of orphans using the source of the import using deletion as a configuration`() {
val old = indicatorConfigProperties.importing.deleting
try {
indicatorConfigProperties.importing.deleting = true
val source = uid("S")
val prefix = uid("P")
val data = IndicatorImports(
source = source,
categories = listOf(
IndicatorImportCategory(
id = "$prefix-cat-one",
name = "Category 1",
types = listOf(
IndicatorImportsType(
id = "$prefix-type-one",
name = "Type 1",
link = null,
required = false
),
IndicatorImportsType(
id = "$prefix-type-two",
name = "Type 2",
link = "https://github.com/nemerosa/ontrack",
required = true
)
)
),
IndicatorImportCategory(
id = "$prefix-cat-two",
name = "Category 2",
types = listOf(
IndicatorImportsType(
id = "$prefix-type-three",
name = "Type 3",
link = null,
required = false
),
IndicatorImportsType(
id = "$prefix-type-four",
name = "Type 4",
link = "https://github.com/nemerosa/ontrack",
required = true
)
)
)
)
)
asAdmin {
indicatorImportsService.imports(data)
}
// Checks the imported data
assertNotNull(indicatorCategoryService.findCategoryById("$prefix-cat-one"))
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-one"))
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-two"))
assertNotNull(indicatorCategoryService.findCategoryById("$prefix-cat-two"))
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-three"))
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-four"))
// Removes some types, adds some types and categories
val newData = IndicatorImports(
source = source,
categories = listOf(
IndicatorImportCategory(
id = "$prefix-cat-one",
name = "Category 1",
types = listOf(
IndicatorImportsType(
id = "$prefix-type-two",
name = "Type 2",
link = "https://github.com/nemerosa/ontrack",
required = true
),
IndicatorImportsType(
id = "$prefix-type-five",
name = "Type 5",
link = "https://github.com/nemerosa/ontrack",
required = true
)
)
),
IndicatorImportCategory(
id = "$prefix-cat-three",
name = "Category 3",
types = listOf(
IndicatorImportsType(
id = "$prefix-type-six",
name = "Type 6",
link = null,
required = false
)
)
)
)
)
asAdmin {
indicatorImportsService.imports(newData)
}
// Checks the imported data
assertNotNull(indicatorCategoryService.findCategoryById("$prefix-cat-one"))
assertNull(indicatorTypeService.findTypeById("$prefix-type-one"), "Type should be gone")
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-two"))
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-five"))
assertNull(indicatorCategoryService.findCategoryById("$prefix-cat-two"), "Category should be gone")
assertNull(indicatorTypeService.findTypeById("$prefix-type-three"), "Type should be gone")
assertNull(indicatorTypeService.findTypeById("$prefix-type-four"), "Type should be gone")
assertNotNull(indicatorCategoryService.findCategoryById("$prefix-cat-three"))
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-six"))
} finally {
indicatorConfigProperties.importing.deleting = old
}
}
@Test
fun `Management of orphans using the source of the import using deprecation as a configuration`() {
val old = indicatorConfigProperties.importing.deleting
assertFalse(old, "We expect the deprecation mode to be true by default")
try {
indicatorConfigProperties.importing.deleting = false
val source = uid("S")
val prefix = uid("P")
val data = IndicatorImports(
source = source,
categories = listOf(
IndicatorImportCategory(
id = "$prefix-cat-one",
name = "Category 1",
types = listOf(
IndicatorImportsType(
id = "$prefix-type-one",
name = "Type 1",
link = null,
required = false
),
IndicatorImportsType(
id = "$prefix-type-two",
name = "Type 2",
link = "https://github.com/nemerosa/ontrack",
required = true
)
)
),
IndicatorImportCategory(
id = "$prefix-cat-two",
name = "Category 2",
types = listOf(
IndicatorImportsType(
id = "$prefix-type-three",
name = "Type 3",
link = null,
required = false
),
IndicatorImportsType(
id = "$prefix-type-four",
name = "Type 4",
link = "https://github.com/nemerosa/ontrack",
required = true
)
)
)
)
)
asAdmin {
indicatorImportsService.imports(data)
}
// Checks the imported data
assertNotNull(indicatorCategoryService.findCategoryById("$prefix-cat-one"))
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-one"))
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-two"))
assertNotNull(indicatorCategoryService.findCategoryById("$prefix-cat-two"))
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-three"))
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-four"))
// Removes some types, adds some types and categories
val newData = IndicatorImports(
source = source,
categories = listOf(
IndicatorImportCategory(
id = "$prefix-cat-one",
name = "Category 1",
types = listOf(
IndicatorImportsType(
id = "$prefix-type-two",
name = "Type 2",
link = "https://github.com/nemerosa/ontrack",
required = true
),
IndicatorImportsType(
id = "$prefix-type-five",
name = "Type 5",
link = "https://github.com/nemerosa/ontrack",
required = true
)
)
),
IndicatorImportCategory(
id = "$prefix-cat-three",
name = "Category 3",
types = listOf(
IndicatorImportsType(
id = "$prefix-type-six",
name = "Type 6",
link = null,
required = false
)
)
)
)
)
asAdmin {
indicatorImportsService.imports(newData)
}
// Checks the imported data
assertNotNull(indicatorCategoryService.findCategoryById("$prefix-cat-one"))
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-one")) {
assertEquals("Deprecated because not part of the $source import source.", it.deprecated)
}
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-two"))
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-five"))
assertNotNull(indicatorCategoryService.findCategoryById("$prefix-cat-two")) {
assertEquals("Deprecated because not part of the $source import source.", it.deprecated)
}
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-three"))
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-four"))
assertNotNull(indicatorCategoryService.findCategoryById("$prefix-cat-three"))
assertNotNull(indicatorTypeService.findTypeById("$prefix-type-six"))
} finally {
indicatorConfigProperties.importing.deleting = old
}
}
} | mit | 97f94b58a95e594bf62e709717aea89c | 44.237952 | 111 | 0.466507 | 6.350106 | false | false | false | false |
binout/soccer-league | src/test/kotlin/io/github/binout/soccer/infrastructure/persistence/mongo/MongoPlayerRepositoryTest.kt | 1 | 1950 | package io.github.binout.soccer.infrastructure.persistence.mongo
import io.github.binout.soccer.domain.player.Player
import io.github.binout.soccer.domain.player.PlayerName
import io.github.binout.soccer.infrastructure.persistence.MongoConfiguration
import io.github.binout.soccer.infrastructure.persistence.MongoPlayerRepository
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
class MongoPlayerRepositoryTest {
private lateinit var repository: MongoPlayerRepository
@BeforeEach
fun initRepository() {
repository = MongoPlayerRepository(MongoConfiguration("").database())
}
@Test
fun should_persist_player() {
repository.add(Player(PlayerName("benoit")))
val benoit = repository.byName(PlayerName("benoit"))
assertThat(benoit).isNotNull
assertThat(benoit!!.email).isNull()
assertThat(benoit.isPlayerLeague).isFalse()
}
@Test
fun should_persist_league_player() {
val leaguePlayer = Player(name = PlayerName("benoit"), email = "[email protected]")
leaguePlayer.isPlayerLeague = true
repository.add(leaguePlayer)
val benoit = repository.byName(PlayerName("benoit"))
assertThat(benoit).isNotNull
assertThat(benoit!!.email).isEqualTo("[email protected]")
assertThat(benoit.isPlayerLeague).isTrue()
}
@Test
fun should_persist_goalkeeper() {
val leaguePlayer = Player(name = PlayerName("thomas"), email = "[email protected]")
leaguePlayer.isPlayerLeague = true
leaguePlayer.isGoalkeeper = true
repository.add(leaguePlayer)
val thomas = repository.byName(PlayerName("thomas"))
assertThat(thomas).isNotNull
assertThat(thomas!!.email).isEqualTo("[email protected]")
assertThat(thomas.isPlayerLeague).isTrue()
assertThat(thomas.isGoalkeeper).isTrue()
}
} | apache-2.0 | 27cf1984575dc2954a251ae90749794d | 33.839286 | 89 | 0.713333 | 4.482759 | false | true | false | false |
groupdocs-comparison/GroupDocs.Comparison-for-Java | Demos/Compose/src/main/kotlin/com/groupdocs/ui/theme/Type.kt | 1 | 510 | package com.groupdocs.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 14.sp
),
body2 = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
) | mit | 76ac20511c2351f3512f723deaa49833 | 25.894737 | 47 | 0.717647 | 4.112903 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/toml/platform/forge/inspections/ModsTomlValidationInspection.kt | 1 | 5357 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.toml.platform.forge.inspections
import com.demonwav.mcdev.platform.forge.util.ForgeConstants
import com.demonwav.mcdev.toml.TomlElementVisitor
import com.demonwav.mcdev.toml.platform.forge.ModsTomlSchema
import com.demonwav.mcdev.toml.stringValue
import com.demonwav.mcdev.toml.tomlType
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiFile
import com.intellij.psi.util.parentOfType
import org.toml.lang.psi.TomlArrayTable
import org.toml.lang.psi.TomlHeaderOwner
import org.toml.lang.psi.TomlKey
import org.toml.lang.psi.TomlKeySegment
import org.toml.lang.psi.TomlKeyValue
import org.toml.lang.psi.TomlKeyValueOwner
import org.toml.lang.psi.TomlTableHeader
import org.toml.lang.psi.TomlValue
import org.toml.lang.psi.ext.name
class ModsTomlValidationInspection : LocalInspectionTool() {
override fun getDisplayName(): String = "Forge's mods.toml validation"
override fun getStaticDescription(): String = "Checks mods.toml files for errors"
override fun processFile(file: PsiFile, manager: InspectionManager): MutableList<ProblemDescriptor> {
if (file.virtualFile.name == ForgeConstants.MODS_TOML) {
return super.processFile(file, manager)
}
return mutableListOf()
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
if (holder.file.virtualFile.name == ForgeConstants.MODS_TOML) {
return Visitor(holder)
}
return PsiElementVisitor.EMPTY_VISITOR
}
private class Visitor(val holder: ProblemsHolder) : TomlElementVisitor() {
override fun visitKeyValue(keyValue: TomlKeyValue) {
when (keyValue.key.text) {
"modId" -> {
val value = keyValue.value ?: return
val modId = value.stringValue() ?: return
if (!ForgeConstants.MOD_ID_REGEX.matches(modId)) {
val endOffset = if (value.text.endsWith('"')) modId.length + 1 else modId.length
holder.registerProblem(value, TextRange(1, endOffset), "Mod ID is invalid")
}
}
"side" -> {
val value = keyValue.value ?: return
val side = value.stringValue() ?: return
if (side !in ForgeConstants.DEPENDENCY_SIDES) {
val endOffset = if (value.text.endsWith('"')) side.length + 1 else side.length
holder.registerProblem(value, TextRange(1, endOffset), "Side $side does not exist")
}
}
"ordering" -> {
val value = keyValue.value ?: return
val order = value.stringValue() ?: return
if (order !in ForgeConstants.DEPENDENCY_ORDER) {
val endOffset = if (value.text.endsWith('"')) order.length + 1 else order.length
holder.registerProblem(value, TextRange(1, endOffset), "Order $order does not exist")
}
}
}
}
override fun visitKeySegment(keySegment: TomlKeySegment) {
val key = keySegment.parent as? TomlKey ?: return
if (key.parent is TomlTableHeader &&
key.segments.indexOf(keySegment) == 1 &&
key.segments.first().text == "dependencies" // We are visiting a dependency table
) {
val targetId = keySegment.text
val isDeclaredId = keySegment.containingFile.children
.filterIsInstance<TomlArrayTable>()
.filter { it.header.key?.name == "mods" }
.any { it.entries.find { it.key.text == "modId" }?.value?.stringValue() == targetId }
if (!isDeclaredId) {
holder.registerProblem(keySegment, "Mod $targetId is not declared in this file")
}
}
}
override fun visitValue(value: TomlValue) {
val schema = ModsTomlSchema.get(value.project)
val key = value.parentOfType<TomlKeyValue>()?.key?.text ?: return
val (expectedType, actualType) = when (val parent = value.parent) {
is TomlKeyValue -> when (val table = value.parentOfType<TomlKeyValueOwner>()) {
is TomlHeaderOwner ->
table.header.key?.segments?.firstOrNull()?.text?.let { schema.tableEntry(it, key)?.type }
null -> schema.topLevelEntries.find { it.key == key }?.type
else -> return
} to parent.value?.tomlType
else -> return
}
if (expectedType != null && actualType != null && expectedType != actualType) {
holder.registerProblem(value, "Wrong value type, expected ${expectedType.presentableName}")
}
}
}
}
| mit | 951d3d63cac9ba6d7e43b97ed19892f7 | 43.272727 | 113 | 0.61135 | 4.744907 | false | false | false | false |
bozaro/git-as-svn | src/test/kotlin/svnserver/tester/SvnTesterExternalListener.kt | 1 | 6017 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.tester
import org.testng.ITestContext
import org.testng.ITestListener
import org.testng.ITestResult
import org.tmatesoft.svn.core.SVNAuthenticationException
import org.tmatesoft.svn.core.SVNErrorCode
import org.tmatesoft.svn.core.SVNException
import org.tmatesoft.svn.core.SVNURL
import org.tmatesoft.svn.core.auth.BasicAuthenticationManager
import org.tmatesoft.svn.core.io.SVNRepositoryFactory
import svnserver.SvnTestHelper
import svnserver.TestHelper
import java.io.FileWriter
import java.net.InetAddress
import java.net.ServerSocket
import java.nio.file.Path
import java.text.MessageFormat
import java.util.concurrent.TimeUnit
/**
* Listener for creating SvnTesterExternal.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class SvnTesterExternalListener : ITestListener {
override fun onTestStart(result: ITestResult) {}
override fun onTestSuccess(result: ITestResult) {}
override fun onTestFailure(result: ITestResult) {}
override fun onTestSkipped(result: ITestResult) {}
override fun onTestFailedButWithinSuccessPercentage(result: ITestResult) {}
override fun onStart(context: ITestContext) {
try {
val svnserve = SvnTestHelper.findExecutable("svnserve")
val svnadmin = SvnTestHelper.findExecutable("svnadmin")
if (svnserve != null && svnadmin != null) {
log.warn("Native svn daemon executables: {}, {}", svnserve, svnadmin)
daemon = NativeDaemon(svnserve, svnadmin)
} else {
log.warn("Native svn daemon disabled")
}
} catch (e: Exception) {
throw IllegalStateException(e)
}
}
override fun onFinish(context: ITestContext) {
if (daemon != null) {
try {
daemon!!.close()
} catch (e: Exception) {
throw IllegalStateException(e)
} finally {
daemon = null
}
}
}
private class NativeDaemon(svnserve: String, svnadmin: String) : SvnTesterFactory, AutoCloseable {
private val daemon: Process
private val repo: Path
private val url: SVNURL
private fun detectPort(): Int {
ServerSocket(0, 0, InetAddress.getByName(HOST)).use { socket -> return socket.localPort }
}
override fun create(): SvnTester {
return SvnTesterExternal(url, BasicAuthenticationManager.newInstance(USER_NAME, PASSWORD.toCharArray()))
}
override fun close() {
log.info("Stopping native svn daemon.")
daemon.destroy()
daemon.waitFor()
TestHelper.deleteDirectory(repo)
}
companion object {
private fun createConfigs(repo: Path): Path {
val config = repo.resolve("conf/server.conf")
val passwd = repo.resolve("conf/server.passwd")
FileWriter(config.toFile()).use { writer -> writer.write(MessageFormat.format(CONFIG_SERVER, passwd.toString())) }
FileWriter(passwd.toFile()).use { writer -> writer.write(MessageFormat.format(CONFIG_PASSWD, USER_NAME, PASSWORD)) }
return config
}
}
init {
val port = detectPort()
url = SVNURL.create("svn", null, HOST, port, null, true)
repo = TestHelper.createTempDir("git-as-svn-repo")
log.info("Starting native svn daemon at: {}, url: {}", repo, url)
Runtime.getRuntime().exec(
arrayOf(
svnadmin,
"create",
repo.toString()
)
).waitFor()
val config = createConfigs(repo)
daemon = Runtime.getRuntime().exec(
arrayOf(
svnserve,
"--daemon",
"--root", repo.toString(),
"--config-file", config.toString(),
"--listen-host", HOST,
"--listen-port", port.toString()
)
)
val serverStartupTimeout = System.currentTimeMillis() + SERVER_STARTUP_TIMEOUT
while (true) {
try {
SVNRepositoryFactory.create(url).getRevisionPropertyValue(0, "example")
} catch (ignored: SVNAuthenticationException) {
break
} catch (e: SVNException) {
if (e.errorMessage.errorCode === SVNErrorCode.RA_SVN_IO_ERROR && System.currentTimeMillis() < serverStartupTimeout) {
Thread.sleep(SERVER_STARTUP_DELAY)
continue
}
throw e
}
break
}
}
}
companion object {
private val log = TestHelper.logger
private const val USER_NAME = "tester"
private const val PASSWORD = "passw0rd"
private const val HOST = "127.0.0.2"
private const val CONFIG_SERVER = "" +
"[general]\n" +
"anon-access = none\n" +
"auth-access = write\n" +
"password-db = {0}\n"
private const val CONFIG_PASSWD = "" +
"[users]\n" +
"{0} = {1}\n"
private val SERVER_STARTUP_TIMEOUT = TimeUnit.SECONDS.toMillis(30)
private val SERVER_STARTUP_DELAY = TimeUnit.MILLISECONDS.toMillis(20)
private var daemon: NativeDaemon? = null
fun get(): SvnTesterFactory? {
return daemon
}
}
}
| gpl-2.0 | 152716e97753b9fa5cd6dd876124cdb1 | 37.570513 | 137 | 0.582184 | 4.760285 | false | true | false | false |
Egorand/kotlin-playground | src/me/egorand/kotlin/playground/misc/NullSafety.kt | 1 | 1205 | /*
* Copyright 2016 Egor Andreevici
*
* 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.egorand.kotlin.playground.misc
fun main(args: Array<String>) {
var a: String = "abc"
// a = null // won't compile, a can't be null!
var b: String? = "abc"
b = null // b can be null, since type is String? vs String
println(a.length)
// println(b.length) // won't compile, since b can be null!
println(if (b != null) b.length else -1)
println(b?.length)
println(b?.length ?: -1)
try {
println(b!!.length) // will compile, but will throw an NPE
} catch (e: NullPointerException) {
println("NPE!")
}
} | apache-2.0 | af455f638cce9639238d37fe851a6a9f | 29.923077 | 80 | 0.650622 | 3.597015 | false | false | false | false |
SirWellington/alchemy-generator | src/main/java/tech/sirwellington/alchemy/generator/TimeGenerators.kt | 1 | 7440 | /*
* Copyright © 2019. Sir Wellington.
* 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 tech.sirwellington.alchemy.generator
import org.slf4j.LoggerFactory
import tech.sirwellington.alchemy.annotations.access.NonInstantiable
import tech.sirwellington.alchemy.annotations.arguments.Required
import tech.sirwellington.alchemy.annotations.designs.patterns.StrategyPattern
import tech.sirwellington.alchemy.annotations.designs.patterns.StrategyPattern.Role.CONCRETE_BEHAVIOR
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.integers
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.longs
import java.time.Instant
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.temporal.ChronoUnit.*
/**
* Generators for [Java Instants][Instant].
*
* @author SirWellington
*/
@NonInstantiable
@StrategyPattern(role = CONCRETE_BEHAVIOR)
class TimeGenerators
@Throws(IllegalAccessException::class)
internal constructor()
{
init
{
throw IllegalAccessException("cannot instantiate")
}
companion object
{
private val LOG = LoggerFactory.getLogger(TimeGenerators::class.java)
/**
* Produces [Instants][Instant] representing the *present*, i.e *now*. Note that
* the 'present'
* depends on when the Generator is [called][AlchemyGenerator.get].
*
* @return
*/
@JvmStatic
fun presentInstants(): AlchemyGenerator<Instant>
{
return AlchemyGenerator { Instant.now() }
}
/**
* Produces [Instants][Instant] that are always in the past, i.e. before the present.
*
* @return
*/
@JvmStatic
fun pastInstants(): AlchemyGenerator<Instant>
{
/*
* There is no need to recalculate the present instant per-call. We simply capture the present Instant, and
* supply dates before that reference point. They will always be in the past.
*/
return before(Instant.now())
}
/**
* Produces [Instants][Instant] that are always in the future, i.e. after the present.
*
* @return
*/
@JvmStatic
fun futureInstants(): AlchemyGenerator<Instant>
{
// In order to stay in the future, the "present" must be continuously recalculated.
return AlchemyGenerator {
val present = Instant.now()
after(present).get()
}
}
/**
* Produces [Instants][Instant] that are always before the specified time.
*
* @param instant
*
*
* @return
*
* @throws IllegalArgumentException
*/
@JvmStatic
@Throws(IllegalArgumentException::class)
fun before(@Required instant: Instant): AlchemyGenerator<Instant>
{
checkNotNull(instant, "instant cannot be null")
return AlchemyGenerator {
val daysBefore = one(integers(1, 1000))
val hoursBefore = one(integers(0, 100))
val minutesBefore = one(integers(0, 60))
val secondsBefore = one(integers(0, 60))
val millisecondsBefore = one(integers(0, 1000))
instant.minus(daysBefore.toLong(), DAYS)
.minus(hoursBefore.toLong(), HOURS)
.minus(minutesBefore.toLong(), MINUTES)
.minus(secondsBefore.toLong(), SECONDS)
.minus(millisecondsBefore.toLong(), MILLIS)
}
}
/**
* Produces [Instants][Instant] that are always after the specified time.
*
* @param instant
*
*
* @return
*
* @throws IllegalArgumentException
*/
@JvmStatic
@Throws(IllegalArgumentException::class)
fun after(@Required instant: Instant): AlchemyGenerator<Instant>
{
checkNotNull(instant, "instant cannot be null")
return AlchemyGenerator {
val daysAhead = one(integers(1, 11000))
val hoursAhead = one(integers(0, 100))
val minutesAhead = one(integers(0, 60))
val secondsAhead = one(integers(0, 60))
val millisecondsAhead = one(integers(0, 1000))
instant.plus(daysAhead.toLong(), DAYS)
.plus(hoursAhead.toLong(), HOURS)
.plus(minutesAhead.toLong(), MINUTES)
.plus(secondsAhead.toLong(), SECONDS)
.plus(millisecondsAhead.toLong(), MILLIS)
}
}
/**
* Produces [Instants][Instant] from any time, past, present, or future.
*
* @return
*/
@JvmStatic
fun anytime(): AlchemyGenerator<Instant>
{
return AlchemyGenerator {
val choice = one(integers(0, 3))
when (choice)
{
0 -> pastInstants().get()
1 -> futureInstants().get()
else -> presentInstants().get()
}
}
}
/**
* Generates [Instants][Instant] between the specified times.
*
* @param startTime Times produced will come at or after this time.
*
* @param endTime Times produced will come before this time.
*
*
* @return
*
* @throws IllegalArgumentException If either time is null, or if the startTime is not before the endTime.
*/
@JvmStatic
@Throws(IllegalArgumentException::class)
fun timesBetween(@Required startTime: Instant, @Required endTime: Instant): AlchemyGenerator<Instant>
{
checkNotNull(startTime, "startTime is null")
checkNotNull(endTime, "endTime is null")
checkThat(startTime.isBefore(endTime), "startTime must be before endTime")
val epochOfStart = startTime.toEpochMilli()
val epochOfEnd = endTime.toEpochMilli()
val timestampGenerator = longs(epochOfStart, epochOfEnd)
return AlchemyGenerator {
val timestamp = timestampGenerator.get()
Instant.ofEpochMilli(timestamp)
}
}
}
}
/**
* Converts this [Instant] generator into a [ZonedDateTime] generator.
*
* @param zone The [ZoneId] to the generate times in. Defaults to [ZoneOffset.UTC].
*/
fun AlchemyGenerator<Instant>.asZonedDateTimeGenerator(zone: ZoneId = ZoneOffset.UTC): AlchemyGenerator<ZonedDateTime>
{
return AlchemyGenerator {
val instant = this.get()
ZonedDateTime.ofInstant(instant, zone)
}
} | apache-2.0 | 28e0933602205d21e044d5161e5247f2 | 31.77533 | 118 | 0.592687 | 4.956029 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/page/customize/CustomizeToolbarFragment.kt | 1 | 9261 | package org.wikipedia.page.customize
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.wikipedia.R
import org.wikipedia.analytics.eventplatform.CustomizeToolbarEvent
import org.wikipedia.databinding.FragmentCustomizeToolbarBinding
import org.wikipedia.page.action.PageActionItem
import org.wikipedia.settings.Prefs
import org.wikipedia.views.DefaultViewHolder
class CustomizeToolbarFragment : Fragment() {
private var _binding: FragmentCustomizeToolbarBinding? = null
private val binding get() = _binding!!
private val viewModel: CustomizeToolbarViewModel by viewModels()
private lateinit var itemTouchHelper: ItemTouchHelper
private lateinit var adapter: RecyclerItemAdapter
private lateinit var customizeToolbarEvent: CustomizeToolbarEvent
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
super.onCreateView(inflater, container, savedInstanceState)
customizeToolbarEvent = CustomizeToolbarEvent()
_binding = FragmentCustomizeToolbarBinding.inflate(LayoutInflater.from(context), container, false)
return binding.root
}
override fun onResume() {
super.onResume()
customizeToolbarEvent.resume()
}
override fun onPause() {
super.onPause()
customizeToolbarEvent.pause()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
setupRecyclerView()
super.onViewCreated(view, savedInstanceState)
}
override fun onDestroyView() {
customizeToolbarEvent.logCustomization(Prefs.customizeToolbarOrder.toMutableList(), Prefs.customizeToolbarMenuOrder.toMutableList())
_binding = null
super.onDestroyView()
}
private fun setupRecyclerView() {
binding.recyclerView.setHasFixedSize(true)
adapter = RecyclerItemAdapter()
binding.recyclerView.adapter = adapter
binding.recyclerView.layoutManager = LinearLayoutManager(requireActivity())
itemTouchHelper = ItemTouchHelper(RearrangeableItemTouchHelperCallback(adapter))
itemTouchHelper.attachToRecyclerView(binding.recyclerView)
}
private inner class RecyclerItemAdapter : RecyclerView.Adapter<DefaultViewHolder<*>>() {
override fun getItemViewType(position: Int): Int {
return viewModel.fullList[position].first
}
override fun getItemCount(): Int {
return viewModel.fullList.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DefaultViewHolder<*> {
return when (viewType) {
VIEW_TYPE_HEADER -> {
HeaderViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_customize_toolbar_header, parent, false))
}
VIEW_TYPE_EMPTY_PLACEHOLDER -> {
EmptyPlaceholderViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_customize_toolbar_empty_placeholder, parent, false))
}
VIEW_TYPE_DESCRIPTION -> {
DescriptionViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_customize_toolbar_description, parent, false))
}
VIEW_TYPE_SET_TO_DEFAULT -> {
SetToDefaultViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_customize_toolbar_set_to_default, parent, false))
}
else -> {
ItemHolder(CustomizeToolbarItemView(parent.context))
}
}
}
override fun onBindViewHolder(holder: DefaultViewHolder<*>, pos: Int) {
when (holder) {
is ItemHolder -> {
holder.bindItem(viewModel.fullList[pos].second as PageActionItem, pos)
holder.view.setDragHandleEnabled(true)
}
is HeaderViewHolder -> {
holder.bindItem(viewModel.fullList[pos].second as Int)
}
}
}
override fun onViewAttachedToWindow(holder: DefaultViewHolder<*>) {
super.onViewAttachedToWindow(holder)
if (holder is ItemHolder) {
holder.view.setDragHandleTouchListener { v, event ->
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
itemTouchHelper.startDrag(holder)
}
MotionEvent.ACTION_UP -> v.performClick()
else -> { }
}
false
}
}
}
override fun onViewDetachedFromWindow(holder: DefaultViewHolder<*>) {
if (holder is ItemHolder) {
holder.view.setDragHandleTouchListener(null)
}
super.onViewDetachedFromWindow(holder)
}
fun onMoveItem(oldPosition: Int, newPosition: Int) {
viewModel.swapList(oldPosition, newPosition)
notifyItemMoved(oldPosition, newPosition)
}
fun onItemMoved(rearrangedItems: List<Int>) {
val removePosition = viewModel.removeEmptyPlaceholder()
if (removePosition >= 0) {
notifyItemRemoved(removePosition)
}
val addPosition = viewModel.addEmptyPlaceholder()
if (addPosition >= 0) {
notifyItemRangeChanged(addPosition, viewModel.fullList.size - addPosition)
}
// Notify recycler view adapter that some items in the list have been manually swapped.
rearrangedItems.forEach {
notifyItemMoved(it, it + 1)
}
}
}
private inner class RearrangeableItemTouchHelperCallback constructor(private val adapter: RecyclerItemAdapter) : ItemTouchHelper.Callback() {
override fun isLongPressDragEnabled(): Boolean {
return true
}
override fun isItemViewSwipeEnabled(): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {}
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
return if (isMovable(viewHolder)) makeMovementFlags(ItemTouchHelper.UP or ItemTouchHelper.DOWN, 0) else 0
}
override fun onMove(recyclerView: RecyclerView, source: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
if (isMovable(target)) {
adapter.onMoveItem(source.absoluteAdapterPosition, target.absoluteAdapterPosition)
}
return true
}
override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
super.clearView(recyclerView, viewHolder)
recyclerView.post {
if (isAdded) {
adapter.onItemMoved(viewModel.saveChanges())
}
}
}
private fun isMovable(target: RecyclerView.ViewHolder): Boolean {
// TODO: Add (target is HeaderViewHolder) with matching title string to make them swappable between categories
return target is ItemHolder
}
}
private inner class HeaderViewHolder constructor(itemView: View) : DefaultViewHolder<View>(itemView) {
fun bindItem(@StringRes stringRes: Int) {
itemView.findViewById<TextView>(R.id.headerTitle).setText(stringRes)
}
}
private inner class ItemHolder constructor(itemView: CustomizeToolbarItemView) : DefaultViewHolder<CustomizeToolbarItemView>(itemView) {
fun bindItem(pageActionItem: PageActionItem, position: Int) {
view.setContents(pageActionItem, position)
}
}
private inner class DescriptionViewHolder constructor(itemView: View) : DefaultViewHolder<View>(itemView)
private inner class SetToDefaultViewHolder constructor(itemView: View) : DefaultViewHolder<View>(itemView) {
init {
itemView.findViewById<TextView>(R.id.resetToDefaultButton).setOnClickListener {
viewModel.resetToDefault()
setupRecyclerView()
}
}
}
private inner class EmptyPlaceholderViewHolder constructor(itemView: View) : DefaultViewHolder<View>(itemView)
companion object {
const val VIEW_TYPE_DESCRIPTION = 0
const val VIEW_TYPE_HEADER = 1
const val VIEW_TYPE_ITEM = 2
const val VIEW_TYPE_SET_TO_DEFAULT = 3
const val VIEW_TYPE_EMPTY_PLACEHOLDER = 4
const val TOOLBAR_ITEMS_LIMIT = 5
fun newInstance(): CustomizeToolbarFragment {
return CustomizeToolbarFragment()
}
}
}
| apache-2.0 | 14c78bf0d52e91a67f26fc6428faa35d | 39.441048 | 157 | 0.649822 | 5.599154 | false | false | false | false |
martypitt/boxtape | cli/src/main/java/io/boxtape/cli/core/Dependency.kt | 1 | 674 | package io.boxtape.core
import com.github.zafarkhaja.semver.Version
data class Dependency(val groupId: String, val artifactId: String, val version: String) {
/**
* Indicates if this dependency matches other.
*
* It is expected that this method is called on a fully
* qualified, resolved Dependency.
*
* The value of other may contain version ranges.
*/
fun matches(other: Dependency): Boolean {
return this.groupId == other.groupId &&
this.artifactId == other.artifactId &&
Version.valueOf(version).satisfies(other.version)
}
fun name(): String = "${groupId}:${artifactId}:${version}"
}
| apache-2.0 | 0c6315d8ce0894bb0a8d9d27fa215d65 | 29.636364 | 89 | 0.654303 | 4.434211 | false | false | false | false |
spring-cloud-samples/spring-cloud-contract-samples | producer_kotlin/src/main/kotlin/com/example/StatsController.kt | 1 | 1467 | package com.example
import org.springframework.stereotype.Service
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
/**
* @author Marcin Grzejszczak
*/
@RestController
class StatsController(private val statsService: StatsService) {
@RequestMapping(value = ["/stats"],
method = arrayOf(RequestMethod.POST),
consumes = arrayOf("application/json"),
produces = arrayOf("application/json"))
fun check(@RequestBody request: StatsRequest): StatsResponse {
val bottles = this.statsService.findBottlesByName(request.name)
val text = "Dear " + request.name + " thanks for your interested in drinking beer"
return StatsResponse(bottles, text)
}
}
interface StatsService {
fun findBottlesByName(name: String): Int
}
@Service
internal class NoOpStatsService : StatsService {
override fun findBottlesByName(name: String): Int {
return 0
}
}
class StatsRequest {
var name: String = ""
constructor(name: String) {
this.name = name
}
constructor() {}
}
class StatsResponse {
var quantity: Int = 0
var text: String = ""
constructor(quantity: Int, text: String) {
this.quantity = quantity
this.text = text
}
constructor() {}
} | apache-2.0 | 69b566886cf63c8f385cfcfecdcb0655 | 24.310345 | 90 | 0.693933 | 4.252174 | false | false | false | false |
joaoevangelista/Convertx | app/src/main/kotlin/io/github/joaoevangelista/convertx/activity/UnitSelectedListeners.kt | 1 | 1230 | package io.github.joaoevangelista.convertx.activity
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import io.github.joaoevangelista.convertx.op.NamedUnit
class ToUnitItemSelected(val typeUnits: Array<out NamedUnit>?,
val notifyChange: () -> Unit) : OnItemSelectedListener {
override fun onNothingSelected(adapter: AdapterView<*>?) {
UnitsSelectedHolder.toUnit = typeUnits?.get(0)
}
override fun onItemSelected(adapter: AdapterView<*>?, view: View?, position: Int, id: Long) {
UnitsSelectedHolder.toUnit = typeUnits?.get(position)
notifyChange()
}
}
class FromUnitItemSelected(val typeUnits: Array<out NamedUnit>?,
val notifyChange: () -> Unit) : OnItemSelectedListener {
override fun onNothingSelected(adapter: AdapterView<*>?) {
UnitsSelectedHolder.fromUnit = typeUnits?.get(0)
}
override fun onItemSelected(adapter: AdapterView<*>?, view: View?, position: Int, id: Long) {
UnitsSelectedHolder.fromUnit = typeUnits?.get(position)
notifyChange()
}
}
object UnitsSelectedHolder {
var fromUnit: NamedUnit? = null
var toUnit: NamedUnit? = null
fun clear() {
fromUnit = null
toUnit = null
}
}
| apache-2.0 | b01fcc764a8fba0ae87663bcfddff482 | 27.604651 | 95 | 0.738211 | 4.046053 | false | false | false | false |
android/xAnd11 | core/src/main/java/com/monksanctum/xand11/core/comm/ServerListener.kt | 1 | 2177 | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.monksanctum.xand11.comm
import org.monksanctum.xand11.core.COMM_DEBUG
import org.monksanctum.xand11.core.IOException
import org.monksanctum.xand11.core.Platform
import org.monksanctum.xand11.core.ServerSocket
/**
* Manages the [ServerSocket] and creates a new [ClientListener]
* for each connection.
*/
class ServerListener(private val mPort: Int, private val mManager: ClientManager) {
private var mSocket: ServerSocket? = null
private var mRunning: Boolean = false
init {
if (DEBUG) Platform.logd(TAG, "Create: $mPort")
}
public fun run() {
if (DEBUG) Platform.logd(TAG, "run")
try {
mSocket = ServerSocket(mPort)
while (mRunning) {
if (DEBUG) Platform.logd(TAG, "Waiting for connection")
val connection = mSocket!!.accept()
mManager.addClient(connection)
}
} catch (e: IOException) {
if (DEBUG) Platform.loge(TAG, "IOException", e)
}
}
fun open() {
if (DEBUG) Platform.logd(TAG, "open")
mRunning = true
Platform.startThread(this::run)
}
fun close() {
if (DEBUG) Platform.logd(TAG, "close")
mRunning = false
if (mSocket != null) {
try {
mSocket!!.close()
} catch (e: IOException) {
}
}
}
companion object {
private val TAG = "ServerListener"
private val DEBUG = COMM_DEBUG
}
}
| apache-2.0 | 3fdd931adae619ca1ff0112690f19241 | 27.418919 | 83 | 0.604961 | 4.138783 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/macros/tt/TokenTree.kt | 2 | 2409 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.macros.tt
import org.rust.lang.core.macros.tt.Spacing.Alone
import org.rust.lang.core.psi.MacroBraces
/**
* [TokenTree] is a kind of AST used to communicate with Rust procedural macros.
*
* A procedural macro (defined in terms of [TokenTree]s) is a function that accepts a [TokenTree] and
* returns a [TokenTree].
*/
sealed class TokenTree {
sealed class Leaf: TokenTree() {
abstract val id: TokenId
data class Literal(
val text: String,
override val id: TokenId
): Leaf()
data class Punct(
val char: String,
val spacing: Spacing,
override val id: TokenId
): Leaf()
data class Ident(
val text: String,
override val id: TokenId
): Leaf()
}
data class Subtree(
val delimiter: Delimiter?,
val tokenTrees: List<TokenTree>
): TokenTree()
}
typealias TokenId = Int
/**
* Specifies whether there is a space **after** a [TokenTree.Leaf.Punct].
* The last token is always [Alone]
*/
enum class Spacing {
Alone, Joint
}
data class Delimiter(
val id: TokenId,
val kind: MacroBraces
)
fun TokenTree.toDebugString(): String {
val sb = StringBuilder()
debugPrintTokenTree(sb, 0)
return sb.toString()
}
private fun TokenTree.debugPrintTokenTree(sb: StringBuilder, level: Int) {
sb.append(" ".repeat(level)) // Alignment
when (this) {
is TokenTree.Leaf -> debugPrintLeaf(sb)
is TokenTree.Subtree -> debugPrintSubtree(sb, level)
}
}
private fun TokenTree.Subtree.debugPrintSubtree(sb: StringBuilder, level: Int) {
val aux = if (delimiter == null) {
"$"
} else {
"${delimiter.kind.openText}${delimiter.kind.closeText} ${delimiter.id}"
}
sb.append("SUBTREE $aux")
for (tokenTree in this.tokenTrees) {
sb.append("\n")
tokenTree.debugPrintTokenTree(sb, level + 1)
}
}
private fun TokenTree.Leaf.debugPrintLeaf(sb: StringBuilder) {
when (this) {
is TokenTree.Leaf.Literal -> sb.append("LITERAL $text $id")
is TokenTree.Leaf.Punct -> sb.append("PUNCT $char [${spacing.toString().lowercase()}] $id")
is TokenTree.Leaf.Ident -> sb.append("IDENT $text $id")
}
}
| mit | 2087a3e7a70330569f25168b82f36b1a | 25.184783 | 101 | 0.628061 | 3.689127 | false | false | false | false |
mickele/DBFlow | dbflow-processor/src/main/java/com/raizlabs/android/dbflow/processor/definition/TableDefinition.kt | 1 | 29301 | package com.raizlabs.android.dbflow.processor.definition
import com.google.common.collect.Lists
import com.google.common.collect.Maps
import com.raizlabs.android.dbflow.annotation.*
import com.raizlabs.android.dbflow.processor.*
import com.raizlabs.android.dbflow.processor.definition.column.ColumnDefinition
import com.raizlabs.android.dbflow.processor.definition.column.ForeignKeyColumnDefinition
import com.raizlabs.android.dbflow.processor.utils.ElementUtility
import com.raizlabs.android.dbflow.processor.utils.ModelUtils
import com.raizlabs.android.dbflow.processor.utils.isNullOrEmpty
import com.raizlabs.android.dbflow.sql.QueryBuilder
import com.squareup.javapoet.*
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.Modifier
import javax.lang.model.element.TypeElement
import javax.lang.model.type.MirroredTypeException
/**
* Description: Used in writing ModelAdapters
*/
class TableDefinition(manager: ProcessorManager, element: TypeElement) : BaseTableDefinition(element, manager) {
var tableName: String? = null
var databaseTypeName: TypeName? = null
var insertConflictActionName: String = ""
var updateConflictActionName: String = ""
var primaryKeyConflictActionName: String = ""
var _primaryColumnDefinitions: MutableList<ColumnDefinition>
var foreignKeyDefinitions: MutableList<ForeignKeyColumnDefinition>
var uniqueGroupsDefinitions: MutableList<UniqueGroupsDefinition>
var indexGroupsDefinitions: MutableList<IndexGroupsDefinition>
var implementsContentValuesListener = false
var implementsSqlStatementListener = false
var implementsLoadFromCursorListener = false
private val methods: Array<MethodDefinition>
var cachingEnabled = false
var cacheSize: Int = 0
var customCacheFieldName: String? = null
var customMultiCacheFieldName: String? = null
var allFields = false
var useIsForPrivateBooleans: Boolean = false
val columnMap: MutableMap<String, ColumnDefinition> = Maps.newHashMap<String, ColumnDefinition>()
var columnUniqueMap: MutableMap<Int, MutableList<ColumnDefinition>>
= Maps.newHashMap<Int, MutableList<ColumnDefinition>>()
var oneToManyDefinitions: MutableList<OneToManyDefinition> = ArrayList()
var inheritedColumnMap: MutableMap<String, InheritedColumn> = HashMap()
var inheritedFieldNameList: MutableList<String> = ArrayList()
var inheritedPrimaryKeyMap: MutableMap<String, InheritedPrimaryKey> = HashMap()
init {
_primaryColumnDefinitions = ArrayList<ColumnDefinition>()
foreignKeyDefinitions = ArrayList<ForeignKeyColumnDefinition>()
uniqueGroupsDefinitions = ArrayList<UniqueGroupsDefinition>()
indexGroupsDefinitions = ArrayList<IndexGroupsDefinition>()
val table = element.getAnnotation(Table::class.java)
if (table != null) {
this.tableName = table.name
if (tableName == null || tableName!!.isEmpty()) {
tableName = element.simpleName.toString()
}
try {
table.database
} catch (mte: MirroredTypeException) {
databaseTypeName = TypeName.get(mte.typeMirror)
}
cachingEnabled = table.cachingEnabled
cacheSize = table.cacheSize
orderedCursorLookUp = table.orderedCursorLookUp
assignDefaultValuesFromCursor = table.assignDefaultValuesFromCursor
allFields = table.allFields
useIsForPrivateBooleans = table.useBooleanGetterSetters
elementClassName?.let { databaseTypeName?.let { it1 -> manager.addModelToDatabase(it, it1) } }
val inheritedColumns = table.inheritedColumns
inheritedColumns.forEach {
if (inheritedFieldNameList.contains(it.fieldName)) {
manager.logError("A duplicate inherited column with name %1s was found for %1s",
it.fieldName, tableName)
}
inheritedFieldNameList.add(it.fieldName)
inheritedColumnMap.put(it.fieldName, it)
}
val inheritedPrimaryKeys = table.inheritedPrimaryKeys
inheritedPrimaryKeys.forEach {
if (inheritedFieldNameList.contains(it.fieldName)) {
manager.logError("A duplicate inherited column with name %1s was found for %1s",
it.fieldName, tableName)
}
inheritedFieldNameList.add(it.fieldName)
inheritedPrimaryKeyMap.put(it.fieldName, it)
}
implementsLoadFromCursorListener = ProcessorUtils.implementsClass(manager.processingEnvironment,
ClassNames.LOAD_FROM_CURSOR_LISTENER.toString(), element)
implementsContentValuesListener = ProcessorUtils.implementsClass(manager.processingEnvironment,
ClassNames.CONTENT_VALUES_LISTENER.toString(), element)
implementsSqlStatementListener = ProcessorUtils.implementsClass(manager.processingEnvironment,
ClassNames.SQLITE_STATEMENT_LISTENER.toString(), element)
}
methods = arrayOf(BindToContentValuesMethod(this, true, implementsContentValuesListener),
BindToContentValuesMethod(this, false, implementsContentValuesListener),
BindToStatementMethod(this, true), BindToStatementMethod(this, false),
InsertStatementQueryMethod(this, true), InsertStatementQueryMethod(this, false),
CreationQueryMethod(this), LoadFromCursorMethod(this), ExistenceMethod(this),
PrimaryConditionMethod(this), OneToManyDeleteMethod(this, false),
OneToManyDeleteMethod(this, true),
OneToManySaveMethod(this, OneToManySaveMethod.METHOD_SAVE, false),
OneToManySaveMethod(this, OneToManySaveMethod.METHOD_INSERT, false),
OneToManySaveMethod(this, OneToManySaveMethod.METHOD_UPDATE, false),
OneToManySaveMethod(this, OneToManySaveMethod.METHOD_SAVE, true),
OneToManySaveMethod(this, OneToManySaveMethod.METHOD_INSERT, true),
OneToManySaveMethod(this, OneToManySaveMethod.METHOD_UPDATE, true))
}
override fun prepareForWrite() {
columnDefinitions = ArrayList<ColumnDefinition>()
columnMap.clear()
classElementLookUpMap.clear()
_primaryColumnDefinitions.clear()
uniqueGroupsDefinitions.clear()
indexGroupsDefinitions.clear()
foreignKeyDefinitions.clear()
columnUniqueMap.clear()
oneToManyDefinitions.clear()
customCacheFieldName = null
customMultiCacheFieldName = null
val table = element.getAnnotation(Table::class.java)
if (table != null) {
databaseDefinition = manager.getDatabaseHolderDefinition(databaseTypeName)?.databaseDefinition
if (databaseDefinition == null) {
manager.logError("DatabaseDefinition was null for : $tableName for db type: $databaseTypeName")
}
databaseDefinition?.let {
setOutputClassName(it.classSeparator + DBFLOW_TABLE_TAG)
// globular default
var insertConflict: ConflictAction? = table.insertConflict
if (insertConflict == ConflictAction.NONE && it.insertConflict != ConflictAction.NONE) {
insertConflict = it.insertConflict
}
var updateConflict: ConflictAction? = table.updateConflict
if (updateConflict == ConflictAction.NONE
&& it.updateConflict != ConflictAction.NONE) {
updateConflict = it.updateConflict
}
val primaryKeyConflict = table.primaryKeyConflict
insertConflictActionName = if (insertConflict == ConflictAction.NONE) "" else insertConflict?.name ?: ""
updateConflictActionName = if (updateConflict == ConflictAction.NONE) "" else updateConflict?.name ?: ""
primaryKeyConflictActionName = if (primaryKeyConflict == ConflictAction.NONE) "" else primaryKeyConflict.name
}
typeElement?.let { createColumnDefinitions(it) }
val groups = table.uniqueColumnGroups
var uniqueNumbersSet: MutableSet<Int> = HashSet()
for (uniqueGroup in groups) {
if (uniqueNumbersSet.contains(uniqueGroup.groupNumber)) {
manager.logError("A duplicate unique group with number %1s was found for %1s", uniqueGroup.groupNumber, tableName)
}
val definition = UniqueGroupsDefinition(uniqueGroup)
for (columnDefinition in columnDefinitions) {
if (columnDefinition.uniqueGroups.contains(definition.number)) {
definition.addColumnDefinition(columnDefinition)
}
}
uniqueGroupsDefinitions.add(definition)
uniqueNumbersSet.add(uniqueGroup.groupNumber)
}
val indexGroups = table.indexGroups
uniqueNumbersSet = HashSet<Int>()
for (indexGroup in indexGroups) {
if (uniqueNumbersSet.contains(indexGroup.number)) {
manager.logError(TableDefinition::class, "A duplicate unique index number %1s was found for %1s", indexGroup.number, elementName)
}
val definition = IndexGroupsDefinition(this, indexGroup)
columnDefinitions.forEach {
if (it.indexGroups.contains(definition.indexNumber)) {
definition.columnDefinitionList.add(it)
}
}
indexGroupsDefinitions.add(definition)
uniqueNumbersSet.add(indexGroup.number)
}
}
}
override fun createColumnDefinitions(typeElement: TypeElement) {
val elements = ElementUtility.getAllElements(typeElement, manager)
for (element in elements) {
classElementLookUpMap.put(element.simpleName.toString(), element)
}
val columnValidator = ColumnValidator()
val oneToManyValidator = OneToManyValidator()
elements.forEach { element ->
// no private static or final fields for all columns, or any inherited columns here.
val isAllFields = ElementUtility.isValidAllFields(allFields, element)
// package private, will generate helper
val isPackagePrivate = ElementUtility.isPackagePrivate(element)
val isPackagePrivateNotInSamePackage = isPackagePrivate && !ElementUtility.isInSamePackage(manager, element, this.element)
val isForeign = element.getAnnotation(ForeignKey::class.java) != null
val isPrimary = element.getAnnotation(PrimaryKey::class.java) != null
val isInherited = inheritedColumnMap.containsKey(element.simpleName.toString())
val isInheritedPrimaryKey = inheritedPrimaryKeyMap.containsKey(element.simpleName.toString())
if (element.getAnnotation(Column::class.java) != null || isForeign || isPrimary
|| isAllFields || isInherited || isInheritedPrimaryKey) {
val columnDefinition: ColumnDefinition
if (isInheritedPrimaryKey) {
val inherited = inheritedPrimaryKeyMap[element.simpleName.toString()]
columnDefinition = ColumnDefinition(manager, element, this, isPackagePrivateNotInSamePackage,
inherited?.column, inherited?.primaryKey)
} else if (isInherited) {
val inherited = inheritedColumnMap[element.simpleName.toString()]
columnDefinition = ColumnDefinition(manager, element, this, isPackagePrivateNotInSamePackage,
inherited?.column, null)
} else if (isForeign) {
columnDefinition = ForeignKeyColumnDefinition(manager, this,
element, isPackagePrivateNotInSamePackage)
} else {
columnDefinition = ColumnDefinition(manager, element,
this, isPackagePrivateNotInSamePackage)
}
if (columnValidator.validate(manager, columnDefinition)) {
columnDefinitions.add(columnDefinition)
columnMap.put(columnDefinition.columnName, columnDefinition)
if (columnDefinition.isPrimaryKey) {
_primaryColumnDefinitions.add(columnDefinition)
} else if (columnDefinition.isPrimaryKeyAutoIncrement) {
autoIncrementColumn = columnDefinition
hasAutoIncrement = true
} else if (columnDefinition.isRowId) {
autoIncrementColumn = columnDefinition
hasRowID = true
}
if (columnDefinition is ForeignKeyColumnDefinition) {
foreignKeyDefinitions.add(columnDefinition)
}
if (!columnDefinition.uniqueGroups.isEmpty()) {
val groups = columnDefinition.uniqueGroups
for (group in groups) {
var groupList: MutableList<ColumnDefinition>? = columnUniqueMap[group]
if (groupList == null) {
groupList = ArrayList<ColumnDefinition>()
columnUniqueMap.put(group, groupList)
}
if (!groupList.contains(columnDefinition)) {
groupList.add(columnDefinition)
}
}
}
if (isPackagePrivate) {
packagePrivateList.add(columnDefinition)
}
}
} else if (element.getAnnotation(OneToMany::class.java) != null) {
val oneToManyDefinition = OneToManyDefinition(element as ExecutableElement, manager)
if (oneToManyValidator.validate(manager, oneToManyDefinition)) {
oneToManyDefinitions.add(oneToManyDefinition)
}
} else if (element.getAnnotation(ModelCacheField::class.java) != null) {
if (!element.modifiers.contains(Modifier.PUBLIC)) {
manager.logError("ModelCacheField must be public from: " + typeElement)
}
if (!element.modifiers.contains(Modifier.STATIC)) {
manager.logError("ModelCacheField must be static from: " + typeElement)
}
if (!customCacheFieldName.isNullOrEmpty()) {
manager.logError("ModelCacheField can only be declared once from: " + typeElement)
} else {
customCacheFieldName = element.simpleName.toString()
}
} else if (element.getAnnotation(MultiCacheField::class.java) != null) {
if (!element.modifiers.contains(Modifier.PUBLIC)) {
manager.logError("MultiCacheField must be public from: " + typeElement)
}
if (!element.modifiers.contains(Modifier.STATIC)) {
manager.logError("MultiCacheField must be static from: " + typeElement)
}
if (!customMultiCacheFieldName.isNullOrEmpty()) {
manager.logError("MultiCacheField can only be declared once from: " + typeElement)
} else {
customMultiCacheFieldName = element.simpleName.toString()
}
}
}
}
override val primaryColumnDefinitions: List<ColumnDefinition>
get() = if (autoIncrementColumn != null) {
Lists.newArrayList(autoIncrementColumn!!)
} else {
_primaryColumnDefinitions
}
override val propertyClassName: ClassName
get() = outputClassName
override val extendsClass: TypeName?
get() = ParameterizedTypeName.get(ClassNames.MODEL_ADAPTER, elementClassName)
override fun onWriteDefinition(typeBuilder: TypeSpec.Builder) {
InternalAdapterHelper.writeGetModelClass(typeBuilder, elementClassName)
InternalAdapterHelper.writeGetTableName(typeBuilder, tableName)
val getAllColumnPropertiesMethod = FieldSpec.builder(
ArrayTypeName.of(ClassNames.IPROPERTY), "ALL_COLUMN_PROPERTIES",
Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
val getPropertiesBuilder = CodeBlock.builder()
val paramColumnName = "columnName"
val getPropertyForNameMethod = MethodSpec.methodBuilder("getProperty")
.addAnnotation(Override::class.java)
.addParameter(ClassName.get(String::class.java), paramColumnName)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.returns(ClassNames.BASE_PROPERTY)
getPropertyForNameMethod.addStatement("\$L = \$T.quoteIfNeeded(\$L)", paramColumnName,
ClassName.get(QueryBuilder::class.java), paramColumnName)
getPropertyForNameMethod.beginControlFlow("switch (\$L) ", paramColumnName)
columnDefinitions.indices.forEach { i ->
if (i > 0) {
getPropertiesBuilder.add(",")
}
val columnDefinition = columnDefinitions[i]
elementClassName?.let { columnDefinition.addPropertyDefinition(typeBuilder, it) }
columnDefinition.addPropertyCase(getPropertyForNameMethod)
columnDefinition.addColumnName(getPropertiesBuilder)
}
getPropertyForNameMethod.beginControlFlow("default: ")
getPropertyForNameMethod.addStatement("throw new \$T(\$S)", IllegalArgumentException::class.java,
"Invalid column name passed. Ensure you are calling the correct table's column")
getPropertyForNameMethod.endControlFlow()
getPropertyForNameMethod.endControlFlow()
getAllColumnPropertiesMethod.initializer("new \$T[]{\$L}", ClassNames.IPROPERTY, getPropertiesBuilder.build().toString())
typeBuilder.addField(getAllColumnPropertiesMethod.build())
// add index properties here
for (indexGroupsDefinition in indexGroupsDefinitions) {
typeBuilder.addField(indexGroupsDefinition.fieldSpec)
}
typeBuilder.addMethod(getPropertyForNameMethod.build())
if (hasAutoIncrement || hasRowID) {
val autoIncrement = autoIncrementColumn
autoIncrement?.let {
InternalAdapterHelper.writeUpdateAutoIncrement(typeBuilder, elementClassName, autoIncrement)
typeBuilder.addMethod(MethodSpec.methodBuilder("getAutoIncrementingId")
.addAnnotation(Override::class.java).addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addParameter(elementClassName, ModelUtils.variable)
.addCode(autoIncrement.getSimpleAccessString())
.returns(ClassName.get(Number::class.java)).build())
typeBuilder.addMethod(MethodSpec.methodBuilder("getAutoIncrementingColumnName")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addStatement("return \$S", QueryBuilder.stripQuotes(autoIncrement.columnName))
.returns(ClassName.get(String::class.java)).build())
}
}
val saveForeignKeyFields = columnDefinitions.filter { (it is ForeignKeyColumnDefinition) && it.saveForeignKeyModel }
.map { it as ForeignKeyColumnDefinition }
if (saveForeignKeyFields.isNotEmpty()) {
val code = CodeBlock.builder()
saveForeignKeyFields.forEach {
it.appendSaveMethod(code)
}
typeBuilder.addMethod(MethodSpec.methodBuilder("saveForeignKeys")
.addAnnotation(Override::class.java).addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addParameter(elementClassName, ModelUtils.variable)
.addParameter(ClassNames.DATABASE_WRAPPER, ModelUtils.wrapper)
.addCode(code.build())
.build())
}
val deleteForeignKeyFields = columnDefinitions.filter { (it is ForeignKeyColumnDefinition) && it.deleteForeignKeyModel }
.map { it as ForeignKeyColumnDefinition }
if (deleteForeignKeyFields.isNotEmpty()) {
val code = CodeBlock.builder()
deleteForeignKeyFields.forEach {
it.appendDeleteMethod(code)
}
typeBuilder.addMethod(MethodSpec.methodBuilder("deleteForeignKeys")
.addAnnotation(Override::class.java).addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addParameter(elementClassName, ModelUtils.variable)
.addParameter(ClassNames.DATABASE_WRAPPER, ModelUtils.wrapper)
.addCode(code.build())
.build())
}
typeBuilder.addMethod(MethodSpec.methodBuilder("getAllColumnProperties")
.addAnnotation(Override::class.java).addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addStatement("return ALL_COLUMN_PROPERTIES", outputClassName)
.returns(ArrayTypeName.of(ClassNames.IPROPERTY)).build())
if (cachingEnabled) {
// TODO: pass in model cache loaders.
val singlePrimaryKey = primaryColumnDefinitions.size == 1
typeBuilder.addMethod(MethodSpec.methodBuilder("createSingleModelLoader")
.addAnnotation(Override::class.java).addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addStatement("return new \$T<>(getModelClass())",
if (singlePrimaryKey)
ClassNames.SINGLE_KEY_CACHEABLE_MODEL_LOADER
else
ClassNames.CACHEABLE_MODEL_LOADER).returns(ClassNames.SINGLE_MODEL_LOADER).build())
typeBuilder.addMethod(MethodSpec.methodBuilder("createListModelLoader")
.addAnnotation(Override::class.java).addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addStatement("return new \$T<>(getModelClass())",
if (singlePrimaryKey)
ClassNames.SINGLE_KEY_CACHEABLE_LIST_MODEL_LOADER
else
ClassNames.CACHEABLE_LIST_MODEL_LOADER).returns(ClassNames.LIST_MODEL_LOADER).build())
typeBuilder.addMethod(MethodSpec.methodBuilder("createListModelSaver")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addStatement("return new \$T<>(getModelSaver())", ClassNames.CACHEABLE_LIST_MODEL_SAVER)
.returns(ParameterizedTypeName.get(ClassNames.CACHEABLE_LIST_MODEL_SAVER,
elementClassName)).build())
typeBuilder.addMethod(MethodSpec.methodBuilder("cachingEnabled")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addStatement("return \$L", true)
.returns(TypeName.BOOLEAN).build())
val primaries = primaryColumnDefinitions
InternalAdapterHelper.writeGetCachingId(typeBuilder, elementClassName, primaries)
val cachingbuilder = MethodSpec.methodBuilder("createCachingColumns").addAnnotation(Override::class.java).addModifiers(Modifier.PUBLIC, Modifier.FINAL)
var columns = "return new String[]{"
primaries.indices.forEach { i ->
val column = primaries[i]
if (i > 0) {
columns += ","
}
columns += "\"" + QueryBuilder.quoteIfNeeded(column.columnName) + "\""
}
columns += "}"
cachingbuilder.addStatement(columns).returns(ArrayTypeName.of(ClassName.get(String::class.java)))
typeBuilder.addMethod(cachingbuilder.build())
if (cacheSize != Table.DEFAULT_CACHE_SIZE) {
typeBuilder.addMethod(MethodSpec.methodBuilder("getCacheSize")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL).addStatement("return \$L", cacheSize)
.returns(TypeName.INT).build())
}
if (!customCacheFieldName.isNullOrEmpty()) {
typeBuilder.addMethod(MethodSpec.methodBuilder("createModelCache")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addStatement("return \$T.\$L", elementClassName, customCacheFieldName)
.returns(ParameterizedTypeName.get(ClassNames.MODEL_CACHE, elementClassName,
WildcardTypeName.subtypeOf(Any::class.java))).build())
}
if (!customMultiCacheFieldName.isNullOrEmpty()) {
typeBuilder.addMethod(MethodSpec.methodBuilder("getCacheConverter")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addStatement("return \$T.\$L", elementClassName, customMultiCacheFieldName)
.returns(ParameterizedTypeName.get(ClassNames.MULTI_KEY_CACHE_CONVERTER,
WildcardTypeName.subtypeOf(Any::class.java))).build())
}
val reloadMethod = MethodSpec.methodBuilder("reloadRelationships")
.addAnnotation(Override::class.java)
.addParameter(elementClassName, ModelUtils.variable)
.addParameter(ClassNames.CURSOR, LoadFromCursorMethod.PARAM_CURSOR)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
val loadStatements = CodeBlock.builder()
val noIndex = AtomicInteger(-1)
if (elementClassName.toString() == "com.raizlabs.android.dbflow.test.container.AIContainerForeign") {
val success = true
}
foreignKeyDefinitions.forEach {
loadStatements.add(it.getLoadFromCursorMethod(false, noIndex))
}
reloadMethod.addCode(loadStatements.build())
typeBuilder.addMethod(reloadMethod.build())
}
val customTypeConverterPropertyMethod = CustomTypeConverterPropertyMethod(this)
customTypeConverterPropertyMethod.addToType(typeBuilder)
val constructorCode = CodeBlock.builder()
constructorCode.addStatement("super(databaseDefinition)")
customTypeConverterPropertyMethod.addCode(constructorCode)
typeBuilder.addMethod(MethodSpec.constructorBuilder()
.addParameter(ClassNames.DATABASE_HOLDER, "holder")
.addParameter(ClassNames.BASE_DATABASE_DEFINITION_CLASSNAME, "databaseDefinition")
.addCode(constructorCode.build()).addModifiers(Modifier.PUBLIC).build())
for (methodDefinition in methods) {
val spec = methodDefinition.methodSpec
if (spec != null) {
typeBuilder.addMethod(spec)
}
}
typeBuilder.addMethod(MethodSpec.methodBuilder("newInstance")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addStatement("return new \$T()", elementClassName)
.returns(elementClassName).build())
if (!updateConflictActionName.isEmpty()) {
typeBuilder.addMethod(MethodSpec.methodBuilder("getUpdateOnConflictAction")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addStatement("return \$T.\$L", ClassNames.CONFLICT_ACTION, updateConflictActionName)
.returns(ClassNames.CONFLICT_ACTION).build())
}
if (!insertConflictActionName.isEmpty()) {
typeBuilder.addMethod(MethodSpec.methodBuilder("getInsertOnConflictAction")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addStatement("return \$T.\$L", ClassNames.CONFLICT_ACTION, insertConflictActionName)
.returns(ClassNames.CONFLICT_ACTION).build())
}
}
companion object {
val DBFLOW_TABLE_TAG = "Table"
}
}
| mit | 4b6ab4ed67b0f064284d53f02b696379 | 48.411467 | 163 | 0.626327 | 5.668601 | false | false | false | false |
brianwernick/ExoMedia | demo/src/main/kotlin/com/devbrackets/android/exomediademo/ui/support/CaptionPopupManager.kt | 1 | 2658 | package com.devbrackets.android.exomediademo.ui.support
import android.util.Log
import android.view.View
import androidx.appcompat.widget.PopupMenu
import com.devbrackets.android.exomedia.core.renderer.RendererType
import com.devbrackets.android.exomedia.ui.widget.VideoView
import com.devbrackets.android.exomediademo.R
class CaptionPopupManager {
companion object {
const val CC_GROUP_INDEX_MOD = 1000
const val CC_DISABLED = -1001
const val CC_DEFAULT = -1000
}
data class CaptionItem(
val id: Int,
val title: String,
val selected: Boolean
)
fun getCaptionItems(videoView: VideoView): List<CaptionItem> {
val trackGroupArray = videoView.availableTracks?.get(RendererType.CLOSED_CAPTION)
if (trackGroupArray == null || trackGroupArray.isEmpty) {
return emptyList()
}
val items = mutableListOf<CaptionItem>()
var trackSelected = false
for (groupIndex in 0 until trackGroupArray.length) {
val selectedIndex = videoView.getSelectedTrackIndex(RendererType.CLOSED_CAPTION, groupIndex)
Log.d("Captions", "Selected Caption Track: $groupIndex | $selectedIndex")
val trackGroup = trackGroupArray.get(groupIndex)
for (index in 0 until trackGroup.length) {
val format = trackGroup.getFormat(index)
// Skip over non text formats.
if (!format.sampleMimeType!!.startsWith("text")) {
continue
}
val title = format.label ?: format.language ?: "${groupIndex.toShort()}:$index"
val itemId = groupIndex * CC_GROUP_INDEX_MOD + index
items.add(CaptionItem(itemId, title, index == selectedIndex))
if (index == selectedIndex) {
trackSelected = true
}
}
}
// Adds "Disabled" and "Auto" options
val rendererEnabled = videoView.isRendererEnabled(RendererType.CLOSED_CAPTION)
items.add(0, CaptionItem(CC_DEFAULT, videoView.context.getString(R.string.auto), rendererEnabled && !trackSelected))
items.add(0, CaptionItem(CC_DISABLED, videoView.context.getString(R.string.disable), !rendererEnabled))
return items
}
fun showCaptionsMenu(items: List<CaptionItem>, button: View, clickListener: PopupMenu.OnMenuItemClickListener) {
val context = button.context
val popupMenu = PopupMenu(context, button)
val menu = popupMenu.menu
// Add Menu Items
items.forEach {
val item = menu.add(0, it.id, 0, it.title)
item.isCheckable = true
if (it.selected) {
item.isChecked = true
}
}
menu.setGroupCheckable(0, true, true)
popupMenu.setOnMenuItemClickListener(clickListener)
popupMenu.show()
}
} | apache-2.0 | c7965da1381c0ddfcc43fbccb130e1d5 | 32.2375 | 120 | 0.697141 | 4.307942 | false | false | false | false |
MoonlightOwl/Yui | src/main/kotlin/totoro/yui/client/Command.kt | 1 | 949 | package totoro.yui.client
/**
* Small utility class containing all useful info about a received command
*/
class Command(val chan: String, val user: String, val original: String) {
companion object {
fun parse(message: String, channel: String, user: String, botName: String): Command? {
return when {
message.startsWith("~") ->
Command(channel, user, message.drop(1))
message.startsWith(botName) ->
Command(channel, user, message.drop(message.indexOfFirst { it.isWhitespace() } + 1))
else ->
null
}
}
}
@Suppress("MemberVisibilityCanPrivate")
private val words = original.split(' ', '\t', '\r', '\n').filterNot { it.isEmpty() }
val name = words.getOrNull(0)
val content = original.drop(name?.length ?: 0).trim()
val args = words.drop(1)
val valid = name != null
}
| mit | 1e88c1edc3779edf4175510ba20aaeca | 34.148148 | 104 | 0.573235 | 4.373272 | false | false | false | false |
solkin/drawa-android | app/src/main/java/com/tomclaw/drawa/share/ShareItem.kt | 1 | 1043 | package com.tomclaw.drawa.share
import android.os.Parcel
import android.os.Parcelable
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
class ShareItem(
val id: Int,
@DrawableRes val image: Int,
@StringRes val title: Int,
@StringRes val description: Int
) : Parcelable {
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeInt(id)
writeInt(image)
writeInt(title)
writeInt(description)
}
override fun describeContents(): Int = 0
companion object CREATOR : Parcelable.Creator<ShareItem> {
override fun createFromParcel(parcel: Parcel): ShareItem {
val id = parcel.readInt()
val image = parcel.readInt()
val title = parcel.readInt()
val description = parcel.readInt()
return ShareItem(id, image, title, description)
}
override fun newArray(size: Int): Array<ShareItem?> {
return arrayOfNulls(size)
}
}
}
| apache-2.0 | 9eafdf4fabb66cc27cbf11b7bb9b2272 | 26.447368 | 71 | 0.63279 | 4.594714 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-okta/src/main/kotlin/org/ccci/gto/android/common/okta/authfoundation/credential/StoredEntries.kt | 1 | 2499 | package org.ccci.gto.android.common.okta.authfoundation.credential
import com.okta.authfoundation.credential.Token
import com.okta.authfoundation.credential.TokenStorage
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
internal class StoredEntries(@SerialName("entries") val entries: List<StoredEntry>) {
@Serializable
internal class StoredEntry(
@SerialName("identifier") val identifier: String,
@SerialName("token") val token: StoredToken?,
@SerialName("tags") val tags: Map<String, String>,
) {
constructor(entry: TokenStorage.Entry) : this(
identifier = entry.identifier,
token = entry.token?.let { StoredToken(it) },
tags = entry.tags
)
fun asEntry() = TokenStorage.Entry(
identifier = identifier,
token = token?.asToken(),
tags = tags
)
}
@Serializable
internal class StoredToken internal constructor(
@SerialName("token_type") val tokenType: String,
@SerialName("expires_in") val expiresIn: Int,
@SerialName("access_token") val accessToken: String,
@SerialName("scope") val scope: String? = null,
@SerialName("refresh_token") val refreshToken: String? = null,
@SerialName("id_token") val idToken: String? = null,
@SerialName("device_secret") val deviceSecret: String? = null,
@SerialName("issued_token_type") val issuedTokenType: String? = null,
) {
constructor(token: Token) : this(
tokenType = token.tokenType,
expiresIn = token.expiresIn,
accessToken = token.accessToken,
scope = token.scope,
refreshToken = token.refreshToken,
idToken = token.idToken,
deviceSecret = token.deviceSecret,
issuedTokenType = token.issuedTokenType
)
fun asToken() = Token(
tokenType = tokenType,
expiresIn = expiresIn,
accessToken = accessToken,
scope = scope,
refreshToken = refreshToken,
idToken = idToken,
deviceSecret = deviceSecret,
issuedTokenType = issuedTokenType,
)
}
internal companion object {
fun from(entries: List<TokenStorage.Entry>) = StoredEntries(entries.map { StoredEntry(it) })
}
fun asTokenStorageEntries(): List<TokenStorage.Entry> = entries.map { it.asEntry() }
}
| mit | 727a2611c9188c43e79b56e305ed2efd | 35.75 | 100 | 0.627451 | 4.76 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-androidx-lifecycle/src/main/kotlin/org/ccci/gto/android/common/androidx/lifecycle/LiveData.kt | 2 | 2822 | package org.ccci.gto.android.common.androidx.lifecycle
import androidx.annotation.MainThread
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
fun <T> LiveData<T>.copyInto(owner: LifecycleOwner, target: MutableLiveData<in T>) =
observe(owner) { target.value = it }
// region Multi-observe
fun <IN1, IN2> LifecycleOwner.observe(
source1: LiveData<IN1>,
source2: LiveData<IN2>,
observer: (IN1, IN2) -> Unit
) = compoundLiveData(source1, source2).observe(this) {
@Suppress("UNCHECKED_CAST")
observer(source1.value as IN1, source2.value as IN2)
}
fun <IN1, IN2, IN3> LifecycleOwner.observe(
source1: LiveData<IN1>,
source2: LiveData<IN2>,
source3: LiveData<IN3>,
observer: (IN1, IN2, IN3) -> Unit
) = compoundLiveData(source1, source2, source3).observe(this) {
@Suppress("UNCHECKED_CAST")
observer(source1.value as IN1, source2.value as IN2, source3.value as IN3)
}
fun <IN1, IN2> observeForever(
source1: LiveData<IN1>,
source2: LiveData<IN2>,
observer: (IN1, IN2) -> Unit
) = compoundLiveData(source1, source2).observeForever {
@Suppress("UNCHECKED_CAST")
observer(source1.value as IN1, source2.value as IN2)
}
fun <IN1, IN2, IN3> observeForever(
source1: LiveData<IN1>,
source2: LiveData<IN2>,
source3: LiveData<IN3>,
observer: (IN1, IN2, IN3) -> Unit
) = compoundLiveData(source1, source2, source3).observeForever {
@Suppress("UNCHECKED_CAST")
observer(source1.value as IN1, source2.value as IN2, source3.value as IN3)
}
internal fun compoundLiveData(vararg input: LiveData<*>): LiveData<Unit> {
val result = MediatorLiveData<Unit>()
val state = object {
val inputInitialized = BooleanArray(input.size) { false }
var isInitialized = false
get() = field || inputInitialized.all { it }.also { field = it }
}
input.forEachIndexed { i, it ->
result.addSource(it) {
state.inputInitialized[i] = true
if (state.isInitialized) result.value = Unit
}
}
return result
}
// endregion Multi-observe
// region observeOnce
@MainThread
inline fun <T> LiveData<T>.observeOnce(owner: LifecycleOwner, crossinline onChanged: (T) -> Unit) =
observeOnceObserver(onChanged).also { observe(owner, it) }
@MainThread
inline fun <T> LiveData<T>.observeOnce(crossinline onChanged: (T) -> Unit) =
observeOnceObserver(onChanged).also { observeForever(it) }
@JvmSynthetic
inline fun <T> LiveData<T>.observeOnceObserver(crossinline onChanged: (T) -> Unit) = object : Observer<T> {
override fun onChanged(t: T) {
onChanged.invoke(t)
removeObserver(this)
}
}
// endregion observeOnce
| mit | 620b439c4e8992a1edce6c4ac19c198a | 32.2 | 107 | 0.698086 | 3.572152 | false | false | false | false |
JakeWharton/Reagent | reagent/common/src/main/kotlin/reagent/operator/minMax.kt | 1 | 1192 | package reagent.operator
import reagent.Observable
import reagent.Task
import kotlin.math.sign
fun <I : Comparable<I>> Observable<I>.max(): Task<I> = ObservableComparing(this, 1, { it })
fun <I : Comparable<I>> Observable<I>.min(): Task<I> = ObservableComparing(this, -1, { it })
fun <I, S : Comparable<S>> Observable<I>.maxBy(selector: (I) -> S): Task<I> = ObservableComparing(this, 1, selector)
fun <I, S : Comparable<S>> Observable<I>.minBy(selector: (I) -> S): Task<I> = ObservableComparing(this, -1, selector)
internal class ObservableComparing<out I, in S : Comparable<S>>(
private val upstream: Observable<I>,
private val order: Int,
private val selector: (I) -> S
): Task<I>() {
@Suppress("UNCHECKED_CAST") // 'max' is set to an R instance before cast occurs.
override suspend fun produce(): I {
var first = true
var max: Any? = null
upstream.subscribe {
if (first) {
max = it
first = false
} else if (selector(it).compareTo(selector(max as I)).sign == order) {
max = it
}
return@subscribe true
}
if (first) {
throw NoSuchElementException("No elements to compare")
}
return max as I
}
}
| apache-2.0 | 266f9de779c80e0632e549dbeac79afd | 33.057143 | 117 | 0.643456 | 3.537092 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/storage/StorageService.kt | 1 | 3945 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.storage
import com.google.gson.reflect.TypeToken
import com.vk.api.sdk.requests.VKRequest
import com.vk.dto.common.id.UserId
import com.vk.sdk.api.GsonHolder
import com.vk.sdk.api.NewApiRequest
import com.vk.sdk.api.base.dto.BaseOkResponse
import com.vk.sdk.api.storage.dto.StorageValue
import kotlin.Int
import kotlin.String
import kotlin.collections.List
class StorageService {
/**
* Returns a value of variable with the name set by key parameter.
*
* @param key
* @param keys
* @param userId
* @return [VKRequest] with [Unit]
*/
fun storageGet(
key: String? = null,
keys: List<String>? = null,
userId: UserId? = null
): VKRequest<List<StorageValue>> = NewApiRequest("storage.get") {
val typeToken = object: TypeToken<List<StorageValue>>() {}.type
GsonHolder.gson.fromJson<List<StorageValue>>(it, typeToken)
}
.apply {
key?.let { addParam("key", it, maxLength = 100) }
keys?.let { addParam("keys", it) }
userId?.let { addParam("user_id", it, min = 0) }
}
/**
* Returns the names of all variables.
*
* @param userId - user id, whose variables names are returned if they were requested with a
* server method.
* @param offset
* @param count - amount of variable names the info needs to be collected from.
* @return [VKRequest] with [Unit]
*/
fun storageGetKeys(
userId: UserId? = null,
offset: Int? = null,
count: Int? = null
): VKRequest<List<String>> = NewApiRequest("storage.getKeys") {
val typeToken = object: TypeToken<List<String>>() {}.type
GsonHolder.gson.fromJson<List<String>>(it, typeToken)
}
.apply {
userId?.let { addParam("user_id", it, min = 0) }
offset?.let { addParam("offset", it, min = 0) }
count?.let { addParam("count", it, min = 0, max = 1000) }
}
/**
* Saves a value of variable with the name set by 'key' parameter.
*
* @param key
* @param value
* @param userId
* @return [VKRequest] with [BaseOkResponse]
*/
fun storageSet(
key: String,
value: String? = null,
userId: UserId? = null
): VKRequest<BaseOkResponse> = NewApiRequest("storage.set") {
GsonHolder.gson.fromJson(it, BaseOkResponse::class.java)
}
.apply {
addParam("key", key, maxLength = 100)
value?.let { addParam("value", it) }
userId?.let { addParam("user_id", it, min = 0) }
}
}
| mit | f50bf90527b2278b94112c42d7312cf3 | 35.869159 | 96 | 0.631939 | 4.050308 | false | false | false | false |
athkalia/Just-Another-Android-App | .teamcity/JustAnotherAndroidApp/Project.kt | 1 | 5631 | package JustAnotherAndroidApp
import JustAnotherAndroidApp.buildTypes.*
import jetbrains.buildServer.configs.kotlin.v2017_2.*
import jetbrains.buildServer.configs.kotlin.v2017_2.Project
import jetbrains.buildServer.configs.kotlin.v2017_2.projectFeatures.VersionedSettings
import jetbrains.buildServer.configs.kotlin.v2017_2.projectFeatures.versionedSettings
object Project : Project({
uuid = "4327d4b5-598e-47df-9a7a-044d28cd1356"
id = "JustAnotherAndroidApp"
parentId = "_Root"
name = "Just Another Android App"
buildType(JustAnotherAndroidApp_DevelopBranchNightlyPipeline)
buildType(JustAnotherAndroidApp_ReleaseBranchToPlaystoreBeta)
buildType(JustAnotherAndroidApp_PullRequestJob)
features {
feature {
id = "PROJECT_EXT_1"
type = "ReportTab"
param("buildTypeId", "JustAnotherAndroidApp_DevelopBranchNightlyPipeline")
param("startPage", "dex_count/debugChart/index.html")
param("revisionRuleName", "lastSuccessful")
param("revisionRuleRevision", "latest.lastSuccessful")
param("title", "Dex Debug method count")
param("type", "ProjectReportTab")
}
feature {
id = "PROJECT_EXT_14"
type = "ReportTab"
param("startPage", "dex_count/debugChart/index.html")
param("title", "Dex Debug method count")
param("type", "BuildReportTab")
}
feature {
id = "PROJECT_EXT_15"
type = "ReportTab"
param("startPage", "dex_count/qaChart/index.html")
param("title", "Dex Qa method count")
param("type", "BuildReportTab")
}
feature {
id = "PROJECT_EXT_16"
type = "ReportTab"
param("startPage", "dex_count/releaseChart/index.html")
param("title", "Dex Release method count")
param("type", "BuildReportTab")
}
feature {
id = "PROJECT_EXT_19"
type = "ReportTab"
param("startPage", "static_analysis/checkstyle/checkstyle.html")
param("title", "Checkstyle Report")
param("type", "BuildReportTab")
}
feature {
id = "PROJECT_EXT_2"
type = "ReportTab"
param("buildTypeId", "JustAnotherAndroidApp_DevelopBranchNightlyPipeline")
param("startPage", "dex_count/qaChart/index.html")
param("revisionRuleName", "lastSuccessful")
param("revisionRuleRevision", "latest.lastSuccessful")
param("title", "Dex Qa method count")
param("type", "ProjectReportTab")
}
feature {
id = "PROJECT_EXT_20"
type = "ReportTab"
param("startPage", "test_results/testDebugUnitTest/index.html")
param("title", "Debug Unit Tests Report")
param("type", "BuildReportTab")
}
feature {
id = "PROJECT_EXT_21"
type = "ReportTab"
param("startPage", "test_results/testQaUnitTest/index.html")
param("title", "Qa Unit Tests Report")
param("type", "BuildReportTab")
}
feature {
id = "PROJECT_EXT_22"
type = "ReportTab"
param("startPage", "test_results/testReleaseUnitTest/index.html")
param("title", "Release Unit Test Report")
param("type", "BuildReportTab")
}
feature {
id = "PROJECT_EXT_24"
type = "ReportTab"
param("startPage", "static_analysis/findbugs/findbugs.html")
param("title", "Findbugs Report")
param("type", "BuildReportTab")
}
feature {
id = "PROJECT_EXT_25"
type = "ReportTab"
param("startPage", "static_analysis/pmd/pmd.html")
param("title", "PMD Report")
param("type", "BuildReportTab")
}
feature {
id = "PROJECT_EXT_26"
type = "ReportTab"
param("startPage", "static_analysis/lint/lint-results.html")
param("title", "Lint")
param("type", "BuildReportTab")
}
feature {
id = "PROJECT_EXT_3"
type = "ReportTab"
param("buildTypeId", "JustAnotherAndroidApp_DevelopBranchNightlyPipeline")
param("startPage", "dex_count/releaseChart/index.html")
param("revisionRuleName", "lastSuccessful")
param("revisionRuleRevision", "latest.lastSuccessful")
param("title", "Dex Release method count")
param("type", "ProjectReportTab")
}
versionedSettings {
id = "PROJECT_EXT_30"
mode = VersionedSettings.Mode.ENABLED
buildSettingsMode = VersionedSettings.BuildSettingsMode.PREFER_SETTINGS_FROM_VCS
rootExtId = "HttpsGithubComAthkaliaJustAnotherAndroidAppGit"
showChanges = true
settingsFormat = VersionedSettings.Format.KOTLIN
storeSecureParamsOutsideOfVcs = true
}
feature {
id = "PROJECT_EXT_40"
type = "IssueTracker"
param("secure:password", "")
param("name", "athkalia/Just-Another-Android-App")
param("pattern", """#(\d+)""")
param("authType", "anonymous")
param("repository", "https://github.com/athkalia/Just-Another-Android-App")
param("type", "GithubIssues")
param("secure:accessToken", "")
param("username", "")
}
}
})
| apache-2.0 | 5bf074fc73f7c15ad4d28a5ae46b9bca | 38.65493 | 92 | 0.573078 | 4.365116 | false | true | true | false |
pbauerochse/youtrack-worklog-viewer | common-api/src/main/java/de/pbauerochse/worklogviewer/timereport/TimeRange.kt | 1 | 4859 | package de.pbauerochse.worklogviewer.timereport
import de.pbauerochse.worklogviewer.isSameDayOrAfter
import de.pbauerochse.worklogviewer.isSameDayOrBefore
import java.time.LocalDate
import java.time.Period
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.time.temporal.ChronoField
import java.time.temporal.ChronoUnit
import java.time.temporal.WeekFields
import java.util.*
data class TimeRange(val start: LocalDate, val end: LocalDate) : Iterable<LocalDate> {
val reportName: String = "${start.format(ISO_DATE_FORMATTER)}_${end.format(ISO_DATE_FORMATTER)}"
val formattedForLocale: String = "${start.format(LOCALIZED_FORMATTER)} - ${end.format(LOCALIZED_FORMATTER)}"
override fun toString(): String {
return "${start.format(ISO_DATE_FORMATTER)} - ${end.format(ISO_DATE_FORMATTER)}"
}
fun includes(date: LocalDate): Boolean = date.isSameDayOrAfter(start) && date.isSameDayOrBefore(end)
/**
* Returns the total number of days for this timerange.
* Start and End are both counted as full days (inclusive)
*/
val totalNumberOfDays : Int
get() = Period.between(start, end.plusDays(1)).days
/**
* Iterates over all days covered by this timerange
*/
override fun iterator(): Iterator<LocalDate> {
return TimeRangeIterator(start, end)
}
private class TimeRangeIterator(start : LocalDate, private val end : LocalDate) : Iterator<LocalDate> {
private var nextValue : LocalDate?
init {
require(start.isSameDayOrBefore(end)) { "End must not be before Start" }
nextValue = start
}
override fun hasNext(): Boolean = nextValue != null
override fun next(): LocalDate {
val currentValue = nextValue!!
nextValue = currentValue.plusDays(1).takeIf { it.isSameDayOrBefore(end) }
return currentValue
}
}
companion object {
private val ISO_DATE_FORMATTER = DateTimeFormatter.ISO_DATE
private val LOCALIZED_FORMATTER = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)
@JvmStatic
fun currentMonth(): TimeRange {
val now = LocalDate.now(ZoneId.systemDefault())
val startDate = now.withDayOfMonth(1)
val endDate = now.withDayOfMonth(now.month.length(now.isLeapYear))
return TimeRange(startDate, endDate)
}
@JvmStatic
fun lastMonth(): TimeRange {
val now = LocalDate.now(ZoneId.systemDefault())
val lastMonth = now.minus(1, ChronoUnit.MONTHS)
val firstDayOfMonth = lastMonth.withDayOfMonth(1)
val lastDayOfMonth = lastMonth.withDayOfMonth(lastMonth.month.length(lastMonth.isLeapYear))
return TimeRange(firstDayOfMonth, lastDayOfMonth)
}
@JvmStatic
fun currentWeek(): TimeRange {
val weekFields = WeekFields.of(Locale.getDefault())
val firstDayOfTheWeekForLocale = weekFields.firstDayOfWeek
val lastDayOfTheWeekForLocale = firstDayOfTheWeekForLocale.plus(6)
val now = LocalDate.now(ZoneId.systemDefault())
val endDate = now.with(ChronoField.DAY_OF_WEEK, lastDayOfTheWeekForLocale.value.toLong())
val startDateCandidate = now.with(ChronoField.DAY_OF_WEEK, firstDayOfTheWeekForLocale.value.toLong())
val startDate = if (startDateCandidate.isBefore(endDate)) startDateCandidate else startDateCandidate.minusWeeks(1)
return TimeRange(startDate, endDate)
}
@JvmStatic
fun lastWeek(): TimeRange {
val weekFields = WeekFields.of(Locale.getDefault())
val firstDayOfTheWeekForLocale = weekFields.firstDayOfWeek
val lastDayOfTheWeekForLocale = firstDayOfTheWeekForLocale.plus(6)
val now = LocalDate.now(ZoneId.systemDefault())
val lastWeek = now.minus(1, ChronoUnit.WEEKS)
val startDateCandidate = lastWeek.with(ChronoField.DAY_OF_WEEK, firstDayOfTheWeekForLocale.value.toLong())
val endDate = lastWeek.with(ChronoField.DAY_OF_WEEK, lastDayOfTheWeekForLocale.value.toLong())
val startDate = if (startDateCandidate.isBefore(endDate)) startDateCandidate else startDateCandidate.minusWeeks(1)
return TimeRange(startDate, endDate)
}
@JvmStatic
fun lastTwoWeeks(): TimeRange {
val lastWeek = lastWeek()
val start = lastWeek.start.minusWeeks(1)
val end = lastWeek.end
return TimeRange(start, end)
}
@JvmStatic
fun currentAndLastWeek(): TimeRange {
val start = lastWeek().start
val end = currentWeek().end
return TimeRange(start, end)
}
}
}
| mit | 5550d2e4f63a9bbd2f91ad520b7ee440 | 37.259843 | 126 | 0.668244 | 4.726654 | false | false | false | false |
austinv11/KotBot-IV | Core/src/main/kotlin/com/austinv11/kotbot/core/scripting/ScriptManager.kt | 1 | 4165 | package com.austinv11.kotbot.core.scripting
import com.austinv11.kotbot.core.LOGGER
import nl.komponents.kovenant.task
import org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngineFactory
import sx.blah.discord.api.IDiscordClient
import sx.blah.discord.modules.IModule
import java.io.File
import java.nio.file.FileSystems
import java.nio.file.Path
import java.nio.file.StandardWatchEventKinds
import java.nio.file.WatchService
import java.util.concurrent.atomic.AtomicInteger
import javax.script.ScriptEngine
import kotlin.concurrent.thread
class ScriptManager(val client: IDiscordClient) {
val scriptFactory = KotlinJsr223JvmLocalScriptEngineFactory() //Skipping the indirect invocation from java because the shadow jar breaks the javax service
val engine: ScriptEngine
get() = scriptFactory.scriptEngine
val modulesPath = File("./modules").toPath()
val modules = mutableMapOf<File, IModule>()
val loadedModules: AtomicInteger = AtomicInteger(0)
val totalModules: AtomicInteger = AtomicInteger(0)
init {
val files = modulesPath.toFile().listFiles { dir, name -> return@listFiles name.endsWith(".kts") }
totalModules.set(files.size)
task {
files.forEach {
try {
LOGGER.info("Loading module $it")
loadModule(it)
LOGGER.info("$it successfully loaded!")
} catch (e: Throwable) {
LOGGER.error("Unable to load module $it", e)
}
}
}
//Starting a file watcher to watch for module changes
thread {
val watchService: WatchService = FileSystems.getDefault().newWatchService()
modulesPath.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY)
while (true) {
val key = watchService.take()
key.pollEvents().forEach {
if (it.kind() == StandardWatchEventKinds.OVERFLOW) {
LOGGER.warn("Overflow event received! Ignoring...")
return@forEach
}
val child = it.context() as Path
val filePath = modulesPath.resolve(child)
if (child.toString().endsWith(".kts")) {
if (it.kind() == StandardWatchEventKinds.ENTRY_CREATE) { //Load new module
LOGGER.info("New script detected! Now loading ${child.fileName}")
loadModule(filePath.toFile())
} else if (it.kind() == StandardWatchEventKinds.ENTRY_DELETE) { //Unload module
LOGGER.info("Script deleted! Now unloading ${child.fileName}")
disableModule(filePath.toFile())
} else if (it.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { //Reload module
LOGGER.info("Script modified! Now reloading ${child.fileName}")
disableModule(filePath.toFile())
loadModule(filePath.toFile())
}
}
}
if (!key.isValid)
break
}
}
}
fun loadModule(script: File): IModule {
val module = eval(script) as IModule
client.moduleLoader.loadModule(module)
if (modules.containsKey(script)) {
disableModule(script)
}
modules[script] = module
return module
}
fun disableModule(script: File) {
val module = modules[script]!!
client.moduleLoader.unloadModule(module)
modules.remove(script)
}
fun eval(script: String): Any? {
return engine.eval(script)
}
fun eval(script: File): Any? {
return eval(script.readText())
}
}
| gpl-3.0 | c6a255fe44a197ecd339ad002be39d6b | 38.292453 | 158 | 0.563986 | 5.272152 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/roof_shape/AddRoofShape.kt | 1 | 2909 | package de.westnordost.streetcomplete.quests.roof_shape
import de.westnordost.osmapi.map.MapDataWithGeometry
import de.westnordost.osmapi.map.data.Element
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression
import de.westnordost.streetcomplete.data.meta.CountryInfos
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.osmquest.OsmElementQuestType
class AddRoofShape(private val countryInfos: CountryInfos) : OsmElementQuestType<RoofShape> {
private val filter by lazy { """
ways, relations with (building:levels or roof:levels)
and !roof:shape and !3dr:type and !3dr:roof
and building and building!=no and building!=construction
""".toElementFilterExpression() }
override val commitMessage = "Add roof shapes"
override val wikiLink = "Key:roof:shape"
override val icon = R.drawable.ic_quest_roof_shape
override fun getTitle(tags: Map<String, String>) = R.string.quest_roofShape_title
override fun createForm() = AddRoofShapeForm()
override fun applyAnswerTo(answer: RoofShape, changes: StringMapChangesBuilder) {
changes.add("roof:shape", answer.osmValue)
}
override fun getApplicableElements(mapData: MapDataWithGeometry) =
mapData.filter { element ->
filter.matches(element)
&& isRoofProbablyVisibleFromBelow(element.tags) != false
&& (
element.tags?.get("roof:levels")?.toFloatOrNull() ?: 0f > 0f
|| roofsAreUsuallyFlatAt(element, mapData) == false
)
}
override fun isApplicableTo(element: Element): Boolean? {
if (!filter.matches(element)) return false
if (isRoofProbablyVisibleFromBelow(element.tags) == false) return false
/* if it has 0 roof levels, or the roof levels aren't specified,
the quest should only be shown in certain countries. But whether
the element is in a certain country cannot be ascertained at this point */
if (element.tags?.get("roof:levels")?.toFloatOrNull() ?: 0f == 0f) return null
return true
}
private fun isRoofProbablyVisibleFromBelow(tags: Map<String,String>?): Boolean? {
if (tags == null) return null
val roofLevels = tags["roof:levels"]?.toFloatOrNull() ?: 0f
val buildingLevels = tags["building:levels"]?.toFloatOrNull() ?: return null
if (roofLevels < 0f || buildingLevels < 0f) return null
return buildingLevels / (roofLevels + 2f) < 2f
}
private fun roofsAreUsuallyFlatAt(element: Element, mapData: MapDataWithGeometry): Boolean? {
val center = mapData.getGeometry(element.type, element.id)?.center ?: return null
return countryInfos.get(center.longitude, center.latitude).isRoofsAreUsuallyFlat
}
}
| gpl-3.0 | f1893e248bd5ff2d002df38e05bf617f | 45.174603 | 97 | 0.70471 | 4.496136 | false | false | false | false |
kazhida/kotos2d | src/jp/kazhida/kotos2d/Kotos2dBitmap.kt | 1 | 16666 | package jp.kazhida.kotos2d
import android.content.Context
import com.vlad.android.kotlin.*
import android.graphics.Paint
import android.graphics.Bitmap
import android.graphics.Paint.FontMetricsInt
import android.graphics.Rect
import java.nio.ByteBuffer
import android.graphics.Canvas
import android.graphics.Color
import android.util.Log
import android.graphics.Typeface
import android.graphics.Paint.Align
import android.util.FloatMath
import java.util.LinkedList
import java.nio.ByteOrder
import android.text.TextUtils
import android.text.TextPaint
import java.util.ArrayList
import java.util.LinkedList
/**
* Created by kazhida on 2013/07/29.
*/
public class Kotos2dBitmap {
class object {
private val HORIZONTALALIGN_LEFT = 1
private val HORIZONTALALIGN_RIGHT = 2
private val HORIZONTALALIGN_CENTER = 3
private val VERTICALALIGN_TOP = 1
private val VERTICALALIGN_BOTTOM = 2
private val VERTICALALIGN_CENTER = 3
public var context: Context? = null
private fun nativeInitBitmapDC(width: Int, height: Int, pixels: ByteArray?): Unit {
//todo: native呼び出し
}
public fun createTextBitmap(string: String, fontName: String, fontSize: Int, alignment: Int, width: Int, height: Int) {
createTextBitmapShadowStroke(string, fontName, fontSize,
1.f, 1.f, 1.f,
alignment, width, height,
false, 0.f, 0.f, 0.f,
false, 1.f, 1.f, 1.f, 1.f)
}
public fun createTextBitmapShadowStroke(string: String, fontName: String, fontSize: Int,
fontTintR: Float, fontTintG: Float, fontTintB: Float,
alignment: Int, width: Int, height: Int,
shadow: Boolean, shadowDX: Float, shadowDY: Float, shadowBlur: Float,
stroke: Boolean, strokeR: Float, strokeG: Float, strokeB: Float,
strokeSize: Float) {
val horizontalAlignment = alignment and 15
val verticalAlignment = (alignment shr 4) and 15
val refactoredString = refactorString(string)
val paint = newPaint(fontName, fontSize, horizontalAlignment)
paint.setARGB(255, (255.0 * fontTintR).toInt(),
(255.0 * fontTintG).toInt(),
(255.0 * fontTintB).toInt())
val textProperty = computeTextProperty(refactoredString, width, height, paint)
val bitmapTotalHeight = if (height == 0) {
textProperty.mTotalHeight
} else {
height
}
var bitmapPaddingX: Float = 0.0.toFloat()
var bitmapPaddingY: Float = 0.0.toFloat()
var renderTextDeltaX: Float = 0.0.toFloat()
var renderTextDeltaY: Float = 0.0.toFloat()
if (shadow) {
var shadowColor: Int = -8553091
paint.setShadowLayer(shadowBlur, shadowDX, shadowDY, shadowColor)
bitmapPaddingX = Math.abs(shadowDX)
bitmapPaddingY = Math.abs(shadowDY)
if (shadowDX < 0.0) {
renderTextDeltaX = bitmapPaddingX
}
if (shadowDY < 0.0) {
renderTextDeltaY = bitmapPaddingY
}
}
val bitmap = Bitmap.createBitmap(textProperty.maxWidth + bitmapPaddingX.toInt(),
bitmapTotalHeight + bitmapPaddingY.toInt(),
Bitmap.Config.ARGB_8888)!!
val canvas = Canvas(bitmap)
val fontMetricsInt = paint.getFontMetricsInt()!!
var y = computeY(fontMetricsInt, height, textProperty.mTotalHeight, verticalAlignment)
for (line : String in textProperty.lines) {
val x = computeX(textProperty.maxWidth, horizontalAlignment)
canvas.drawText(line, x + renderTextDeltaX, y + renderTextDeltaY, paint)
y += textProperty.heightPerLine
}
if (stroke) {
val paintStroke = newPaint(fontName, fontSize, horizontalAlignment)
paintStroke.setStyle(Paint.Style.STROKE)
paintStroke.setStrokeWidth(strokeSize * 0.5.f)
paintStroke.setARGB(255, (strokeR.toInt()) * 255,
(strokeG.toInt()) * 255,
(strokeB.toInt()) * 255)
y = computeY(fontMetricsInt, height, textProperty.mTotalHeight, verticalAlignment)
val lines2: Array<String> = textProperty.lines
for (line: String in lines2)
{
val x = computeX(textProperty.maxWidth, horizontalAlignment)
canvas.drawText(line, x + renderTextDeltaX, y + renderTextDeltaY, paintStroke)
y += textProperty.heightPerLine
}
}
val buf = ByteBuffer.allocate(bitmap.getWidth() * bitmap.getHeight() * 4)
buf.order(ByteOrder.nativeOrder()!!)
bitmap.copyPixelsToBuffer(buf)
nativeInitBitmapDC(bitmap.getWidth(), bitmap.getHeight(), buf.array())
}
private fun newPaint(fontName: String, fontSize: Int, horizontalAlignment: Int): Paint {
val paint: Paint = Paint()
paint.setColor(Color.WHITE)
paint.setTextSize(fontSize.toFloat())
paint.setAntiAlias(true)
if (fontName.endsWith(".ttf")) {
try {
val typeFace: Typeface? = Kotos2dTypefaces.get(context!!, fontName)
paint.setTypeface(typeFace)
} catch (e: Exception) {
Log.e("Cocos2dxBitmap", "error to create ttf type face: " + fontName)
paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL))
}
} else {
paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL))
}
when (horizontalAlignment) {
HORIZONTALALIGN_CENTER -> paint.setTextAlign(Align.CENTER)
HORIZONTALALIGN_RIGHT -> paint.setTextAlign(Align.RIGHT)
else -> paint.setTextAlign(Align.LEFT)
}
return paint
}
private fun computeTextProperty(string: String, width: Int, height: Int, paint: Paint): TextProperty {
val lines = splitString(string, width, height, paint)
val metrics = paint.getFontMetricsInt()!!
val maxContentWidth = if (width != 0) {
width
} else {
var maxWidth = 0
for (line : String in lines) {
val temp = FloatMath.ceil(paint.measureText(line, 0, line.length())).toInt()
if (temp > maxWidth) {
maxWidth = temp
}
}
maxWidth
}
return TextProperty(maxContentWidth, metrics.bottom - metrics.top, lines)
}
private fun computeX(maxWidth: Int, horizontalAlignment: Int): Int {
return when (horizontalAlignment) {
HORIZONTALALIGN_CENTER -> maxWidth / 2
HORIZONTALALIGN_RIGHT -> maxWidth
else -> 0
}
}
private fun computeY(metrics: FontMetricsInt, constrainHeight: Int, totalHeight: Int, verticalAlignment: Int): Int {
return if (constrainHeight > totalHeight) {
when (verticalAlignment) {
VERTICALALIGN_TOP -> -metrics.top
VERTICALALIGN_CENTER -> -metrics.top + (constrainHeight - totalHeight) / 2
VERTICALALIGN_BOTTOM -> -metrics.top + (constrainHeight - totalHeight)
else -> -metrics.top
}
} else {
-metrics.top
}
}
private fun splitString(string: String, maxWidth: Int, maxHeight: Int, paint: Paint): Array<String> {
val lines = string.split("\\n")
val fm = paint.getFontMetricsInt()!!
val heightPerLine = fm.bottom - fm.top
val maxLines = maxHeight / heightPerLine
if (maxWidth != 0) {
return splitWithMaxWidth(maxWidth, maxLines, lines, paint)
} else if (maxHeight != 0 && lines.size > maxLines) {
return Array<String>(maxLines, {(i: Int): String -> lines[i] })
} else {
return lines
}
}
private fun splitWithMaxWidth(maxWidth: Int, maxLines: Int, lines: Array<String>, paint: Paint): Array<String> {
val list = ArrayList<String>()
for (line : String in lines) {
val lineWidth = FloatMath.ceil(paint.measureText(line)).toInt()
if (lineWidth > maxWidth) {
list.addAll(divideStringWithMaxWidth(line, maxWidth, paint))
} else {
list.add(line)
}
if (maxLines > 0 && list.size() >= maxLines) break
}
while (list.size() > maxLines) {
list.remove(list.size() - 1)
}
// Arrayにする
return Array<String>(list.size, {(i: Int): String ->
list.get(i)
})
}
private fun divideStringWithMaxWidth(string: String, maxWidth: Int, paint: Paint): List<String> {
// 要するに、ワードラップして横幅をmaxWidthに納めればいい
val list = ArrayList<String>()
val builder = StringBuilder()
for (c: Char in string) {
val s = builder.toString() + c
if (paint.measureText(s) > maxWidth) {
// 次の文字を加えたらmaxWidthを超えちゃう
val idx = builder.lastIndexOf(" ")
if (idx < 0) {
// 空白がないので、ここまでで切る
list.add(builder.toString())
builder.delete(0, builder.length - 1)
} else {
// 空白のところで切る(ワードラップ)
list.add(builder.substring(0, idx))
builder.delete(0, idx)
}
}
builder.append(c)
}
if (builder.length > 0) list.add(builder.toString())
return list
// val charLength = string.length()
// var start = 0
// var tempWidth = 0
//
// {
// var i : Int = 1
// while (i <= charLength)
// {
// {
// tempWidth = (FloatMath.ceil((paint?.measureText(string, start, i))!!) as Int)
// if (tempWidth >= maxWidth)
// {
// val lastIndexOfSpace : Int = string?.substring(0, i)?.lastIndexOf(" ")!!
// if (lastIndexOfSpace != -1 && lastIndexOfSpace > start)
// {
// strList?.add(string?.substring(start, lastIndexOfSpace))
// i = lastIndexOfSpace + 1
// }
// else
// {
// if (tempWidth > maxWidth)
// {
// strList?.add(string?.substring(start, i - 1))
// --i
// }
// else
// {
// strList?.add(string?.substring(start, i))
// }
// }
// while ((string?.charAt(i))!! == ' ')
// {
// ++i
// }
// start = i
// }
//
// }
// {
// ++i
// }
// }
// }
// if (start < charLength) {
// list.add(string.substring(start))
// }
//
// return list
}
private fun refactorString(string: String): String {
// 要するに空行に、空白を一つ入れればいいんでしょ
val builder = StringBuilder()
for (line: String in string.split("\n")) {
if (line.length == 0) {
builder.append(" ")
} else {
builder.append(line)
}
builder.append("\n")
}
return builder.toString()
// if (string.length() == 0) {
// return " "
// } else {
// val strBuilder = StringBuilder(string)
// var start : Int = 0
// var index : Int = strBuilder.indexOf("\n")
// while (index != -1) {
// if (index == 0 || strBuilder.charAt(index - 1) == '\n') {
// // 最初の改行あるいは改行のあとの改行
// strBuilder.insert(start, " ")
// start = index + 2
// } else {
// start = index + 1
// }
// if (start > (strBuilder.length()) || index == strBuilder.length()) {
// break
// }
//
// index = strBuilder.indexOf("\n", start)
// }
// return strBuilder.toString()
// }
}
// private fun getFontSizeAccordingHeight(height: Int): Int {
// var paint = Paint()
// var bounds = Rect()
// paint.setTypeface(Typeface.DEFAULT)
//
// var incr_text_size = 1
// var found_desired_size = false
//
// while (!found_desired_size) {
// paint.setTextSize((incr_text_size).f())
//
// var text = "SghMNy"
// paint.getTextBounds(text, 0, text.length(), bounds)
//
// incr_text_size++
// if (height - bounds.height() <= 2) {
// found_desired_size = true
// }
//
// Log.d("font size", "incr size:" + incr_text_size)
// }
// return incr_text_size
// }
//
// private fun getStringWithEllipsis(pString : String, width : Float, fontSize : Float) : String {
// if (TextUtils.isEmpty(pString)) {
// return ""
// }
//
// var paint : TextPaint? = TextPaint()
// paint?.setTypeface(Typeface.DEFAULT)
// paint?.setTextSize(fontSize)
//
// return TextUtils.ellipsize(pString, paint, width, TextUtils.TruncateAt.END)?.toString()
// }
private class TextProperty(val maxWidth: Int, val heightPerLine: Int, val lines: Array<String>) {
val mTotalHeight: Int = heightPerLine * lines.size
}
}
} | mit | c596aff54e1c822aa2ba0f947b6e481b | 41.353093 | 127 | 0.450158 | 5.068476 | false | false | false | false |
Akjir/WiFabs | src/main/kotlin/net/kejira/wifabs/ui/fabric/FabricDetailsView.kt | 1 | 4598 | /*
* Copyright (c) 2017 Stefan Neubert
*
* 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 net.kejira.wifabs.ui.fabric
import javafx.geometry.Insets
import javafx.scene.control.*
import javafx.scene.layout.VBox
import net.kejira.wifabs.IMAGE_SIZE_PREVIEW
import net.kejira.wifabs.SelectedFabricChanged
import net.kejira.wifabs.SelectedFabricEdited
import net.kejira.wifabs.fabric.Fabric
import tornadofx.*
class FabricDetailsView: View() {
private val l_name = Label()
private val l_designer = Label()
private val l_manufacturer = Label()
private val l_location = Label()
private val l_suitable = Label()
private var ta_notice: TextArea by singleAssign()
private var tp_parts : TitledPane by singleAssign()
private var p_parts : VBox by singleAssign()
override val root = Accordion()
init {
subscribe<SelectedFabricChanged> { set(it.fabric) }
subscribe<SelectedFabricEdited> { set(it.fabric) }
ta_notice = textarea {
maxWidth = IMAGE_SIZE_PREVIEW
prefHeight = 20000.0
isEditable = false
isWrapText = true
}
p_parts = vbox(10.0) {
padding = Insets(10.0)
}
val sp = ScrollPane(p_parts)
sp.prefHeight = 20000.0
tp_parts = TitledPane("Stoffteile", sp)
val p_data = gridpane {
prefHeight = 20000.0
padding = Insets(10.0)
hgap = 5.0
add(Label("Name:") , 0, 0)
add(Label("Designer:") , 0, 1)
add(Label("Hersteller:") , 0, 2)
add(Label("Ort:") , 0, 3)
add(Label("Geeigent für:"), 0, 4)
add(l_name , 1, 0)
add(l_designer , 1, 1)
add(l_manufacturer, 1, 2)
add(l_location , 1, 3)
add(l_suitable , 1, 4)
}
with(root) {
panes.addAll(
TitledPane("Details", p_data),
tp_parts,
TitledPane("Notiz", ta_notice)
)
expandedPane = panes[0]
/* prevent complete closing */
expandedPaneProperty().addListener({ _, old_pane, _ ->
var expand = true
panes.iterator().forEach { pane ->
if (pane.isExpanded) expand = false
}
if (expand && old_pane != null) {
expandedPane = old_pane
}
})
}
}
private fun clear() {
l_name .text = ""
l_designer .text = ""
l_manufacturer.text = ""
l_location .text = ""
l_suitable .text = ""
ta_notice .clear()
tp_parts.text = "Stoffteile"
p_parts.children.clear()
}
private fun set(fabric: Fabric?) {
if (fabric != null) {
l_name .text = fabric.name
l_designer .text = fabric.designer
l_manufacturer.text = fabric.manufacturer
l_location .text = fabric.location
ta_notice .text = fabric.notice
tp_parts.text = "Stoffteile (${ fabric.parts.size })"
if (fabric.parts.isEmpty()) {
p_parts.children.clear()
} else {
val list = fabric.parts.map { FabricPartBox(it, editable = false) }
p_parts.children.setAll(list)
}
} else {
clear()
}
}
} | mit | 2b89fa733307793a20d80e78b59c52b9 | 32.318841 | 83 | 0.566456 | 4.213566 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/exh/metadata/metadata/PervEdenSearchMetadata.kt | 1 | 3044 | package exh.metadata.metadata
import android.net.Uri
import eu.kanade.tachiyomi.source.model.SManga
import exh.PERV_EDEN_EN_SOURCE_ID
import exh.PERV_EDEN_IT_SOURCE_ID
import exh.metadata.metadata.base.RaisedSearchMetadata
import exh.metadata.metadata.base.RaisedTitle
import exh.plusAssign
class PervEdenSearchMetadata : RaisedSearchMetadata() {
var pvId: String? = null
var url: String? = null
var thumbnailUrl: String? = null
var title by titleDelegate(TITLE_TYPE_MAIN)
var altTitles
get() = titles.filter { it.type == TITLE_TYPE_ALT }.map { it.title }
set(value) {
titles.removeAll { it.type == TITLE_TYPE_ALT }
titles += value.map { RaisedTitle(it, TITLE_TYPE_ALT) }
}
var artist: String? = null
var type: String? = null
var rating: Float? = null
var status: String? = null
var lang: String? = null
override fun copyTo(manga: SManga) {
url?.let { manga.url = it }
thumbnailUrl?.let { manga.thumbnail_url = it }
val titleDesc = StringBuilder()
title?.let {
manga.title = it
titleDesc += "Title: $it\n"
}
if(altTitles.isNotEmpty())
titleDesc += "Alternate Titles: \n" + altTitles
.joinToString(separator = "\n", postfix = "\n") {
"▪ $it"
}
val detailsDesc = StringBuilder()
artist?.let {
manga.artist = it
detailsDesc += "Artist: $it\n"
}
type?.let {
detailsDesc += "Type: $it\n"
}
status?.let {
manga.status = when(it) {
"Ongoing" -> SManga.ONGOING
"Completed", "Suspended" -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
detailsDesc += "Status: $it\n"
}
rating?.let {
detailsDesc += "Rating: %.2\n".format(it)
}
//Copy tags -> genres
manga.genre = tagsToGenreString()
val tagsDesc = tagsToDescription()
manga.description = listOf(titleDesc.toString(), detailsDesc.toString(), tagsDesc.toString())
.filter(String::isNotBlank)
.joinToString(separator = "\n")
}
companion object {
private const val TITLE_TYPE_MAIN = 0
private const val TITLE_TYPE_ALT = 1
const val TAG_TYPE_DEFAULT = 0
private fun splitGalleryUrl(url: String)
= url.let {
Uri.parse(it).pathSegments.filterNot(String::isNullOrBlank)
}
fun pvIdFromUrl(url: String) = splitGalleryUrl(url).last()
}
}
enum class PervEdenLang(val id: Long) {
//DO NOT RENAME THESE TO CAPITAL LETTERS! The enum names are used to build URLs
en(PERV_EDEN_EN_SOURCE_ID),
it(PERV_EDEN_IT_SOURCE_ID);
companion object {
fun source(id: Long)
= values().find { it.id == id }
?: throw IllegalArgumentException("Unknown source ID: $id!")
}
}
| apache-2.0 | b8a80fdb752124298487ab03851371f2 | 26.908257 | 101 | 0.567719 | 4.018494 | false | false | false | false |
Commit451/GitLabAndroid | app/src/main/java/com/commit451/gitlab/viewHolder/BranchViewHolder.kt | 2 | 1234 | package com.commit451.gitlab.viewHolder
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.commit451.addendum.recyclerview.bindView
import com.commit451.addendum.recyclerview.context
import com.commit451.addendum.themeAttrColor
import com.commit451.gitlab.R
import com.commit451.gitlab.model.api.Branch
/**
* Label
*/
class BranchViewHolder(view: View) : RecyclerView.ViewHolder(view) {
companion object {
fun inflate(parent: ViewGroup): BranchViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_branch, parent, false)
return BranchViewHolder(view)
}
}
private val textTitle: TextView by bindView(R.id.title)
private var colorHighlighted: Int = 0
init {
colorHighlighted = context.themeAttrColor(R.attr.colorControlHighlight)
}
fun bind(branch: Branch, selected: Boolean) {
textTitle.text = branch.name
if (selected) {
itemView.setBackgroundColor(colorHighlighted)
} else {
itemView.background = null
}
}
}
| apache-2.0 | 3a32eda52240bb6fb457cd097ef2ef9d | 27.045455 | 79 | 0.705024 | 4.360424 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt | 1 | 5304 | package info.nightscout.androidaps.plugins.source
import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.database.transactions.CgmSourceTransaction
import info.nightscout.androidaps.interfaces.BgSource
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.receivers.DataWorker
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.XDripBroadcast
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.shared.sharedPreferences.SP
import org.json.JSONArray
import org.json.JSONException
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class MM640gPlugin @Inject constructor(
injector: HasAndroidInjector,
rh: ResourceHelper,
aapsLogger: AAPSLogger,
private val sp: SP
) : PluginBase(PluginDescription()
.mainType(PluginType.BGSOURCE)
.fragmentClass(BGSourceFragment::class.java.name)
.pluginIcon(R.drawable.ic_generic_cgm)
.pluginName(R.string.MM640g)
.description(R.string.description_source_mm640g),
aapsLogger, rh, injector
), BgSource {
// cannot be inner class because of needed injection
class MM640gWorker(
context: Context,
params: WorkerParameters
) : Worker(context, params) {
@Inject lateinit var mM640gPlugin: MM640gPlugin
@Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var dataWorker: DataWorker
@Inject lateinit var repository: AppRepository
@Inject lateinit var xDripBroadcast: XDripBroadcast
init {
(context.applicationContext as HasAndroidInjector).androidInjector().inject(this)
}
override fun doWork(): Result {
var ret = Result.success()
if (!mM640gPlugin.isEnabled()) return Result.success()
val collection = inputData.getString("collection") ?: return Result.failure(workDataOf("Error" to "missing collection"))
if (collection == "entries") {
val data = inputData.getString("data")
aapsLogger.debug(LTag.BGSOURCE, "Received MM640g Data: $data")
if (data != null && data.isNotEmpty()) {
try {
val glucoseValues = mutableListOf<CgmSourceTransaction.TransactionGlucoseValue>()
val jsonArray = JSONArray(data)
for (i in 0 until jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(i)
when (val type = jsonObject.getString("type")) {
"sgv" ->
glucoseValues += CgmSourceTransaction.TransactionGlucoseValue(
timestamp = jsonObject.getLong("date"),
value = jsonObject.getDouble("sgv"),
raw = jsonObject.getDouble("sgv"),
noise = null,
trendArrow = GlucoseValue.TrendArrow.fromString(jsonObject.getString("direction")),
sourceSensor = GlucoseValue.SourceSensor.MM_600_SERIES
)
else -> aapsLogger.debug(LTag.BGSOURCE, "Unknown entries type: $type")
}
}
repository.runTransactionForResult(CgmSourceTransaction(glucoseValues, emptyList(), null))
.doOnError {
aapsLogger.error(LTag.DATABASE, "Error while saving values from Eversense App", it)
ret = Result.failure(workDataOf("Error" to it.toString()))
}
.blockingGet()
.also { savedValues ->
savedValues.all().forEach {
xDripBroadcast.send(it)
aapsLogger.debug(LTag.DATABASE, "Inserted bg $it")
}
}
} catch (e: JSONException) {
aapsLogger.error("Exception: ", e)
ret = Result.failure(workDataOf("Error" to e.toString()))
}
}
}
return ret
}
}
override fun shouldUploadToNs(glucoseValue: GlucoseValue): Boolean =
glucoseValue.sourceSensor == GlucoseValue.SourceSensor.MM_600_SERIES && sp.getBoolean(R.string.key_dexcomg5_nsupload, false)
} | agpl-3.0 | 6c282071604afb302e04f56d8268e185 | 45.946903 | 132 | 0.603695 | 5.37931 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/run/AbstractKotlinTestMethodGradleConfigurationProducer.kt | 4 | 8497 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.gradleJava.run
import com.intellij.execution.Location
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.ConfigurationFromContext
import com.intellij.execution.actions.ConfigurationFromContextImpl
import com.intellij.execution.junit.InheritorChooser
import com.intellij.execution.junit2.PsiMemberParameterizedLocation
import com.intellij.execution.junit2.info.MethodLocation
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import org.jetbrains.kotlin.idea.base.facet.isNewMultiPlatformModule
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.gradle.run.KotlinGradleConfigurationProducer
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer
import org.jetbrains.plugins.gradle.execution.test.runner.applyTestConfiguration
import org.jetbrains.plugins.gradle.service.execution.GradleRunConfiguration
import org.jetbrains.plugins.gradle.util.GradleConstants
import org.jetbrains.plugins.gradle.util.createTestFilterFrom
abstract class AbstractKotlinMultiplatformTestMethodGradleConfigurationProducer : AbstractKotlinTestMethodGradleConfigurationProducer() {
override val forceGradleRunner: Boolean get() = true
override val hasTestFramework: Boolean get() = true
private val mppTestTasksChooser = MultiplatformTestTasksChooser()
abstract fun isApplicable(module: Module, platform: TargetPlatform): Boolean
final override fun isApplicable(module: Module): Boolean {
if (!module.isNewMultiPlatformModule) {
return false
}
val platform = module.platform ?: return false
return isApplicable(module, platform)
}
private fun shouldDisgraceConfiguration(other: ConfigurationFromContext): Boolean {
return other.isJpsJunitConfiguration() ||
(other as? ConfigurationFromContextImpl)?.configurationProducer is TestMethodGradleConfigurationProducer
}
override fun isPreferredConfiguration(self: ConfigurationFromContext, other: ConfigurationFromContext): Boolean {
return shouldDisgraceConfiguration(other)
}
override fun shouldReplace(self: ConfigurationFromContext, other: ConfigurationFromContext): Boolean {
return shouldDisgraceConfiguration(other)
}
override fun onFirstRun(fromContext: ConfigurationFromContext, context: ConfigurationContext, performRunnable: Runnable) {
val psiMethod = fromContext.sourceElement as PsiMethod
val psiClass = psiMethod.containingClass ?: return
val inheritorChooser = object : InheritorChooser() {
override fun runForClasses(classes: List<PsiClass>, method: PsiMethod?, context: ConfigurationContext, runnable: Runnable) {
chooseTestClassConfiguration(fromContext, context, runnable, psiMethod, *classes.toTypedArray())
}
override fun runForClass(aClass: PsiClass, psiMethod: PsiMethod, context: ConfigurationContext, runnable: Runnable) {
chooseTestClassConfiguration(fromContext, context, runnable, psiMethod, aClass)
}
}
if (inheritorChooser.runMethodInAbstractClass(context, performRunnable, psiMethod, psiClass)) return
chooseTestClassConfiguration(fromContext, context, performRunnable, psiMethod, psiClass)
}
override fun getAllTestsTaskToRun(
context: ConfigurationContext,
element: PsiMethod,
chosenElements: List<PsiClass>
): List<TestTasksToRun> {
val tasks = mppTestTasksChooser.listAvailableTasks(listOf(element))
val wildcardFilter = createTestFilterFrom(element.containingClass!!, element)
return tasks.map { TestTasksToRun(it, wildcardFilter) }
}
private fun chooseTestClassConfiguration(
fromContext: ConfigurationFromContext,
context: ConfigurationContext,
performRunnable: Runnable,
psiMethod: PsiMethod,
vararg classes: PsiClass
) {
val dataContext = MultiplatformTestTasksChooser.createContext(context.dataContext, psiMethod.name)
val contextualSuffix = when (context.location) {
is PsiMemberParameterizedLocation -> (context.location as? PsiMemberParameterizedLocation)?.paramSetName?.trim('[', ']')
is MethodLocation -> "jvm" // jvm, being default target, is treated differently
else -> null // from gutters
}
mppTestTasksChooser.multiplatformChooseTasks(context.project, dataContext, classes.asList(), contextualSuffix) { tasks ->
val configuration = fromContext.configuration as GradleRunConfiguration
val settings = configuration.settings
val result = settings.applyTestConfiguration(context.module, tasks, *classes) {
var filters = createTestFilterFrom(context.location, it, psiMethod)
if (context.location is PsiMemberParameterizedLocation && contextualSuffix != null) {
filters = filters.replace("[*$contextualSuffix*]", "")
}
filters
}
settings.externalProjectPath = ExternalSystemApiUtil.getExternalProjectPath(context.module)
if (result) {
configuration.name = (if (classes.size == 1) classes[0].name!! + "." else "") + psiMethod.name
performRunnable.run()
} else {
LOG.warn("Cannot apply method test configuration, uses raw run configuration")
performRunnable.run()
}
}
}
}
abstract class AbstractKotlinTestMethodGradleConfigurationProducer
: TestMethodGradleConfigurationProducer(), KotlinGradleConfigurationProducer {
override fun isConfigurationFromContext(configuration: GradleRunConfiguration, context: ConfigurationContext): Boolean {
if (!context.check()) {
return false
}
if (!forceGradleRunner) {
return super.isConfigurationFromContext(configuration, context)
}
if (GradleConstants.SYSTEM_ID != configuration.settings.externalSystemId) return false
return doIsConfigurationFromContext(configuration, context)
}
override fun setupConfigurationFromContext(
configuration: GradleRunConfiguration,
context: ConfigurationContext,
sourceElement: Ref<PsiElement>
): Boolean {
if (!context.check()) {
return false
}
if (!forceGradleRunner) {
return super.setupConfigurationFromContext(configuration, context, sourceElement)
}
if (GradleConstants.SYSTEM_ID != configuration.settings.externalSystemId) return false
if (sourceElement.isNull) return false
(configuration as? GradleRunConfiguration)?.isScriptDebugEnabled = false
return doSetupConfigurationFromContext(configuration, context, sourceElement)
}
private fun ConfigurationContext.check(): Boolean {
return hasTestFramework && module != null && isApplicable(module)
}
override fun getPsiMethodForLocation(contextLocation: Location<*>) = getTestMethodForKotlinTest(contextLocation)
override fun isPreferredConfiguration(self: ConfigurationFromContext, other: ConfigurationFromContext): Boolean {
return checkShouldReplace(self, other) || super.isPreferredConfiguration(self, other)
}
override fun shouldReplace(self: ConfigurationFromContext, other: ConfigurationFromContext): Boolean {
return checkShouldReplace(self, other) || super.shouldReplace(self, other)
}
private fun checkShouldReplace(self: ConfigurationFromContext, other: ConfigurationFromContext): Boolean {
if (self.isProducedBy(javaClass)) {
if (other.isProducedBy(TestMethodGradleConfigurationProducer::class.java) ||
other.isProducedBy(AbstractKotlinTestClassGradleConfigurationProducer::class.java)
) {
return true
}
}
return false
}
}
| apache-2.0 | f4bc09822da99789e4731efdef8e54e4 | 44.92973 | 158 | 0.728845 | 5.683612 | false | true | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/troika/TroikaTrip.kt | 1 | 2747 | package au.id.micolous.metrodroid.transit.troika
import au.id.micolous.metrodroid.multi.FormattedString
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.Timestamp
import au.id.micolous.metrodroid.transit.Station
import au.id.micolous.metrodroid.transit.TransitCurrency
import au.id.micolous.metrodroid.transit.Trip
import au.id.micolous.metrodroid.util.StationTableReader
// Troika doesn't store monetary price of trip. Only a fare code. So show this fare
// code to the user.
@Parcelize
private class TroikaFare (private val mDesc: String): TransitCurrency(0, "RUB") {
override fun formatCurrencyString(isBalance: Boolean)= FormattedString(mDesc)
}
@Parcelize
internal class TroikaTrip (override val startTimestamp: Timestamp?,
private val mTransportType: TroikaBlock.TroikaTransportType?,
private val mValidator: Int?,
private val mRawTransport: String?,
private val mFareDesc: String?): Trip() {
override val startStation: Station?
get() = if (mValidator == null) null else StationTableReader.getStation(TROIKA_STR, mValidator)
override val fare: TransitCurrency?
get() = if (mFareDesc == null) null else TroikaFare(mFareDesc)
override val mode: Trip.Mode
get() = when (mTransportType) {
null -> Trip.Mode.OTHER
TroikaBlock.TroikaTransportType.NONE, TroikaBlock.TroikaTransportType.UNKNOWN -> Trip.Mode.OTHER
TroikaBlock.TroikaTransportType.SUBWAY -> Trip.Mode.METRO
TroikaBlock.TroikaTransportType.MONORAIL -> Trip.Mode.MONORAIL
TroikaBlock.TroikaTransportType.GROUND -> Trip.Mode.BUS
TroikaBlock.TroikaTransportType.MCC -> Trip.Mode.TRAIN
}
override fun getAgencyName(isShort: Boolean) =
when (mTransportType) {
TroikaBlock.TroikaTransportType.UNKNOWN -> Localizer.localizeFormatted(R.string.unknown)
null, TroikaBlock.TroikaTransportType.NONE -> mRawTransport?.let { FormattedString(it) }
TroikaBlock.TroikaTransportType.SUBWAY -> Localizer.localizeFormatted(R.string.moscow_subway)
TroikaBlock.TroikaTransportType.MONORAIL -> Localizer.localizeFormatted(R.string.moscow_monorail)
TroikaBlock.TroikaTransportType.GROUND -> Localizer.localizeFormatted(R.string.moscow_ground_transport)
TroikaBlock.TroikaTransportType.MCC -> Localizer.localizeFormatted(R.string.moscow_mcc)
}
companion object {
private const val TROIKA_STR = "troika"
}
}
| gpl-3.0 | f3b2471d7ef2bded4a4e57b62e88859a | 48.945455 | 119 | 0.708045 | 4.312402 | false | false | false | false |
Major-/Vicis | legacy/src/main/kotlin/rs/emulate/legacy/widget/WidgetDecoder.kt | 1 | 2227 | package rs.emulate.legacy.widget
import rs.emulate.legacy.archive.Archive
import rs.emulate.legacy.widget.script.LegacyClientScriptCodec
import java.io.FileNotFoundException
import java.util.ArrayList
/**
* Decodes data into [Widget]s.
*
* @param widgets The [Archive] containing the [Widget]s.
* @throws FileNotFoundException If the [data][.DATA_FILE_NAME] file could not be found.
*/
class WidgetDecoder(widgets: Archive) {
/**
* The Archive containing the Widgets.
*/
private val buffer = widgets[DATA_FILE_NAME].buffer
/**
* Decodes the [Widget]s.
*/
fun decode(): List<Widget> {
val widgets = ArrayList<Widget>()
while (buffer.readableBytes() > 0) {
widgets.add(decodeWidget())
}
return widgets
}
/**
* Decodes a single [Widget].
*/
private fun decodeWidget(): Widget {
var id = buffer.readUnsignedShort()
var parent = -1
if (id == CHILD_WIDGET_IDENTIFIER) {
parent = buffer.readUnsignedShort()
id = buffer.readUnsignedShort()
}
val group = WidgetGroup.valueOf(buffer.readUnsignedByte().toInt())
val option = WidgetOption.valueOf(buffer.readUnsignedByte().toInt())
val contentType = buffer.readUnsignedByte()
val width = buffer.readUnsignedShort()
val height = buffer.readUnsignedShort()
val alpha = buffer.readUnsignedByte()
val hoverId = buffer.readUnsignedByte().toInt()
val hover = when (hoverId) {
0 -> hoverId - 1 shl java.lang.Byte.SIZE or buffer.readUnsignedByte().toInt()
else -> null
}
val scripts = LegacyClientScriptCodec.decode(buffer)
return TODO()
}
companion object {
/**
* The identifier that indicates that a Widget has a parent.
*/
private const val CHILD_WIDGET_IDENTIFIER = 65535
/**
* The name of the file containing the Widget data.
*/
private const val DATA_FILE_NAME = "data"
/**
* The amount of sprites used by an [WidgetGroup.INVENTORY] Widget.
*/
private const val SPRITE_COUNT = 20
}
}
| isc | e3ef085a469f180c65263afc5a86e9cd | 25.831325 | 89 | 0.611136 | 4.563525 | false | false | false | false |
nonylene/MackerelAgentAndroid | app/src/main/java/net/nonylene/mackerelagent/utils/OtherUtils.kt | 1 | 795 | package net.nonylene.mackerelagent.utils
import com.google.gson.ExclusionStrategy
import com.google.gson.FieldAttributes
import com.google.gson.GsonBuilder
import net.nonylene.mackerelagent.network.Exclude
import retrofit2.HttpException
fun createErrorMessage(error: Throwable): String? {
return when (error) {
is HttpException -> {
"${error.message} - ${error.response().errorBody()?.string()}"
}
else -> error.message
}
}
val GSON_IGNORE_EXCLUDE_ANNOTATION = GsonBuilder().setExclusionStrategies(object : ExclusionStrategy {
override fun shouldSkipClass(clazz: Class<*>?) = false
override fun shouldSkipField(f: FieldAttributes?) = f?.getAnnotation(Exclude::class.java) != null
}).create()
val MACKEREL_API_DOMAIN = "api.mackerelio.com"
| mit | 16b6e9de1d2960579d5287a4939fde05 | 33.565217 | 102 | 0.72956 | 4.251337 | false | false | false | false |
iMeiji/Daily | app/src/main/java/com/meiji/daily/binder/ZhuanlanViewBinder.kt | 1 | 2414 | package com.meiji.daily.binder
import android.support.v7.widget.CardView
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.meiji.daily.GlideApp
import com.meiji.daily.R
import com.meiji.daily.bean.ZhuanlanBean
import com.meiji.daily.module.postslist.PostsListActivity
import de.hdodenhof.circleimageview.CircleImageView
import kotlinx.android.synthetic.main.item_zhuanlan.view.*
import me.drakeet.multitype.ItemViewBinder
/**
* Created by Meiji on 2017/6/6.
*/
internal class ZhuanlanViewBinder : ItemViewBinder<ZhuanlanBean, ZhuanlanViewBinder.ViewHolder>() {
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): ZhuanlanViewBinder.ViewHolder {
val view = inflater.inflate(R.layout.item_zhuanlan, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ZhuanlanViewBinder.ViewHolder, item: ZhuanlanBean) {
val context = holder.itemView.context
val followersCount = item.followersCount.toString() + "人关注TA"
val postsCount = item.postsCount.toString() + "篇文章"
var avatarUrl = item.avatar.template
if (!TextUtils.isEmpty(avatarUrl)) {
// 拼凑avatar链接
avatarUrl = avatarUrl.replace("{id}", item.avatar.id.toString()).replace("{size}", "m")
GlideApp.with(context)
.load(avatarUrl)
.centerCrop()
.error(R.color.viewBackground)
.into(holder.cv_avatar)
}
holder.tv_name.text = item.name
holder.tv_followersCount.text = followersCount
holder.tv_postsCount.text = postsCount
holder.tv_intro.text = item.intro
holder.cardView.setOnClickListener { PostsListActivity.start(context, item.slug, item.name, item.postsCount) }
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val cardView: CardView = itemView.cardview
val cv_avatar: CircleImageView = itemView.cv_avatar
val tv_name: TextView = itemView.tv_name
val tv_followersCount: TextView = itemView.tv_followersCount
val tv_postsCount: TextView = itemView.tv_postsCount
val tv_intro: TextView = itemView.tv_intro
}
}
| apache-2.0 | 658d016ed27ae0d3288b2a1e7d97c8e5 | 38.245902 | 118 | 0.705096 | 4.17801 | false | false | false | false |
mvmike/min-cal-widget | app/src/test/kotlin/cat/mvmike/minimalcalendarwidget/domain/component/MonthAndYearHeaderServiceTest.kt | 1 | 6886 | // Copyright (c) 2016, Miquel Martí <[email protected]>
// See LICENSE for licensing information
package cat.mvmike.minimalcalendarwidget.domain.component
import android.widget.RemoteViews
import cat.mvmike.minimalcalendarwidget.BaseTest
import cat.mvmike.minimalcalendarwidget.R
import cat.mvmike.minimalcalendarwidget.domain.Format
import cat.mvmike.minimalcalendarwidget.domain.configuration.item.Theme
import cat.mvmike.minimalcalendarwidget.domain.configuration.item.DARK_THEME_MAIN_TEXT_COLOUR
import cat.mvmike.minimalcalendarwidget.domain.configuration.item.LIGHT_THEME_MAIN_TEXT_COLOUR
import cat.mvmike.minimalcalendarwidget.infrastructure.resolver.GraphicResolver.createMonthAndYearHeader
import cat.mvmike.minimalcalendarwidget.infrastructure.resolver.SystemResolver
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.justRun
import io.mockk.mockk
import io.mockk.verify
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import java.time.Instant
import java.time.LocalDateTime
import java.time.Month
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.util.stream.Stream
internal class MonthAndYearHeaderServiceTest : BaseTest() {
private val widgetRv = mockk<RemoteViews>()
@ParameterizedTest
@MethodSource("getSpreadInstantsAndFormatsWithExpectedTextAndColour")
fun draw_shouldAddMonthAndYearWithColourAndRelativeMonthAndYearSize(
instant: Instant,
format: Format,
theme: Theme,
expectedText: String,
expectedTextColour: Int,
) {
val expectedHeaderRelativeYearSize = 0.7f
mockGetSystemInstant(instant)
mockGetSystemZoneId()
mockSharedPreferences()
mockWidgetTheme(theme)
val month = instant.atZone(zoneId).month
every { context.getString(month.getExpectedResourceId()) } returns month.getExpectedAbbreviatedString()
justRun { createMonthAndYearHeader(context, widgetRv, expectedText, expectedTextColour, expectedHeaderRelativeYearSize, format.headerTextRelativeSize) }
MonthAndYearHeaderService.draw(context, widgetRv, format)
verify { SystemResolver.getSystemInstant() }
verify { SystemResolver.getSystemZoneId() }
verify { context.getString(month.getExpectedResourceId()) }
verifyWidgetTheme()
verify { createMonthAndYearHeader(context, widgetRv, expectedText, expectedTextColour, expectedHeaderRelativeYearSize, format.headerTextRelativeSize) }
confirmVerified(widgetRv)
}
@Suppress("UnusedPrivateMember")
private fun getSpreadInstantsAndFormatsWithExpectedTextAndColour() = Stream.of(
Arguments.of("2018-01-26".toInstant(), Format(220), Theme.DARK, "January 2018", DARK_THEME_MAIN_TEXT_COLOUR),
Arguments.of("2018-01-26".toInstant(), Format(150), Theme.DARK, "Jan 2018", DARK_THEME_MAIN_TEXT_COLOUR),
Arguments.of("2005-02-19".toInstant(), Format(220), Theme.DARK, "February 2005", DARK_THEME_MAIN_TEXT_COLOUR),
Arguments.of("2005-02-19".toInstant(), Format(150), Theme.DARK, "Feb 2005", DARK_THEME_MAIN_TEXT_COLOUR),
Arguments.of("2027-03-05".toInstant(), Format(220), Theme.DARK, "March 2027", DARK_THEME_MAIN_TEXT_COLOUR),
Arguments.of("2027-03-05".toInstant(), Format(150), Theme.DARK, "Mar 2027", DARK_THEME_MAIN_TEXT_COLOUR),
Arguments.of("2099-04-30".toInstant(), Format(220), Theme.DARK, "April 2099", DARK_THEME_MAIN_TEXT_COLOUR),
Arguments.of("2099-04-30".toInstant(), Format(150), Theme.DARK, "Apr 2099", DARK_THEME_MAIN_TEXT_COLOUR),
Arguments.of("2000-05-01".toInstant(), Format(220), Theme.DARK, "May 2000", DARK_THEME_MAIN_TEXT_COLOUR),
Arguments.of("2000-05-01".toInstant(), Format(150), Theme.DARK, "May 2000", DARK_THEME_MAIN_TEXT_COLOUR),
Arguments.of("1998-06-02".toInstant(), Format(220), Theme.DARK, "June 1998", DARK_THEME_MAIN_TEXT_COLOUR),
Arguments.of("1998-06-02".toInstant(), Format(150), Theme.DARK, "Jun 1998", DARK_THEME_MAIN_TEXT_COLOUR),
Arguments.of("1992-07-07".toInstant(), Format(220), Theme.LIGHT, "July 1992", LIGHT_THEME_MAIN_TEXT_COLOUR),
Arguments.of("1992-07-07".toInstant(), Format(150), Theme.LIGHT, "Jul 1992", LIGHT_THEME_MAIN_TEXT_COLOUR),
Arguments.of("2018-08-01".toInstant(), Format(220), Theme.LIGHT, "August 2018", LIGHT_THEME_MAIN_TEXT_COLOUR),
Arguments.of("2018-08-01".toInstant(), Format(150), Theme.LIGHT, "Aug 2018", LIGHT_THEME_MAIN_TEXT_COLOUR),
Arguments.of("1987-09-12".toInstant(), Format(220), Theme.LIGHT, "September 1987", LIGHT_THEME_MAIN_TEXT_COLOUR),
Arguments.of("1987-09-12".toInstant(), Format(150), Theme.LIGHT, "Sep 1987", LIGHT_THEME_MAIN_TEXT_COLOUR),
Arguments.of("2017-10-01".toInstant(), Format(220), Theme.LIGHT, "October 2017", LIGHT_THEME_MAIN_TEXT_COLOUR),
Arguments.of("2017-10-01".toInstant(), Format(150), Theme.LIGHT, "Oct 2017", LIGHT_THEME_MAIN_TEXT_COLOUR),
Arguments.of("1000-11-12".toInstant(), Format(220), Theme.LIGHT, "November 1000", LIGHT_THEME_MAIN_TEXT_COLOUR),
Arguments.of("1000-11-12".toInstant(), Format(150), Theme.LIGHT, "Nov 1000", LIGHT_THEME_MAIN_TEXT_COLOUR),
Arguments.of("1994-12-13".toInstant(), Format(220), Theme.LIGHT, "December 1994", LIGHT_THEME_MAIN_TEXT_COLOUR),
Arguments.of("1994-12-13".toInstant(), Format(150), Theme.LIGHT, "Dec 1994", LIGHT_THEME_MAIN_TEXT_COLOUR)
)!!
private fun String.toInstant() = LocalDateTime
.parse(this.plus("T00:00:00Z"), DateTimeFormatter.ISO_ZONED_DATE_TIME)
.toInstant(ZoneOffset.UTC)
private fun Month.getExpectedResourceId() =
when (this) {
Month.JANUARY -> R.string.january
Month.FEBRUARY -> R.string.february
Month.MARCH -> R.string.march
Month.APRIL -> R.string.april
Month.MAY -> R.string.may
Month.JUNE -> R.string.june
Month.JULY -> R.string.july
Month.AUGUST -> R.string.august
Month.SEPTEMBER -> R.string.september
Month.OCTOBER -> R.string.october
Month.NOVEMBER -> R.string.november
Month.DECEMBER -> R.string.december
}
private fun Month.getExpectedAbbreviatedString() =
when (this) {
Month.JANUARY -> "January"
Month.FEBRUARY -> "February"
Month.MARCH -> "March"
Month.APRIL -> "April"
Month.MAY -> "May"
Month.JUNE -> "June"
Month.JULY -> "July"
Month.AUGUST -> "August"
Month.SEPTEMBER -> "September"
Month.OCTOBER -> "October"
Month.NOVEMBER -> "November"
Month.DECEMBER -> "December"
}
}
| bsd-3-clause | f172d19fc7c0008f17f4b5d1f97b9b02 | 54.524194 | 160 | 0.696587 | 3.876689 | false | false | false | false |
google/accompanist | appcompat-theme/src/main/java/com/google/accompanist/appcompattheme/TypedArrayUtils.kt | 1 | 5032 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.accompanist.appcompattheme
import android.annotation.SuppressLint
import android.content.res.Resources
import android.content.res.TypedArray
import android.os.Build
import android.util.TypedValue
import androidx.annotation.RequiresApi
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.font.toFontFamily
import androidx.core.content.res.FontResourcesParserCompat
import androidx.core.content.res.getColorOrThrow
import kotlin.concurrent.getOrSet
private val tempTypedValue = ThreadLocal<TypedValue>()
internal fun TypedArray.getComposeColor(
index: Int,
fallbackColor: Color = Color.Unspecified
): Color = if (hasValue(index)) Color(getColorOrThrow(index)) else fallbackColor
/**
* Returns the given index as a [FontFamily] and [FontWeight],
* or `null` if the value can not be coerced to a [FontFamily].
*
* @param index index of attribute to retrieve.
*/
internal fun TypedArray.getFontFamilyOrNull(index: Int): FontFamilyWithWeight? {
val tv = tempTypedValue.getOrSet(::TypedValue)
if (getValue(index, tv) && tv.type == TypedValue.TYPE_STRING) {
return when (tv.string) {
"sans-serif" -> FontFamilyWithWeight(FontFamily.SansSerif)
"sans-serif-thin" -> FontFamilyWithWeight(FontFamily.SansSerif, FontWeight.Thin)
"sans-serif-light" -> FontFamilyWithWeight(FontFamily.SansSerif, FontWeight.Light)
"sans-serif-medium" -> FontFamilyWithWeight(FontFamily.SansSerif, FontWeight.Medium)
"sans-serif-black" -> FontFamilyWithWeight(FontFamily.SansSerif, FontWeight.Black)
"serif" -> FontFamilyWithWeight(FontFamily.Serif)
"cursive" -> FontFamilyWithWeight(FontFamily.Cursive)
"monospace" -> FontFamilyWithWeight(FontFamily.Monospace)
// TODO: Compose does not expose a FontFamily for all strings yet
else -> {
// If there's a resource ID and the string starts with res/font,
// it's probably a @font resource
if (tv.resourceId != 0 && tv.string.startsWith("res/font")) {
// If we're running on API 23+ and the resource is an XML, we can parse
// the fonts into a full FontFamily.
if (Build.VERSION.SDK_INT >= 23 && tv.string.endsWith(".xml")) {
resources.parseXmlFontFamily(tv.resourceId)?.let(::FontFamilyWithWeight)
} else {
// Otherwise we just load it as a single font
FontFamilyWithWeight(Font(tv.resourceId).toFontFamily())
}
} else null
}
}
}
return null
}
@SuppressLint("RestrictedApi") // FontResourcesParserCompat.*
@RequiresApi(23) // XML font families with >1 fonts are only supported on API 23+
private fun Resources.parseXmlFontFamily(resourceId: Int): FontFamily? {
val parser = getXml(resourceId)
// Can't use {} since XmlResourceParser is AutoCloseable, not Closeable
@Suppress("ConvertTryFinallyToUseCall")
try {
val result = FontResourcesParserCompat.parse(parser, this)
if (result is FontResourcesParserCompat.FontFamilyFilesResourceEntry) {
val fonts = result.entries.map { font ->
Font(
resId = font.resourceId,
weight = fontWeightOf(font.weight),
style = if (font.isItalic) FontStyle.Italic else FontStyle.Normal
)
}
return FontFamily(fonts)
}
} finally {
parser.close()
}
return null
}
private fun fontWeightOf(weight: Int): FontWeight = when (weight) {
in 0..149 -> FontWeight.W100
in 150..249 -> FontWeight.W200
in 250..349 -> FontWeight.W300
in 350..449 -> FontWeight.W400
in 450..549 -> FontWeight.W500
in 550..649 -> FontWeight.W600
in 650..749 -> FontWeight.W700
in 750..849 -> FontWeight.W800
in 850..999 -> FontWeight.W900
// Else, we use the 'normal' weight
else -> FontWeight.W400
}
internal data class FontFamilyWithWeight(
val fontFamily: FontFamily,
val weight: FontWeight = FontWeight.Normal
)
| apache-2.0 | bffde9483565f04f7e8ec45678d69cae | 40.245902 | 96 | 0.67349 | 4.398601 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.