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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/OrderNotesTab.kt | 1 | 3516 | package alraune
import alraune.entity.*
import pieces100.*
import vgrechka.*
class OrderNotesTab(val pedro: OrderPedro_A2) : EntityPageTemplate.Tab {
companion object {
val tabId = "Notes"
}
val params = GetParams()
override fun id() = tabId
override fun title() = t("TOTE", "Заметки")
val juan get() = pedro.juan
override fun addTopRightControls(trc: TopRightControls) {
trc.addButton(FA.plus).whenDomReady_addOnClick(
jsBustOutModal(createOrUpdateOrderUserNoteModal(juan.toLight(), rctx0.al.viewBucketIfAdmin(), note = null)))
}
override fun render(): AlTag {
val order = juan.order
val notes = order.viewBucket().notes
.sortedByDescending {it.time}
if (notes.isEmpty())
return div("Нихрена заметок еще нет...")
return div().with {
for (note in notes) {
oo(div().style("position: relative;").className(AlCSS.pizda1)
.add(div(TimePile.kievTimeString(note.time)).style("font-weight: bold;"))
.add(composePreWrapDiv(note.text))
.add(composeUsualTopRightHamburger {
it.item("Редактировать", FA.pencil).onClick(jsBustOutModal(createOrUpdateOrderUserNoteModal(juan.toLight(), rctx0.al.viewBucketIfAdmin(), note)))
it.item("Убить", FA.trash).onClick(jsBustOutModal(deleteOrderUserNoteModal(juan.toLight(), rctx0.al.viewBucketIfAdmin(), note)))
// it.item("Убить old", FA.trash).withDomid {bustOutKillModalOnClick(
// domid = it,
// modalTitle = "Заебашить заметку?",
// shitTitle = note.text,
// serve = bakeShit3(juan.toLight(), note))}
}))
}
}
}
}
fun deleteOrderUserNoteModal(lej: LightEptJuan, viewBucket: String?, viewNote: Order.UserNote) =
!KillerModal(
modalTitle = "Заебашить заметку?",
shitTitle = viewNote.text,
serveMurder = {
doDeleteOrderUserNote(lej.handle, postBucket(viewBucket), viewNote)
btfEval(lej.jsReload())
})
fun createOrUpdateOrderUserNoteModal(lej: LightEptJuan, bucketName: String?, note: Order.UserNote?): ShitWithContext<ModalShit, Context1> {
return !object : Kate<OrderUserNoteFields>(
modalTitle = "Заметка-ебучка",
submitButtonTitle = AlText.fuckingSubmit,
submitButtonLevel = AlButtonStyle.Primary) {
override fun setInitialFields(fs: OrderUserNoteFields) {
if (note != null) {
fs.accept(
text = {it.set(note.text)})
}
}
override fun serveGivenValidFields(fs: OrderUserNoteFields) {
if (note == null) {
doCreateOrderUserNote(lej.handle, bucketName, fs)
} else {
doUpdateOrderUserNote(lej.handle, bucketName, note, fs)
}
btfEval(lej.jsReload())
}
override fun serveOkButtonForScrewedState() {
btfEval(lej.jsReload())
}
override fun makeFields() = OrderUserNoteFields()
override fun ooModalBody(fs: OrderUserNoteFields) {
OrderUserNoteFields.__version1
oo(fs.text.begin().focused().compose())
}
}
}
| apache-2.0 | adab70ff2ea58c40506760ee754a3c0b | 33.21 | 169 | 0.586086 | 4.131643 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/internal/ShowPoweredProgressAction.kt | 7 | 2734 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.ui.DialogBuilder
import com.intellij.openapi.ui.LabeledComponent
import com.intellij.openapi.util.Ref
import com.intellij.ui.DocumentAdapter
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.TimerUtil
import java.awt.event.ActionEvent
import javax.swing.*
import javax.swing.event.DocumentEvent
internal class ShowPoweredProgressAction : AnAction("Show Powered Progress") {
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun actionPerformed(e: AnActionEvent) {
val builder = DialogBuilder()
builder.addAction(object : AbstractAction("Restart Indicators") {
override fun actionPerformed(e: ActionEvent?) {
}
})
builder.addCancelAction()
val dialogPanel = JPanel()
dialogPanel.layout = BoxLayout(dialogPanel, BoxLayout.Y_AXIS)
val progresses = mutableListOf<JProgressBar>()
val powers = mutableListOf<Ref<Double>>()
val values = mutableListOf<Ref<Int>>()
val MAX = 60000
for (i in 0..2) {
val progress = JProgressBar()
progresses.add(progress)
progress.isIndeterminate = false
progress.minimum = 0
progress.maximum = MAX
dialogPanel.add(Box.createRigidArea(JBDimension(0, 10)))
dialogPanel.add(progress)
dialogPanel.add(Box.createRigidArea(JBDimension(0, 10)))
val power: Ref<Double> = Ref.create((i + 1).toDouble())
val jTextField = JTextField(power.get().toString())
jTextField.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
jTextField.text.toDoubleOrNull()?.let {
power.set(it)
}
}
})
values.add(Ref.create(0))
powers.add(power)
val labeledComponent = LabeledComponent.create(jTextField, "power:")
dialogPanel.add(labeledComponent)
dialogPanel.add(Box.createRigidArea(JBDimension(0, 10)))
}
val timer = TimerUtil.createNamedTimer("progresses", 1) {
for ((index, progress) in progresses.withIndex()) {
values[index].set((values[index].get() + 1) % MAX)
progress.value = (MAX * Math.pow((values[index].get().toDouble() / MAX.toDouble()), powers[index].get())).toInt()
}
}
timer.isRepeats = true
timer.start()
builder.setCenterPanel(dialogPanel)
builder.addDisposable {
timer.stop()
}
builder.show()
}
} | apache-2.0 | f013b1d5bec3e366a52eaec28c544b0c | 34.519481 | 121 | 0.702634 | 4.245342 | false | false | false | false |
GunoH/intellij-community | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/attach/dialog/items/list/AttachListColumnSettingsState.kt | 2 | 2238 | package com.intellij.xdebugger.impl.ui.attach.dialog.items.list
import com.intellij.ide.util.PropertiesComponent
import com.intellij.xdebugger.impl.ui.attach.dialog.items.AttachColumnSettingsState
class AttachListColumnSettingsState: AttachColumnSettingsState {
companion object {
private const val ATTACH_TREE_EXECUTABLE_COLUMN_WIDTH_KEY = "ATTACH_TREE_EXECUTABLE_COLUMN_WIDTH"
private const val ATTACH_TREE_PID_COLUMN_WIDTH_KEY = "ATTACH_TREE_PID_COLUMN_WIDTH"
private const val ATTACH_TREE_COMMAND_LINE_COLUMN_WIDTH_KEY = "ATTACH_TREE_COMMAND_LINE_COLUMN_WIDTH"
private const val EXECUTABLE_COLUMN_DEFAULT_WIDTH = 270
private const val PID_COLUMN_DEFAULT_WIDTH = 100
private const val COMMAND_LINE_COLUMN_DEFAULT_WIDTH = 430
}
private var executableColumnWidth: Int
get() = PropertiesComponent.getInstance().getInt(ATTACH_TREE_EXECUTABLE_COLUMN_WIDTH_KEY, EXECUTABLE_COLUMN_DEFAULT_WIDTH)
set(value) {
PropertiesComponent.getInstance().setValue(ATTACH_TREE_EXECUTABLE_COLUMN_WIDTH_KEY, value, EXECUTABLE_COLUMN_DEFAULT_WIDTH)
}
private var pidColumnWidth: Int
get() = PropertiesComponent.getInstance().getInt(ATTACH_TREE_PID_COLUMN_WIDTH_KEY, PID_COLUMN_DEFAULT_WIDTH)
set(value) {
PropertiesComponent.getInstance().setValue(ATTACH_TREE_PID_COLUMN_WIDTH_KEY, value, PID_COLUMN_DEFAULT_WIDTH)
}
private var commandLineColumnWidth: Int
get() = PropertiesComponent.getInstance().getInt(ATTACH_TREE_COMMAND_LINE_COLUMN_WIDTH_KEY, COMMAND_LINE_COLUMN_DEFAULT_WIDTH)
set(value) {
PropertiesComponent.getInstance().setValue(ATTACH_TREE_COMMAND_LINE_COLUMN_WIDTH_KEY, value, COMMAND_LINE_COLUMN_DEFAULT_WIDTH)
}
override fun getColumnWidth(index: Int): Int {
return when(index) {
0 -> executableColumnWidth
1 -> pidColumnWidth
2 -> commandLineColumnWidth
else -> throw IllegalStateException("Unexpected column index: $index")
}
}
override fun setColumnWidth(index: Int, value: Int) {
when (index) {
0 -> executableColumnWidth = value
1 -> pidColumnWidth = value
2 -> commandLineColumnWidth = value
else -> throw IllegalStateException("Unexpected column index: $index")
}
}
} | apache-2.0 | 6275de619c03f1210b1bf3a7ffdf3b39 | 41.245283 | 133 | 0.744861 | 4.113971 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/compiler-plugins/noarg/gradle/src/org/jetbrains/kotlin/idea/compilerPlugin/noarg/gradleJava/NoArgGradleProjectImportHandler.kt | 1 | 1642 | // 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.compilerPlugin.noarg.gradleJava
import org.jetbrains.kotlin.idea.gradleJava.compilerPlugin.annotationBased.AbstractGradleImportHandler
import org.jetbrains.kotlin.idea.compilerPlugin.AnnotationBasedCompilerPluginSetup.PluginOption
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.noarg.NoArgCommandLineProcessor
import org.jetbrains.kotlin.idea.gradleTooling.model.noarg.NoArgModel
class NoArgGradleProjectImportHandler : AbstractGradleImportHandler<NoArgModel>() {
override val compilerPluginId = NoArgCommandLineProcessor.PLUGIN_ID
override val pluginName = "noarg"
override val annotationOptionName = NoArgCommandLineProcessor.ANNOTATION_OPTION.optionName
override val pluginJarFileFromIdea = KotlinArtifacts.instance.noargCompilerPlugin
override val modelKey = NoArgProjectResolverExtension.KEY
override fun getAdditionalOptions(model: NoArgModel): List<PluginOption> {
return listOf(PluginOption(
NoArgCommandLineProcessor.INVOKE_INITIALIZERS_OPTION.optionName,
model.invokeInitializers.toString()))
}
override fun getAnnotationsForPreset(presetName: String): List<String> {
for ((name, annotations) in NoArgCommandLineProcessor.SUPPORTED_PRESETS.entries) {
if (presetName == name) {
return annotations
}
}
return super.getAnnotationsForPreset(presetName)
}
}
| apache-2.0 | 83bbc6a0f495cfb3aea65b5e4efd49a2 | 48.757576 | 158 | 0.77771 | 5.246006 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/android/lint/log.kt | 13 | 6793 | // INSPECTION_CLASS: com.android.tools.idea.lint.AndroidLintLogConditionalInspection
// INSPECTION_CLASS2: com.android.tools.idea.lint.AndroidLintLogTagMismatchInspection
// INSPECTION_CLASS3: com.android.tools.idea.lint.AndroidLintLongLogTagInspection
import android.annotation.SuppressLint
import android.util.Log
import android.util.Log.DEBUG
@SuppressWarnings("UnusedDeclaration")
@Suppress("UsePropertyAccessSyntax", "UNUSED_VARIABLE", "unused", "UNUSED_PARAMETER", "DEPRECATION")
class LogTest {
fun checkConditional(m: String) {
Log.d(TAG1, "message") // ok: unconditional, but not performing computation
Log.d(TAG1, m) // ok: unconditional, but not performing computation
Log.d(TAG1, "a" + "b") // ok: unconditional, but not performing non-constant computation
Log.d(TAG1, Constants.MY_MESSAGE) // ok: unconditional, but constant string
<warning descr="The log call Log.i(...) should be conditional: surround with `if (Log.isLoggable(...))` or `if (BuildConfig.DEBUG) { ... }`">Log.i(TAG1, "message" + m)</warning> // error: unconditional w/ computation
<warning descr="The log call Log.i(...) should be conditional: surround with `if (Log.isLoggable(...))` or `if (BuildConfig.DEBUG) { ... }`">Log.i(TAG1, toString())</warning> // error: unconditional w/ computation
Log.e(TAG1, toString()) // ok: only flagging debug/info messages
Log.w(TAG1, toString()) // ok: only flagging debug/info messages
Log.wtf(TAG1, toString()) // ok: only flagging debug/info messages
if (Log.isLoggable(TAG1, 0)) {
Log.d(TAG1, toString()) // ok: conditional
}
}
fun checkWrongTag(tag: String) {
if (Log.isLoggable(<error descr="Mismatched tags: the `d()` and `isLoggable()` calls typically should pass the same tag: `TAG1` versus `TAG2` (Conflicting tag)">TAG1</error>, Log.DEBUG)) {
Log.d(<error descr="Mismatched tags: the `d()` and `isLoggable()` calls typically should pass the same tag: `TAG1` versus `TAG2`">TAG2</error>, "message") // warn: mismatched tags!
}
if (Log.isLoggable("<error descr="Mismatched tags: the `d()` and `isLoggable()` calls typically should pass the same tag: `\"my_tag\"` versus `\"other_tag\"` (Conflicting tag)">my_tag</error>", Log.DEBUG)) {
Log.d("<error descr="Mismatched tags: the `d()` and `isLoggable()` calls typically should pass the same tag: `\"my_tag\"` versus `\"other_tag\"`">other_tag</error>", "message") // warn: mismatched tags!
}
if (Log.isLoggable("my_tag", Log.DEBUG)) {
Log.d("my_tag", "message") // ok: strings equal
}
if (Log.isLoggable(tag, Log.DEBUG)) {
Log.d(tag, "message") // ok: same variable
}
}
fun checkLongTag(shouldLog: Boolean) {
if (shouldLog) {
// String literal tags
Log.d("short_tag", "message") // ok: short
Log.d("<error descr="The logging tag can be at most 23 characters, was 43 (really_really_really_really_really_long_tag)">really_really_really_really_really_long_tag</error>", "message") // error: too long
// Resolved field tags
Log.d(TAG1, "message") // ok: short
Log.d(TAG22, "message") // ok: short
Log.d(TAG23, "message") // ok: threshold
Log.d(<error descr="The logging tag can be at most 23 characters, was 24 (123456789012345678901234)">TAG24</error>, "message") // error: too long
Log.d(<error descr="The logging tag can be at most 23 characters, was 39 (MyReallyReallyReallyReallyReallyLongTag)">LONG_TAG</error>, "message") // error: way too long
// Locally defined variable tags
val LOCAL_TAG = "MyReallyReallyReallyReallyReallyLongTag"
Log.d(<error descr="The logging tag can be at most 23 characters, was 39 (MyReallyReallyReallyReallyReallyLongTag)">LOCAL_TAG</error>, "message") // error: too long
// Concatenated tags
Log.d(<error descr="The logging tag can be at most 23 characters, was 28 (1234567890123456789012MyTag1)">TAG22 + TAG1</error>, "message") // error: too long
Log.d(<error descr="The logging tag can be at most 23 characters, was 27 (1234567890123456789012MyTag)">TAG22 + "MyTag"</error>, "message") // error: too long
}
}
fun checkWrongLevel(tag: String) {
if (Log.isLoggable(TAG1, Log.DEBUG)) {
Log.d(TAG1, "message") // ok: right level
}
if (Log.isLoggable(TAG1, Log.INFO)) {
Log.i(TAG1, "message") // ok: right level
}
if (Log.isLoggable(TAG1, <error descr="Mismatched logging levels: when checking `isLoggable` level `DEBUG`, the corresponding log call should be `Log.d`, not `Log.v` (Conflicting tag)">Log.DEBUG</error>)) {
Log.<error descr="Mismatched logging levels: when checking `isLoggable` level `DEBUG`, the corresponding log call should be `Log.d`, not `Log.v`">v</error>(TAG1, "message") // warn: wrong level
}
if (Log.isLoggable(TAG1, <error descr="Mismatched logging levels: when checking `isLoggable` level `DEBUG`, the corresponding log call should be `Log.d`, not `Log.v` (Conflicting tag)">DEBUG</error>)) {
// static import of level
Log.<error descr="Mismatched logging levels: when checking `isLoggable` level `DEBUG`, the corresponding log call should be `Log.d`, not `Log.v`">v</error>(TAG1, "message") // warn: wrong level
}
if (Log.isLoggable(TAG1, <error descr="Mismatched logging levels: when checking `isLoggable` level `VERBOSE`, the corresponding log call should be `Log.v`, not `Log.d` (Conflicting tag)">Log.VERBOSE</error>)) {
Log.<error descr="Mismatched logging levels: when checking `isLoggable` level `VERBOSE`, the corresponding log call should be `Log.v`, not `Log.d`">d</error>(TAG1, "message") // warn? verbose is a lower logging level, which includes debug
}
if (Log.isLoggable(TAG1, Constants.MY_LEVEL)) {
Log.d(TAG1, "message") // ok: unknown level alias
}
}
@SuppressLint("all")
fun suppressed1() {
Log.d(TAG1, "message") // ok: suppressed
}
@SuppressLint("LogConditional")
fun suppressed2() {
Log.d(TAG1, "message") // ok: suppressed
}
private object Constants {
val MY_MESSAGE = "My Message"
val MY_LEVEL = 5
}
companion object {
private val TAG1 = "MyTag1"
private val TAG2 = "MyTag2"
private val TAG22 = "1234567890123456789012"
private val TAG23 = "12345678901234567890123"
private val TAG24 = "123456789012345678901234"
private val LONG_TAG = "MyReallyReallyReallyReallyReallyLongTag"
}
} | apache-2.0 | 6866b53eee0ec956d10fb0263ad0611d | 60.207207 | 250 | 0.646106 | 3.892837 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ide/customize/CustomizeIDEWizardInteractions.kt | 7 | 3062 | // 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 com.intellij.ide.customize
import com.intellij.ide.ApplicationInitializedListener
import com.intellij.internal.statistic.FeaturedPluginsInfoProvider
import com.intellij.internal.statistic.utils.getPluginInfoByDescriptorWithFeaturedPlugins
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.extensions.PluginId
import java.util.concurrent.ForkJoinPool
import java.util.concurrent.atomic.AtomicReference
object CustomizeIDEWizardInteractions {
/**
* Featured plugins group which are suggested in IDE Customization Wizard.
*/
val featuredPluginGroups = AtomicReference<PluginGroups>()
var skippedOnPage = -1
val interactions = mutableListOf<CustomizeIDEWizardInteraction>()
@JvmOverloads
fun record(type: CustomizeIDEWizardInteractionType, pluginDescriptor: PluginDescriptor? = null, groupId: String? = null) {
interactions.add(CustomizeIDEWizardInteraction(type, System.currentTimeMillis(), pluginDescriptor, groupId))
}
}
enum class CustomizeIDEWizardInteractionType {
WizardDisplayed,
UIThemeChanged,
DesktopEntryCreated,
LauncherScriptCreated,
BundledPluginGroupDisabled,
BundledPluginGroupEnabled,
BundledPluginGroupCustomized,
FeaturedPluginInstalled
}
data class CustomizeIDEWizardInteraction(
val type: CustomizeIDEWizardInteractionType,
val timestamp: Long,
val pluginDescriptor: PluginDescriptor?,
val groupId: String?
)
internal class CustomizeIDEWizardCollectorActivity : ApplicationInitializedListener {
override fun componentsInitialized() {
if (CustomizeIDEWizardInteractions.interactions.isEmpty()) {
return
}
ForkJoinPool.commonPool().execute {
if (CustomizeIDEWizardInteractions.skippedOnPage != -1) {
CustomizeWizardCollector.logRemainingPagesSkipped(CustomizeIDEWizardInteractions.skippedOnPage)
}
val featuredPluginsProvider = CustomizeIDEWizardFeaturedPluginsProvider(CustomizeIDEWizardInteractions.featuredPluginGroups.get())
for (interaction in CustomizeIDEWizardInteractions.interactions) {
val pluginInfo = if (interaction.pluginDescriptor != null)
getPluginInfoByDescriptorWithFeaturedPlugins(interaction.pluginDescriptor, featuredPluginsProvider)
else
null
CustomizeWizardCollector.logEvent(interaction.type, interaction.timestamp, pluginInfo, interaction.groupId)
}
}
}
}
private class CustomizeIDEWizardFeaturedPluginsProvider(private val pluginGroups: PluginGroups?) : FeaturedPluginsInfoProvider {
private val validatedPlugins: Set<PluginId> by lazy {
if (pluginGroups != null) {
val fromRepository = pluginGroups.pluginsFromRepository
if (fromRepository.isNotEmpty()) {
return@lazy fromRepository.map { it.pluginId }.toSet()
}
}
return@lazy emptySet()
}
override fun getFeaturedPluginsFromMarketplace(): Set<PluginId> = validatedPlugins
} | apache-2.0 | 5a5f2ca0a785b2f912a3f76607786585 | 36.814815 | 140 | 0.791966 | 4.995106 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/pkg/tasks/compose/BundleInstalledResolved.kt | 1 | 916 | package com.cognifide.gradle.aem.pkg.tasks.compose
import com.cognifide.gradle.aem.common.pkg.vault.FilterType
import com.cognifide.gradle.aem.pkg.tasks.PackageCompose
import org.gradle.api.tasks.Input
class BundleInstalledResolved(private val target: PackageCompose, @Input val notation: Any) : BundleInstalled {
private val aem = target.aem
private val resolvedFile by lazy { aem.common.resolveFile(notation) }
override val file = aem.obj.file { fileProvider(aem.obj.provider { resolvedFile }) }
override val dirPath = aem.obj.string { convention(target.bundlePath) }
override val fileName = aem.obj.string { convention(aem.obj.provider { resolvedFile.name }) }
override val vaultFilter = aem.obj.boolean { convention(target.vaultFilters) }
override val vaultFilterType = aem.obj.typed<FilterType> { convention(FilterType.FILE) }
override val runMode = aem.obj.string()
}
| apache-2.0 | 4c506a5736021cae5eba54de0c2d18d0 | 37.166667 | 111 | 0.758734 | 3.93133 | false | false | false | false |
juzraai/ted-xml-model | src/main/kotlin/hu/juzraai/ted/xml/model/helper/PConverter.kt | 1 | 1164 | package hu.juzraai.ted.xml.model.helper
import hu.juzraai.ted.xml.model.tedexport.common.Ft
import hu.juzraai.ted.xml.model.tedexport.common.FtType
import hu.juzraai.ted.xml.model.tedexport.common.P
import org.simpleframework.xml.convert.Converter
import org.simpleframework.xml.stream.InputNode
import org.simpleframework.xml.stream.OutputNode
/**
* Custom parser for P elements.
*
* @author Zsolt Jurányi
*/
class PConverter : Converter<P> {
fun addPNodeText(pNode: InputNode, values: MutableList<Any>) {
val t = text(pNode)
if (!t.isEmpty()) values.add(t)
}
fun parseFt(ftNode: InputNode): Ft = Ft(text(ftNode), FtType.valueOf(ftNode.getAttribute("TYPE")?.value.toString()))
override fun read(pNode: InputNode?): P {
if (pNode == null) return P()
val values = mutableListOf<Any>()
addPNodeText(pNode, values)
var ftNode = pNode.next
while (ftNode != null) {
values.add(parseFt(ftNode))
addPNodeText(pNode, values)
ftNode = pNode.next
}
return P(values)
}
fun text(n: InputNode): String = n.value?.trim() ?: ""
override fun write(n: OutputNode?, e: P?) {
throw UnsupportedOperationException("not implemented")
}
} | apache-2.0 | 28f29da8b55ba9554a077d980fe3070a | 26.714286 | 117 | 0.72313 | 2.959288 | false | false | false | false |
Duke1/UnrealMedia | UnrealMedia/app/src/main/java/com/qfleng/um/view/UriImageView.kt | 1 | 1375 | package com.qfleng.um.view
import android.content.Context
import android.util.AttributeSet
import com.facebook.drawee.generic.RoundingParams
import com.facebook.drawee.view.SimpleDraweeView
/**
* ps:roundingBorderPadding解决白边问题
*/
class UriImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : SimpleDraweeView(context, attrs, defStyleAttr) {
fun setCornersRadius(radius: Float) {
var roundingParams: RoundingParams? = hierarchy.roundingParams
if (null == roundingParams) {
roundingParams = RoundingParams.fromCornersRadius(radius)
} else
roundingParams.setCornersRadius(radius)
hierarchy.roundingParams = roundingParams
}
fun setBorderWidth(width: Float) {
val roundingParams = hierarchy.roundingParams ?: return
roundingParams.borderWidth = width
hierarchy.roundingParams = roundingParams
}
fun setBorderPadding(padding: Float) {
val roundingParams = hierarchy.roundingParams ?: return
roundingParams.padding = padding
hierarchy.roundingParams = roundingParams
}
fun setBorderColor(color: Int) {
val roundingParams = hierarchy.roundingParams ?: return
roundingParams.borderColor = color
hierarchy.roundingParams = roundingParams
}
}
| mit | 4257b910588cc8d40aa6575edbd8109a | 28.630435 | 165 | 0.716801 | 4.974453 | false | false | false | false |
flicus/vertx-telegram-bot-api | kotlin/src/main/kotlin/kt/schors/vertx/telegram/bot/api/types/Game.kt | 1 | 652 | package kt.schors.vertx.telegram.bot.api.types
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty
data class Game
@JsonCreator constructor(
@JsonProperty("title")
var title: String? = null,
@JsonProperty("description")
var description: String? = null,
@JsonProperty("photo")
var photo: Array<PhotoSize>? = null,
@JsonProperty("text")
var text: String? = null,
@JsonProperty("text_entities")
var textEntities: Array<MessageEntity>? = null,
@JsonProperty("animation")
var animation: Animation? = null
) | mit | 0390a09473309cfeabf246f8f4032cbc | 31.65 | 55 | 0.662577 | 4.435374 | false | false | false | false |
solokot/Simple-Gallery | app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/SetWallpaperActivity.kt | 1 | 5914 | package com.simplemobiletools.gallery.pro.activities
import android.annotation.SuppressLint
import android.app.Activity
import android.app.WallpaperManager
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import com.simplemobiletools.commons.dialogs.RadioGroupDialog
import com.simplemobiletools.commons.extensions.checkAppSideloading
import com.simplemobiletools.commons.extensions.toast
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import com.simplemobiletools.commons.helpers.isNougatPlus
import com.simplemobiletools.commons.models.RadioItem
import com.simplemobiletools.gallery.pro.R
import com.theartofdev.edmodo.cropper.CropImageView
import kotlinx.android.synthetic.main.activity_set_wallpaper.*
import kotlinx.android.synthetic.main.bottom_set_wallpaper_actions.*
class SetWallpaperActivity : SimpleActivity(), CropImageView.OnCropImageCompleteListener {
private val PICK_IMAGE = 1
private var isLandscapeRatio = true
private var wallpaperFlag = -1
lateinit var uri: Uri
lateinit var wallpaperManager: WallpaperManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_set_wallpaper)
if (checkAppSideloading()) {
return
}
if (intent.data == null) {
val pickIntent = Intent(applicationContext, MainActivity::class.java)
pickIntent.action = Intent.ACTION_PICK
pickIntent.type = "image/*"
startActivityForResult(pickIntent, PICK_IMAGE)
return
}
handleImage(intent)
setupBottomActions()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_set_wallpaper, menu)
updateMenuItemColors(menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.save -> confirmWallpaper()
else -> return super.onOptionsItemSelected(item)
}
return true
}
private fun handleImage(intent: Intent) {
uri = intent.data!!
if (uri.scheme != "file" && uri.scheme != "content") {
toast(R.string.unknown_file_location)
finish()
return
}
wallpaperManager = WallpaperManager.getInstance(applicationContext)
crop_image_view.apply {
setOnCropImageCompleteListener(this@SetWallpaperActivity)
setImageUriAsync(uri)
}
setupAspectRatio()
}
private fun setupBottomActions() {
bottom_set_wallpaper_aspect_ratio.setOnClickListener {
changeAspectRatio(!isLandscapeRatio)
}
bottom_set_wallpaper_rotate.setOnClickListener {
crop_image_view.rotateImage(90)
}
}
private fun setupAspectRatio() {
val wallpaperWidth = if (isLandscapeRatio) wallpaperManager.desiredMinimumWidth else wallpaperManager.desiredMinimumWidth / 2
crop_image_view.setAspectRatio(wallpaperWidth, wallpaperManager.desiredMinimumHeight)
bottom_set_wallpaper_aspect_ratio.setImageResource(if (isLandscapeRatio) R.drawable.ic_minimize_vector else R.drawable.ic_maximize_vector)
}
private fun changeAspectRatio(isLandscape: Boolean) {
isLandscapeRatio = isLandscape
setupAspectRatio()
}
@SuppressLint("InlinedApi")
private fun confirmWallpaper() {
if (isNougatPlus()) {
val items = arrayListOf(
RadioItem(WallpaperManager.FLAG_SYSTEM, getString(R.string.home_screen)),
RadioItem(WallpaperManager.FLAG_LOCK, getString(R.string.lock_screen)),
RadioItem(WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK, getString(R.string.home_and_lock_screen))
)
RadioGroupDialog(this, items) {
wallpaperFlag = it as Int
crop_image_view.getCroppedImageAsync()
}
} else {
crop_image_view.getCroppedImageAsync()
}
}
@SuppressLint("NewApi")
override fun onCropImageComplete(view: CropImageView?, result: CropImageView.CropResult) {
if (isDestroyed)
return
if (result.error == null) {
toast(R.string.setting_wallpaper)
ensureBackgroundThread {
val bitmap = result.bitmap
val wantedHeight = wallpaperManager.desiredMinimumHeight
val ratio = wantedHeight / bitmap.height.toFloat()
val wantedWidth = (bitmap.width * ratio).toInt()
try {
val scaledBitmap = Bitmap.createScaledBitmap(bitmap, wantedWidth, wantedHeight, true)
if (isNougatPlus()) {
wallpaperManager.setBitmap(scaledBitmap, null, true, wallpaperFlag)
} else {
wallpaperManager.setBitmap(scaledBitmap)
}
setResult(Activity.RESULT_OK)
} catch (e: OutOfMemoryError) {
toast(R.string.out_of_memory_error)
setResult(Activity.RESULT_CANCELED)
}
finish()
}
} else {
toast("${getString(R.string.image_editing_failed)}: ${result.error.message}")
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
if (requestCode == PICK_IMAGE) {
if (resultCode == Activity.RESULT_OK && resultData != null) {
handleImage(resultData)
} else {
finish()
}
}
super.onActivityResult(requestCode, resultCode, resultData)
}
}
| gpl-3.0 | be63671ddecc361a62115c9e94fed59f | 35.506173 | 146 | 0.645587 | 4.978114 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/graphql/GqlConst.kt | 1 | 1791 | package org.evomaster.core.problem.graphql
object GqlConst {
/**
* This tag is for the GQL union type. Needed in getValueAsPrintableString to print out things like:
* fieldXName{
* ... on UnionObject1 {
* field
* }
* ... on UnionObjectN {
* field
* }
* }
*/
const val UNION_TAG = "#UNION#"
/**
* Is used for the GQL interface type. Needed in getValueAsPrintableString to print out: field1 ... fieldN in:
* fieldXName{
* field1
* fieldN
* ... on InterfaceObject1 {
* field
* }
* ... on InterfaceObjectN {
* field
* }
* }
*/
const val INTERFACE_BASE_TAG = "#BASE#"
/**
* Is used for the GQL interface type. Needed in getValueAsPrintableString to print out: ... on InterfaceObject1 ... on InterfaceObjectN in :
* fieldXName{
* field1
* fieldN
* ... on InterfaceObject1 {
* field
* }
* ... on InterfaceObjectN {
* field
* }
* }
*/
const val INTERFACE_TAG = "#INTERFACE#"
const val SCALAR = "scalar"
const val OBJECT = "object"
const val UNION = "union"
const val INTERFACE = "interface"
const val ENUM = "enum"
const val LIST = "list"
const val INPUT_OBJECT = "input_object"
/*
*Those are entry points of GraphQL query and mutation
* Todo Currently, they are used to calculate statistic from the graph. Need to be generalised.
*/
const val QUERY = "query"
const val QUERY_TYPE = "querytype"
const val ROOT = "root"
const val MUTATION = "mutation"
} | lgpl-3.0 | dd2a5d6320ca62c9e369f1ce56ec485a | 28.866667 | 145 | 0.522613 | 4.184579 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/inspections/Utils.kt | 1 | 6335 | package com.gmail.blueboxware.libgdxplugin.inspections
import com.gmail.blueboxware.libgdxplugin.versions.VersionService
import com.gmail.blueboxware.libgdxplugin.filetypes.properties.GDXPropertyReference
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.LibGDXSkinFileType
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.findUsages.ClassTagFindUsagesHandler
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinFile
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.quickfixes.CreateAssetQuickFix
import com.gmail.blueboxware.libgdxplugin.message
import com.gmail.blueboxware.libgdxplugin.references.AssetReference
import com.gmail.blueboxware.libgdxplugin.utils.*
import com.gmail.blueboxware.libgdxplugin.versions.Libraries
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.find.findUsages.FindUsagesOptions
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiLiteralExpression
import org.jetbrains.kotlin.config.MavenComparableVersion
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
/*
* Copyright 2018 Blue Box Ware
*
* 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.
*/
internal fun checkForNonExistingAssetReference(element: PsiElement, elementName: String, holder: ProblemsHolder) {
element
.references
.filterIsInstance<AssetReference>()
.takeIf { it.isNotEmpty() }
?.firstOrNull { it.multiResolve(true).isEmpty() }
?.let { reference ->
val type = reference.className ?: "<unknown>"
val files = reference.filesPresentableText(true).takeIf { it != "" }?.let { "in $it" } ?: ""
val fixes =
if (elementName.isNotBlank()) {
reference.className?.takeIf { it.plainName != TEXTURE_REGION_CLASS_NAME }?.let { className ->
reference.skinFiles.map { skinFile ->
CreateAssetQuickFix(skinFile, elementName, className, skinFile.name)
}.toTypedArray()
}
} else {
null
}
holder.registerProblem(
element,
message("nonexisting.asset.problem.descriptor", elementName, type, files),
*fixes ?: arrayOf()
)
}
}
internal fun checkForUnusedClassTag(element: PsiElement, holder: ProblemsHolder) {
val tagName =
(element as? PsiLiteralExpression)?.asString()
?: (element as? KtStringTemplateExpression)?.asPlainString()
?: return
var found = false
val findUsagesHandler =
(element as? PsiLiteralExpression)?.let(::ClassTagFindUsagesHandler)
?: (element as? KtStringTemplateExpression)?.let(::ClassTagFindUsagesHandler)
?: return
findUsagesHandler.processElementUsages(
element,
{
found = true
false
},
FindUsagesOptions(element.allScope())
)
if (!found) {
holder.registerProblem(element, message("unused.class.tag.problem.descriptor", tagName))
}
}
internal fun isValidProperty(element: PsiElement): Boolean {
element.references.filterIsInstance<GDXPropertyReference>().let { references ->
if (references.isEmpty()) {
return true
}
references.forEach { reference ->
if ((reference as? GDXPropertyReference)?.multiResolve(false)?.isEmpty() != true) {
return true
}
}
}
return false
}
internal fun isProblematicGDXVersionFor64Bit(project: Project): Boolean {
project.service<VersionService>().let { versionManager ->
val gdxVersion = versionManager.getUsedVersion(Libraries.LIBGDX) ?: return false
if (gdxVersion >= MavenComparableVersion("1.9.0") && gdxVersion < MavenComparableVersion("1.9.2")) {
return true
}
}
return false
}
internal fun checkSkinFilename(element: PsiElement, fileName: String, holder: ProblemsHolder) {
checkFilename(element, fileName, holder)?.let { psiFile ->
if (psiFile.fileType != LibGDXSkinFileType.INSTANCE && psiFile !is SkinFile) {
holder.registerProblem(
element,
message("gdxassets.annotation.problem.descriptor.not.a.skin", fileName),
ProblemHighlightType.WEAK_WARNING
)
}
}
}
internal fun checkFilename(element: PsiElement, fileName: String, holder: ProblemsHolder): PsiFile? {
if (fileName == "") return null
val psiFile = element.project.getPsiFile(fileName)
if (psiFile == null) {
holder.registerProblem(
element,
message(
"gdxassets.annotation.problem.descriptor.nofile",
fileName,
element.project.getProjectBaseDir()?.path ?: ""
),
ProblemHighlightType.ERROR
)
}
return psiFile
}
private val keyMethods = key<Pair<Set<PsiElement>, Set<PsiElement>>>("flushingmethods")
private val keyPreviousProject = key<Project>("previousproject")
internal fun getFlushingMethods(project: Project, session: LocalInspectionToolSession): Set<PsiElement>? {
if (session.getUserData(keyMethods) == null || session.getUserData(keyPreviousProject) != project) {
val methods = FlushingMethodsUtils.getAllFlushingMethods(project)
session.putUserData(keyMethods, methods)
session.putUserData(keyPreviousProject, project)
}
return session.getUserData(keyMethods)?.second
}
| apache-2.0 | e66ea796e393fec0b2c1243c1edc9368 | 34.391061 | 114 | 0.679874 | 4.914663 | false | false | false | false |
tmarsteel/kotlin-prolog | stdlib/src/main/kotlin/com/github/prologdb/runtime/stdlib/essential/math/comparison_builtins.kt | 1 | 860 | package com.github.prologdb.runtime.stdlib.essential.math
import com.github.prologdb.runtime.stdlib.nativeRule
import com.github.prologdb.runtime.unification.Unification
val BuiltinGreaterThan2 = nativeRule(">", 2) { args, _ ->
Unification.whether(args[0].asPrologNumber > args[1].asPrologNumber)
}
val BuiltinGreaterThanOrEqual2 = nativeRule(">=", 2) { args, _ ->
Unification.whether(args[0].asPrologNumber >= args[1].asPrologNumber)
}
val BuiltinLessThan2 = nativeRule("<", 2) { args, _ ->
Unification.whether(args[0].asPrologNumber < args[1].asPrologNumber)
}
val BuiltinLessThanOrEqual2 = nativeRule("=<", 2) { args, _ ->
Unification.whether(args[0].asPrologNumber <= args[1].asPrologNumber)
}
val BuiltinNumericNotEqual2 = nativeRule("=\\=", 2) { args, _ ->
Unification.whether(args[0].asPrologNumber != args[1].asPrologNumber)
} | mit | 42da6b2fa5fa79fdfc24a4c3f54b8c03 | 34.875 | 73 | 0.726744 | 3.539095 | false | false | false | false |
gradle/gradle | build-logic/basics/src/main/kotlin/gradlebuild/basics/BuildEnvironment.kt | 2 | 5235 | /*
* 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.basics
import gradlebuild.basics.BuildParams.CI_ENVIRONMENT_VARIABLE
import org.gradle.api.JavaVersion
import org.gradle.api.Project
import org.gradle.api.file.Directory
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.internal.os.OperatingSystem
import org.gradle.kotlin.dsl.*
abstract class BuildEnvironmentExtension {
abstract val gitCommitId: Property<String>
abstract val gitBranch: Property<String>
abstract val repoRoot: DirectoryProperty
}
// `generatePrecompiledScriptPluginAccessors` task invokes this method without `gradle.build-environment` applied
private
fun Project.getBuildEnvironmentExtension(): BuildEnvironmentExtension? = rootProject.extensions.findByType(BuildEnvironmentExtension::class.java)
fun Project.repoRoot(): Directory = getBuildEnvironmentExtension()?.repoRoot?.get() ?: layout.projectDirectory.parentOrRoot()
fun Directory.parentOrRoot(): Directory = if (this.file("version.txt").asFile.exists()) {
this
} else {
val parent = dir("..")
when {
parent.file("version.txt").asFile.exists() -> parent
this == parent -> throw IllegalStateException("Cannot find 'version.txt' file in root of repository")
else -> parent.parentOrRoot()
}
}
fun Project.releasedVersionsFile() = repoRoot().file("released-versions.json")
/**
* We use command line Git instead of JGit, because JGit's [Repository.resolve] does not work with worktrees.
*/
fun Project.currentGitBranchViaFileSystemQuery(): Provider<String> = getBuildEnvironmentExtension()?.gitBranch ?: objects.property(String::class.java)
fun Project.currentGitCommitViaFileSystemQuery(): Provider<String> = getBuildEnvironmentExtension()?.gitCommitId ?: objects.property(String::class.java)
@Suppress("UnstableApiUsage")
fun Project.git(vararg args: String): String {
val projectDir = layout.projectDirectory.asFile
val execOutput = providers.exec {
workingDir = projectDir
isIgnoreExitValue = true
commandLine = listOf("git", *args)
if (OperatingSystem.current().isWindows) {
commandLine = listOf("cmd", "/c") + commandLine
}
}
return if (execOutput.result.get().exitValue == 0) execOutput.standardOutput.asText.get().trim()
else "<unknown>" // It's a source distribution, we don't know.
}
// pre-test/master/queue/alice/feature -> master
// pre-test/release/current/bob/bugfix -> release
fun toPreTestedCommitBaseBranch(actualBranch: String): String = when {
actualBranch.startsWith("pre-test/") -> actualBranch.substringAfter("/").substringBefore("/")
else -> actualBranch
}
object BuildEnvironment {
/**
* A selection of environment variables injected into the enviroment by the `codeql-env.sh` script.
*/
private
val CODEQL_ENVIRONMENT_VARIABLES = arrayOf(
"CODEQL_JAVA_HOME",
"CODEQL_EXTRACTOR_JAVA_SCRATCH_DIR",
"CODEQL_ACTION_RUN_MODE",
"CODEQL_ACTION_VERSION",
"CODEQL_DIST",
"CODEQL_PLATFORM",
"CODEQL_RUNNER"
)
private
val architecture = System.getProperty("os.arch").toLowerCase()
val isCiServer = CI_ENVIRONMENT_VARIABLE in System.getenv()
val isTravis = "TRAVIS" in System.getenv()
val isGhActions = "GITHUB_ACTIONS" in System.getenv()
val isTeamCity = "TEAMCITY_VERSION" in System.getenv()
val isCodeQl: Boolean by lazy {
// This logic is kept here instead of `codeql-analysis.init.gradle` because that file will hopefully be removed in the future.
// Removing that file is waiting on the GitHub team fixing an issue in Autobuilder logic.
CODEQL_ENVIRONMENT_VARIABLES.any { it in System.getenv() }
}
val jvm = org.gradle.internal.jvm.Jvm.current()
val javaVersion = JavaVersion.current()
val isWindows = OperatingSystem.current().isWindows
val isLinux = OperatingSystem.current().isLinux
val isMacOsX = OperatingSystem.current().isMacOsX
val isIntel: Boolean = architecture == "x86_64" || architecture == "x86"
val isSlowInternetConnection
get() = System.getProperty("slow.internet.connection", "false")!!.toBoolean()
val agentNum: Int
get() {
if (System.getenv().containsKey("USERNAME")) {
val agentNumEnv = System.getenv("USERNAME").replaceFirst("tcagent", "")
if (Regex("""\d+""").containsMatchIn(agentNumEnv)) {
return agentNumEnv.toInt()
}
}
return 1
}
}
| apache-2.0 | 961b25345d15f350cf52c947de55bea3 | 36.661871 | 152 | 0.704871 | 4.3372 | false | false | false | false |
xwiki-contrib/android-authenticator | authdemo/src/main/java/org/xwiki/android/authdemo/Constants.kt | 1 | 1505 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.android.authdemo
/**
* @version $Id: 75a8139c61762e9c24bca94897df7331856e374f $
*/
object Constants {
/**
* Server
*/
val SERVER_ADDRESS = "requestUrl"
/**
* Account type id
*/
val ACCOUNT_TYPE = "org.xwiki.android.sync"
/**
* Auth token types
*/
val AUTHTOKEN_TYPE_READ_ONLY = "Read only"
val AUTHTOKEN_TYPE_READ_ONLY_LABEL = "Read only access to an XWiki account"
val AUTHTOKEN_TYPE_FULL_ACCESS = "Full access" + "org.xwiki.android.authdemo"
val AUTHTOKEN_TYPE_FULL_ACCESS_LABEL = "Full access to an XWiki account"
}
| lgpl-2.1 | 1ac884b57bce70d6db1c0444cb11c228 | 31.717391 | 81 | 0.706977 | 3.858974 | false | false | false | false |
the4thfloor/Msync | app/src/main/java/eu/the4thfloor/msync/ui/CheckLoginStatusActivity.kt | 1 | 3942 | /*
* Copyright 2017 Ralph Bergmann
*
* 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 eu.the4thfloor.msync.ui
import android.app.Activity
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import androidx.browser.customtabs.CustomTabsCallback
import androidx.browser.customtabs.CustomTabsClient
import androidx.browser.customtabs.CustomTabsIntent
import androidx.browser.customtabs.CustomTabsServiceConnection
import eu.the4thfloor.msync.BuildConfig
import eu.the4thfloor.msync.R
import eu.the4thfloor.msync.utils.hasAccount
import org.jetbrains.anko.startActivity
import java.lang.ref.WeakReference
class CheckLoginStatusActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (hasAccount()) {
startActivity<SettingsActivity>()
finish()
} else {
loadCustomTab()
}
}
private fun loadCustomTab() {
val uri = Uri.Builder()
.scheme("https")
.authority("secure.meetup.com")
.appendPath("oauth2")
.appendPath("authorize")
.appendQueryParameter("client_id", BuildConfig.MEETUP_OAUTH_KEY)
.appendQueryParameter("redirect_uri", BuildConfig.MEETUP_OAUTH_REDIRECT_URI)
.appendQueryParameter("response_type", "code")
.appendQueryParameter("set_mobile", "on")
.build()
val browserIntent = Intent("android.intent.action.VIEW", Uri.parse("https://"))
val resolveInfo = packageManager.resolveActivity(browserIntent, PackageManager.MATCH_DEFAULT_ONLY)
val packageName = resolveInfo.activityInfo.packageName
CustomTabsClient.bindCustomTabsService(this, packageName,
Connection(this, uri, packageName))
}
private class Connection(activity: CheckLoginStatusActivity,
private val uri: Uri,
private val packageName: String,
private val ref: WeakReference<CheckLoginStatusActivity> = WeakReference(activity)) : CustomTabsServiceConnection() {
override fun onCustomTabsServiceConnected(name: ComponentName, client: CustomTabsClient) {
ref.get()?.let {
val session = client.newSession(Callback(it))
CustomTabsIntent.Builder(session)
.apply {
setToolbarColor(it.resources.getColor(R.color.red))
enableUrlBarHiding()
}
.build()
.apply {
intent.`package` = packageName
}
.launchUrl(it, uri)
}
}
override fun onServiceDisconnected(name: ComponentName) { }
}
private class Callback(activity: CheckLoginStatusActivity,
private val ref: WeakReference<CheckLoginStatusActivity> = WeakReference(activity)) : CustomTabsCallback() {
override fun onNavigationEvent(navigationEvent: Int, extras: Bundle?) {
super.onNavigationEvent(navigationEvent, extras)
when (navigationEvent) {
TAB_HIDDEN -> {
ref.get()?.finish()
}
}
}
}
}
| apache-2.0 | e72dcb9895079e14d16684c65ab71269 | 36.903846 | 146 | 0.64206 | 5.11284 | false | false | false | false |
NLPIE/BioMedICUS | biomedicus-uima/src/main/kotlin/edu/umn/biomedicus/uima/labels/LabelAdapters.kt | 1 | 2426 | /*
* Copyright (c) 2018 Regents of the University of Minnesota.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.umn.biomedicus.uima.labels
import com.google.inject.Inject
import com.google.inject.Singleton
import edu.umn.biomedicus.framework.LabelAliases
import edu.umn.nlpengine.Document
import edu.umn.nlpengine.Label
import org.apache.uima.cas.CAS
import org.apache.uima.cas.Type
import org.apache.uima.cas.text.AnnotationFS
import java.util.*
@Singleton
class LabelAdapters @Inject
constructor(private val labelAliases: LabelAliases?) {
private val factoryMap = HashMap<Class<*>, LabelAdapterFactory<*>>()
private val backMap = HashMap<String, LabelAdapterFactory<*>>()
fun addFactory(labelAdapterFactory: LabelAdapterFactory<*>) {
val tClass = labelAdapterFactory.labelClass
factoryMap[labelAdapterFactory.labelClass] = labelAdapterFactory
backMap[labelAdapterFactory.typeName] = labelAdapterFactory
labelAliases?.addAlias(tClass.simpleName, tClass)
}
@Suppress("UNCHECKED_CAST")
fun <T : Label> getLabelAdapterFactory(tClass: Class<T>): LabelAdapterFactory<T> {
return factoryMap[tClass]?.let { it as LabelAdapterFactory<T> }
?: throw IllegalArgumentException("No label adapter found for class: ${tClass.canonicalName}")
}
fun getLabelAdapterFactory(type: Type): LabelAdapterFactory<*> {
return backMap[type.name] ?: throw NoSuchElementException("No label adapter for type: ${type.name}")
}
}
interface LabelAdapterFactory<T : Label> {
val labelClass: Class<T>
val typeName: String
fun create(cas: CAS, document: Document?): LabelAdapter<T>
}
interface LabelAdapter<T : Label> {
val labelClass: Class<T>
val distinct: Boolean
val type: Type
fun labelToAnnotation(label: T): AnnotationFS
fun annotationToLabel(annotationFS: AnnotationFS): T
}
| apache-2.0 | 00b086639adcb2fdf8b5eb06fcc76423 | 31.346667 | 110 | 0.734955 | 4.168385 | false | false | false | false |
lice-lang/lice | src/main/kotlin/org/lice/parse/Parser.kt | 1 | 1196 | package org.lice.parse
import org.lice.util.ParseException
import java.util.*
object Parser {
fun parseTokenStream(lexer: Lexer): ASTNode {
val nodes = ArrayList<ASTNode>()
while (lexer.currentToken().type != Token.TokenType.EOI) nodes.add(parseNode(lexer))
return ASTRootNode(nodes)
}
private fun parseNode(l: Lexer) =
if (l.currentToken().type == Token.TokenType.LispKwd && l.currentToken().strValue == "(") parseList(l)
else {
val ret = ASTAtomicNode(l.currentToken().metaData, l.currentToken())
l.nextToken()
ret
}
private fun parseList(l: Lexer): ASTListNode {
// assert(l.currentToken().type == Token.TokenType.LispKwd && l.currentToken().strValue == "(")
l.nextToken()
val leftParthToken = l.currentToken()
val subNodes = ArrayList<ASTNode>()
while (!(l.currentToken().type == Token.TokenType.LispKwd
&& l.currentToken().strValue == ")")
&& l.currentToken().type != Token.TokenType.EOI) {
subNodes.add(parseNode(l))
}
if (l.currentToken().type == Token.TokenType.EOI)
throw ParseException("Unexpected EOI, expected ')'", l.currentToken().metaData)
l.nextToken()
return ASTListNode(leftParthToken.metaData, subNodes)
}
}
| gpl-3.0 | 42df5923437b5e3bb957feb21e6f73b1 | 31.324324 | 105 | 0.69398 | 3.369014 | false | false | false | false |
chrix75/domino | src/main/kotlin/domain/processing/entities/objects/ParameterEntity.kt | 1 | 1379 | package domain.processing.entities.objects
import domain.global.entities.NamedEntity
import domain.global.generators.ParameterGenerator
import domain.global.validators.EntityValidator
import domain.global.validators.ParameterValidator
import domain.global.validators.Validable
import org.neo4j.ogm.annotation.NodeEntity
import org.neo4j.ogm.annotation.Relationship
/**
* The parameter entity.
*
* Created by Christian Sperandio on 09/04/2016.
*
*/
@NodeEntity(label = "Parameter")
class ParameterEntity(_name: String = "") : NamedEntity(_name), Validable<ParameterEntity> {
var value: String? = null
get() = field
set(value) {
field = value
parameters.forEach { it.value = value }
}
@Relationship(type = "INITIALIZES", direction = Relationship.OUTGOING)
var parameters: Set<ParameterEntity> = setOf()
@Relationship(type = "GENERATES", direction = Relationship.INCOMING)
var generator: ParameterGenerator? = null
/**
* Returns an instance of the validator checks if a parameter is valid before saving into the DB.
*/
override fun buildValidator(): EntityValidator<ParameterEntity> {
return ParameterValidator()
}
/**
* Resets the id to null of the current parameter.
*/
override fun resetId() {
id = null
generator?.resetId()
}
}
| mpl-2.0 | 1d84bc0e10c3c521249c756c730e30b1 | 27.142857 | 101 | 0.694706 | 4.322884 | false | false | false | false |
googlemaps/android-maps-rx | app/src/main/java/com/google/maps/android/rx/demo/MainActivity.kt | 1 | 3123 | // Copyright 2021 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 com.google.maps.android.rx.demo
import android.os.Bundle
import android.util.Log
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.*
import com.google.android.gms.maps.MapView
import com.google.maps.android.ktx.awaitMap
import com.google.maps.android.rx.cameraIdleEvents
import com.trello.lifecycle4.android.lifecycle.AndroidLifecycle
class MainActivity : AppCompatActivity() {
private val provider = AndroidLifecycle.createLifecycleProvider(this)
private val mapView by lazy {
MapView(this).apply {
layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(mapView)
val mapViewBundle = savedInstanceState?.getBundle(MAPVIEW_BUNDLE_KEY)
mapView.onCreate(mapViewBundle)
mapView.observe(lifecycle)
lifecycle.coroutineScope.launchWhenCreated {
val googleMap = mapView.awaitMap()
googleMap.cameraIdleEvents()
.compose(provider.bindToLifecycle())
.subscribe {
Log.d(TAG, "Camera is idle")
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
val mapViewBundle = outState.getBundle(MAPVIEW_BUNDLE_KEY) ?: Bundle().also {
outState.putBundle(MAPVIEW_BUNDLE_KEY, it)
}
mapView.onSaveInstanceState(mapViewBundle)
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
companion object {
private const val MAPVIEW_BUNDLE_KEY = "MapViewBundleKey"
private val TAG = MainActivity::class.java.simpleName
}
}
fun MapView.observe(lifecycle: Lifecycle) {
lifecycle.addObserver(object : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() {
[email protected]()
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {
[email protected]()
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
[email protected]()
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {
[email protected]()
}
})
} | apache-2.0 | dddda9e2ce0079ff3fa8343be7df6d59 | 30.877551 | 85 | 0.666987 | 4.738998 | false | false | false | false |
android/kotlin-multiplatform-samples | DiceRoller/shared/src/commonMain/kotlin/com/google/samples/apps/diceroller/DiceRoller.kt | 1 | 1934 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.diceroller
import kotlin.random.Random
import kotlin.random.nextInt
class DiceRoller {
@Throws(IllegalArgumentException::class)
fun rollDice(settings: DiceSettings): List<Int> {
require(settings.diceCount >= 1) {
"Must throw a positive number of dice (tried to roll ${settings.diceCount})"
}
require(settings.sideCount >= 3) {
"Dice must have at least 3 sides (tried to roll ${settings.sideCount}-sided dice)"
}
return if (!settings.uniqueRollsOnly) {
// Just roll the given number of dice and return results
List(settings.diceCount) { Random.nextInt(1..settings.sideCount) }
} else {
require(settings.diceCount <= settings.sideCount) {
"Can't roll ${settings.diceCount} unique values with ${settings.sideCount}-side dice"
}
buildList {
// Create set of available numbers
val availableNumbers = (1..settings.sideCount).toMutableSet()
// Draw numbers from set
repeat(settings.diceCount) {
val next = availableNumbers.random().also { availableNumbers.remove(it) }
add(next)
}
}
}
}
}
| apache-2.0 | 2e0629d8682fd3eb686c0ff9c4cfc24e | 37.68 | 101 | 0.635471 | 4.476852 | false | false | false | false |
android/user-interface-samples | WindowManager/app/src/main/java/com/example/windowmanagersample/embedding/SplitActivityList.kt | 1 | 2700 | /*
* 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.example.windowmanagersample.embedding
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.util.Consumer
import androidx.window.core.ExperimentalWindowApi
import androidx.window.embedding.SplitController
import androidx.window.embedding.SplitInfo
import com.example.windowmanagersample.R
import com.example.windowmanagersample.embedding.SplitActivityDetail.Companion.EXTRA_SELECTED_ITEM
@OptIn(ExperimentalWindowApi::class)
open class SplitActivityList : AppCompatActivity() {
lateinit var splitController: SplitController
val splitChangeListener = SplitStateChangeListener()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_split_activity_list_layout)
findViewById<View>(R.id.root_split_activity_layout)
.setBackgroundColor(Color.parseColor("#e0f7fa"))
splitController = SplitController.getInstance()
}
open fun onItemClick(view: View) {
val text = (view as TextView).text ?: throw IllegalArgumentException()
val startIntent = Intent(this, SplitActivityDetail::class.java)
startIntent.putExtra(EXTRA_SELECTED_ITEM, text)
startActivity(startIntent)
}
override fun onStart() {
super.onStart()
splitController.addSplitListener(
this,
ContextCompat.getMainExecutor(this),
splitChangeListener
)
}
override fun onStop() {
super.onStop()
splitController.removeSplitListener(
splitChangeListener
)
}
inner class SplitStateChangeListener : Consumer<List<SplitInfo>> {
override fun accept(newSplitInfos: List<SplitInfo>) {
findViewById<View>(R.id.infoButton).visibility =
if (newSplitInfos.isEmpty()) View.VISIBLE else View.GONE
}
}
}
| apache-2.0 | 4b992d4fff8f4e7e0845bc8806e603b1 | 34.526316 | 98 | 0.72963 | 4.6875 | false | false | false | false |
square/kotlinpoet | kotlinpoet/src/main/java/com/squareup/kotlinpoet/WildcardTypeName.kt | 1 | 4696 | /*
* Copyright (C) 2015 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.
*/
@file:JvmName("WildcardTypeNames")
package com.squareup.kotlinpoet
import java.lang.reflect.Type
import java.lang.reflect.WildcardType
import javax.lang.model.element.TypeParameterElement
import kotlin.reflect.KClass
public class WildcardTypeName private constructor(
outTypes: List<TypeName>,
inTypes: List<TypeName>,
nullable: Boolean = false,
annotations: List<AnnotationSpec> = emptyList(),
tags: Map<KClass<*>, Any> = emptyMap(),
) : TypeName(nullable, annotations, TagMap(tags)) {
public val outTypes: List<TypeName> = outTypes.toImmutableList()
public val inTypes: List<TypeName> = inTypes.toImmutableList()
init {
require(this.outTypes.size == 1) { "unexpected out types: $outTypes" }
}
override fun copy(
nullable: Boolean,
annotations: List<AnnotationSpec>,
tags: Map<KClass<*>, Any>,
): WildcardTypeName {
return WildcardTypeName(outTypes, inTypes, nullable, annotations, tags)
}
override fun emit(out: CodeWriter): CodeWriter {
return when {
inTypes.size == 1 -> out.emitCode("in·%T", inTypes[0])
outTypes == STAR.outTypes -> out.emit("*")
else -> out.emitCode("out·%T", outTypes[0])
}
}
public companion object {
/**
* Returns a type that represents an unknown type that produces `outType`. For example, if
* `outType` is `CharSequence`, this returns `out CharSequence`. If `outType` is `Any?`, this
* returns `*`, which is shorthand for `out Any?`.
*/
@JvmStatic public fun producerOf(outType: TypeName): WildcardTypeName =
WildcardTypeName(listOf(outType), emptyList())
@DelicateKotlinPoetApi(
message = "Java reflection APIs don't give complete information on Kotlin types. Consider " +
"using the kotlinpoet-metadata APIs instead.",
)
@JvmStatic
public fun producerOf(outType: Type): WildcardTypeName =
producerOf(outType.asTypeName())
@JvmStatic public fun producerOf(outType: KClass<*>): WildcardTypeName =
producerOf(outType.asTypeName())
/**
* Returns a type that represents an unknown type that consumes `inType`. For example, if
* `inType` is `String`, this returns `in String`.
*/
@JvmStatic public fun consumerOf(inType: TypeName): WildcardTypeName =
WildcardTypeName(listOf(ANY), listOf(inType))
@DelicateKotlinPoetApi(
message = "Java reflection APIs don't give complete information on Kotlin types. Consider " +
"using the kotlinpoet-metadata APIs instead.",
)
@JvmStatic
public fun consumerOf(inType: Type): WildcardTypeName =
consumerOf(inType.asTypeName())
@JvmStatic public fun consumerOf(inType: KClass<*>): WildcardTypeName =
consumerOf(inType.asTypeName())
internal fun get(
mirror: javax.lang.model.type.WildcardType,
typeVariables: Map<TypeParameterElement, TypeVariableName>,
): TypeName {
val outType = mirror.extendsBound
return if (outType == null) {
val inType = mirror.superBound
if (inType == null) {
STAR
} else {
consumerOf(get(inType, typeVariables))
}
} else {
producerOf(get(outType, typeVariables))
}
}
internal fun get(
wildcardName: WildcardType,
map: MutableMap<Type, TypeVariableName>,
): TypeName {
return WildcardTypeName(
wildcardName.upperBounds.map { get(it, map = map) },
wildcardName.lowerBounds.map { get(it, map = map) },
)
}
}
}
@DelicateKotlinPoetApi(
message = "Mirror APIs don't give complete information on Kotlin types. Consider using" +
" the kotlinpoet-metadata APIs instead.",
)
@JvmName("get")
public fun javax.lang.model.type.WildcardType.asWildcardTypeName(): TypeName =
WildcardTypeName.get(this, mutableMapOf())
@DelicateKotlinPoetApi(
message = "Java reflection APIs don't give complete information on Kotlin types. Consider using" +
" the kotlinpoet-metadata APIs instead.",
)
@JvmName("get")
public fun WildcardType.asWildcardTypeName(): TypeName =
WildcardTypeName.get(this, mutableMapOf())
| apache-2.0 | adda6db437f9bbdd329e050efbff66da | 33.514706 | 100 | 0.691734 | 4.290676 | false | false | false | false |
CPRTeam/CCIP-Android | app/src/main/java/app/opass/ccip/ui/schedule/ScheduleFilterFragment.kt | 1 | 6299 | package app.opass.ccip.ui.schedule
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isGone
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.get
import androidx.lifecycle.observe
import androidx.recyclerview.widget.GridLayoutManager
import app.opass.ccip.databinding.FragmentScheduleFilterBinding
import app.opass.ccip.extension.doOnApplyWindowInsets
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.math.MathUtils
fun BottomSheetBehavior<*>.approxSlideOffset() = when (state) {
BottomSheetBehavior.STATE_EXPANDED -> 1F
BottomSheetBehavior.STATE_COLLAPSED -> 0F
else -> 0F
}
fun BottomSheetBehavior<*>.collapseOrHide() {
state = if (skipCollapsed) BottomSheetBehavior.STATE_HIDDEN
else BottomSheetBehavior.STATE_COLLAPSED
}
class ScheduleFilterFragment : Fragment() {
private var _binding: FragmentScheduleFilterBinding? = null
private val binding get() = _binding!!
private val vm by lazy { ViewModelProvider(requireParentFragment()).get<ScheduleViewModel>() }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentScheduleFilterBinding.inflate(inflater, container, false)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val sheetBehavior = BottomSheetBehavior.from(binding.filterSheet)
val peekHeight = sheetBehavior.peekHeight
binding.root.doOnApplyWindowInsets { _, insets, _, _ ->
sheetBehavior.peekHeight = insets.systemWindowInsetBottom + peekHeight
}
binding.filterHeaderRv.isNestedScrollingEnabled = false
binding.filterHeaderRv.adapter = FilterHeaderChipAdapter(requireContext())
binding.filterContentRv.run {
doOnApplyWindowInsets { v, insets, padding, _ ->
v.updatePadding(bottom = padding.bottom + insets.systemGestureInsets.bottom)
}
(layoutManager as GridLayoutManager).run {
spanCount = 2
spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
return when ((adapter as ScheduleFilterAdapter).currentList[position]) {
is SessionFilter.TagFilter -> 1
else -> 2
}
}
}
}
adapter = ScheduleFilterAdapter(requireContext()) { filter ->
when (filter) {
is SessionFilter.StarredFilter -> vm.toggleStarFilter()
is SessionFilter.TagFilter -> vm.toggleFilterTag(filter.tag.id)
}
}
}
binding.collapseButton.setOnClickListener {
sheetBehavior.collapseOrHide()
}
binding.clearButton.setOnClickListener {
vm.clearFilter()
}
binding.expand.setOnClickListener {
if (sheetBehavior.state == BottomSheetBehavior.STATE_COLLAPSED)
sheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
}
binding.filterSheet.post { updateSheetView(sheetBehavior.approxSlideOffset(), sheetBehavior) }
sheetBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
override fun onSlide(bottomSheet: View, slideOffset: Float) {
updateSheetView(slideOffset, sheetBehavior)
}
override fun onStateChanged(bottomSheet: View, newState: Int) {}
})
vm.shouldFilterSheetCollapse.observe(viewLifecycleOwner) { collapse ->
sheetBehavior.isHideable = !collapse
sheetBehavior.skipCollapsed = !collapse
if (!collapse && sheetBehavior.state == BottomSheetBehavior.STATE_COLLAPSED)
sheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN
}
MediatorLiveData<List<SessionFilter>>().apply {
val update = update@{
val starredOnly = vm.showStarredOnly.value!!
val tags = vm.tags.value ?: return@update
val selectedTags = vm.selectedTagIds.value!!
value =
emptyList<SessionFilter>() + SessionFilter.StarredFilter(starredOnly) + tags.map { tag ->
SessionFilter.TagFilter(
tag,
selectedTags.contains(tag.id)
)
}
}
addSource(vm.showStarredOnly) { update() }
addSource(vm.tags) { update() }
addSource(vm.selectedTagIds) { update() }
}.observe(viewLifecycleOwner) { filters ->
(binding.filterHeaderRv.adapter as FilterHeaderChipAdapter).submitList(filters.filter { f -> f.isActivated })
(binding.filterContentRv.adapter as ScheduleFilterAdapter).submitList(filters)
}
}
private fun updateSheetView(slideOffset: Float, sheetBehavior: BottomSheetBehavior<*>) {
val offset = slideOffset.coerceIn(0F, 1F)
val filterContentAlpha = if (sheetBehavior.skipCollapsed) 1F else MathUtils.lerp(0F, 1F, offset)
val peekAlpha = if (sheetBehavior.skipCollapsed) 0F else MathUtils.lerp(1F, 0F, offset)
binding.filterTitle.alpha = filterContentAlpha
binding.filterContentRv.alpha = filterContentAlpha
binding.collapseButton.alpha = filterContentAlpha
binding.clearButton.alpha = peekAlpha
binding.filterHeaderRv.alpha = peekAlpha
binding.collapseButton.run {
isClickable = offset == 1F
isGone = alpha == 0F
}
binding.clearButton.run {
isClickable = offset == 0F
isGone = alpha == 0F
}
}
}
| gpl-3.0 | dc438b056d4b28ff269378aecc572959 | 40.440789 | 121 | 0.646134 | 5.25793 | false | false | false | false |
ujpv/intellij-rust | src/test/kotlin/org/rust/ide/typing/RustBraceMatcherTest.kt | 1 | 803 | package org.rust.ide.typing
import org.rust.lang.RustFileType
import org.rust.lang.RustTestCaseBase
class RustBraceMatcherTest : RustTestCaseBase() {
override val dataPath: String get() = ""
fun testBeforeIdent() = doTest(
"fn main() { let _ = <caret>typing }",
'(',
"fn main() { let _ = (<caret>typing }"
)
fun testBeforeSemicolon() = doTest(
"fn main() { let _ = <caret>; }",
'(',
"fn main() { let _ = (<caret>); }"
)
fun testBeforeBrace() = doTest(
"fn foo<caret>{}",
'(',
"fn foo(<caret>){}"
)
private fun doTest(before: String, type: Char, after: String) {
myFixture.configureByText(RustFileType, before)
myFixture.type(type)
myFixture.checkResult(after)
}
}
| mit | 8b6c65ee7a77f7f7f9ad8abfe1550be5 | 23.333333 | 67 | 0.559153 | 3.917073 | false | true | false | false |
signed/intellij-community | platform/configuration-store-impl/testSrc/ModuleStoreRenameTest.kt | 1 | 5822 | package com.intellij.configurationStore
import com.intellij.ProjectTopics
import com.intellij.ide.highlighter.ModuleFileType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.ModuleListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.impl.ModuleRootManagerComponent
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.project.modifyModules
import com.intellij.project.rootManager
import com.intellij.testFramework.*
import com.intellij.util.Function
import com.intellij.util.SmartList
import com.intellij.util.io.systemIndependentPath
import org.assertj.core.api.Assertions.assertThat
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExternalResource
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import kotlin.properties.Delegates
internal class ModuleStoreRenameTest {
companion object {
@JvmField
@ClassRule val projectRule = ProjectRule()
private val Module.storage: FileBasedStorage
get() = (stateStore.stateStorageManager as StateStorageManagerImpl).getCachedFileStorages(listOf(StoragePathMacros.MODULE_FILE)).first()
}
var module: Module by Delegates.notNull()
// we test fireModuleRenamedByVfsEvent
private val oldModuleNames = SmartList<String>()
private val tempDirManager = TemporaryDirectory()
private val ruleChain = RuleChain(
tempDirManager,
object : ExternalResource() {
override fun before() {
runInEdtAndWait {
module = projectRule.createModule(tempDirManager.newPath(refreshVfs = true).resolve("m.iml"))
}
module.messageBus.connect().subscribe(ProjectTopics.MODULES, object : ModuleListener {
override fun modulesRenamed(project: Project, modules: MutableList<Module>, oldNameProvider: Function<Module, String>) {
assertThat(modules).containsOnly(module)
oldModuleNames.add(oldNameProvider.`fun`(module))
}
})
}
// should be invoked after project tearDown
override fun after() {
(ApplicationManager.getApplication().stateStore.stateStorageManager as StateStorageManagerImpl).getVirtualFileTracker()!!.remove {
if (it.storageManager.componentManager == module) {
throw AssertionError("Storage manager is not disposed, module $module, storage $it")
}
false
}
}
},
DisposeModulesRule(projectRule),
EdtRule()
)
@Rule fun getChain() = ruleChain
// project structure
@Test fun `rename module using model`() {
runInEdtAndWait { module.saveStore() }
val storage = module.storage
val oldFile = storage.file
assertThat(oldFile).isRegularFile()
val oldName = module.name
val newName = "foo"
runInEdtAndWait { projectRule.project.modifyModules { renameModule(module, newName) } }
assertRename(newName, oldFile)
assertThat(oldModuleNames).containsOnly(oldName)
}
// project view
@Test fun `rename module using rename virtual file`() {
runInEdtAndWait { module.saveStore() }
val storage = module.storage
val oldFile = storage.file
assertThat(oldFile).isRegularFile()
val oldName = module.name
val newName = "foo"
runInEdtAndWait { runWriteAction { LocalFileSystem.getInstance().refreshAndFindFileByPath(oldFile.systemIndependentPath)!!.rename(null, "$newName${ModuleFileType.DOT_DEFAULT_EXTENSION}") } }
assertRename(newName, oldFile)
assertThat(oldModuleNames).containsOnly(oldName)
}
// we cannot test external rename yet, because it is not supported - ModuleImpl doesn't support delete and create events (in case of external change we don't get move event, but get "delete old" and "create new")
private fun assertRename(newName: String, oldFile: Path) {
val newFile = module.storage.file
assertThat(newFile.fileName.toString()).isEqualTo("$newName${ModuleFileType.DOT_DEFAULT_EXTENSION}")
assertThat(oldFile)
.doesNotExist()
.isNotEqualTo(newFile)
assertThat(newFile).isRegularFile()
// ensure that macro value updated
assertThat(module.stateStore.stateStorageManager.expandMacros(StoragePathMacros.MODULE_FILE)).isEqualTo(newFile.systemIndependentPath)
}
@Test fun `rename module parent virtual dir`() {
runInEdtAndWait { module.saveStore() }
val storage = module.storage
val oldFile = storage.file
val parentVirtualDir = storage.virtualFile!!.parent
runInEdtAndWait { runWriteAction { parentVirtualDir.rename(null, UUID.randomUUID().toString()) } }
val newFile = Paths.get(parentVirtualDir.path, "${module.name}${ModuleFileType.DOT_DEFAULT_EXTENSION}")
try {
assertThat(newFile).isRegularFile()
assertRename(module.name, oldFile)
assertThat(oldModuleNames).isEmpty()
}
finally {
runInEdtAndWait { runWriteAction { parentVirtualDir.delete(this) } }
}
}
@Test
@RunsInEdt
fun `rename module source root`() {
runInEdtAndWait { module.saveStore() }
val storage = module.storage
val parentVirtualDir = storage.virtualFile!!.parent
val src = VfsTestUtil.createDir(parentVirtualDir, "foo")
runWriteAction {
PsiTestUtil.addSourceContentToRoots(module, src, false)
}
module.saveStore()
val rootManager = module.rootManager as ModuleRootManagerComponent
val stateModificationCount = rootManager.stateModificationCount
runWriteAction { src.rename(null, "bar") }
assertThat(stateModificationCount).isLessThan(rootManager.stateModificationCount)
}
} | apache-2.0 | 9309d03de99319434f5b6cc91ecad5d6 | 36.089172 | 214 | 0.743387 | 4.963342 | false | true | false | false |
etesync/android | app/src/main/java/com/etesync/syncadapter/ui/WebViewActivity.kt | 1 | 7786 | package com.etesync.syncadapter.ui
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.webkit.*
import android.widget.ProgressBar
import android.widget.Toast
import androidx.appcompat.app.ActionBar
import com.etesync.syncadapter.Constants
import com.etesync.syncadapter.R
class WebViewActivity : BaseActivity() {
private var mWebView: WebView? = null
private var mProgressBar: ProgressBar? = null
private var mToolbar: ActionBar? = null
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_webview)
mToolbar = supportActionBar
mToolbar!!.setDisplayHomeAsUpEnabled(true)
var uri = intent.getParcelableExtra<Uri>(KEY_URL)!!
uri = addQueryParams(uri)
mWebView = findViewById<View>(R.id.webView) as WebView
mProgressBar = findViewById<View>(R.id.progressBar) as ProgressBar
mWebView!!.settings.javaScriptEnabled = true
if (savedInstanceState == null) {
mWebView!!.loadUrl(uri.toString())
}
mWebView!!.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
title = view.title
}
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
return shouldOverrideUrl(Uri.parse(url))
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
return shouldOverrideUrl(request.url)
}
override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) {
loadErrorPage(failingUrl)
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
loadErrorPage(request.url.toString())
}
}
mWebView!!.webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView, progress: Int) {
if (progress == 100) {
mToolbar!!.title = view.title
mProgressBar!!.visibility = View.INVISIBLE
} else {
mToolbar!!.setTitle(R.string.loading)
mProgressBar!!.visibility = View.VISIBLE
mProgressBar!!.progress = progress
}
}
}
}
private fun addQueryParams(uri: Uri): Uri {
return uri.buildUpon().appendQueryParameter(QUERY_KEY_EMBEDDED, "1").build()
}
private fun loadErrorPage(failingUrl: String) {
val htmlData = "<html><title>" +
getString(R.string.loading_error_title) +
"</title>" +
"<style>" +
".btn {" +
" display: inline-block;" +
" padding: 6px 12px;" +
" font-size: 20px;" +
" font-weight: 400;" +
" line-height: 1.42857143;" +
" text-align: center;" +
" white-space: nowrap;" +
" vertical-align: middle;" +
" touch-action: manipulation;" +
" cursor: pointer;" +
" user-select: none;" +
" border: 1px solid #ccc;" +
" border-radius: 4px;" +
" color: #333;" +
" text-decoration: none;" +
" margin-top: 50px;" +
"}" +
"</style>" +
"<body>" +
"<div align=\"center\">" +
"<a class=\"btn\" href=\"" + failingUrl + "\">" + getString(R.string.loading_error_content) +
"</a>" +
"</form></body></html>"
mWebView!!.loadDataWithBaseURL("about:blank", htmlData, "text/html", "UTF-8", null)
mWebView!!.invalidate()
}
private fun shouldOverrideUrl(_uri: Uri): Boolean {
var uri = _uri
if (isAllowedUrl(uri)) {
if (uri.getQueryParameter(QUERY_KEY_EMBEDDED) != null) {
return false
} else {
uri = addQueryParams(uri)
mWebView!!.loadUrl(uri.toString())
return true
}
} else {
try {
startActivity(Intent(Intent.ACTION_VIEW, uri))
} catch (e: ActivityNotFoundException) {
Toast.makeText(this, getString(R.string.open_url_no_activity), Toast.LENGTH_LONG).show()
}
return true
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mWebView!!.saveState(outState)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
mWebView!!.restoreState(savedInstanceState)
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (mWebView!!.canGoBack()) {
mWebView!!.goBack()
return true
}
}
return super.onKeyDown(keyCode, event)
}
companion object {
private val KEY_URL = "url"
private val QUERY_KEY_EMBEDDED = "embedded"
fun openUrl(context: Context, uri: Uri) {
if (isAllowedUrl(uri)) {
val intent = Intent(context, WebViewActivity::class.java)
intent.putExtra(KEY_URL, uri)
context.startActivity(intent)
} else {
try {
context.startActivity(Intent(Intent.ACTION_VIEW, uri))
} catch (e: ActivityNotFoundException) {
Toast.makeText(context, context.getString(R.string.open_url_no_activity), Toast.LENGTH_LONG).show()
}
}
}
private fun uriEqual(uri1: Uri, uri2: Uri): Boolean {
return uri1.host == uri2.host && uri1.path == uri2.path
}
private fun allowedUris(allowedUris: Array<Uri>, uri2: Uri): Boolean {
for (uri in allowedUris) {
if (uriEqual(uri, uri2)) {
return true
}
}
return false
}
private fun isAllowedUrl(uri: Uri): Boolean {
val allowedUris = arrayOf(
Constants.faqUri,
Constants.helpUri,
Constants.registrationUrl,
Constants.dashboard,
Constants.webUri.buildUpon().appendEncodedPath("tos/").build(),
Constants.webUri.buildUpon().appendEncodedPath("about/").build(),
Constants.pricing,
)
val accountsUri = Constants.webUri.buildUpon().appendEncodedPath("accounts/").build()
return allowedUris(allowedUris, uri) || (
uri.host == accountsUri.host && uri.path!!.startsWith(accountsUri.path!!)
) || (
uri.host == Constants.etebaseDashboardPrefix.host && uri.path!!.startsWith(Constants.etebaseDashboardPrefix.path!!)
)
}
}
}
| gpl-3.0 | e16bb88e2e0a99bf54b79cd2f5931602 | 35.726415 | 135 | 0.552145 | 4.97508 | false | false | false | false |
MaibornWolff/codecharta | analysis/filter/StructureModifier/src/test/kotlin/de/maibornwolff/codecharta/filter/structuremodifier/PipedInputTestHelper.kt | 1 | 1067 | package de.maibornwolff.codecharta.filter.structuremodifier
import de.maibornwolff.codecharta.filter.structuremodifier.StructureModifier.Companion.mainWithInOut
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.io.PrintStream
fun executeForOutput(input: String, args: Array<String> = emptyArray()) =
outputAsString(input) { inputStream, outputStream, errorStream ->
mainWithInOut(inputStream, outputStream, errorStream, args)
}
fun outputAsString(input: String, aMethod: (input: InputStream, output: PrintStream, error: PrintStream) -> Unit) =
outputAsString(ByteArrayInputStream(input.toByteArray()), aMethod)
fun outputAsString(
inputStream: InputStream = System.`in`,
aMethod: (input: InputStream, output: PrintStream, error: PrintStream) -> Unit
) =
ByteArrayOutputStream().use { baOutputStream ->
PrintStream(baOutputStream).use { outputStream ->
aMethod(inputStream, outputStream, System.err)
}
baOutputStream.toString()
}
| bsd-3-clause | cf1a7caf543fc9a76ab2b8d9afd2b5e1 | 40.038462 | 115 | 0.756326 | 4.721239 | false | false | false | false |
grimrose/KotlinAdventCalendar2013 | src/test/kotlin/sample/KotlinTwitterSearchTest.kt | 1 | 1885 | import org.junit.Test as test
import sample.KotlinTwitterSearch
import twitter4j.Twitter
import twitter4j.Query
import twitter4j.Status
import java.util.ArrayList
import twitter4j.QueryResult
import org.mockito.Mockito
import org.mockito.Matchers
import kotlin.test.assertNotNull
import org.junit.Assert
import org.hamcrest.CoreMatchers
import twitter4j.User
import org.apache.commons.lang3.time.DateUtils
import org.vertx.java.core.json.JsonObject
import kotlin.test.assertEquals
class KotlinTwitterSearchTest {
test fun searchTest() {
// when
val twitter = Mockito.mock(javaClass<Twitter>())!!
val result = Mockito.mock(javaClass<QueryResult>())!!
var list = ArrayList<Status>()
val status = Mockito.mock(javaClass<Status>())!!
val user = Mockito.mock(javaClass<User>())!!
Mockito.`when`(user.getScreenName())?.thenReturn("user1")
Mockito.`when`(status.getUser())?.thenReturn(user)
Mockito.`when`(status.getText())?.thenReturn("Hello Kotlin!")
val date = DateUtils.parseDate("2013-12-22 12:34:56", "yyyy-MM-dd HH:mm:ss")
Mockito.`when`(status.getCreatedAt())?.thenReturn(date)
list.add(status)
Mockito.`when`(result.getTweets())?.thenReturn(list)
Mockito.`when`(twitter.search(Matchers.any(javaClass<Query>())))?.thenReturn(result)
var sut = KotlinTwitterSearch(twitter)
// then
val actual = sut.search("hoge")
// expect
assertNotNull(actual)
val tweets = actual?.getArray("tweets")
assertNotNull(tweets)
assertEquals(1, tweets?.count())
val tweet = tweets?.get<JsonObject>(0)
assertEquals("user1", tweet?.getString("user"))
assertEquals("2013-12-22 12:34:56", tweet?.getString("time"))
assertEquals("Hello Kotlin!", tweet?.getString("tweet"))
}
}
| apache-2.0 | f4068afcc55036b6078a979f702a7369 | 28 | 92 | 0.675332 | 4.198218 | false | true | false | false |
VladRassokhin/intellij-hcl | src/kotlin/org/intellij/plugins/hil/refactoring/ILIntroduceVariableHandler.kt | 1 | 17066 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.plugins.hil.refactoring
import com.intellij.codeInsight.CodeInsightUtilCore
import com.intellij.codeInsight.template.impl.TemplateManagerImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.Result
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Pass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtilCore
import com.intellij.refactoring.IntroduceTargetChooser
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.introduce.inplace.OccurrencesChooser
import com.intellij.refactoring.listeners.RefactoringEventData
import com.intellij.refactoring.listeners.RefactoringEventListener
import com.intellij.refactoring.util.CommonRefactoringUtil
import org.intellij.plugins.hcl.HCLBundle
import org.intellij.plugins.hcl.psi.HCLBlock
import org.intellij.plugins.hcl.terraform.config.model.Type
import org.intellij.plugins.hcl.terraform.config.model.Types
import org.intellij.plugins.hcl.terraform.config.psi.TerraformElementGenerator
import org.intellij.plugins.hcl.terraform.config.refactoring.BaseIntroduceOperation
import org.intellij.plugins.hcl.terraform.config.refactoring.BaseIntroduceVariableHandler
import org.intellij.plugins.hil.psi.*
import org.intellij.plugins.hil.psi.impl.HILPsiImplUtils
import org.intellij.plugins.hil.psi.impl.getHCLHost
import org.jetbrains.annotations.NonNls
import java.util.*
open class ILIntroduceVariableHandler : BaseIntroduceVariableHandler<ILExpression>() {
companion object {
@NonNls val REFACTORING_ID = "hil.refactoring.extractVariable"
fun findOccurrenceUnderCaret(occurrences: List<PsiElement>, editor: Editor): PsiElement? {
if (occurrences.isEmpty()) {
return null
}
val offset = editor.caretModel.offset
occurrences.firstOrNull { it.textRange.contains(offset) }?.let { return it }
val line = editor.document.getLineNumber(offset)
for (occurrence in occurrences) {
PsiUtilCore.ensureValid(occurrence)
if (occurrence.isValid && editor.document.getLineNumber(occurrence.textRange.startOffset) == line) {
return occurrence
}
}
for (occurrence in occurrences) {
PsiUtilCore.ensureValid(occurrence)
return occurrence
}
return null
}
fun findAnchor(occurrence: PsiElement): PsiElement? {
return findAnchor(listOf(occurrence))
}
fun findAnchor(occurrences: List<PsiElement>): PsiElement? {
val hosts = occurrences.mapNotNull {
if (it is ILExpression) {
it.getHCLHost()
} else {
it
}
}
val minOffset = hosts
.map { it.textRange.startOffset }
.min()
?: Integer.MAX_VALUE
val statements = hosts.firstOrNull()?.containingFile ?: return null
var child: PsiElement? = null
for (aChildren in statements.children) {
child = aChildren
if (child.textRange.contains(minOffset)) {
break
}
}
return child
}
}
override fun createOperation(editor: Editor, file: PsiFile, project: Project) = IntroduceOperation(project, editor, file, null)
override fun performAction(operation: BaseIntroduceOperation<ILExpression>) {
if (operation !is IntroduceOperation) return
val file = operation.file
if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) {
return
}
val editor = operation.editor
if (editor.settings.isVariableInplaceRenameEnabled) {
val templateState = TemplateManagerImpl.getTemplateState(operation.editor)
if (templateState != null && !templateState.isFinished) {
return
}
}
var element1: PsiElement? = null
var element2: PsiElement? = null
val selectionModel = editor.selectionModel
if (selectionModel.hasSelection()) {
element1 = file.findElementAt(selectionModel.selectionStart)
element2 = file.findElementAt(selectionModel.selectionEnd - 1)
if (element1 is PsiWhiteSpace) {
val startOffset = element1.textRange.endOffset
element1 = file.findElementAt(startOffset)
}
if (element2 is PsiWhiteSpace) {
val endOffset = element2.textRange.startOffset
element2 = file.findElementAt(endOffset - 1)
}
} else {
if (smartIntroduce(operation)) {
return
}
val caretModel = editor.caretModel
val document = editor.document
val lineNumber = document.getLineNumber(caretModel.offset)
if (lineNumber >= 0 && lineNumber < document.lineCount) {
element1 = file.findElementAt(document.getLineStartOffset(lineNumber))
element2 = file.findElementAt(document.getLineEndOffset(lineNumber) - 1)
}
}
val project = operation.project
if (element1 == null || element2 == null) {
showCannotPerformError(project, editor)
return
}
element1 = ILRefactoringUtil.getSelectedExpression(element1, element2)
if (element1 == null || !isValidIntroduceVariant(element1)) {
showCannotPerformError(project, editor)
return
}
if (!checkIntroduceContext(file, editor, element1)) {
return
}
operation.element = element1
performActionOnElement(operation)
}
private fun smartIntroduce(operation: IntroduceOperation): Boolean {
val editor = operation.editor
val file = operation.file
val offset = editor.caretModel.offset
var elementAtCaret = file.findElementAt(offset)
if ((elementAtCaret is PsiWhiteSpace && offset == elementAtCaret.textOffset || elementAtCaret == null) && offset > 0) {
elementAtCaret = file.findElementAt(offset - 1)
}
if (!checkIntroduceContext(file, editor, elementAtCaret)) return true
val expressions = ArrayList<ILExpression>()
while (elementAtCaret != null) {
if (elementAtCaret is ILExpressionHolder || elementAtCaret is ILPsiFile) {
break
}
if (elementAtCaret is ILExpression && isValidIntroduceVariant(elementAtCaret)) {
expressions.add(elementAtCaret)
}
elementAtCaret = elementAtCaret.parent
}
if (expressions.size == 1 || ApplicationManager.getApplication().isUnitTestMode) {
operation.element = expressions[0]
performActionOnElement(operation)
return true
} else if (expressions.size > 1) {
IntroduceTargetChooser.showChooser(editor, expressions, object : Pass<ILExpression>() {
override fun pass(expression: ILExpression) {
operation.element = expression
performActionOnElement(operation)
}
}, ILExpression::getText)
return true
}
return false
}
protected fun checkIntroduceContext(file: PsiFile, editor: Editor, element: PsiElement?): Boolean {
if (!isValidIntroduceContext(element)) {
showCannotPerformError(file.project, editor)
return false
}
return true
}
protected fun isValidIntroduceContext(element: PsiElement?): Boolean {
// TODO: Investigate cases when refactoring should not be supported
return element != null
}
private fun isValidIntroduceVariant(element: PsiElement): Boolean {
val call = element.parent as? ILMethodCallExpression
if (call != null && call.callee === element) {
return false
}
if (element is ILParameterList) return false
return element is ILLiteralExpression
}
private fun performActionOnElement(operation: IntroduceOperation) {
val element = operation.element
val initializer = element as ILExpression?
operation.initializer = initializer
if (initializer != null) {
operation.occurrences = getOccurrences(element, initializer)
operation.suggestedNames = getSuggestedNames(initializer)
}
if (operation.occurrences.isEmpty()) {
operation.isReplaceAll = false
}
performActionOnElementOccurrences(operation)
}
protected fun performActionOnElementOccurrences(operation: IntroduceOperation) {
val editor = operation.editor
if (editor.settings.isVariableInplaceRenameEnabled) {
ensureName(operation)
if (operation.isReplaceAll) {
performInplaceIntroduce(operation)
} else {
OccurrencesChooser.simpleChooser<PsiElement>(editor).showChooser(operation.element, operation.occurrences, object : Pass<OccurrencesChooser.ReplaceChoice>() {
override fun pass(replaceChoice: OccurrencesChooser.ReplaceChoice) {
operation.isReplaceAll = replaceChoice == OccurrencesChooser.ReplaceChoice.ALL
performInplaceIntroduce(operation)
}
})
}
} else {
performIntroduceWithDialog(operation)
}
}
protected fun performInplaceIntroduce(operation: IntroduceOperation) {
val statement = performRefactoring(operation)
if (statement is HCLBlock) {
val target = statement.nameIdentifier!!
val occurrences = operation.occurrences
val occurrence = findOccurrenceUnderCaret(occurrences, operation.editor)
var elementForCaret = occurrence ?: target
if (elementForCaret is ILSelectExpression) {
elementForCaret = elementForCaret.field as ILVariable
}
operation.editor.caretModel.moveToOffset(elementForCaret.textRange.startOffset)
// TODO: Uncomment once have idea hw to change name of variable from it's usage
// val introducer: InplaceVariableIntroducer<PsiElement> = object : InplaceVariableIntroducer<PsiElement>(target as HCLStringLiteralMixin, operation.editor, operation.project, "Introduce Variable", operation.occurrences.toTypedArray(), null) {
// override fun checkLocalScope(): PsiElement? {
// return target.containingFile
// }
// }
// introducer.performInplaceRefactoring(LinkedHashSet(operation.suggestedNames))
}
}
protected fun performIntroduceWithDialog(operation: IntroduceOperation) {
val project = operation.project
if (operation.name == null) {
val dialog = ILIntroduceDialog(project, "Introduce Variable", validator, operation)
if (!dialog.showAndGet()) {
return
}
operation.name = dialog.name
operation.isReplaceAll = dialog.doReplaceAllOccurrences()
// TODO: Support introducing in separate file
//operation.setInitPlace(dialog.getInitPlace())
}
val declaration = performRefactoring(operation) ?: return
val editor = operation.editor
editor.caretModel.moveToOffset(declaration.textRange.endOffset)
editor.selectionModel.removeSelection()
}
protected fun performRefactoring(operation: IntroduceOperation): PsiElement? {
var declaration: PsiElement? = createDeclaration(operation)
if (declaration == null) {
showCannotPerformError(operation.project, operation.editor)
return null
}
declaration = performReplace(declaration, operation)
declaration = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(declaration)
return declaration
}
private fun createDeclaration(operation: IntroduceOperation): PsiElement? {
val expr = operation.initializer ?: return null
val name = operation.name ?: return null
val type: Type = expr.getType() ?: Types.String
return TerraformElementGenerator(operation.project).createVariable(name, type, expr)
}
private fun performReplace(declaration: PsiElement,
operation: IntroduceOperation): PsiElement {
val expression = operation.initializer!!
val project = operation.project
return object : WriteCommandAction<PsiElement>(project, expression.getHCLHost()?.containingFile ?: expression.containingFile) {
@Throws(Throwable::class)
override fun run(result: Result<PsiElement>) {
try {
val afterData = RefactoringEventData()
afterData.addElement(declaration)
project.messageBus.syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC)
.refactoringStarted(REFACTORING_ID, afterData)
result.setResult(addDeclaration(operation, declaration))
val newExpression = createExpression(project, operation.name!!)
if (operation.isReplaceAll) {
operation.occurrences = operation.occurrences.map { replaceExpression(it, newExpression) }
} else {
val replaced = replaceExpression(expression, newExpression)
operation.occurrences = listOf(replaced)
}
} finally {
val afterData = RefactoringEventData()
afterData.addElement(declaration)
project.messageBus.syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC)
.refactoringDone(REFACTORING_ID, afterData)
}
}
}.execute().resultObject
}
private fun createExpression(project: Project, name: String): PsiElement {
return ILElementGenerator(project).createVarReference(name)
}
protected fun replaceExpression(expression: PsiElement, newExpression: PsiElement): PsiElement {
return outermostParenthesizedILExpression(expression).replace(newExpression)
}
fun addDeclaration(operation: IntroduceOperation, declaration: PsiElement): PsiElement? {
val anchor = if (operation.isReplaceAll) findAnchor(operation.occurrences) else findAnchor(operation.initializer!!)
if (anchor == null) {
CommonRefactoringUtil.showErrorHint(
operation.project,
operation.editor,
RefactoringBundle.getCannotRefactorMessage(HCLBundle.message("refactoring.introduce.anchor.error")),
HCLBundle.message("refactoring.introduce.error"), null
)
return null
}
return anchor.parent.addBefore(declaration, anchor)
}
protected fun getOccurrences(element: PsiElement?, expression: ILExpression): List<PsiElement> {
var context: PsiElement? = PsiTreeUtil.getParentOfType(element, ILExpressionHolder::class.java, true) ?: element
if (context == null) {
context = expression.containingFile
}
return ILRefactoringUtil.getOccurrences(expression, context)
}
val validator = IntroduceValidator()
fun getSuggestedNames(expression: ILExpression): Collection<String> {
val candidates = generateSuggestedNames(expression)
val res = candidates
.filter { validator.checkPossibleName(it, expression) }
.toMutableList()
if (res.isEmpty()) { // no available names found, generate disambiguated suggestions
for (name in candidates) {
var index = 1
while (!validator.checkPossibleName(name + index, expression)) {
index++
}
res.add(name + index)
}
}
if (res.isEmpty()) {
res += "a"
}
return res
}
protected fun ensureName(operation: IntroduceOperation) {
if (operation.name == null) {
val suggestedNames = operation.suggestedNames
if (suggestedNames != null && suggestedNames.isNotEmpty()) {
operation.name = suggestedNames.first()
} else {
operation.name = "x"
}
}
}
protected fun generateSuggestedNames(expression: ILExpression): Collection<String> {
val candidates = LinkedHashSet<String>()
var text = expression.text
if (expression is ILMethodCallExpression) {
text = expression.callee.text
} // TODO: Add candidates based on HCLBlock property name
if (text != null) {
candidates.addAll(ILRefactoringUtil.generateNames(text))
}
val type = expression.getType()
if (type != null) {
candidates.addAll(ILRefactoringUtil.generateNamesByType(type.name))
}
val list = PsiTreeUtil.getParentOfType(expression, ILParameterList::class.java)
if (list != null) {
val call = list.parent as ILMethodCallExpression
// TODO: resolve called method name and all known argument names
candidates.add("arg")
}
return candidates
}
private fun outermostParenthesizedILExpression(expr: PsiElement): PsiElement {
if (expr !is ILExpression) return expr
var e: ILExpression = expr
while (e.parent is ILParenthesizedExpression) {
e = e.parent as ILParenthesizedExpression
}
return e
}
}
private fun ILExpression.getType(): Type? {
return HILPsiImplUtils.getType(this)
}
| apache-2.0 | 0f3aa33e77bac8111d462200768ba389 | 36.262009 | 248 | 0.712821 | 4.873215 | false | false | false | false |
RyanAndroidTaylor/Rapido | rapidocommon/src/main/java/com/izeni/rapidocommon/kLog.kt | 1 | 5550 | @file:Suppress("unused")
package com.izeni.rapidocommon
import android.support.annotation.IntDef
import android.util.Log
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 Camaron Crowe.
*
* 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.
**/
private val MAX_LOG_LENGTH = 4000
object kLog {
const val WTF: Int = 8
const val ASSERT: Int = 7
const val ERROR: Int = 6
const val WARN: Int = 5
const val INFO: Int = 4
const val DEBUG: Int = 3
const val VERBOSE: Int = 2
const val ALL: Int = 1
@LoggingLevel var loggingLevel: Int = ALL
var defaultTag = "kLog"
var postPrintLogic: (priority: Int, tag: String, msg: String) -> Boolean = { p, t, m -> true }
@IntDef(*longArrayOf(8, 7, 6, 5, 4, 3, 2, 1))
@Retention(AnnotationRetention.SOURCE)
annotation class LoggingLevel
var enableLineWrapping: Boolean = true
var enableStackLog: Boolean = true
@Suppress("NOTHING_TO_INLINE")
inline fun stack_trace(message: String?, stack_depth: Int = 4): String {
val stackTrace = Thread.currentThread().stackTrace
val fullClassName = stackTrace[stack_depth].fileName
val methodName = stackTrace[stack_depth].methodName
val lineNumber = stackTrace[stack_depth].lineNumber
val shortMN = methodName.substring(0, 1).toUpperCase() + methodName.substring(1)
return "($fullClassName:$lineNumber) $shortMN() - $message"
}
private fun logMessage(priority: Int, tag: String, message: String) {
if (message.length < MAX_LOG_LENGTH || !enableLineWrapping) {
println(priority, tag, message)
return
}
// Split by line, then ensure each line can fit into Log's maximum length.
var i = 0
val length = message.length
while (i < length) {
var newline = message.indexOf('\n', i)
newline = if (newline != -1) newline else length
do {
val end = Math.min(newline, i + MAX_LOG_LENGTH)
println(priority, tag, message.substring(i, end))
i = end
} while (i < newline)
i++
}
}
fun println(priority: Int, tag: String, msg: String): Int {
if (!postPrintLogic(priority, tag, msg)) return 0
return Log.println(priority, tag, msg)
}
fun log(message: String?, tag: String? = null, t: Throwable? = null, @LoggingLevel priority: Int = DEBUG, log_line: Boolean = enableStackLog) {
if (priority >= loggingLevel) {
var msg = if (log_line) stack_trace(message) else message
if (msg == null || msg.isEmpty()) {
if (t == null) return
msg = Log.getStackTraceString(t)
} else {
if (t != null) msg += "\n" + Log.getStackTraceString(t)
}
logMessage(priority, tag ?: defaultTag, msg!!)
}
}
}
fun v(message: String?, tag: String? = null, t: Throwable? = null, log_line: Boolean = kLog.enableStackLog) {
kLog.log(if (log_line) kLog.stack_trace(message) else message, tag, t, log_line = false, priority = kLog.VERBOSE)
}
fun d(message: String?, tag: String? = null, t: Throwable? = null, log_line: Boolean = kLog.enableStackLog) {
kLog.log(if (log_line) kLog.stack_trace(message) else message, tag, t, log_line = false, priority = kLog.DEBUG)
}
fun i(message: String?, tag: String? = null, t: Throwable? = null, log_line: Boolean = kLog.enableStackLog) {
kLog.log(if (log_line) kLog.stack_trace(message) else message, tag, t, log_line = false, priority = kLog.INFO)
}
fun w(message: String?, tag: String? = null, t: Throwable? = null, log_line: Boolean = kLog.enableStackLog) {
kLog.log(if (log_line) kLog.stack_trace(message) else message, tag, t, log_line = false, priority = kLog.WARN)
}
fun e(message: String?, tag: String? = null, t: Throwable? = null, log_line: Boolean = kLog.enableStackLog) {
kLog.log(if (log_line) kLog.stack_trace(message) else message, tag, t, log_line = false, priority = kLog.ERROR)
}
fun a(message: String?, tag: String? = null, t: Throwable? = null, log_line: Boolean = kLog.enableStackLog) {
kLog.log(if (log_line) kLog.stack_trace(message) else message, tag, t, log_line = false, priority = kLog.ASSERT)
}
fun wtf(message: String?, tag: String? = null, t: Throwable? = null, log_line: Boolean = kLog.enableStackLog) {
kLog.log(if (log_line) kLog.stack_trace(message) else message, tag, t, log_line = false, priority = kLog.WTF)
} | mit | 137b126a8e03f98f8b8294f05695cee3 | 39.518248 | 147 | 0.653514 | 3.692615 | false | false | false | false |
luoyuan800/NeverEnd | dataModel/src/cn/luo/yuan/maze/model/real/level/NonsrRealLevel.kt | 1 | 3739 | package cn.luo.yuan.maze.model.real.level
/**
* Created by luoyuan on 2017/9/7.
*/
enum class NonsrRealLevel(val point: Int, val level: Int, val display: String) {
Bronze(5, 10, "青铜"), Silver(8, 10, "白银"), Gold(15, 10, "黄金"), Platinum(20, 10, "铂金"), Diamond(30, 10, "钻石"), Adamas(40, 10, "金刚"), Stars(40, 10, "星辰");
companion object {
fun getLevel(p: Long): String {
var point = p
if (point < Bronze.level * Bronze.point) {
return buildLevelString(Bronze, point)
}
point -= Bronze.level * Bronze.point
if (point < Silver.point * Silver.level) {
return buildLevelString(Silver, point)
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level
if (point < Gold.point * Gold.level) {
return buildLevelString(Gold, point)
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level + Gold.point * Gold.level
if (point < Platinum.point * Platinum.level) {
return buildLevelString(Platinum, point)
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level + Gold.point * Gold.level + Platinum.point * Platinum.level
if (point < Diamond.point * Diamond.level) {
return buildLevelString(Diamond, point)
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level + Gold.point * Gold.level + Platinum.point * Platinum.level + Diamond.point * Diamond.level
if (point < Adamas.point * Adamas.level) {
return buildLevelString(Adamas, point)
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level + Gold.point * Gold.level +
Platinum.point * Platinum.level + Diamond.point * Diamond.level + Adamas.point * Adamas.level
return buildLevelString(Stars, point)
}
private fun buildLevelString(level: NonsrRealLevel, point: Long) = "${level.display} + ${point / level.point}"
fun getCurrentLevel(p: Long): NonsrRealLevel {
var point = p
if (point < Bronze.level * Bronze.point) {
return Bronze
}
point -= Bronze.level * Bronze.point
if (point < Silver.point * Silver.level) {
return Silver
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level
if (point < Gold.point * Gold.level) {
return Gold
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level + Gold.point * Gold.level
if (point < Platinum.point * Platinum.level) {
return Platinum
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level + Gold.point * Gold.level + Platinum.point * Platinum.level
if (point < Diamond.point * Diamond.level) {
return Diamond
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level + Gold.point * Gold.level + Platinum.point * Platinum.level + Diamond.point * Diamond.level
if (point < Adamas.point * Adamas.level) {
return Adamas
}
point -= Bronze.level * Bronze.point + Silver.point * Silver.level + Gold.point * Gold.level +
Platinum.point * Platinum.level + Diamond.point * Diamond.level + Adamas.point * Adamas.level
return Stars
}
fun isLevelUp(cp: Long, pp:Long):Boolean{
return getCurrentLevel(cp)!= getCurrentLevel(pp)
}
}
} | bsd-3-clause | 86019fde2e62863ec5a0b669c580a26f | 47.842105 | 170 | 0.564807 | 3.551196 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/misc/vector/EnumFacing.kt | 2 | 2590 | package com.cout970.magneticraft.misc.vector
import com.cout970.magneticraft.misc.toRadians
import com.cout970.magneticraft.misc.toRads
import net.minecraft.util.EnumFacing
import net.minecraft.util.EnumFacing.*
import net.minecraft.util.math.AxisAlignedBB
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Vec3d
/**
* Created by cout970 on 2017/02/20.
*/
fun EnumFacing.getRelative(other: EnumFacing): EnumFacing = when (this) {
EnumFacing.DOWN, EnumFacing.UP, EnumFacing.NORTH -> other
EnumFacing.SOUTH -> other.safeRotateY().safeRotateY()
EnumFacing.WEST -> other.safeRotateYCCW()
EnumFacing.EAST -> other.safeRotateY()
}
fun EnumFacing.safeRotateYCCW(): EnumFacing {
return when (this) {
NORTH -> WEST
EAST -> NORTH
SOUTH -> EAST
WEST -> SOUTH
else -> this
}
}
fun EnumFacing.safeRotateY(): EnumFacing {
return when (this) {
NORTH -> EAST
EAST -> SOUTH
SOUTH -> WEST
WEST -> NORTH
else -> this
}
}
fun EnumFacing.rotatePoint(origin: BlockPos = BlockPos.ORIGIN, point: BlockPos): BlockPos {
val rel = point - origin
val rot = when (this) {
DOWN -> return BlockPos(origin + BlockPos(Vec3d(rel).rotatePitch(-90.0f)))
UP -> return BlockPos(origin + BlockPos(Vec3d(rel).rotatePitch(90.0f)))
NORTH -> return point
SOUTH -> 180.0f
WEST -> 90.0f
EAST -> 360f - 90.0f
}
val pos2 = Vec3d(rel).rotateYaw(rot.toRadians())
val pos3 = pos2.transform { Math.round(it).toDouble() }
return BlockPos(origin + BlockPos(pos3))
}
/**
* The default value is associated to the NORTH direction
*/
fun EnumFacing.rotatePoint(origin: Vec3d, point: Vec3d): Vec3d {
val rel = point - origin
val rot = when (this) {
DOWN -> return origin + rel.rotatePitch(90.toRads().toFloat())
UP -> return origin + rel.rotatePitch(-90.toRads().toFloat())
NORTH -> return point
SOUTH -> 180.0f
WEST -> 90.0f
EAST -> -90.0f
}
return origin + rel.rotateYaw(rot.toRadians())
}
fun EnumFacing.rotateBox(origin: Vec3d, box: AxisAlignedBB): AxisAlignedBB {
val min = Vec3d(box.minX, box.minY, box.minZ)
val max = Vec3d(box.maxX, box.maxY, box.maxZ)
return rotatePoint(origin, min) createAABBUsing rotatePoint(origin, max)
}
fun EnumFacing.isHorizontal() = this != UP && this != DOWN
fun EnumFacing.toBlockPos() = directionVec.toBlockPos()
fun EnumFacing.toVector3() = directionVec.toVec3d()
inline val EnumFacing.lowercaseName get() = name2 | gpl-2.0 | 1b9f4a099599898f7bec125dc90caf66 | 29.845238 | 91 | 0.662934 | 3.684211 | false | false | false | false |
collinx/susi_android | app/src/main/java/org/fossasia/susi/ai/skills/skilldetails/SkillDetailsFragment.kt | 1 | 10951 | package org.fossasia.susi.ai.skills.skilldetails
import android.support.v4.app.Fragment
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.Html
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.fragment_skill_details.*
import org.fossasia.susi.ai.R
import org.fossasia.susi.ai.chat.ChatActivity
import org.fossasia.susi.ai.rest.responses.susi.SkillData
import org.fossasia.susi.ai.skills.SkillsActivity
import org.fossasia.susi.ai.skills.skilldetails.adapters.recycleradapters.SkillExamplesAdapter
import java.io.Serializable
import android.net.Uri
/**
*
* Created by chiragw15 on 24/8/17.
*/
class SkillDetailsFragment: Fragment() {
lateinit var skillData: SkillData
lateinit var skillGroup: String
lateinit var skillTag: String
val imageLink = "https://raw.githubusercontent.com/fossasia/susi_skill_data/master/models/general/"
companion object {
val SKILL_KEY = "skill_key"
val SKILL_TAG = "skill_tag"
val SKILL_GROUP = "skill_group"
fun newInstance(skillData: SkillData, skillGroup: String, skillTag: String): SkillDetailsFragment {
val fragment = SkillDetailsFragment()
val bundle = Bundle()
bundle.putSerializable(SKILL_KEY, skillData as Serializable)
bundle.putString(SKILL_GROUP, skillGroup)
bundle.putString(SKILL_TAG, skillTag)
fragment.arguments = bundle
return fragment
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
skillData = arguments.getSerializable(
SKILL_KEY) as SkillData
skillGroup = arguments.getString(SKILL_GROUP)
skillTag = arguments.getString(SKILL_TAG)
return inflater.inflate(R.layout.fragment_skill_details, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
if(skillData.skillName != null && !skillData.skillName.isEmpty())
(activity as SkillsActivity).title = skillData.skillName
setupUI()
super.onViewCreated(view, savedInstanceState)
}
fun setupUI() {
setImage()
setName()
setAuthor()
setTryButton()
setShareButton()
setDescription()
setExamples()
setRating()
setDynamicContent()
setPolicy()
setTerms()
}
fun setImage() {
skill_detail_image.setImageResource(R.drawable.ic_susi)
if(skillData.image != null && !skillData.image.isEmpty()){
Picasso.with(activity.applicationContext).load(StringBuilder(imageLink)
.append(skillGroup).append("/en/").append(skillData.image).toString())
.error(R.drawable.ic_susi)
.fit().centerCrop()
.into(skill_detail_image)
}
}
fun setName() {
skill_detail_title.text = activity.getString(R.string.no_skill_name)
if(skillData.skillName != null && !skillData.skillName.isEmpty()){
skill_detail_title.text = skillData.skillName
}
}
fun setAuthor() {
skill_detail_author.text = "Author : ${activity.getString(R.string.no_skill_author)}"
if(skillData.author != null && !skillData.author.isEmpty()){
if(skillData.authorUrl == null || skillData.authorUrl.isEmpty())
skill_detail_author.text = "Author : ${skillData.skillName}"
else {
skill_detail_author.linksClickable = true
skill_detail_author.movementMethod = LinkMovementMethod.getInstance()
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
skill_detail_author.text = Html.fromHtml("Author : <a href=\"${skillData.authorUrl}\">${skillData.author}</a>", Html.FROM_HTML_MODE_COMPACT)
} else {
skill_detail_author.text = Html.fromHtml("Author : <a href=\"${skillData.authorUrl}\">${skillData.author}</a>")
}
}
}
}
fun setTryButton() {
if(skillData.examples == null || skillData.examples.isEmpty())
skill_detail_try_button.visibility = View.GONE
skill_detail_try_button.setOnClickListener {
activity.overridePendingTransition(R.anim.trans_right_in, R.anim.trans_right_out)
val intent = Intent(activity, ChatActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
if(skillData.examples != null && skillData.examples.isNotEmpty())
intent.putExtra("example",skillData.examples[0])
else
intent.putExtra("example","")
startActivity(intent)
activity.finish()
}
}
fun setShareButton() {
if(skillTag == null || skillTag.isEmpty()) {
skill_detail_share_button.visibility = View.GONE
return
}
skill_detail_share_button.setOnClickListener {
val shareUriBuilder = Uri.Builder()
shareUriBuilder.scheme("https")
.authority("skills.susi.ai")
.appendPath(skillGroup)
.appendPath(skillTag)
.appendPath("en")
val sendIntent = Intent()
sendIntent.action = Intent.ACTION_SEND
sendIntent.putExtra(Intent.EXTRA_TEXT, shareUriBuilder.build().toString())
sendIntent.type = "text/plain"
context.startActivity(sendIntent)
}
}
fun setDescription() {
skill_detail_description.text = activity.getString(R.string.no_skill_description)
if( skillData.descriptions != null && !skillData.descriptions.isEmpty()){
skill_detail_description.text = skillData.descriptions
}
}
fun setExamples() {
if(skillData.examples != null) {
skill_detail_examples.setHasFixedSize(true)
val mLayoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
skill_detail_examples.layoutManager = mLayoutManager
skill_detail_examples.adapter = SkillExamplesAdapter(activity, skillData.examples)
}
}
fun setRating() {
if(skillData.skillRating == null) {
skill_detail_rating_positive.text = "Skill not rated yet"
val params = skill_detail_rating_positive.layoutParams
params.width = 344
skill_detail_rating_positive.layoutParams = params
skill_detail_rating_negative.visibility = View.GONE
skill_detail_rating_thumbs_up.visibility = View.GONE
skill_detail_rating_thumbs_down.visibility = View.GONE
} else {
skill_detail_rating_positive.text = "Positive: " + skillData.skillRating?.positive
skill_detail_rating_negative.text = "Negative: " + skillData.skillRating?.negative
val positiveColor = getRatedColor(skillData.skillRating?.positive, "Positive")
val negativeColor = getRatedColor(skillData.skillRating?.negative, "Negative")
skill_detail_rating_thumbs_up.setColorFilter(positiveColor)
skill_detail_rating_thumbs_down.setColorFilter(negativeColor)
}
}
private fun getRatedColor(rating: Int?, s: String?): Int {
var resId = R.color.colorAccent
if (rating != null) {
when (s) {
"Positive" ->
if (rating < 10)
resId = R.color.md_red_100
else if (rating in 10..19)
resId = R.color.md_red_200
else if (rating in 20..29)
resId = R.color.md_red_300
else if (rating in 30..39)
resId = R.color.md_red_300
else if (rating in 40..49)
resId = R.color.md_red_300
else
resId = R.color.md_red_400
"Negative" ->
if (rating < 10)
resId = R.color.md_blue_100
else if (rating in 10..19)
resId = R.color.md_blue_200
else if (rating in 20..29)
resId = R.color.md_blue_300
else if (rating in 30..39)
resId = R.color.md_blue_300
else if (rating in 40..49)
resId = R.color.md_blue_300
else
resId = R.color.md_blue_400
}
}
return resources.getColor(resId)
}
fun setDynamicContent() {
if(skillData.dynamicContent == null) {
skill_detail_content.visibility = View.GONE
} else {
if(skillData.dynamicContent!!) {
skill_detail_content.text = "Content type: Dynamic"
} else {
skill_detail_content.text = "Content type: Static"
}
}
}
fun setPolicy() {
if(skillData.developerPrivacyPolicy == null || skillData.developerPrivacyPolicy.isEmpty()) {
skill_detail_policy.visibility = View.GONE
} else {
skill_detail_policy.linksClickable = true
skill_detail_policy.movementMethod = LinkMovementMethod.getInstance()
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
skill_detail_policy.text = Html.fromHtml("<a href=\"${skillData.developerPrivacyPolicy}\">Developer's Privacy Policy</a>", Html.FROM_HTML_MODE_COMPACT)
} else {
skill_detail_policy.text = Html.fromHtml("<a href=\"${skillData.developerPrivacyPolicy}\">Developer's Privacy Policy</a>")
}
}
}
fun setTerms() {
if(skillData.termsOfUse == null || skillData.termsOfUse.isEmpty()) {
skill_detail_terms.visibility = View.GONE
} else {
skill_detail_terms.linksClickable = true
skill_detail_terms.movementMethod = LinkMovementMethod.getInstance()
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
skill_detail_terms.text = Html.fromHtml("<a href=\"${skillData.termsOfUse}\">Terms of use</a>", Html.FROM_HTML_MODE_COMPACT)
} else {
skill_detail_terms.text = Html.fromHtml("<a href=\"${skillData.termsOfUse}\">Terms of use</a>")
}
}
}
override fun onDestroyView() {
super.onDestroyView()
}
}
| apache-2.0 | f137cabc7a0c33bcb54345e5064e2719 | 40.014981 | 167 | 0.595471 | 4.455248 | false | false | false | false |
ReactiveCircus/FlowBinding | flowbinding-material/src/main/java/reactivecircus/flowbinding/material/SliderChangeEventFlow.kt | 1 | 1675 | package reactivecircus.flowbinding.material
import androidx.annotation.CheckResult
import com.google.android.material.slider.Slider
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import reactivecircus.flowbinding.common.InitialValueFlow
import reactivecircus.flowbinding.common.asInitialValueFlow
import reactivecircus.flowbinding.common.checkMainThread
/**
* Create a [InitialValueFlow] of change events on the [Slider] instance.
*
* Note: Created flow keeps a strong reference to the [Slider] instance
* until the coroutine that launched the flow collector is cancelled.
*
* Example of usage:
*
* ```
* slider.changeEvents()
* .onEach { event ->
* // handle event
* }
* .launchIn(uiScope)
* ```
*/
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
public fun Slider.changeEvents(): InitialValueFlow<SliderChangeEvent> = callbackFlow {
checkMainThread()
val listener = Slider.OnChangeListener { slider, value, fromUser ->
trySend(
SliderChangeEvent(
slider = slider,
value = value,
fromUser = fromUser
)
)
}
addOnChangeListener(listener)
awaitClose { removeOnChangeListener(listener) }
}
.conflate()
.asInitialValueFlow {
SliderChangeEvent(
slider = this,
value = value,
fromUser = false
)
}
public data class SliderChangeEvent(
public val slider: Slider,
public val value: Float,
public val fromUser: Boolean
)
| apache-2.0 | c7f79f011202b071fef763c60fff83e5 | 27.87931 | 86 | 0.693731 | 4.912023 | false | false | false | false |
sys1yagi/goat-reader-2-android-prototype | app/src/main/kotlin/com/sys1yagi/goatreader/views/ItemListAdapter.kt | 1 | 2539 | package com.sys1yagi.goatreader.views
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import com.sys1yagi.goatreader.R
import com.sys1yagi.goatreader.models.Item
import android.widget.TextView
import android.widget.ImageView
import com.squareup.picasso.Picasso
import java.text.SimpleDateFormat
import java.util.Locale
import com.activeandroid.query.From
import java.util.ArrayList
public class ItemListAdapter(context: Context, val loader: ((ItemListAdapter, List<Item>?) -> Unit)) : ArrayAdapter<Item>(context, -1) {
class object {
val FORMAT = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
}
{
loader(this, null)
}
override fun remove(obj: Item?) {
super<ArrayAdapter>.remove(obj)
if (getCount() <= 10) {
val remain = ArrayList<Item>()
for (i in 0..getCount() - 1) {
remain.add(getItem(i)!!)
}
loader(this, remain)
}
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
var view: View? = convertView
if (view == null) {
view = View.inflate(getContext()!!, R.layout.listitem_item, null)
view?.setTag(ViewHolder(view!!))
}
var holder: ViewHolder? = view?.getTag() as ViewHolder
val item = getItem(position)
if (item?.createdAt != null) {
holder?.date?.setText(FORMAT.format(item?.createdAt))
}
holder?.title?.setText(item?.title)
holder?.description?.setText(item?.description)
holder?.link?.setText(item?.link)
if (item?.imageLink != null) {
holder?.icon?.setVisibility(View.VISIBLE)
Picasso.with(getContext())?.load(item?.imageLink)?.into(holder?.icon)
} else {
holder?.icon?.setVisibility(View.GONE)
}
return view
}
class ViewHolder(root: View) {
var date: TextView? = null
var title: TextView? = null
var description: TextView? = null
var icon: ImageView? = null
var link: TextView? = null
{
date = root.findViewById(R.id.date_text) as TextView
title = root.findViewById(R.id.title_text) as TextView
description = root.findViewById(R.id.description_text) as TextView
icon = root.findViewById(R.id.icon_image) as ImageView
link = root.findViewById(R.id.link_text) as TextView
}
}
}
| apache-2.0 | 7bb402e2a2ab5f22bf1d840b911a45b1 | 31.974026 | 136 | 0.619141 | 4.148693 | false | false | false | false |
macrat/RuuMusic | app/src/main/java/jp/blanktar/ruumusic/util/DynamicShortcuts.kt | 1 | 4224 | package jp.blanktar.ruumusic.util
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ShortcutInfo
import android.content.pm.ShortcutManager
import android.graphics.drawable.Icon
import android.os.Build
import jp.blanktar.ruumusic.R
import jp.blanktar.ruumusic.client.main.MainActivity
const val SHORTCUTS_EXTRA_SHORTCUT_ID = "jp.blanktar.ruumusic.EXTRA_SHORTCUT_ID"
fun createDynamicShortcutInfo(context: Context, file: RuuFileBase): ShortcutInfo? {
if (Build.VERSION.SDK_INT < 25) {
return null
} else {
val id = "view:" + (if (file.isDirectory) "dir:" else "file:") + file.fullPath
val intent = Intent(context, MainActivity::class.java)
.setAction(if (file.isDirectory) MainActivity.ACTION_OPEN_PLAYLIST else MainActivity.ACTION_START_PLAY)
.setData(file.toUri())
.putExtra(SHORTCUTS_EXTRA_SHORTCUT_ID, id)
return ShortcutInfo.Builder(context, id)
.setActivity(ComponentName(context, MainActivity::class.java))
.setIntent(intent)
.setIcon(Icon.createWithResource(context, if (file.isDirectory) R.drawable.ic_shortcut_playlist else R.drawable.ic_shortcut_player))
.setShortLabel(if (file.name.length <= 10) file.name else file.name.substring(0, 9) + "…")
.setLongLabel(if (file.name.length <= 25) file.name else file.name.substring(0, 24) + "…")
.build()
}
}
class DynamicShortcuts(val context: Context) {
val manager: ShortcutManager? = if (Build.VERSION.SDK_INT < 25) null else context.getSystemService(ShortcutManager::class.java)
var shortcuts: List<ShortcutInfo>?
get() = manager?.dynamicShortcuts
set(xs) {
manager?.dynamicShortcuts = xs?.takeLast(maxShortcuts) ?: listOf<ShortcutInfo>()
}
val maxShortcuts
get() = (manager?.maxShortcutCountPerActivity ?: 0) - (manager?.manifestShortcuts?.count() ?: 0)
val isRequestPinSupported
get() = manager?.isRequestPinShortcutSupported ?: false
fun requestPin(x: ShortcutInfo): Boolean {
val intent = manager?.createShortcutResultIntent(x)
if (intent != null) {
return manager?.requestPinShortcut(x, PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT).intentSender) ?: false
}
return false
}
fun requestPin(context: Context, file: RuuFileBase): Boolean {
if (Build.VERSION.SDK_INT >= 26) {
val shortcut = createDynamicShortcutInfo(context, file)
if (shortcut != null) {
return requestPin(shortcut)
}
}
return false
}
fun reportShortcutUsed(id: String?) {
if (id != null) {
manager?.reportShortcutUsed(id)
}
}
fun managePinnedShortcuts() {
val shortcuts = manager?.pinnedShortcuts?.filter { it.id.startsWith("view:") }
if (shortcuts == null) {
return
}
val enabled = shortcuts.map(fun (it): Boolean {
val path = it.intent?.data?.path
if (path == null) {
return false
}
try {
val file = if (it.id.startsWith("view:file:")) {
RuuFile.getInstance(context, path.dropLastWhile { it != '.' }.dropLast(1))
} else {
RuuDirectory.getInstance(context, path)
}
file.ruuPath
} catch (e: RuuFileBase.NotFound) {
return false
} catch (e: RuuFileBase.OutOfRootDirectory) {
return false
}
return true
})
manager?.enableShortcuts(shortcuts.filterIndexed { i, _ -> enabled[i] }.map { it.id })
manager?.disableShortcuts(shortcuts.filterIndexed { i, _ -> !enabled[i] }.map { it.id })
}
companion object {
const val EXTRA_SHORTCUT_ID = SHORTCUTS_EXTRA_SHORTCUT_ID
}
}
| mit | 43a073375467c9884bfeb275b9ce26aa | 36.017544 | 159 | 0.599289 | 4.355005 | false | false | false | false |
amith01994/intellij-community | plugins/settings-repository/src/autoSync.kt | 13 | 5972 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository
import com.intellij.configurationStore.ComponentStoreImpl
import com.intellij.notification.Notification
import com.intellij.notification.Notifications
import com.intellij.notification.NotificationsAdapter
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationAdapter
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ShutDownTracker
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier
import java.util.concurrent.Future
class AutoSyncManager(private val icsManager: IcsManager) {
private volatile var autoSyncFuture: Future<*>? = null
fun waitAutoSync(indicator: ProgressIndicator) {
val autoFuture = autoSyncFuture
if (autoFuture != null) {
if (autoFuture.isDone()) {
autoSyncFuture = null
}
else if (autoSyncFuture != null) {
LOG.info("Wait for auto sync future")
indicator.setText("Wait for auto sync completion")
while (!autoFuture.isDone()) {
if (indicator.isCanceled()) {
return
}
Thread.sleep(5)
}
}
}
}
fun registerListeners(application: Application) {
application.addApplicationListener(object : ApplicationAdapter() {
override fun applicationExiting() {
autoSync(true)
}
})
}
fun registerListeners(project: Project) {
project.getMessageBus().connect().subscribe(Notifications.TOPIC, object : NotificationsAdapter() {
override fun notify(notification: Notification) {
if (!icsManager.repositoryActive || project.isDisposed()) {
return
}
if (when {
notification.getGroupId() == VcsBalloonProblemNotifier.NOTIFICATION_GROUP.getDisplayId() -> {
val message = notification.getContent()
message.startsWith("VCS Update Finished") ||
message == VcsBundle.message("message.text.file.is.up.to.date") ||
message == VcsBundle.message("message.text.all.files.are.up.to.date")
}
notification.getGroupId() == VcsNotifier.NOTIFICATION_GROUP_ID.getDisplayId() && notification.getTitle() == "Push successful" -> true
else -> false
}) {
autoSync()
}
}
})
}
fun autoSync(onAppExit: Boolean = false, force: Boolean = false) {
if (!icsManager.repositoryActive || (!force && !icsManager.settings.autoSync)) {
return
}
var future = autoSyncFuture
if (future != null && !future.isDone()) {
return
}
val app = ApplicationManagerEx.getApplicationEx() as ApplicationImpl
if (onAppExit) {
sync(app, onAppExit)
return
}
else if (app.isDisposeInProgress()) {
// will be handled by applicationExiting listener
return
}
future = app.executeOnPooledThread {
if (autoSyncFuture == future) {
// to ensure that repository will not be in uncompleted state and changes will be pushed
ShutDownTracker.getInstance().registerStopperThread(Thread.currentThread())
try {
sync(app, onAppExit)
}
finally {
autoSyncFuture = null
ShutDownTracker.getInstance().unregisterStopperThread(Thread.currentThread())
}
}
}
autoSyncFuture = future
}
private fun sync(app: ApplicationImpl, onAppExit: Boolean) {
catchAndLog {
icsManager.runInAutoCommitDisabledMode {
val repositoryManager = icsManager.repositoryManager
if (!repositoryManager.canCommit()) {
LOG.warn("Auto sync skipped: repository is not committable")
return@runInAutoCommitDisabledMode
}
// on app exit fetch and push only if there are commits to push
if (onAppExit && !repositoryManager.commit() && repositoryManager.getAheadCommitsCount() == 0) {
return@runInAutoCommitDisabledMode
}
val updater = repositoryManager.fetch()
// we merge in EDT non-modal to ensure that new settings will be properly applied
app.invokeAndWait({
catchAndLog {
val updateResult = updater.merge()
if (!onAppExit && !app.isDisposeInProgress() && updateResult != null && updateStoragesFromStreamProvider(app.stateStore as ComponentStoreImpl, updateResult, app.getMessageBus())) {
// force to avoid saveAll & confirmation
app.exit(true, true, true, true)
}
}
}, ModalityState.NON_MODAL)
if (!updater.definitelySkipPush) {
repositoryManager.push()
}
}
}
}
}
inline fun catchAndLog(runnable: () -> Unit) {
try {
runnable()
}
catch (e: ProcessCanceledException) {
}
catch (e: Throwable) {
if (e is AuthenticationException || e is NoRemoteRepositoryException) {
LOG.warn(e)
}
else {
LOG.error(e)
}
}
} | apache-2.0 | 16978a337713fb677928e6ac31f655fe | 32.745763 | 192 | 0.675486 | 4.812248 | false | false | false | false |
google/ksp | kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/impl/symbol/kotlin/KSTypeReferenceImpl.kt | 1 | 4648 | /*
* Copyright 2022 Google LLC
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.impl.symbol.kotlin
import com.google.devtools.ksp.ExceptionMessage
import com.google.devtools.ksp.IdKeyTriple
import com.google.devtools.ksp.KSObjectCache
import com.google.devtools.ksp.symbol.*
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiTypeParameter
import com.intellij.psi.impl.source.PsiClassReferenceType
import org.jetbrains.kotlin.analysis.api.types.*
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtTypeParameter
class KSTypeReferenceImpl private constructor(
private val ktType: KtType,
override val parent: KSNode?,
private val index: Int
) : KSTypeReference {
companion object : KSObjectCache<IdKeyTriple<KtType, KSNode?, Int>, KSTypeReference>() {
fun getCached(type: KtType, parent: KSNode? = null, index: Int = -1): KSTypeReference =
cache.getOrPut(IdKeyTriple(type, parent, index)) { KSTypeReferenceImpl(type, parent, index) }
}
override val element: KSReferenceElement? by lazy {
if (parent == null || parent.origin == Origin.SYNTHETIC) {
null
} else {
when (ktType) {
is KtFunctionalType -> KSCallableReferenceImpl.getCached(ktType, this@KSTypeReferenceImpl)
is KtDynamicType -> KSDynamicReferenceImpl.getCached(this@KSTypeReferenceImpl)
is KtUsualClassType -> KSClassifierReferenceImpl.getCached(ktType, this@KSTypeReferenceImpl)
is KtFlexibleType -> KSClassifierReferenceImpl.getCached(
ktType.lowerBound as KtUsualClassType,
this@KSTypeReferenceImpl
)
is KtClassErrorType -> null
is KtTypeParameterType -> null
else -> throw IllegalStateException("Unexpected type element ${ktType.javaClass}, $ExceptionMessage")
}
}
}
override fun resolve(): KSType {
// TODO: non exist type returns KtNonErrorClassType, check upstream for KtClassErrorType usage.
return if (
analyze {
ktType is KtClassErrorType || (ktType.classifierSymbol() == null)
}
) {
KSErrorType
} else {
KSTypeImpl.getCached(ktType)
}
}
override val annotations: Sequence<KSAnnotation> by lazy {
ktType.annotations()
}
override val origin: Origin = parent?.origin ?: Origin.SYNTHETIC
override val location: Location by lazy {
if (index != -1) {
parent?.location ?: NonExistLocation
} else {
when (parent) {
is KSClassDeclarationImpl -> {
when (val psi = parent.ktClassOrObjectSymbol.psi) {
is KtClassOrObject -> psi.superTypeListEntries.get(index).toLocation()
is PsiClass -> (psi as? PsiClassReferenceType)?.reference?.toLocation() ?: NonExistLocation
else -> NonExistLocation
}
}
is KSTypeParameterImpl -> {
when (val psi = parent.ktTypeParameterSymbol.psi) {
is KtTypeParameter -> parent.location
is PsiTypeParameter -> (psi.extendsListTypes[index] as? PsiClassReferenceType)
?.reference?.toLocation() ?: NonExistLocation
else -> NonExistLocation
}
}
else -> NonExistLocation
}
}
}
override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R {
return visitor.visitTypeReference(this, data)
}
override val modifiers: Set<Modifier>
get() = if (ktType is KtFunctionalType && ktType.isSuspend) {
setOf(Modifier.SUSPEND)
} else {
emptySet()
}
override fun toString(): String {
return ktType.render()
}
}
| apache-2.0 | 07dc1898557ee936fded1f20a843c151 | 38.389831 | 117 | 0.626506 | 5.019438 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/psi/element/MdAttributesImpl.kt | 1 | 3420 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.psi.element
import com.intellij.lang.ASTNode
import com.intellij.openapi.project.Project
import com.vladsch.md.nav.parser.MdFactoryContext
import com.vladsch.md.nav.psi.util.MdElementFactory
class MdAttributesImpl(node: ASTNode) : MdCompositeImpl(node), MdAttributes {
override fun getIdValueAttribute(): MdAttributeIdValue? {
for (attribute in children) {
if (attribute is MdAttribute) {
val attributeName = attribute.attributeName ?: continue
if (attributeName == "id") {
return attribute.attributeValueElement as MdAttributeIdValue?
}
}
}
return null
}
override fun setAttributes(attributes: Map<String, String?>): MdAttributes {
val attributesText = getAttributesText(project, attributes)
val newAttributes = MdElementFactory.createAttributes(MdFactoryContext(this), attributesText)
if (newAttributes != null) {
return replace(newAttributes) as MdAttributes
}
return this
}
override fun getAttributes(): Map<String, String?> {
val attributes = HashMap<String, String?>()
for (attribute in children) {
if (attribute is MdAttribute) {
val attributeName = attribute.attributeName ?: continue
attributes[attributeName] = attribute.attributeValue
}
}
return attributes
}
companion object {
@Suppress("UNUSED_PARAMETER")
fun getElementText(factoryContext: MdFactoryContext, attributesText: String): String {
return "{$attributesText}"
}
@Suppress("UNUSED_PARAMETER")
fun getAttributesText(project: Project, attributes: Map<String, String?>): String {
val attributesText = StringBuilder()
for (entry in attributes) {
if (attributesText.isNotEmpty()) attributesText.append(' ')
var isBuiltIn = false
when (entry.key) {
"id" -> {
attributesText.append('#')
isBuiltIn = true
}
"class" -> {
attributesText.append('.')
isBuiltIn = true
}
else -> attributesText.append(entry.key)
}
if (entry.value != null) {
if (!isBuiltIn) {
attributesText.append('=')
if (!entry.value!!.contains('"')) {
attributesText.append('"').append(entry.value).append('"')
} else if (!entry.value!!.contains('\'')) {
attributesText.append('\'').append(entry.value).append('\'')
} else {
attributesText.append('"').append(entry.value!!.replace("\"", "\\\"")).append('"')
}
} else {
attributesText.append(entry.value)
}
}
}
return attributesText.toString()
}
}
}
| apache-2.0 | 39805f48a4689f541b7a565b8b2d2e16 | 37.863636 | 177 | 0.537135 | 5.411392 | false | true | false | false |
ac-opensource/Matchmaking-App | app/src/main/java/com/youniversals/playupgo/notifications/NotificationActivity.kt | 1 | 2145 | package com.youniversals.playupgo.notifications
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.youniversals.playupgo.PlayUpApplication
import com.youniversals.playupgo.R
import com.youniversals.playupgo.flux.BaseActivity
import com.youniversals.playupgo.flux.action.NotificationActionCreator
import com.youniversals.playupgo.flux.action.NotificationActionCreator.Companion.ACTION_GET_NOTIF_S
import com.youniversals.playupgo.flux.store.NotificationStore
import kotlinx.android.synthetic.main.activity_notification.*
import javax.inject.Inject
class NotificationActivity : BaseActivity() {
@Inject lateinit var notificationActionCreator: NotificationActionCreator
@Inject lateinit var notificationStore: NotificationStore
private lateinit var layoutManager: LinearLayoutManager
private lateinit var notificationAdapter: NotificationListAdapter
companion object {
fun startActivity(context: Context) {
val intent = Intent(context, NotificationActivity::class.java)
context.startActivity(intent)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_notification)
PlayUpApplication.fluxComponent.inject(this)
title = "Notifications"
layoutManager = LinearLayoutManager(this)
notificationAdapter = NotificationListAdapter(View.OnClickListener { v ->
})
notificationRecyclerView.setHasFixedSize(true)
notificationRecyclerView.layoutManager = layoutManager
notificationRecyclerView.adapter = notificationAdapter
initFlux()
}
private fun initFlux() {
notificationStore.observableWithFilter(ACTION_GET_NOTIF_S)
.subscribe {
runOnUiThreadIfAlive(Runnable {
notificationAdapter.addNotifications(it.notifications)
})
}
notificationActionCreator.getNotifications()
}
}
| agpl-3.0 | 1b45fafc02a1b1bc29c45520eeebc3b7 | 36.631579 | 99 | 0.744056 | 5.458015 | false | false | false | false |
JimSeker/ui | ListViews/ListDemo_kt/app/src/main/java/edu/cs4730/listdemo_kt/Simple1_ListFragment.kt | 1 | 1102 | package edu.cs4730.listdemo_kt
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast
import androidx.fragment.app.ListFragment
class Simple1_ListFragment : ListFragment() {
var TAG = "Simple_frag"
var values = arrayOf(
"Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2"
)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.listfragment_layout, container, false)
val adapter = ArrayAdapter(inflater.context, android.R.layout.simple_list_item_1, values)
listAdapter = adapter
return view
}
override fun onListItemClick(l: ListView, v: View, position: Int, id: Long) {
Toast.makeText(requireContext(), "${values[position]} selected", Toast.LENGTH_LONG).show()
}
}
| apache-2.0 | 9fa8eea49667080842bd08eaea6b0c5e | 30.485714 | 98 | 0.68784 | 4.11194 | false | false | false | false |
gameover-fwk/gameover-fwk | src/main/kotlin/gameover/fwk/libgdx/scene2d/Holder.kt | 1 | 1309 | package gameover.fwk.libgdx.scene2d
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.scenes.scene2d.ui.Button
/**
* This helper class can be used to check if a key was just pressed. the key can be a keyboard key or a
* {@link com.badlogic.gdx.scenes.scene2d.ui.Button} on a screen.
*/
abstract class Holder {
companion object {
fun forKeyboard(keyCode: Int) : Holder = KeyboardKeyHolder(keyCode)
fun forButton(button: Button) : Holder = ButtonHolder(button)
}
var keyPressedStartTime: Float = .0f
private var isPressed: Boolean = false
abstract fun checkIfPressed(): Boolean
fun updateState(stateTime: Float, checkStateChangeOnly: Boolean): Boolean {
val wasPressed = isPressed
isPressed = checkIfPressed()
if (isPressed) {
if (!wasPressed) {
keyPressedStartTime = stateTime
}
}
else {
keyPressedStartTime = -1f
}
return isPressed && (!checkStateChangeOnly || !wasPressed)
}
}
private class KeyboardKeyHolder(val keyCode: Int) : Holder() {
override fun checkIfPressed(): Boolean = Gdx.input.isKeyPressed(keyCode)
}
private class ButtonHolder(val button: Button) : Holder() {
override fun checkIfPressed(): Boolean = button.isPressed
}
| mit | e7cc3df8a94be6c68c3b51fde90b1e41 | 29.44186 | 103 | 0.668449 | 4.25 | false | false | false | false |
square/moshi | moshi/src/main/java/com/squareup/moshi/JsonValueWriter.kt | 1 | 8563 | /*
* Copyright (C) 2017 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 com.squareup.moshi
import com.squareup.moshi.JsonScope.EMPTY_ARRAY
import com.squareup.moshi.JsonScope.EMPTY_DOCUMENT
import com.squareup.moshi.JsonScope.EMPTY_OBJECT
import com.squareup.moshi.JsonScope.NONEMPTY_DOCUMENT
import com.squareup.moshi.JsonScope.STREAMING_VALUE
import com.squareup.moshi.internal.knownNotNull
import okio.Buffer
import okio.BufferedSink
import okio.ForwardingSink
import okio.IOException
import okio.buffer
import java.math.BigDecimal
/** Writes JSON by building a Java object comprising maps, lists, and JSON primitives. */
internal class JsonValueWriter : JsonWriter() {
var stack = arrayOfNulls<Any>(32)
private var deferredName: String? = null
init {
pushScope(EMPTY_DOCUMENT)
}
fun root(): Any? {
val size = stackSize
check(size <= 1 && (size != 1 || scopes[0] == NONEMPTY_DOCUMENT)) { "Incomplete document" }
return stack[0]
}
override fun beginArray(): JsonWriter {
check(!promoteValueToName) { "Array cannot be used as a map key in JSON at path $path" }
if (stackSize == flattenStackSize && scopes[stackSize - 1] == EMPTY_ARRAY) {
// Cancel this open. Invert the flatten stack size until this is closed.
flattenStackSize = flattenStackSize.inv()
return this
}
checkStack()
val list = mutableListOf<Any>()
add(list)
stack[stackSize] = list
pathIndices[stackSize] = 0
pushScope(EMPTY_ARRAY)
return this
}
override fun endArray(): JsonWriter {
check(peekScope() == EMPTY_ARRAY) { "Nesting problem." }
if (stackSize == flattenStackSize.inv()) {
// Cancel this close. Restore the flattenStackSize so we're ready to flatten again!
flattenStackSize = flattenStackSize.inv()
return this
}
stackSize--
stack[stackSize] = null
pathIndices[stackSize - 1]++
return this
}
override fun beginObject(): JsonWriter {
check(!promoteValueToName) { "Object cannot be used as a map key in JSON at path $path" }
if (stackSize == flattenStackSize && scopes[stackSize - 1] == EMPTY_OBJECT) {
// Cancel this open. Invert the flatten stack size until this is closed.
flattenStackSize = flattenStackSize.inv()
return this
}
checkStack()
val map = LinkedHashTreeMap<String, Any>()
add(map)
stack[stackSize] = map
pushScope(EMPTY_OBJECT)
return this
}
override fun endObject(): JsonWriter {
check(peekScope() == EMPTY_OBJECT) { "Nesting problem." }
check(deferredName == null) { "Dangling name: $deferredName" }
if (stackSize == flattenStackSize.inv()) {
// Cancel this close. Restore the flattenStackSize so we're ready to flatten again!
flattenStackSize = flattenStackSize.inv()
return this
}
promoteValueToName = false
stackSize--
stack[stackSize] = null
pathNames[stackSize] = null // Free the last path name so that it can be garbage collected!
pathIndices[stackSize - 1]++
return this
}
override fun name(name: String): JsonWriter {
check(stackSize != 0) { "JsonWriter is closed." }
check(peekScope() == EMPTY_OBJECT && deferredName == null && !promoteValueToName) { "Nesting problem." }
deferredName = name
pathNames[stackSize - 1] = name
return this
}
override fun value(value: String?): JsonWriter {
if (promoteValueToName) {
promoteValueToName = false
return name(value!!)
}
add(value)
pathIndices[stackSize - 1]++
return this
}
override fun nullValue(): JsonWriter {
check(!promoteValueToName) { "null cannot be used as a map key in JSON at path $path" }
add(null)
pathIndices[stackSize - 1]++
return this
}
override fun value(value: Boolean): JsonWriter {
check(!promoteValueToName) { "Boolean cannot be used as a map key in JSON at path $path" }
add(value)
pathIndices[stackSize - 1]++
return this
}
override fun value(value: Boolean?): JsonWriter {
check(!promoteValueToName) { "Boolean cannot be used as a map key in JSON at path $path" }
add(value)
pathIndices[stackSize - 1]++
return this
}
override fun value(value: Double): JsonWriter {
require(isLenient || !value.isNaN() && value != Double.NEGATIVE_INFINITY && value != Double.POSITIVE_INFINITY) {
"Numeric values must be finite, but was $value"
}
if (promoteValueToName) {
promoteValueToName = false
return name(value.toString())
}
add(value)
pathIndices[stackSize - 1]++
return this
}
override fun value(value: Long): JsonWriter {
if (promoteValueToName) {
promoteValueToName = false
return name(value.toString())
}
add(value)
pathIndices[stackSize - 1]++
return this
}
override fun value(value: Number?): JsonWriter = apply {
when (value) {
null -> nullValue()
// If it's trivially converted to a long, do that.
is Byte, is Short, is Int, is Long -> value(value.toLong())
// If it's trivially converted to a double, do that.
is Float, is Double -> value(value.toDouble())
else -> {
// Everything else gets converted to a BigDecimal.
val bigDecimalValue = if (value is BigDecimal) value else BigDecimal(value.toString())
if (promoteValueToName) {
promoteValueToName = false
return name(bigDecimalValue.toString())
}
add(bigDecimalValue)
pathIndices[stackSize - 1]++
}
}
}
override fun valueSink(): BufferedSink {
check(!promoteValueToName) { "BufferedSink cannot be used as a map key in JSON at path $path" }
check(peekScope() != STREAMING_VALUE) { "Sink from valueSink() was not closed" }
pushScope(STREAMING_VALUE)
val buffer = Buffer()
return object : ForwardingSink(buffer) {
override fun close() {
if (peekScope() != STREAMING_VALUE || stack[stackSize] != null) {
throw AssertionError()
}
stackSize-- // Remove STREAMING_VALUE from the stack.
val value = JsonReader.of(buffer).readJsonValue()
val serializeNulls = serializeNulls
[email protected] = true
try {
add(value)
} finally {
[email protected] = serializeNulls
}
pathIndices[stackSize - 1]++
}
}.buffer()
}
override fun close() {
val size = stackSize
if (size > 1 || size == 1 && scopes[0] != NONEMPTY_DOCUMENT) {
throw IOException("Incomplete document")
}
stackSize = 0
}
override fun flush() {
check(stackSize != 0) { "JsonWriter is closed." }
}
private fun add(newTop: Any?): JsonValueWriter {
val scope = peekScope()
when {
stackSize == 1 -> {
check(scope == EMPTY_DOCUMENT) { "JSON must have only one top-level value." }
scopes[stackSize - 1] = NONEMPTY_DOCUMENT
stack[stackSize - 1] = newTop
}
scope == EMPTY_OBJECT && deferredName != null -> {
if (newTop != null || serializeNulls) {
// Our maps always have string keys and object values.
@Suppress("UNCHECKED_CAST")
val map = stack[stackSize - 1] as MutableMap<String, Any?>
// Safe to assume not null as this is single-threaded and smartcast just can't handle it
val replaced = map.put(knownNotNull(deferredName), newTop)
require(replaced == null) {
"Map key '$deferredName' has multiple values at path $path: $replaced and $newTop"
}
}
deferredName = null
}
scope == EMPTY_ARRAY -> {
// Our lists always have object values.
@Suppress("UNCHECKED_CAST")
val list = stack[stackSize - 1] as MutableList<Any?>
list.add(newTop)
}
scope == STREAMING_VALUE -> throw IllegalStateException("Sink from valueSink() was not closed")
else -> throw IllegalStateException("Nesting problem.")
}
return this
}
}
| apache-2.0 | 8b2801e878df644caa834478697f8dfd | 32.449219 | 116 | 0.653276 | 4.266567 | false | false | false | false |
yamamotoj/workshop-jb | src/i_introduction/_9_Extensions_On_Collections/ExtensionsOnCollections.kt | 1 | 1680 | package i_introduction._9_Extensions_On_Collections
import util.TODO
data class User(val name: String, val lastName: String, val age: Int)
fun operationsWithCollections() {
val users = listOf(
User("John", "Doe", 19),
User("Jane", "Doe", 22)
)
//iterate over collection:
for (user in users) {
}
val minors = users.filter { u -> u.age < 21 }
println("${minors.size()} user(s) under 21 years old")
val youngestOver20 = users filter { u -> u.age > 20 } minBy { u -> u.age }
println("Youngest over 20: $youngestOver20")
}
fun operationsWithMaps() {
val map = hashMapOf(1 to "one", 3 to "three", 42 to "forty two")
//iterate over map:
for ((key, value) in map) {
}
//convenient way to access elements:
map[43] = map[42] + " plus one"
//the details (how it works) you'll found in 'Conventions' task later
println(map)
}
fun main(args: Array<String>) {
operationsWithCollections()
operationsWithMaps()
}
fun todoTask9() = TODO(
"""
Task 9.
The function should do the same as 'JavaCode9.doSomethingStrangeWithCollection'
Replace all invocations of 'todoTask9()' with the appropriate code.
""",
references = { c: Collection<String> -> JavaCode9().doSomethingStrangeWithCollection(c) }
)
fun doSomethingStrangeWithCollection(collection: Collection<String>): Collection<String>? {
val groupsByLength = collection. groupBy { s -> s.length() }
val maximumSizeOfGroup = groupsByLength. values(). map { group -> group.size() }. max()
return groupsByLength. values(). firstOrNull { group -> group.size() == maximumSizeOfGroup }
}
| mit | b084765c813d88a9ea181b534174118c | 26.540984 | 96 | 0.645238 | 3.826879 | false | false | false | false |
SerCeMan/intellij-community | platform/script-debugger/protocol/protocol-reader/src/PrimitiveValueReader.kt | 36 | 1386 | package org.jetbrains.protocolReader
open class PrimitiveValueReader(private val className: String, val defaultValue: String? = null, private val asRawString: Boolean = false, private val nullable: Boolean = false) : ValueReader() {
private val readPostfix: String
init {
if (Character.isLowerCase(className.charAt(0))) {
readPostfix = Character.toUpperCase(className.charAt(0)) + className.substring(1)
}
else {
readPostfix = if (asRawString) ("Raw" + className) else className
}
}
override fun writeReadCode(scope: ClassScope, subtyping: Boolean, out: TextOutput) {
if (asRawString) {
out.append("readRawString(")
addReaderParameter(subtyping, out)
out.append(')')
}
else {
addReaderParameter(subtyping, out)
out.append(".next");
if (nullable) {
out.append("Nullable");
}
out.append(readPostfix).append("()")
//beginReadCall(readPostfix, subtyping, out, name);
}
}
override fun appendFinishedValueTypeName(out: TextOutput) {
out.append(className)
}
override fun writeArrayReadCode(scope: ClassScope, subtyping: Boolean, out: TextOutput) {
if (readPostfix == "String") {
out.append("nextList")
}
else {
out.append("read").append(readPostfix).append("Array")
}
out.append('(').append(READER_NAME)
out.append(')')
}
}
| apache-2.0 | abac8e5ea2a1d3ab98d87ee41942daad | 29.130435 | 195 | 0.65873 | 4.149701 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/bus_stop_name/AddBusStopName.kt | 1 | 1979 | package de.westnordost.streetcomplete.quests.bus_stop_name
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.quest.AllCountriesExcept
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.PEDESTRIAN
class AddBusStopName : OsmFilterQuestType<BusStopNameAnswer>() {
override val elementFilter = """
nodes with
(
(public_transport = platform and ~bus|trolleybus|tram ~ yes)
or
(highway = bus_stop and public_transport != stop_position)
)
and !name and noname != yes and name:signed != no
"""
override val enabledInCountries = AllCountriesExcept("US", "CA")
override val commitMessage = "Determine bus/tram stop names"
override val wikiLink = "Tag:public_transport=platform"
override val icon = R.drawable.ic_quest_bus_stop_name
override val questTypeAchievements = listOf(PEDESTRIAN)
override fun getTitle(tags: Map<String, String>) =
if (tags["tram"] == "yes")
R.string.quest_tramStopName_title
else
R.string.quest_busStopName_title
override fun createForm() = AddBusStopNameForm()
override fun applyAnswerTo(answer: BusStopNameAnswer, changes: StringMapChangesBuilder) {
when(answer) {
is NoBusStopName -> {
changes.add("name:signed", "no")
}
is BusStopName -> {
for ((languageTag, name) in answer.localizedNames) {
val key = when (languageTag) {
"" -> "name"
"international" -> "int_name"
else -> "name:$languageTag"
}
changes.addOrModify(key, name)
}
}
}
}
}
| gpl-3.0 | d076373be597060bdb11b4b838f6e65a | 36.339623 | 93 | 0.625568 | 4.613054 | false | false | false | false |
JetBrains/anko | anko/library/generator/src/org/jetbrains/android/anko/annotations/annotationProviders.kt | 4 | 2960 | /*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko.annotations
import java.io.File
import java.util.zip.ZipFile
enum class ExternalAnnotation {
NotNull,
GenerateLayout,
GenerateView
}
interface AnnotationProvider {
fun getExternalAnnotations(packageName: String): Map<String, Set<ExternalAnnotation>>
}
class ZipFileAnnotationProvider(val zipFile: File) : AnnotationProvider {
private val archive by lazy { ZipFile(zipFile) }
override fun getExternalAnnotations(packageName: String): Map<String, Set<ExternalAnnotation>> {
val entryName = packageName.replace('.', '/') + "/annotations.xml"
val entry = archive.getEntry(entryName) ?: return emptyMap()
return archive.getInputStream(entry).reader().use {
parseAnnotations(parseXml(it.readText()))
}
}
}
class DirectoryAnnotationProvider(val directory: File) : AnnotationProvider {
override fun getExternalAnnotations(packageName: String): Map<String, Set<ExternalAnnotation>> {
val annotationFile = File(directory, packageName.replace('.', '/') + "/annotations.xml")
if (!annotationFile.exists()) return emptyMap()
return parseAnnotations(parseXml(annotationFile.readText()))
}
}
class CachingAnnotationProvider(val underlyingProvider: AnnotationProvider) : AnnotationProvider {
private val cache = hashMapOf<String, Map<String, Set<ExternalAnnotation>>>()
override fun getExternalAnnotations(packageName: String) = cache.getOrPut(packageName) {
underlyingProvider.getExternalAnnotations(packageName)
}
}
class CompoundAnnotationProvider(vararg private val providers: AnnotationProvider) : AnnotationProvider {
override fun getExternalAnnotations(packageName: String): Map<String, Set<ExternalAnnotation>> {
val providerAnnotations = providers.map { it.getExternalAnnotations(packageName) }
val map = hashMapOf<String, Set<ExternalAnnotation>>()
for (providerAnnotationMap in providerAnnotations) {
for ((key, value) in providerAnnotationMap) {
val existingAnnotations = map[key]
if (existingAnnotations == null) {
map.put(key, value)
} else {
map.put(key, (value + existingAnnotations).toSet())
}
}
}
return map
}
} | apache-2.0 | 16169724c1c45a99e271ad968813faf7 | 35.109756 | 105 | 0.700338 | 4.868421 | false | false | false | false |
android/topeka | base/src/main/java/com/google/samples/apps/topeka/model/Player.kt | 2 | 2895 | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.topeka.model
import android.os.Parcel
import android.os.Parcelable
import com.google.android.gms.auth.api.credentials.Credential
import com.google.samples.apps.topeka.helper.TAG
/**
* Stores values to identify the subject that is currently attempting to solve quizzes.
*/
data class Player(
var firstName: String?,
var lastInitial: String?,
var avatar: Avatar?,
/**
* Only used for SmartLock purposes.
*/
val email: String? = TAG
) : Parcelable {
/**
* Create a Player from SmartLock API.
*/
constructor(credential: Credential) :
// The avatar choice could be done by fetching data stored on a server, but this
// is a sample after all. So we don't bother with creating a server and storing
// this information at the moment.
this(firstName = credential.name?.substringBefore(" "),
lastInitial = credential.name?.substringAfterLast(" ")?.get(0).toString(),
avatar = Avatar.ELEVEN,
email = credential.id ?: TAG)
override fun writeToParcel(dest: Parcel, flags: Int) {
with(dest) {
writeString(firstName)
writeString(lastInitial)
writeString(email)
avatar?.run { writeInt(ordinal) }
}
}
override fun toString() = "$firstName $lastInitial"
fun valid() = !(firstName.isNullOrEmpty() || lastInitial.isNullOrEmpty()) && avatar != null
override fun describeContents() = 0
/**
* Create a [Credential] containing information of this [Player].
*/
fun toCredential(): Credential = Credential.Builder(email)
.setName(toString())
.build()
companion object {
@JvmField val CREATOR: Parcelable.Creator<Player> = object : Parcelable.Creator<Player> {
override fun createFromParcel(parcel: Parcel) = with(parcel) {
Player(firstName = readString(),
lastInitial = readString(),
email = readString(),
avatar = Avatar.values()[readInt()])
}
override fun newArray(size: Int): Array<Player?> = arrayOfNulls(size)
}
}
}
| apache-2.0 | e7f665393f3b7f5663164cb1745ef9da | 33.058824 | 97 | 0.623834 | 4.738134 | false | false | false | false |
WindSekirun/RichUtilsKt | RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/utils/RVibrate.kt | 1 | 2329 | @file:JvmName("RichUtils")
@file:JvmMultifileClass
package pyxis.uzuki.live.richutilskt.utils
import android.content.Context
/**
* Vibrate
* need VIBRATE permission
*
* @param[millSec] duration of vibrate
*/
fun Context.vibrate(millSec: Long) {
vibrator.vibrate(millSec)
}
/**
* Vibrate
* need VIBRATE permission
*
* @param[pattern] vibrate pattern
* @param[repeat] count of repeat, if once, give repeat as -1
*/
@JvmOverloads
fun Context.vibrate(pattern: LongArray, repeat: Int = -1) {
vibrator.vibrate(pattern, repeat)
}
/**
* get Intensity (Desired Strength) of Vibrate
* NOTE: Some device's default value may 0.7f (Tested in Galaxy S6),
*
* @param intensity Desired strength of vibration. There are 5 Options.
* @param duration Time to vibrate.
* @return long[] array of Pattern of Vibrate.
*/
fun getVibratorPattern(intensity: Intensity, duration: Long): LongArray {
return when (intensity) {
Intensity.VERYSOFT -> getVibratorPattern(0.1f, duration)
Intensity.SOFT -> getVibratorPattern(0.3f, duration)
Intensity.NORMAL -> getVibratorPattern(0.5f, duration)
Intensity.HARD -> getVibratorPattern(0.7f, duration)
Intensity.VERYHARD -> getVibratorPattern(0.9f, duration)
}
}
/**
* get Intensity (Desired Strength) of Vibrate
* Normal Way, just use getVibratorPattern(Intensity, long) for easy work.
*
* @param intensity Float value. Range is 0.0f ~ 1.0f
* @param duration Time to vibrate
* @return long[] array of Pattern of Vibrate
*/
fun getVibratorPattern(intensity: Float, duration: Long): LongArray {
val pattern: LongArray
if (intensity in 0.0f..1.0f) {
val dutyCycle = Math.abs(intensity * 2.0f - 1.0f)
val hWidth = (dutyCycle * (duration - 1)).toLong() + 1
val lWidth = (if (dutyCycle == 1.0f) 0 else 1).toLong()
val pulseCount = (2.0f * (duration.toFloat() / (hWidth + lWidth).toFloat())).toInt()
pattern = LongArray(pulseCount)
for (i in 0 until pulseCount)
pattern[i] = if (intensity < 0.5f) if (i % 2 == 0) hWidth else lWidth else if (i % 2 == 0) lWidth else hWidth
return pattern
} else {
throw RuntimeException("Abnormal intensity value! check your method")
}
}
enum class Intensity {
VERYSOFT, SOFT, NORMAL, HARD, VERYHARD
} | apache-2.0 | 9cf24134b3142042ca9e220a815afa0a | 28.871795 | 121 | 0.674968 | 3.470939 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/action/preview/ShowEquationPreview.kt | 1 | 1297 | package nl.hannahsten.texifyidea.action.preview
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import nl.hannahsten.texifyidea.TexifyIcons
import nl.hannahsten.texifyidea.util.findOuterMathEnvironment
/**
* Show a preview of a LaTeX equation in a separate window.
*
* @author Sergei Izmailov
*/
class ShowEquationPreview : PreviewAction("Equation Preview", TexifyIcons.EQUATION_PREVIEW) {
companion object {
@JvmStatic
val FORM_KEY = Key<PreviewFormUpdater>("updater")
@JvmStatic
val MATH_PREAMBLE = "\\usepackage{amsmath,amsthm,amssymb,amsfonts}"
}
override fun actionPerformed(file: VirtualFile, project: Project, textEditor: TextEditor) {
val element: PsiElement = getElement(file, project, textEditor) ?: return
val outerMathEnvironment = element.findOuterMathEnvironment() ?: return
displayPreview(project, outerMathEnvironment, FORM_KEY) {
resetPreamble()
preamble += MATH_PREAMBLE
val psiFile = element.containingFile
userPreamble += findPreamblesFromMagicComments(psiFile, "math")
}
}
} | mit | c58d3189a686c73c36e9821742d4a5ea | 32.282051 | 95 | 0.726291 | 4.381757 | false | false | false | false |
android/android-studio-poet | aspoet/src/main/kotlin/com/google/androidstudiopoet/generators/bazel/BazelLang.kt | 1 | 2959 | /*
Copyright 2018 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
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.androidstudiopoet.generators.bazel
/**
* Bazel uses the Starlark configuration language for BUILD files and .bzl extensions.
*
* Starlark is previously known as Skylark.
*
* https://docs.bazel.build/versions/master/skylark/language.html
*/
private const val BASE_INDENT = " "
sealed class Statement
/**
* foo = "bar"
*/
data class AssignmentStatement(val lhs: String, val rhs: String) : Statement() {
override fun toString() = """$lhs = $rhs"""
}
/**
* load("@foo//bar:baz.bzl", "symbol_foo", "symbol_bar")
*/
data class LoadStatement(val module: String, val symbols: List<String>) : Statement() {
override fun toString() = """load("$module", ${symbols.map { "\"$it\"" }.joinToString(separator = ", ")})"""
}
/**
* # Comment foo bar baz
*/
data class Comment(val comment: String) {
override fun toString(): String = """# $comment"""
}
/**
* A BUILD / BUILD.bazel target.
*
* A target is made of
*
* 1) a rule class.
* 2) mandatory "name" attribute.
* 3) other rule-specific attributes.
*
* e.g.
*
* java_library(
* name = "lib_foo",
* srcs = ["Foo.java", "Bar.java"],
* deps = [":lib_baz"],
* )
*/
data class Target(val ruleClass: String, val attributes: List<Attribute>) : Statement() {
override fun toString() : String {
return when (attributes.size) {
0 -> "$ruleClass()"
else -> """$ruleClass(
$BASE_INDENT${attributes.joinToString(separator = ",\n$BASE_INDENT") { it.toString() }},
)"""
}
}
}
/**
* Data classes representing attributes in targets.
*
* To improve type safety, create data classes implementing Attribute, e.g. StringAttribute.
*
* Bazel supports the following attribute types:
*
* bool
* int
* int_list
* label
* label_keyed_string_dict
* label_list
* license
* output
* output_list
* string
* string_dict
* string_list
* string_list_dict
*
* List of attribute schemas from:
* https://docs.bazel.build/versions/master/skylark/lib/attr.html
*/
sealed class Attribute {
abstract val name: String
abstract val value: Any
}
data class RawAttribute(override val name: String, override val value: String): Attribute() {
override fun toString() = "$name = $value"
}
data class StringAttribute(override val name: String, override val value: String): Attribute() {
override fun toString() = "$name = \"$value\""
}
| apache-2.0 | 118d83e729aefc7cdbbffc24dcf9d48f | 24.508621 | 112 | 0.669821 | 3.653086 | false | false | false | false |
PaulWoitaschek/Voice | app/src/main/kotlin/voice/app/features/widget/TriggerWidgetOnChange.kt | 1 | 1753 | package voice.app.features.widget
import androidx.datastore.core.DataStore
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.launch
import voice.common.BookId
import voice.common.pref.CurrentBook
import voice.data.Book
import voice.data.repo.BookRepository
import voice.playback.playstate.PlayStateManager
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class TriggerWidgetOnChange
@Inject constructor(
@CurrentBook
private val currentBook: DataStore<BookId?>,
private val repo: BookRepository,
private val playStateManager: PlayStateManager,
private val widgetUpdater: WidgetUpdater,
) {
fun init() {
MainScope().launch {
anythingChanged().collect {
widgetUpdater.update()
}
}
}
private fun anythingChanged(): Flow<Any?> {
return merge(currentBookChanged(), playStateChanged(), bookIdChanged())
}
private fun bookIdChanged(): Flow<BookId?> {
return currentBook.data.distinctUntilChanged()
}
private fun playStateChanged(): Flow<PlayStateManager.PlayState> {
return playStateManager.flow.distinctUntilChanged()
}
private fun currentBookChanged(): Flow<Book> {
return currentBook.data.filterNotNull()
.flatMapLatest { id ->
repo.flow(id)
}
.filterNotNull()
.distinctUntilChanged { previous, current ->
previous.id == current.id &&
previous.content.chapters == current.content.chapters &&
previous.content.currentChapter == current.content.currentChapter
}
}
}
| gpl-3.0 | d0fc74f040caccae9d1ff120347dfb54 | 27.737705 | 75 | 0.749002 | 4.725067 | false | false | false | false |
Ahmed-Abdelmeged/Android-BluetoothMCLibrary | app/src/main/java/com/ahmedabdelmeged/bluetoothmcsample/MainActivity.kt | 1 | 6054 | package com.ahmedabdelmeged.bluetoothmcsample
import android.app.Activity
import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.ahmedabdelmeged.bluetoothmc.BluetoothMC
import com.ahmedabdelmeged.bluetoothmc.ui.BluetoothDevices
import com.ahmedabdelmeged.bluetoothmc.util.BluetoothStates
import com.ahmedabdelmeged.bluetoothmc.util.InputDataHelper
import kotlinx.android.synthetic.main.activity_main.*
/**
* @author Ahmed Abd-Elmeged
*/
class MainActivity : AppCompatActivity() {
/**
* Variables for bluetooth
*/
private lateinit var bluetoothMC: BluetoothMC
private lateinit var inputDataHelper: InputDataHelper
private var sensors = listOf<String>()
/**
* UI Element
*/
private var progressDialog: ProgressDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// initialize the bluetoothmc and the data helper
bluetoothMC = BluetoothMC()
inputDataHelper = InputDataHelper()
//check if the mobile have a bluetooth
if (!bluetoothMC.isBluetoothAvailable()) {
finish()
} else if (!bluetoothMC.isBluetoothEnabled()) {
bluetoothMC.enableBluetooth()
}//check if the bluetooth enable or not and enable it if not
//you can retrieve the current bluetooth adapter to customize it as you want
val bluetoothAdapter = bluetoothMC.getBluetoothAdapter()
fab_connect!!.setOnClickListener {
val intent = Intent(this@MainActivity, BluetoothDevices::class.java)
startActivityForResult(intent, BluetoothStates.REQUEST_CONNECT_DEVICE)
}
//send a o command to the micro controller
on_button!!.setOnClickListener { bluetoothMC.send("o") }
//send a f command to the micro controller
off_button!!.setOnClickListener { bluetoothMC.send("f") }
//set listener for listen for the incoming data from the microcontroller
bluetoothMC.setOnDataReceivedListener(object : BluetoothMC.onDataReceivedListener {
override fun onDataReceived(data: String) {
sensors = inputDataHelper.setSensorsValues(data)
if (sensors.size >= 4 /*this number despond on number of sensors you put*/) {
sensor_temp!!.text = getString(R.string.sensor_temp, sensors[0])
sensor_ldr!!.text = getString(R.string.sensor_ldr, sensors[1])
sensor_pot!!.text = getString(R.string.sensor_pot, sensors[2])
sensor_button!!.text = getString(R.string.sensor_button, sensors[3])
}
}
})
//set listener to keep track for the connection states
bluetoothMC.setOnBluetoothConnectionListener(object : BluetoothMC.BluetoothConnectionListener {
override fun onDeviceConnecting() {
//this method triggered during the connection processes
//show a progress dialog
progressDialog = ProgressDialog.show(this@MainActivity,
"Connecting...", "Please wait!!!")
}
override fun onDeviceConnected() {
//this method triggered if the connection success
showToast("Device Connected")
progressDialog!!.dismiss()
}
override fun onDeviceDisconnected() {
//this method triggered if the device disconnected
showToast("Device disconnected")
}
override fun onDeviceConnectionFailed() {
//this method triggered if the connection failed
showToast("Connection failed try again")
progressDialog!!.dismiss()
}
})
//set listener to keep track the communication errors
bluetoothMC.setOnBluetoothErrorsListener(object : BluetoothMC.BluetoothErrorsListener {
override fun onSendingFailed() {
//this method triggered if the app failed to send data
showToast("Send data failed")
}
override fun onReceivingFailed() {
//this method triggered if the app failed to receive data
showToast("Receive data failed")
}
override fun onDisconnectingFailed() {
//this method triggered if the app failed to disconnect to the bluetooth device
showToast("Can't disconnect")
}
override fun onCommunicationFailed() {
//this method triggered if the app connect and unable to send and receive data
//from the bluetooth device
showToast("Communication failed try again")
}
})
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == BluetoothStates.REQUEST_CONNECT_DEVICE) {
if (resultCode == Activity.RESULT_OK) {
bluetoothMC.connect(data!!)
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.item_disconnect) {
//here disconnect to the bluetooth device
bluetoothMC.disconnect()
}
return super.onOptionsItemSelected(item)
}
/**
* Fast way to call toast
*/
private fun showToast(message: String) {
Toast.makeText(this@MainActivity, message, Toast.LENGTH_SHORT).show()
}
} | mit | d72a5d8835ed81998bc0a7bbef1e20fe | 36.573248 | 103 | 0.618599 | 5.296588 | false | false | false | false |
jrodriguezva/Kotlin-MVP-Weather | app/src/main/java/com/jagrod/weather/domain/model/Sys.kt | 1 | 990 | /*
* Copyright (c) 2017 Juan Agustín Rodríguez Valle Open Source Project.
*
* This file is part of Kotlin-MVP-Weather.
*
* Kotlin-MVP-Weather 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.
*
* Kotlin-MVP-Weather 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 Kotlin-MVP-Weather. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jagrod.weather.domain.model
data class Sys(var type: Int = 0, val id: Int = 0, val message: Double = 0.0, val country: String? = null,
val sunrise: Int = 0, val sunset: Int = 0) | gpl-3.0 | cc28ec66dd9a3dbc9ba297aa9e0f6ab3 | 42 | 106 | 0.728745 | 3.714286 | false | false | false | false |
fejd/jesture | clients/android/app/src/main/java/com/jesterlabs/recognizer/ui/HelloRecognizerActivity.kt | 1 | 5065 | /*
* Copyright (c) 2016 Fredrik Henricsson
*
* 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.jesterlabs.recognizer.ui
import android.app.Activity
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ViewManager
import com.jesterlabs.jesture.recognizers.common.data.Point
import com.jesterlabs.jesture.recognizers.onedollar.OneDollarRecognizer
import org.jetbrains.anko.custom.ankoView
import org.jetbrains.anko.dip
import org.jetbrains.anko.padding
import org.jetbrains.anko.verticalLayout
import java.util.*
class HelloRecognizerActivity : Activity() {
var recognizer = OneDollarRecognizer()
val TAG = "HelloRecognizerActivity"
var points: ArrayList<Point>
init {
points = ArrayList<Point>()
}
inline fun ViewManager.resultView() = resultView {}
inline fun ViewManager.resultView(init: ResultView.() -> Unit) = ankoView({ ResultView(it) }, init)
override fun onCreate(savedInstanceState : Bundle?) {
super.onCreate(savedInstanceState)
val ID_TEXT_VIEW = 1
verticalLayout {
val resultView = resultView {
id = ID_TEXT_VIEW
}
setOnTouchListener { resultText, motionEvent ->
val resultView = findViewById(ID_TEXT_VIEW) as ResultView
when(motionEvent.actionMasked) {
MotionEvent.ACTION_DOWN -> {
resultView.clearResults()
points.clear()
points.add(Point(motionEvent.x.toDouble(), motionEvent.y.toDouble()))
}
MotionEvent.ACTION_MOVE -> {
points.add(Point(motionEvent.x.toDouble(), motionEvent.y.toDouble()))
}
MotionEvent.ACTION_UP -> {
points.add(Point(motionEvent.x.toDouble(), motionEvent.y.toDouble()))
val result = recognizer.recognize(points)
resultView.updateResult(result.name, result.score.toString())
Log.i(TAG, "Name: " + result.name)
Log.i(TAG, "Score: " + result.score)
}
}
resultView.updatePoints(points)
resultView.invalidate()
true
}
}
}
class ResultView(context: Context?) : View(context) {
var points: ArrayList<Point>
val paint: Paint
var resultText: String = ""
var resultScore: String = ""
init {
points = ArrayList<Point>()
paint = Paint()
paint.color = Color.GRAY
paint.strokeWidth = 10f
paint.textSize = 50f
}
override fun onDraw(canvas: Canvas) {
points.forEachIndexed { i, point -> run {
if (i < 1) {
return@forEachIndexed
} else if (points.size < 2) {
return
}
val firstPoint = points.get(i-1)
val secondPoint = points.get(i)
canvas.drawLine(firstPoint.x.toFloat(), firstPoint.y.toFloat(),
secondPoint.x.toFloat(), secondPoint.y.toFloat(), paint)
} }
if (resultText.isNotEmpty()) {
canvas.drawText(resultText, points.last().x.toFloat(), points.last().y.toFloat(),
paint)
}
}
fun updatePoints(points: ArrayList<Point>) {
this.points = points;
}
fun updateResult(resultText: String, resultScore: String) {
this.resultText = resultText
this.resultScore = resultScore
}
fun clearResults() {
this.resultText = ""
this.resultScore = ""
}
}
}
| mit | 4497d6ac777863f242294d8e71a6b836 | 36.518519 | 103 | 0.605331 | 4.733645 | false | false | false | false |
songzhw/AndroidArchitecture | deprecated/Tools/DaggerPlayground/app/src/main/java/six/ca/dagger101/thirty2_test/Src32.kt | 1 | 1781 | package six.ca.dagger101.thirty2_test
import android.content.SharedPreferences
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.Retrofit
import okhttp3.OkHttpClient
import six.ca.dagger101.Mockable
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class Repo {
var id: Int = 0 //lateinit var不能用于基本类型
var isForked = false
lateinit var name: String
}
interface UserApiService {
@GET("users/{user}/repos")
fun listRepos(@Path("user") user: String): Call<List<Repo>>
}
class UserManager(val sp: SharedPreferences, val api: UserApiService)
class PasswordValidator
@Mockable
class LoginPresenter(val mgr: UserManager, val validator: PasswordValidator) {
fun init() {}
fun fetch() {}
}
// kotlin中一个全局object就解决的问题, 真没必要用Dagger.
object HttpEngine {
fun retrofit(): Retrofit {
val okhttpClient = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.build()
val retrofit = Retrofit.Builder()
.client(okhttpClient)
.baseUrl("https://api.github.com")
.build()
return retrofit
}
}
class LoginActivity : AppCompatActivity() {
@Inject
lateinit var presenter: LoginPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
println("szw actv : app = ${this.application}")
DaggerLoginComponent.builder()
.app(this.application)
.build()
.inject(this)
presenter.init()
}
fun clickOne() {
presenter.fetch()
}
}
/*
Errors I got before:
Mockito cannot mock/spy following:
- final classes (In this case, this requires us to add an "open" to LoginPrsenter)
- anonymous classes
- primitive types
*/ | apache-2.0 | 8d7a07f70a5419b71d32676bdc5e4a0c | 21.815789 | 85 | 0.746105 | 3.508097 | false | false | false | false |
didi/DoraemonKit | Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/connect/ConnectListAdapter.kt | 1 | 1361 | package com.didichuxing.doraemonkit.kit.connect
import android.view.View
import android.widget.TextView
import androidx.core.view.isGone
import com.didichuxing.doraemonkit.R
import com.didichuxing.doraemonkit.widget.brvah.BaseQuickAdapter
import com.didichuxing.doraemonkit.widget.brvah.viewholder.BaseViewHolder
/**
* didi Create on 2022/1/18 .
*
* Copyright (c) 2022/1/18 by didiglobal.com.
*
* @author <a href="[email protected]">zhangjun</a>
* @version 1.0
* @Date 2022/1/18 8:12 下午
* @Description 用一句话说明文件功能
*/
class ConnectListAdapter(clientList: MutableList<ConnectAddress>, callback: (client: ConnectAddress) -> Unit) :
BaseQuickAdapter<ConnectAddress, BaseViewHolder>(R.layout.dk_item_connect_address, clientList) {
val callback2 = callback
override fun convert(holder: BaseViewHolder, item: ConnectAddress) {
holder.getView<TextView>(R.id.tv_name).text = "主机名称:${item.name}"
holder.getView<TextView>(R.id.tv_address).text = "地址:${item.url}"
holder.getView<TextView>(R.id.tv_time).text = "时间:${item.time}"
holder.getView<TextView>(R.id.connect).setOnClickListener {
callback2(item)
}
holder.getView<View>(R.id.state_dot).isGone = !item.enable
holder.getView<TextView>(R.id.connect).isGone = item.enable
}
}
| apache-2.0 | 074f59bddd3506c341d90e8586f71571 | 31.219512 | 111 | 0.71461 | 3.629121 | false | false | false | false |
arturbosch/detekt | detekt-psi-utils/src/main/kotlin/io/github/detekt/psi/KtFiles.kt | 1 | 2336 | package io.github.detekt.psi
import org.jetbrains.kotlin.com.intellij.psi.PsiFile
import java.io.File
import java.nio.file.Path
import java.nio.file.Paths
const val KOTLIN_SUFFIX = ".kt"
const val KOTLIN_SCRIPT_SUFFIX = ".kts"
val PsiFile.fileName: String
get() = name.substringAfterLast(File.separatorChar)
fun PsiFile.fileNameWithoutSuffix(): String {
val fileName = this.fileName
if (fileName.endsWith(KOTLIN_SCRIPT_SUFFIX)) {
return fileName.removeSuffix(KOTLIN_SCRIPT_SUFFIX)
}
return fileName.removeSuffix(KOTLIN_SUFFIX)
}
fun PsiFile.absolutePath(): Path = Paths.get(name)
fun PsiFile.relativePath(): Path? = getUserData(RELATIVE_PATH)?.let { Paths.get(it) }
fun PsiFile.basePath(): Path? = getUserData(BASE_PATH)?.let { Paths.get(it) }
/**
* Represents both absolute path and relative path if available.
*/
data class FilePath constructor(
val absolutePath: Path,
val basePath: Path? = null,
val relativePath: Path? = null
) {
init {
require(
basePath == null ||
relativePath == null ||
absolutePath == basePath.resolve(relativePath).normalize()
) {
"Absolute path = $absolutePath much match base path = $basePath and relative path = $relativePath"
}
}
companion object {
fun fromAbsolute(path: Path) = FilePath(absolutePath = path.normalize())
fun fromRelative(basePath: Path, relativePath: Path) = FilePath(
absolutePath = basePath.resolve(relativePath).normalize(),
basePath = basePath.normalize(),
relativePath = relativePath
)
}
}
fun PsiFile.toFilePath(): FilePath {
val relativePath = relativePath()
val basePath = basePath()
return when {
basePath != null && relativePath != null -> FilePath(
absolutePath = absolutePath(),
basePath = basePath,
relativePath = relativePath
)
basePath == null && relativePath == null -> FilePath(absolutePath = absolutePath())
else -> error("Cannot build a FilePath from base path = $basePath and relative path = $relativePath")
}
}
/**
* Returns a system-independent string with UNIX system file separator.
*/
fun Path.toUnifiedString(): String = toString().replace(File.separatorChar, '/')
| apache-2.0 | 4ad17b25a5e4319c0fb6db0f8b4a9a44 | 30.567568 | 110 | 0.65839 | 4.518375 | false | false | false | false |
arturbosch/detekt | detekt-rules-errorprone/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/MissingWhenCaseSpec.kt | 1 | 16230 | package io.gitlab.arturbosch.detekt.rules.bugs
import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment
import io.gitlab.arturbosch.detekt.test.TestConfig
import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object MissingWhenCaseSpec : Spek({
setupKotlinEnvironment()
val env: KotlinCoreEnvironment by memoized()
describe("MissingWhenCase rule") {
val subject by memoized { MissingWhenCase() }
context("enum") {
it("reports when `when` expression used as statement and not all cases are covered") {
val code = """
enum class Color {
RED,
GREEN,
BLUE
}
fun whenOnEnumFail(c: Color) {
when(c) {
Color.BLUE -> {}
Color.GREEN -> {}
}
}
"""
val actual = subject.compileAndLintWithContext(env, code)
assertThat(actual).hasSize(1)
assertThat(actual.first().issue.id).isEqualTo("MissingWhenCase")
assertThat(actual.first().message).isEqualTo("When expression is missing cases: RED. Either add missing cases or a default `else` case.")
}
it("reports when `when` expression used as statement and not all cases including null are covered") {
val code = """
enum class Color {
RED,
GREEN,
BLUE
}
fun whenOnEnumFail(c: Color?) {
when(c) {
Color.BLUE -> {}
Color.GREEN -> {}
}
}
"""
val actual = subject.compileAndLintWithContext(env, code)
assertThat(actual).hasSize(1)
assertThat(actual.first().issue.id).isEqualTo("MissingWhenCase")
assertThat(actual.first().message).isEqualTo("When expression is missing cases: RED, null. Either add missing cases or a default `else` case.")
}
it("reports when `when` expression used as statement and null case is not covered") {
val code = """
enum class Color {
RED,
GREEN,
BLUE
}
fun whenOnEnumFail(c: Color?) {
when(c) {
Color.BLUE -> {}
Color.GREEN -> {}
Color.RED -> {}
}
}
"""
val actual = subject.compileAndLintWithContext(env, code)
assertThat(actual).hasSize(1)
assertThat(actual.first().issue.id).isEqualTo("MissingWhenCase")
assertThat(actual.first().message).isEqualTo("When expression is missing cases: null. Either add missing cases or a default `else` case.")
}
it("does not report missing null case in `when` expression when it is handled outside of `when`") {
val code = """
enum class Color {
RED,
GREEN,
BLUE
}
fun whenNulLCheckEnum(c: Color?) {
if(c == null) return
when(c) {
Color.BLUE -> {}
Color.GREEN -> {}
Color.RED -> {}
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report when `when` expression used as statement and all cases are covered") {
val code = """
enum class Color {
RED,
GREEN,
BLUE
}
fun whenOnEnumPass(c: Color) {
when(c) {
Color.BLUE -> {}
Color.GREEN -> {}
Color.RED -> {}
}
}
fun whenOnEnumPass2(c: Color) {
when(c) {
Color.BLUE -> {}
else -> {}
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
}
context("sealed classes") {
it("reports when `when` expression used as statement and not all cases are covered") {
val code = """
sealed class Variant {
object VariantA : Variant()
class VariantB : Variant()
object VariantC : Variant()
}
fun whenOnEnumFail(v: Variant) {
when(v) {
is Variant.VariantA -> {}
is Variant.VariantB -> {}
}
}
"""
val actual = subject.compileAndLintWithContext(env, code)
assertThat(actual).hasSize(1)
assertThat(actual.first().issue.id).isEqualTo("MissingWhenCase")
assertThat(actual.first().message).isEqualTo("When expression is missing cases: VariantC. Either add missing cases or a default `else` case.")
}
it("reports when `when` expression used as statement and null case is not covered") {
val code = """
sealed class Variant {
object VariantA : Variant()
class VariantB : Variant()
object VariantC : Variant()
}
fun whenOnEnumFail(v: Variant?) {
when(v) {
is Variant.VariantA -> {}
is Variant.VariantB -> {}
is Variant.VariantC -> {}
}
}
"""
val actual = subject.compileAndLintWithContext(env, code)
assertThat(actual).hasSize(1)
assertThat(actual.first().issue.id).isEqualTo("MissingWhenCase")
assertThat(actual.first().message).isEqualTo("When expression is missing cases: null. Either add missing cases or a default `else` case.")
}
it("reports when `when` expression used as statement and not all cases including null are covered") {
val code = """
sealed class Variant {
object VariantA : Variant()
class VariantB : Variant()
object VariantC : Variant()
}
fun whenOnEnumFail(v: Variant?) {
when(v) {
is Variant.VariantA -> {}
is Variant.VariantB -> {}
}
}
"""
val actual = subject.compileAndLintWithContext(env, code)
assertThat(actual).hasSize(1)
assertThat(actual.first().issue.id).isEqualTo("MissingWhenCase")
assertThat(actual.first().message).isEqualTo("When expression is missing cases: VariantC, null. Either add missing cases or a default `else` case.")
}
it("does not report missing null case in `when` expression when it is handled outside of `when`") {
val code = """
sealed class Variant {
object VariantA : Variant()
class VariantB : Variant()
object VariantC : Variant()
}
fun whenOnEnumFail(v: Variant?) {
if(v == null) return
when(v) {
is Variant.VariantA -> {}
is Variant.VariantB -> {}
is Variant.VariantC -> {}
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report when `when` expression used as statement and all cases are covered") {
val code = """
sealed class Variant {
object VariantA : Variant()
class VariantB : Variant()
object VariantC : Variant()
}
fun whenOnEnumPassA(v: Variant) {
when(v) {
is Variant.VariantA -> {}
is Variant.VariantB -> {}
else -> {}
}
}
fun whenOnEnumPassB(v: Variant) {
when(v) {
is Variant.VariantA -> {}
is Variant.VariantB -> {}
is Variant.VariantC -> {}
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
}
context("standard when") {
it("does not report when `when` not checking for missing cases") {
val code = """
fun whenChecks() {
val x = 3
val s = "3"
when (x) {
0, 1 -> print("x == 0 or x == 1")
else -> print("otherwise")
}
when (x) {
Integer.parseInt(s) -> print("s encodes x")
else -> print("s does not encode x")
}
when (x) {
in 1..10 -> print("x is in the range")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
val y = when(s) {
is String -> s.startsWith("prefix")
else -> false
}
when {
x.equals(s) -> print("x equals s")
x.plus(3) == 4 -> print("x is 1")
else -> print("x is funny")
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
}
}
describe("MissingWhenCase rule when else expression is not considered") {
val subject by memoized {
MissingWhenCase(
TestConfig(mapOf("allowElseExpression" to false))
)
}
context("enum") {
it("reports when `when` expression used as statement and not all cases are covered") {
val code = """
enum class Color {
RED,
GREEN,
BLUE
}
fun whenOnEnumFail(c: Color) {
when(c) {
Color.BLUE -> {}
Color.GREEN -> {}
else -> {}
}
}
"""
val actual = subject.compileAndLintWithContext(env, code)
assertThat(actual).hasSize(1)
assertThat(actual.first().issue.id).isEqualTo("MissingWhenCase")
assertThat(actual.first().message).isEqualTo("When expression is missing cases: RED.")
}
it("reports when `when` expression used as statement and null case is not covered") {
val code = """
enum class Color {
RED,
GREEN,
BLUE
}
fun whenOnEnumFail(c: Color?) {
when(c) {
Color.BLUE -> {}
Color.GREEN -> {}
Color.RED -> {}
else -> {}
}
}
"""
val actual = subject.compileAndLintWithContext(env, code)
assertThat(actual).hasSize(1)
assertThat(actual.first().issue.id).isEqualTo("MissingWhenCase")
assertThat(actual.first().message).isEqualTo("When expression is missing cases: null.")
}
it("does not reports when `when` expression used as statement and all cases are covered") {
val code = """
enum class Color {
RED,
GREEN,
BLUE
}
fun whenOnEnumFail(c: Color) {
when(c) {
Color.BLUE -> {}
Color.GREEN -> {}
Color.RED -> {}
}
}
"""
val actual = subject.compileAndLintWithContext(env, code)
assertThat(actual).isEmpty()
}
}
context("sealed classes") {
it("reports when `when` expression used as statement and not all cases covered") {
val code = """
sealed class Variant {
object VariantA : Variant()
class VariantB : Variant()
object VariantC : Variant()
}
fun whenOnEnumFail(v: Variant) {
when(v) {
is Variant.VariantA -> {}
is Variant.VariantB -> {}
else -> {}
}
}
"""
val actual = subject.compileAndLintWithContext(env, code)
assertThat(actual).hasSize(1)
assertThat(actual.first().issue.id).isEqualTo("MissingWhenCase")
assertThat(actual.first().message).isEqualTo("When expression is missing cases: VariantC.")
}
it("does not report when `when` expression used as statement and all cases are covered") {
val code = """
sealed class Variant {
object VariantA : Variant()
class VariantB : Variant()
object VariantC : Variant()
}
fun whenOnEnumPassA(v: Variant) {
when(v) {
is Variant.VariantA -> {}
is Variant.VariantB -> {}
is Variant.VariantC -> {}
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
}
context("standard when") {
it("does not report when else is used for non enum or sealed `when` expression") {
val code = """
fun whenChecks() {
val x = 3
when (x) {
0, 1 -> print("x == 0 or x == 1")
else -> print("otherwise")
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
}
}
})
| apache-2.0 | afa2552523f3dc5757e5f78f654a3a8d | 37.920863 | 164 | 0.412693 | 5.997783 | false | false | false | false |
rcgroot/open-gpstracker-ng | studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/trackedit/NameGenerator.kt | 1 | 2892 | /*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: René de Groot
** Copyright: (c) 2017 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker 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.
*
* OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.ng.features.trackedit
import android.content.Context
import nl.sogeti.android.gpstracker.ng.base.location.LocationFactory
import nl.sogeti.android.opengpstrack.ng.features.R
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject
import javax.inject.Named
class NameGenerator @Inject constructor(
val context: Context,
@Named("dayFormatter") private val dayFormat: SimpleDateFormat,
private val locationFactory: LocationFactory) {
fun generateName(now: Calendar): String {
val today = dayFormat.format(now.time)
val period = period(now)
val location = locationFactory.getLocationName()
return if (location == null) {
context.getString(R.string.initial_time_track_name, today, period)
} else {
context.getString(R.string.initial_time_location_track_name, today, period, location)
}
}
private fun period(now: Calendar): String {
val hour = now.get(Calendar.HOUR_OF_DAY)
return when (hour) {
in 0..4 -> context.getString(R.string.period_night)
in 5..11 -> context.getString(R.string.period_morning)
in 12..17 -> context.getString(R.string.period_afternoon)
in 18..23 -> context.getString(R.string.period_evening)
else -> ""
}
}
}
| gpl-3.0 | 3134b3a0f3614779a6f75cd9cf24014b | 42.80303 | 97 | 0.619163 | 4.531348 | false | false | false | false |
adrcotfas/Goodtime | app/src/main/java/com/apps/adrcotfas/goodtime/statistics/main/SelectLabelDialog.kt | 1 | 11076 | /*
* Copyright 2016-2019 Adrian Cotfas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
package com.apps.adrcotfas.goodtime.statistics.main
import com.apps.adrcotfas.goodtime.util.UpgradeDialogHelper.Companion.launchUpgradeDialog
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import com.apps.adrcotfas.goodtime.settings.PreferenceHelper
import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import android.view.LayoutInflater
import com.apps.adrcotfas.goodtime.R
import android.content.Intent
import com.apps.adrcotfas.goodtime.labels.AddEditLabelActivity
import com.apps.adrcotfas.goodtime.main.LabelsViewModel
import com.google.android.material.chip.Chip
import android.content.res.ColorStateList
import com.apps.adrcotfas.goodtime.util.ThemeHelper
import android.content.DialogInterface
import android.os.Handler
import android.view.View
import android.widget.ArrayAdapter
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.viewModels
import com.apps.adrcotfas.goodtime.database.Label
import com.apps.adrcotfas.goodtime.database.Profile
import com.apps.adrcotfas.goodtime.databinding.DialogSelectLabelBinding
import com.apps.adrcotfas.goodtime.settings.ProfilesViewModel
import com.apps.adrcotfas.goodtime.statistics.Utils
import java.lang.ref.WeakReference
@AndroidEntryPoint
class SelectLabelDialog : DialogFragment() {
/**
* The callback used to indicate the user is done selecting the title
*/
interface OnLabelSelectedListener {
/**
* @param label the label that was set
*/
fun onLabelSelected(label: Label)
}
@Inject
lateinit var preferenceHelper: PreferenceHelper
private lateinit var mProfiles: List<Profile>
private lateinit var mLabel: String
private lateinit var mCallback: WeakReference<OnLabelSelectedListener>
/**
* The extended version of this dialog is used in the Statistics
* where it also contains "all" as a label.
*/
private var mIsExtendedVersion = false
/**
* The neutral button used to change the profile
*/
private var showProfileSelection = false
private var mAlertDialog: AlertDialog? = null
@SuppressLint("ResourceType")
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val binding: DialogSelectLabelBinding = DataBindingUtil.inflate(
LayoutInflater.from(context),
R.layout.dialog_select_label,
null,
false
)
binding.editLabels.setOnClickListener {
if (preferenceHelper.isPro()) {
val intent = Intent(activity, AddEditLabelActivity::class.java)
startActivity(intent)
} else {
launchUpgradeDialog(requireActivity().supportFragmentManager)
}
if (mAlertDialog != null) {
mAlertDialog!!.dismiss()
}
}
val viewModel : LabelsViewModel by viewModels()
viewModel.labels.observe(this, { labels: List<Label> ->
var i = 0
if (mIsExtendedVersion) {
val chip = Chip(requireContext())
val total = Utils.getInstanceTotalLabel(requireContext())
chip.text = total.title
chip.chipBackgroundColor = ColorStateList.valueOf(
ThemeHelper.getColor(
requireContext(),
ThemeHelper.COLOR_INDEX_ALL_LABELS
)
)
chip.isCheckable = true
chip.chipIcon = resources.getDrawable(R.drawable.ic_check_off)
chip.checkedIcon = resources.getDrawable(R.drawable.ic_check)
chip.id = i++
if (chip.text.toString() == mLabel) {
chip.isChecked = true
}
binding.labels.addView(chip)
}
for (j in labels.indices.reversed()) {
val crt = labels[j]
val chip = Chip(requireContext())
chip.text = crt.title
chip.chipBackgroundColor =
ColorStateList.valueOf(ThemeHelper.getColor(requireContext(), crt.colorId))
chip.isCheckable = true
chip.chipIcon = resources.getDrawable(R.drawable.ic_check_off)
chip.checkedIcon = resources.getDrawable(R.drawable.ic_check)
chip.id = i++
if (crt.title == mLabel) {
chip.isChecked = true
}
binding.labels.addView(chip)
}
if (binding.labels.childCount == 0) {
binding.emptyState.visibility = View.VISIBLE
} else {
binding.emptyState.visibility = View.GONE
binding.labelsView.visibility = View.VISIBLE
}
})
val builder = AlertDialog.Builder(requireContext())
.setView(binding.root)
.setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int ->
if (binding.labels.checkedChipId != -1) {
val chip = binding.labels.getChildAt(binding.labels.checkedChipId) as Chip
mLabel = chip.text.toString()
val color = chip.chipBackgroundColor!!.defaultColor
notifyLabelSelected(
Label(
mLabel,
ThemeHelper.getIndexOfColor(requireContext(), color)
)
)
} else {
notifyLabelSelected(Utils.getInstanceUnlabeledLabel(requireContext()))
}
dismiss()
}
.setNegativeButton(android.R.string.cancel) { dialog: DialogInterface?, _: Int -> dialog?.dismiss() }
if (showProfileSelection) {
builder.setNeutralButton(
if (preferenceHelper.isUnsavedProfileActive()) resources.getString(R.string.Profile) else preferenceHelper.profile,
null
)
mAlertDialog = builder.create()
mAlertDialog!!.setOnShowListener {
//TODO: Clean-up this mess
val neutral = mAlertDialog!!.getButton(DialogInterface.BUTTON_NEUTRAL)
neutral.setOnClickListener {
val profilesViewModel : ProfilesViewModel by viewModels()
val profilesLiveData = profilesViewModel.profiles
profilesLiveData.observe(this@SelectLabelDialog, { profiles: List<Profile> ->
mProfiles = profiles
var profileIdx = 0
val arrayAdapter = ArrayAdapter<String>(
requireContext(),
R.layout.checked_text_view
)
val pref25 =
[email protected](R.string.pref_profile_default)
.toString()
val pref52 =
[email protected](R.string.pref_profile_5217)
.toString()
val crtProfileName = preferenceHelper.profile
if (crtProfileName == pref25) {
profileIdx = 0
} else if (crtProfileName == pref52) {
profileIdx = 1
}
arrayAdapter.add(pref25)
arrayAdapter.add(pref52)
val predefinedProfileNum = arrayAdapter.count
for (i in profiles.indices) {
val p = profiles[i]
arrayAdapter.add(p.name)
if (crtProfileName == p.name) {
profileIdx = i + predefinedProfileNum
}
}
val profileDialogBuilder = AlertDialog.Builder(requireContext())
.setTitle([email protected](R.string.Profile))
.setSingleChoiceItems(
arrayAdapter,
if (preferenceHelper.isUnsavedProfileActive()) -1 else profileIdx
) { dialogInterface: DialogInterface, which: Int ->
val selected = arrayAdapter.getItem(which)
updateProfile(which)
dialogInterface.dismiss()
if (mAlertDialog != null) {
mAlertDialog!!.getButton(AlertDialog.BUTTON_NEUTRAL).text =
selected
}
}
.setNegativeButton(android.R.string.cancel) { dialog1: DialogInterface, _: Int -> dialog1.dismiss() }
profileDialogBuilder.show()
})
}
}
} else {
mAlertDialog = builder.create()
}
return mAlertDialog!!
}
private fun notifyLabelSelected(label: Label) {
mCallback.get()!!.onLabelSelected(label)
}
private fun updateProfile(index: Int) {
when (index) {
0 -> {
preferenceHelper.setProfile25to5()
}
1 -> {
preferenceHelper.setProfile52to17()
}
else -> {
preferenceHelper.setProfile(mProfiles[index - PREDEFINED_PROFILES_NR])
}
}
}
companion object {
const val PREDEFINED_PROFILES_NR = 2
@JvmStatic
fun newInstance(
listener: OnLabelSelectedListener,
label: String,
isExtendedVersion: Boolean,
showProfileSelection: Boolean = false
): SelectLabelDialog {
val dialog = SelectLabelDialog()
dialog.mCallback = WeakReference(listener)
dialog.mLabel = label
dialog.mIsExtendedVersion = isExtendedVersion
dialog.showProfileSelection = showProfileSelection
return dialog
}
}
} | apache-2.0 | bedfdef634bc06a9aacaf92b0df30661 | 41.117871 | 131 | 0.56636 | 5.50497 | false | false | false | false |
rsiebert/TVHClient | app/src/main/java/org/tvheadend/tvhclient/ui/features/startup/StartupFragment.kt | 1 | 6529 | package org.tvheadend.tvhclient.ui.features.startup
import android.content.Intent
import android.os.Bundle
import android.view.*
import androidx.core.view.forEach
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.afollestad.materialdialogs.MaterialDialog
import org.tvheadend.tvhclient.R
import org.tvheadend.tvhclient.databinding.StartupFragmentBinding
import org.tvheadend.tvhclient.ui.base.BaseViewModel
import org.tvheadend.tvhclient.ui.common.interfaces.HideNavigationDrawerInterface
import org.tvheadend.tvhclient.ui.common.interfaces.LayoutControlInterface
import org.tvheadend.tvhclient.ui.common.interfaces.ToolbarInterface
import org.tvheadend.tvhclient.ui.features.settings.SettingsActivity
import org.tvheadend.tvhclient.util.extensions.gone
import org.tvheadend.tvhclient.util.extensions.visible
import timber.log.Timber
class StartupFragment : Fragment(), HideNavigationDrawerInterface {
private lateinit var binding: StartupFragmentBinding
private lateinit var startupViewModel: StartupViewModel
private lateinit var baseViewModel: BaseViewModel
private var loadingDone = false
private var connectionCount: Int = 0
private var isConnectionActive = false
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = StartupFragmentBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
startupViewModel = ViewModelProvider(requireActivity())[StartupViewModel::class.java]
baseViewModel = ViewModelProvider(requireActivity())[BaseViewModel::class.java]
if (activity is LayoutControlInterface) {
(activity as LayoutControlInterface).forceSingleScreenLayout()
}
if (activity is ToolbarInterface) {
(activity as ToolbarInterface).setTitle(getString(R.string.status))
}
setHasOptionsMenu(true)
loadingDone = false
Timber.d("Observing connection status")
startupViewModel.connectionStatus.observe(viewLifecycleOwner, { status ->
Timber.d("Received connection status from view model")
if (status != null) {
loadingDone = true
connectionCount = status.first!!
isConnectionActive = status.second!!
Timber.d("connection count is $connectionCount and connection is active is $isConnectionActive")
showStartupStatus()
} else {
Timber.d("Connection count and active connection are still loading")
binding.startupStatus.visible()
binding.startupStatus.text = getString(R.string.initializing)
binding.addConnectionButton.gone()
binding.listConnectionsButton.gone()
}
})
}
private fun showStartupStatus() {
if (loadingDone) {
if (!isConnectionActive && connectionCount == 0) {
Timber.d("No connection available, showing settings button")
binding.startupStatus.visible()
binding.startupStatus.text = getString(R.string.no_connection_available)
binding.addConnectionButton.visible()
binding.addConnectionButton.setOnClickListener { showSettingsAddNewConnection() }
binding.listConnectionsButton.gone()
} else if (!isConnectionActive && connectionCount > 0) {
Timber.d("No active connection available, showing settings button")
binding.startupStatus.visible()
binding.startupStatus.text = getString(R.string.no_connection_active_advice)
binding.addConnectionButton.gone()
binding.listConnectionsButton.visible()
binding.listConnectionsButton.setOnClickListener { showConnectionListSettings() }
} else {
Timber.d("Connection is available and active, showing contents")
binding.startupStatus.gone()
binding.addConnectionButton.gone()
binding.listConnectionsButton.gone()
baseViewModel.setStartupComplete(true)
}
}
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
menu.forEach { it.isVisible = false }
// Do not show the reconnect menu in case no connections are available or none is active
menu.findItem(R.id.menu_settings)?.isVisible = loadingDone
menu.findItem(R.id.menu_reconnect_to_server)?.isVisible = loadingDone && isConnectionActive
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.startup_options_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_settings -> {
showMainSettings()
true
}
R.id.menu_reconnect_to_server -> {
activity?.let { activity ->
MaterialDialog(activity).show {
title(R.string.reconnect_to_server)
message(R.string.restart_and_sync)
positiveButton(R.string.reconnect) {
Timber.d("Reconnect requested, stopping service and updating active connection to require a full sync")
baseViewModel.updateConnectionAndRestartApplication(context)
}
negativeButton(R.string.cancel)
}
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun showSettingsAddNewConnection() {
val intent = Intent(context, SettingsActivity::class.java)
intent.putExtra("setting_type", "add_connection")
startActivity(intent)
}
private fun showConnectionListSettings() {
val intent = Intent(context, SettingsActivity::class.java)
intent.putExtra("setting_type", "list_connections")
startActivity(intent)
}
private fun showMainSettings() {
val intent = Intent(context, SettingsActivity::class.java)
startActivity(intent)
}
}
| gpl-3.0 | bcaae0ef6577626f875037a13d243c28 | 41.953947 | 131 | 0.659366 | 5.278092 | false | false | false | false |
cbeust/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/aether/ConsoleRepositoryListener.kt | 2 | 3536 | package com.beust.kobalt.maven.aether
import com.beust.kobalt.internal.eventbus.ArtifactDownloadedEvent
import com.beust.kobalt.misc.kobaltLog
import com.google.common.eventbus.EventBus
import org.eclipse.aether.AbstractRepositoryListener
import org.eclipse.aether.RepositoryEvent
import java.io.PrintStream
/**
* A simplistic repository listener that logs events to the console.
*/
class ConsoleRepositoryListener @JvmOverloads constructor(out: PrintStream? = null, val eventBus: EventBus)
: AbstractRepositoryListener() {
companion object {
val LOG_LEVEL = 4
}
override fun artifactDeployed(event: RepositoryEvent?) {
kobaltLog(LOG_LEVEL, "Deployed " + event!!.artifact + " to " + event.repository)
}
override fun artifactDeploying(event: RepositoryEvent?) {
kobaltLog(LOG_LEVEL, "Deploying " + event!!.artifact + " to " + event.repository)
}
override fun artifactDescriptorInvalid(event: RepositoryEvent?) {
kobaltLog(LOG_LEVEL, "Invalid artifact descriptor for " + event!!.artifact + ": "
+ event.exception.message)
}
override fun artifactDescriptorMissing(event: RepositoryEvent?) {
kobaltLog(LOG_LEVEL, "Missing artifact descriptor for " + event!!.artifact)
}
override fun artifactInstalled(event: RepositoryEvent?) {
kobaltLog(LOG_LEVEL, "Installed " + event!!.artifact + " to " + event.file)
}
override fun artifactInstalling(event: RepositoryEvent?) {
kobaltLog(LOG_LEVEL, "Installing " + event!!.artifact + " to " + event.file)
}
override fun artifactResolved(event: RepositoryEvent?) {
kobaltLog(LOG_LEVEL, "Resolved artifact " + event!!.artifact + " from " + event.repository)
}
override fun artifactDownloading(event: RepositoryEvent?) {
kobaltLog(LOG_LEVEL, "Downloading artifact " + event!!.artifact + " from " + event.repository)
}
override fun artifactDownloaded(event: RepositoryEvent?) {
if (event?.file != null && event?.artifact != null) {
val artifact = event!!.artifact
kobaltLog(1, "Downloaded artifact " + artifact + " from " + event.repository)
eventBus.post(ArtifactDownloadedEvent(artifact.toString(), event.repository))
}
}
override fun artifactResolving(event: RepositoryEvent?) {
kobaltLog(LOG_LEVEL, "Resolving artifact " + event!!.artifact)
}
override fun metadataDeployed(event: RepositoryEvent?) {
kobaltLog(LOG_LEVEL, "Deployed " + event!!.metadata + " to " + event.repository)
}
override fun metadataDeploying(event: RepositoryEvent?) {
kobaltLog(LOG_LEVEL, "Deploying " + event!!.metadata + " to " + event.repository)
}
override fun metadataInstalled(event: RepositoryEvent?) {
kobaltLog(LOG_LEVEL, "Installed " + event!!.metadata + " to " + event.file)
}
override fun metadataInstalling(event: RepositoryEvent?) {
kobaltLog(LOG_LEVEL, "Installing " + event!!.metadata + " to " + event.file)
}
override fun metadataInvalid(event: RepositoryEvent?) {
kobaltLog(LOG_LEVEL, "Invalid metadata " + event!!.metadata)
}
override fun metadataResolved(event: RepositoryEvent?) {
kobaltLog(LOG_LEVEL, "Resolved metadata " + event!!.metadata + " from " + event.repository)
}
override fun metadataResolving(event: RepositoryEvent?) {
kobaltLog(LOG_LEVEL, "Resolving metadata " + event!!.metadata + " from " + event.repository)
}
}
| apache-2.0 | 0ede4def27e4df033b04d5f0f0af13f0 | 37.021505 | 107 | 0.676471 | 4.392547 | false | false | false | false |
RedstonerServer/Parcels | src/main/kotlin/io/dico/parcels2/options/Options.kt | 1 | 2309 | package io.dico.parcels2.options
import io.dico.parcels2.TickJobtimeOptions
import org.bukkit.GameMode
import org.bukkit.Material
import java.io.Reader
import java.io.Writer
import java.util.EnumSet
class Options {
var worlds: Map<String, WorldOptions> = hashMapOf()
private set
var storage: StorageOptions = StorageOptions()
var tickJobtime: TickJobtimeOptions = TickJobtimeOptions(20, 1)
var migration = MigrationOptionsHolder()
fun addWorld(name: String,
generatorOptions: GeneratorOptions? = null,
worldOptions: RuntimeWorldOptions? = null) {
val optionsHolder = WorldOptions(
generatorOptions ?: GeneratorOptions(),
worldOptions ?: RuntimeWorldOptions()
)
(worlds as MutableMap).put(name, optionsHolder)
}
fun writeTo(writer: Writer) = optionsMapper.writeValue(writer, this)
fun mergeFrom(reader: Reader) = optionsMapper.readerForUpdating(this).readValue<Options>(reader)
override fun toString(): String = optionsMapper.writeValueAsString(this)
}
class WorldOptions(val generator: GeneratorOptions,
var runtime: RuntimeWorldOptions = RuntimeWorldOptions())
class RuntimeWorldOptions(var gameMode: GameMode? = GameMode.CREATIVE,
var dayTime: Boolean = true,
var noWeather: Boolean = true,
var preventWeatherBlockChanges: Boolean = true,
var preventBlockSpread: Boolean = true, // TODO
var dropEntityItems: Boolean = true,
var doTileDrops: Boolean = false,
var disableExplosions: Boolean = true,
var blockPortalCreation: Boolean = true,
var blockMobSpawning: Boolean = true,
var blockedItems: Set<Material> = EnumSet.of(Material.FLINT_AND_STEEL, Material.SNOWBALL),
var axisLimit: Int = 10)
class DataFileOptions(val location: String = "/flatfile-storage/")
class MigrationOptionsHolder {
var enabled = false
var disableWhenComplete = true
var instance: MigrationOptions? = MigrationOptions()
} | gpl-2.0 | 2c813c3e7743689d5feb62df8ef2d5e1 | 37.844828 | 116 | 0.625379 | 4.741273 | false | false | false | false |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/GuiUrl.kt | 4 | 1573 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2020 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.rpc
import android.os.Parcel
import android.os.Parcelable
data class GuiUrl(var name: String? = "", var description: String? = "", var url: String? = "") : Parcelable {
private constructor(parcel: Parcel) : this(parcel.readString(), parcel.readString(), parcel.readString())
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, arg1: Int) {
dest.writeString(name)
dest.writeString(description)
dest.writeString(url)
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<GuiUrl> = object : Parcelable.Creator<GuiUrl> {
override fun createFromParcel(parcel: Parcel) = GuiUrl(parcel)
override fun newArray(size: Int) = arrayOfNulls<GuiUrl>(size)
}
}
}
| lgpl-3.0 | 0ecbacc27c49d69c07e333924e343aa9 | 35.581395 | 110 | 0.701208 | 4.228495 | false | true | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/ide/annotator/RsCrateDocLineMarkerProvider.kt | 1 | 1615 | package org.rust.ide.annotator
import com.intellij.codeHighlighting.Pass
import com.intellij.codeInsight.daemon.LineMarkerInfo
import com.intellij.codeInsight.daemon.LineMarkerProvider
import com.intellij.execution.filters.BrowserHyperlinkInfo
import com.intellij.openapi.editor.markup.GutterIconRenderer
import com.intellij.psi.PsiElement
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.psi.RsExternCrateItem
import org.rust.lang.core.psi.ext.containingCargoPackage
/**
* Provides an external crate imports with gutter icons that open documentation on docs.rs.
*/
class RsCrateDocLineMarkerProvider : LineMarkerProvider {
override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<PsiElement>? = null
override fun collectSlowLineMarkers(elements: List<PsiElement>, result: MutableCollection<LineMarkerInfo<PsiElement>>) {
for (el in elements) {
val crateItem = el as? RsExternCrateItem ?: continue
val crateName = crateItem.identifier.text
val crate = crateItem.containingCargoPackage?.findCrateByName(crateName) ?: continue
if (crate.pkg.source == null) continue
result.add(LineMarkerInfo(
crateItem.crate,
crateItem.crate.textRange,
RsIcons.DOCS_MARK,
Pass.LINE_MARKERS,
{ "Open documentation for `${crate.pkg.normName}`" },
{ _, _ -> BrowserHyperlinkInfo.openUrl("https://docs.rs/${crate.pkg.name}/${crate.pkg.version}/${crate.normName}") },
GutterIconRenderer.Alignment.LEFT))
}
}
}
| mit | 4cf2a3a19ab15ddca327a20d2dca7f3a | 43.861111 | 133 | 0.70774 | 4.778107 | false | false | false | false |
ProxyApp/Proxy | Application/src/main/kotlin/com/shareyourproxy/api/rx/RxActivityFeedSync.kt | 1 | 6059 | package com.shareyourproxy.api.rx
import android.content.Context
import android.util.Log
import com.shareyourproxy.R
import com.shareyourproxy.api.TwitterRestClient
import com.shareyourproxy.api.domain.model.ActivityFeedItem
import com.shareyourproxy.api.domain.model.Channel
import com.shareyourproxy.api.domain.model.ChannelType
import com.shareyourproxy.api.rx.command.eventcallback.ActivityFeedDownloadedEvent
import com.shareyourproxy.util.ObjectUtils.getTwitterDateFormat
import com.twitter.sdk.android.core.TwitterSession
import com.twitter.sdk.android.core.models.Tweet
import rx.Observable
import rx.functions.Func1
import timber.log.Timber
import java.text.ParseException
import java.util.*
/**
* Created by Evan on 10/12/15.
*/
object RxActivityFeedSync {
private val _dateFormat = getTwitterDateFormat()
private var _sinceId = 0L
private var _maxId = 0L
private val ITEM_COUNT = 10L
fun getChannelFeed(
context: Context, session: TwitterSession,
channels: HashMap<String, Channel>): Observable<ActivityFeedDownloadedEvent> {
return Observable.defer { Observable.from(channels.values).map(getServiceObservable(context, session)).filter(RxHelper.filterNullObject()).map(syncronizeData()).map(createEvent()) }
}
private fun getServiceObservable(
context: Context, twitterSession: TwitterSession?): Func1<Channel, Observable<List<ActivityFeedItem>>> {
return Func1 { channel ->
var observe: Observable<List<ActivityFeedItem>>? = null
when (channel.channelType()) {
ChannelType.Twitter -> if (twitterSession != null) {
observe = getTwitterActivity(context, channel, twitterSession)
} else {
observe = Observable.just(ActivityFeedItem.createEmpty(channel.channelType())).toList()
}
ChannelType.Youtube -> {
}
ChannelType.Custom -> {
}
ChannelType.Phone -> {
}
ChannelType.SMS -> {
}
ChannelType.Email -> {
}
ChannelType.Web -> {
}
ChannelType.URL -> {
}
ChannelType.Facebook -> {
}
ChannelType.Meerkat -> {
}
ChannelType.Snapchat -> {
}
ChannelType.Spotify -> {
}
ChannelType.Reddit -> {
}
ChannelType.Linkedin -> {
}
ChannelType.FBMessenger -> {
}
ChannelType.Hangouts -> {
}
ChannelType.Whatsapp -> {
}
ChannelType.Yo -> {
}
ChannelType.Googleplus -> {
}
ChannelType.Github -> {
}
ChannelType.Address -> {
}
ChannelType.Slack -> {
}
ChannelType.Instagram -> {
}
ChannelType.Tumblr -> {
}
ChannelType.Ello -> {
}
ChannelType.Venmo -> {
}
ChannelType.Periscope -> {
}
ChannelType.Medium -> {
}
ChannelType.Soundcloud -> {
}
ChannelType.Skype -> {
}
}
observe
}
}
private fun createEvent(): Func1<List<ActivityFeedItem>, ActivityFeedDownloadedEvent> {
return Func1 { activityFeedItems -> ActivityFeedDownloadedEvent(activityFeedItems) }
}
private fun syncronizeData(): Func1<Observable<List<ActivityFeedItem>>, List<ActivityFeedItem>> {
return Func1 { observer -> observer.toBlocking().single() }
}
private fun getTwitterActivity(
context: Context,
channel: Channel, session: TwitterSession): Observable<List<ActivityFeedItem>> {
if (_sinceId.equals(0) || _maxId.equals(0)) {
return TwitterRestClient.newInstance(session).userService.getUserTimeline(java.lang.Long.valueOf(channel.id()), ITEM_COUNT).map(timelineToFeedItem(context, channel))
} else {
return TwitterRestClient.newInstance(session).userService.getUserTimeline(java.lang.Long.valueOf(channel.id()), ITEM_COUNT, _sinceId, _maxId).map(timelineToFeedItem(context, channel))
}
}
/**
* https://dev.twitter.com/rest/public/timelines.
* @param channel twitter channel data
* *
* @return activity feed items
*/
private fun timelineToFeedItem(
context: Context, channel: Channel): Func1<List<Tweet>, List<ActivityFeedItem>> {
return Func1 { tweets ->
val channelType = channel.channelType()
val label = channel.actionAddress()
val feedItems = ArrayList<ActivityFeedItem>(tweets.size)
for (tweet in tweets) {
val idVal = tweet.id
_sinceId = if (idVal.compareTo(_sinceId) > 0) idVal else _sinceId
_maxId = if (idVal.compareTo(_maxId) < 0) (idVal - 1) else _maxId
var date = Date()
try {
date = _dateFormat.parse(tweet.createdAt)
} catch (e: ParseException) {
Timber.e("Parse Exception: ${Log.getStackTraceString(e)}")
}
val subtext = context.getString(R.string.posted_on, channelType)
feedItems.add(ActivityFeedItem.create(label, subtext, channelType,
getTwitterLink(tweet), date))
}
feedItems
}
}
private fun getTwitterLink(tweet: Tweet): String {
return StringBuilder("twitter.com/").append(tweet.user.id).append("/status/").append(tweet.id).toString()
}
}
| apache-2.0 | 131de3695146031f1dda2a447990a2a8 | 36.63354 | 195 | 0.558673 | 4.98273 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge3d/RenderContext3D.kt | 1 | 1486 | package com.soywiz.korge3d
import com.soywiz.kds.*
import com.soywiz.korag.*
import com.soywiz.korge.render.*
import com.soywiz.korma.geom.*
@Korge3DExperimental
class RenderContext3D() {
lateinit var ag: AG
lateinit var rctx: RenderContext
val shaders = Shaders3D()
val textureUnit = AG.TextureUnit()
val bindMat4 = Matrix3D()
val bones = Array(128) { Matrix3D() }
val tempMat = Matrix3D()
val projMat: Matrix3D = Matrix3D()
val lights = arrayListOf<Light3D>()
val projCameraMat: Matrix3D = Matrix3D()
val cameraMat: Matrix3D = Matrix3D()
val cameraMatInv: Matrix3D = Matrix3D()
val dynamicVertexBufferPool = Pool { ag.createVertexBuffer() }
val dynamicVertexDataPool = Pool { ag.createVertexData() }
val dynamicIndexBufferPool = Pool { ag.createIndexBuffer() }
val ambientColor: Vector3D = Vector3D()
val tempAgVertexData = FastArrayList<AG.VertexData>()
inline fun useDynamicVertexData(vertexBuffers: FastArrayList<BufferWithVertexLayout>, block: (FastArrayList<AG.VertexData>) -> Unit) {
dynamicVertexDataPool.allocMultiple(vertexBuffers.size, tempAgVertexData) { vertexData ->
for (n in 0 until vertexBuffers.size) {
val bufferWithVertexLayout = vertexBuffers[n]
vertexData[n].buffer.upload(bufferWithVertexLayout.buffer)
vertexData[n].layout = bufferWithVertexLayout.layout
}
block(vertexData)
}
}
}
| apache-2.0 | de1cd99ed80cbac0f108465fbee5971f | 37.102564 | 138 | 0.693136 | 3.983914 | false | false | false | false |
kiruto/kotlin-android-mahjong | app/src/main/java/dev/yuriel/kotmvp/layout/AbsoluteLayoutElement.kt | 1 | 2060 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 yuriel<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dev.yuriel.kotmvp.layout
/**
* Created by yuriel on 8/11/16.
*/
class AbsoluteLayoutElement(override val id: String): LayoutElement() {
fun rect(top: Number, right: Number, bottom: Number, left: Number) {
attr.size.width = right.toFloat() - left.toFloat()
attr.size.height = top.toFloat() - bottom.toFloat()
attr.origin.x = left.toFloat()
attr.origin.y = bottom.toFloat()
}
fun String.top() = target(this)?.top()?: 0F
fun String.right() = target(this)?.right()?: 0F
fun String.bottom() = target(this)?.bottom()?: 0F
fun String.left() = target(this)?.left()?: 0F
fun moveUnits(relativeX: Number?, relativeY: Number?) {
attr.correct((relativeX?.toFloat()?: 0F) * unit.toFloat(),
(relativeY?.toFloat()?: 0F) * unit.toFloat())
}
private fun target(id: String): LayoutPosition? = this[id]?.attr
} | mit | 4ba823b88f09826bc3540425aa1b21ab | 40.22 | 81 | 0.696602 | 4.071146 | false | false | false | false |
martin-nordberg/KatyDOM | Katydid-CSS-JS/src/main/kotlin/i/katydid/css/styles/KatydidStyleImpl.kt | 1 | 2449 | //
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package i.katydid.css.styles
import o.katydid.css.styles.KatydidStyle
//---------------------------------------------------------------------------------------------------------------------
internal class KatydidStyleImpl
: KatydidStyle {
/** The individual key: value properties of this style. */
private val myProperties = mutableListOf<String>()
////
override val important: Unit
get() {
require(properties.size > 0) { "Set a property before making it important." }
require(!properties[properties.size - 1].endsWith("!important")) { "Last property already set to important." }
myProperties[myProperties.size - 1] += " !important"
}
override val isNotEmpty
get() = properties.isNotEmpty()
override val properties = myProperties
////
override fun include(style: KatydidStyle) {
for (property in style.properties) {
myProperties.add(property)
}
}
override fun inherit(key: String) =
setProperty(key, "inherit")
override fun <T> setBoxProperty(key: String, top: T, right: T, bottom: T, left: T) {
var css = "$top"
if (right != top || bottom != top || left != right) {
css += " $right"
}
if (bottom != top || left != right) {
css += " $bottom"
}
if (left != right) {
css += " $left"
}
setProperty(key, css)
}
override fun setProperty(key: String, value: String) {
myProperties.add("$key: $value")
}
override fun <T> setXyProperty(key: String, x: T, y: T) {
var css = "$x"
if (x != y) {
css += " $y"
}
setProperty(key, css)
}
override fun setStringProperty(key: String, value: String) {
var cssValue = value.replace("\"", "\\\"")
cssValue = cssValue.replace("\n", "\\A")
// TODO: probably more characters worth escaping
setProperty(key, "\"$cssValue\"")
}
override fun toCssString(indent: String, whitespace: String) =
properties.map { p -> indent + p }.joinToString(";" + whitespace) + ";"
override fun toString() =
toCssString("", " ")
}
//---------------------------------------------------------------------------------------------------------------------
| apache-2.0 | c39dc49500bac9eba21c342214b75484 | 23.989796 | 122 | 0.502246 | 4.56903 | false | false | false | false |
cashapp/sqldelight | sqldelight-gradle-plugin/src/test/integration-mysql-schema/src/test/kotlin/app/cash/sqldelight/mysql/integration/MySqlTest.kt | 1 | 2253 | package app.cash.sqldelight.mysql.integration
import app.cash.sqldelight.Query
import app.cash.sqldelight.driver.jdbc.JdbcDriver
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.sql.Connection
import java.sql.DriverManager
class MySqlTest {
lateinit var connection: Connection
lateinit var queries: DogsQueries
@Before
fun before() {
connection = DriverManager.getConnection("jdbc:tc:mysql:///myDb")
val driver = object : JdbcDriver() {
override fun getConnection() = connection
override fun closeConnection(connection: Connection) = Unit
override fun addListener(listener: Query.Listener, queryKeys: Array<String>) = Unit
override fun removeListener(listener: Query.Listener, queryKeys: Array<String>) = Unit
override fun notifyListeners(queryKeys: Array<String>) = Unit
}
val database = MyDatabase(driver)
MyDatabase.Schema.create(driver)
queries = database.dogsQueries
}
@After
fun after() {
connection.close()
}
@Test
fun `select dogs for owner`() {
queries.insertPerson(1, "Jeff")
queries.insertPerson(2, "Jake")
queries.insertDog("Iris", "Cat", 1, true)
queries.insertDog("Hazel", "French Bulldog", 2, true)
queries.insertDog("Olive", "French Bulldog", 2, true)
assertThat(queries.selectDogsForOwnerName("Jake").executeAsList())
.containsExactly(
Dog(
name = "Hazel",
breed = "French Bulldog",
owner = 2,
is_good = true,
),
Dog(
name = "Olive",
breed = "French Bulldog",
owner = 2,
is_good = true,
),
)
}
@Test
fun `select bad name dogs`() {
queries.insertPerson(1, "Jeff")
queries.insertPerson(2, "Jake")
queries.insertDog("Cat", "Cat", 1, true)
queries.insertDog("Dog", "Dog", 2, true)
queries.insertDog("Olive", "French Bulldog", 2, true)
assertThat(queries.selectBadNameDogs().executeAsList())
.containsExactly(
Bad_name_dogs(
name = "Cat",
breed = "Cat",
),
Bad_name_dogs(
name = "Dog",
breed = "Dog",
),
)
}
}
| apache-2.0 | a2136acb7840369bf98c25eca5c3a89b | 26.47561 | 92 | 0.632046 | 3.857877 | false | false | false | false |
panpf/sketch | sketch-gif-koral/src/main/java/com/github/panpf/sketch/drawable/GifDrawableWrapperDrawable.kt | 1 | 2346 | package com.github.panpf.sketch.drawable
import android.annotation.SuppressLint
import android.graphics.drawable.Animatable
import android.widget.MediaController.MediaPlayerControl
import androidx.appcompat.graphics.drawable.DrawableWrapper
import pl.droidsonroids.gif.GifDrawable
@SuppressLint("RestrictedApi")
class GifDrawableWrapperDrawable(
val gifDrawable: GifDrawable
) : DrawableWrapper(gifDrawable), Animatable, MediaPlayerControl {
override fun start() {
gifDrawable.start()
}
override fun pause() {
gifDrawable.pause()
}
override fun stop() {
gifDrawable.stop()
}
override fun isRunning(): Boolean {
return gifDrawable.isRunning
}
override fun getDuration(): Int {
return gifDrawable.duration
}
override fun getCurrentPosition(): Int {
return gifDrawable.currentPosition
}
override fun seekTo(pos: Int) {
gifDrawable.seekTo(pos)
}
override fun isPlaying(): Boolean {
return gifDrawable.isPlaying
}
override fun getBufferPercentage(): Int {
return gifDrawable.bufferPercentage
}
override fun canPause(): Boolean {
return gifDrawable.canPause()
}
override fun canSeekBackward(): Boolean {
return gifDrawable.canSeekBackward()
}
override fun canSeekForward(): Boolean {
return gifDrawable.canSeekForward()
}
override fun getAudioSessionId(): Int {
return gifDrawable.audioSessionId
}
override fun mutate(): GifDrawableWrapperDrawable {
val mutateDrawable = gifDrawable.mutate()
return if (mutateDrawable !== gifDrawable) {
GifDrawableWrapperDrawable(gifDrawable)
} else {
this
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GifDrawableWrapperDrawable) return false
if (gifDrawable != other.gifDrawable) return false
return true
}
override fun hashCode(): Int {
return gifDrawable.hashCode()
}
override fun toString(): String {
val toHexString = Integer.toHexString(gifDrawable.hashCode())
return "GifDrawableWrapperDrawable(GifDrawable(${gifDrawable.intrinsicWidth}x${gifDrawable.intrinsicHeight})@$toHexString)"
}
} | apache-2.0 | 9fc92ebb2654e4a639722468770aacef | 25.077778 | 131 | 0.674339 | 4.980892 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/activity/KeyboardShortcutPreferenceCompatActivity.kt | 1 | 4055 | package de.vanita5.twittnuker.activity
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.view.View.OnClickListener
import kotlinx.android.synthetic.main.activity_keyboard_shortcut_input.*
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.constant.SharedPreferenceConstants.VALUE_THEME_BACKGROUND_DEFAULT
import de.vanita5.twittnuker.util.KeyboardShortcutsHandler
import de.vanita5.twittnuker.util.KeyboardShortcutsHandler.KeyboardShortcutSpec
class KeyboardShortcutPreferenceCompatActivity : BaseActivity(), OnClickListener {
private var keySpec: KeyboardShortcutSpec? = null
private var metaState: Int = 0
override val themeBackgroundOption: String
get() = VALUE_THEME_BACKGROUND_DEFAULT
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_keyboard_shortcut_input)
title = KeyboardShortcutsHandler.getActionLabel(this, keyAction)
buttonPositive.setOnClickListener(this)
buttonNegative.setOnClickListener(this)
buttonNeutral.setOnClickListener(this)
}
override fun onClick(v: View) {
when (v.id) {
R.id.buttonPositive -> {
if (keySpec == null) return
keyboardShortcutsHandler.register(keySpec, keyAction)
finish()
}
R.id.buttonNeutral -> {
keyboardShortcutsHandler.unregister(keyAction)
finish()
}
R.id.buttonNegative -> {
finish()
}
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (KeyEvent.isModifierKey(keyCode)) {
metaState = metaState or KeyboardShortcutsHandler.getMetaStateForKeyCode(keyCode)
}
return super.onKeyDown(keyCode, event)
}
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
if (KeyEvent.isModifierKey(keyCode)) {
metaState = metaState and KeyboardShortcutsHandler.getMetaStateForKeyCode(keyCode).inv()
}
val keyAction = keyAction ?: return false
val spec = KeyboardShortcutsHandler.getKeyboardShortcutSpec(contextTag,
keyCode, event, KeyEvent.normalizeMetaState(metaState or event.metaState))
if (spec == null || !spec.isValid) {
return super.onKeyUp(keyCode, event)
}
keySpec = spec
keysLabel.text = spec.toKeyString()
val oldAction = keyboardShortcutsHandler.findAction(spec)
val copyOfSpec = spec.copy()
copyOfSpec.contextTag = null
val oldGeneralAction = keyboardShortcutsHandler.findAction(copyOfSpec)
if (!TextUtils.isEmpty(oldAction) && keyAction != oldAction) {
// Conflicts with keys in same context tag
conflictLabel.visibility = View.VISIBLE
val label = KeyboardShortcutsHandler.getActionLabel(this, oldAction)
conflictLabel.text = getString(R.string.conflicts_with_name, label)
buttonPositive.setText(R.string.overwrite)
} else if (!TextUtils.isEmpty(oldGeneralAction) && keyAction != oldGeneralAction) {
// Conflicts with keys in root context
conflictLabel.visibility = View.VISIBLE
val label = KeyboardShortcutsHandler.getActionLabel(this, oldGeneralAction)
conflictLabel.text = getString(R.string.conflicts_with_name, label)
buttonPositive.setText(R.string.overwrite)
} else {
conflictLabel.visibility = View.GONE
buttonPositive.setText(android.R.string.ok)
}
return true
}
private val contextTag: String
get() = intent.getStringExtra(EXTRA_CONTEXT_TAG)
private val keyAction: String?
get() = intent.getStringExtra(EXTRA_KEY_ACTION)
companion object {
val EXTRA_CONTEXT_TAG = "context_tag"
val EXTRA_KEY_ACTION = "key_action"
}
} | gpl-3.0 | 40a054c61e022e2ea017a621f64b2363 | 38.378641 | 100 | 0.673983 | 4.687861 | false | false | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/ui/ShowInfo.kt | 1 | 708 | package au.com.codeka.warworlds.client.ui
import android.view.View
class ShowInfo private constructor(builder: Builder) {
val view: View?
val toolbarVisible: Boolean
class Builder {
var view: View? = null
var toolbarVisible = true
fun view(view: View?): Builder {
this.view = view
return this
}
fun toolbarVisible(toolbarVisible: Boolean): Builder {
this.toolbarVisible = toolbarVisible
return this
}
fun build(): ShowInfo {
return ShowInfo(this)
}
}
companion object {
@JvmStatic
fun builder(): Builder {
return Builder()
}
}
init {
view = builder.view
toolbarVisible = builder.toolbarVisible
}
} | mit | 875aeb3a217c3a9070bf20e28c43013d | 17.657895 | 58 | 0.64548 | 4.189349 | false | false | false | false |
exponent/exponent | packages/expo-modules-core/android/src/main/java/expo/modules/kotlin/types/EnumTypeConverter.kt | 2 | 2919 | package expo.modules.kotlin.types
import com.facebook.react.bridge.Dynamic
import expo.modules.kotlin.exception.IncompatibleArgTypeException
import expo.modules.kotlin.toKType
import kotlin.reflect.KClass
import kotlin.reflect.full.createType
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.full.primaryConstructor
class EnumTypeConverter(
private val enumClass: KClass<Enum<*>>,
isOptional: Boolean
) : TypeConverter<Enum<*>>(isOptional) {
override fun convertNonOptional(value: Dynamic): Enum<*> {
@Suppress("UNCHECKED_CAST")
val enumConstants = requireNotNull(enumClass.java.enumConstants) {
"Passed type is not an enum type."
}
require(enumConstants.isNotEmpty()) {
"Passed enum type is empty."
}
val primaryConstructor = requireNotNull(enumClass.primaryConstructor) {
"Cannot convert js value to enum without the primary constructor."
}
if (primaryConstructor.parameters.isEmpty()) {
return convertEnumWithoutParameter(value, enumConstants)
} else if (primaryConstructor.parameters.size == 1) {
return convertEnumWithParameter(
value,
enumConstants,
primaryConstructor.parameters.first().name!!
)
}
throw IncompatibleArgTypeException(value.type.toKType(), enumClass.createType())
}
/**
* If the primary constructor doesn't take any parameters, we treat the name of each enum as a value.
* So the jsValue has to contain string.
*/
private fun convertEnumWithoutParameter(
jsValue: Dynamic,
enumConstants: Array<out Enum<*>>
): Enum<*> {
val unwrappedJsValue = jsValue.asString()
return requireNotNull(
enumConstants.find { it.name == unwrappedJsValue }
) { "Couldn't convert ${jsValue.asString()} to ${enumClass.simpleName}." }
}
/**
* If the primary constructor take one parameter, we treat this parameter as a enum value.
* In that case, we handles two different types: Int and String.
*/
private fun convertEnumWithParameter(
jsValue: Dynamic,
enumConstants: Array<out Enum<*>>,
parameterName: String
): Enum<*> {
// To obtain the value of parameter, we have to find a property that is connected with this parameter.
@Suppress("UNCHECKED_CAST")
val parameterProperty = enumClass
.declaredMemberProperties
.find { it.name == parameterName }
requireNotNull(parameterProperty) { "Cannot find a property for $parameterName parameter." }
val parameterType = parameterProperty.returnType.classifier
val jsUnwrapValue = if (parameterType == String::class) {
jsValue.asString()
} else {
jsValue.asInt()
}
return requireNotNull(
enumConstants.find {
parameterProperty.get(it) == jsUnwrapValue
}
) { "Couldn't convert ${jsValue.asString()} to ${enumClass.simpleName} where $parameterName is the enum parameter. " }
}
}
| bsd-3-clause | 1bd00be290f4e0b565e4d2a6438e8ee4 | 33.75 | 122 | 0.70949 | 4.633333 | false | false | false | false |
codeka/wwmmo | planet-render/src/main/kotlin/au/com/codeka/warworlds/planetrender/Template.kt | 1 | 17934 | package au.com.codeka.warworlds.planetrender
import au.com.codeka.warworlds.common.Colour
import au.com.codeka.warworlds.common.ColourGradient
import au.com.codeka.warworlds.common.Vector3
import au.com.codeka.warworlds.common.XmlIterator.childElements
import au.com.codeka.warworlds.planetrender.Template.AtmosphereTemplate.AtmosphereTemplateFactory
import au.com.codeka.warworlds.planetrender.Template.ColourGradientTemplate.ColourGradientTemplateFactory
import au.com.codeka.warworlds.planetrender.Template.PerlinNoiseTemplate.PerlinNoiseTemplateFactory
import au.com.codeka.warworlds.planetrender.Template.PlanetTemplate.PlanetTemplateFactory
import au.com.codeka.warworlds.planetrender.Template.PlanetsTemplate.PlanetsTemplateFactory
import au.com.codeka.warworlds.planetrender.Template.PointCloudTemplate.PointCloudTemplateFactory
import au.com.codeka.warworlds.planetrender.Template.TextureTemplate.TextureTemplateFactory
import au.com.codeka.warworlds.planetrender.Template.VoronoiTemplate.VoronoiTemplateFactory
import au.com.codeka.warworlds.planetrender.Template.WarpTemplate.WarpTemplateFactory
import org.w3c.dom.Document
import org.w3c.dom.Element
import java.io.InputStream
import java.util.*
import javax.xml.parsers.DocumentBuilderFactory
/**
* A template is used to create an image (usually a complete planet, but it doesn't have to be).
*/
class Template {
var template: BaseTemplate? = null
private set
var templateVersion = 0
private set
/*
* The name of the template is whatever you want it to be. We don't care...
*/ var name: String? = null
abstract class TemplateFactory {
@Throws(TemplateException::class)
abstract fun parse(elem: Element): BaseTemplate
@Throws(TemplateException::class)
protected fun parseVector3(`val`: String): Vector3 {
val parts = `val`.split(" ").toTypedArray()
return if (parts.size == 3) {
Vector3(parts[0].toDouble(), parts[1].toDouble(), parts[2].toDouble())
} else {
throw TemplateException("Invalid vector: $`val`")
}
}
}
open class BaseTemplate {
val parameters: MutableList<BaseTemplate>
fun <T : BaseTemplate?> getParameters(classFactory: Class<T>): List<T> {
val params: MutableList<T> = ArrayList()
for (bt in parameters) {
if (bt.javaClass.isAssignableFrom(classFactory)) {
@Suppress("UNCHECKED_CAST")
params.add(bt as T)
}
}
return params
}
fun <T : BaseTemplate?> getParameter(classFactory: Class<T>): T? {
val params = getParameters(classFactory)
return if (params.isNotEmpty()) {
params[0]
} else null
}
init {
parameters = ArrayList()
}
}
class PlanetsTemplate : BaseTemplate() {
class PlanetsTemplateFactory : TemplateFactory() {
@Throws(TemplateException::class)
override fun parse(elem: Element): BaseTemplate {
val tmpl = PlanetsTemplate()
for (child in childElements(elem, null)) {
tmpl.parameters.add(parseElement(child))
}
return tmpl
}
}
}
class PlanetTemplate : BaseTemplate() {
lateinit var northFrom: Vector3
private set
lateinit var northTo: Vector3
private set
var planetSize = 0.0
private set
var ambient = 0.0
private set
lateinit var sunLocation: Vector3
lateinit var originFrom: Vector3
private set
lateinit var originTo: Vector3
private set
class PlanetTemplateFactory : TemplateFactory() {
/**
* Parses a <planet> node and returns the corresponding \c PlanetTemplate.
*/
override fun parse(elem: Element): BaseTemplate {
val tmpl = PlanetTemplate()
tmpl.originFrom = Vector3(0.0, 0.0, 30.0)
tmpl.originTo = Vector3(0.0, 0.0, 30.0)
if (elem.getAttribute("origin") != null && elem.getAttribute("origin") != "") {
val other = parseVector3(elem.getAttribute("origin"))
tmpl.originFrom.reset(other)
tmpl.originTo.reset(other)
}
if (elem.getAttribute("originFrom") != null
&& elem.getAttribute("originFrom") != "") {
val other = parseVector3(elem.getAttribute("originFrom"))
tmpl.originFrom.reset(other)
}
if (elem.getAttribute("originTo") != null && elem.getAttribute("originTo") != "") {
val other = parseVector3(elem.getAttribute("originTo"))
tmpl.originTo.reset(other)
}
tmpl.northFrom = Vector3(0.0, 1.0, 0.0)
tmpl.northTo = Vector3(0.0, 1.0, 0.0)
if (elem.getAttribute("northFrom") != null && elem.getAttribute("northFrom") != "") {
val other = parseVector3(elem.getAttribute("northFrom"))
tmpl.northFrom.reset(other)
}
if (elem.getAttribute("northTo") != null && elem.getAttribute("northTo") != "") {
val other = parseVector3(elem.getAttribute("northTo"))
tmpl.northTo.reset(other)
}
tmpl.planetSize = 10.0
if (elem.getAttribute("size") != null && elem.getAttribute("size") != "") {
tmpl.planetSize = elem.getAttribute("size").toDouble()
}
tmpl.ambient = 0.1
if (elem.getAttribute("ambient") != null && elem.getAttribute("ambient") != "") {
tmpl.ambient = elem.getAttribute("ambient").toDouble()
}
tmpl.sunLocation = Vector3(100.0, 100.0, -150.0)
if (elem.getAttribute("sun") != null && elem.getAttribute("sun") != "") {
val other = parseVector3(elem.getAttribute("sun"))
tmpl.sunLocation.reset(other)
}
for (child in childElements(elem, null)) {
tmpl.parameters.add(parseElement(child))
}
return tmpl
}
}
}
class TextureTemplate : BaseTemplate() {
enum class Generator {
VoronoiMap, PerlinNoise
}
var generator: Generator? = null
private set
var noisiness = 0.0
private set
var scaleX = 0.0
private set
var scaleY = 0.0
private set
class TextureTemplateFactory : TemplateFactory() {
/**
* Parses a <texture> node and returns the corresponding \c TextureTemplate.
</texture> */
@Throws(TemplateException::class)
override fun parse(elem: Element): BaseTemplate {
val tmpl = TextureTemplate()
val generator = elem.getAttribute("generator")
if (generator == "voronoi-map") {
tmpl.generator = Generator.VoronoiMap
} else if (generator == "perlin-noise") {
tmpl.generator = Generator.PerlinNoise
} else {
throw TemplateException("Unknown <texture generator> attribute: $generator")
}
val noisiness = elem.getAttribute("noisiness")
if (noisiness == null || noisiness == "") {
tmpl.noisiness = 0.5
} else {
tmpl.noisiness = noisiness.toDouble()
}
tmpl.scaleX = 1.0
tmpl.scaleY = 1.0
if (elem.getAttribute("scaleX") != null && elem.getAttribute("scaleX") != "") {
tmpl.scaleX = elem.getAttribute("scaleX").toDouble()
}
if (elem.getAttribute("scaleY") != null && elem.getAttribute("scaleY") != "") {
tmpl.scaleY = elem.getAttribute("scaleY").toDouble()
}
for (child in childElements(elem, null)) {
tmpl.parameters.add(parseElement(child))
}
return tmpl
}
}
}
class VoronoiTemplate : BaseTemplate() {
class VoronoiTemplateFactory : TemplateFactory() {
/**
* Parses a <voronoi> node and returns the corresponding \c VoronoiTemplate.
</voronoi> */
@Throws(TemplateException::class)
override fun parse(elem: Element): BaseTemplate {
val tmpl = VoronoiTemplate()
for (child in childElements(elem, null)) {
tmpl.parameters.add(parseElement(child))
}
return tmpl
}
}
}
class PointCloudTemplate : BaseTemplate() {
enum class Generator {
Random, Poisson
}
var generator: Generator? = null
private set
var density = 0.0
private set
var randomness = 0.0
private set
class PointCloudTemplateFactory : TemplateFactory() {
/**
* Parses a <point-cloud> node and returns the corresponding \c PointCloudTemplate.
</point-cloud> */
@Throws(TemplateException::class)
override fun parse(elem: Element): BaseTemplate {
val tmpl = PointCloudTemplate()
val `val` = elem.getAttribute("generator")
if (`val` == "random") {
tmpl.generator = Generator.Random
} else if (`val` == "poisson") {
tmpl.generator = Generator.Poisson
} else {
throw TemplateException("Unknown <point-cloud> 'generator' attribute: $`val`")
}
tmpl.density = elem.getAttribute("density").toDouble()
tmpl.randomness = elem.getAttribute("randomness").toDouble()
return tmpl
}
}
}
class ColourGradientTemplate : BaseTemplate() {
lateinit var colourGradient: ColourGradient
private set
/**
* Parses a <colour> node and returns the corresponding \c ColourGradient.
</colour> */
class ColourGradientTemplateFactory : TemplateFactory() {
override fun parse(elem: Element): BaseTemplate {
val tmpl = ColourGradientTemplate()
tmpl.colourGradient = ColourGradient()
for (child in childElements(elem, "node")) {
val n = child.getAttribute("n").toDouble()
val argb = child.getAttribute("colour").toLong(16).toInt()
tmpl.colourGradient.addNode(n, Colour(argb))
}
return tmpl
}
}
}
class PerlinNoiseTemplate : BaseTemplate() {
enum class Interpolation {
None, Linear, Cosine
}
var persistence = 0.0
private set
var interpolation: Interpolation? = null
private set
var startOctave = 0
private set
var endOctave = 0
private set
class PerlinNoiseTemplateFactory : TemplateFactory() {
override fun parse(elem: Element): BaseTemplate {
val tmpl = PerlinNoiseTemplate()
val `val` = elem.getAttribute("interpolation")
if (`val` == null || `val` == "linear") {
tmpl.interpolation = Interpolation.Linear
} else if (`val` == "cosine") {
tmpl.interpolation = Interpolation.Cosine
} else if (`val` == "none") {
tmpl.interpolation = Interpolation.None
} else {
throw TemplateException("Unknown <perlin> 'interpolation' attribute: $`val`")
}
tmpl.persistence = elem.getAttribute("persistence").toDouble()
if (elem.getAttribute("startOctave") == null) {
tmpl.startOctave = 1
} else {
tmpl.startOctave = elem.getAttribute("startOctave").toInt()
}
if (elem.getAttribute("endOctave") == null) {
tmpl.endOctave = 10
} else {
tmpl.endOctave = elem.getAttribute("endOctave").toInt()
}
return tmpl
}
}
}
class AtmosphereTemplate : BaseTemplate() {
enum class BlendMode {
Alpha, Additive, Multiply
}
var innerTemplate: InnerOuterTemplate? = null
private set
var outerTemplate: InnerOuterTemplate? = null
private set
var starTemplate: StarTemplate? = null
private set
open class InnerOuterTemplate : BaseTemplate() {
var sunStartShadow = 0.0
var sunShadowFactor = 0.0
var size = 0.0
var noisiness = 0.0
var blendMode: BlendMode? = null
}
class StarTemplate : InnerOuterTemplate() {
var numPoints = 0
var baseWidth = 0.0
var slope = 0.0
}
class AtmosphereTemplateFactory : TemplateFactory() {
override fun parse(elem: Element): BaseTemplate {
val tmpl = AtmosphereTemplate()
for (child in childElements(elem, null)) {
when (child.tagName) {
"inner" -> {
tmpl.innerTemplate = InnerOuterTemplate()
parseInnerOuterTemplate(tmpl.innerTemplate!!, child)
}
"outer" -> {
tmpl.outerTemplate = InnerOuterTemplate()
parseInnerOuterTemplate(tmpl.outerTemplate!!, child)
}
"star" -> {
tmpl.starTemplate = StarTemplate()
parseStarTemplate(tmpl.starTemplate!!, child)
}
}
}
return tmpl
}
private fun parseInnerOuterTemplate(tmpl: InnerOuterTemplate, elem: Element) {
if (elem.getAttribute("sunStartShadow") != null
&& elem.getAttribute("sunStartShadow") != "") {
tmpl.sunStartShadow = elem.getAttribute("sunStartShadow").toDouble()
}
if (elem.getAttribute("sunShadowFactor") != null
&& elem.getAttribute("sunShadowFactor") != "") {
tmpl.sunShadowFactor = elem.getAttribute("sunShadowFactor").toDouble()
}
tmpl.size = 1.0
if (elem.getAttribute("size") != null && elem.getAttribute("size") != "") {
tmpl.size = elem.getAttribute("size").toDouble()
}
tmpl.blendMode = BlendMode.Alpha
if (elem.getAttribute("blend") != null && elem.getAttribute("blend") != "") {
when {
elem.getAttribute("blend").equals("alpha", ignoreCase = true) -> {
tmpl.blendMode = BlendMode.Alpha
}
elem.getAttribute("blend").equals("additive", ignoreCase = true) -> {
tmpl.blendMode = BlendMode.Additive
}
elem.getAttribute("blend").equals("multiply", ignoreCase = true) -> {
tmpl.blendMode = BlendMode.Multiply
}
else -> {
throw TemplateException("Unknown 'blend' value: " + elem.getAttribute("blend"))
}
}
}
if (elem.getAttribute("noisiness") != null && elem.getAttribute("noisiness") != "") {
tmpl.noisiness = elem.getAttribute("noisiness").toDouble()
}
for (child in childElements(elem, null)) {
tmpl.parameters.add(parseElement(child))
}
}
@Throws(TemplateException::class)
private fun parseStarTemplate(tmpl: StarTemplate, elem: Element) {
parseInnerOuterTemplate(tmpl, elem)
tmpl.numPoints = 5
if (elem.getAttribute("points") != null && elem.getAttribute("points") != "") {
tmpl.numPoints = elem.getAttribute("points").toInt()
}
tmpl.baseWidth = 1.0
if (elem.getAttribute("baseWidth") != null && elem.getAttribute("baseWidth") != "") {
tmpl.baseWidth = elem.getAttribute("baseWidth").toDouble()
}
tmpl.slope = 0.0
if (elem.getAttribute("slope") != null && elem.getAttribute("slope") != "") {
tmpl.slope = elem.getAttribute("slope").toDouble()
}
}
}
}
class WarpTemplate : BaseTemplate() {
enum class NoiseGenerator {
Perlin, Spiral
}
var noiseGenerator: NoiseGenerator? = null
private set
var warpFactor = 0.0
private set
class WarpTemplateFactory : TemplateFactory() {
/**
* Parses a <warp> node and returns the corresponding \c ImageWarpTemplate.
</warp> */
@Throws(TemplateException::class)
override fun parse(elem: Element): BaseTemplate {
val tmpl = WarpTemplate()
if (elem.getAttribute("generator") == "perlin-noise") {
tmpl.noiseGenerator = NoiseGenerator.Perlin
} else if (elem.getAttribute("generator") == "spiral") {
tmpl.noiseGenerator = NoiseGenerator.Spiral
} else {
throw TemplateException("Unknown generator type: " + elem.getAttribute("generator"))
}
tmpl.warpFactor = 0.1
if (elem.getAttribute("factor") != null && elem.getAttribute("factor").length > 0) {
tmpl.warpFactor = elem.getAttribute("factor").toDouble()
}
for (child in childElements(elem, null)) {
tmpl.parameters.add(parseElement(child))
}
return tmpl
}
}
}
companion object {
/**
* Parses the given string input and returns the \c Template it represents.
*/
@Throws(TemplateException::class)
fun parse(inp: InputStream?): Template {
val builderFactory = DocumentBuilderFactory.newInstance()
builderFactory.isValidating = false
val xmldoc: Document
xmldoc = try {
val builder = builderFactory.newDocumentBuilder()
builder.parse(inp)
} catch (e: Exception) {
throw TemplateException(e)
}
val tmpl = Template()
val version = xmldoc.documentElement.getAttribute("version")
if (version != null && version.length > 0) {
tmpl.templateVersion = version.toInt()
} else {
tmpl.templateVersion = 1
}
tmpl.template = parseElement(xmldoc.documentElement)
return tmpl
}
@Throws(TemplateException::class)
private fun parseElement(elem: Element): BaseTemplate {
val factory = when (elem.tagName) {
"planets" -> {
PlanetsTemplateFactory()
}
"planet" -> {
PlanetTemplateFactory()
}
"texture" -> {
TextureTemplateFactory()
}
"point-cloud" -> {
PointCloudTemplateFactory()
}
"voronoi" -> {
VoronoiTemplateFactory()
}
"colour" -> {
ColourGradientTemplateFactory()
}
"perlin" -> {
PerlinNoiseTemplateFactory()
}
"atmosphere" -> {
AtmosphereTemplateFactory()
}
"warp" -> {
WarpTemplateFactory()
}
else -> {
throw TemplateException("Unknown element: " + elem.tagName)
}
}
return factory.parse(elem)
}
}
} | mit | 84431bd5b0270637ef20aa1a09942338 | 33.096958 | 105 | 0.608844 | 4.253795 | false | false | false | false |
QingMings/flashair | src/main/kotlin/com/iezview/model/Solution.kt | 1 | 2703 | package com.iezview.model
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import tornadofx.*
import javax.json.JsonObject
/**
* Created by shishifanbuxie on 2017/4/12.
* 方案
*/
class Solution() :JsonModel{
var name by property<String>()
fun nameProperty() =getProperty(Solution::name)
var cameraList by property<ObservableList<Camera>>(FXCollections.observableArrayList())
fun cameraListProperty() =getProperty(Solution::cameraList)
override fun updateModel(json: JsonObject) {
with(json){
name= string("name")
cameraList.setAll(getJsonArray("cameraList").toModel())
}
}
override fun toJSON(json: JsonBuilder) {
with(json){
add("name",name)
add("cameraList",cameraList.toJSON())
}
}
override fun toString(): String {
return "Solution(name=$name,cameraList=$cameraList)"
}
}
class SolutionModel : ItemViewModel<Solution>(Solution()) {
val name = bind ( Solution::nameProperty,true )
val cameraList = bind(Solution::cameraListProperty,true)
}
/**
* 方案列表
* 储存方案列表
* 并且用于动态构建菜单
*/
class Solutions(sn: ObservableList<SolutionName>?=FXCollections.observableArrayList<SolutionName>(emptyList<SolutionName>())) :JsonModel{
companion object{
val ROOT="solutions"
val SOLUTION_NAMES="solutionNames"
}
var solutionNames by property(sn)
fun solutionNamesProperty()=getProperty(Solutions::solutionNames)
override fun updateModel(json: JsonObject) {
with(json){
solutionNames.setAll(getJsonArray(SOLUTION_NAMES).toModel<SolutionName>())
}
}
override fun toJSON(json: JsonBuilder) {
with(json){
add(SOLUTION_NAMES,solutionNames.toJSON())
}
}
override fun toString(): String {
return "Solutions(solutionNames:$solutionNames)"
}
}
class SolutionsModel : ItemViewModel<Solutions>() {
val solutionNames = bind { item?.solutionNamesProperty() }
}
/**
* 方案名称
*/
class SolutionName( solutionName: String?="") :JsonModel{
var name by property(solutionName)
fun nameProperty() =getProperty(SolutionName::name)
override fun updateModel(json: JsonObject) {
with(json){
name=string("name")
}
}
override fun toJSON(json: JsonBuilder) {
with(json){
add("name",name)
}
}
override fun toString(): String {
return "SolutionName(name=$name)"
}
}
class SolutionNameModel : ItemViewModel<SolutionName>() {
val name = bind { item?.nameProperty() }
}
| mit | 055b3f589c96e4aa9b11efb5413ad006 | 24.990196 | 137 | 0.650321 | 4.262058 | false | false | false | false |
AndroidX/androidx | compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/KeyboardOptions.kt | 3 | 4592 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.text
import androidx.compose.runtime.Immutable
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.ImeOptions
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
/**
* The keyboard configuration options for TextFields. It is not guaranteed if software keyboard
* will comply with the options provided here.
*
* @param capitalization informs the keyboard whether to automatically capitalize characters,
* words or sentences. Only applicable to only text based [KeyboardType]s such as
* [KeyboardType.Text], [KeyboardType.Ascii]. It will not be applied to [KeyboardType]s such as
* [KeyboardType.Number].
* @param autoCorrect informs the keyboard whether to enable auto correct. Only applicable to
* text based [KeyboardType]s such as [KeyboardType.Email], [KeyboardType.Uri]. It will not be
* applied to [KeyboardType]s such as [KeyboardType.Number]. Most of keyboard
* implementations ignore this value for [KeyboardType]s such as [KeyboardType.Text].
* @param keyboardType The keyboard type to be used in this text field. Note that this input type
* is honored by keyboard and shows corresponding keyboard but this is not guaranteed. For example,
* some keyboards may send non-ASCII character even if you set [KeyboardType.Ascii].
* @param imeAction The IME action. This IME action is honored by keyboard and may show specific
* icons on the keyboard. For example, search icon may be shown if [ImeAction.Search] is specified.
* When [ImeOptions.singleLine] is false, the keyboard might show return key rather than the action
* requested here.
*/
@Immutable
class KeyboardOptions constructor(
val capitalization: KeyboardCapitalization = KeyboardCapitalization.None,
val autoCorrect: Boolean = true,
val keyboardType: KeyboardType = KeyboardType.Text,
val imeAction: ImeAction = ImeAction.Default
) {
companion object {
/**
* Default [KeyboardOptions]. Please see parameter descriptions for default values.
*/
val Default = KeyboardOptions()
}
/**
* Returns a new [ImeOptions] with the values that are in this [KeyboardOptions] and provided
* params.
*
* @param singleLine see [ImeOptions.singleLine]
*/
internal fun toImeOptions(singleLine: Boolean = ImeOptions.Default.singleLine) = ImeOptions(
singleLine = singleLine,
capitalization = capitalization,
autoCorrect = autoCorrect,
keyboardType = keyboardType,
imeAction = imeAction
)
fun copy(
capitalization: KeyboardCapitalization = this.capitalization,
autoCorrect: Boolean = this.autoCorrect,
keyboardType: KeyboardType = this.keyboardType,
imeAction: ImeAction = this.imeAction
): KeyboardOptions {
return KeyboardOptions(
capitalization = capitalization,
autoCorrect = autoCorrect,
keyboardType = keyboardType,
imeAction = imeAction
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is KeyboardOptions) return false
if (capitalization != other.capitalization) return false
if (autoCorrect != other.autoCorrect) return false
if (keyboardType != other.keyboardType) return false
if (imeAction != other.imeAction) return false
return true
}
override fun hashCode(): Int {
var result = capitalization.hashCode()
result = 31 * result + autoCorrect.hashCode()
result = 31 * result + keyboardType.hashCode()
result = 31 * result + imeAction.hashCode()
return result
}
override fun toString(): String {
return "KeyboardOptions(capitalization=$capitalization, autoCorrect=$autoCorrect, " +
"keyboardType=$keyboardType, imeAction=$imeAction)"
}
} | apache-2.0 | b8986433b5bb53c4570a8570ca46d40b | 40.378378 | 99 | 0.714068 | 4.885106 | false | false | false | false |
foreverigor/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/chat/ChatMessagesCard.kt | 1 | 3507 | package de.tum.`in`.tumcampusapp.component.ui.chat
import android.content.Context
import android.content.SharedPreferences.Editor
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.google.common.collect.Lists
import com.google.gson.Gson
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.other.navigation.NavigationDestination
import de.tum.`in`.tumcampusapp.component.other.navigation.SystemActivity
import de.tum.`in`.tumcampusapp.component.ui.chat.activity.ChatActivity
import de.tum.`in`.tumcampusapp.component.ui.chat.model.ChatMessage
import de.tum.`in`.tumcampusapp.component.ui.chat.model.ChatRoom
import de.tum.`in`.tumcampusapp.component.ui.chat.model.ChatRoomDbRow
import de.tum.`in`.tumcampusapp.component.ui.overview.CardManager.CARD_CHAT
import de.tum.`in`.tumcampusapp.component.ui.overview.card.Card
import de.tum.`in`.tumcampusapp.component.ui.overview.card.CardViewHolder
import de.tum.`in`.tumcampusapp.database.TcaDb
import de.tum.`in`.tumcampusapp.utils.Const
import java.util.*
/**
* Card that shows the cafeteria menu
*/
class ChatMessagesCard(context: Context,
room: ChatRoomDbRow) : Card(CARD_CHAT, context, "card_chat") {
private var mUnread: List<ChatMessage> = ArrayList()
private var nrUnread = 0;
private var mRoomName = ""
private var mRoomId = 0
private var mRoomIdString = ""
private val chatMessageDao: ChatMessageDao
override val optionsMenuResId: Int
get() = R.menu.card_popup_menu
init {
val tcaDb = TcaDb.getInstance(context)
chatMessageDao = tcaDb.chatMessageDao()
setChatRoom(room.name, room.room, "${room.semesterId}:${room.name}")
}
override fun updateViewHolder(viewHolder: RecyclerView.ViewHolder) {
super.updateViewHolder(viewHolder)
val chatMessagesViewHolder = viewHolder as? ChatMessagesCardViewHolder
chatMessagesViewHolder?.bind(mRoomName, mRoomId, mRoomIdString, mUnread)
}
/**
* Sets the information needed to build the card
*
* @param roomName Name of the chat room
* @param roomId Id of the chat room
*/
private fun setChatRoom(roomName: String, roomId: Int, roomIdString: String) {
mRoomName = listOf("[A-Z, 0-9(LV\\.Nr)=]+$", "\\([A-Z]+[0-9]+\\)", "\\[[A-Z]+[0-9]+\\]")
.map { it.toRegex() }
.fold(roomName) { name, regex -> name.replace(regex, "") }
.trim()
chatMessageDao.deleteOldEntries()
nrUnread = chatMessageDao.getNumberUnread(roomId)
mUnread = Lists.reverse(chatMessageDao.getLastUnread(roomId))
mRoomIdString = roomIdString
mRoomId = roomId
}
override fun getNavigationDestination(): NavigationDestination? {
val bundle = Bundle().apply {
val chatRoom = ChatRoom(mRoomIdString).apply { id = mRoomId }
val value = Gson().toJson(chatRoom)
putString(Const.CURRENT_CHAT_ROOM, value)
}
return SystemActivity(ChatActivity::class.java, bundle)
}
override fun getId() = mRoomId
override fun discard(editor: Editor) = chatMessageDao.markAsRead(mRoomId)
companion object {
fun inflateViewHolder(parent: ViewGroup) =
CardViewHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.card_chat_messages, parent, false))
}
}
| gpl-3.0 | 34d64795f287cf7c30049ae8cf5848e8 | 37.538462 | 96 | 0.694611 | 4.082654 | false | false | false | false |
physphil/UnitConverterUltimate | v6000/src/main/java/com/physphil/android/unitconverterultimate/settings/SettingsViewModel.kt | 1 | 1945 | package com.physphil.android.unitconverterultimate.settings
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.physphil.android.unitconverterultimate.util.Event
private const val URL_RATE_APP = "market://details?id=com.physphil.android.unitconverterultimate"
private const val URL_GITHUB_REPO = "https://github.com/physphil/UnitConverterUltimate"
private const val URL_GITHUB_ISSUE = "https://github.com/physphil/UnitConverterUltimate/issues"
private const val URL_PRIVACY_POLICY = "https://privacypolicies.com/privacy/view/f7a41d67f1b0081f249c2ff0a3123136"
class SettingsViewModel : ViewModel() {
private val _openUrlEvent = MutableLiveData<Event<String>>()
val openUrlEvent: LiveData<Event<String>> = _openUrlEvent
fun onPreferenceClicked(key: String) {
when (key) {
Keys.UNIT_REQUEST -> TODO("Still need to figure out how to accept unit requests")
Keys.RATE_APP -> _openUrlEvent.postValue(Event(URL_RATE_APP))
Keys.OPEN_ISSUE -> _openUrlEvent.postValue(Event(URL_GITHUB_ISSUE))
Keys.VIEW_SOURCE -> _openUrlEvent.postValue(Event(URL_GITHUB_REPO))
Keys.PRIVACY_POLICY -> _openUrlEvent.postValue(Event(URL_PRIVACY_POLICY))
}
}
object Keys {
const val NUMBER_DECIMALS = "pref_number_decimals"
const val GROUP_SEPARATOR = "pref_group_separator"
const val DECIMAL_SEPARATOR = "pref_decimal_separator"
const val THEME = "pref_theme"
const val LANGUAGE = "pref_language"
const val DONATE = "pref_donate"
const val ACKNOWLEDGEMENTS = "pref_acknowledgements"
const val UNIT_REQUEST = "pref_unit_request"
const val RATE_APP = "pref_rate_app"
const val OPEN_ISSUE = "pref_open_issue"
const val VIEW_SOURCE = "pref_view_source"
const val PRIVACY_POLICY = "pref_privacy_policy"
}
} | apache-2.0 | 73bf7ad15bca7798931a6d37571a8a52 | 45.333333 | 114 | 0.711054 | 3.851485 | false | false | false | false |
google/dokka | core/src/main/kotlin/Formats/KotlinWebsiteHtmlFormatService.kt | 2 | 6397 | package org.jetbrains.dokka
import com.google.inject.Inject
import com.google.inject.name.Named
import org.jetbrains.dokka.Utilities.impliedPlatformsName
import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty
import java.io.File
object EmptyHtmlTemplateService : HtmlTemplateService {
override fun appendFooter(to: StringBuilder) {}
override fun appendHeader(to: StringBuilder, title: String?, basePath: File) {}
}
open class KotlinWebsiteHtmlOutputBuilder(
to: StringBuilder,
location: Location,
generator: NodeLocationAwareGenerator,
languageService: LanguageService,
extension: String,
impliedPlatforms: List<String>,
templateService: HtmlTemplateService
) : HtmlOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms, templateService) {
private var needHardLineBreaks = false
private var insideDiv = 0
override fun appendLine() {}
override fun appendBreadcrumbs(path: Iterable<FormatLink>) {
if (path.count() > 1) {
to.append("<div class='api-docs-breadcrumbs'>")
super.appendBreadcrumbs(path)
to.append("</div>")
}
}
override fun appendCode(body: () -> Unit) = wrapIfNotEmpty("<code>", "</code>", body)
protected fun div(to: StringBuilder, cssClass: String, otherAttributes: String = "", block: () -> Unit) {
to.append("<div class=\"$cssClass\"$otherAttributes")
to.append(">")
insideDiv++
block()
insideDiv--
to.append("</div>\n")
}
override fun appendAsSignature(node: ContentNode, block: () -> Unit) {
val contentLength = node.textLength
if (contentLength == 0) return
div(to, "signature") {
needHardLineBreaks = contentLength >= 62
try {
block()
} finally {
needHardLineBreaks = false
}
}
}
override fun appendAsOverloadGroup(to: StringBuilder, platforms: Set<String>, block: () -> Unit) {
div(to, "overload-group", calculateDataAttributes(platforms)) {
block()
}
}
override fun appendLink(href: String, body: () -> Unit) = wrap("<a href=\"$href\">", "</a>", body)
override fun appendTable(vararg columns: String, body: () -> Unit) {
to.appendln("<table class=\"api-docs-table\">")
body()
to.appendln("</table>")
}
override fun appendTableBody(body: () -> Unit) {
to.appendln("<tbody>")
body()
to.appendln("</tbody>")
}
override fun appendTableRow(body: () -> Unit) {
to.appendln("<tr>")
body()
to.appendln("</tr>")
}
override fun appendTableCell(body: () -> Unit) {
to.appendln("<td>")
body()
to.appendln("\n</td>")
}
override fun appendSymbol(text: String) {
to.append("<span class=\"symbol\">${text.htmlEscape()}</span>")
}
override fun appendKeyword(text: String) {
to.append("<span class=\"keyword\">${text.htmlEscape()}</span>")
}
override fun appendIdentifier(text: String, kind: IdentifierKind, signature: String?) {
val id = signature?.let { " id=\"$it\"" }.orEmpty()
to.append("<span class=\"${identifierClassName(kind)}\"$id>${text.htmlEscape()}</span>")
}
override fun appendSoftLineBreak() {
if (needHardLineBreaks)
to.append("<br/>")
}
override fun appendIndentedSoftLineBreak() {
if (needHardLineBreaks) {
to.append("<br/> ")
}
}
private fun identifierClassName(kind: IdentifierKind) = when (kind) {
IdentifierKind.ParameterName -> "parameterName"
IdentifierKind.SummarizedTypeName -> "summarizedTypeName"
else -> "identifier"
}
fun calculateDataAttributes(platforms: Set<String>): String {
fun String.isKotlinVersion() = this.startsWith("Kotlin")
fun String.isJREVersion() = this.startsWith("JRE")
val kotlinVersion = platforms.singleOrNull(String::isKotlinVersion)
val jreVersion = platforms.singleOrNull(String::isJREVersion)
val targetPlatforms = platforms.filterNot { it.isKotlinVersion() || it.isJREVersion() }
val kotlinVersionAttr = kotlinVersion?.let { " data-kotlin-version=\"$it\"" } ?: ""
val jreVersionAttr = jreVersion?.let { " data-jre-version=\"$it\"" } ?: ""
val platformsAttr = targetPlatforms.ifNotEmpty { " data-platform=\"${targetPlatforms.joinToString()}\"" } ?: ""
return "$platformsAttr$kotlinVersionAttr$jreVersionAttr"
}
override fun appendIndexRow(platforms: Set<String>, block: () -> Unit) {
if (platforms.isNotEmpty())
wrap("<tr${calculateDataAttributes(platforms)}>", "</tr>", block)
else
appendTableRow(block)
}
override fun appendPlatforms(platforms: Set<String>) {}
override fun appendBreadcrumbSeparator() {
to.append(" / ")
}
override fun appendSampleBlockCode(language: String, imports: () -> Unit, body: () -> Unit) {
div(to, "sample") {
appendBlockCode(language) {
imports()
wrap("\n\nfun main(args: Array<String>) {".htmlEscape(), "}") {
wrap("\n//sampleStart\n", "\n//sampleEnd\n", body)
}
}
}
}
override fun appendSoftParagraph(body: () -> Unit) = appendParagraph(body)
override fun appendSectionWithTag(section: ContentSection) {
appendParagraph {
appendStrong { appendText(section.tag) }
appendText(" ")
appendContent(section)
}
}
}
class KotlinWebsiteHtmlFormatService @Inject constructor(
generator: NodeLocationAwareGenerator,
signatureGenerator: LanguageService,
@Named(impliedPlatformsName) impliedPlatforms: List<String>,
templateService: HtmlTemplateService
) : HtmlFormatService(generator, signatureGenerator, templateService, impliedPlatforms) {
override fun enumerateSupportFiles(callback: (String, String) -> Unit) {}
override fun createOutputBuilder(to: StringBuilder, location: Location) =
KotlinWebsiteHtmlOutputBuilder(to, location, generator, languageService, extension, impliedPlatforms, templateService)
}
| apache-2.0 | 05e3270fe7e3b1aa087cd4dac9dc2c54 | 33.392473 | 130 | 0.621541 | 4.50493 | false | false | false | false |
jean79/yested | src/main/docsite/demo/chartjs/chartjs_doughnut.kt | 2 | 1570 | package demo.chartjs
import net.yested.Div
import net.yested.div
import net.yested.Chart
import net.yested.PieChartSeries
import net.yested.randomColor
import net.yested.toHTMLColor
import net.yested.lighten
class Data3(val countryCode:String, val temperature:Double)
fun createDoughnutChartSection(): Div {
val chart = Chart(width = 300, height = 250)
val temperaturesData = arrayOf(
Data3("BEL", 9.51),
Data3("BEN", 27.46),
Data3("BFA", 28.18),
Data3("BGD", 25.47),
Data3("BGR", 10.40),
Data3("BHS", 25.06),
Data3("BIH", 9.02),
Data3("BLR", 6.29),
Data3("BLZ", 25.06),
Data3("BOL", 20.98),
Data3("BRA", 24.92),
Data3("BRN", 25.93),
Data3("BTN", 8.58),
Data3("BWA", 21.48),
Data3("CAF", 24.84))
val chartData:Array<PieChartSeries> = temperaturesData.map {
val color = randomColor(1.0)
PieChartSeries(
value = it.temperature,
color = color.toHTMLColor(),
highlight = color.lighten(30).toHTMLColor(),
label = it.countryCode
)
}.toTypedArray()
val options = object {
val responsive = true
}
chart.drawDoughnutChart(chartData, options)
return div {
h4 { +"Doughnut Chart"}
+chart
a(href = "https://github.com/jean79/yested/blob/master/src/main/docsite/demo/chartjs/chartjs_doughnut.kt", target = "_blank") { +"Source code"}
}
} | mit | c08b284ed44286a67654a3502df61ec7 | 27.053571 | 151 | 0.56242 | 3.473451 | false | false | false | false |
google/ide-perf | src/main/java/com/google/idea/perf/tracer/ui/TracerUIUtil.kt | 1 | 3302 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.perf.tracer.ui
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.event.BulkAwareDocumentListener
import com.intellij.openapi.project.ProjectManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.ui.EditorTextField
import com.intellij.util.textCompletion.TextCompletionProvider
import com.intellij.util.textCompletion.TextCompletionUtil
import com.intellij.util.textCompletion.TextFieldWithCompletion
import java.awt.KeyboardFocusManager
import java.awt.event.ActionListener
import java.awt.event.KeyEvent
import javax.swing.JComponent
import javax.swing.JComponent.WHEN_FOCUSED
import javax.swing.KeyStroke
object TracerUIUtil {
fun addEnterKeyAction(textField: EditorTextField, action: () -> Unit) {
check(textField.editor == null) { "Must be called before the editor is initialized" }
textField.addSettingsProvider { editor ->
val enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0)
val enterHandler = ActionListener { action() }
editor.contentComponent.registerKeyboardAction(enterHandler, enter, WHEN_FOCUSED)
}
}
// TODO: This is a workaround for https://youtrack.jetbrains.com/issue/IDEA-248576.
// (Needed when the text field is backed by the 'default' project.)
fun reinstallCompletionProviderAsNeeded(
textField: TextFieldWithCompletion,
completionProvider: TextCompletionProvider
) {
check(textField.editor == null) { "Must be called before the editor is initialized" }
textField.addSettingsProvider { editor ->
editor.document.addDocumentListener(object : BulkAwareDocumentListener.Simple {
override fun beforeDocumentChange(document: Document) {
ApplicationManager.getApplication().assertReadAccessAllowed()
val project = textField.project ?: ProjectManager.getInstance().defaultProject
val psiDocumentManager = PsiDocumentManager.getInstance(project)
val psiFile = psiDocumentManager.getPsiFile(document) ?: return
val currentProvider = TextCompletionUtil.getProvider(psiFile)
if (currentProvider == null) {
val logger = Logger.getInstance(TracerUIUtil::class.java)
logger.warn("Reinstalling TextCompletionProvider (see IDEA-248576)")
TextCompletionUtil.installProvider(psiFile, completionProvider, true)
}
}
})
}
}
} | apache-2.0 | 77919492fa3f14bd84e88f547ab1757a | 45.521127 | 98 | 0.713507 | 4.987915 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/util/NullUtil.kt | 1 | 1086 | /*
* Copyright (C) 2019 yvolk (Yuri Volkov), http://yurivolkov.com
*
* 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.andstatus.app.util
/** Avoiding null-s */
object NullUtil {
fun nonEmpty(any: Any?): Boolean {
if (any is IsEmpty) return any.nonEmpty
return if (any is String) !(any as String?).isNullOrEmpty() else any != null
}
fun <K, V> getOrDefault(map: Map<K, V>?, key: K?, defaultValue: V): V {
if (map == null || key == null) return defaultValue
val v = map[key]
return v ?: defaultValue
}
}
| apache-2.0 | 4d76d1faa3f86096e899c0c554a696bf | 35.2 | 84 | 0.672192 | 3.920578 | false | false | false | false |
solkin/drawa-android | app/src/main/java/com/tomclaw/drawa/draw/view/DrawingView.kt | 1 | 2302 | package com.tomclaw.drawa.draw.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.tomclaw.drawa.R
import com.tomclaw.drawa.draw.BitmapDrawHost
import com.tomclaw.drawa.draw.BitmapHost
import com.tomclaw.drawa.draw.DrawHost
import kotlin.math.min
class DrawingView(
context: Context,
attributeSet: AttributeSet
) : View(context, attributeSet), BitmapHost by BitmapDrawHost(), DrawHost {
private var dst: Rect? = null
override val paint: Paint = Paint().apply {
isAntiAlias = true
isDither = true
isFilterBitmap = true
}
var drawingListener: DrawingListener? = null
override fun onDraw(canvas: Canvas) {
if (dst == null) {
dst = Rect(0, 0, width, height)
}
val dst = dst ?: return
drawTransparency(canvas)
canvas.drawBitmap(normalBitmap, src, dst, paint)
drawingListener?.onDraw()
}
private fun drawTransparency(canvas: Canvas) {
canvas.drawColor(resources.getColor(R.color.transparent_chess_light))
paint.color = resources.getColor(R.color.transparent_chess_dark)
val size = resources.getDimensionPixelSize(R.dimen.transparent_chess_size)
val colCount = width / size + 1
val rowCount = height / size + 1
for (vrt in 0 until colCount step 1) {
val start = vrt % 2
for (hrz in start until rowCount step 2) {
val hrzPxl = size * hrz.toFloat()
val vrtPxl = size * vrt.toFloat()
canvas.drawRect(hrzPxl, vrtPxl, hrzPxl + size, vrtPxl + size, paint)
}
}
}
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
val eventX = (bitmap.width * event.x / width).toInt()
val eventY = (bitmap.height * event.y / height).toInt()
drawingListener?.onTouchEvent(TouchEvent(eventX, eventY, event.action))
invalidate()
return true
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val size = min(widthMeasureSpec, heightMeasureSpec)
super.onMeasure(size, size)
}
}
| apache-2.0 | f6c135ca95f3b3e7bb61a8f44406e8f6 | 30.108108 | 84 | 0.657689 | 4.132855 | false | false | false | false |
smichel17/simpletask-android | app/src/main/java/nl/mpcjanssen/simpletask/Constants.kt | 1 | 2710 | /**
* This file is part of Todo.txt Touch, an Android app for managing your todo.txt file (http://todotxt.com).
* Copyright (c) 2009-2012 Todo.txt contributors (http://todotxt.com)
* LICENSE:
* Todo.txt Touch 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.
* Todo.txt Touch 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 Todo.txt Touch. If not, see
* //www.gnu.org/licenses/>.
* @author Todo.txt contributors @yahoogroups.com>
* *
* @license http://www.gnu.org/licenses/gpl.html
* *
* @copyright 2009-2012 Todo.txt contributors (http://todotxt.com)
*/
package nl.mpcjanssen.simpletask
object Constants {
const val DATE_FORMAT = "YYYY-MM-DD"
// Constants for creating shortcuts
const val INTENT_SELECTED_TASK_LINE = "SELECTED_TASK_LINE"
const val BROADCAST_ACTION_LOGOUT = "ACTION_LOGOUT"
const val BROADCAST_TASKLIST_CHANGED = "TASKLIST_CHANGED"
const val BROADCAST_AUTH_FAILED = "AUTH_FAILED"
const val BROADCAST_UPDATE_WIDGETS = "UPDATE_WIDGETS"
const val BROADCAST_FILE_SYNC = "FILE_SYNC"
const val BROADCAST_THEME_CHANGED = "THEME_CHANGED"
const val BROADCAST_DATEBAR_SIZE_CHANGED = "DATEBAR_SIZE_CHANGED"
const val BROADCAST_SYNC_START = "SYNC_START"
const val BROADCAST_SYNC_DONE = "SYNC_DONE"
const val BROADCAST_HIGHLIGHT_SELECTION = "HIGHLIGHT_SELECTION"
const val BROADCAST_STATE_INDICATOR = "STATE_INDICATOR"
const val BROADCAST_MAIN_FONTSIZE_CHANGED = "MAIN_FONT_SIZE_CHANGED"
// Sharing constants
const val SHARE_FILE_NAME = "simpletask.txt"
// Public intents
const val INTENT_START_FILTER = "nl.mpcjanssen.simpletask.START_WITH_FILTER"
const val INTENT_BACKGROUND_TASK = "nl.mpcjanssen.simpletask.BACKGROUND_TASK"
// Intent extras
const val EXTRA_BACKGROUND_TASK = "task"
const val EXTRA_HELP_PAGE = "page"
const val EXTRA_WIDGET_RECONFIGURE = "widgetreconfigure"
const val EXTRA_WIDGET_ID = "widgetid"
const val EXTRA_PREFILL_TEXT = "prefill_text"
// Android OS specific constants
const val ANDROID_EVENT = "vnd.android.cursor.item/event"
const val ALARM_REASON_EXTRA = "reason"
const val ALARM_RELOAD = "reload"
const val ALARM_NEW_DAY = "newday"
}
enum class DateType {
DUE, THRESHOLD
}
| gpl-3.0 | 10acdb28278f25b7eab60cf42f54ad47 | 35.133333 | 119 | 0.721771 | 3.732782 | false | false | false | false |
pbauerochse/youtrack-worklog-viewer | application/src/main/java/de/pbauerochse/worklogviewer/fx/issuesearch/task/SearchIssuesTask.kt | 1 | 1103 | package de.pbauerochse.worklogviewer.fx.issuesearch.task
import de.pbauerochse.worklogviewer.datasource.DataSources
import de.pbauerochse.worklogviewer.tasks.Progress
import de.pbauerochse.worklogviewer.tasks.WorklogViewerTask
import de.pbauerochse.worklogviewer.timereport.Issue
import de.pbauerochse.worklogviewer.util.FormattingUtil.getFormatted
import org.slf4j.LoggerFactory
/**
* Task that searches a List of Issues by a given query
*/
class SearchIssuesTask(
private val query: String,
private val offset: Int,
private val maxResults: Int
) : WorklogViewerTask<List<Issue>>(getFormatted("dialog.issuesearch.task.title")) {
val isNewSearch = offset == 0
override fun start(progress: Progress): List<Issue> {
LOGGER.info("Searching for Issues with query='$query' and offset=$offset and maxResults=$maxResults")
val dataSource = DataSources.activeDataSource!!
return dataSource.searchIssues(query, offset, maxResults, progress)
}
companion object {
private val LOGGER = LoggerFactory.getLogger(SearchIssuesTask::class.java)
}
}
| mit | 212aad113b96a5ce80224e13ee664e62 | 35.766667 | 109 | 0.766092 | 4.465587 | false | false | false | false |
StepicOrg/stepic-android | model/src/main/java/org/stepik/android/model/Progress.kt | 1 | 717 | package org.stepik.android.model
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
import ru.nobird.android.core.model.Identifiable
@Parcelize
data class Progress(
@SerializedName("id")
override val id: String,
@SerializedName("last_viewed")
val lastViewed: String? = null, //in SECONDS
@SerializedName("score")
var score: String? = null,
@SerializedName("cost")
val cost: Long = 0,
@SerializedName("n_steps")
val nSteps: Long = 0,
@SerializedName("n_steps_passed")
val nStepsPassed: Long = 0,
@SerializedName("is_passed")
val isPassed: Boolean = false
) : Parcelable, Identifiable<String>
| apache-2.0 | 3f5315e98e75d25de07551617c76cbc1 | 28.875 | 49 | 0.712692 | 3.875676 | false | false | false | false |
savvasdalkitsis/gameframe | ip/src/main/java/com/savvasdalkitsis/gameframe/feature/ip/view/IpTextView.kt | 1 | 3745 | /**
* Copyright 2017 Savvas Dalkitsis
* 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.
*
* 'Game Frame' is a registered trademark of LEDSEQ
*/
package com.savvasdalkitsis.gameframe.feature.ip.view
import android.annotation.SuppressLint
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.savvasdalkitsis.gameframe.feature.ip.R
import com.savvasdalkitsis.gameframe.feature.networking.model.IpAddress
class IpTextView : LinearLayout {
private lateinit var part1: TextView
private lateinit var part2: TextView
private lateinit var part3: TextView
private lateinit var part4: TextView
private var ipChangedListener: IpChangedListener? = null
var ipAddress: IpAddress = IpAddress()
private set
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun onFinishInflate() {
super.onFinishInflate()
part1 = findViewById(R.id.view_ip_text_view_part_1)
part2 = findViewById(R.id.view_ip_text_view_part_2)
part3 = findViewById(R.id.view_ip_text_view_part_3)
part4 = findViewById(R.id.view_ip_text_view_part_4)
listOf(part1, part2, part3, part4).forEach { setup(it) }
}
private fun setup(textView: TextView) {
textView.addTextChangedListener(IpTextChanged(textView))
textView.setSelectAllOnFocus(true)
}
private fun rebuildIpAddress() {
ipAddress = IpAddress(
part1 = part1.text.toString(),
part2 = part2.text.toString(),
part3 = part3.text.toString(),
part4 = part4.text.toString()
)
}
fun setOnIpChangedListener(ipChangedListener: IpChangedListener) {
this.ipChangedListener = ipChangedListener
}
fun bind(ipAddress: IpAddress) {
part1.text = ipAddress.part1
part2.text = ipAddress.part2
part3.text = ipAddress.part3
part4.text = ipAddress.part4
part1.requestFocus()
}
override fun setEnabled(enabled: Boolean) {
super.setEnabled(enabled)
part1.isEnabled = enabled
part2.isEnabled = enabled
part3.isEnabled = enabled
part4.isEnabled = enabled
}
private inner class IpTextChanged internal constructor(private val textView: TextView) : TextWatcher {
@SuppressLint("WrongConstant")
override fun afterTextChanged(editable: Editable) {
rebuildIpAddress()
ipChangedListener?.onIpChangedListener(ipAddress)
editable.toString().let {
if (it.length == 3 || it == "0") {
textView.focusSearch(View.FOCUS_FORWARD)?.requestFocus()
}
}
}
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
}
}
| apache-2.0 | 7503ae4d0cc9c28b8eeb0a6701d58548 | 34 | 111 | 0.684379 | 4.380117 | false | false | false | false |
android/performance-samples | MicrobenchmarkSample/microbenchmark/src/androidTest/java/com/example/benchmark/RecyclerViewBenchmark.kt | 1 | 4215 | package com.example.benchmark
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.FrameLayout.LayoutParams.MATCH_PARENT
import androidx.benchmark.junit4.BenchmarkRule
import androidx.benchmark.junit4.measureRepeated
import androidx.test.annotation.UiThreadTest
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.example.benchmark.ui.MainActivity
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* RecyclerView benchmark - scrolls a RecyclerView, and measures the time taken to reveal each item
*
* You can use this general approach to benchmark the performance of RecyclerView. Some things to be
* aware of:
*
* - Benchmark one ItemView type at a time. If you have for example section headers, or other types
* of item variation, it's recommended to use fake adapter data with just a single type of item
* at a time.
* - If you want to benchmark TextView performance, use randomized text. Reusing words between items
* (such as in this simple test) will artificially perform better than real world usage, due to
* unrealistic layout cache hit rates.
* - You won't see the effects of RecyclerView prefetching, or Async text layout with this simple
* approach. We'll add more complex RecyclerView examples as time goes on.
*
* This benchmark measures the sum of multiple potentially expensive stages of displaying an item:
* - Attaching an ItemView to RecyclerView
* - Detaching an ItemView (scrolling out of viewport) from RecyclerView
* - onBindViewHolder
* - ItemView layout
*
* It does *not* measure any of the following work:
* - onCreateViewHolder
* - RenderThread and GPU Rendering work
*/
@LargeTest
@RunWith(AndroidJUnit4::class)
class RecyclerViewBenchmark {
class LazyComputedList<T>(
override val size: Int = Int.MAX_VALUE,
private inline val compute: (Int) -> T
) : AbstractList<T>() {
override fun get(index: Int): T = compute(index)
}
@get:Rule
val benchmarkRule = BenchmarkRule()
@get:Rule
val activityRule = ActivityScenarioRule(MainActivity::class.java)
@Before
fun setup() {
activityRule.scenario.onActivity { activity ->
// Set the RecyclerView to have a height of 1 pixel.
// This ensures that only one item can be displayed at once.
activity.recyclerView.layoutParams = FrameLayout.LayoutParams(MATCH_PARENT, 1)
// Initialize the Adapter with fake data.
// (Submit null first so both are synchronous for simplicity)
// 1st ViewHolder will be inflated and displayed by the next onActivity callback
activity.adapter.submitList(null)
activity.adapter.submitList(LazyComputedList { buildRandomParagraph() })
}
}
@Test
fun buildParagraph() {
benchmarkRule.measureRepeated {
// measure cost of generating paragraph - this is overhead in the primary scroll()
// benchmark, but is a very small fraction of the amount of work there.
buildRandomParagraph()
}
}
@UiThreadTest
@Test
fun scroll() {
activityRule.scenario.onActivity { activity ->
val recyclerView = activity.recyclerView
assertTrue("RecyclerView expected to have children", recyclerView.childCount > 0)
assertEquals("RecyclerView must have height = 1", 1, recyclerView.height)
// RecyclerView has children, its items are attached, bound, and have gone through layout.
// Ready to benchmark!
benchmarkRule.measureRepeated {
// Scroll RecyclerView by one item
// this will synchronously execute: attach / detach(old item) / bind / layout
recyclerView.scrollBy(0, recyclerView.getLastChild().height)
}
}
}
}
private fun ViewGroup.getLastChild(): View = getChildAt(childCount - 1)
| apache-2.0 | 81d173bdb4f1d60faf8b94b50950c3a3 | 38.392523 | 102 | 0.704152 | 4.778912 | false | true | false | false |
MarkNKamau/JustJava-Android | core/src/main/java/com/marknjunge/core/data/network/interceptors/ConvertNoContentInterceptor.kt | 1 | 1108 | package com.marknjunge.core.data.network.interceptors
import com.marknjunge.core.data.model.ApiResponse
import com.marknjunge.core.utils.appJsonConfig
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
class ConvertNoContentInterceptor : Interceptor {
private val mediaType = "application/json".toMediaType()
override fun intercept(chain: Interceptor.Chain): Response {
val response = chain.proceed(chain.request())
return if (response.code == 204 || response.body?.contentLength() == 0L) {
val apiResponse = ApiResponse("No content")
val rawBody = appJsonConfig.encodeToString(ApiResponse.serializer(), apiResponse)
Response.Builder()
.code(200)
.protocol(Protocol.HTTP_1_1)
.body(rawBody.toResponseBody(mediaType))
.request(chain.request())
.message("")
.build()
} else {
response
}
}
}
| apache-2.0 | 25853accf81c74ea39b9a388d0012d9e | 32.575758 | 93 | 0.661552 | 4.775862 | false | true | false | false |
java-opengl-labs/ogl-samples | src/main/kotlin/ogl_samples/framework/compiler.kt | 1 | 2587 | package ogl_samples.framework
import org.lwjgl.opengl.GL11.GL_TRUE
import org.lwjgl.opengl.GL20.*
import org.lwjgl.opengl.GL32.GL_GEOMETRY_SHADER
import uno.gln.programName
import java.io.File
import uno.gln.get
/**
* Created by GBarbieri on 07.04.2017.
*/
class Compiler {
val pendingChecks = mutableListOf<Pair<String, Int>>()
fun create(vararg shader: String): Int {
val program = glCreateProgram()
shader.map { create(it) }.forEach { glAttachShader(program, it) }
return program
}
fun create(filename: String): Int {
val path = "data/$filename"
val url = ClassLoader.getSystemResource(path)
val lines = File(url.toURI()).readLines()
var source = ""
lines.forEach {
if (it.startsWith("#include "))
source += parseInclude(path.substringBeforeLast('/'), it.substring("#include ".length).trim())
else
source += it
source += '\n'
}
val name = glCreateShader(filename.substringAfterLast('.').type)
// println(source)
glShaderSource(name, source)
glCompileShader(name)
pendingChecks += filename to name
return name
}
fun parseInclude(root: String, shader: String): String {
if (shader.startsWith('"') && shader.endsWith('"'))
shader.substring(1, shader.length - 1)
val url = ClassLoader.getSystemResource("$root/$shader")
return File(url.toURI()).readText() + "\n"
}
infix fun checkProgram(program: Enum<*>) = checkProgram(programName[program])
infix fun checkProgram(program: IntArray) = checkProgram(program[0])
infix fun checkProgram(program: Int): Boolean {
if (program == 0) return false
val result = glGetProgrami(program, GL_LINK_STATUS)
if (result == GL_TRUE) return true
println(glGetProgramInfoLog(program))
return result == GL_TRUE
}
fun check(): Boolean {
var success = true
pendingChecks.forEach {
val shaderName = it.second
val result = glGetShaderi(shaderName, GL_COMPILE_STATUS)
if (result == GL_TRUE) return@forEach
println(glGetShaderInfoLog(shaderName))
success = success && result == GL_TRUE
}
return success
}
private val String.type
get() = when (this) {
"vert" -> GL_VERTEX_SHADER
"geom" -> GL_GEOMETRY_SHADER
"frag" -> GL_FRAGMENT_SHADER
else -> throw Error()
}
} | mit | acb405cb2e8e7f36b794a26767e1d2ad | 25.958333 | 110 | 0.596444 | 4.414676 | false | false | false | false |
Maccimo/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/impl/storage/SwitchFileBasedIndexStorageAction.kt | 1 | 3122 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.indexing.impl.storage
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.ui.CollectionComboBoxModel
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.popup.list.ComboBoxPopup
import com.intellij.util.indexing.FileBasedIndexTumbler
import com.intellij.util.indexing.IndexingBundle
import com.intellij.util.indexing.storage.FileBasedIndexLayoutProviderBean
import org.jetbrains.annotations.Nls
import java.util.function.Consumer
import javax.swing.ListCellRenderer
import javax.swing.ListModel
class SwitchFileBasedIndexStorageAction : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val allStorages = customIndexStorageDescriptors() + defaultIndexStorageDescriptor()
val activeStorage = allStorages.find { it.bean == FileBasedIndexLayoutSettings.getUsedLayout()}
val popupContext = IndexStorageDescriptorPopupContext(project, allStorages)
ComboBoxPopup(popupContext, activeStorage, Consumer {
restartIndexesWithStorage(it)
}).showInBestPositionFor(e.dataContext)
}
private fun restartIndexesWithStorage(indexStorage: IndexStorageDescriptor) {
val usedLayout = FileBasedIndexLayoutSettings.getUsedLayout()
if (usedLayout != indexStorage.bean) {
val switcher = FileBasedIndexTumbler("Index Storage Switching")
switcher.turnOff()
try {
FileBasedIndexLayoutSettings.setUsedLayout(indexStorage.bean)
}
finally {
switcher.turnOn(null)
}
}
}
}
private data class IndexStorageDescriptor(val presentableName: @Nls String,
val id: String,
val version: Int,
val bean: FileBasedIndexLayoutProviderBean?)
private fun defaultIndexStorageDescriptor(): IndexStorageDescriptor {
return IndexStorageDescriptor(IndexingBundle.message("default.index.storage.presentable.name"),
"default",
0,
null)
}
private fun customIndexStorageDescriptors(): List<IndexStorageDescriptor> =
DefaultIndexStorageLayout.availableLayouts.map {
IndexStorageDescriptor(it.localizedPresentableName, it.id, it.version, it)
}
private class IndexStorageDescriptorPopupContext(private val project: Project,
val indexStorages: List<IndexStorageDescriptor>) : ComboBoxPopup.Context<IndexStorageDescriptor> {
private val model = CollectionComboBoxModel(indexStorages)
override fun getProject(): Project = project
override fun getModel(): ListModel<IndexStorageDescriptor> {
return model
}
override fun getRenderer(): ListCellRenderer<IndexStorageDescriptor> {
return SimpleListCellRenderer.create { label, value, _ -> label.text = value.presentableName }
}
} | apache-2.0 | 8bd3196463317a8702f95ab5b7566e7b | 41.202703 | 137 | 0.738309 | 4.98722 | false | false | false | false |
android/renderscript-intrinsics-replacement-toolkit | test-app/src/main/java/com/google/android/renderscript_test/IntrinsicHistogram.kt | 1 | 6833 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.renderscript_test
import android.graphics.Bitmap
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.Script
import android.renderscript.ScriptIntrinsicHistogram
import android.renderscript.Type
import com.google.android.renderscript.Range2d
/**
* Does a Histogram operation using the RenderScript Intrinsics.
*/
fun intrinsicHistogram(
context: RenderScript,
inputArray: ByteArray,
vectorSize: Int,
sizeX: Int,
sizeY: Int,
restriction: Range2d?
): IntArray {
val element = renderScriptVectorElementForU8(context, vectorSize)
val scriptHistogram = ScriptIntrinsicHistogram.create(context, element)
val builder = Type.Builder(context, element)
builder.setX(sizeX)
builder.setY(sizeY)
val arrayType = builder.create()
val inputAllocation = Allocation.createTyped(context, arrayType)
val outAllocation =
Allocation.createSized(
context,
renderScriptVectorElementForI32(context, vectorSize),
256
)
inputAllocation.copyFrom(inputArray)
scriptHistogram.setOutput(outAllocation)
if (restriction != null) {
val options = Script.LaunchOptions()
options.setX(restriction.startX, restriction.endX)
options.setY(restriction.startY, restriction.endY)
scriptHistogram.forEach(inputAllocation, options)
} else {
scriptHistogram.forEach(inputAllocation)
}
val intrinsicOutArray = IntArray(256 * paddedSize(vectorSize))
outAllocation.copyTo(intrinsicOutArray)
inputAllocation.destroy()
outAllocation.destroy()
arrayType.destroy()
scriptHistogram.destroy()
return intrinsicOutArray
}
fun intrinsicHistogram(
context: RenderScript,
bitmap: Bitmap,
restriction: Range2d?
): IntArray {
val baseElement = renderScriptElementForBitmap(context, bitmap)
val scriptHistogram = ScriptIntrinsicHistogram.create(context, baseElement)
val inputAllocation = Allocation.createFromBitmap(context, bitmap)
inputAllocation.copyFrom(bitmap)
val vectorSize = vectorSizeOfBitmap(bitmap)
val outAllocation =
Allocation.createSized(
context,
renderScriptVectorElementForI32(context, vectorSize),
256
)
scriptHistogram.setOutput(outAllocation)
if (restriction != null) {
val options = Script.LaunchOptions()
options.setX(restriction.startX, restriction.endX)
options.setY(restriction.startY, restriction.endY)
scriptHistogram.forEach(inputAllocation, options)
} else {
scriptHistogram.forEach(inputAllocation)
}
val intrinsicOutArray = IntArray(256 * vectorSize)
outAllocation.copyTo(intrinsicOutArray)
inputAllocation.destroy()
outAllocation.destroy()
scriptHistogram.destroy()
return intrinsicOutArray
}
fun intrinsicHistogramDot(
context: RenderScript,
inputArray: ByteArray,
vectorSize: Int,
sizeX: Int,
sizeY: Int,
coefficients: FloatArray?,
restriction: Range2d?
): IntArray {
val element = renderScriptVectorElementForU8(context, vectorSize)
val scriptHistogram = ScriptIntrinsicHistogram.create(context, element)
val builder = Type.Builder(context, element)
builder.setX(sizeX)
builder.setY(sizeY)
val arrayType = builder.create()
val inputAllocation = Allocation.createTyped(context, arrayType)
val outAllocation =
Allocation.createSized(context, Element.I32(context), 256)
inputAllocation.copyFrom(inputArray)
if (coefficients != null) {
require(coefficients.size == vectorSize) {
"RenderScriptToolkit tests. $vectorSize coefficients are required for histogram. " +
"${coefficients.size} provided."
}
scriptHistogram.setDotCoefficients(
coefficients[0],
if (vectorSize > 1) coefficients[1] else 0f,
if (vectorSize > 2) coefficients[2] else 0f,
if (vectorSize > 3) coefficients[3] else 0f
)
}
scriptHistogram.setOutput(outAllocation)
if (restriction != null) {
val options = Script.LaunchOptions()
options.setX(restriction.startX, restriction.endX)
options.setY(restriction.startY, restriction.endY)
scriptHistogram.forEach_Dot(inputAllocation, options)
} else {
scriptHistogram.forEach_Dot(inputAllocation)
}
val intrinsicOutArray = IntArray(256)
outAllocation.copyTo(intrinsicOutArray)
inputAllocation.destroy()
outAllocation.destroy()
arrayType.destroy()
scriptHistogram.destroy()
return intrinsicOutArray
}
fun intrinsicHistogramDot(
context: RenderScript,
bitmap: Bitmap,
coefficients: FloatArray?,
restriction: Range2d?
): IntArray {
val baseElement = renderScriptElementForBitmap(context, bitmap)
val scriptHistogram = ScriptIntrinsicHistogram.create(context, baseElement)
val inputAllocation = Allocation.createFromBitmap(context, bitmap)
inputAllocation.copyFrom(bitmap)
val outAllocation =
Allocation.createSized(context, Element.I32(context), 256)
if (coefficients != null) {
require(coefficients.size == 4) {
"RenderScriptToolkit tests. Four coefficients are required for histogram. " +
"${coefficients.size} provided."
}
scriptHistogram.setDotCoefficients(
coefficients[0],
coefficients[1],
coefficients[2],
coefficients[3]
)
}
scriptHistogram.setOutput(outAllocation)
if (restriction != null) {
val options = Script.LaunchOptions()
options.setX(restriction.startX, restriction.endX)
options.setY(restriction.startY, restriction.endY)
scriptHistogram.forEach_Dot(inputAllocation, options)
} else {
scriptHistogram.forEach_Dot(inputAllocation)
}
val intrinsicOutArray = IntArray(256)
outAllocation.copyTo(intrinsicOutArray)
inputAllocation.destroy()
outAllocation.destroy()
scriptHistogram.destroy()
return intrinsicOutArray
}
| apache-2.0 | bba3ee7507ab297ca4bf0138ed0f32d8 | 33.862245 | 96 | 0.707888 | 4.632542 | false | false | false | false |
DuncanCasteleyn/DiscordModBot | src/main/kotlin/be/duncanc/discordmodbot/data/entities/VoteEmotes.kt | 1 | 1461 | /*
* Copyright 2018 Duncan Casteleyn
*
* 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 be.duncanc.discordmodbot.data.entities
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table
@Entity
@Table(name = "voting_emotes")
data class VoteEmotes(
@Id
val guildId: Long,
@Column(nullable = false)
val voteYesEmote: Long,
@Column(nullable = false)
val voteNoEmote: Long
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as VoteEmotes
if (guildId != other.guildId) return false
return true
}
override fun hashCode(): Int {
return guildId.hashCode()
}
override fun toString(): String {
return "VoteEmotes(guildId=$guildId, voteYesEmote=$voteYesEmote, voteNoEmote=$voteNoEmote)"
}
}
| apache-2.0 | d378eb291206c6359de84f7025f1b4d2 | 26.055556 | 99 | 0.698836 | 4.13881 | false | false | false | false |
KotlinNLP/SimpleDNN | src/test/kotlin/core/functionalities/updatemethods/RADAMSpec.kt | 1 | 4956 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package core.functionalities.updatemethods
import com.kotlinnlp.simplednn.core.arrays.ParamsArray
import com.kotlinnlp.simplednn.core.functionalities.updatemethods.radam.RADAMMethod
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertTrue
/**
*
*/
class RADAMSpec : Spek({
describe("the RADAM update method") {
context("time step = 1") {
context("update with dense errors") {
context("update") {
val updateHelper = RADAMMethod(stepSize = 0.001, beta1 = 0.9, beta2 = 0.999, epsilon = 1.0e-8)
val updatableArray: ParamsArray = UpdateMethodsUtils.buildParamsArray()
val supportStructure = updateHelper.getSupportStructure(updatableArray)
supportStructure.firstOrderMoments.assignValues(UpdateMethodsUtils.supportArray1())
supportStructure.secondOrderMoments.assignValues(UpdateMethodsUtils.supportArray2())
updateHelper.newBatch()
updateHelper.update(array = updatableArray, errors = UpdateMethodsUtils.buildDenseErrors())
it("should match the expected updated array") {
assertTrue {
updatableArray.values.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.399772, 0.399605, 0.499815, 0.995625, 0.799866)),
tolerance = 1.0e-6)
}
}
}
}
context("update with sparse errors") {
context("update") {
val updateHelper = RADAMMethod(stepSize = 0.001, beta1 = 0.9, beta2 = 0.999, epsilon = 1.0e-8)
val updatableArray: ParamsArray = UpdateMethodsUtils.buildParamsArray()
val supportStructure = updateHelper.getSupportStructure(updatableArray)
supportStructure.firstOrderMoments.assignValues(UpdateMethodsUtils.supportArray1())
supportStructure.secondOrderMoments.assignValues(UpdateMethodsUtils.supportArray2())
updateHelper.newBatch()
updateHelper.update(array = updatableArray, errors = UpdateMethodsUtils.buildSparseErrors())
it("should match the expected updated array") {
assertTrue {
updatableArray.values.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.399801, 0.399605, 0.49983, -269999.0, 0.799851)),
tolerance = 1.0e-6)
}
}
}
}
}
context("time step = 6") {
context("update with dense errors") {
context("update") {
val updateHelper = RADAMMethod(stepSize = 0.001, beta1 = 0.9, beta2 = 0.999, epsilon = 1.0e-8)
val updatableArray: ParamsArray = UpdateMethodsUtils.buildParamsArray()
val supportStructure = updateHelper.getSupportStructure(updatableArray)
supportStructure.firstOrderMoments.assignValues(UpdateMethodsUtils.supportArray1())
supportStructure.secondOrderMoments.assignValues(UpdateMethodsUtils.supportArray2())
repeat(5) { updateHelper.newBatch() }
updateHelper.newBatch()
updateHelper.update(array = updatableArray, errors = UpdateMethodsUtils.buildDenseErrors())
it("should match the expected updated array") {
assertTrue {
updatableArray.values.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.399997, 0.399995, 0.499998, 0.999941, 0.799998)),
tolerance = 1.0e-6)
}
}
}
}
context("update with sparse errors") {
context("update") {
val updateHelper = RADAMMethod(stepSize = 0.001, beta1 = 0.9, beta2 = 0.999, epsilon = 1.0e-8)
val updatableArray: ParamsArray = UpdateMethodsUtils.buildParamsArray()
val supportStructure = updateHelper.getSupportStructure(updatableArray)
supportStructure.firstOrderMoments.assignValues(UpdateMethodsUtils.supportArray1())
supportStructure.secondOrderMoments.assignValues(UpdateMethodsUtils.supportArray2())
repeat(5) { updateHelper.newBatch() }
updateHelper.newBatch()
updateHelper.update(array = updatableArray, errors = UpdateMethodsUtils.buildSparseErrors())
it("should match the expected updated array") {
assertTrue {
updatableArray.values.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.399997, 0.399995, 0.499998, -1486.902368, 0.799998)),
tolerance = 1.0e-6)
}
}
}
}
}
}
})
| mpl-2.0 | 08733fb9000741bc59e0bf3f0296a9f1 | 37.123077 | 113 | 0.654358 | 4.381963 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/mysite/MySiteViewModel.kt | 1 | 69221 | @file:Suppress("DEPRECATION", "MaximumLineLength")
package org.wordpress.android.ui.mysite
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import androidx.annotation.DimenRes
import androidx.annotation.StringRes
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.distinctUntilChanged
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.delay
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode.MAIN
import org.wordpress.android.R
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.model.DynamicCardType
import org.wordpress.android.fluxc.model.MediaModel
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.dashboard.CardModel.PostsCardModel
import org.wordpress.android.fluxc.model.dashboard.CardModel.TodaysStatsCardModel
import org.wordpress.android.fluxc.store.AccountStore
import org.wordpress.android.fluxc.store.PostStore.OnPostUploaded
import org.wordpress.android.fluxc.store.QuickStartStore.Companion.QUICK_START_CHECK_STATS_LABEL
import org.wordpress.android.fluxc.store.QuickStartStore.Companion.QUICK_START_UPLOAD_MEDIA_LABEL
import org.wordpress.android.fluxc.store.QuickStartStore.Companion.QUICK_START_VIEW_SITE_LABEL
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartNewSiteTask
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartTask
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartTaskType
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.PagePostCreationSourcesDetail.STORY_FROM_MY_SITE
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.DashboardCards
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.DomainRegistrationCard
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.QuickStartCard
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Item.InfoItem
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Item.SingleActionCard
import org.wordpress.android.ui.mysite.MySiteCardAndItem.JetpackBadge
import org.wordpress.android.ui.mysite.MySiteCardAndItem.SiteInfoHeaderCard
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Type
import org.wordpress.android.ui.mysite.MySiteCardAndItemBuilderParams.BloggingPromptCardBuilderParams
import org.wordpress.android.ui.mysite.MySiteCardAndItemBuilderParams.DashboardCardsBuilderParams
import org.wordpress.android.ui.mysite.MySiteCardAndItemBuilderParams.DomainRegistrationCardBuilderParams
import org.wordpress.android.ui.mysite.MySiteCardAndItemBuilderParams.InfoItemBuilderParams
import org.wordpress.android.ui.mysite.MySiteCardAndItemBuilderParams.PostCardBuilderParams
import org.wordpress.android.ui.mysite.MySiteCardAndItemBuilderParams.PostCardBuilderParams.PostItemClickParams
import org.wordpress.android.ui.mysite.MySiteCardAndItemBuilderParams.QuickActionsCardBuilderParams
import org.wordpress.android.ui.mysite.MySiteCardAndItemBuilderParams.QuickLinkRibbonBuilderParams
import org.wordpress.android.ui.mysite.MySiteCardAndItemBuilderParams.QuickStartCardBuilderParams
import org.wordpress.android.ui.mysite.MySiteCardAndItemBuilderParams.SiteInfoCardBuilderParams
import org.wordpress.android.ui.mysite.MySiteCardAndItemBuilderParams.SiteItemsBuilderParams
import org.wordpress.android.ui.mysite.MySiteCardAndItemBuilderParams.TodaysStatsCardBuilderParams
import org.wordpress.android.ui.mysite.MySiteUiState.PartialState
import org.wordpress.android.ui.mysite.MySiteUiState.PartialState.BloggingPromptUpdate
import org.wordpress.android.ui.mysite.MySiteUiState.PartialState.CardsUpdate
import org.wordpress.android.ui.mysite.MySiteViewModel.State.NoSites
import org.wordpress.android.ui.mysite.MySiteViewModel.State.SiteSelected
import org.wordpress.android.ui.mysite.MySiteViewModel.TabsUiState.TabUiState
import org.wordpress.android.ui.mysite.SiteDialogModel.AddSiteIconDialogModel
import org.wordpress.android.ui.mysite.SiteDialogModel.ChangeSiteIconDialogModel
import org.wordpress.android.ui.mysite.SiteDialogModel.ShowRemoveNextStepsDialog
import org.wordpress.android.ui.mysite.cards.CardsBuilder
import org.wordpress.android.ui.mysite.cards.DomainRegistrationCardShownTracker
import org.wordpress.android.ui.mysite.cards.dashboard.CardsTracker
import org.wordpress.android.ui.mysite.cards.dashboard.bloggingprompts.BloggingPromptsCardAnalyticsTracker
import org.wordpress.android.ui.mysite.cards.dashboard.posts.PostCardType
import org.wordpress.android.ui.mysite.cards.dashboard.todaysstats.TodaysStatsCardBuilder.Companion.URL_GET_MORE_VIEWS_AND_TRAFFIC
import org.wordpress.android.ui.mysite.cards.quickstart.QuickStartCardBuilder
import org.wordpress.android.ui.mysite.cards.quickstart.QuickStartRepository
import org.wordpress.android.ui.mysite.cards.quickstart.QuickStartRepository.QuickStartCategory
import org.wordpress.android.ui.mysite.cards.quickstart.QuickStartRepository.QuickStartTabStep
import org.wordpress.android.ui.mysite.cards.siteinfo.SiteInfoHeaderCardBuilder
import org.wordpress.android.ui.mysite.dynamiccards.DynamicCardMenuFragment.DynamicCardMenuModel
import org.wordpress.android.ui.mysite.dynamiccards.DynamicCardMenuViewModel.DynamicCardMenuInteraction
import org.wordpress.android.ui.mysite.dynamiccards.DynamicCardsBuilder
import org.wordpress.android.ui.mysite.items.SiteItemsBuilder
import org.wordpress.android.ui.mysite.items.SiteItemsTracker
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction
import org.wordpress.android.ui.mysite.tabs.MySiteTabType
import org.wordpress.android.ui.pages.SnackbarMessageHolder
import org.wordpress.android.ui.photopicker.PhotoPickerActivity
import org.wordpress.android.ui.posts.BasicDialogViewModel.DialogInteraction
import org.wordpress.android.ui.posts.BasicDialogViewModel.DialogInteraction.Dismissed
import org.wordpress.android.ui.posts.BasicDialogViewModel.DialogInteraction.Negative
import org.wordpress.android.ui.posts.BasicDialogViewModel.DialogInteraction.Positive
import org.wordpress.android.ui.prefs.AppPrefsWrapper
import org.wordpress.android.ui.quickstart.QuickStartTracker
import org.wordpress.android.ui.quickstart.QuickStartType.NewSiteQuickStartType
import org.wordpress.android.ui.sitecreation.misc.SiteCreationSource
import org.wordpress.android.ui.utils.ListItemInteraction
import org.wordpress.android.ui.utils.UiString
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.util.BuildConfigWrapper
import org.wordpress.android.util.DisplayUtilsWrapper
import org.wordpress.android.util.FluxCUtilsWrapper
import org.wordpress.android.util.JetpackBrandingUtils
import org.wordpress.android.util.JetpackBrandingUtils.Screen.HOME
import org.wordpress.android.util.MediaUtilsWrapper
import org.wordpress.android.util.NetworkUtilsWrapper
import org.wordpress.android.util.QuickStartUtilsWrapper
import org.wordpress.android.util.SiteUtils
import org.wordpress.android.util.SnackbarSequencer
import org.wordpress.android.util.UriWrapper
import org.wordpress.android.util.WPMediaUtilsWrapper
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
import org.wordpress.android.util.config.BloggingPromptsFeatureConfig
import org.wordpress.android.util.config.LandOnTheEditorFeatureConfig
import org.wordpress.android.util.config.MySiteDashboardTabsFeatureConfig
import org.wordpress.android.util.config.QuickStartDynamicCardsFeatureConfig
import org.wordpress.android.util.filter
import org.wordpress.android.util.getEmailValidationMessage
import org.wordpress.android.util.map
import org.wordpress.android.util.merge
import org.wordpress.android.util.publicdata.AppStatus
import org.wordpress.android.util.publicdata.WordPressPublicData
import org.wordpress.android.viewmodel.ContextProvider
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.ScopedViewModel
import org.wordpress.android.viewmodel.SingleLiveEvent
import java.io.File
import java.util.Date
import javax.inject.Inject
import javax.inject.Named
@Suppress("LargeClass", "LongMethod", "LongParameterList")
class MySiteViewModel @Inject constructor(
private val networkUtilsWrapper: NetworkUtilsWrapper,
@param:Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher,
@param:Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher,
private val analyticsTrackerWrapper: AnalyticsTrackerWrapper,
private val siteItemsBuilder: SiteItemsBuilder,
private val accountStore: AccountStore,
private val selectedSiteRepository: SelectedSiteRepository,
private val wpMediaUtilsWrapper: WPMediaUtilsWrapper,
private val mediaUtilsWrapper: MediaUtilsWrapper,
private val fluxCUtilsWrapper: FluxCUtilsWrapper,
private val contextProvider: ContextProvider,
private val siteIconUploadHandler: SiteIconUploadHandler,
private val siteStoriesHandler: SiteStoriesHandler,
private val displayUtilsWrapper: DisplayUtilsWrapper,
private val quickStartRepository: QuickStartRepository,
private val quickStartCardBuilder: QuickStartCardBuilder,
private val siteInfoHeaderCardBuilder: SiteInfoHeaderCardBuilder,
private val homePageDataLoader: HomePageDataLoader,
private val quickStartDynamicCardsFeatureConfig: QuickStartDynamicCardsFeatureConfig,
private val quickStartUtilsWrapper: QuickStartUtilsWrapper,
private val snackbarSequencer: SnackbarSequencer,
private val cardsBuilder: CardsBuilder,
private val dynamicCardsBuilder: DynamicCardsBuilder,
private val landOnTheEditorFeatureConfig: LandOnTheEditorFeatureConfig,
private val mySiteSourceManager: MySiteSourceManager,
private val cardsTracker: CardsTracker,
private val siteItemsTracker: SiteItemsTracker,
private val domainRegistrationCardShownTracker: DomainRegistrationCardShownTracker,
private val buildConfigWrapper: BuildConfigWrapper,
mySiteDashboardTabsFeatureConfig: MySiteDashboardTabsFeatureConfig,
bloggingPromptsFeatureConfig: BloggingPromptsFeatureConfig,
private val jetpackBrandingUtils: JetpackBrandingUtils,
private val appPrefsWrapper: AppPrefsWrapper,
private val bloggingPromptsCardAnalyticsTracker: BloggingPromptsCardAnalyticsTracker,
private val quickStartTracker: QuickStartTracker,
private val dispatcher: Dispatcher,
private val appStatus: AppStatus,
private val wordPressPublicData: WordPressPublicData
) : ScopedViewModel(mainDispatcher) {
private var isDefaultTabSet: Boolean = false
private val _onSnackbarMessage = MutableLiveData<Event<SnackbarMessageHolder>>()
private val _onTechInputDialogShown = MutableLiveData<Event<TextInputDialogModel>>()
private val _onBasicDialogShown = MutableLiveData<Event<SiteDialogModel>>()
private val _onDynamicCardMenuShown = MutableLiveData<Event<DynamicCardMenuModel>>()
private val _onNavigation = MutableLiveData<Event<SiteNavigationAction>>()
private val _onMediaUpload = MutableLiveData<Event<MediaModel>>()
private val _activeTaskPosition = MutableLiveData<Pair<QuickStartTask, Int>>()
private val _onShare = MutableLiveData<Event<String>>()
private val _onTrackWithTabSource = MutableLiveData<Event<MySiteTrackWithTabSource>>()
private val _selectTab = MutableLiveData<Event<TabNavigation>>()
private val _onAnswerBloggingPrompt = SingleLiveEvent<Event<Pair<SiteModel, PromptID>>>()
private val _onBloggingPromptsLearnMore = SingleLiveEvent<Event<Unit>>()
private val tabsUiState: LiveData<TabsUiState> = quickStartRepository.onQuickStartTabStep
.switchMap { quickStartSiteMenuStep ->
val result = MutableLiveData<TabsUiState>()
/* We want to filter out tabs state livedata update when state is not set in uiModel.
Without this check, tabs state livedata merge with state livedata may return a null state
when building UiModel. */
uiModel.value?.state?.tabsUiState?.let {
result.value = it.copy(tabUiStates = it.update(quickStartSiteMenuStep))
}
result
}
/* Capture and track the site selected event so we can circumvent refreshing sources on resume
as they're already built on site select. */
private var isSiteSelected = false
private val isMySiteDashboardTabsFeatureConfigEnabled = mySiteDashboardTabsFeatureConfig.isEnabled()
private val isBloggingPromptsFeatureConfigEnabled = bloggingPromptsFeatureConfig.isEnabled()
val isMySiteTabsEnabled: Boolean
get() = isMySiteDashboardTabsFeatureConfigEnabled &&
buildConfigWrapper.isMySiteTabsEnabled &&
selectedSiteRepository.getSelectedSite()?.isUsingWpComRestApi ?: true
val orderedTabTypes: List<MySiteTabType>
get() = if (isMySiteTabsEnabled) {
listOf(MySiteTabType.DASHBOARD, MySiteTabType.SITE_MENU)
} else {
listOf(MySiteTabType.ALL)
}
private val defaultTab: MySiteTabType
get() = if (isMySiteTabsEnabled) {
if (appPrefsWrapper.getMySiteInitialScreen(buildConfigWrapper.isJetpackApp) ==
MySiteTabType.SITE_MENU.label) {
MySiteTabType.SITE_MENU
} else {
MySiteTabType.DASHBOARD
}
} else {
MySiteTabType.ALL
}
val onScrollTo: LiveData<Event<Int>> = merge(
_activeTaskPosition.distinctUntilChanged(),
quickStartRepository.activeTask
) { pair, activeTask ->
if (pair != null && activeTask != null && pair.first == activeTask) {
Event(pair.second)
} else {
null
}
}
val onSnackbarMessage = merge(_onSnackbarMessage, siteStoriesHandler.onSnackbar, quickStartRepository.onSnackbar)
val onQuickStartMySitePrompts = quickStartRepository.onQuickStartMySitePrompts
val onTextInputDialogShown = _onTechInputDialogShown as LiveData<Event<TextInputDialogModel>>
val onBasicDialogShown = _onBasicDialogShown as LiveData<Event<SiteDialogModel>>
val onDynamicCardMenuShown = _onDynamicCardMenuShown as LiveData<Event<DynamicCardMenuModel>>
val onNavigation = merge(_onNavigation, siteStoriesHandler.onNavigation)
val onMediaUpload = _onMediaUpload as LiveData<Event<MediaModel>>
val onUploadedItem = siteIconUploadHandler.onUploadedItem
val onShare = _onShare
val onAnswerBloggingPrompt = _onAnswerBloggingPrompt as LiveData<Event<Pair<SiteModel, Int>>>
val onBloggingPromptsLearnMore = _onBloggingPromptsLearnMore as LiveData<Event<Unit>>
val onTrackWithTabSource = _onTrackWithTabSource as LiveData<Event<MySiteTrackWithTabSource>>
val selectTab: LiveData<Event<TabNavigation>> = _selectTab
private var shouldMarkUpdateSiteTitleTaskComplete = false
val state: LiveData<MySiteUiState> =
selectedSiteRepository.siteSelected.switchMap { siteLocalId ->
isSiteSelected = true
resetShownTrackers()
val result = MediatorLiveData<SiteIdToState>()
for (newSource in mySiteSourceManager.build(viewModelScope, siteLocalId)) {
result.addSource(newSource) { partialState ->
if (partialState != null) {
result.value = (result.value ?: SiteIdToState(siteLocalId)).update(partialState)
}
}
}
// We want to filter out the empty state where we have a site ID but site object is missing.
// Without this check there is an emission of a NoSites state even if we have the site
result.filter { it.siteId == null || it.state.site != null }.map { it.state }
}
val uiModel: LiveData<UiModel> = merge(tabsUiState, state) { tabsUiState, mySiteUiState ->
with(requireNotNull(mySiteUiState)) {
val state = if (site != null) {
cardsUpdate?.checkAndShowSnackbarError()
val state = buildSiteSelectedStateAndScroll(
tabsUiState,
site,
showSiteIconProgressBar,
activeTask,
isDomainCreditAvailable,
quickStartCategories,
pinnedDynamicCard,
visibleDynamicCards,
backupAvailable,
scanAvailable,
cardsUpdate,
bloggingPromptsUpdate
)
selectDefaultTabIfNeeded()
trackCardsAndItemsShownIfNeeded(state)
state
} else {
buildNoSiteState()
}
UiModel(currentAvatarUrl.orEmpty(), state)
}
}
private fun CardsUpdate.checkAndShowSnackbarError() {
if (showSnackbarError) {
_onSnackbarMessage
.postValue(Event(SnackbarMessageHolder(UiStringRes(R.string.my_site_dashboard_update_error))))
}
}
init {
dispatcher.register(this)
}
@Suppress("LongParameterList")
private fun buildSiteSelectedStateAndScroll(
tabsUiState: TabsUiState?,
site: SiteModel,
showSiteIconProgressBar: Boolean,
activeTask: QuickStartTask?,
isDomainCreditAvailable: Boolean,
quickStartCategories: List<QuickStartCategory>,
pinnedDynamicCard: DynamicCardType?,
visibleDynamicCards: List<DynamicCardType>,
backupAvailable: Boolean,
scanAvailable: Boolean,
cardsUpdate: CardsUpdate?,
bloggingPromptUpdate: BloggingPromptUpdate?
): SiteSelected {
val siteItems = buildSiteSelectedState(
site,
activeTask,
isDomainCreditAvailable,
quickStartCategories,
pinnedDynamicCard,
visibleDynamicCards,
backupAvailable,
scanAvailable,
cardsUpdate,
bloggingPromptUpdate
)
val siteInfoCardBuilderParams = SiteInfoCardBuilderParams(
site = site,
showSiteIconProgressBar = showSiteIconProgressBar,
titleClick = this::titleClick,
iconClick = this::iconClick,
urlClick = this::urlClick,
switchSiteClick = this::switchSiteClick,
activeTask = activeTask
)
val siteInfo = siteInfoHeaderCardBuilder.buildSiteInfoCard(siteInfoCardBuilderParams)
if (activeTask != null) {
scrollToQuickStartTaskIfNecessary(
activeTask,
getPositionOfQuickStartItem(siteItems, activeTask)
)
}
// It is okay to use !! here because we are explicitly creating the lists
return SiteSelected(
tabsUiState = tabsUiState?.copy(
showTabs = isMySiteTabsEnabled,
tabUiStates = orderedTabTypes.mapToTabUiStates(),
shouldUpdateViewPager = shouldUpdateViewPager()
) ?: createTabsUiState(),
siteInfoToolbarViewParams = getSiteInfoToolbarViewParams(),
siteInfoHeaderState = SiteInfoHeaderState(
hasUpdates = hasSiteHeaderUpdates(siteInfo),
siteInfoHeader = siteInfo
),
cardAndItems = siteItems[MySiteTabType.ALL]!!,
siteMenuCardsAndItems = siteItems[MySiteTabType.SITE_MENU]!!,
dashboardCardsAndItems = siteItems[MySiteTabType.DASHBOARD]!!
)
}
private fun getSiteInfoToolbarViewParams(): SiteInfoToolbarViewParams {
return if (isMySiteTabsEnabled) {
SiteInfoToolbarViewParams(
R.dimen.app_bar_with_site_info_tabs_height,
R.dimen.toolbar_bottom_margin_with_tabs
)
} else {
SiteInfoToolbarViewParams(
R.dimen.app_bar_with_site_info_height,
R.dimen.toolbar_bottom_margin_with_no_tabs
)
}
}
private fun getPositionOfQuickStartItem(
siteItems: Map<MySiteTabType, List<MySiteCardAndItem>>,
activeTask: QuickStartTask
) = if (isMySiteTabsEnabled) {
_selectTab.value?.let { tabEvent ->
val currentTab = orderedTabTypes[tabEvent.peekContent().position]
if (currentTab == MySiteTabType.DASHBOARD && activeTask.showInSiteMenu()) {
(siteItems[MySiteTabType.SITE_MENU] as List<MySiteCardAndItem>)
.indexOfFirst { it.activeQuickStartItem }
} else {
(siteItems[currentTab] as List<MySiteCardAndItem>)
.indexOfFirst { it.activeQuickStartItem }
}
} ?: LIST_INDEX_NO_ACTIVE_QUICK_START_ITEM
} else {
(siteItems[MySiteTabType.ALL] as List<MySiteCardAndItem>)
.indexOfFirst { it.activeQuickStartItem }
}
private fun QuickStartTask.showInSiteMenu() = when (this) {
QuickStartNewSiteTask.ENABLE_POST_SHARING -> true
else -> false
}
@Suppress("LongParameterList")
private fun buildSiteSelectedState(
site: SiteModel,
activeTask: QuickStartTask?,
isDomainCreditAvailable: Boolean,
quickStartCategories: List<QuickStartCategory>,
pinnedDynamicCard: DynamicCardType?,
visibleDynamicCards: List<DynamicCardType>,
backupAvailable: Boolean,
scanAvailable: Boolean,
cardsUpdate: CardsUpdate?,
bloggingPromptUpdate: BloggingPromptUpdate?
): Map<MySiteTabType, List<MySiteCardAndItem>> {
val infoItem = siteItemsBuilder.build(
InfoItemBuilderParams(
isStaleMessagePresent = cardsUpdate?.showStaleMessage ?: false
)
)
val migrationSuccessCard = SingleActionCard(
textResource = R.string.jp_migration_success_card_message,
imageResource = R.drawable.ic_wordpress_blue_32dp,
onActionClick = {
_onNavigation.value = Event(SiteNavigationAction.OpenJetpackMigrationDeleteWP)
}
).takeIf {
val isJetpackApp = buildConfigWrapper.isJetpackApp
val isMigrationCompleted = appPrefsWrapper.isJetpackMigrationCompleted()
val isWordPressInstalled = appStatus.isAppInstalled(wordPressPublicData.currentPackageId())
isJetpackApp && isMigrationCompleted && isWordPressInstalled
}
val cardsResult = cardsBuilder.build(
QuickActionsCardBuilderParams(
siteModel = site,
onQuickActionStatsClick = this::quickActionStatsClick,
onQuickActionPagesClick = this::quickActionPagesClick,
onQuickActionPostsClick = this::quickActionPostsClick,
onQuickActionMediaClick = this::quickActionMediaClick
),
DomainRegistrationCardBuilderParams(
isDomainCreditAvailable = isDomainCreditAvailable,
domainRegistrationClick = this::domainRegistrationClick
),
QuickStartCardBuilderParams(
quickStartCategories = quickStartCategories,
onQuickStartBlockRemoveMenuItemClick = this::onQuickStartBlockRemoveMenuItemClick,
onQuickStartTaskTypeItemClick = this::onQuickStartTaskTypeItemClick
),
DashboardCardsBuilderParams(
showErrorCard = cardsUpdate?.showErrorCard == true,
onErrorRetryClick = this::onDashboardErrorRetry,
todaysStatsCardBuilderParams = TodaysStatsCardBuilderParams(
todaysStatsCard = cardsUpdate?.cards?.firstOrNull { it is TodaysStatsCardModel }
as? TodaysStatsCardModel,
onTodaysStatsCardClick = this::onTodaysStatsCardClick,
onGetMoreViewsClick = this::onGetMoreViewsClick,
onFooterLinkClick = this::onTodaysStatsCardFooterLinkClick
),
postCardBuilderParams = PostCardBuilderParams(
posts = cardsUpdate?.cards?.firstOrNull { it is PostsCardModel } as? PostsCardModel,
onPostItemClick = this::onPostItemClick,
onFooterLinkClick = this::onPostCardFooterLinkClick
),
bloggingPromptCardBuilderParams = BloggingPromptCardBuilderParams(
bloggingPrompt = if (isBloggingPromptsFeatureConfigEnabled) {
bloggingPromptUpdate?.promptModel
} else null,
onShareClick = this::onBloggingPromptShareClick,
onAnswerClick = this::onBloggingPromptAnswerClick,
onSkipClick = this::onBloggingPromptSkipClicked
)
),
QuickLinkRibbonBuilderParams(
siteModel = site,
onPagesClick = this::onQuickLinkRibbonPagesClick,
onPostsClick = this::onQuickLinkRibbonPostsClick,
onMediaClick = this::onQuickLinkRibbonMediaClick,
onStatsClick = this::onQuickLinkRibbonStatsClick,
activeTask = activeTask,
enableFocusPoints = shouldEnableQuickLinkRibbonFocusPoints()
),
isMySiteTabsEnabled
)
val dynamicCards = dynamicCardsBuilder.build(
quickStartCategories,
pinnedDynamicCard,
visibleDynamicCards,
this::onDynamicCardMoreClick,
this::onQuickStartTaskCardClick
)
val siteItems = siteItemsBuilder.build(
SiteItemsBuilderParams(
site = site,
activeTask = activeTask,
backupAvailable = backupAvailable,
scanAvailable = scanAvailable,
enableStatsFocusPoint = shouldEnableSiteItemsFocusPoints(),
enablePagesFocusPoint = shouldEnableSiteItemsFocusPoints(),
enableMediaFocusPoint = shouldEnableSiteItemsFocusPoints(),
onClick = this::onItemClick
)
)
val jetpackBadge = JetpackBadge(
if (jetpackBrandingUtils.shouldShowJetpackPoweredBottomSheet()) {
ListItemInteraction.create(this::onJetpackBadgeClick)
} else {
null
}
).takeIf { jetpackBrandingUtils.shouldShowJetpackBranding() }
return mapOf(
MySiteTabType.ALL to orderForDisplay(
infoItem = infoItem,
migrationSuccessCard = migrationSuccessCard,
cards = cardsResult,
dynamicCards = dynamicCards,
siteItems = siteItems,
jetpackBadge = jetpackBadge
),
MySiteTabType.SITE_MENU to orderForDisplay(
infoItem = infoItem,
migrationSuccessCard = migrationSuccessCard,
cards = cardsResult.filterNot {
getCardTypeExclusionFiltersForTab(MySiteTabType.SITE_MENU).contains(it.type)
},
dynamicCards = if (shouldIncludeDynamicCards(MySiteTabType.SITE_MENU)) {
dynamicCards
} else {
listOf()
},
siteItems = siteItems
),
MySiteTabType.DASHBOARD to orderForDisplay(
infoItem = infoItem,
migrationSuccessCard = migrationSuccessCard,
cards = cardsResult.filterNot {
getCardTypeExclusionFiltersForTab(MySiteTabType.DASHBOARD).contains(it.type)
},
dynamicCards = if (shouldIncludeDynamicCards(MySiteTabType.DASHBOARD)) {
dynamicCards
} else {
listOf()
},
siteItems = listOf(),
jetpackBadge = jetpackBadge
)
)
}
private fun onJetpackBadgeClick() {
jetpackBrandingUtils.trackBadgeTapped(HOME)
_onNavigation.value = Event(SiteNavigationAction.OpenJetpackPoweredBottomSheet)
}
private fun shouldEnableQuickLinkRibbonFocusPoints() = defaultTab == MySiteTabType.DASHBOARD
private fun shouldEnableSiteItemsFocusPoints() = defaultTab != MySiteTabType.DASHBOARD
private fun getCardTypeExclusionFiltersForTab(tabType: MySiteTabType) = when (tabType) {
MySiteTabType.SITE_MENU -> mutableListOf<Type>().apply {
add(Type.DASHBOARD_CARDS)
if (defaultTab == MySiteTabType.DASHBOARD) {
add(Type.QUICK_START_CARD)
}
add(Type.QUICK_LINK_RIBBON)
}
MySiteTabType.DASHBOARD -> mutableListOf<Type>().apply {
if (defaultTab == MySiteTabType.SITE_MENU) {
add(Type.QUICK_START_CARD)
}
add(Type.DOMAIN_REGISTRATION_CARD)
add(Type.QUICK_ACTIONS_CARD)
}
MySiteTabType.ALL -> emptyList()
}
private fun shouldIncludeDynamicCards(tabType: MySiteTabType) = when (tabType) {
MySiteTabType.SITE_MENU -> defaultTab != MySiteTabType.DASHBOARD
MySiteTabType.DASHBOARD -> defaultTab != MySiteTabType.SITE_MENU
MySiteTabType.ALL -> true
}
@Suppress("EmptyFunctionBlock")
private fun onGetMoreViewsClick() {
cardsTracker.trackTodaysStatsCardGetMoreViewsNudgeClicked()
_onNavigation.value = Event(
SiteNavigationAction.OpenTodaysStatsGetMoreViewsExternalUrl(URL_GET_MORE_VIEWS_AND_TRAFFIC)
)
}
private fun onTodaysStatsCardFooterLinkClick() {
cardsTracker.trackTodaysStatsCardFooterLinkClicked()
navigateToTodaysStats()
}
private fun onTodaysStatsCardClick() {
cardsTracker.trackTodaysStatsCardClicked()
navigateToTodaysStats()
}
private fun navigateToTodaysStats() {
val selectedSite = requireNotNull(selectedSiteRepository.getSelectedSite())
_onNavigation.value = Event(SiteNavigationAction.OpenStatsInsights(selectedSite))
}
private fun buildNoSiteState(): NoSites {
// Hide actionable empty view image when screen height is under specified min height.
val shouldShowImage = !buildConfigWrapper.isJetpackApp &&
displayUtilsWrapper.getWindowPixelHeight() >= MIN_DISPLAY_PX_HEIGHT_NO_SITE_IMAGE
return NoSites(
tabsUiState = TabsUiState(showTabs = false, tabUiStates = emptyList()),
siteInfoToolbarViewParams = SiteInfoToolbarViewParams(
appBarHeight = R.dimen.app_bar_with_no_site_info_height,
toolbarBottomMargin = R.dimen.toolbar_bottom_margin_with_no_tabs,
headerVisible = false,
appBarLiftOnScroll = true
),
shouldShowImage = shouldShowImage
)
}
private fun orderForDisplay(
infoItem: InfoItem?,
migrationSuccessCard: SingleActionCard? = null,
cards: List<MySiteCardAndItem>,
dynamicCards: List<MySiteCardAndItem>,
siteItems: List<MySiteCardAndItem>,
jetpackBadge: JetpackBadge? = null
): List<MySiteCardAndItem> {
val indexOfDashboardCards = cards.indexOfFirst { it is DashboardCards }
return mutableListOf<MySiteCardAndItem>().apply {
infoItem?.let { add(infoItem) }
migrationSuccessCard?.let { add(migrationSuccessCard) }
addAll(cards)
if (indexOfDashboardCards == -1) {
addAll(dynamicCards)
} else {
addAll(indexOfDashboardCards, dynamicCards)
}
addAll(siteItems)
jetpackBadge?.let { add(jetpackBadge) }
}.toList()
}
private fun scrollToQuickStartTaskIfNecessary(
quickStartTask: QuickStartTask,
position: Int
) {
if (_activeTaskPosition.value?.first != quickStartTask && isValidQuickStartFocusPosition(
quickStartTask,
position
)) {
_activeTaskPosition.postValue(quickStartTask to position)
}
}
private fun isValidQuickStartFocusPosition(quickStartTask: QuickStartTask, position: Int): Boolean {
return if (position == LIST_INDEX_NO_ACTIVE_QUICK_START_ITEM && isSiteHeaderQuickStartTask(quickStartTask)) {
true
} else {
position >= 0
}
}
private fun isSiteHeaderQuickStartTask(quickStartTask: QuickStartTask): Boolean {
return when (quickStartTask) {
QuickStartNewSiteTask.UPDATE_SITE_TITLE,
QuickStartNewSiteTask.UPLOAD_SITE_ICON,
quickStartRepository.quickStartType.getTaskFromString(QUICK_START_VIEW_SITE_LABEL) -> true
else -> false
}
}
fun onTabChanged(position: Int) {
quickStartRepository.currentTab = orderedTabTypes[position]
findUiStateForTab(orderedTabTypes[position])?.pendingTask?.let { requestTabStepPendingTask(it) }
trackTabChanged(position == orderedTabTypes.indexOf(MySiteTabType.SITE_MENU))
}
private fun requestTabStepPendingTask(pendingTask: QuickStartTask) {
quickStartRepository.clearTabStep()
launch {
delay(LIST_SCROLL_DELAY_MS)
quickStartRepository.setActiveTask(pendingTask)
}
}
@Suppress("ComplexMethod")
private fun onItemClick(action: ListItemAction) {
selectedSiteRepository.getSelectedSite()?.let { selectedSite ->
siteItemsTracker.trackSiteItemClicked(action)
val navigationAction = when (action) {
ListItemAction.ACTIVITY_LOG -> SiteNavigationAction.OpenActivityLog(selectedSite)
ListItemAction.BACKUP -> SiteNavigationAction.OpenBackup(selectedSite)
ListItemAction.SCAN -> SiteNavigationAction.OpenScan(selectedSite)
ListItemAction.PLAN -> {
SiteNavigationAction.OpenPlan(selectedSite)
}
ListItemAction.POSTS -> SiteNavigationAction.OpenPosts(selectedSite)
ListItemAction.PAGES -> {
quickStartRepository.completeTask(QuickStartNewSiteTask.REVIEW_PAGES)
SiteNavigationAction.OpenPages(selectedSite)
}
ListItemAction.ADMIN -> SiteNavigationAction.OpenAdmin(selectedSite)
ListItemAction.PEOPLE -> SiteNavigationAction.OpenPeople(selectedSite)
ListItemAction.SHARING -> {
quickStartRepository.requestNextStepOfTask(QuickStartNewSiteTask.ENABLE_POST_SHARING)
SiteNavigationAction.OpenSharing(selectedSite)
}
ListItemAction.DOMAINS -> SiteNavigationAction.OpenDomains(selectedSite)
ListItemAction.SITE_SETTINGS -> SiteNavigationAction.OpenSiteSettings(selectedSite)
ListItemAction.THEMES -> SiteNavigationAction.OpenThemes(selectedSite)
ListItemAction.PLUGINS -> SiteNavigationAction.OpenPlugins(selectedSite)
ListItemAction.STATS -> {
quickStartRepository.completeTask(
quickStartRepository.quickStartType.getTaskFromString(QUICK_START_CHECK_STATS_LABEL)
)
getStatsNavigationActionForSite(selectedSite)
}
ListItemAction.MEDIA -> {
quickStartRepository.requestNextStepOfTask(
quickStartRepository.quickStartType.getTaskFromString(QUICK_START_UPLOAD_MEDIA_LABEL)
)
SiteNavigationAction.OpenMedia(selectedSite)
}
ListItemAction.COMMENTS -> SiteNavigationAction.OpenUnifiedComments(selectedSite)
ListItemAction.VIEW_SITE -> {
SiteNavigationAction.OpenSite(selectedSite)
}
ListItemAction.JETPACK_SETTINGS -> SiteNavigationAction.OpenJetpackSettings(selectedSite)
}
_onNavigation.postValue(Event(navigationAction))
} ?: _onSnackbarMessage.postValue(Event(SnackbarMessageHolder(UiStringRes(R.string.site_cannot_be_loaded))))
}
private fun onDynamicCardMoreClick(model: DynamicCardMenuModel) {
_onDynamicCardMenuShown.postValue(Event(model))
}
private fun onQuickStartBlockRemoveMenuItemClick() {
_onBasicDialogShown.value = Event(ShowRemoveNextStepsDialog)
}
private fun onQuickStartTaskTypeItemClick(type: QuickStartTaskType) {
clearActiveQuickStartTask()
if (defaultTab == MySiteTabType.DASHBOARD) {
cardsTracker.trackQuickStartCardItemClicked(type)
} else {
quickStartTracker.track(Stat.QUICK_START_TAPPED, mapOf(TYPE to type.toString()))
}
_onNavigation.value = Event(
SiteNavigationAction.OpenQuickStartFullScreenDialog(type, quickStartCardBuilder.getTitle(type))
)
}
fun onQuickStartTaskCardClick(task: QuickStartTask) {
quickStartRepository.setActiveTask(task)
}
fun onQuickStartFullScreenDialogDismiss() {
mySiteSourceManager.refreshQuickStart()
}
private fun titleClick() {
val selectedSite = requireNotNull(selectedSiteRepository.getSelectedSite())
if (!networkUtilsWrapper.isNetworkAvailable()) {
_onSnackbarMessage.value = Event(SnackbarMessageHolder(UiStringRes(R.string.error_network_connection)))
} else if (!SiteUtils.isAccessedViaWPComRest(selectedSite) || !selectedSite.hasCapabilityManageOptions) {
_onSnackbarMessage.value = Event(
SnackbarMessageHolder(UiStringRes(R.string.my_site_title_changer_dialog_not_allowed_hint))
)
} else {
_onTechInputDialogShown.value = Event(
TextInputDialogModel(
callbackId = SITE_NAME_CHANGE_CALLBACK_ID,
title = R.string.my_site_title_changer_dialog_title,
initialText = selectedSite.name,
hint = R.string.my_site_title_changer_dialog_hint,
isMultiline = false,
isInputEnabled = true
)
)
}
}
private fun iconClick() {
val selectedSite = requireNotNull(selectedSiteRepository.getSelectedSite())
analyticsTrackerWrapper.track(Stat.MY_SITE_ICON_TAPPED)
val hasIcon = selectedSite.iconUrl != null
if (selectedSite.hasCapabilityManageOptions && selectedSite.hasCapabilityUploadFiles) {
if (hasIcon) {
_onBasicDialogShown.value = Event(ChangeSiteIconDialogModel)
} else {
_onBasicDialogShown.value = Event(AddSiteIconDialogModel)
}
} else {
val message = when {
!selectedSite.isUsingWpComRestApi -> {
R.string.my_site_icon_dialog_change_requires_jetpack_message
}
hasIcon -> {
R.string.my_site_icon_dialog_change_requires_permission_message
}
else -> {
R.string.my_site_icon_dialog_add_requires_permission_message
}
}
_onSnackbarMessage.value = Event(SnackbarMessageHolder(UiStringRes(message)))
}
}
private fun urlClick() {
val selectedSite = requireNotNull(selectedSiteRepository.getSelectedSite())
quickStartRepository.completeTask(
quickStartRepository.quickStartType.getTaskFromString(QUICK_START_VIEW_SITE_LABEL)
)
_onNavigation.value = Event(SiteNavigationAction.OpenSite(selectedSite))
}
private fun switchSiteClick() {
val selectedSite = requireNotNull(selectedSiteRepository.getSelectedSite())
trackWithTabSourceIfNeeded(Stat.MY_SITE_SITE_SWITCHER_TAPPED)
_onNavigation.value = Event(SiteNavigationAction.OpenSitePicker(selectedSite))
}
private fun quickActionStatsClick() {
val selectedSite = requireNotNull(selectedSiteRepository.getSelectedSite())
trackWithTabSourceIfNeeded(Stat.QUICK_ACTION_STATS_TAPPED)
quickStartRepository.completeTask(
quickStartRepository.quickStartType.getTaskFromString(QUICK_START_CHECK_STATS_LABEL)
)
_onNavigation.value = Event(getStatsNavigationActionForSite(selectedSite))
}
private fun quickActionPagesClick() {
val selectedSite = requireNotNull(selectedSiteRepository.getSelectedSite())
trackWithTabSourceIfNeeded(Stat.QUICK_ACTION_PAGES_TAPPED)
quickStartRepository.completeTask(QuickStartNewSiteTask.REVIEW_PAGES)
_onNavigation.value = Event(SiteNavigationAction.OpenPages(selectedSite))
}
private fun quickActionPostsClick() {
val selectedSite = requireNotNull(selectedSiteRepository.getSelectedSite())
trackWithTabSourceIfNeeded(Stat.QUICK_ACTION_POSTS_TAPPED)
_onNavigation.value = Event(SiteNavigationAction.OpenPosts(selectedSite))
}
private fun quickActionMediaClick() {
val selectedSite = requireNotNull(selectedSiteRepository.getSelectedSite())
trackWithTabSourceIfNeeded(Stat.QUICK_ACTION_MEDIA_TAPPED)
quickStartRepository.requestNextStepOfTask(
quickStartRepository.quickStartType.getTaskFromString(QUICK_START_UPLOAD_MEDIA_LABEL)
)
_onNavigation.value = Event(SiteNavigationAction.OpenMedia(selectedSite))
}
private fun onQuickLinkRibbonStatsClick() {
val selectedSite = requireNotNull(selectedSiteRepository.getSelectedSite())
trackWithTabSourceIfNeeded(Stat.QUICK_LINK_RIBBON_STATS_TAPPED)
quickStartRepository.completeTask(
quickStartRepository.quickStartType.getTaskFromString(QUICK_START_CHECK_STATS_LABEL)
)
_onNavigation.value = Event(getStatsNavigationActionForSite(selectedSite))
}
private fun onQuickLinkRibbonPagesClick() {
val selectedSite = requireNotNull(selectedSiteRepository.getSelectedSite())
trackWithTabSourceIfNeeded(Stat.QUICK_LINK_RIBBON_PAGES_TAPPED)
quickStartRepository.completeTask(QuickStartNewSiteTask.REVIEW_PAGES)
_onNavigation.value = Event(SiteNavigationAction.OpenPages(selectedSite))
}
private fun onQuickLinkRibbonPostsClick() {
val selectedSite = requireNotNull(selectedSiteRepository.getSelectedSite())
trackWithTabSourceIfNeeded(Stat.QUICK_LINK_RIBBON_POSTS_TAPPED)
_onNavigation.value = Event(SiteNavigationAction.OpenPosts(selectedSite))
}
private fun onQuickLinkRibbonMediaClick() {
val selectedSite = requireNotNull(selectedSiteRepository.getSelectedSite())
trackWithTabSourceIfNeeded(Stat.QUICK_LINK_RIBBON_MEDIA_TAPPED)
quickStartRepository.requestNextStepOfTask(
quickStartRepository.quickStartType.getTaskFromString(QUICK_START_UPLOAD_MEDIA_LABEL)
)
_onNavigation.value = Event(SiteNavigationAction.OpenMedia(selectedSite))
}
private fun domainRegistrationClick() {
val selectedSite = requireNotNull(selectedSiteRepository.getSelectedSite())
analyticsTrackerWrapper.track(Stat.DOMAIN_CREDIT_REDEMPTION_TAPPED, selectedSite)
_onNavigation.value = Event(SiteNavigationAction.OpenDomainRegistration(selectedSite))
}
fun refresh(isPullToRefresh: Boolean = false) {
if (isPullToRefresh) trackWithTabSourceIfNeeded(Stat.MY_SITE_PULL_TO_REFRESH)
mySiteSourceManager.refresh()
}
fun onResume() {
mySiteSourceManager.onResume(isSiteSelected)
isSiteSelected = false
checkAndShowQuickStartNotice()
}
fun clearActiveQuickStartTask() {
quickStartRepository.clearActiveTask()
}
fun checkAndShowQuickStartNotice() {
quickStartRepository.checkAndShowQuickStartNotice()
}
fun dismissQuickStartNotice() {
if (quickStartRepository.isQuickStartNoticeShown) snackbarSequencer.dismissLastSnackbar()
}
fun onSiteNameChosen(input: String) {
if (!networkUtilsWrapper.isNetworkAvailable()) {
_onSnackbarMessage.postValue(
Event(SnackbarMessageHolder(UiStringRes(R.string.error_update_site_title_network)))
)
} else {
selectedSiteRepository.updateTitle(input)
}
}
fun onSiteNameChooserDismissed() {
// This callback is called even when the dialog interaction is positive,
// otherwise we would need to call 'completeTask' on 'onSiteNameChosen' as well.
quickStartRepository.completeTask(QuickStartNewSiteTask.UPDATE_SITE_TITLE)
quickStartRepository.checkAndShowQuickStartNotice()
}
fun onDialogInteraction(interaction: DialogInteraction) {
when (interaction) {
is Positive -> when (interaction.tag) {
TAG_ADD_SITE_ICON_DIALOG, TAG_CHANGE_SITE_ICON_DIALOG -> {
quickStartRepository.completeTask(QuickStartNewSiteTask.UPLOAD_SITE_ICON)
_onNavigation.postValue(
Event(
SiteNavigationAction.OpenMediaPicker(
requireNotNull(selectedSiteRepository.getSelectedSite())
)
)
)
}
TAG_REMOVE_NEXT_STEPS_DIALOG -> onRemoveNextStepsDialogPositiveButtonClicked()
}
is Negative -> when (interaction.tag) {
TAG_ADD_SITE_ICON_DIALOG -> {
quickStartRepository.completeTask(QuickStartNewSiteTask.UPLOAD_SITE_ICON)
quickStartRepository.checkAndShowQuickStartNotice()
}
TAG_CHANGE_SITE_ICON_DIALOG -> {
analyticsTrackerWrapper.track(Stat.MY_SITE_ICON_REMOVED)
quickStartRepository.completeTask(QuickStartNewSiteTask.UPLOAD_SITE_ICON)
quickStartRepository.checkAndShowQuickStartNotice()
selectedSiteRepository.updateSiteIconMediaId(0, true)
}
TAG_REMOVE_NEXT_STEPS_DIALOG -> onRemoveNextStepsDialogNegativeButtonClicked()
}
is Dismissed -> when (interaction.tag) {
TAG_ADD_SITE_ICON_DIALOG, TAG_CHANGE_SITE_ICON_DIALOG -> {
quickStartRepository.completeTask(QuickStartNewSiteTask.UPLOAD_SITE_ICON)
quickStartRepository.checkAndShowQuickStartNotice()
}
}
}
}
private fun onRemoveNextStepsDialogPositiveButtonClicked() {
quickStartTracker.track(Stat.QUICK_START_REMOVE_DIALOG_POSITIVE_TAPPED)
quickStartRepository.skipQuickStart()
refresh()
clearActiveQuickStartTask()
}
private fun onRemoveNextStepsDialogNegativeButtonClicked() {
quickStartTracker.track(Stat.QUICK_START_REMOVE_DIALOG_NEGATIVE_TAPPED)
}
@Suppress("DEPRECATION")
fun handleTakenSiteIcon(iconUrl: String?, source: PhotoPickerActivity.PhotoPickerMediaSource?) {
val stat = if (source == PhotoPickerActivity.PhotoPickerMediaSource.ANDROID_CAMERA) {
Stat.MY_SITE_ICON_SHOT_NEW
} else {
Stat.MY_SITE_ICON_GALLERY_PICKED
}
analyticsTrackerWrapper.track(stat)
val imageUri = Uri.parse(iconUrl)?.let { UriWrapper(it) }
if (imageUri != null) {
launch(bgDispatcher) {
val fetchMedia = wpMediaUtilsWrapper.fetchMediaToUriWrapper(imageUri)
if (fetchMedia != null) {
_onNavigation.postValue(Event(SiteNavigationAction.OpenCropActivity(fetchMedia)))
}
}
}
}
fun handleSelectedSiteIcon(mediaId: Long) {
selectedSiteRepository.updateSiteIconMediaId(mediaId.toInt(), true)
}
fun handleCropResult(croppedUri: Uri?, success: Boolean) {
if (success && croppedUri != null) {
analyticsTrackerWrapper.track(Stat.MY_SITE_ICON_CROPPED)
selectedSiteRepository.showSiteIconProgressBar(true)
launch(bgDispatcher) {
wpMediaUtilsWrapper.fetchMediaToUriWrapper(UriWrapper(croppedUri))?.let { fetchMedia ->
mediaUtilsWrapper.getRealPathFromURI(fetchMedia.uri)
}?.let {
startSiteIconUpload(it)
}
}
} else {
_onSnackbarMessage.postValue(Event(SnackbarMessageHolder(UiStringRes(R.string.error_cropping_image))))
}
}
fun handleSuccessfulLoginResult() {
selectedSiteRepository.getSelectedSite()?.let { site ->
_onNavigation.value = Event(
SiteNavigationAction.OpenStats(site)
)
}
}
fun handleSuccessfulDomainRegistrationResult(email: String?) {
analyticsTrackerWrapper.track(Stat.DOMAIN_CREDIT_REDEMPTION_SUCCESS)
_onSnackbarMessage.postValue(Event(SnackbarMessageHolder(getEmailValidationMessage(email))))
}
@Suppress("ReturnCount")
private fun startSiteIconUpload(filePath: String) {
if (TextUtils.isEmpty(filePath)) {
_onSnackbarMessage.postValue(Event(SnackbarMessageHolder(UiStringRes(R.string.error_locating_image))))
return
}
val file = File(filePath)
if (!file.exists()) {
_onSnackbarMessage.postValue(Event(SnackbarMessageHolder(UiStringRes(R.string.file_error_create))))
return
}
val selectedSite = selectedSiteRepository.getSelectedSite()
if (selectedSite != null) {
val media = buildMediaModel(file, selectedSite)
if (media == null) {
_onSnackbarMessage.postValue(Event(SnackbarMessageHolder(UiStringRes(R.string.file_not_found))))
return
}
_onMediaUpload.postValue(Event(media))
} else {
_onSnackbarMessage.postValue(Event(SnackbarMessageHolder(UiStringRes(R.string.error_generic))))
}
}
private fun buildMediaModel(file: File, site: SiteModel): MediaModel? {
val uri = Uri.Builder().path(file.path).build()
val mimeType = contextProvider.getContext().contentResolver.getType(uri)
return fluxCUtilsWrapper.mediaModelFromLocalUri(uri, mimeType, site.id)
}
private fun getStatsNavigationActionForSite(site: SiteModel) = when {
// If the user is not logged in and the site is already connected to Jetpack, ask to login.
!accountStore.hasAccessToken() && site.isJetpackConnected -> SiteNavigationAction.StartWPComLoginForJetpackStats
// If it's a WordPress.com or Jetpack site, show the Stats screen.
site.isWPCom || site.isJetpackInstalled && site.isJetpackConnected -> SiteNavigationAction.OpenStats(site)
// If it's a self-hosted site, ask to connect to Jetpack.
else -> SiteNavigationAction.ConnectJetpackForStats(site)
}
fun onAvatarPressed() {
_onNavigation.value = Event(SiteNavigationAction.OpenMeScreen)
}
fun onAddSitePressed() {
_onNavigation.value = Event(
SiteNavigationAction.AddNewSite(
accountStore.hasAccessToken(),
SiteCreationSource.MY_SITE_NO_SITES
)
)
analyticsTrackerWrapper.track(Stat.MY_SITE_NO_SITES_VIEW_ACTION_TAPPED)
}
override fun onCleared() {
siteIconUploadHandler.clear()
siteStoriesHandler.clear()
quickStartRepository.clear()
mySiteSourceManager.clear()
dispatcher.unregister(this)
super.onCleared()
}
fun handleStoriesPhotoPickerResult(data: Intent) {
selectedSiteRepository.getSelectedSite()?.let {
siteStoriesHandler.handleStoriesResult(it, data, STORY_FROM_MY_SITE)
}
}
fun onCreateSiteResult() {
isDefaultTabSet = false
selectDefaultTabIfNeeded()
}
fun onSitePicked() {
selectedSiteRepository.getSelectedSite()?.let {
val siteLocalId = it.id.toLong()
val lastSelectedQuickStartType = appPrefsWrapper.getLastSelectedQuickStartTypeForSite(siteLocalId)
quickStartRepository.checkAndSetQuickStartType(lastSelectedQuickStartType == NewSiteQuickStartType)
}
mySiteSourceManager.refreshQuickStart()
}
fun performFirstStepAfterSiteCreation(
siteLocalId: Int,
isSiteTitleTaskCompleted: Boolean,
isNewSite: Boolean
) {
if (landOnTheEditorFeatureConfig.isEnabled()) {
checkAndStartLandOnTheEditor(isNewSite)
} else {
checkAndStartQuickStart(siteLocalId, isSiteTitleTaskCompleted, isNewSite)
}
}
private fun checkAndStartLandOnTheEditor(isNewSite: Boolean) {
selectedSiteRepository.getSelectedSite()?.let { selectedSite ->
launch(bgDispatcher) {
homePageDataLoader.loadHomepage(selectedSite)?.pageId?.let { localHomepageId ->
val landOnTheEditorAction = SiteNavigationAction
.OpenHomepage(selectedSite, localHomepageId, isNewSite)
_onNavigation.postValue(Event(landOnTheEditorAction))
analyticsTrackerWrapper.track(Stat.LANDING_EDITOR_SHOWN)
}
}
}
}
fun checkAndStartQuickStart(
siteLocalId: Int,
isSiteTitleTaskCompleted: Boolean,
isNewSite: Boolean
) {
quickStartRepository.checkAndSetQuickStartType(isNewSite = isNewSite)
if (quickStartDynamicCardsFeatureConfig.isEnabled()) {
startQuickStart(siteLocalId, isSiteTitleTaskCompleted)
} else {
shouldMarkUpdateSiteTitleTaskComplete = isSiteTitleTaskCompleted
showQuickStartDialog(selectedSiteRepository.getSelectedSite())
}
}
private fun startQuickStart(siteLocalId: Int, isSiteTitleTaskCompleted: Boolean) {
if (siteLocalId != SelectedSiteRepository.UNAVAILABLE) {
quickStartUtilsWrapper
.startQuickStart(
siteLocalId,
isSiteTitleTaskCompleted,
quickStartRepository.quickStartType,
quickStartTracker
)
mySiteSourceManager.refreshQuickStart()
}
}
fun onQuickStartMenuInteraction(interaction: DynamicCardMenuInteraction) {
launch { mySiteSourceManager.onQuickStartMenuInteraction(interaction) }
}
private fun showQuickStartDialog(siteModel: SiteModel?) {
if (siteModel != null && quickStartUtilsWrapper.isQuickStartAvailableForTheSite(siteModel)) {
_onNavigation.postValue(
Event(
SiteNavigationAction.ShowQuickStartDialog(
R.string.quick_start_dialog_need_help_manage_site_title,
R.string.quick_start_dialog_need_help_manage_site_message,
R.string.quick_start_dialog_need_help_manage_site_button_positive,
R.string.quick_start_dialog_need_help_button_negative
)
)
)
}
}
fun startQuickStart() {
quickStartTracker.track(Stat.QUICK_START_REQUEST_DIALOG_POSITIVE_TAPPED)
startQuickStart(selectedSiteRepository.getSelectedSiteLocalId(), shouldMarkUpdateSiteTitleTaskComplete)
shouldMarkUpdateSiteTitleTaskComplete = false
}
fun ignoreQuickStart() {
shouldMarkUpdateSiteTitleTaskComplete = false
quickStartTracker.track(Stat.QUICK_START_REQUEST_DIALOG_NEGATIVE_TAPPED)
}
private fun onPostItemClick(params: PostItemClickParams) {
selectedSiteRepository.getSelectedSite()?.let { site ->
cardsTracker.trackPostItemClicked(params.postCardType)
when (params.postCardType) {
PostCardType.CREATE_FIRST, PostCardType.CREATE_NEXT -> _onNavigation.value =
Event(SiteNavigationAction.OpenEditorToCreateNewPost(site))
PostCardType.DRAFT -> _onNavigation.value =
Event(SiteNavigationAction.EditDraftPost(site, params.postId))
PostCardType.SCHEDULED -> _onNavigation.value =
Event(SiteNavigationAction.EditScheduledPost(site, params.postId))
}
}
}
private fun onDashboardErrorRetry() {
mySiteSourceManager.refresh()
}
private fun onPostCardFooterLinkClick(postCardType: PostCardType) {
selectedSiteRepository.getSelectedSite()?.let { site ->
cardsTracker.trackPostCardFooterLinkClicked(postCardType)
_onNavigation.value = when (postCardType) {
PostCardType.CREATE_FIRST, PostCardType.CREATE_NEXT ->
Event(SiteNavigationAction.OpenEditorToCreateNewPost(site))
PostCardType.DRAFT -> Event(SiteNavigationAction.OpenDraftsPosts(site))
PostCardType.SCHEDULED -> Event(SiteNavigationAction.OpenScheduledPosts(site))
}
}
}
private fun onBloggingPromptShareClick(message: String) {
onShare.postValue(Event(message))
}
private fun onBloggingPromptAnswerClick(promptId: Int) {
bloggingPromptsCardAnalyticsTracker.trackMySiteCardAnswerPromptClicked()
val selectedSite = requireNotNull(selectedSiteRepository.getSelectedSite())
_onAnswerBloggingPrompt.postValue(Event(Pair(selectedSite, promptId)))
}
private fun onBloggingPromptSkipClicked() {
selectedSiteRepository.getSelectedSite()?.let { site ->
val siteId = site.localId().value
appPrefsWrapper.setSkippedPromptDay(Date(), siteId)
mySiteSourceManager.refreshBloggingPrompts(true)
val snackbar = SnackbarMessageHolder(
message = UiStringRes(R.string.my_site_blogging_prompt_card_skipped_snackbar),
buttonTitle = UiStringRes(R.string.undo),
buttonAction = {
appPrefsWrapper.setSkippedPromptDay(null, siteId)
mySiteSourceManager.refreshBloggingPrompts(true)
},
isImportant = true
)
_onSnackbarMessage.postValue(Event(snackbar))
}
}
fun isRefreshing() = mySiteSourceManager.isRefreshing()
fun setActionableEmptyViewGone(isVisible: Boolean, setGone: () -> Unit) {
if (isVisible) analyticsTrackerWrapper.track(Stat.MY_SITE_NO_SITES_VIEW_HIDDEN)
setGone()
}
fun setActionableEmptyViewVisible(isVisible: Boolean, setVisible: () -> Unit) {
if (!isVisible) analyticsTrackerWrapper.track(Stat.MY_SITE_NO_SITES_VIEW_DISPLAYED)
setVisible()
}
fun trackWithTabSource(event: MySiteTrackWithTabSource) {
if (event.currentTab == MySiteTabType.ALL) {
analyticsTrackerWrapper.track(event.stat, event.properties ?: emptyMap())
} else {
val props: MutableMap<String, Any> = mutableMapOf(event.key to event.currentTab.trackingLabel)
if (!event.properties.isNullOrEmpty()) {
props.putAll(event.properties)
}
analyticsTrackerWrapper.track(event.stat, props)
}
}
fun onBloggingPromptsLearnMoreClicked() {
_onBloggingPromptsLearnMore.postValue(Event(Unit))
}
private fun trackWithTabSourceIfNeeded(stat: Stat, properties: HashMap<String, *>? = null) {
if (isMySiteDashboardTabsFeatureConfigEnabled) {
_onTrackWithTabSource.postValue(Event(MySiteTrackWithTabSource(stat, properties)))
} else {
analyticsTrackerWrapper.track(stat, properties ?: emptyMap())
}
}
@Suppress("NestedBlockDepth")
private fun selectDefaultTabIfNeeded() {
if (!isMySiteTabsEnabled) return
val index = orderedTabTypes.indexOf(defaultTab)
if (index != -1) {
if (isDefaultTabSet) {
// This logic checks if the current default tab is the same as the tab
// set as initial screen, if yes then return
_selectTab.value?.let { tab ->
val currentDefaultTab = tab.peekContent().position
if (currentDefaultTab == index) return
}
}
quickStartRepository.quickStartTaskOriginTab = orderedTabTypes[index]
_selectTab.postValue(Event(TabNavigation(index, smoothAnimation = false)))
isDefaultTabSet = true
}
}
private fun trackCardsAndItemsShownIfNeeded(siteSelected: SiteSelected) {
siteSelected.cardAndItems.filterIsInstance<DomainRegistrationCard>()
.forEach { domainRegistrationCardShownTracker.trackShown(it.type) }
siteSelected.cardAndItems.filterIsInstance<DashboardCards>().forEach { cardsTracker.trackShown(it) }
siteSelected.cardAndItems.filterIsInstance<QuickStartCard>()
.firstOrNull()?.let { quickStartTracker.trackShown(it.type, defaultTab) }
siteSelected.dashboardCardsAndItems.filterIsInstance<QuickStartCard>()
.firstOrNull()?.let { cardsTracker.trackQuickStartCardShown(quickStartRepository.quickStartType) }
}
private fun resetShownTrackers() {
domainRegistrationCardShownTracker.resetShown()
cardsTracker.resetShown()
quickStartTracker.resetShown()
}
private fun trackTabChanged(isSiteMenu: Boolean) {
if (isSiteMenu) {
analyticsTrackerWrapper.track(
Stat.MY_SITE_TAB_TAPPED,
mapOf(MY_SITE_TAB to MySiteTabType.SITE_MENU.trackingLabel)
)
analyticsTrackerWrapper.track(Stat.MY_SITE_SITE_MENU_SHOWN)
} else {
analyticsTrackerWrapper.track(
Stat.MY_SITE_TAB_TAPPED,
mapOf(MY_SITE_TAB to MySiteTabType.DASHBOARD.trackingLabel)
)
analyticsTrackerWrapper.track(Stat.MY_SITE_DASHBOARD_SHOWN)
}
}
private fun findUiStateForTab(tabType: MySiteTabType) =
tabsUiState.value?.tabUiStates?.firstOrNull { it.tabType == tabType }
private fun createTabsUiState() = TabsUiState(
showTabs = isMySiteTabsEnabled,
tabUiStates = orderedTabTypes.mapToTabUiStates(),
shouldUpdateViewPager = shouldUpdateViewPager()
)
private fun List<MySiteTabType>.mapToTabUiStates() = map {
TabUiState(
label = UiStringRes(it.stringResId),
tabType = it,
showQuickStartFocusPoint = findUiStateForTab(it)?.showQuickStartFocusPoint ?: false
)
}
private fun shouldUpdateViewPager() = uiModel.value?.state?.tabsUiState?.tabUiStates?.size != orderedTabTypes.size
private fun hasSiteHeaderUpdates(nextSiteInfoHeaderCard: SiteInfoHeaderCard): Boolean {
return !((uiModel.value?.state as? SiteSelected)?.siteInfoHeaderState?.siteInfoHeader?.equals(
nextSiteInfoHeaderCard
) ?: false)
}
// FluxC events
@Subscribe(threadMode = MAIN)
fun onPostUploaded(event: OnPostUploaded) {
if (!event.isError) {
event.post?.let {
if (event.post.answeredPromptId > 0 && event.isFirstTimePublish) {
mySiteSourceManager.refreshBloggingPrompts(true)
}
}
}
}
data class UiModel(
val accountAvatarUrl: String,
val state: State
)
sealed class State {
abstract val tabsUiState: TabsUiState
abstract val siteInfoToolbarViewParams: SiteInfoToolbarViewParams
data class SiteSelected(
override val tabsUiState: TabsUiState,
override val siteInfoToolbarViewParams: SiteInfoToolbarViewParams,
val siteInfoHeaderState: SiteInfoHeaderState,
val cardAndItems: List<MySiteCardAndItem>,
val siteMenuCardsAndItems: List<MySiteCardAndItem>,
val dashboardCardsAndItems: List<MySiteCardAndItem>
) : State()
data class NoSites(
override val tabsUiState: TabsUiState,
override val siteInfoToolbarViewParams: SiteInfoToolbarViewParams,
val shouldShowImage: Boolean
) : State()
}
data class SiteInfoHeaderState(
val hasUpdates: Boolean,
val siteInfoHeader: SiteInfoHeaderCard
)
data class TabsUiState(
val showTabs: Boolean = false,
val tabUiStates: List<TabUiState>,
val shouldUpdateViewPager: Boolean = false
) {
data class TabUiState(
val label: UiString,
val tabType: MySiteTabType,
val showQuickStartFocusPoint: Boolean = false,
val pendingTask: QuickStartTask? = null
)
fun update(quickStartTabStep: QuickStartTabStep?) = tabUiStates.map { tabUiState ->
tabUiState.copy(
showQuickStartFocusPoint = quickStartTabStep?.mySiteTabType == tabUiState.tabType &&
quickStartTabStep.isStarted,
pendingTask = quickStartTabStep?.task
)
}
}
data class SiteInfoToolbarViewParams(
@DimenRes val appBarHeight: Int,
@DimenRes val toolbarBottomMargin: Int,
val headerVisible: Boolean = true,
val appBarLiftOnScroll: Boolean = false
)
data class TabNavigation(val position: Int, val smoothAnimation: Boolean)
data class TextInputDialogModel(
val callbackId: Int = SITE_NAME_CHANGE_CALLBACK_ID,
@StringRes val title: Int,
val initialText: String,
@StringRes val hint: Int,
val isMultiline: Boolean,
val isInputEnabled: Boolean
)
private data class SiteIdToState(val siteId: Int?, val state: MySiteUiState = MySiteUiState()) {
fun update(partialState: PartialState): SiteIdToState {
return this.copy(state = state.update(partialState))
}
}
data class MySiteTrackWithTabSource(
val stat: Stat,
val properties: HashMap<String, *>? = null,
val key: String = TAB_SOURCE,
val currentTab: MySiteTabType = MySiteTabType.ALL
)
companion object {
private const val MIN_DISPLAY_PX_HEIGHT_NO_SITE_IMAGE = 600
private const val LIST_INDEX_NO_ACTIVE_QUICK_START_ITEM = -1
private const val TYPE = "type"
const val TAG_ADD_SITE_ICON_DIALOG = "TAG_ADD_SITE_ICON_DIALOG"
const val TAG_CHANGE_SITE_ICON_DIALOG = "TAG_CHANGE_SITE_ICON_DIALOG"
const val TAG_REMOVE_NEXT_STEPS_DIALOG = "TAG_REMOVE_NEXT_STEPS_DIALOG"
const val SITE_NAME_CHANGE_CALLBACK_ID = 1
const val ARG_QUICK_START_TASK = "ARG_QUICK_START_TASK"
const val HIDE_WP_ADMIN_GMT_TIME_ZONE = "GMT"
const val LIST_SCROLL_DELAY_MS = 500L
const val MY_SITE_TAB = "tab"
const val TAB_SOURCE = "tab_source"
}
}
| gpl-2.0 | 34bea92b9d5df89a11b6c25996dbc7e1 | 45.332664 | 130 | 0.665679 | 5.201849 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/reflect/Reflection.kt | 2 | 4461 | // 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.
@file:OptIn(ExperimentalStdlibApi::class)
package org.jetbrains.kotlin.idea.gradleTooling.reflect
import org.gradle.api.logging.Logger
import org.gradle.api.logging.Logging
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.typeOf
internal inline fun <reified T> returnType(): TypeToken<T> = TypeToken.create()
internal inline fun <reified T> parameter(value: T?): Parameter<T> = Parameter(TypeToken.create(), value)
internal fun parameters(vararg parameter: Parameter<*>): ParameterList =
if (parameter.isEmpty()) ParameterList.empty else ParameterList(parameter.toList())
internal class TypeToken<T> private constructor(
val kotlinType: KType?,
val kotlinClass: KClass<*>,
val isMarkedNullable: Boolean
) {
override fun toString(): String {
return kotlinType?.toString() ?: (kotlinClass.java.name + if (isMarkedNullable) "?" else "")
}
companion object {
inline fun <reified T> create(): TypeToken<T> {
/* KType is not supported with older versions of Kotlin bundled in old Gradle versions (4.x) */
val type = runCatching { typeOf<T>() }.getOrNull()
val isMarkedNullable = when {
type != null -> type.isMarkedNullable
else -> null is T
}
return TypeToken(type, T::class, isMarkedNullable)
}
}
}
interface ReflectionLogger {
fun logIssue(message: String, exception: Throwable? = null)
}
fun ReflectionLogger(clazz: Class<*>) = ReflectionLogger(Logging.getLogger(clazz))
fun ReflectionLogger(logger: Logger): ReflectionLogger = GradleReflectionLogger(logger)
private class GradleReflectionLogger(private val logger: Logger) : ReflectionLogger {
override fun logIssue(message: String, exception: Throwable?) {
assert(false) { message }
logger.error("[Reflection Error] $message", exception)
}
}
internal class Parameter<T>(
/**
* Optional, because this is not supported in old Gradle/Kotlin Versions
*/
val typeToken: TypeToken<T>,
val value: T?
)
internal class ParameterList(private val parameters: List<Parameter<*>>) : List<Parameter<*>> by parameters {
companion object {
val empty = ParameterList(emptyList())
}
}
internal inline fun <reified T> Any.callReflective(
methodName: String, parameters: ParameterList, returnTypeToken: TypeToken<T>, logger: ReflectionLogger
): T? {
val parameterClasses = parameters.map { parameter ->
/* Ensure using the object representation for primitive types, when marked nullable */
if (parameter.typeToken.isMarkedNullable) parameter.typeToken.kotlinClass.javaObjectType
else parameter.typeToken.kotlinClass.javaPrimitiveType ?: parameter.typeToken.kotlinClass.java
}
val method = try {
this::class.java.getMethod(methodName, *parameterClasses.toTypedArray())
} catch (e: Exception) {
logger.logIssue("Failed to invoke $methodName on ${this.javaClass.name}", e)
return null
}
runCatching {
@Suppress("Since15")
method.trySetAccessible()
}
val returnValue = try {
method.invoke(this, *parameters.map { it.value }.toTypedArray())
} catch (t: Throwable) {
logger.logIssue("Failed to invoke $methodName on ${this.javaClass.name}", t)
return null
}
if (returnValue == null) {
if (!returnTypeToken.isMarkedNullable) {
logger.logIssue("Method $methodName on ${this.javaClass.name} unexpectedly returned null (expected $returnTypeToken)")
}
return null
}
if (!returnTypeToken.kotlinClass.javaObjectType.isInstance(returnValue)) {
logger.logIssue(
"Method $methodName on ${this.javaClass.name} unexpectedly returned ${returnValue.javaClass.name}, which is " +
"not an instance of ${returnTypeToken}"
)
return null
}
return returnValue as T
}
internal fun Any.callReflectiveAnyGetter(methodName: String, logger: ReflectionLogger): Any? = callReflectiveGetter<Any>(methodName, logger)
internal inline fun <reified T> Any.callReflectiveGetter(methodName: String, logger: ReflectionLogger): T? =
callReflective(methodName, parameters(), returnType<T>(), logger) | apache-2.0 | 5b860bdaa6eafcae1eaad39acf401151 | 35.876033 | 158 | 0.690876 | 4.584789 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.