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
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt
1
13900
package info.nightscout.androidaps.dialogs import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.common.base.Joiner import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.databinding.DialogCarbsBinding import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TempTarget import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.treatments.CarbsGenerator import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.extensions.formatColor import info.nightscout.androidaps.utils.resources.ResourceHelper import java.text.DecimalFormat import java.util.* import javax.inject.Inject import kotlin.math.max class CarbsDialog : DialogFragmentWithDate() { @Inject lateinit var mainApp: MainApp @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin @Inject lateinit var nsUpload: NSUpload @Inject lateinit var carbsGenerator: CarbsGenerator companion object { private const val FAV1_DEFAULT = 5 private const val FAV2_DEFAULT = 10 private const val FAV3_DEFAULT = 20 } private val textWatcher: TextWatcher = object : TextWatcher { override fun afterTextChanged(s: Editable) { validateInputs() } override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {} } private fun validateInputs() { val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble() val time = binding.time.value.toInt() if (time > 12 * 60 || time < -12 * 60) { binding.time.value = 0.0 ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.constraintapllied)) } if (binding.duration.value > 10) { binding.duration.value = 0.0 ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.constraintapllied)) } if (binding.carbs.value.toInt() > maxCarbs) { binding.carbs.value = 0.0 ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.carbsconstraintapplied)) } } private var _binding: DialogCarbsBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putDouble("time", binding.time.value) savedInstanceState.putDouble("duration", binding.duration.value) savedInstanceState.putDouble("carbs", binding.carbs.value) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { onCreateViewGeneral() _binding = DialogCarbsBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble() binding.time.setParams(savedInstanceState?.getDouble("time") ?: 0.0, -12 * 60.0, 12 * 60.0, 5.0, DecimalFormat("0"), false, binding.okcancel.ok, textWatcher) binding.duration.setParams(savedInstanceState?.getDouble("duration") ?: 0.0, 0.0, 10.0, 1.0, DecimalFormat("0"), false, binding.okcancel.ok, textWatcher) binding.carbs.setParams(savedInstanceState?.getDouble("carbs") ?: 0.0, 0.0, maxCarbs, 1.0, DecimalFormat("0"), false, binding.okcancel.ok, textWatcher) binding.plus1.text = toSignedString(sp.getInt(R.string.key_carbs_button_increment_1, FAV1_DEFAULT)) binding.plus1.setOnClickListener { binding.carbs.value = max(0.0, binding.carbs.value + sp.getInt(R.string.key_carbs_button_increment_1, FAV1_DEFAULT)) validateInputs() } binding.plus2.text = toSignedString(sp.getInt(R.string.key_carbs_button_increment_2, FAV2_DEFAULT)) binding.plus2.setOnClickListener { binding.carbs.value = max(0.0, binding.carbs.value + sp.getInt(R.string.key_carbs_button_increment_2, FAV2_DEFAULT)) validateInputs() } binding.plus3.text = toSignedString(sp.getInt(R.string.key_carbs_button_increment_3, FAV3_DEFAULT)) binding.plus3.setOnClickListener { binding.carbs.value = max(0.0, binding.carbs.value + sp.getInt(R.string.key_carbs_button_increment_3, FAV3_DEFAULT)) validateInputs() } iobCobCalculatorPlugin.actualBg()?.let { bgReading -> if (bgReading.value < 72) binding.hypoTt.isChecked = true } binding.hypoTt.setOnClickListener { binding.activityTt.isChecked = false binding.eatingSoonTt.isChecked = false } binding.activityTt.setOnClickListener { binding.hypoTt.isChecked = false binding.eatingSoonTt.isChecked = false } binding.eatingSoonTt.setOnClickListener { binding.hypoTt.isChecked = false binding.activityTt.isChecked = false } } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun toSignedString(value: Int): String { return if (value > 0) "+$value" else value.toString() } override fun submit(): Boolean { if (_binding == null) return false val carbs = binding.carbs.value?.toInt() ?: return false val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() val units = profileFunction.getUnits() val activityTTDuration = defaultValueHelper.determineActivityTTDuration() val activityTT = defaultValueHelper.determineActivityTT() val eatingSoonTTDuration = defaultValueHelper.determineEatingSoonTTDuration() val eatingSoonTT = defaultValueHelper.determineEatingSoonTT() val hypoTTDuration = defaultValueHelper.determineHypoTTDuration() val hypoTT = defaultValueHelper.determineHypoTT() val actions: LinkedList<String?> = LinkedList() val unitLabel = if (units == Constants.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) val activitySelected = binding.activityTt.isChecked if (activitySelected) actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(activityTT) + " " + unitLabel + " (" + resourceHelper.gs(R.string.format_mins, activityTTDuration) + ")").formatColor(resourceHelper, R.color.tempTargetConfirmation)) val eatingSoonSelected = binding.eatingSoonTt.isChecked if (eatingSoonSelected) actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + resourceHelper.gs(R.string.format_mins, eatingSoonTTDuration) + ")").formatColor(resourceHelper, R.color.tempTargetConfirmation)) val hypoSelected = binding.hypoTt.isChecked if (hypoSelected) actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(hypoTT) + " " + unitLabel + " (" + resourceHelper.gs(R.string.format_mins, hypoTTDuration) + ")").formatColor(resourceHelper, R.color.tempTargetConfirmation)) val timeOffset = binding.time.value.toInt() eventTime -= eventTime % 1000 val time = eventTime + timeOffset * 1000 * 60 if (timeOffset != 0) actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(time)) val duration = binding.duration.value.toInt() if (duration > 0) actions.add(resourceHelper.gs(R.string.duration) + ": " + duration + resourceHelper.gs(R.string.shorthour)) if (carbsAfterConstraints > 0) { actions.add(resourceHelper.gs(R.string.carbs) + ": " + "<font color='" + resourceHelper.gc(R.color.carbs) + "'>" + resourceHelper.gs(R.string.format_carbs, carbsAfterConstraints) + "</font>") if (carbsAfterConstraints != carbs) actions.add("<font color='" + resourceHelper.gc(R.color.warning) + "'>" + resourceHelper.gs(R.string.carbsconstraintapplied) + "</font>") } val notes = binding.notesLayout.notes.text.toString() if (notes.isNotEmpty()) actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) if (eventTimeChanged) actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime)) if (carbsAfterConstraints > 0 || activitySelected || eatingSoonSelected || hypoSelected) { activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.carbs), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), { when { activitySelected -> { aapsLogger.debug("USER ENTRY: TEMPTARGET ACTIVITY $activityTT duration: $activityTTDuration") val tempTarget = TempTarget() .date(System.currentTimeMillis()) .duration(activityTTDuration) .reason(resourceHelper.gs(R.string.activity)) .source(Source.USER) .low(Profile.toMgdl(activityTT, profileFunction.getUnits())) .high(Profile.toMgdl(activityTT, profileFunction.getUnits())) treatmentsPlugin.addToHistoryTempTarget(tempTarget) } eatingSoonSelected -> { aapsLogger.debug("USER ENTRY: TEMPTARGET EATING SOON $eatingSoonTT duration: $eatingSoonTTDuration") val tempTarget = TempTarget() .date(System.currentTimeMillis()) .duration(eatingSoonTTDuration) .reason(resourceHelper.gs(R.string.eatingsoon)) .source(Source.USER) .low(Profile.toMgdl(eatingSoonTT, profileFunction.getUnits())) .high(Profile.toMgdl(eatingSoonTT, profileFunction.getUnits())) treatmentsPlugin.addToHistoryTempTarget(tempTarget) } hypoSelected -> { aapsLogger.debug("USER ENTRY: TEMPTARGET HYPO $hypoTT duration: $hypoTTDuration") val tempTarget = TempTarget() .date(System.currentTimeMillis()) .duration(hypoTTDuration) .reason(resourceHelper.gs(R.string.hypo)) .source(Source.USER) .low(Profile.toMgdl(hypoTT, profileFunction.getUnits())) .high(Profile.toMgdl(hypoTT, profileFunction.getUnits())) treatmentsPlugin.addToHistoryTempTarget(tempTarget) } } if (carbsAfterConstraints > 0) { if (duration == 0) { aapsLogger.debug("USER ENTRY: CARBS $carbsAfterConstraints time: $time") carbsGenerator.createCarb(carbsAfterConstraints, time, CareportalEvent.CARBCORRECTION, notes) } else { aapsLogger.debug("USER ENTRY: CARBS $carbsAfterConstraints time: $time duration: $duration") carbsGenerator.generateCarbs(carbsAfterConstraints, time, duration, notes) nsUpload.uploadEvent(CareportalEvent.NOTE, DateUtil.now() - 2000, resourceHelper.gs(R.string.generated_ecarbs_note, carbsAfterConstraints, duration, timeOffset)) } } }, null) } } else activity?.let { activity -> OKDialog.show(activity, resourceHelper.gs(R.string.carbs), resourceHelper.gs(R.string.no_action_selected)) } return true } }
agpl-3.0
7c275c7b1736baf8e810096dbc452b7d
51.259398
276
0.648633
4.625624
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/scene/Model.kt
1
1801
package de.fabmax.kool.scene import de.fabmax.kool.KoolContext import de.fabmax.kool.pipeline.Texture2d import de.fabmax.kool.scene.animation.Animation import de.fabmax.kool.scene.animation.Skin class Model(name: String? = null) : Group(name) { val nodes = mutableMapOf<String, Group>() val meshes = mutableMapOf<String, Mesh>() val textures = mutableMapOf<String, Texture2d>() val animations = mutableListOf<Animation>() val skins = mutableListOf<Skin>() fun disableAllAnimations() { enableAnimation(-1) } fun enableAnimation(iAnimation: Int) { for (i in animations.indices) { animations[i].weight = if (i == iAnimation) 1f else 0f } } fun setAnimationWeight(iAnimation: Int, weight: Float) { if (iAnimation in animations.indices) { animations[iAnimation].weight = weight } } fun applyAnimation(deltaT: Float) { var firstActive = true for (i in animations.indices) { if (animations[i].weight > 0f) { animations[i].apply(deltaT, firstActive) firstActive = false } } for (i in skins.indices) { skins[i].updateJointTransforms() } } fun printHierarchy() { printHierarchy("") } private fun Group.printHierarchy(indent: String) { println("$indent$name [${children.filterIsInstance<Mesh>().count()} meshes]") children.forEach { if (it is Group) { it.printHierarchy("$indent ") } else { println("$indent ${it.name}") } } } override fun dispose(ctx: KoolContext) { textures.values.forEach { it.dispose() } super.dispose(ctx) } }
apache-2.0
164c77427891250e7d5524693ec1fe3e
26.723077
85
0.586896
4.217799
false
false
false
false
Flank/flank
flank-scripts/src/main/kotlin/flank/scripts/utils/Version.kt
1
2241
package flank.scripts.utils import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder object VersionSerializer : KSerializer<Version> { override val descriptor = PrimitiveSerialDescriptor("Version", PrimitiveKind.STRING) override fun deserialize(decoder: Decoder): Version = parseToVersion(decoder.decodeString()) override fun serialize(encoder: Encoder, value: Version) = encoder.encodeString(value.toString()) } @Serializable(with = VersionSerializer::class) data class Version( private val major: Int? = null, private val minor: Int? = null, private val micro: Int? = null, private val patch: Int? = null, private val qualifier: String? = null ) : Comparable<Version> { private val hasSuffix = major != null && qualifier != null override operator fun compareTo(other: Version): Int = when { major differs other.major -> compareValuesBy(major, other.major, { it ?: 0 }) minor differs other.minor -> compareValuesBy(minor, other.minor, { it ?: 0 }) micro differs other.micro -> compareValuesBy(micro, other.micro, { it ?: 0 }) patch differs other.patch -> compareValuesBy(patch, other.patch, { it ?: 0 }) else -> nullsLast<String>().compare(qualifier, other.qualifier) } private infix fun Int?.differs(other: Int?) = (this ?: 0) != (other ?: 0) override fun toString(): String = listOfNotNull(major, minor, micro, patch) .joinToString(".") + "${if (hasSuffix) "-" else ""}${qualifier ?: ""}" } fun parseToVersion(versionString: String): Version { val groups = "(\\d*)\\.?(\\d*)\\.?(\\d*)\\.?(\\d*)[-.]?([a-zA-Z0-9_.-]*)".toRegex().find(versionString)?.groupValues return if (groups == null) Version(qualifier = versionString) else Version( major = groups[1].toIntOrNull(), minor = groups[2].toIntOrNull(), micro = groups[3].toIntOrNull(), patch = groups[4].toIntOrNull(), qualifier = if (groups[5].isNotBlank()) groups[5] else null ) }
apache-2.0
5eefecaac17f7a44e93ec3388a8956cf
42.096154
120
0.68407
4.334623
false
false
false
false
siosio/intellij-community
platform/platform-api/src/com/intellij/ui/tabs/impl/JBDefaultTabPainter.kt
1
3003
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.tabs.impl import com.intellij.openapi.rd.fill2DRect import com.intellij.openapi.rd.paint2DLine import com.intellij.openapi.util.registry.ExperimentalUI import com.intellij.ui.paint.LinePainter2D import com.intellij.ui.tabs.JBTabPainter import com.intellij.ui.tabs.JBTabsPosition import com.intellij.ui.tabs.impl.themes.DefaultTabTheme import com.intellij.ui.tabs.impl.themes.TabTheme import java.awt.Color import java.awt.Graphics2D import java.awt.Point import java.awt.Rectangle open class JBDefaultTabPainter(val theme : TabTheme = DefaultTabTheme()) : JBTabPainter { override fun getTabTheme(): TabTheme = theme override fun getBackgroundColor(): Color = theme.background ?: theme.borderColor override fun fillBackground(g: Graphics2D, rect: Rectangle) { theme.background?.let{ g.fill2DRect(rect, it) } } override fun paintTab(position: JBTabsPosition, g: Graphics2D, rect: Rectangle, borderThickness: Int, tabColor: Color?, active: Boolean, hovered: Boolean) { tabColor?.let { g.fill2DRect(rect, it) theme.inactiveColoredTabBackground?.let { inactive -> g.fill2DRect(rect, inactive) } } if(hovered) { (if (active) theme.hoverBackground else theme.hoverInactiveBackground)?.let{ g.fill2DRect(rect, it) } } } override fun paintSelectedTab(position: JBTabsPosition, g: Graphics2D, rect: Rectangle, borderThickness: Int, tabColor: Color?, active: Boolean, hovered: Boolean) { val color = (tabColor ?: if(active) theme.underlinedTabBackground else theme.underlinedTabInactiveBackground) ?: theme.background color?.let { g.fill2DRect(rect, it) } if(hovered) { if (ExperimentalUI.isNewEditorTabs()) return; (if (active) theme.hoverBackground else theme.hoverInactiveBackground)?.let{ g.fill2DRect(rect, it) } } paintUnderline(position, rect, borderThickness, g, active) } override fun paintUnderline(position: JBTabsPosition, rect: Rectangle, borderThickness: Int, g: Graphics2D, active: Boolean) { val underline = underlineRectangle(position, rect, theme.underlineHeight) g.fill2DRect(underline, if (active) theme.underlineColor else theme.inactiveUnderlineColor) } override fun paintBorderLine(g: Graphics2D, thickness: Int, from: Point, to: Point) { g.paint2DLine(from, to, LinePainter2D.StrokeType.INSIDE, thickness.toDouble(), theme.borderColor) } protected open fun underlineRectangle(position: JBTabsPosition, rect: Rectangle, thickness: Int): Rectangle { return Rectangle(rect.x, rect.y + rect.height - thickness, rect.width, thickness) } }
apache-2.0
7e127306a2f77137fd71a01cf795ab94
36.5375
166
0.691309
4.15928
false
false
false
false
siosio/intellij-community
plugins/kotlin/gradle/gradle-idea/tests/test/org/jetbrains/kotlin/idea/scripting/gradle/roots/AbstractGradleBuildRootsLocatorTest.kt
1
3467
// 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.scripting.gradle.roots import com.intellij.mock.MockProjectEx import com.intellij.openapi.Disposable import com.intellij.openapi.util.Disposer import com.intellij.util.ThrowableRunnable import junit.framework.TestCase import org.jetbrains.kotlin.idea.scripting.gradle.GradleKotlinScriptConfigurationInputs import org.jetbrains.kotlin.idea.scripting.gradle.LastModifiedFiles import org.jetbrains.kotlin.idea.scripting.gradle.importing.KotlinDslScriptModel import org.jetbrains.kotlin.idea.test.runAll abstract class AbstractGradleBuildRootsLocatorTest : TestCase() { private val scripts = mutableMapOf<String, ScriptFixture>() class ScriptFixture(val introductionTs: Long, val info: GradleScriptInfo) private lateinit var locator: MyRootsLocator private lateinit var disposable: Disposable override fun setUp() { super.setUp() val newDisposable = Disposer.newDisposable() locator = MyRootsLocator(newDisposable) disposable = newDisposable } override fun tearDown() { runAll( ThrowableRunnable { Disposer.dispose(disposable) }, ThrowableRunnable { super.tearDown() } ) } private inner class MyRootsLocator(disposable: Disposable) : GradleBuildRootsLocator(MockProjectEx(disposable)) { override fun getScriptFirstSeenTs(path: String): Long = scripts[path]?.introductionTs ?: 0 override fun getScriptInfo(localPath: String): GradleScriptInfo? = scripts[localPath]?.info fun accessRoots() = roots } private fun add(root: GradleBuildRoot) { locator.accessRoots().add(root) } fun newImportedGradleProject( dir: String, relativeProjectRoots: List<String> = listOf(""), relativeScripts: List<String> = listOf("build.gradle.kts"), ts: Long = 0 ) { val pathPrefix = "$dir/" val root = Imported( dir, GradleBuildRootData( ts, relativeProjectRoots.map { (pathPrefix + it).removeSuffix("/") }, "gradleHome", "javaHome", listOf() ), LastModifiedFiles() ) add(root) relativeScripts.forEach { val path = pathPrefix + it scripts[path] = ScriptFixture( 0, GradleScriptInfo( root, null, KotlinDslScriptModel( file = path, inputs = GradleKotlinScriptConfigurationInputs("", 0, dir), classPath = listOf(), sourcePath = listOf(), imports = listOf(), messages = listOf() ) ) ) } } private fun findScriptBuildRoot(filePath: String, searchNearestLegacy: Boolean = true): GradleBuildRootsLocator.ScriptUnderRoot? { return locator.findScriptBuildRoot(filePath, searchNearestLegacy) } fun assertNotificationKind(filePath: String, notificationKind: GradleBuildRootsLocator.NotificationKind) { assertEquals(notificationKind, findScriptBuildRoot(filePath)?.notificationKind) } }
apache-2.0
d70376c0d3c1045a05939232b38dbaed
35.114583
158
0.63542
5.221386
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/AbstractOutOfBlockModificationTest.kt
1
7201
// 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.codeInsight import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiComment import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiManager import com.intellij.psi.impl.PsiModificationTrackerImpl import com.intellij.psi.util.PsiTreeUtil import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.trackers.outOfBlockModificationCount import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.idea.test.DirectiveBasedActionUtils import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.kdoc.psi.api.KDoc import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics import org.jetbrains.kotlin.resolve.lazy.ResolveSession import org.jetbrains.kotlin.test.InTextDirectivesUtils abstract class AbstractOutOfBlockModificationTest : KotlinLightCodeInsightFixtureTestCase() { protected fun doTest(unused: String?) { val ktFile = myFixture.configureByFile(fileName()) as KtFile if (ktFile.isScript()) { ScriptConfigurationManager.updateScriptDependenciesSynchronously(ktFile) } val expectedOutOfBlock = expectedOutOfBlockResult val isSkipCheckDefined = InTextDirectivesUtils.isDirectiveDefined( ktFile.text, SKIP_ANALYZE_CHECK_DIRECTIVE ) val tracker = PsiManager.getInstance(myFixture.project).modificationTracker as PsiModificationTrackerImpl val element = ktFile.findElementAt(myFixture.caretOffset) assertNotNull("Should be valid element", element) val oobBeforeType = ktFile.outOfBlockModificationCount val modificationCountBeforeType = tracker.modificationCount // have to analyze file before any change to support incremental analysis ktFile.analyzeWithAllCompilerChecks() myFixture.type(stringToType) PsiDocumentManager.getInstance(myFixture.project).commitDocument(myFixture.getDocument(myFixture.file)) val oobAfterCount = ktFile.outOfBlockModificationCount val modificationCountAfterType = tracker.modificationCount assertTrue( "Modification tracker should always be changed after type", modificationCountBeforeType != modificationCountAfterType ) assertEquals( "Result for out of block test is differs from expected on element in file:\n" + FileUtil.loadFile(testDataFile()), expectedOutOfBlock, oobBeforeType != oobAfterCount ) checkForUnexpectedErrors(ktFile) if (!isSkipCheckDefined) { checkOOBWithDescriptorsResolve(expectedOutOfBlock) } } private fun checkForUnexpectedErrors(ktFile: KtFile) { val diagnosticsProvider: (KtFile) -> Diagnostics = { it.analyzeWithAllCompilerChecks().bindingContext.diagnostics } DirectiveBasedActionUtils.checkForUnexpectedWarnings(ktFile, diagnosticsProvider) DirectiveBasedActionUtils.checkForUnexpectedErrors(ktFile, diagnosticsProvider) } private fun checkOOBWithDescriptorsResolve(expectedOutOfBlock: Boolean) { ApplicationManager.getApplication().runWriteAction { (PsiManager.getInstance(myFixture.project).modificationTracker as PsiModificationTrackerImpl) .incOutOfCodeBlockModificationCounter() } val updateElement = myFixture.file.findElementAt(myFixture.caretOffset - 1) val kDoc: KDoc? = PsiTreeUtil.getParentOfType(updateElement, KDoc::class.java, false) val ktExpression: KtExpression? = PsiTreeUtil.getParentOfType(updateElement, KtExpression::class.java, false) val ktDeclaration: KtDeclaration? = PsiTreeUtil.getParentOfType(updateElement, KtDeclaration::class.java, false) val ktElement = ktExpression ?: ktDeclaration ?: return val facade = ktElement.containingKtFile.getResolutionFacade() @OptIn(FrontendInternals::class) val session = facade.getFrontendService(ResolveSession::class.java) session.forceResolveAll() val context = session.bindingContext if (ktExpression != null && ktExpression !== ktDeclaration) { val expression = if (ktExpression is KtFunctionLiteral) ktExpression.getParent() as KtLambdaExpression else ktExpression val processed = context.get(BindingContext.PROCESSED, expression) val expressionProcessed = processed === java.lang.Boolean.TRUE assertEquals( "Expected out-of-block should result expression analyzed and vise versa", expectedOutOfBlock, expressionProcessed ) } else if (updateElement !is PsiComment && kDoc == null) { // comments could be ignored from analyze val declarationProcessed = context.get( BindingContext.DECLARATION_TO_DESCRIPTOR, ktDeclaration ) != null assertEquals( "Expected out-of-block should result declaration analyzed and vise versa", expectedOutOfBlock, declarationProcessed ) } } private val stringToType: String get() = stringToType(myFixture) private val expectedOutOfBlockResult: Boolean get() { val text = myFixture.getDocument(myFixture.file).text val outOfCodeBlockDirective = InTextDirectivesUtils.findStringWithPrefixes( text, OUT_OF_CODE_BLOCK_DIRECTIVE ) assertNotNull( "${fileName()}: Expectation of code block result test should be configured with " + "\"// " + OUT_OF_CODE_BLOCK_DIRECTIVE + " TRUE\" or " + "\"// " + OUT_OF_CODE_BLOCK_DIRECTIVE + " FALSE\" directive in the file", outOfCodeBlockDirective ) return outOfCodeBlockDirective?.toBoolean() ?: false } companion object { const val OUT_OF_CODE_BLOCK_DIRECTIVE = "OUT_OF_CODE_BLOCK:" const val SKIP_ANALYZE_CHECK_DIRECTIVE = "SKIP_ANALYZE_CHECK" const val TYPE_DIRECTIVE = "TYPE:" fun stringToType(fixture: JavaCodeInsightTestFixture): String { val text = fixture.getDocument(fixture.file).text val typeDirectives = InTextDirectivesUtils.findStringWithPrefixes(text, TYPE_DIRECTIVE) return if (typeDirectives != null) StringUtil.unescapeStringCharacters(typeDirectives) else "a" } } }
apache-2.0
e8f914800e6221afc81ef354304c3bf8
49.013889
158
0.710457
5.674547
false
true
false
false
SimpleMobileTools/Simple-Calendar
app/src/main/kotlin/com/simplemobiletools/calendar/pro/activities/SimpleActivity.kt
1
3642
package com.simplemobiletools.calendar.pro.activities import android.content.Context import android.database.ContentObserver import android.os.Handler import android.provider.CalendarContract import androidx.core.app.NotificationManagerCompat import com.simplemobiletools.calendar.pro.R import com.simplemobiletools.calendar.pro.extensions.config import com.simplemobiletools.calendar.pro.extensions.refreshCalDAVCalendars import com.simplemobiletools.commons.activities.BaseSimpleActivity import com.simplemobiletools.commons.dialogs.ConfirmationDialog import com.simplemobiletools.commons.extensions.toast import com.simplemobiletools.commons.helpers.ensureBackgroundThread open class SimpleActivity : BaseSimpleActivity() { val CALDAV_REFRESH_DELAY = 3000L val calDAVRefreshHandler = Handler() var calDAVRefreshCallback: (() -> Unit)? = null override fun getAppIconIDs() = arrayListOf( R.mipmap.ic_launcher_red, R.mipmap.ic_launcher_pink, R.mipmap.ic_launcher_purple, R.mipmap.ic_launcher_deep_purple, R.mipmap.ic_launcher_indigo, R.mipmap.ic_launcher_blue, R.mipmap.ic_launcher_light_blue, R.mipmap.ic_launcher_cyan, R.mipmap.ic_launcher_teal, R.mipmap.ic_launcher_green, R.mipmap.ic_launcher_light_green, R.mipmap.ic_launcher_lime, R.mipmap.ic_launcher_yellow, R.mipmap.ic_launcher_amber, R.mipmap.ic_launcher, R.mipmap.ic_launcher_deep_orange, R.mipmap.ic_launcher_brown, R.mipmap.ic_launcher_blue_grey, R.mipmap.ic_launcher_grey_black ) override fun getAppLauncherName() = getString(R.string.app_launcher_name) fun Context.syncCalDAVCalendars(callback: () -> Unit) { calDAVRefreshCallback = callback ensureBackgroundThread { val uri = CalendarContract.Calendars.CONTENT_URI contentResolver.unregisterContentObserver(calDAVSyncObserver) contentResolver.registerContentObserver(uri, false, calDAVSyncObserver) refreshCalDAVCalendars(config.caldavSyncedCalendarIds, true) } } // caldav refresh content observer triggers multiple times in a row at updating, so call the callback only a few seconds after the (hopefully) last one private val calDAVSyncObserver = object : ContentObserver(Handler()) { override fun onChange(selfChange: Boolean) { super.onChange(selfChange) if (!selfChange) { calDAVRefreshHandler.removeCallbacksAndMessages(null) calDAVRefreshHandler.postDelayed({ ensureBackgroundThread { unregisterObserver() calDAVRefreshCallback?.invoke() calDAVRefreshCallback = null } }, CALDAV_REFRESH_DELAY) } } } private fun unregisterObserver() { contentResolver.unregisterContentObserver(calDAVSyncObserver) } protected fun handleNotificationAvailability(callback: () -> Unit) { handleNotificationPermission { granted -> if (granted) { if (NotificationManagerCompat.from(this).areNotificationsEnabled()) { callback() } else { ConfirmationDialog(this, messageId = R.string.notifications_disabled, positive = R.string.ok, negative = 0) { callback() } } } else { toast(R.string.no_post_notifications_permissions) } } } }
gpl-3.0
1eab89d94079555329f8cc752c165a10
39.021978
155
0.660626
4.811096
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/OverloadResolutionChangeFix.kt
3
2570
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.daemon.QuickFixBundle import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.base.utils.fqname.fqName import org.jetbrains.kotlin.idea.inspections.dfa.getKotlinType import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.utils.addToStdlib.safeAs class OverloadResolutionChangeFix(element: KtExpression) : KotlinPsiOnlyQuickFixAction<KtExpression>(element) { companion object : QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) { override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> { val expression = psiElement.safeAs<KtExpression>() ?: return emptyList() return listOf(OverloadResolutionChangeFix(expression)) } } override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = element != null private fun getTypeArgumentForCast(expression: KtExpression): String? { val exprType = expression.getKotlinType() ?: return null val fqName = exprType.fqName?.asString() ?: return null return when (fqName) { "kotlin.ranges.IntRange" -> "Int" "kotlin.ranges.CharRange" -> "Char" "kotlin.ranges.LongRange" -> "Long" "kotlin.ranges.UIntRange" -> "UInt" "kotlin.ranges.ULongRange" -> "ULong" else -> null } } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val expression = element ?: return val typeArgument = getTypeArgumentForCast(expression) ?: return val casted = KtPsiFactory(file).createExpressionByPattern("($0) as Iterable<$1>", expression, typeArgument) expression.replace(casted) } override fun getText(): String { val expression = element ?: return "" val typeArgument = getTypeArgumentForCast(expression) ?: return "" return QuickFixBundle.message("add.typecast.text", "Iterable<$typeArgument>") } override fun getFamilyName(): String = text }
apache-2.0
6379440b1e00cfd868ae6fa553dadfb1
44.105263
158
0.724125
4.759259
false
false
false
false
loxal/FreeEthereum
free-ethereum-core/src/test/java/org/ethereum/net/rlpx/RlpxConnectionTest.kt
1
4583
/* * The MIT License (MIT) * * Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved. * Copyright (c) [2016] [ <ether.camp> ] * * 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 org.ethereum.net.rlpx import com.google.common.collect.Lists import org.ethereum.crypto.ECKey import org.ethereum.net.client.Capability import org.junit.Assert.* import org.junit.Before import org.junit.Test import java.io.* import java.security.SecureRandom class RlpxConnectionTest { private var iCodec: FrameCodec? = null private var rCodec: FrameCodec? = null private var initiator: EncryptionHandshake? = null private var responder: EncryptionHandshake? = null private var iMessage: HandshakeMessage? = null private var to: PipedInputStream? = null private var toOut: PipedOutputStream? = null private var from: PipedInputStream? = null private var fromOut: PipedOutputStream? = null @Before @Throws(Exception::class) fun setUp() { val remoteKey = ECKey() val myKey = ECKey() initiator = EncryptionHandshake(remoteKey.pubKeyPoint) responder = EncryptionHandshake() val initiate = initiator!!.createAuthInitiate(null, myKey) val initiatePacket = initiator!!.encryptAuthMessage(initiate) val responsePacket = responder!!.handleAuthInitiate(initiatePacket, remoteKey) initiator!!.handleAuthResponse(myKey, initiatePacket, responsePacket) to = PipedInputStream(1024 * 1024) toOut = PipedOutputStream(to) from = PipedInputStream(1024 * 1024) fromOut = PipedOutputStream(from) iCodec = FrameCodec(initiator!!.secrets) rCodec = FrameCodec(responder!!.secrets) val nodeId = byteArrayOf(1, 2, 3, 4) iMessage = HandshakeMessage( 123, "abcd", Lists.newArrayList( Capability("zz", 1.toByte()), Capability("yy", 3.toByte()) ), 3333, nodeId ) } @Test @Throws(Exception::class) fun testFrame() { val payload = ByteArray(123) SecureRandom().nextBytes(payload) val frame = FrameCodec.Frame(12345, 123, ByteArrayInputStream(payload)) iCodec!!.writeFrame(frame, toOut) val frame1 = rCodec!!.readFrames(DataInputStream(to!!))[0] val payload1 = ByteArray(frame1.size) assertEquals(frame.size.toLong(), frame1.size.toLong()) frame1.payload.read(payload1) assertArrayEquals(payload, payload1) assertEquals(frame.type, frame1.type) } @Test @Throws(IOException::class) fun testMessageEncoding() { val wire = iMessage!!.encode() val message1 = HandshakeMessage.parse(wire) assertEquals(123, message1.version) assertEquals("abcd", message1.name) assertEquals(3333, message1.listenPort) assertArrayEquals(message1.nodeId, message1.nodeId) assertEquals(iMessage!!.caps, message1.caps) } @Test @Throws(IOException::class) fun testHandshake() { val iConn = RlpxConnection(initiator!!.secrets, from!!, toOut!!) val rConn = RlpxConnection(responder!!.secrets, to!!, fromOut!!) iConn.sendProtocolHandshake(iMessage!!) rConn.handleNextMessage() val receivedMessage = rConn.handshakeMessage assertNotNull(receivedMessage) assertArrayEquals(iMessage!!.nodeId, receivedMessage!!.nodeId) } }
mit
40c5d13e6bb7fafb2c08ced2db028841
38.17094
86
0.680122
4.432302
false
true
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionWithDemorgansLawIntention.kt
1
9140
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.inspections.ReplaceNegatedIsEmptyWithIsNotEmptyInspection.Companion.invertSelectorFunction import org.jetbrains.kotlin.idea.inspections.SimplifyNegatedBinaryExpressionInspection import org.jetbrains.kotlin.idea.inspections.collections.isCalling import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.psi2ir.deparenthesize import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.typeUtil.isBoolean import org.jetbrains.kotlin.utils.addToStdlib.safeAs sealed class ConvertFunctionWithDemorgansLawIntention( intentionName: () -> String, conversions: List<Conversion>, ) : SelfTargetingRangeIntention<KtCallExpression>( KtCallExpression::class.java, intentionName ) { @SafeFieldForPreview private val conversions = conversions.associateBy { it.fromFunctionName } override fun applicabilityRange(element: KtCallExpression): TextRange? { val callee = element.calleeExpression ?: return null val (fromFunctionName, toFunctionName, _, _) = conversions[callee.text] ?: return null val fqNames = functions[fromFunctionName] ?: return null val lambda = element.singleLambdaArgumentExpression() ?: return null val lambdaBody = lambda.bodyExpression ?: return null val lastStatement = lambdaBody.statements.lastOrNull() ?: return null if (lambdaBody.anyDescendantOfType<KtReturnExpression> { it != lastStatement }) return null val context = element.analyze(BodyResolveMode.PARTIAL) if (element.getResolvedCall(context)?.resultingDescriptor?.fqNameOrNull() !in fqNames) return null val predicate = when (lastStatement) { is KtReturnExpression -> { val targetFunctionDescriptor = lastStatement.getTargetFunctionDescriptor(context) val lambdaDescriptor = context[BindingContext.FUNCTION, lambda.functionLiteral] if (targetFunctionDescriptor == lambdaDescriptor) lastStatement.returnedExpression else null } else -> lastStatement } ?: return null if (predicate.getType(context)?.isBoolean() != true) return null setTextGetter(KotlinBundle.lazyMessage("replace.0.with.1", fromFunctionName, toFunctionName)) return callee.textRange } override fun applyTo(element: KtCallExpression, editor: Editor?) { val (_, toFunctionName, negateCall, negatePredicate) = conversions[element.calleeExpression?.text] ?: return val lambda = element.singleLambdaArgumentExpression() ?: return val lastStatement = lambda.bodyExpression?.statements?.lastOrNull() ?: return val returnExpression = lastStatement.safeAs<KtReturnExpression>() val predicate = returnExpression?.returnedExpression ?: lastStatement if (negatePredicate) negate(predicate) val psiFactory = KtPsiFactory(element) if (returnExpression?.getLabelName() == element.calleeExpression?.text) { returnExpression?.labelQualifier?.replace(psiFactory.createLabelQualifier(toFunctionName)) } val callOrQualified = element.getQualifiedExpressionForSelectorOrThis() val parentNegatedExpression = callOrQualified.parentNegatedExpression() psiFactory.buildExpression { val addNegation = negateCall && parentNegatedExpression == null if (addNegation && callOrQualified !is KtSafeQualifiedExpression) { appendFixedText("!") } appendCallOrQualifiedExpression(element, toFunctionName) if (addNegation && callOrQualified is KtSafeQualifiedExpression) { appendFixedText("?.not()") } }.let { (parentNegatedExpression ?: callOrQualified).replaced(it) } } private fun negate(predicate: KtExpression) { val exclPrefixExpression = predicate.asExclPrefixExpression() if (exclPrefixExpression != null) { val replaced = exclPrefixExpression.baseExpression?.let { predicate.replaced(it) } replaced.removeUnnecessaryParentheses() return } val replaced = predicate.replaced(KtPsiFactory(predicate).createExpressionByPattern("!($0)", predicate)) as KtPrefixExpression replaced.baseExpression.removeUnnecessaryParentheses() when (val baseExpression = replaced.baseExpression?.deparenthesize()) { is KtBinaryExpression -> { val operationToken = baseExpression.operationToken if (operationToken == KtTokens.ANDAND || operationToken == KtTokens.OROR) { ConvertBinaryExpressionWithDemorgansLawIntention.convertIfPossible(baseExpression) } else { SimplifyNegatedBinaryExpressionInspection.simplifyNegatedBinaryExpressionIfNeeded(replaced) } } is KtQualifiedExpression -> { baseExpression.invertSelectorFunction()?.let { replaced.replace(it) } } } } private fun KtExpression.parentNegatedExpression(): KtExpression? { val parent = parents.dropWhile { it is KtParenthesizedExpression }.firstOrNull() ?: return null return parent.asExclPrefixExpression() ?: parent.asQualifiedExpressionWithNotCall() } private fun PsiElement.asExclPrefixExpression(): KtPrefixExpression? { return safeAs<KtPrefixExpression>()?.takeIf { it.operationToken == KtTokens.EXCL && it.baseExpression != null } } private fun PsiElement.asQualifiedExpressionWithNotCall(): KtQualifiedExpression? { return safeAs<KtQualifiedExpression>()?.takeIf { it.callExpression?.isCalling(FqName("kotlin.Boolean.not")) == true } } private fun KtExpression?.removeUnnecessaryParentheses() { if (this !is KtParenthesizedExpression) return val innerExpression = this.expression ?: return if (KtPsiUtil.areParenthesesUseless(this)) { this.replace(innerExpression) } } private fun KtPsiFactory.createLabelQualifier(labelName: String): KtContainerNode { return (createExpression("return@$labelName 1") as KtReturnExpression).labelQualifier!! } companion object { private val collectionFunctions = listOf("all", "any", "none", "filter", "filterNot", "filterTo", "filterNotTo").associateWith { listOf(FqName("kotlin.collections.$it"), FqName("kotlin.sequences.$it")) } private val standardFunctions = listOf("takeIf", "takeUnless").associateWith { listOf(FqName("kotlin.$it")) } private val functions = collectionFunctions + standardFunctions } } private data class Conversion( val fromFunctionName: String, val toFunctionName: String, val negateCall: Boolean, val negatePredicate: Boolean ) class ConvertCallToOppositeIntention : ConvertFunctionWithDemorgansLawIntention( KotlinBundle.lazyMessage("replace.function.call.with.the.opposite"), listOf( Conversion("all", "none", false, true), Conversion("none", "all", false, true), Conversion("filter", "filterNot", false, true), Conversion("filterNot", "filter", false, true), Conversion("filterTo", "filterNotTo", false, true), Conversion("filterNotTo", "filterTo", false, true), Conversion("takeIf", "takeUnless", false, true), Conversion("takeUnless", "takeIf", false, true) ) ) class ConvertAnyToAllAndViceVersaIntention : ConvertFunctionWithDemorgansLawIntention( KotlinBundle.lazyMessage("replace.0.with.1.and.vice.versa", "any", "all"), listOf( Conversion("any", "all", true, true), Conversion("all", "any", true, true) ) ) class ConvertAnyToNoneAndViceVersaIntention : ConvertFunctionWithDemorgansLawIntention( KotlinBundle.lazyMessage("replace.0.with.1.and.vice.versa", "any", "none"), listOf( Conversion("any", "none", true, false), Conversion("none", "any", true, false) ) )
apache-2.0
4968f2b42735a7616a7effc77cea045e
47.105263
136
0.718271
5.357562
false
false
false
false
jwren/intellij-community
plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/features/SearchEverywhereFileFeaturesProvider.kt
1
7090
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions.searcheverywhere.ml.features import com.intellij.filePrediction.features.history.FileHistoryManagerWrapper import com.intellij.ide.actions.GotoFileItemProvider import com.intellij.ide.actions.searcheverywhere.FileSearchEverywhereContributor import com.intellij.ide.actions.searcheverywhere.RecentFilesSEContributor import com.intellij.ide.favoritesTreeView.FavoritesManager import com.intellij.internal.statistic.eventLog.events.EventField import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventPair import com.intellij.openapi.application.ReadAction import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.impl.EditorHistoryManager import com.intellij.openapi.project.guessProjectDir import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.PsiFileSystemItem import com.intellij.util.PathUtil import com.intellij.util.Time.* internal class SearchEverywhereFileFeaturesProvider : SearchEverywhereElementFeaturesProvider(FileSearchEverywhereContributor::class.java, RecentFilesSEContributor::class.java) { companion object { internal val IS_DIRECTORY_DATA_KEY = EventFields.Boolean("isDirectory") internal val FILETYPE_DATA_KEY = EventFields.StringValidatedByCustomRule("fileType", "file_type") internal val IS_FAVORITE_DATA_KEY = EventFields.Boolean("isFavorite") internal val IS_OPENED_DATA_KEY = EventFields.Boolean("isOpened") internal val RECENT_INDEX_DATA_KEY = EventFields.Int("recentFilesIndex") internal val PREDICTION_SCORE_DATA_KEY = EventFields.Double("predictionScore") internal val IS_EXACT_MATCH_DATA_KEY = EventFields.Boolean("isExactMatch") internal val FILETYPE_MATCHES_QUERY_DATA_KEY = EventFields.Boolean("fileTypeMatchesQuery") internal val IS_TOP_LEVEL_DATA_KEY = EventFields.Boolean("isTopLevel") internal val TIME_SINCE_LAST_MODIFICATION_DATA_KEY = EventFields.Long("timeSinceLastModification") internal val WAS_MODIFIED_IN_LAST_MINUTE_DATA_KEY = EventFields.Boolean("wasModifiedInLastMinute") internal val WAS_MODIFIED_IN_LAST_HOUR_DATA_KEY = EventFields.Boolean("wasModifiedInLastHour") internal val WAS_MODIFIED_IN_LAST_DAY_DATA_KEY = EventFields.Boolean("wasModifiedInLastDay") internal val WAS_MODIFIED_IN_LAST_MONTH_DATA_KEY = EventFields.Boolean("wasModifiedInLastMonth") } override fun getFeaturesDeclarations(): List<EventField<*>> { return arrayListOf<EventField<*>>( IS_DIRECTORY_DATA_KEY, FILETYPE_DATA_KEY, IS_FAVORITE_DATA_KEY, IS_OPENED_DATA_KEY, RECENT_INDEX_DATA_KEY, PREDICTION_SCORE_DATA_KEY, IS_EXACT_MATCH_DATA_KEY, FILETYPE_MATCHES_QUERY_DATA_KEY, TIME_SINCE_LAST_MODIFICATION_DATA_KEY, WAS_MODIFIED_IN_LAST_MINUTE_DATA_KEY, WAS_MODIFIED_IN_LAST_HOUR_DATA_KEY, WAS_MODIFIED_IN_LAST_DAY_DATA_KEY, WAS_MODIFIED_IN_LAST_MONTH_DATA_KEY, IS_TOP_LEVEL_DATA_KEY ) } override fun getElementFeatures(element: Any, currentTime: Long, searchQuery: String, elementPriority: Int, cache: Any?): List<EventPair<*>> { val item = (SearchEverywhereClassOrFileFeaturesProvider.getPsiElement(element) as? PsiFileSystemItem) ?: return emptyList() val data = arrayListOf<EventPair<*>>( IS_FAVORITE_DATA_KEY.with(isFavorite(item)), IS_DIRECTORY_DATA_KEY.with(item.isDirectory), IS_EXACT_MATCH_DATA_KEY.with(elementPriority == GotoFileItemProvider.EXACT_MATCH_DEGREE) ) data.putIfValueNotNull(IS_TOP_LEVEL_DATA_KEY, isTopLevel(item)) val nameOfItem = item.virtualFile.nameWithoutExtension // Remove the directory and the extension if they are present val fileNameFromQuery = FileUtil.getNameWithoutExtension(PathUtil.getFileName(searchQuery)) data.addAll(getNameMatchingFeatures(nameOfItem, fileNameFromQuery)) if (item.isDirectory) { // Rest of the features are only applicable to files, not directories return data } data.add(IS_OPENED_DATA_KEY.with(isOpened(item))) data.add(FILETYPE_DATA_KEY.with(item.virtualFile.fileType.name)) data.putIfValueNotNull(FILETYPE_MATCHES_QUERY_DATA_KEY, matchesFileTypeInQuery(item, searchQuery)) data.add(RECENT_INDEX_DATA_KEY.with(getRecentFilesIndex(item))) data.add(PREDICTION_SCORE_DATA_KEY.with(getPredictionScore(item))) data.addAll(getModificationTimeStats(item, currentTime)) return data } private fun isFavorite(item: PsiFileSystemItem): Boolean { val favoritesManager = FavoritesManager.getInstance(item.project) return ReadAction.compute<Boolean, Nothing> { favoritesManager.getFavoriteListName(null, item.virtualFile) != null } } private fun isTopLevel(item: PsiFileSystemItem): Boolean? { val basePath = item.project.guessProjectDir()?.path ?: return null val fileDirectoryPath = item.virtualFile.parent?.path ?: return null return fileDirectoryPath == basePath } private fun isOpened(item: PsiFileSystemItem): Boolean { val openedFiles = FileEditorManager.getInstance(item.project).openFiles return item.virtualFile in openedFiles } private fun matchesFileTypeInQuery(item: PsiFileSystemItem, searchQuery: String): Boolean? { val fileExtension = item.virtualFile.extension val extensionInQuery = searchQuery.substringAfterLast('.', missingDelimiterValue = "") if (extensionInQuery.isEmpty() || fileExtension == null) { return null } return extensionInQuery == fileExtension } private fun getRecentFilesIndex(item: PsiFileSystemItem): Int { val historyManager = EditorHistoryManager.getInstance(item.project) val recentFilesList = historyManager.fileList val fileIndex = recentFilesList.indexOf(item.virtualFile) if (fileIndex == -1) { return fileIndex } // Give the most recent files the lowest index value return recentFilesList.size - fileIndex } private fun getModificationTimeStats(item: PsiFileSystemItem, currentTime: Long): List<EventPair<*>> { val timeSinceLastMod = currentTime - item.virtualFile.timeStamp return arrayListOf<EventPair<*>>( TIME_SINCE_LAST_MODIFICATION_DATA_KEY.with(timeSinceLastMod), WAS_MODIFIED_IN_LAST_MINUTE_DATA_KEY.with((timeSinceLastMod <= MINUTE)), WAS_MODIFIED_IN_LAST_HOUR_DATA_KEY.with((timeSinceLastMod <= HOUR)), WAS_MODIFIED_IN_LAST_DAY_DATA_KEY.with((timeSinceLastMod <= DAY)), WAS_MODIFIED_IN_LAST_MONTH_DATA_KEY.with((timeSinceLastMod <= (4 * WEEK.toLong()))) ) } private fun getPredictionScore(item: PsiFileSystemItem): Double { val historyManagerWrapper = FileHistoryManagerWrapper.getInstance(item.project) val probability = historyManagerWrapper.calcNextFileProbability(item.virtualFile) return roundDouble(probability) } }
apache-2.0
ab7aed1ee5b180fdacce44ac7432411c
48.929577
158
0.759097
4.392813
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/utils.kt
1
4676
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.dsl.builder.impl import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.util.NlsContexts import com.intellij.ui.TitledSeparator import com.intellij.ui.ToolbarDecorator import com.intellij.ui.dsl.UiDslException import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.builder.components.DslLabel import com.intellij.ui.dsl.builder.components.DslLabelType import com.intellij.ui.dsl.builder.components.SegmentedButtonToolbar import com.intellij.ui.dsl.gridLayout.Gaps import com.intellij.ui.dsl.gridLayout.GridLayoutComponentProperty import org.jetbrains.annotations.ApiStatus import java.util.ArrayList import javax.swing.* import javax.swing.text.JTextComponent /** * Internal component properties for UI DSL */ @ApiStatus.Internal internal enum class DslComponentPropertyInternal { /** * Removes standard bottom gap from label */ LABEL_NO_BOTTOM_GAP, /** * A mark that component is a cell label, see [Cell.label] * * Value: true */ CELL_LABEL } /** * [JPanel] descendants that should use default vertical gaps around similar to other standard components like labels, text fields etc */ private val DEFAULT_VERTICAL_GAP_COMPONENTS = setOf( SegmentedButtonComponent::class, SegmentedButtonToolbar::class, TextFieldWithBrowseButton::class, TitledSeparator::class ) /** * Throws exception instead of logging warning. Useful while forms building to avoid layout mistakes */ private const val FAIL_ON_WARN = false private val LOG = Logger.getInstance("Jetbrains UI DSL") /** * Components that can have assigned labels */ private val ALLOWED_LABEL_COMPONENTS = listOf( JComboBox::class, JSlider::class, JSpinner::class, JTable::class, JTextComponent::class, JTree::class, SegmentedButtonComponent::class, SegmentedButtonToolbar::class ) internal val JComponent.origin: JComponent get() { return when (this) { is TextFieldWithBrowseButton -> textField else -> this } } internal fun prepareVisualPaddings(component: JComponent): Gaps { val insets = component.insets val customVisualPaddings = component.getClientProperty(DslComponentProperty.VISUAL_PADDINGS) as? Gaps if (customVisualPaddings == null) { return Gaps(top = insets.top, left = insets.left, bottom = insets.bottom, right = insets.right) } component.putClientProperty(GridLayoutComponentProperty.SUB_GRID_AUTO_VISUAL_PADDINGS, false) return customVisualPaddings } internal fun getComponentGaps(left: Int, right: Int, component: JComponent, spacing: SpacingConfiguration): Gaps { val top = getDefaultVerticalGap(component, spacing) var bottom = top if (component is JLabel && component.getClientProperty(DslComponentPropertyInternal.LABEL_NO_BOTTOM_GAP) == true) { bottom = 0 } return Gaps(top = top, left = left, bottom = bottom, right = right) } /** * Returns default top and bottom gap for [component]. All non [JPanel] components or * [DEFAULT_VERTICAL_GAP_COMPONENTS] have default vertical gap, zero otherwise */ internal fun getDefaultVerticalGap(component: JComponent, spacing: SpacingConfiguration): Int { val noDefaultVerticalGap = component is JPanel && component.getClientProperty(ToolbarDecorator.DECORATOR_KEY) == null && !DEFAULT_VERTICAL_GAP_COMPONENTS.any { clazz -> clazz.isInstance(component) } return if (noDefaultVerticalGap) 0 else spacing.verticalComponentGap } internal fun createComment(@NlsContexts.Label text: String, maxLineLength: Int, action: HyperlinkEventAction): DslLabel { val result = DslLabel(DslLabelType.COMMENT) result.action = action result.maxLineLength = maxLineLength result.text = text return result } internal fun isAllowedLabel(cell: CellBaseImpl<*>?): Boolean { return cell is CellImpl<*> && ALLOWED_LABEL_COMPONENTS.any { clazz -> clazz.isInstance(cell.component.origin) } } internal fun labelCell(label: JLabel, cell: CellBaseImpl<*>?) { if (isAllowedLabel(cell)) { label.labelFor = (cell as CellImpl<*>).component.origin } } internal fun warn(message: String) { if (FAIL_ON_WARN) { throw UiDslException(message) } else { LOG.warn(message) } } internal fun buildPanelHierarchy(leaf: RowImpl): List<Panel> { val hierarchy = ArrayList<Panel>() var row: RowImpl? = leaf while (row != null) { hierarchy.add(row.parent) row = row.parent.parent } return hierarchy }
apache-2.0
d957cddcb45199e2ff13d9182c753686
31.248276
158
0.749145
4.309677
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/inspections/IntentionBasedInspection.kt
2
10345
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInsight.FileModificationService import com.intellij.codeInsight.intention.FileModifier import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.codeInspection.* import com.intellij.codeInspection.util.InspectionMessage import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.SmartList import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getStartOffsetIn import org.jetbrains.kotlin.psi.psiUtil.startOffset import kotlin.reflect.KClass // This class was originally created to make possible switching inspection off and using intention instead. // Since IDEA 2017.1, it's possible to have inspection severity "No highlighting, only fix" // thus making the original purpose useless. // The class still can be used, if you want to create a pair for existing intention with additional checker abstract class IntentionBasedInspection<TElement : PsiElement> private constructor( private val intentionInfo: IntentionData<TElement>, protected open val problemText: String? ) : AbstractKotlinInspection() { val intention: SelfTargetingRangeIntention<TElement> by lazy { val intentionClass = intentionInfo.intention intentionClass.constructors.single { it.parameters.isEmpty() }.call().apply { inspection = this@IntentionBasedInspection } } @Deprecated("Please do not use for new inspections. Use AbstractKotlinInspection as base class for them") constructor( intention: KClass<out SelfTargetingRangeIntention<TElement>>, problemText: String? = null ) : this(IntentionData(intention), problemText) constructor( intention: KClass<out SelfTargetingRangeIntention<TElement>>, additionalChecker: (TElement, IntentionBasedInspection<TElement>) -> Boolean, problemText: String? = null ) : this(IntentionData(intention, additionalChecker), problemText) constructor( intention: KClass<out SelfTargetingRangeIntention<TElement>>, additionalChecker: (TElement) -> Boolean, problemText: String? = null ) : this(IntentionData(intention) { element, _ -> additionalChecker(element) }, problemText) data class IntentionData<TElement : PsiElement>( val intention: KClass<out SelfTargetingRangeIntention<TElement>>, val additionalChecker: (TElement, IntentionBasedInspection<TElement>) -> Boolean = { _, _ -> true } ) open fun additionalFixes(element: TElement): List<LocalQuickFix>? = null open fun inspectionTarget(element: TElement): PsiElement? = null @InspectionMessage open fun inspectionProblemText(element: TElement): String? = null private fun PsiElement.toRange(baseElement: PsiElement): TextRange { val start = getStartOffsetIn(baseElement) return TextRange(start, start + endOffset - startOffset) } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { val elementType = intention.elementType return object : PsiElementVisitor() { override fun visitElement(element: PsiElement) { if (!elementType.isInstance(element) || element.textLength == 0) return @Suppress("UNCHECKED_CAST") val targetElement = element as TElement var problemRange: TextRange? = null var fixes: SmartList<LocalQuickFix>? = null val additionalChecker = intentionInfo.additionalChecker run { val range = intention.applicabilityRange(targetElement)?.let { range -> val elementRange = targetElement.textRange assert(range in elementRange) { "Wrong applicabilityRange() result for $intention - should be within element's range" } range.shiftRight(-elementRange.startOffset) } if (range != null && additionalChecker(targetElement, this@IntentionBasedInspection)) { problemRange = problemRange?.union(range) ?: range if (fixes == null) { fixes = SmartList() } fixes!!.add(createQuickFix(intention, additionalChecker, targetElement)) } } val range = inspectionTarget(targetElement)?.toRange(element) ?: problemRange if (range != null) { val allFixes = fixes ?: SmartList() additionalFixes(targetElement)?.let { allFixes.addAll(it) } if (!allFixes.isEmpty()) { holder.registerProblemWithoutOfflineInformation( targetElement, inspectionProblemText(element) ?: problemText ?: allFixes.first().name, isOnTheFly, problemHighlightType(targetElement), range, *allFixes.toTypedArray() ) } } } } } protected open fun problemHighlightType(element: TElement): ProblemHighlightType = ProblemHighlightType.GENERIC_ERROR_OR_WARNING private fun createQuickFix( intention: SelfTargetingRangeIntention<TElement>, additionalChecker: (TElement, IntentionBasedInspection<TElement>) -> Boolean, targetElement: TElement ): IntentionBasedQuickFix = when (intention) { is LowPriorityAction -> LowPriorityIntentionBasedQuickFix(intention, additionalChecker, targetElement) is HighPriorityAction -> HighPriorityIntentionBasedQuickFix(intention, additionalChecker, targetElement) else -> IntentionBasedQuickFix(intention, additionalChecker, targetElement) } /* we implement IntentionAction to provide isAvailable which will be used to hide outdated items and make sure we never call 'invoke' for such item */ internal open inner class IntentionBasedQuickFix( val intention: SelfTargetingRangeIntention<TElement>, private val additionalChecker: (TElement, IntentionBasedInspection<TElement>) -> Boolean, targetElement: TElement ) : LocalQuickFixOnPsiElement(targetElement), IntentionAction { private val text = intention.text // store text into variable because intention instance is shared and may change its text later override fun getFamilyName() = intention.familyName override fun getText(): String = text override fun startInWriteAction() = intention.startInWriteAction() override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?) = isAvailable() override fun isAvailable(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement): Boolean { assert(startElement == endElement) @Suppress("UNCHECKED_CAST") return intention.applicabilityRange(startElement as TElement) != null && additionalChecker( startElement, this@IntentionBasedInspection ) } override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { applyFix() } override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) { assert(startElement == endElement) if (!isAvailable(project, file, startElement, endElement)) return if (file.isPhysical && !FileModificationService.getInstance().prepareFileForWrite(file)) return val editor = startElement.findExistingEditor() editor?.caretModel?.moveToOffset(startElement.textOffset) @Suppress("UNCHECKED_CAST") intention.applyTo(startElement as TElement, editor) } @Suppress("UNCHECKED_CAST") override fun getFileModifierForPreview(target: PsiFile): FileModifier? { val newIntention = intention.getFileModifierForPreview(target) as? SelfTargetingRangeIntention<TElement> ?: return null val newElement = PsiTreeUtil.findSameElementInCopy(startElement, target) as? TElement ?: return null return IntentionBasedQuickFix(newIntention, additionalChecker, newElement) } } private inner class LowPriorityIntentionBasedQuickFix( intention: SelfTargetingRangeIntention<TElement>, additionalChecker: (TElement, IntentionBasedInspection<TElement>) -> Boolean, targetElement: TElement ) : IntentionBasedQuickFix(intention, additionalChecker, targetElement), LowPriorityAction private inner class HighPriorityIntentionBasedQuickFix( intention: SelfTargetingRangeIntention<TElement>, additionalChecker: (TElement, IntentionBasedInspection<TElement>) -> Boolean, targetElement: TElement ) : IntentionBasedQuickFix(intention, additionalChecker, targetElement), HighPriorityAction } fun PsiElement.findExistingEditor(): Editor? { ApplicationManager.getApplication().assertReadAccessAllowed() if (!containingFile.isValid) return null val file = containingFile?.virtualFile ?: return null val document = FileDocumentManager.getInstance().getDocument(file) ?: return null val editorFactory = EditorFactory.getInstance() val editors = editorFactory.getEditors(document) return if (editors.isEmpty()) null else editors[0] }
apache-2.0
bda50ed801c410476afc9b803a97f94b
46.454128
154
0.693765
5.76966
false
false
false
false
youdonghai/intellij-community
python/src/com/jetbrains/python/highlighting/PyRainbowVisitor.kt
1
5227
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.highlighting import com.intellij.codeInsight.daemon.RainbowVisitor import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.jetbrains.python.PyNames import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil import com.jetbrains.python.psi.* import com.jetbrains.python.psi.resolve.PyResolveContext class PyRainbowVisitor : RainbowVisitor() { companion object { private val IGNORED_NAMES = setOf(PyNames.NONE, PyNames.TRUE, PyNames.FALSE) } override fun suitableForFile(file: PsiFile) = file is PyFile override fun visit(element: PsiElement) { when (element) { is PyReferenceExpression -> processReference(element) is PyTargetExpression -> processTarget(element) is PyNamedParameter -> processNamedParameter(element) } } override fun clone() = PyRainbowVisitor() private fun processReference(referenceExpression: PyReferenceExpression) { val context = getReferenceContext(referenceExpression) ?: return val name = updateNameIfGlobal(context, referenceExpression.name) ?: return addInfo(context, referenceExpression, name) } private fun processTarget(targetExpression: PyTargetExpression) { val context = getTargetContext(targetExpression) ?: return val name = updateNameIfGlobal(context, targetExpression.name) ?: return addInfo(context, targetExpression, name) } private fun processNamedParameter(namedParameter: PyNamedParameter) { val context = getNamedParameterContext(namedParameter) ?: return val name = namedParameter.name ?: return getHighlightedParameterElements(namedParameter).forEach { addInfo(context, it, name, PyHighlighter.PY_PARAMETER) } } private fun getReferenceContext(referenceExpression: PyReferenceExpression): PsiElement? { if (referenceExpression.isQualified || referenceExpression.name in IGNORED_NAMES) return null val resolved = referenceExpression.reference.resolve() return when (resolved) { is PyTargetExpression -> getTargetContext(resolved) is PyNamedParameter -> getNamedParameterContext(resolved) is PyReferenceExpression -> if (resolved.parent is PyAugAssignmentStatement) getReferenceContext(resolved) else null else -> null } } private fun getTargetContext(targetExpression: PyTargetExpression): PsiElement? { if (targetExpression.isQualified || targetExpression.name in IGNORED_NAMES) return null val parent = targetExpression.parent if (parent is PyGlobalStatement) return targetExpression.containingFile if (parent is PyNonlocalStatement) { val outerResolved = targetExpression.reference.resolve() return if (outerResolved is PyTargetExpression) getTargetContext(outerResolved) else null } val resolveResults = targetExpression.getReference(PyResolveContext.noImplicits()).multiResolve(false) val resolvesToGlobal = resolveResults .asSequence() .map { it.element } .any { it is PyTargetExpression && it.parent is PyGlobalStatement } if (resolvesToGlobal) return targetExpression.containingFile val resolvedNonLocal = resolveResults .asSequence() .map { it.element } .filterIsInstance<PyTargetExpression>() .find { it.parent is PyNonlocalStatement } if (resolvedNonLocal != null) return getTargetContext(resolvedNonLocal) val scopeOwner = ScopeUtil.getScopeOwner(targetExpression) return if (scopeOwner is PyFile || scopeOwner is PyFunction || scopeOwner is PyLambdaExpression) scopeOwner else null } private fun getNamedParameterContext(namedParameter: PyNamedParameter): PsiElement? { if (namedParameter.isSelf) return null val scopeOwner = ScopeUtil.getScopeOwner(namedParameter) return if (scopeOwner is PyLambdaExpression || scopeOwner is PyFunction) scopeOwner else null } private fun updateNameIfGlobal(context: PsiElement, name: String?) = if (context is PyFile && name != null) "global_$name" else name private fun getHighlightedParameterElements(namedParameter: PyNamedParameter): List<PsiElement> { val nameIdentifier = namedParameter.nameIdentifier return if (namedParameter.isPositionalContainer || namedParameter.isKeywordContainer) { listOfNotNull(namedParameter.firstChild, nameIdentifier) } else { listOfNotNull(nameIdentifier) } } private fun addInfo(context: PsiElement, rainbowElement: PsiElement, name: String, colorKey: TextAttributesKey? = null) { addInfo(getInfo(context, rainbowElement, name, colorKey)) } }
apache-2.0
113534053846de33895e40130449b36c
38.606061
134
0.76277
5.030799
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/privacy/advanced/AdvancedPrivacySettingsViewModel.kt
1
6972
package org.thoughtcrime.securesms.components.settings.app.privacy.advanced import android.content.SharedPreferences import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.jobmanager.impl.NetworkConstraint import org.thoughtcrime.securesms.jobs.RefreshAttributesJob import org.thoughtcrime.securesms.jobs.RefreshOwnProfileJob import org.thoughtcrime.securesms.keyvalue.SettingsValues import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.phonenumbers.PhoneNumberFormatter import org.thoughtcrime.securesms.util.SingleLiveEvent import org.thoughtcrime.securesms.util.TextSecurePreferences import org.thoughtcrime.securesms.util.livedata.Store import org.whispersystems.signalservice.api.websocket.WebSocketConnectionState class AdvancedPrivacySettingsViewModel( private val sharedPreferences: SharedPreferences, private val repository: AdvancedPrivacySettingsRepository ) : ViewModel() { private val store = Store(getState()) private val singleEvents = SingleLiveEvent<Event>() val state: LiveData<AdvancedPrivacySettingsState> = store.stateLiveData val events: LiveData<Event> = singleEvents val disposables: CompositeDisposable = CompositeDisposable() init { disposables.add( ApplicationDependencies.getSignalWebSocket().webSocketState .observeOn(AndroidSchedulers.mainThread()) .subscribe { refresh() } ) } fun disablePushMessages() { store.update { getState().copy(showProgressSpinner = true) } repository.disablePushMessages { when (it) { AdvancedPrivacySettingsRepository.DisablePushMessagesResult.SUCCESS -> { SignalStore.account().setRegistered(false) SignalStore.registrationValues().clearRegistrationComplete() SignalStore.registrationValues().clearHasUploadedProfile() } AdvancedPrivacySettingsRepository.DisablePushMessagesResult.NETWORK_ERROR -> { singleEvents.postValue(Event.DISABLE_PUSH_FAILED) } } store.update { getState().copy(showProgressSpinner = false) } } } fun setAlwaysRelayCalls(enabled: Boolean) { sharedPreferences.edit().putBoolean(TextSecurePreferences.ALWAYS_RELAY_CALLS_PREF, enabled).apply() refresh() } fun setShowStatusIconForSealedSender(enabled: Boolean) { sharedPreferences.edit().putBoolean(TextSecurePreferences.SHOW_UNIDENTIFIED_DELIVERY_INDICATORS, enabled).apply() repository.syncShowSealedSenderIconState() refresh() } fun setAllowSealedSenderFromAnyone(enabled: Boolean) { sharedPreferences.edit().putBoolean(TextSecurePreferences.UNIVERSAL_UNIDENTIFIED_ACCESS, enabled).apply() ApplicationDependencies.getJobManager().startChain(RefreshAttributesJob()).then(RefreshOwnProfileJob()).enqueue() refresh() } fun setCensorshipCircumventionEnabled(enabled: Boolean) { SignalStore.settings().setCensorshipCircumventionEnabled(enabled) SignalStore.misc().isServiceReachableWithoutCircumvention = false ApplicationDependencies.resetAllNetworkConnections() refresh() } fun refresh() { store.update { getState().copy(showProgressSpinner = it.showProgressSpinner) } } override fun onCleared() { disposables.dispose() } private fun getState(): AdvancedPrivacySettingsState { val censorshipCircumventionState = getCensorshipCircumventionState() return AdvancedPrivacySettingsState( isPushEnabled = SignalStore.account().isRegistered, alwaysRelayCalls = TextSecurePreferences.isTurnOnly(ApplicationDependencies.getApplication()), censorshipCircumventionState = censorshipCircumventionState, censorshipCircumventionEnabled = getCensorshipCircumventionEnabled(censorshipCircumventionState), showSealedSenderStatusIcon = TextSecurePreferences.isShowUnidentifiedDeliveryIndicatorsEnabled( ApplicationDependencies.getApplication() ), allowSealedSenderFromAnyone = TextSecurePreferences.isUniversalUnidentifiedAccess( ApplicationDependencies.getApplication() ), false ) } private fun getCensorshipCircumventionState(): CensorshipCircumventionState { val countryCode: Int = PhoneNumberFormatter.getLocalCountryCode() val isCountryCodeCensoredByDefault: Boolean = ApplicationDependencies.getSignalServiceNetworkAccess().isCountryCodeCensoredByDefault(countryCode) val enabledState: SettingsValues.CensorshipCircumventionEnabled = SignalStore.settings().censorshipCircumventionEnabled val hasInternet: Boolean = NetworkConstraint.isMet(ApplicationDependencies.getApplication()) val websocketConnected: Boolean = ApplicationDependencies.getSignalWebSocket().webSocketState.firstOrError().blockingGet() == WebSocketConnectionState.CONNECTED return when { SignalStore.internalValues().allowChangingCensorshipSetting() -> { CensorshipCircumventionState.AVAILABLE } isCountryCodeCensoredByDefault && enabledState == SettingsValues.CensorshipCircumventionEnabled.DISABLED -> { CensorshipCircumventionState.AVAILABLE_MANUALLY_DISABLED } isCountryCodeCensoredByDefault -> { CensorshipCircumventionState.AVAILABLE_AUTOMATICALLY_ENABLED } !hasInternet && enabledState != SettingsValues.CensorshipCircumventionEnabled.ENABLED -> { CensorshipCircumventionState.UNAVAILABLE_NO_INTERNET } websocketConnected && enabledState != SettingsValues.CensorshipCircumventionEnabled.ENABLED -> { CensorshipCircumventionState.UNAVAILABLE_CONNECTED } else -> { CensorshipCircumventionState.AVAILABLE } } } private fun getCensorshipCircumventionEnabled(state: CensorshipCircumventionState): Boolean { return when (state) { CensorshipCircumventionState.UNAVAILABLE_CONNECTED, CensorshipCircumventionState.UNAVAILABLE_NO_INTERNET, CensorshipCircumventionState.AVAILABLE_MANUALLY_DISABLED -> { false } CensorshipCircumventionState.AVAILABLE_AUTOMATICALLY_ENABLED -> { true } else -> { SignalStore.settings().censorshipCircumventionEnabled == SettingsValues.CensorshipCircumventionEnabled.ENABLED } } } enum class Event { DISABLE_PUSH_FAILED } class Factory( private val sharedPreferences: SharedPreferences, private val repository: AdvancedPrivacySettingsRepository ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return requireNotNull( modelClass.cast( AdvancedPrivacySettingsViewModel( sharedPreferences, repository ) ) ) } } }
gpl-3.0
ba4cfb031e94dbe7b302a3c70cf3702c
39.068966
164
0.772519
5.096491
false
false
false
false
GunoH/intellij-community
plugins/gradle/java/testSources/execution/GradleDebuggingIntegrationTest.kt
6
12096
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.execution import com.intellij.openapi.util.io.systemIndependentPath import org.assertj.core.api.Assertions.assertThat import org.jetbrains.plugins.gradle.testFramework.util.createBuildFile import org.jetbrains.plugins.gradle.testFramework.util.createSettingsFile import org.jetbrains.plugins.gradle.testFramework.util.importProject import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions import org.junit.Test import java.io.File class GradleDebuggingIntegrationTest : GradleDebuggingIntegrationTestCase() { @Test fun `daemon is started with debug flags only if script debugging is enabled`() { val argsFile = File(projectPath, "args.txt") importProject { withMavenCentral() applyPlugin("'java'") addPostfix(""" import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; task myTask { doFirst { RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); List<String> arguments = runtimeMxBean.getInputArguments(); File file = new File("${argsFile.systemIndependentPath}") file.write(arguments.toString()) } } """.trimIndent()) } ensureDeleted(argsFile) executeRunConfiguration("myTask", isScriptDebugEnabled = true) assertDebugJvmArgs(":myTask", argsFile) ensureDeleted(argsFile) executeRunConfiguration("myTask", isScriptDebugEnabled = false) assertDebugJvmArgs(":myTask", argsFile, shouldBeDebugged = false) } @Test fun `test tasks debugging for modules`() { createPrintArgsClass() createPrintArgsClass("module") val projectArgsFile = createArgsFile() val moduleArgsFile = createArgsFile("module") createSettingsFile { include("module") } createBuildFile("module") { withPrintArgsTask(moduleArgsFile) } importProject { withPrintArgsTask(projectArgsFile) } ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration("printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration(":printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile) assertDebugJvmArgs(":module:printArgs", moduleArgsFile, shouldBeStarted = false) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration(":module:printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration("module:printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration(":printArgs", modulePath = "module") assertDebugJvmArgs(":printArgs", projectArgsFile) assertDebugJvmArgs(":module:printArgs", moduleArgsFile, shouldBeStarted = false) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration("printArgs", modulePath = "module") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) } @Test fun `test tasks debugging for module with dependent tasks`() { createPrintArgsClass() val implicitArgsFile = createArgsFile(name = "implicit-args.txt") val explicitArgsFile = createArgsFile(name = "explicit-args.txt") importProject { withPrintArgsTask(implicitArgsFile, "implicitTask") withPrintArgsTask(explicitArgsFile, "explicitTask", dependsOn = ":implicitTask") } ensureDeleted(implicitArgsFile, explicitArgsFile) executeRunConfiguration("explicitTask") assertDebugJvmArgs(":implicitTask", implicitArgsFile, shouldBeDebugged = false) assertDebugJvmArgs(":explicitTask", explicitArgsFile) ensureDeleted(implicitArgsFile, explicitArgsFile) executeRunConfiguration("explicitTask", isDebugAllEnabled = true) assertDebugJvmArgs(":implicitTask", implicitArgsFile) assertDebugJvmArgs(":explicitTask", explicitArgsFile) } @Test fun `test tasks debugging for module with dependent tasks with same name`() { createPrintArgsClass() createPrintArgsClass("module") val projectArgsFile = createArgsFile() val moduleArgsFile = createArgsFile("module") createSettingsFile { include("module") } createBuildFile("module") { withPrintArgsTask(moduleArgsFile, dependsOn = ":printArgs") } importProject { withPrintArgsTask(projectArgsFile) } ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration("printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration(":module:printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeDebugged = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration("module:printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeDebugged = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration(":printArgs", modulePath = "module") assertDebugJvmArgs(":printArgs", projectArgsFile) assertDebugJvmArgs(":module:printArgs", moduleArgsFile, shouldBeStarted = false) ensureDeleted(projectArgsFile, moduleArgsFile) executeRunConfiguration("printArgs", modulePath = "module") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeDebugged = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) } @Test fun `test tasks debugging for partial matched tasks`() { createPrintArgsClass() val projectArgsFile = createArgsFile() importProject { withPrintArgsTask(projectArgsFile) } ensureDeleted(projectArgsFile, projectArgsFile) executeRunConfiguration("print") assertDebugJvmArgs("printArgs", projectArgsFile) ensureDeleted(projectArgsFile, projectArgsFile) executeRunConfiguration(":print") assertDebugJvmArgs("printArgs", projectArgsFile) ensureDeleted(projectArgsFile, projectArgsFile) executeRunConfiguration("printArgs") assertDebugJvmArgs("printArgs", projectArgsFile) ensureDeleted(projectArgsFile, projectArgsFile) executeRunConfiguration(":printArgs") assertDebugJvmArgs("printArgs", projectArgsFile) } @Test fun `test tasks debugging for tasks that defined in script parameters`() { createPrintArgsClass() val projectArgsFile = createArgsFile() importProject { withPrintArgsTask(projectArgsFile) } ensureDeleted(projectArgsFile) executeRunConfiguration("printArgs", scriptParameters = "print") assertDebugJvmArgs("printArgs", projectArgsFile) ensureDeleted(projectArgsFile) executeRunConfiguration("printArgs", scriptParameters = ":print") assertDebugJvmArgs("printArgs", projectArgsFile) } @Test @TargetVersions("4.9+") fun `test tasks configuration avoidance during debug`() { createPrintArgsClass() val projectArgsFile = createArgsFile() importProject { withPrintArgsTask(projectArgsFile) registerTask("bomb") { call("println", "BOOM!") } } ensureDeleted(projectArgsFile) assertThat(executeRunConfiguration("printArgs")) .doesNotContain("BOOM!") assertDebugJvmArgs("printArgs", projectArgsFile) ensureDeleted(projectArgsFile) assertThat(executeRunConfiguration(":printArgs")) .doesNotContain("BOOM!") assertDebugJvmArgs("printArgs", projectArgsFile) ensureDeleted(projectArgsFile) assertThat(executeRunConfiguration("bomb")) .contains("BOOM!") assertDebugJvmArgs("printArgs", projectArgsFile, shouldBeStarted = false) } @Test @TargetVersions("3.1+") fun `test tasks debugging for composite build`() { createPrintArgsClass() createPrintArgsClass("module") createPrintArgsClass("composite") createPrintArgsClass("composite/module") val projectArgsFile = createArgsFile() val moduleArgsFile = createArgsFile("module") val compositeArgsFile = createArgsFile("composite") val compositeModuleArgsFile = createArgsFile("composite/module") createSettingsFile("composite") { include("module") } createBuildFile("composite") { withPrintArgsTask(compositeArgsFile) } createBuildFile("composite/module") { withPrintArgsTask(compositeModuleArgsFile) } createSettingsFile { include("module") includeBuild("composite") } createBuildFile("module") { withPrintArgsTask(moduleArgsFile) } importProject { withPrintArgsTask(projectArgsFile) } ensureDeleted(projectArgsFile, moduleArgsFile, compositeArgsFile, compositeModuleArgsFile) executeRunConfiguration("printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile) assertDebugJvmArgs(":module:printArgs", moduleArgsFile) assertDebugJvmArgs(":composite:printArgs", compositeArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":composite:module:printArgs", compositeModuleArgsFile, shouldBeStarted = false) if (isGradleNewerOrSameAs("6.9")) { ensureDeleted(projectArgsFile, moduleArgsFile, compositeArgsFile, compositeModuleArgsFile) executeRunConfiguration(":composite:printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":composite:printArgs", compositeArgsFile) assertDebugJvmArgs(":composite:module:printArgs", compositeModuleArgsFile, shouldBeStarted = false) ensureDeleted(projectArgsFile, moduleArgsFile, compositeArgsFile, compositeModuleArgsFile) executeRunConfiguration(":composite:module:printArgs") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":composite:printArgs", compositeArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":composite:module:printArgs", compositeModuleArgsFile) } ensureDeleted(projectArgsFile, moduleArgsFile, compositeArgsFile, compositeModuleArgsFile) executeRunConfiguration("printArgs", modulePath = "composite") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":composite:printArgs", compositeArgsFile) assertDebugJvmArgs(":composite:module:printArgs", compositeModuleArgsFile) ensureDeleted(projectArgsFile, moduleArgsFile, compositeArgsFile, compositeModuleArgsFile) executeRunConfiguration(":printArgs", modulePath = "composite") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":composite:printArgs", compositeArgsFile) assertDebugJvmArgs(":composite:module:printArgs", compositeModuleArgsFile, shouldBeStarted = false) ensureDeleted(projectArgsFile, moduleArgsFile, compositeArgsFile, compositeModuleArgsFile) executeRunConfiguration(":module:printArgs", modulePath = "composite") assertDebugJvmArgs(":printArgs", projectArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":module:printArgs", moduleArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":composite:printArgs", compositeArgsFile, shouldBeStarted = false) assertDebugJvmArgs(":composite:module:printArgs", compositeModuleArgsFile) } }
apache-2.0
c8f76d1da2eb5283ec273d5e7f19e46f
41.149826
140
0.763228
4.645161
false
true
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/FindTransformationMatcher.kt
3
17223
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions.loopToCallChain.result import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isNullExpression import org.jetbrains.kotlin.idea.intentions.loopToCallChain.* import org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence.Condition import org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence.FilterTransformationBase import org.jetbrains.kotlin.idea.intentions.negate import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange import org.jetbrains.kotlin.types.typeUtil.TypeNullability import org.jetbrains.kotlin.types.typeUtil.nullability /** * Matches: * val variable = ... * for (...) { * ... * variable = ... * break * } * or * val variable = ... * for (...) { * ... * variable = ... * } * or * for (...) { * ... * return ... * } * return ... */ object FindTransformationMatcher : TransformationMatcher { override val indexVariableAllowed: Boolean get() = false override val shouldUseInputVariables: Boolean get() = false override fun match(state: MatchingState): TransformationMatch.Result? { return matchWithFilterBefore(state, null) } fun matchWithFilterBefore(state: MatchingState, filterTransformation: FilterTransformationBase?): TransformationMatch.Result? { matchReturn(state, filterTransformation)?.let { return it } when (state.statements.size) { 1 -> { } 2 -> { val breakExpression = state.statements.last() as? KtBreakExpression ?: return null if (breakExpression.targetLoop() != state.outerLoop) return null } else -> return null } val findFirst = state.statements.size == 2 val binaryExpression = state.statements.first() as? KtBinaryExpression ?: return null if (binaryExpression.operationToken != KtTokens.EQ) return null val left = binaryExpression.left ?: return null val right = binaryExpression.right ?: return null val initialization = left.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = true) ?: return null // this should be the only usage of this variable inside the loop if (initialization.variable.countUsages(state.outerLoop) != 1) return null // we do not try to convert anything if the initializer is not compile-time constant because of possible side-effects if (!initialization.initializer.isConstant()) return null val generator = buildFindOperationGenerator( state.outerLoop, state.inputVariable, state.indexVariable, filterTransformation, valueIfFound = right, valueIfNotFound = initialization.initializer, findFirst = findFirst, reformat = state.reformat ) ?: return null val transformation = FindAndAssignTransformation(state.outerLoop, generator, initialization) return TransformationMatch.Result(transformation) } private fun matchReturn(state: MatchingState, filterTransformation: FilterTransformationBase?): TransformationMatch.Result? { val returnInLoop = state.statements.singleOrNull() as? KtReturnExpression ?: return null val returnAfterLoop = state.outerLoop.nextStatement() as? KtReturnExpression ?: return null if (returnInLoop.getLabelName() != returnAfterLoop.getLabelName()) return null val returnValueInLoop = returnInLoop.returnedExpression ?: return null val returnValueAfterLoop = returnAfterLoop.returnedExpression ?: return null val generator = buildFindOperationGenerator( state.outerLoop, state.inputVariable, state.indexVariable, filterTransformation, valueIfFound = returnValueInLoop, valueIfNotFound = returnValueAfterLoop, findFirst = true, reformat = state.reformat ) ?: return null val transformation = FindAndReturnTransformation(state.outerLoop, generator, returnAfterLoop) return TransformationMatch.Result(transformation) } private class FindAndReturnTransformation( override val loop: KtForExpression, private val generator: FindOperationGenerator, private val endReturn: KtReturnExpression ) : ResultTransformation { override val commentSavingRange = PsiChildRange(loop.unwrapIfLabeled(), endReturn) override val presentation: String get() = generator.presentation override val chainCallCount: Int get() = generator.chainCallCount override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression { return generator.generate(chainedCallGenerator) } override fun generateExpressionToReplaceLoopAndCheckErrors(resultCallChain: KtExpression): KtExpression { return KtPsiFactory(resultCallChain).createExpressionByPattern("return $0", resultCallChain, reformat = false) } override fun convertLoop(resultCallChain: KtExpression, commentSavingRangeHolder: CommentSavingRangeHolder): KtExpression { endReturn.returnedExpression!!.replace(resultCallChain) loop.deleteWithLabels() return endReturn } } private class FindAndAssignTransformation( loop: KtForExpression, private val generator: FindOperationGenerator, initialization: VariableInitialization ) : AssignToVariableResultTransformation(loop, initialization) { override val presentation: String get() = generator.presentation override val chainCallCount: Int get() = generator.chainCallCount override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression { return generator.generate(chainedCallGenerator) } } private abstract class FindOperationGenerator( val functionName: String, val hasFilter: Boolean, val chainCallCount: Int = 1 ) { constructor(other: FindOperationGenerator) : this(other.functionName, other.hasFilter, other.chainCallCount) val presentation: String get() = functionName + (if (hasFilter) "{}" else "()") abstract fun generate(chainedCallGenerator: ChainedCallGenerator): KtExpression } private class SimpleGenerator( functionName: String, private val inputVariable: KtCallableDeclaration, private val filter: KtExpression?, private val argument: KtExpression? = null ) : FindOperationGenerator(functionName, filter != null) { override fun generate(chainedCallGenerator: ChainedCallGenerator): KtExpression { return generateChainedCall(functionName, chainedCallGenerator, inputVariable, filter, argument) } } private class NegatingFindOpetationGenerator(val generator: FindOperationGenerator) : FindOperationGenerator(generator) { override fun generate(chainedCallGenerator: ChainedCallGenerator): KtExpression = generator.generate(chainedCallGenerator).negate() } private fun generateChainedCall( stdlibFunName: String, chainedCallGenerator: ChainedCallGenerator, inputVariable: KtCallableDeclaration, filter: KtExpression?, argument: KtExpression? = null ): KtExpression { return if (filter == null) { if (argument != null) { chainedCallGenerator.generate("$stdlibFunName($0)", argument) } else { chainedCallGenerator.generate("$stdlibFunName()") } } else { val lambda = generateLambda(inputVariable, filter, chainedCallGenerator.reformat) if (argument != null) { chainedCallGenerator.generate("$stdlibFunName($0) $1:'{}'", argument, lambda) } else { chainedCallGenerator.generate("$stdlibFunName $0:'{}'", lambda) } } } private fun buildFindOperationGenerator( loop: KtForExpression, inputVariable: KtCallableDeclaration, indexVariable: KtCallableDeclaration?, filterTransformation: FilterTransformationBase?, valueIfFound: KtExpression, valueIfNotFound: KtExpression, findFirst: Boolean, reformat: Boolean ): FindOperationGenerator? { assert(valueIfFound.isPhysical) assert(valueIfNotFound.isPhysical) val filterCondition = filterTransformation?.effectiveCondition if (indexVariable != null) { if (filterTransformation == null) return null // makes no sense, indexVariable must be always null if (filterTransformation.indexVariable != null) return null // cannot use index in condition for indexOfFirst/indexOfLast //TODO: what if value when not found is not "-1"? if (valueIfFound.isVariableReference(indexVariable) && valueIfNotFound.text == "-1") { val filterExpression = filterCondition!!.asExpression(reformat) val containsArgument = filterExpression.isFilterForContainsOperation(inputVariable, loop) return if (containsArgument != null) { val functionName = if (findFirst) "indexOf" else "lastIndexOf" SimpleGenerator(functionName, inputVariable, null, containsArgument) } else { val functionName = if (findFirst) "indexOfFirst" else "indexOfLast" SimpleGenerator(functionName, inputVariable, filterExpression) } } return null } else { val inputVariableCanHoldNull = (inputVariable.unsafeResolveToDescriptor() as VariableDescriptor).type.nullability() != TypeNullability.NOT_NULL fun FindOperationGenerator.useElvisOperatorIfNeeded(): FindOperationGenerator? { if (valueIfNotFound.isNullExpression()) return this // we cannot use ?: if found value can be null if (inputVariableCanHoldNull) return null return object : FindOperationGenerator(this) { override fun generate(chainedCallGenerator: ChainedCallGenerator): KtExpression { val generated = [email protected](chainedCallGenerator) return KtPsiFactory(generated).createExpressionByPattern( "$0\n ?: $1", generated, valueIfNotFound, reformat = chainedCallGenerator.reformat ) } } } when { valueIfFound.isVariableReference(inputVariable) -> { val functionName = if (findFirst) "firstOrNull" else "lastOrNull" val generator = SimpleGenerator(functionName, inputVariable, filterCondition?.asExpression(reformat)) return generator.useElvisOperatorIfNeeded() } valueIfFound.isTrueConstant() && valueIfNotFound.isFalseConstant() -> { return buildFoundFlagGenerator(loop, inputVariable, filterCondition, negated = false, reformat = reformat) } valueIfFound.isFalseConstant() && valueIfNotFound.isTrueConstant() -> { return buildFoundFlagGenerator(loop, inputVariable, filterCondition, negated = true, reformat = reformat) } inputVariable.hasUsages(valueIfFound) -> { if (!findFirst) return null // too dangerous because of side effects // specially handle the case when the result expression is "<input variable>.<some call>" or "<input variable>?.<some call>" val qualifiedExpression = valueIfFound as? KtQualifiedExpression if (qualifiedExpression != null) { val receiver = qualifiedExpression.receiverExpression val selector = qualifiedExpression.selectorExpression if (receiver.isVariableReference(inputVariable) && selector != null && !inputVariable.hasUsages(selector)) { return object : FindOperationGenerator("firstOrNull", filterCondition != null, chainCallCount = 2) { override fun generate(chainedCallGenerator: ChainedCallGenerator): KtExpression { val findFirstCall = generateChainedCall( functionName, chainedCallGenerator, inputVariable, filterCondition?.asExpression(reformat) ) return chainedCallGenerator.generate("$0", selector, receiver = findFirstCall, safeCall = true) } }.useElvisOperatorIfNeeded() } } // in case of nullable input variable we cannot distinguish by the result of "firstOrNull" whether nothing was found or 'null' was found if (inputVariableCanHoldNull) return null return object : FindOperationGenerator("firstOrNull", filterCondition != null, chainCallCount = 2 /* also includes "let" */) { override fun generate(chainedCallGenerator: ChainedCallGenerator): KtExpression { val findFirstCall = generateChainedCall( functionName, chainedCallGenerator, inputVariable, filterCondition?.asExpression(reformat) ) val letBody = generateLambda(inputVariable, valueIfFound, chainedCallGenerator.reformat) return chainedCallGenerator.generate("let $0:'{}'", letBody, receiver = findFirstCall, safeCall = true) } }.useElvisOperatorIfNeeded() } else -> { val generator = buildFoundFlagGenerator(loop, inputVariable, filterCondition, negated = false, reformat = reformat) return object : FindOperationGenerator(generator) { override fun generate(chainedCallGenerator: ChainedCallGenerator): KtExpression { val chainedCall = generator.generate(chainedCallGenerator) return KtPsiFactory(chainedCall).createExpressionByPattern( "if ($0) $1 else $2", chainedCall, valueIfFound, valueIfNotFound, reformat = chainedCallGenerator.reformat ) } } } } } } private fun buildFoundFlagGenerator( loop: KtForExpression, inputVariable: KtCallableDeclaration, filter: Condition?, negated: Boolean, reformat: Boolean ): FindOperationGenerator { if (filter == null) { return SimpleGenerator(if (negated) "none" else "any", inputVariable, null) } val filterExpression = filter.asExpression(reformat) val containsArgument = filterExpression.isFilterForContainsOperation(inputVariable, loop) if (containsArgument != null) { val generator = SimpleGenerator("contains", inputVariable, null, containsArgument) return if (negated) NegatingFindOpetationGenerator(generator) else generator } if (filterExpression is KtPrefixExpression && filterExpression.operationToken == KtTokens.EXCL && negated) { return SimpleGenerator("all", inputVariable, filter.asNegatedExpression(reformat)) } return SimpleGenerator(if (negated) "none" else "any", inputVariable, filterExpression) } private fun KtExpression.isFilterForContainsOperation(inputVariable: KtCallableDeclaration, loop: KtForExpression): KtExpression? { if (this !is KtBinaryExpression) return null if (operationToken != KtTokens.EQEQ) return null return when { left.isVariableReference(inputVariable) -> right?.takeIf { it.isStableInLoop(loop, false) } right.isVariableReference(inputVariable) -> left?.takeIf { it.isStableInLoop(loop, false) } else -> null } } }
apache-2.0
c84cd7a954020fd070c09ea21618af1f
45.423181
158
0.63392
5.916524
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/util/indexing/diagnostic/ProjectIndexingHistoryFusReporterListener.kt
5
8148
// 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.diagnostic import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.ObjectEventData import com.intellij.internal.statistic.eventLog.events.ObjectListEventField import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.internal.statistic.utils.StatisticsUtil import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.project.Project import com.intellij.util.indexing.diagnostic.dto.toMillis import java.util.* import java.util.concurrent.TimeUnit import kotlin.math.roundToLong internal class ProjectIndexingHistoryFusReporterListener : ProjectIndexingHistoryListener { override fun onStartedIndexing(projectIndexingHistory: ProjectIndexingHistory) { ProjectIndexingHistoryFusReporter.reportIndexingStarted( projectIndexingHistory.project, projectIndexingHistory.indexingSessionId ) } override fun onFinishedIndexing(projectIndexingHistory: ProjectIndexingHistory) { val scanningTime = projectIndexingHistory.times.scanFilesDuration.toMillis() val numberOfFileProviders = projectIndexingHistory.scanningStatistics.size val numberOfScannedFiles = projectIndexingHistory.scanningStatistics.sumOf { it.numberOfScannedFiles } val numberOfFilesIndexedByExtensionsDuringScan = projectIndexingHistory.scanningStatistics.sumOf { it.numberOfFilesFullyIndexedByInfrastructureExtensions } val numberOfFilesIndexedByExtensionsWithLoadingContent = projectIndexingHistory.providerStatistics.sumOf { it.totalNumberOfFilesFullyIndexedByExtensions } val numberOfFilesIndexedWithLoadingContent = projectIndexingHistory.providerStatistics.sumOf { it.totalNumberOfIndexedFiles } val totalContentLoadingTime = projectIndexingHistory.totalStatsPerFileType.values.sumOf { it.totalContentLoadingTimeInAllThreads } val totalContentData = projectIndexingHistory.totalStatsPerFileType.values.sumOf { it.totalBytes } val averageContentLoadingSpeed = calculateReadSpeed(totalContentData, totalContentLoadingTime) val contentLoadingSpeedByFileType = HashMap<FileType, Long>() projectIndexingHistory.totalStatsPerFileType.forEach { (fileType, stats) -> if (stats.totalContentLoadingTimeInAllThreads != 0L && stats.totalBytes != 0L) { contentLoadingSpeedByFileType[FileTypeManager.getInstance().getStdFileType(fileType)] = calculateReadSpeed(stats.totalBytes, stats.totalContentLoadingTimeInAllThreads) } } ProjectIndexingHistoryFusReporter.reportIndexingFinished( projectIndexingHistory.project, projectIndexingHistory.indexingSessionId, projectIndexingHistory.times.scanningType, projectIndexingHistory.times.totalUpdatingTime.toMillis(), projectIndexingHistory.times.indexingDuration.toMillis(), scanningTime, numberOfFileProviders, numberOfScannedFiles, numberOfFilesIndexedByExtensionsDuringScan, numberOfFilesIndexedByExtensionsWithLoadingContent, numberOfFilesIndexedWithLoadingContent, averageContentLoadingSpeed, contentLoadingSpeedByFileType ) } /** * @return speed as bytes per second * */ private fun calculateReadSpeed(bytes: BytesNumber, loadingTime: TimeNano): Long { if (bytes == 0L || loadingTime == 0L) return 0L val nanoSecondInOneSecond = TimeUnit.SECONDS.toNanos(1) return if (bytes * nanoSecondInOneSecond > 0) // avoid hitting overflow; possible if loaded more then 9 223 372 037 bytes // as `loadingTime` in nanoseconds tend to be much bigger value then `bytes` prefer to divide as second step (bytes * nanoSecondInOneSecond) / loadingTime else // do not use by default to avoid unnecessary conversions ((bytes.toDouble() / loadingTime) * nanoSecondInOneSecond).roundToLong() } } object ProjectIndexingHistoryFusReporter : CounterUsagesCollector() { private val GROUP = EventLogGroup("indexing.statistics", 6) override fun getGroup() = GROUP private val indexingSessionId = EventFields.Long("indexing_session_id") private val isFullRescanning = EventFields.Boolean("is_full") private val scanningType = EventFields.Enum<ScanningType>("type") { type -> type.name.lowercase(Locale.ENGLISH) } private val totalTime = EventFields.Long("total_time") private val indexingTime = EventFields.Long("indexing_time") private val scanningTime = EventFields.Long("scanning_time") private val numberOfFileProviders = EventFields.Int("number_of_file_providers") private val numberOfScannedFiles = EventFields.Int("number_of_scanned_files") private val numberOfFilesIndexedByExtensionsDuringScan = EventFields.Int("number_of_files_indexed_by_extensions_during_scan") private val numberOfFilesIndexedByExtensionsWithLoadingContent = EventFields.Int("number_of_files_indexed_by_extensions_with_loading_content") private val numberOfFilesIndexedWithLoadingContent = EventFields.Int("number_of_files_indexed_with_loading_content") private val averageContentLoadingSpeed = EventFields.Long("average_content_loading_speed_bps") private val contentLoadingSpeedForFileType = EventFields.Long("average_content_loading_speed_for_file_type_bps") private val contentLoadingSpeedByFileType = ObjectListEventField("average_content_loading_speeds_by_file_type", EventFields.FileType, contentLoadingSpeedForFileType) private val indexingStarted = GROUP.registerVarargEvent( "started", indexingSessionId ) private val indexingFinished = GROUP.registerVarargEvent( "finished", indexingSessionId, isFullRescanning, scanningType, totalTime, indexingTime, scanningTime, numberOfFileProviders, numberOfScannedFiles, numberOfFilesIndexedByExtensionsDuringScan, numberOfFilesIndexedByExtensionsWithLoadingContent, numberOfFilesIndexedWithLoadingContent, averageContentLoadingSpeed, contentLoadingSpeedByFileType ) fun reportIndexingStarted(project: Project, indexingSessionId: Long) { indexingStarted.log( project, this.indexingSessionId.with(indexingSessionId) ) } fun reportIndexingFinished( project: Project, indexingSessionId: Long, scanningType: ScanningType, totalTime: Long, indexingTime: Long, scanningTime: Long, numberOfFileProviders: Int, numberOfScannedFiles: Int, numberOfFilesIndexedByExtensionsDuringScan: Int, numberOfFilesIndexedByExtensionsWithLoadingContent: Int, numberOfFilesIndexedWithLoadingContent: Int, averageContentLoadingSpeed: Long, contentLoadingSpeedByFileType: Map<FileType, Long> ) { indexingFinished.log( project, this.indexingSessionId.with(indexingSessionId), this.isFullRescanning.with(scanningType.isFull), this.scanningType.with(scanningType), this.totalTime.with(totalTime), this.indexingTime.with(indexingTime), this.scanningTime.with(scanningTime), this.numberOfFileProviders.with(numberOfFileProviders), this.numberOfScannedFiles.with(StatisticsUtil.roundToHighestDigit(numberOfScannedFiles)), this.numberOfFilesIndexedByExtensionsDuringScan.with(StatisticsUtil.roundToHighestDigit(numberOfFilesIndexedByExtensionsDuringScan)), this.numberOfFilesIndexedByExtensionsWithLoadingContent.with( StatisticsUtil.roundToHighestDigit(numberOfFilesIndexedByExtensionsWithLoadingContent)), this.numberOfFilesIndexedWithLoadingContent.with(StatisticsUtil.roundToHighestDigit(numberOfFilesIndexedWithLoadingContent)), this.averageContentLoadingSpeed.with(averageContentLoadingSpeed), this.contentLoadingSpeedByFileType.with(contentLoadingSpeedByFileType.map { entry -> ObjectEventData(EventFields.FileType.with(entry.key), contentLoadingSpeedForFileType.with(entry.value)) }) ) } }
apache-2.0
312e732daa8da46f62a1068df84f6c40
45.833333
139
0.798969
5.762376
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/KotlinTypeArgumentInfoHandler.kt
4
4607
// 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.parameterInfo import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.core.resolveCandidates import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.calls.util.getCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.typeUtil.TypeNullability import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny import org.jetbrains.kotlin.types.typeUtil.nullability class KotlinClassConstructorInfoHandler : KotlinTypeArgumentInfoHandlerBase<ClassConstructorDescriptor>() { override fun fetchTypeParameters(parameterOwner: ClassConstructorDescriptor): List<TypeParameterDescriptor> = parameterOwner.typeParameters override fun findParameterOwners(argumentList: KtTypeArgumentList): Collection<ClassConstructorDescriptor>? { val userType = argumentList.parent as? KtUserType ?: return null val descriptors = userType.referenceExpression?.resolveMainReferenceToDescriptors()?.mapNotNull { it as? ClassConstructorDescriptor } return descriptors?.takeIf { it.isNotEmpty() } } override fun getArgumentListAllowedParentClasses() = setOf(KtUserType::class.java) } class KotlinClassTypeArgumentInfoHandler : KotlinTypeArgumentInfoHandlerBase<ClassDescriptor>() { override fun fetchTypeParameters(parameterOwner: ClassDescriptor) = parameterOwner.typeConstructor.parameters override fun findParameterOwners(argumentList: KtTypeArgumentList): Collection<ClassDescriptor>? { val userType = argumentList.parent as? KtUserType ?: return null val descriptors = userType.referenceExpression?.resolveMainReferenceToDescriptors()?.mapNotNull { it as? ClassDescriptor } return descriptors?.takeIf { it.isNotEmpty() } } override fun getArgumentListAllowedParentClasses() = setOf(KtUserType::class.java) } class KotlinFunctionTypeArgumentInfoHandler : KotlinTypeArgumentInfoHandlerBase<FunctionDescriptor>() { override fun fetchTypeParameters(parameterOwner: FunctionDescriptor) = parameterOwner.typeParameters override fun findParameterOwners(argumentList: KtTypeArgumentList): Collection<FunctionDescriptor>? { val callElement = argumentList.parent as? KtCallElement ?: return null val bindingContext = argumentList.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) val call = callElement.getCall(bindingContext) ?: return null val candidates = call.resolveCandidates(bindingContext, callElement.getResolutionFacade()) return candidates .map { it.resultingDescriptor } .distinctBy { buildPresentation(fetchCandidateInfo(it), -1).first } } override fun getArgumentListAllowedParentClasses() = setOf(KtCallElement::class.java) } abstract class KotlinTypeArgumentInfoHandlerBase<TParameterOwner : Any> : AbstractKotlinTypeArgumentInfoHandler() { protected abstract fun findParameterOwners(argumentList: KtTypeArgumentList): Collection<TParameterOwner>? protected abstract fun fetchTypeParameters(parameterOwner: TParameterOwner): List<TypeParameterDescriptor> override fun fetchCandidateInfos(argumentList: KtTypeArgumentList): List<CandidateInfo>? { val parameterOwners = findParameterOwners(argumentList) ?: return null return parameterOwners.map { fetchCandidateInfo(it) } } protected fun fetchCandidateInfo(parameterOwner: TParameterOwner): CandidateInfo { val parameters = fetchTypeParameters(parameterOwner) return CandidateInfo(parameters.map(::fetchTypeParameterInfo)) } private fun fetchTypeParameterInfo(parameter: TypeParameterDescriptor): TypeParameterInfo { val upperBounds = parameter.upperBounds.map { val isNullableAnyOrFlexibleAny = it.isAnyOrNullableAny() && it.nullability() != TypeNullability.NOT_NULL val renderedType = DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(it) UpperBoundInfo(isNullableAnyOrFlexibleAny, renderedType) } return TypeParameterInfo(parameter.name.asString(), parameter.isReified, parameter.variance, upperBounds) } }
apache-2.0
4cd72e06523d8a4e923eed00693de0ae
55.182927
158
0.790753
5.471496
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ConvertExtensionToFunctionTypeFix.kt
3
2892
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.getReturnTypeFromFunctionType import org.jetbrains.kotlin.builtins.isExtensionFunctionType import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtTypeReference import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType class ConvertExtensionToFunctionTypeFix(element: KtTypeReference, type: KotlinType) : KotlinQuickFixAction<KtTypeReference>(element) { private val targetTypeStringShort = type.renderType(IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS) private val targetTypeStringLong = type.renderType(IdeDescriptorRenderers.SOURCE_CODE) override fun getText() = KotlinBundle.message("convert.supertype.to.0", targetTypeStringShort) override fun getFamilyName() = KotlinBundle.message("convert.extension.function.type.to.regular.function.type") override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val replaced = element.replaced(KtPsiFactory(project).createType(targetTypeStringLong)) ShortenReferences.DEFAULT.process(replaced) } private fun KotlinType.renderType(renderer: DescriptorRenderer) = buildString { append('(') arguments.dropLast(1).joinTo(this@buildString, ", ") { renderer.renderType(it.type) } append(") -> ") append(renderer.renderType([email protected]())) } companion object Factory : KotlinIntentionActionsFactory() { override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> { val casted = Errors.SUPERTYPE_IS_EXTENSION_FUNCTION_TYPE.cast(diagnostic) val element = casted.psiElement val type = element.analyze(BodyResolveMode.PARTIAL).get(BindingContext.TYPE, element) ?: return emptyList() if (!type.isExtensionFunctionType) return emptyList() return listOf(ConvertExtensionToFunctionTypeFix(element, type)) } } }
apache-2.0
039e751a3913136d8ff6264b6765e262
49.736842
158
0.783541
4.764415
false
false
false
false
paul58914080/ff4j-spring-boot-starter-parent
ff4j-spring-boot-web-api/src/main/kotlin/org/ff4j/spring/boot/web/api/resources/PropertyStoreResource.kt
1
4203
/*- * #%L * ff4j-spring-boot-web-api * %% * Copyright (C) 2013 - 2019 FF4J * %% * 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. * #L% */ package org.ff4j.spring.boot.web.api.resources import io.swagger.annotations.Api import io.swagger.annotations.ApiOperation import io.swagger.annotations.ApiResponse import io.swagger.annotations.ApiResponses import org.ff4j.services.PropertyStoreServices import org.ff4j.services.constants.FeatureConstants.RESOURCE_CLEAR_CACHE import org.ff4j.services.constants.FeatureConstants.RESOURCE_FF4J_PROPERTY_STORE import org.ff4j.services.constants.FeatureConstants.RESOURCE_PROPERTIES import org.ff4j.services.domain.CacheApiBean import org.ff4j.services.domain.PropertyApiBean import org.ff4j.services.domain.PropertyStoreApiBean import org.ff4j.web.FF4jWebConstants.RESOURCE_CACHE import org.ff4j.web.FF4jWebConstants.STORE_CLEAR import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus.NO_CONTENT import org.springframework.http.MediaType.APPLICATION_JSON_VALUE import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController /** * Created by Paul * * @author [Paul Williams](mailto:[email protected]) */ @Api(tags = ["PropertyStore"], description = "The API for accessing the store for all properties") @RestController @RequestMapping(value = [RESOURCE_FF4J_PROPERTY_STORE]) class PropertyStoreResource(@Autowired val propertyStoreServices: PropertyStoreServices) { @ApiOperation(value = "Display information regarding Properties Store", response = PropertyStoreApiBean::class) @ApiResponses(ApiResponse(code = 200, message = "status of current properties store")) @GetMapping(produces = [APPLICATION_JSON_VALUE]) fun getPropertyStore(): PropertyStoreApiBean = propertyStoreServices.getPropertyStore() @ApiOperation(value = "Display all the Properties", response = PropertyApiBean::class) @ApiResponses(ApiResponse(code = 200, message = "get all Properties")) @GetMapping(value = [RESOURCE_PROPERTIES], produces = [APPLICATION_JSON_VALUE]) fun getAllProperties(): List<PropertyApiBean> = propertyStoreServices.getAllProperties() @ApiOperation(value = "Display information related to Cache") @ApiResponses( ApiResponse(code = 200, message = "Gets the cached properties", response = CacheApiBean::class), ApiResponse(code = 404, message = "property store is not cached")) @GetMapping(value = [("/$RESOURCE_CACHE")], produces = [APPLICATION_JSON_VALUE]) fun getPropertiesFromCache(): CacheApiBean = propertyStoreServices.getPropertiesFromCache() @ApiOperation(value = "Delete all Properties in store") @ApiResponses(ApiResponse(code = 204, message = "all properties have been deleted", response = ResponseEntity::class)) @DeleteMapping(value = [("/$STORE_CLEAR")]) fun deleteAllProperties(): ResponseEntity<Void> { propertyStoreServices.deleteAllProperties() return ResponseEntity(NO_CONTENT) } @ApiOperation(value = "Clear cache", response = ResponseEntity::class) @ApiResponses( ApiResponse(code = 204, message = "cache is cleared"), ApiResponse(code = 404, message = "property store is not cached")) @DeleteMapping(value = [RESOURCE_CLEAR_CACHE]) fun clearCachedPropertyStore(): ResponseEntity<Void> { propertyStoreServices.clearCachedPropertyStore() return ResponseEntity(NO_CONTENT) } }
apache-2.0
2ee29def536b37009afa6f04c6e14686
46.224719
122
0.763978
4.254049
false
false
false
false
rbatista/algorithms
challenges/hacker-rank/kotlin/src/main/kotlin/com/raphaelnegrisoli/hackerrank/strings/SherlockAndTheValidString.kt
1
990
/** * https://www.hackerrank.com/challenges/sherlock-and-valid-string/ */ package com.raphaelnegrisoli.hackerrank.strings import kotlin.math.absoluteValue fun main(args: Array<String>) { val str = readLine().orEmpty().trim() val frequencies = mutableMapOf<Char, Long>() for (char in str) { frequencies[char] = (frequencies[char] ?: 0) + 1 } val counts = mutableMapOf<Long, Long>() for ((_, value) in frequencies) { counts[value] = (counts[value] ?: 0) + 1 } val valid = when { counts.size == 1 -> true counts.size > 2 -> false else -> { val it = counts.iterator() val (key1, value1) = it.next() val (key2, value2) = it.next() ((key1 - key2).absoluteValue == 1L && (value1 == 1L || value2 == 1L)) || (key1 == 1L && value1 == 1L) || (key2 == 1L && value2 == 1L) } } println(if (valid) "YES" else "NO") }
mit
696b8985dff24c95961e6b277c9e7a55
23.775
81
0.523232
3.523132
false
false
false
false
mikepenz/MaterialDrawer
materialdrawer/src/main/java/com/mikepenz/materialdrawer/model/DividerDrawerItem.kt
1
1739
package com.mikepenz.materialdrawer.model import android.view.View import androidx.annotation.LayoutRes import androidx.core.view.ViewCompat import androidx.recyclerview.widget.RecyclerView import com.mikepenz.materialdrawer.R import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem import com.mikepenz.materialdrawer.util.getDividerColor /** * Describes a [IDrawerItem] acting as a divider in between items */ open class DividerDrawerItem : AbstractDrawerItem<DividerDrawerItem, DividerDrawerItem.ViewHolder>() { override val type: Int get() = R.id.material_drawer_item_divider override val layoutRes: Int @LayoutRes get() = R.layout.material_drawer_item_divider override fun bindView(holder: ViewHolder, payloads: List<Any>) { super.bindView(holder, payloads) val ctx = holder.itemView.context //set the identifier from the drawerItem here. It can be used to run tests holder.itemView.id = hashCode() //define how the divider should look like holder.itemView.isClickable = false holder.itemView.isEnabled = false holder.itemView.minimumHeight = 1 ViewCompat.setImportantForAccessibility(holder.itemView, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO) //set the color for the divider holder.itemView.setBackgroundColor(ctx.getDividerColor()) //call the onPostBindView method to trigger post bind view actions (like the listener to modify the item if required) onPostBindView(this, holder.itemView) } override fun getViewHolder(v: View): ViewHolder { return ViewHolder(v) } class ViewHolder internal constructor(view: View) : RecyclerView.ViewHolder(view) }
apache-2.0
be2a7370ea6b993969206de583aa856f
35.229167
125
0.736055
4.764384
false
false
false
false
fossasia/rp15
app/src/main/java/org/fossasia/openevent/general/utils/extensions/ViewExt.kt
2
771
package org.fossasia.openevent.general.utils.extensions import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.view.View import androidx.core.view.isVisible fun View.hideWithFading(duration: Long = 200L) { alpha = 1f animate().alpha(0f) .setDuration(duration) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?, isReverse: Boolean) { isVisible = false } override fun onAnimationCancel(animation: Animator?) { isVisible = false } }) } fun View.showWithFading(duration: Long = 200L) { alpha = 0f isVisible = true animate().alpha(1f).duration = duration }
apache-2.0
5027f491ef2fa2d629d970ac18b7c978
28.653846
83
0.662776
4.508772
false
false
false
false
ucpdh23/Servant
src/main/kotlin/es/xan/servantv3/sensors/SensorVerticle.kt
1
2417
package es.xan.servantv3.sensors import es.xan.servantv3.Constant import es.xan.servantv3.AbstractServantVerticle import io.vertx.core.logging.LoggerFactory import es.xan.servantv3.messages.Sensor import es.xan.servantv3.Action import io.vertx.core.json.JsonObject import io.vertx.core.eventbus.Message import es.xan.servantv3.MessageBuilder import es.xan.servantv3.SSHUtils class SensorVerticle : AbstractServantVerticle(Constant.SENSOR_VERTICLE) { companion object { val LOG = LoggerFactory.getLogger(SensorVerticle::class.java.name) } init { supportedActions(Actions::class.java) } enum class Actions(val clazz : Class<*>? ) : Action { RESET_SENSOR(Sensor::class.java) ; } val mHost : String by lazy { config().getJsonObject("SensorVerticle").getString("server", "localhost") } val mLogin : String by lazy { config().getJsonObject("SensorVerticle").getString("usr", "guest") } val mPassword : String by lazy { config().getJsonObject("SensorVerticle").getString("pws", "guest") } val mSensors : Map<String, String> by lazy { HashMap<String,String>().apply { config().getJsonObject("SensorVerticle").getJsonArray("items").forEach{ it -> val item = it as JsonObject val name = item.getString("name").decapitalize() val command = item.getString("command") LOG.info("putting [$name]->[$command]") put(name, command) } } }; fun reset_sensor(sensor : Sensor , message : Message<Any> ) { LOG.info("Asking to reset sensor [{}]", sensor.sensor); val item = sensor.sensor.decapitalize(); val sensorsToReset = when (item) { "all" -> this.mSensors.keys; in mSensors.keys -> setOf(item); else -> { val builder = MessageBuilder.createReply() builder.setError(); builder.setMessage("Options [$mSensors.keys]") message.reply(builder.build()) return; } } val resetedWithError = sensorsToReset.filter { it -> val command = mSensors.get(it); try { SSHUtils.runRemoteCommand(mHost, mLogin, mPassword, command); false } catch (e: Throwable) { LOG.warn("Problems trying to manage ssh remote command [$command]", e); true } } val reply = MessageBuilder.createReply().apply { when { resetedWithError.isEmpty() -> setOk() else -> { setError() setMessage("Problems reseting items [$resetedWithError]") } } } message.reply(reply.build()); } }
mit
353bfa1a8b24aecbe221f0e1bb3828d4
27.785714
106
0.686802
3.41867
false
false
false
false
square/sqldelight
sqldelight-compiler/src/main/kotlin/com/squareup/sqldelight/core/lang/psi/InsertStmtValuesMixin.kt
1
2043
package com.squareup.sqldelight.core.lang.psi import com.alecstrong.sql.psi.core.SqlAnnotationHolder import com.alecstrong.sql.psi.core.psi.SqlColumnName import com.alecstrong.sql.psi.core.psi.impl.SqlInsertStmtValuesImpl import com.alecstrong.sql.psi.core.psi.mixins.ColumnDefMixin import com.intellij.lang.ASTNode import com.squareup.sqldelight.core.lang.acceptsTableInterface import com.squareup.sqldelight.core.psi.SqlDelightInsertStmtValues open class InsertStmtValuesMixin( node: ASTNode ) : SqlInsertStmtValuesImpl(node), SqlDelightInsertStmtValues { override fun annotate(annotationHolder: SqlAnnotationHolder) { val parent = parent ?: return if (parent.acceptsTableInterface()) { val table = tableAvailable(this, parent.tableName.name).firstOrNull() ?: return val columns = table.columns.map { (it.element as SqlColumnName).name } val setColumns = if (parent.columnNameList.isEmpty()) { columns } else { parent.columnNameList.mapNotNull { it.name } } val needsDefaultValue = table.columns .filter { (element, _) -> element is SqlColumnName && element.name !in setColumns && !(element.parent as ColumnDefMixin).hasDefaultValue() } .map { it.element as SqlColumnName } if (needsDefaultValue.size == 1) { annotationHolder.createErrorAnnotation( parent, "Cannot populate default value for column " + "${needsDefaultValue.first().name}, it must be specified in insert statement." ) } else if (needsDefaultValue.size > 1) { annotationHolder.createErrorAnnotation( parent, "Cannot populate default values for columns " + "(${needsDefaultValue.joinToString { it.name }}), they must be specified in insert statement." ) } // This is going to break error handling in sqlite-psi so just omit the superclass annotator. return } super.annotate(annotationHolder) } }
apache-2.0
8ed9e312f73b1d73a5dbdc35193d7af9
36.833333
106
0.685267
4.57047
false
false
false
false
serorigundam/numeri3
app/src/main/kotlin/net/ketc/numeri/presentation/presenter/activity/TweetPresenter.kt
1
4617
package net.ketc.numeri.presentation.presenter.activity import android.app.Service import android.content.Intent import net.ketc.numeri.presentation.view.activity.TweetActivityInterface import android.content.ComponentName import android.content.ServiceConnection import android.os.Bundle import android.os.IBinder import net.ketc.numeri.domain.android.service.ITweetService import net.ketc.numeri.domain.android.service.TweetService import net.ketc.numeri.domain.inject import net.ketc.numeri.domain.model.TwitterUser import net.ketc.numeri.domain.model.cache.withUser import net.ketc.numeri.domain.service.OAuthService import net.ketc.numeri.domain.service.TwitterClient import net.ketc.numeri.util.rx.MySchedulers import org.jetbrains.anko.toast import javax.inject.Inject class TweetPresenter(override val activity: TweetActivityInterface) : AutoDisposablePresenter<TweetActivityInterface>() { @Inject lateinit var oAuthService: OAuthService private var clients: List<Pair<TwitterClient, TwitterUser>> = emptyList() private lateinit var tweetService: ITweetService private var clientId: Long = -1 private val mentionRegexList = ArrayList<Regex>() private val connection = object : ServiceConnection { override fun onServiceDisconnected(name: ComponentName?) { } override fun onServiceConnected(name: ComponentName?, service: IBinder?) { service ?: return tweetService = (service as ITweetService.Binder).getService() activity.isSendTweetButtonEnabled = true } } init { inject() } override fun initialize(savedInstanceState: Bundle?) { super.initialize(savedInstanceState) singleTask(MySchedulers.twitter) { oAuthService.clients().map { it.withUser() } } error { ctx.toast("error") } success { clients = it initializeInternal(savedInstanceState) val intent = Intent(ctx, TweetService::class.java) ctx.startService(intent) ctx.bindService(intent, connection, Service.BIND_AUTO_CREATE) } } private fun initializeInternal(savedInstanceState: Bundle?) { val id = activity.defaultClientId val user = clients.firstOrNull { it.second.id == id }?.second ?: clients.firstOrNull()?.second ?: throw IllegalArgumentException() setTweetUser(user.id) if (savedInstanceState == null) { setReplyToScreenName(user) } } private fun setReplyToScreenName(user: TwitterUser) { val replyToStatus = activity.replyToStatus ?: return val replyToScreenName = "@" + replyToStatus.user.screenName val mentionEntities = replyToStatus.userMentionEntities val mentions = mentionEntities.filter { it.screenName != user.screenName }.joinToString { "@${it.screenName} " } activity.setReplyInfo("reply to $replyToScreenName") val text = activity.text activity.text = "$replyToScreenName $mentions $text " mentionRegexList.addAll(mentionEntities.map { "@$it ?".toRegex() }) mentionRegexList.add("$replyToScreenName ?".toRegex()) } fun sendTweet() { val clientPair = clients.firstOrNull { it.first.id == clientId } ?: throw IllegalArgumentException() val client = clientPair.first val clientUser = clientPair.second val replyToStatusId = activity.replyToStatus?.id tweetService.sendTweet(client, clientUser, activity.text, replyToStatusId, activity.mediaList) activity.clear() activity.finish() } fun setTweetUser(clientId: Long) { val user = clients.map { it.second }.firstOrNull { it.id == clientId } ?: throw IllegalArgumentException() activity.setUserIcon(user) this.clientId = clientId } fun onClickSelectUserButton() { clients.takeIf { it.isNotEmpty() } ?: return activity.showSelectUserDialog(clients.map { it.second }) } fun checkRemaining() { val remaining = activity.text.remaining() activity.setRemaining(remaining) } private fun String.remaining(): Int { var s = this // mentionRegexList.forEach { // s = s.replace(it, "") // }//todo 140文字以上ツイートに要対応 return SENDABLE_TEXT_COUNT - s.count() } override fun onDestroy() { super.onDestroy() ctx.unbindService(connection) } companion object { val SENDABLE_TEXT_COUNT = 140 } }
mit
268b430ff48329060eacbb3fd408d21a
34.612403
120
0.675376
4.61608
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/test/testdata/filetypes/skin/inspections/com/example/KColorArrayHolder.kt
1
747
package com.example import com.badlogic.gdx.graphics.Color import com.example.ColorArrayHolder import com.gmail.blueboxware.libgdxplugin.annotations.GDXTag @GDXTag("kotlinTag1", "kotlinTag2") class KColorArrayHolder { val colors = arrayOf(Color.BLACK) val ccolors = arrayOf(arrayOf(Color.BLUE)) val bool = true val i = 1 val f = 1.0 val byte: Byte = 1 var nc: Array<Color>? = null var nnc: Array<Color?>? = null val m = arrayOf(arrayOf(ColorArrayHolder())) class StaticInner {} inner class NonStaticInner {} fun f() { com.badlogic.gdx.utils.Json().addClassTag("Tag2", com.example.ColorArrayHolder::class.java) com.badlogic.gdx.utils.Json().addClassTag("Tag3", com.example.ColorArrayHolder::class.java) } }
apache-2.0
0888aafe288d674ca6efb94ec134f6b7
23.933333
95
0.722892
3.38009
false
false
false
false
proxer/ProxerLibAndroid
library/src/main/kotlin/me/proxer/library/entity/list/TranslatorGroupCore.kt
2
732
package me.proxer.library.entity.list import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import me.proxer.library.entity.ProxerIdItem import me.proxer.library.entity.ProxerImageItem import me.proxer.library.enums.Country /** * Entity containing the core information of a translator group. * * @property name The name. * @property country The country, the translator group is active in. * * @author Ruben Gees */ @JsonClass(generateAdapter = true) data class TranslatorGroupCore( @Json(name = "id") override val id: String, @Json(name = "name") val name: String, @Json(name = "country") val country: Country, @Json(name = "image") override val image: String ) : ProxerIdItem, ProxerImageItem
gpl-3.0
87e0a00608494be30452bc20018b3fd8
30.826087
68
0.745902
3.715736
false
false
false
false
VerifAPS/verifaps-lib
lang/src/main/kotlin/edu/kit/iti/formal/automation/st/StructuredTextHtmlPrinter.kt
1
10193
package edu.kit.iti.formal.automation.st import edu.kit.iti.formal.automation.scope.Scope import edu.kit.iti.formal.automation.st.ast.* import edu.kit.iti.formal.automation.visitors.DefaultVisitor import edu.kit.iti.formal.util.* import edu.kit.iti.formal.util.SemanticClasses.* import java.io.Writer /** * Created by weigla on 15.06.2014. * * @author weigl * @version $Id: $Id */ /*open class StructuredTextHtmlPrinter(stream: Writer) : DefaultVisitor<Unit>() { private var sb = SemanticCodeWriter(DefaultHtmlSemantic(), stream) var isPrintComments: Boolean = false override fun defaultVisit(obj: Any) { sb.cliFormat(SemanticClasses.ERROR, "not implemented: ") .cliFormat(obj::class.java) } override fun visit(exitStatement: ExitStatement) { sb.cliFormat(STATEMENT, KEYWORD, "EXIT").cliFormat(";") } override fun visit(integerCondition: CaseCondition.IntegerCondition) { sb.open(CASE_INTEGER_CONDITION) integerCondition.value.accept(this) sb.close() } override fun visit(enumeration: CaseCondition.Enumeration) { sb.cliFormat(CASE_ENUM_CONDITION) if (enumeration.start === enumeration.stop) { sb.appendIdent() enumeration.start.accept(this) } else { sb.appendIdent() enumeration.start.accept(this) sb.printf("..") enumeration.stop!!.accept(this) } sb.close() } override fun visit(binaryExpression: BinaryExpression) { sb.cliFormat(BINARY_EXPRESSION) sb.append('(') binaryExpression.leftExpr.accept(this) sb.cliFormat(OPERATOR, KEYWORD) sb.printf(" ").printf(binaryExpression.operator!!.symbol).printf(" ") sb.close().close() binaryExpression.rightExpr.accept(this) sb.append(')') sb.close() } override fun visit(assignStatement: AssignmentStatement) { sb.semblock(ASSIGNMENT) { assignStatement.location.accept(this) sb.cliFormat(OPERATOR, ":=") assignStatement.expression.accept(this) } sb.cliFormat(OPERATOR, ";") } override fun visit(enumerationTypeDeclaration: EnumerationTypeDeclaration) { sb.cliFormat(TYPE_DECL_ENUM).cliFormat(TYPE_NAME).printf(enumerationTypeDeclaration.name) sb.close().seperator(":") sb.cliFormat(TYPE_DECL_DECL).printf("(") for (s in enumerationTypeDeclaration.allowedValues) { sb.cliFormat(VALUE).printf(s.text) sb.close().seperator(",") } sb.printf(")") sb.ts().close().close() } override fun visit(repeatStatement: RepeatStatement) { sb.cliFormat(REPEAT).keyword("REPEAT") repeatStatement.statements.accept(this) sb.keyword(" UNTIL ") repeatStatement.condition.accept(this) sb.keyword("END_REPEAT") sb.close() } override fun visit(whileStatement: WhileStatement) { sb.cliFormat(WHILE).keyword("WHILE") whileStatement.condition.accept(this) sb.keyword(" DO ") whileStatement.statements.accept(this) sb.keyword("END_WHILE") sb.close() } override fun visit(unaryExpression: UnaryExpression) { sb.cliFormat(UNARY_EXPRESSION, OPERATOR) .printf(unaryExpression.operator.symbol) sb.close().printf(" ") unaryExpression.expression.accept(this) sb.close() } override fun visit(typeDeclarations: TypeDeclarations) { sb.cliFormat(TYPE_DECL).keyword("TYPE") for (decl in typeDeclarations) { decl.accept(this) } sb.keyword("END_TYPE") sb.close() } override fun visit(caseStatement: CaseStatement) { sb.cliFormat(CASE_STATEMENT).keyword("CASE") caseStatement.expression!!.accept(this) sb.keyword(" OF ") for (c in caseStatement.cases) { c.accept(this) } sb.keyword("END_CASE") sb.close() } override fun visit(symbolicReference: Location) { /*TODO sb.variable(symbolicReference.getName()); if (symbolicReference.getSubscripts() != null && !symbolicReference.getSubscripts().isEmpty()) { sb.cliFormat(SUBSCRIPT).printf('['); for (Expression expr : symbolicReference.getSubscripts()) { expr.accept(this); sb.printf(','); } sb.printf(']'); sb.close(); } if (symbolicReference.getSub() != null) { sb.printf("."); symbolicReference.getSub().accept(this); }*/ } override fun visit(statements: StatementList) { sb.cliFormat(STATEMENT_BLOCK) for (stmt in statements) { if (stmt == null) { sb.printf("{*ERROR: stmt null*}") } else { sb.cliFormat(STATEMENT) stmt.accept(this) sb.close() } } sb.close() } override fun visit(programDeclaration: ProgramDeclaration) { sb.cliFormat(PROGRAM).keyword("PROGRAM") sb.cliFormat(VARIABLE).printf(programDeclaration.name) sb.close().append('\n') programDeclaration.scope.accept(this) programDeclaration.stBody!!.accept(this) sb.keyword("END_PROGRAM") sb.close() } /** * {@inheritDoc} * * @Override public Object visit(ScalarValue tsScalarValue) { * sb.cliFormat(VALUE).span(tsScalarValue.getDataType().getName()) * .printf(tsScalarValue.getDataType().repr(tsScalarValue.getValue())); * sb.close().close(); * ; * } */ override fun visit(expressions: ExpressionList) { sb.cliFormat(EXPRESSION_LIST) for (e in expressions) { e.accept(this) sb.seperator(",") }//TODO sb.close() } override fun visit(invocation: Invocation) { sb.cliFormat(FUNC_CALL) sb.printf(invocation.calleeName) visitInvocationParameters(invocation.parameters) } private fun visitInvocationParameters(parameters: MutableList<InvocationParameter>) { sb.printf("(") parameters.joinInto(sb, ",") { it.accept(this) } sb.printf(")") } override fun visit(forStatement: ForStatement) { sb.cliFormat(FOR) sb.keyword("FOR") sb.variable(forStatement.variable!!) sb.printf(" := ") forStatement.start!!.accept(this) sb.keyword("TO") forStatement.stop!!.accept(this) sb.keyword("DO") forStatement.statements.accept(this) sb.decreaseIndent().nl() sb.printf("END_FOR") sb.close() } override fun visit(functionBlockDeclaration: FunctionBlockDeclaration) { sb.cliFormat(FB).keyword("FUNCTION_BLOCK ").variable(functionBlockDeclaration.name) functionBlockDeclaration.scope.accept(this) functionBlockDeclaration.stBody!!.accept(this) sb.keyword("END_FUNCTION_BLOCK").ts().close() } override fun visit(returnStatement: ReturnStatement) { sb.keyword("RETURN").ts() } override fun visit(ifStatement: IfStatement) { sb.cliFormat(IFSTATEMENT) for (i in 0 until ifStatement.conditionalBranches.size) { if (i == 0) sb.keyword("IF") else sb.keyword("ELSIF") ifStatement.conditionalBranches[i].condition.accept(this) sb.keyword("THEN") sb.cliFormat("thenblock") ifStatement.conditionalBranches[i].statements.accept(this) sb.close() } if (ifStatement.elseBranch.size > 0) { sb.keyword("ELSE") ifStatement.elseBranch.accept(this) } sb.keyword("END_IF").ts().close() } override fun visit(fbc: InvocationStatement) { fbc.callee.accept(this) visitInvocationParameters(fbc.parameters) sb.printf(";") } override fun visit(aCase: Case) { sb.cliFormat(CASE) for (cc in aCase.conditions) { cc.accept(this) sb.seperator(",") } //TODO sb.seperator(":") aCase.statements.accept(this) sb.close() } override fun visit(simpleTypeDeclaration: SimpleTypeDeclaration) { sb.cliFormat(TYPE_DECL_SIMPLE).type(simpleTypeDeclaration.baseType.identifier) if (simpleTypeDeclaration.initialization != null) { sb.operator(" := ") simpleTypeDeclaration.initialization!!.accept(this) } sb.close() } override fun visit(localScope: Scope) { sb.cliFormat(VARIABLES_DEFINITIONS) for (vd in localScope.variables) { sb.cliFormat(VARIABLES_DEFINITION) if (vd.isInput) sb.keyword("VAR_INPUT") else if (vd.isOutput) sb.keyword("VAR_OUTPUT") else if (vd.isInOut) sb.keyword("VAR_INOUT") else if (vd.isExternal) sb.keyword("VAR_EXTERNAL") else if (vd.isGlobal) sb.keyword("VAR_GLOBAL") else sb.keyword("VAR") if (vd.isConstant) sb.keyword("CONSTANT") if (vd.isRetain) sb.keyword("RETAIN") else sb.keyword("NON_RETAIN") sb.printf(" ") sb.variable(vd.name) sb.seperator(":") sb.type(vd.dataType?.name) if (vd.init != null) { sb.operator(" := ") vd.init!!.accept(this) } sb.keyword("END_VAR").close() } sb.close() } override fun visit(commentStatement: CommentStatement) { if (isPrintComments) { sb.cliFormat(COMMENT).printf("{*").printf(commentStatement.comment).printf("*}") sb.close() } } /** * * clear. */ fun clear() { sb = HTMLCodeWriter() } fun closeHtml() { sb.printf("</body></html>") } } */
gpl-3.0
5a7903666113cee4eca7fe74e9003958
24.613065
98
0.580595
4.245314
false
false
false
false
deltaDNA/android-smartads-sdk
library-core/src/test/java/com/deltadna/android/sdk/ads/core/WaterfallTest.kt
1
2931
/* * Copyright (c) 2016 deltaDNA Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deltadna.android.sdk.ads.core import com.deltadna.android.sdk.ads.bindings.AdRequestResult import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class WaterfallTest { @Test fun resetAndGetFirst() { var stubs = stubbedAdapters(2) with(Waterfall(stubs, 1)) { assertThat(resetAndGetFirst()).isSameAs(stubs[0]) assertThat(adapters[0]).isSameAs(stubs[0]) assertThat(adapters[1]).isSameAs(stubs[1]) } stubs = stubbedAdapters(3) stubs[0].updateScore(AdRequestResult.NoFill) stubs[2].updateScore(AdRequestResult.NoFill) with(Waterfall(stubs, 1)) { assertThat(resetAndGetFirst()).isSameAs(stubs[1]) assertThat(adapters[1]).isSameAs(stubs[0]) assertThat(adapters[2]).isSameAs(stubs[2]) } } @Test fun getNext() { val stubs = stubbedAdapters(2) with(Waterfall(stubs, 1)) { assertThat(next).isSameAs(stubs[1]) assertThat(next).isNull() } } @Test fun score() { val stubs = stubbedAdapters(3) with(Waterfall(stubs, 1)) { with(resetAndGetFirst()!!) { score(this, AdRequestResult.NoFill) score(this, AdRequestResult.NoFill) assertThat(this.requests).isEqualTo(0) } score(next!!, AdRequestResult.Error) with(next!!) { score(this, AdRequestResult.Loaded) assertThat(this.requests).isEqualTo(1) } resetAndGetFirst() assertThat(adapters).isEqualTo(listOf(stubs[2], stubs[0])) } } @Test fun remove() { val stubs = stubbedAdapters(2) with(Waterfall(stubs, 1)) { remove(resetAndGetFirst()) assertThat(adapters.size).isEqualTo(1) with(next) { assertThat(this).isSameAs(stubs[1]) remove(this) } assertThat(adapters.isEmpty()) assertThat(next).isNull() } } }
apache-2.0
17204f511821f3174cedaa4e404c22d9
29.852632
75
0.587513
4.361607
false
true
false
false
coil-kt/coil
coil-base/src/main/java/coil/util/Collections.kt
1
2638
@file:JvmName("-Collections") package coil.util import java.util.Collections /** * Functionally the same as [Iterable.forEach] except it generates * an index-based loop that doesn't use an [Iterator]. */ internal inline fun <T> List<T>.forEachIndices(action: (T) -> Unit) { for (i in indices) { action(get(i)) } } /** * Functionally the same as [Iterable.forEachIndexed] except it generates * an index-based loop that doesn't use an [Iterator]. */ internal inline fun <T> List<T>.forEachIndexedIndices(action: (Int, T) -> Unit) { for (i in indices) { action(i, get(i)) } } /** * Functionally the same as [Iterable.fold] except it generates * an index-based loop that doesn't use an [Iterator]. */ internal inline fun <T, R> List<T>.foldIndices(initial: R, operation: (R, T) -> R): R { var accumulator = initial for (i in indices) { accumulator = operation(accumulator, get(i)) } return accumulator } /** * Return the first non-null value returned by [transform]. * Generate an index-based loop that doesn't use an [Iterator]. */ internal inline fun <R, T> List<R>.firstNotNullOfOrNullIndices(transform: (R) -> T?): T? { for (i in indices) { transform(get(i))?.let { return it } } return null } /** * Removes values from the list as determined by the [predicate]. * Generate an index-based loop that doesn't use an [Iterator]. */ internal inline fun <T> MutableList<T>.removeIfIndices(predicate: (T) -> Boolean) { var numDeleted = 0 for (rawIndex in indices) { val index = rawIndex - numDeleted if (predicate(get(index))) { removeAt(index) numDeleted++ } } } /** * Returns a list containing the **non null** results of applying the given * [transform] function to each entry in the original map. */ internal inline fun <K, V, R : Any> Map<K, V>.mapNotNullValues( transform: (Map.Entry<K, V>) -> R? ): Map<K, R> { val destination = mutableMapOf<K, R>() for (entry in entries) { val value = transform(entry) if (value != null) { destination[entry.key] = value } } return destination } internal fun <K, V> Map<K, V>.toImmutableMap(): Map<K, V> = when (size) { 0 -> emptyMap() 1 -> entries.first().let { (key, value) -> Collections.singletonMap(key, value) } else -> Collections.unmodifiableMap(LinkedHashMap(this)) } internal fun <T> List<T>.toImmutableList(): List<T> = when (size) { 0 -> emptyList() 1 -> Collections.singletonList(first()) else -> Collections.unmodifiableList(ArrayList(this)) }
apache-2.0
61c0dd8b4229b34876ba86191644dd25
27.673913
90
0.634572
3.623626
false
false
false
false
shiguredo/sora-android-sdk
sora-android-sdk/src/main/kotlin/jp/shiguredo/sora/sdk/channel/SoraMediaChannel.kt
1
45793
package jp.shiguredo.sora.sdk.channel import android.content.Context import android.os.Handler import android.os.Looper import io.reactivex.rxkotlin.subscribeBy import io.reactivex.schedulers.Schedulers import jp.shiguredo.sora.sdk.BuildConfig import jp.shiguredo.sora.sdk.channel.data.ChannelAttendeesCount import jp.shiguredo.sora.sdk.channel.option.PeerConnectionOption import jp.shiguredo.sora.sdk.channel.option.SoraMediaOption import jp.shiguredo.sora.sdk.channel.rtc.PeerChannel import jp.shiguredo.sora.sdk.channel.rtc.PeerChannelImpl import jp.shiguredo.sora.sdk.channel.rtc.PeerNetworkConfig import jp.shiguredo.sora.sdk.channel.signaling.SignalingChannel import jp.shiguredo.sora.sdk.channel.signaling.SignalingChannelImpl import jp.shiguredo.sora.sdk.channel.signaling.message.MessageConverter import jp.shiguredo.sora.sdk.channel.signaling.message.NotificationMessage import jp.shiguredo.sora.sdk.channel.signaling.message.OfferConfig import jp.shiguredo.sora.sdk.channel.signaling.message.OfferMessage import jp.shiguredo.sora.sdk.channel.signaling.message.PushMessage import jp.shiguredo.sora.sdk.channel.signaling.message.SwitchedMessage import jp.shiguredo.sora.sdk.error.SoraDisconnectReason import jp.shiguredo.sora.sdk.error.SoraErrorReason import jp.shiguredo.sora.sdk.error.SoraMessagingError import jp.shiguredo.sora.sdk.util.ReusableCompositeDisposable import jp.shiguredo.sora.sdk.util.SoraLogger import org.webrtc.DataChannel import org.webrtc.IceCandidate import org.webrtc.MediaStream import org.webrtc.PeerConnection import org.webrtc.RTCStatsCollectorCallback import org.webrtc.RTCStatsReport import org.webrtc.RtpParameters import org.webrtc.SessionDescription import java.nio.ByteBuffer import java.nio.charset.CodingErrorAction import java.nio.charset.StandardCharsets import java.util.Timer import java.util.TimerTask import kotlin.concurrent.schedule /** * Sora への接続を行うクラスです. * * [SignalingChannel] と [PeerChannel] の管理、協調動作制御を行っています. * このクラスを利用することでシグナリングの詳細が隠蔽され、単一の [Listener] でイベントを受けることが出来ます. * * シグナリングの手順とデータに関しては下記の Sora のドキュメントを参照ください. * - [WebSocket 経由のシグナリング](https://sora.shiguredo.jp/doc/SIGNALING) * - [DataChannel 経由のシグナリング](https://sora-doc.shiguredo.jp/DATA_CHANNEL_SIGNALING) * * @constructor * SoraMediaChannel インスタンスを生成します. * * @param context `android.content.Context` * @param signalingEndpoint シグナリングの URL * @param signalingEndpointCandidates シグナリングの URL (クラスター機能で複数の URL を利用したい場合はこちらを指定する) * @param signalingMetadata connect メッセージに含める `metadata` * @param channelId Sora に接続するためのチャネル ID * @param mediaOption 映像、音声に関するオプション * @param timeoutSeconds WebSocket の接続タイムアウト (秒) * @param listener イベントリスナー * @param clientId connect メッセージに含める `client_id` * @param signalingNotifyMetadata connect メッセージに含める `signaling_notify_metadata` * @param dataChannelSignaling connect メッセージに含める `data_channel_signaling` * @param ignoreDisconnectWebSocket connect メッセージに含める `ignore_disconnect_websocket` * @param dataChannels connect メッセージに含める `data_channels` * @param bundleId connect メッセージに含める `bundle_id` */ class SoraMediaChannel @JvmOverloads constructor( private val context: Context, private val signalingEndpoint: String? = null, private val signalingEndpointCandidates: List<String> = emptyList(), private val channelId: String, private val signalingMetadata: Any? = "", private val mediaOption: SoraMediaOption, private val timeoutSeconds: Long = DEFAULT_TIMEOUT_SECONDS, private var listener: Listener?, private val clientId: String? = null, private val signalingNotifyMetadata: Any? = null, private val peerConnectionOption: PeerConnectionOption = PeerConnectionOption(), dataChannelSignaling: Boolean? = null, ignoreDisconnectWebSocket: Boolean? = null, dataChannels: List<Map<String, Any>>? = null, private var bundleId: String? = null, ) { companion object { private val TAG = SoraMediaChannel::class.simpleName const val DEFAULT_TIMEOUT_SECONDS = 10L } // connect メッセージに含める `data_channel_signaling` private val connectDataChannelSignaling: Boolean? // connect メッセージに含める `ignore_disconnect_websocket` private val connectIgnoreDisconnectWebSocket: Boolean? // connect メッセージに含める `data_channels` private val connectDataChannels: List<Map<String, Any>>? // メッセージング機能で利用する DataChannel // offer メッセージに含まれる `data_channels` のうち、 label が # から始まるもの private var dataChannelsForMessaging: List<Map<String, Any>>? = null // DataChannel 経由のシグナリングが有効なら true // Sora から渡された値 (= offer メッセージ) を参照して更新している private var offerDataChannelSignaling: Boolean = false // DataChannel 経由のシグナリング利用時に WebSocket の切断を無視するなら true // 同じく switched メッセージを参照して更新している private var switchedIgnoreDisconnectWebSocket: Boolean = false // DataChannel メッセージの ByteBuffer を String に変換するための CharsetDecoder // CharsetDecoder はスレッドセーフではないため注意 private val utf8Decoder = StandardCharsets.UTF_8 .newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT) /** * メッセージングで受信したデータを UTF-8 の文字列に変換します. * * CharsetDecoder がスレッド・セーフでないため、 Synchronized を付与しています. * アプリケーションで大量のメッセージを処理してパフォーマンスの問題が生じた場合、独自の関数を定義して利用することを推奨します. * * @param data 受信したメッセージ * @return UTF-8 の文字列 */ @Synchronized fun dataToString(data: ByteBuffer): String { return utf8Decoder.decode(data).toString() } init { if ((signalingEndpoint == null && signalingEndpointCandidates.isEmpty()) || (signalingEndpoint != null && signalingEndpointCandidates.isNotEmpty()) ) { throw IllegalArgumentException("Either signalingEndpoint or signalingEndpointCandidates must be specified") } // コンストラクタ以外で dataChannelSignaling, ignoreDisconnectWebSocket を参照すべきではない // 各種ロジックの判定には Sora のメッセージに含まれる値を参照する必要があるため、以下を利用するのが正しい // - offerDataChannelSignaling // - switchedIgnoreDisconnectWebSocket connectDataChannelSignaling = dataChannelSignaling connectIgnoreDisconnectWebSocket = ignoreDisconnectWebSocket connectDataChannels = dataChannels } /** * ロール */ val role = mediaOption.role ?: mediaOption.requiredRole private var getStatsTimer: Timer? = null private var dataChannels: MutableMap<String, DataChannel> = mutableMapOf() /** * [SoraMediaChannel] からコールバックイベントを受けるリスナー */ interface Listener { /** * ローカルストリームが追加されたときに呼び出されるコールバック. * * cf. * - `org.webrtc.MediaStream` * - `org.webrtc.MediaStream.videoTracks` * * @param mediaChannel イベントが発生したチャネル * @param ms 追加されたメディアストリーム */ fun onAddLocalStream(mediaChannel: SoraMediaChannel, ms: MediaStream) {} /** * リモートストリームが追加されたときに呼び出されるコールバック. * * cf. * - `org.webrtc.MediaStream` * - `org.webrtc.MediaStream.videoTracks` * * @param mediaChannel イベントが発生したチャネル * @param ms 追加されたメディアストリーム */ fun onAddRemoteStream(mediaChannel: SoraMediaChannel, ms: MediaStream) {} /** * リモートストリームが削除されたときに呼び出されるコールバック. * * cf. * - `org.webrtc.MediaStream.label()` * * @param mediaChannel イベントが発生したチャネル * @param label メディアストリームのラベル (`ms.label()`) */ fun onRemoveRemoteStream(mediaChannel: SoraMediaChannel, label: String) {} /** * Sora との接続が確立されたときに呼び出されるコールバック. * * cf. * - [PeerChannel] * * @param mediaChannel イベントが発生したチャネル */ fun onConnect(mediaChannel: SoraMediaChannel) {} /** * Sora との接続が切断されたときに呼び出されるコールバック. * * cf. * - [PeerChannel] * * @param mediaChannel イベントが発生したチャネル */ fun onClose(mediaChannel: SoraMediaChannel) {} /** * Sora との通信やメディアでエラーが発生したときに呼び出されるコールバック. * * cf. * - `org.webrtc.PeerConnection` * - `org.webrtc.PeerConnection.Observer` * - [PeerChannel] * * @param reason エラーの理由 */ fun onError(mediaChannel: SoraMediaChannel, reason: SoraErrorReason) {} /** * Sora との通信やメディアでエラーが発生したときに呼び出されるコールバック. * * cf. * - `org.webrtc.PeerConnection` * - `org.webrtc.PeerConnection.Observer` * - [PeerChannel] * * @param reason エラーの理由 * @param message エラーの情報 */ fun onError(mediaChannel: SoraMediaChannel, reason: SoraErrorReason, message: String) {} /** * Sora との通信やメディアで警告が発生したときに呼び出されるコールバック. * * cf. * - `org.webrtc.PeerConnection` * - `org.webrtc.PeerConnection.Observer` * - [PeerChannel] * * @param reason 警告の理由 */ fun onWarning(mediaChannel: SoraMediaChannel, reason: SoraErrorReason) {} /** * Sora との通信やメディアで警告が発生したときに呼び出されるコールバック. * * cf. * - `org.webrtc.PeerConnection` * - `org.webrtc.PeerConnection.Observer` * - [PeerChannel] * * @param reason 警告の理由 * @param message 警告の情報 */ fun onWarning(mediaChannel: SoraMediaChannel, reason: SoraErrorReason, message: String) {} /** * 接続しているチャネルの参加者が増減したときに呼び出されるコールバック. * * @param mediaChannel イベントが発生したチャネル * @param attendees 配信者数と視聴者数を含むオブジェクト */ fun onAttendeesCountUpdated(mediaChannel: SoraMediaChannel, attendees: ChannelAttendeesCount) {} /** * Sora から type: offer メッセージを受信した際に呼び出されるコールバック. * * @param mediaChannel イベントが発生したチャネル * @param offer Sora から受信した type: offer メッセージ */ fun onOfferMessage(mediaChannel: SoraMediaChannel, offer: OfferMessage) {} /** * Sora のシグナリング通知機能の通知を受信したときに呼び出されるコールバック. * * @param mediaChannel イベントが発生したチャネル * @param notification Sora の通知機能により受信したメッセージ */ fun onNotificationMessage(mediaChannel: SoraMediaChannel, notification: NotificationMessage) {} /** * Sora のプッシュ API によりメッセージを受信したときに呼び出されるコールバック. * * @param mediaChannel イベントが発生したチャネル * @param push プッシュ API により受信したメッセージ */ fun onPushMessage(mediaChannel: SoraMediaChannel, push: PushMessage) {} /** * PeerConnection の getStats() 統計情報を取得したときに呼び出されるコールバック. * * cf. * - https://w3c.github.io/webrtc-stats/ * - https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/getStats * * @param mediaChannel イベントが発生したチャネル * @param statsReport 統計レポート */ fun onPeerConnectionStatsReady(mediaChannel: SoraMediaChannel, statsReport: RTCStatsReport) {} /** * サイマルキャスト配信のエンコーダ設定を変更するためのコールバック. * * 引数の encodings は Sora が送ってきた設定を反映した RtpParameters.Encoding のリストです. * デフォルトの実装ではなにも行いません. * このコールバックを実装し、引数のオブジェクトを変更することで、アプリケーションの要件に従った * 設定をエンコーダにわたすことができます. * * cf. Web 標準の対応 API は次のとおりです. libwebrtc の native(C++) と android の実装は * 異なりますので注意してください. * - https://w3c.github.io/webrtc-pc/#dom-rtcrtpencodingparameters * - https://w3c.github.io/webrtc-pc/#dom-rtcrtpsender-setparameters * * @param mediaChannel イベントが発生したチャネル * @param encodings Sora から送信された encodings */ fun onSenderEncodings(mediaChannel: SoraMediaChannel, encodings: List<RtpParameters.Encoding>) {} /** * データチャネルが利用可能になったときに呼び出されるコールバック * * @param mediaChannel イベントが発生したチャネル * @param dataChannels Sora の offer メッセージに含まれる data_channels のうち label が # から始まるもの */ fun onDataChannel(mediaChannel: SoraMediaChannel, dataChannels: List<Map<String, Any>>?) {} /** * メッセージング機能のメッセージを受信したときに呼び出されるコールバック * ラベルが # から始まるメッセージのみが通知されます * * @param mediaChannel イベントが発生したチャネル * @param label ラベル * @param data 受信したメッセージ */ fun onDataChannelMessage(mediaChannel: SoraMediaChannel, label: String, data: ByteBuffer) {} } private var peer: PeerChannel? = null private var signaling: SignalingChannel? = null private var switchedToDataChannel = false private var closing = false // type: redirect で再利用するために、初回接続時の clientOffer を保持する private var clientOffer: SessionDescription? = null /** * コネクション ID. */ var connectionId: String? = null private set /** * 最初に type: connect を最初に送信したエンドポイント. * * Sora から type: redirect メッセージを受信した場合、 contactSignalingEndpoint と connectedSignalingEndpoint の値は異なります * type: redirect メッセージを受信しなかった場合、 contactSignalingEndpoint と connectedSignalingEndpoint は同じ値です */ var contactSignalingEndpoint: String? = null private set /** * 接続中のエンドポイント. */ var connectedSignalingEndpoint: String? = null private set private val compositeDisposable = ReusableCompositeDisposable() private val signalingListener = object : SignalingChannel.Listener { override fun onDisconnect(disconnectReason: SoraDisconnectReason?) { SoraLogger.d( TAG, "[channel:$role] @signaling:onDisconnect " + "switchedToDataChannel=$switchedToDataChannel, " + "switchedIgnoreDisconnectWebSocket=$switchedIgnoreDisconnectWebSocket" ) if (switchedToDataChannel && switchedIgnoreDisconnectWebSocket) { // なにもしない SoraLogger.d(TAG, "[channel:$role] @signaling:onDisconnect: IGNORE") } else { internalDisconnect(disconnectReason) } } override fun onConnect(endpoint: String) { SoraLogger.d(TAG, "[channel:$role] @signaling:onOpen") // SignalingChannel の初回接続時のみ contactSignalingEndpoint を設定する // Sora から type: redirect を受信した場合、このコールバックは複数回実行される可能性がある if (contactSignalingEndpoint == null) { contactSignalingEndpoint = endpoint } } override fun onInitialOffer(offerMessage: OfferMessage, endpoint: String) { SoraLogger.d(TAG, "[channel:$role] @signaling:onInitialOffer") [email protected] = offerMessage.connectionId handleInitialOffer(offerMessage) connectedSignalingEndpoint = endpoint listener?.onOfferMessage(this@SoraMediaChannel, offerMessage) } override fun onSwitched(switchedMessage: SwitchedMessage) { SoraLogger.d(TAG, "[channel:$role] @signaling:onSwitched") switchedIgnoreDisconnectWebSocket = switchedMessage.ignoreDisconnectWebsocket ?: false handleSwitched(switchedMessage) } override fun onUpdatedOffer(sdp: String) { SoraLogger.d(TAG, "[channel:$role] @signaling:onUpdatedOffer") handleUpdateOffer(sdp) } override fun onReOffer(sdp: String) { SoraLogger.d(TAG, "[channel:$role] @signaling:onReOffer") handleReOffer(sdp) } override fun onNotificationMessage(notification: NotificationMessage) { SoraLogger.d(TAG, "[channel:$role] @signaling:onNotificationMessage") handleNotificationMessage(notification) } override fun onPushMessage(push: PushMessage) { SoraLogger.d(TAG, "[channel:$role] @signaling:onPushMessage") listener?.onPushMessage(this@SoraMediaChannel, push) } override fun onError(reason: SoraErrorReason) { SoraLogger.d(TAG, "[channel:$role] @signaling:onError:$reason") val ignoreError = switchedIgnoreDisconnectWebSocket if (switchedToDataChannel && ignoreError) { // なにもしない SoraLogger.d(TAG, "[channel:$role] @signaling:onError: IGNORE reason=$reason") } else { listener?.onError(this@SoraMediaChannel, reason) } } override fun getStats(handler: (RTCStatsReport?) -> Unit) { if (peer != null) { peer!!.getStats(handler) } else { handler(null) } } override fun onRedirect(location: String) { SoraLogger.d(TAG, "[channel:$role] @peer:onRedirect") SoraLogger.i(TAG, "[channel:$role] closing old SignalingChannel") signaling?.disconnect(null) SoraLogger.i(TAG, "[channel:$role] opening new SignalingChannel") val handler = Handler(Looper.getMainLooper()) handler.post() { connectSignalingChannel(clientOffer, location) } } } private val peerListener = object : PeerChannel.Listener { override fun onLocalIceCandidateFound(candidate: IceCandidate) { SoraLogger.d(TAG, "[channel:$role] @peer:onLocalIceCandidateFound") signaling?.sendCandidate(candidate.sdp) } override fun onRemoveRemoteStream(label: String) { SoraLogger.d(TAG, "[channel:$role] @peer:onRemoveRemoteStream:$label") if (connectionId != null && label == connectionId) { SoraLogger.d(TAG, "[channel:$role] this stream is mine, ignore") return } listener?.onRemoveRemoteStream(this@SoraMediaChannel, label) } override fun onAddRemoteStream(ms: MediaStream) { SoraLogger.d(TAG, "[channel:$role] @peer:onAddRemoteStream msid=:${ms.id}, connectionId=$connectionId") if (mediaOption.multistreamEnabled && connectionId != null && ms.id == connectionId) { SoraLogger.d(TAG, "[channel:$role] this stream is mine, ignore: ${ms.id}") return } listener?.onAddRemoteStream(this@SoraMediaChannel, ms) } override fun onAddLocalStream(ms: MediaStream) { SoraLogger.d(TAG, "[channel:$role] @peer:onAddLocalStream") listener?.onAddLocalStream(this@SoraMediaChannel, ms) } override fun onConnect() { SoraLogger.d(TAG, "[channel:$role] @peer:onConnect") stopTimer() listener?.onConnect(this@SoraMediaChannel) } override fun onDataChannelOpen(label: String, dataChannel: DataChannel) { [email protected][label] = dataChannel } override fun onDataChannelMessage(label: String, dataChannel: DataChannel, dataChannelBuffer: DataChannel.Buffer) { if (peer == null) { return } SoraLogger.d(TAG, "[channel:$role] @peer:onDataChannelMessage label=$label") val buffer = peer!!.unzipBufferIfNeeded(label, dataChannelBuffer.data) if (label.startsWith("#")) { listener?.onDataChannelMessage(this@SoraMediaChannel, label, buffer) } else { try { val message = dataToString(buffer) val expectedType = when (label) { "signaling" -> "re-offer" "notify" -> "notify" "push" -> "push" "stats" -> "req-stats" "e2ee" -> "NOT-IMPLEMENTED" else -> label // 追加が発生した時に備えて許容する } MessageConverter.parseType(message)?.let { type -> when (type) { expectedType -> { when (label) { "signaling" -> { val reOfferMessage = MessageConverter.parseReOfferMessage(message) handleReOfferViaDataChannel(dataChannel, reOfferMessage.sdp) } "notify" -> { val notificationMessage = MessageConverter.parseNotificationMessage(message) handleNotificationMessage(notificationMessage) } "push" -> { val pushMessage = MessageConverter.parsePushMessage(message) listener?.onPushMessage(this@SoraMediaChannel, pushMessage) } "stats" -> { // req-stats は type しかないので parse しない handleReqStats(dataChannel) } "e2ee" -> { SoraLogger.i(TAG, "NOT IMPLEMENTED: label=$label, type=$type, message=$message") } else -> SoraLogger.i(TAG, "Unknown label: label=$label, type=$type, message=$message") } } else -> SoraLogger.i(TAG, "Unknown type: label=$label, type=$type, message=$message") } } } catch (e: Exception) { SoraLogger.e(TAG, "failed to process DataChannel message", e) } } } override fun onDataChannelClosed(label: String, dataChannel: DataChannel) { SoraLogger.d(TAG, "[channel:$role] @peer:onDataChannelClosed label=$label") // DataChannel が閉じられたが、その理由を知る方法がないため reason は null にする internalDisconnect(null) } override fun onSenderEncodings(encodings: List<RtpParameters.Encoding>) { SoraLogger.d(TAG, "[channel:$role] @peer:onSenderEncodings") listener?.onSenderEncodings(this@SoraMediaChannel, encodings) } override fun onError(reason: SoraErrorReason) { SoraLogger.d(TAG, "[channel:$role] @peer:onError:$reason") listener?.onError(this@SoraMediaChannel, reason) } override fun onError(reason: SoraErrorReason, message: String) { SoraLogger.d(TAG, "[channel:$role] @peer:onError:$reason:$message") listener?.onError(this@SoraMediaChannel, reason, message) } override fun onWarning(reason: SoraErrorReason) { SoraLogger.d(TAG, "[channel:$role] @peer:onWarning:$reason") listener?.onWarning(this@SoraMediaChannel, reason) } override fun onWarning(reason: SoraErrorReason, message: String) { SoraLogger.d(TAG, "[channel:$role] @peer:onWarning:$reason:$message") listener?.onWarning(this@SoraMediaChannel, reason, message) } override fun onDisconnect(disconnectReason: SoraDisconnectReason?) { SoraLogger.d(TAG, "[channel:$role] @peer:onDisconnect:$disconnectReason") internalDisconnect(disconnectReason) } } /** * Sora に接続します. * * アプリケーションで接続後の処理が必要な場合は [Listener.onConnect] で行います. */ fun connect() { try { val kClass = Class.forName("org.webrtc.WebrtcBuildVersion") val webrtcBranch = kClass.getField("webrtc_branch").get(null) val webrtcCommit = kClass.getField("webrtc_commit").get(null) val maintVersion = kClass.getField("maint_version").get(null) val webrtcRevision = kClass.getField("webrtc_revision").get(null) val webrtcBuildVersion = listOf(webrtcBranch, webrtcCommit, maintVersion) .joinToString(separator = ".") SoraLogger.d(TAG, "libwebrtc version = $webrtcBuildVersion @ $webrtcRevision") } catch (e: ClassNotFoundException) { SoraLogger.d(TAG, "connect: libwebrtc other than Shiguredo build is used.") } SoraLogger.d( TAG, """connect: SoraMediaOption |requiredRole = ${mediaOption.requiredRole} |upstreamIsRequired = ${mediaOption.upstreamIsRequired} |downstreamIsRequired = ${mediaOption.downstreamIsRequired} |multistreamEnabled = ${mediaOption.multistreamEnabled} |audioIsRequired = ${mediaOption.audioIsRequired} |audioUpstreamEnabled = ${mediaOption.audioUpstreamEnabled} |audioDownstreamEnabled = ${mediaOption.audioDownstreamEnabled} |audioCodec = ${mediaOption.audioCodec} |audioBitRate = ${mediaOption.audioBitrate} |audioSource = ${mediaOption.audioOption.audioSource} |useStereoInput = ${mediaOption.audioOption.useStereoInput} |useStereoOutput = ${mediaOption.audioOption.useStereoOutput} |videoIsRequired = ${mediaOption.videoIsRequired} |videoUpstreamEnabled = ${mediaOption.videoUpstreamEnabled} |videoUpstreamContext = ${mediaOption.videoUpstreamContext} |videoDownstreamEnabled = ${mediaOption.videoDownstreamEnabled} |videoDownstreamContext = ${mediaOption.videoDownstreamContext} |videoEncoderFactory = ${mediaOption.videoEncoderFactory} |videoDecoderFactory = ${mediaOption.videoDecoderFactory} |videoCodec = ${mediaOption.videoCodec} |videoBitRate = ${mediaOption.videoBitrate} |videoCapturer = ${mediaOption.videoCapturer} |simulcastEnabled = ${mediaOption.simulcastEnabled} |simulcastRid = ${mediaOption.simulcastRid} |spotlightEnabled = ${mediaOption.spotlightEnabled} |spotlightNumber = ${mediaOption.spotlightOption?.spotlightNumber} |signalingMetadata = ${this.signalingMetadata} |clientId = ${this.clientId} |bundleId = ${this.bundleId} |signalingNotifyMetadata = ${this.signalingNotifyMetadata} """.trimMargin() ) if (closing) { return } startTimer() requestClientOfferSdp() } private var timer: Timer? = null private fun startTimer() { stopTimer() timer = Timer() timer!!.schedule( object : TimerTask() { override fun run() { timer = null onTimeout() } }, timeoutSeconds * 1000 ) } private fun stopTimer() { timer?.cancel() timer = null } private fun onTimeout() { SoraLogger.d(TAG, "[channel:$role] @peer:onTimeout") listener?.onError(this, SoraErrorReason.TIMEOUT) // ここに来た場合、 Sora に接続出来ていない = disconnect メッセージを送信する必要がない // そのため、 reason は null で良い internalDisconnect(null) } private fun requestClientOfferSdp() { val mediaOption = SoraMediaOption().apply { enableVideoDownstream(null) enableAudioDownstream() } val clientOfferPeer = PeerChannelImpl( appContext = context, networkConfig = PeerNetworkConfig( serverConfig = OfferConfig( iceServers = emptyList(), iceTransportPolicy = "" ), mediaOption = mediaOption ), mediaOption = mediaOption, listener = null ) clientOfferPeer.run { val subscription = requestClientOfferSdp() .observeOn(Schedulers.io()) .subscribeBy( onSuccess = { SoraLogger.d(TAG, "[channel:$role] @peer:clientOfferSdp") disconnect(null) if (it.isFailure) { SoraLogger.d(TAG, "[channel:$role] failed to create client offer SDP: ${it.exceptionOrNull()?.message}") } val handler = Handler(Looper.getMainLooper()) clientOffer = it.getOrNull() handler.post() { connectSignalingChannel(clientOffer) } }, onError = { SoraLogger.w( TAG, "[channel:$role] failed request client offer SDP: ${it.message}" ) disconnect(SoraDisconnectReason.SIGNALING_FAILURE) } ) compositeDisposable.add(subscription) } } private fun connectSignalingChannel(clientOfferSdp: SessionDescription?, redirectLocation: String? = null) { val endpoints = when { redirectLocation != null -> listOf(redirectLocation) signalingEndpointCandidates.isNotEmpty() -> signalingEndpointCandidates else -> listOf(signalingEndpoint!!) } signaling = SignalingChannelImpl( endpoints = endpoints, role = role, channelId = channelId, connectDataChannelSignaling = connectDataChannelSignaling, connectIgnoreDisconnectWebSocket = connectIgnoreDisconnectWebSocket, mediaOption = mediaOption, connectMetadata = signalingMetadata, listener = signalingListener, clientOfferSdp = clientOfferSdp, clientId = clientId, bundleId = bundleId, signalingNotifyMetadata = signalingNotifyMetadata, connectDataChannels = connectDataChannels, redirect = redirectLocation != null ) signaling!!.connect() } private fun handleInitialOffer(offerMessage: OfferMessage) { SoraLogger.d(TAG, "[channel:$role] initial offer") SoraLogger.d(TAG, "[channel:$role] @peer:starting") peer = PeerChannelImpl( appContext = context, networkConfig = PeerNetworkConfig( serverConfig = offerMessage.config, mediaOption = mediaOption ), mediaOption = mediaOption, dataChannelConfigs = offerMessage.dataChannels, listener = peerListener ) if (offerMessage.dataChannels?.isNotEmpty() == true) { offerDataChannelSignaling = true dataChannelsForMessaging = offerMessage.dataChannels.filter { it.containsKey("label") && (it["label"] as? String)?.startsWith("#") ?: false } } if (0 < peerConnectionOption.getStatsIntervalMSec) { getStatsTimer = Timer() SoraLogger.d(TAG, "Schedule getStats with interval ${peerConnectionOption.getStatsIntervalMSec} [msec]") getStatsTimer?.schedule(0L, peerConnectionOption.getStatsIntervalMSec) { peer?.getStats( RTCStatsCollectorCallback { listener?.onPeerConnectionStatsReady(this@SoraMediaChannel, it) } ) } } peer?.run { val subscription = handleInitialRemoteOffer(offerMessage.sdp, offerMessage.mid, offerMessage.encodings) .observeOn(Schedulers.io()) .subscribeBy( onSuccess = { SoraLogger.d(TAG, "[channel:$role] @peer:answer") signaling?.sendAnswer(it.description) }, onError = { val msg = "[channel:$role] failure in handleInitialOffer: ${it.message}" SoraLogger.w(TAG, msg, it) disconnect(SoraDisconnectReason.SIGNALING_FAILURE) } ) compositeDisposable.add(subscription) } } private fun handleSwitched(switchedMessage: SwitchedMessage) { switchedToDataChannel = true switchedIgnoreDisconnectWebSocket = switchedMessage.ignoreDisconnectWebsocket ?: false val earlyCloseWebSocket = switchedIgnoreDisconnectWebSocket if (earlyCloseWebSocket) { signaling?.disconnect(null) } listener?.onDataChannel(this, dataChannelsForMessaging) } private fun handleUpdateOffer(sdp: String) { peer?.run { val subscription = handleUpdatedRemoteOffer(sdp) .observeOn(Schedulers.io()) .subscribeBy( onSuccess = { SoraLogger.d(TAG, "[channel:$role] @peer:about to send updated answer") signaling?.sendUpdateAnswer(it.description) }, onError = { val msg = "[channel:$role] failed handle updated offer: ${it.message}" SoraLogger.w(TAG, msg) disconnect(SoraDisconnectReason.SIGNALING_FAILURE) } ) compositeDisposable.add(subscription) } } private fun handleReOffer(sdp: String) { peer?.run { val subscription = handleUpdatedRemoteOffer(sdp) .observeOn(Schedulers.io()) .subscribeBy( onSuccess = { SoraLogger.d(TAG, "[channel:$role] @peer:about to send re-answer") signaling?.sendReAnswer(it.description) }, onError = { val msg = "[channel:$role] failed handle re-offer: ${it.message}" SoraLogger.w(TAG, msg) disconnect(SoraDisconnectReason.SIGNALING_FAILURE) } ) compositeDisposable.add(subscription) } } private fun handleReOfferViaDataChannel(dataChannel: DataChannel, sdp: String) { peer?.run { val subscription = handleUpdatedRemoteOffer(sdp) .observeOn(Schedulers.io()) .subscribeBy( onSuccess = { SoraLogger.d(TAG, "[channel:$role] @peer:about to send re-answer") peer?.sendReAnswer(dataChannel, it.description) }, onError = { val msg = "[channel:$role] failed handle re-offer: ${it.message}" SoraLogger.w(TAG, msg) disconnect(SoraDisconnectReason.SIGNALING_FAILURE) } ) compositeDisposable.add(subscription) } } private fun handleReqStats(dataChannel: DataChannel) { peer?.getStats { it?.let { reports -> peer?.sendStats(dataChannel, reports) } } } private fun handleNotificationMessage(notification: NotificationMessage) { when (notification.eventType) { "connection.created", "connection.destroyed" -> { val attendees = ChannelAttendeesCount( numberOfSendrecvConnections = notification.numberOfSendrecvConnections ?: 0, numberOfSendonlyConnections = notification.numberOfSendonlyConnections ?: 0, numberOfRecvonlyConnections = notification.numberOfRecvonlyConnections ?: 0, ) listener?.onAttendeesCountUpdated(this@SoraMediaChannel, attendees) } } listener?.onNotificationMessage(this@SoraMediaChannel, notification) } /** * Sora への接続を切断します. * * アプリケーションとして切断後の処理が必要な場合は [Listener.onClose] で行います. */ fun disconnect() { // アプリケーションから切断された場合は NO-ERROR とする internalDisconnect(SoraDisconnectReason.NO_ERROR) } private fun internalDisconnect(disconnectReason: SoraDisconnectReason?) { if (closing) return closing = true stopTimer() disconnectReason?.let { sendDisconnectIfNeeded(it) } compositeDisposable.dispose() listener?.onClose(this) listener = null // アプリケーションで定義された切断処理を実行した後に contactSignalingEndpoint と connectedSignalingEndpoint を null にする contactSignalingEndpoint = null connectedSignalingEndpoint = null // 既に type: disconnect を送信しているので、 disconnectReason は null で良い signaling?.disconnect(null) signaling = null getStatsTimer?.cancel() getStatsTimer = null // 既に type: disconnect を送信しているので、 disconnectReason は null で良い peer?.disconnect(null) peer = null } private fun sendDisconnectOverWebSocket(disconnectReason: SoraDisconnectReason) { signaling?.sendDisconnect(disconnectReason) } private fun sendDisconnectOverDataChannel(disconnectReason: SoraDisconnectReason) { dataChannels["signaling"]?.let { peer?.sendDisconnect(it, disconnectReason) } } private fun sendDisconnectIfNeeded(disconnectReason: SoraDisconnectReason) { val state = peer?.connectionState() SoraLogger.d( TAG, "[channel:$role] sendDisconnectIfNeeded switched=$switchedToDataChannel, " + "switchedIgnoreDisconnectWebSocket=$switchedIgnoreDisconnectWebSocket, " + "reason=$disconnectReason, PeerConnectionState=$state" ) if (state == PeerConnection.PeerConnectionState.FAILED) { // この関数に到達した時点で PeerConnectionState が FAILED なのでメッセージの送信は不要 return } when (disconnectReason) { SoraDisconnectReason.NO_ERROR -> { if (!offerDataChannelSignaling) { // WebSocket のみ sendDisconnectOverWebSocket(disconnectReason) } else { // WebSocket と DataChannel / DataChannel のみ if (!switchedToDataChannel) { // type: switched 未受信 sendDisconnectOverWebSocket(disconnectReason) } else { // type: switched 受信済 sendDisconnectOverDataChannel(disconnectReason) } } } SoraDisconnectReason.WEBSOCKET_ONCLOSE, SoraDisconnectReason.WEBSOCKET_ONERROR -> { if (switchedToDataChannel && !switchedIgnoreDisconnectWebSocket) { sendDisconnectOverDataChannel(disconnectReason) } } SoraDisconnectReason.SIGNALING_FAILURE, SoraDisconnectReason.PEER_CONNECTION_STATE_FAILED -> { // メッセージの送信は不要 } else -> { // SoraDisconnectReason のすべての条件が網羅されていて欲しい if (BuildConfig.DEBUG) { throw Exception("when statement should be exhaustive.") } SoraLogger.i(TAG, "when statement should be exhaustive.") } } } /** * メッセージを送信します. * * @param label ラベル * @param data 送信する文字列 * @return エラー */ fun sendDataChannelMessage(label: String, data: String): SoraMessagingError { return sendDataChannelMessage(label, ByteBuffer.wrap(data.toByteArray())) } /** * メッセージを送信します. * * @param label ラベル * @param data 送信するデータ * @return エラー */ fun sendDataChannelMessage(label: String, data: ByteBuffer): SoraMessagingError { if (!switchedToDataChannel) { return SoraMessagingError.NOT_READY } if (!label.startsWith("#")) { SoraLogger.w(TAG, "label must start with \"#\"") return SoraMessagingError.INVALID_LABEL } val dataChannel = dataChannels[label] if (dataChannel == null) { SoraLogger.w(TAG, "data channel for label: $label not found") return SoraMessagingError.LABEL_NOT_FOUND } if (dataChannel.state() != DataChannel.State.OPEN) { return SoraMessagingError.INVALID_STATE } if (peer == null) { return SoraMessagingError.PEER_CHANNEL_UNAVAILABLE } val buffer = peer!!.zipBufferIfNeeded(label, data) val succeeded = dataChannel.send(DataChannel.Buffer(buffer, true)) SoraLogger.d(TAG, "state=${dataChannel.state()} succeeded=$succeeded") return if (succeeded) { SoraMessagingError.OK } else { SoraMessagingError.SEND_FAILED } } }
apache-2.0
bfddda9a9708588250e389388c037223
37.507922
132
0.594448
4.235674
false
false
false
false
quarck/CalendarNotification
app/src/main/java/com/github/quarck/calnotify/utils/PersistentStorageBase.kt
1
6754
// // Calendar Notifications Plus // Copyright (C) 2016 Sergey Parshin ([email protected]) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // package com.github.quarck.calnotify.utils import android.annotation.SuppressLint import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import kotlin.reflect.KProperty open class PersistentStorageBase(ctx: Context, prefName: String? = null) { protected var state: SharedPreferences init { state = if (prefName != null) ctx.getSharedPreferences(prefName, Context.MODE_PRIVATE) else PreferenceManager.getDefaultSharedPreferences(ctx) } fun edit(): SharedPreferences.Editor { return state.edit() } @SuppressLint("CommitPrefEdits") fun setBoolean(key: String, value: Boolean) { val editor = state.edit() editor.putBoolean(key, value) editor.commit() } @SuppressLint("CommitPrefEdits") fun setInt(key: String, value: Int) { val editor = state.edit() editor.putInt(key, value) editor.commit() } @SuppressLint("CommitPrefEdits") fun setLong(key: String, value: Long) { val editor = state.edit() editor.putLong(key, value) editor.commit() } @SuppressLint("CommitPrefEdits") fun setFloat(key: String, value: Float) { val editor = state.edit() editor.putFloat(key, value) editor.commit() } @SuppressLint("CommitPrefEdits") fun setString(key: String, value: String) { val editor = state.edit() editor.putString(key, value) editor.commit() } @SuppressLint("CommitPrefEdits") fun setStringSet(key: String, value: Set<String>) { val editor = state.edit() editor.putStringSet(key, value) editor.commit() } fun getBoolean(key: String, default: Boolean): Boolean = state.getBoolean(key, default) fun getInt(key: String, default: Int): Int = state.getInt(key, default) fun getLong(key: String, default: Long): Long = state.getLong(key, default) fun getFloat(key: String, default: Float): Float = state.getFloat(key, default) fun getString(key: String, default: String): String = state.getString(key, default) ?: default fun getStringSet(key: String, default: Set<String>): Set<String> = state.getStringSet(key, default) ?: default class BooleanProperty(val defaultValue: Boolean, val storageName: String? = null) { operator fun getValue(thisRef: Any?, property: KProperty<*>): Boolean { val _this = (thisRef as PersistentStorageBase); val key = storageName ?: property.name return _this.getBoolean(key, defaultValue) } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean) { val _this = (thisRef as PersistentStorageBase); val key = storageName ?: property.name _this.setBoolean(key, value) } } class IntProperty(val defaultValue: Int, val storageName: String? = null) { operator fun getValue(thisRef: Any?, property: KProperty<*>): Int { val _this = (thisRef as PersistentStorageBase); val key = storageName ?: property.name return _this.getInt(key, defaultValue) } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) { val _this = (thisRef as PersistentStorageBase); val key = storageName ?: property.name _this.setInt(key, value) } } class LongProperty(val defaultValue: Long, val storageName: String? = null) { operator fun getValue(thisRef: Any?, property: KProperty<*>): Long { val _this = (thisRef as PersistentStorageBase); val key = storageName ?: property.name return _this.getLong(key, defaultValue) } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Long) { val _this = (thisRef as PersistentStorageBase); val key = storageName ?: property.name _this.setLong(key, value) } } class FloatProperty(val defaultValue: Float, val storageName: String? = null) { operator fun getValue(thisRef: Any?, property: KProperty<*>): Float { val _this = (thisRef as PersistentStorageBase); val key = storageName ?: property.name return _this.getFloat(key, defaultValue) } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Float) { val _this = (thisRef as PersistentStorageBase); val key = storageName ?: property.name _this.setFloat(key, value) } } class StringProperty(val defaultValue: String, val storageName: String? = null) { operator fun getValue(thisRef: Any?, property: KProperty<*>): String { val _this = (thisRef as PersistentStorageBase); val key = storageName ?: property.name return _this.getString(key, defaultValue) } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) { val _this = (thisRef as PersistentStorageBase); val key = storageName ?: property.name _this.setString(key, value) } } class StringSetProperty(val defaultValue: Set<String>, val storageName: String? = null) { operator fun getValue(thisRef: Any?, property: KProperty<*>): Set<String> { val _this = (thisRef as PersistentStorageBase); val key = storageName ?: property.name return _this.getStringSet(key, defaultValue) } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Set<String>) { val _this = (thisRef as PersistentStorageBase); val key = storageName ?: property.name _this.setStringSet(key, value) } } }
gpl-3.0
d81b975fb2019664d3a4091468056493
35.706522
114
0.633699
4.532886
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/CommandContext.kt
1
14568
package net.perfectdreams.loritta.morenitta.commands import club.minnced.discord.webhook.WebhookClient import club.minnced.discord.webhook.send.WebhookMessage import com.github.kevinsawicki.http.HttpRequest import net.dv8tion.jda.api.EmbedBuilder import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.* import net.dv8tion.jda.api.entities.channel.ChannelType import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel import net.dv8tion.jda.api.exceptions.PermissionException import net.dv8tion.jda.api.utils.FileUpload import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder import net.dv8tion.jda.api.utils.messages.MessageCreateData import net.perfectdreams.i18nhelper.core.I18nContext import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.dao.ServerConfig import net.perfectdreams.loritta.morenitta.events.LorittaMessageEvent import net.perfectdreams.loritta.morenitta.messages.LorittaReply import net.perfectdreams.loritta.morenitta.utils.* import net.perfectdreams.loritta.morenitta.utils.extensions.* import org.jsoup.Jsoup import java.awt.image.BufferedImage import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.File import java.io.InputStream import java.util.* import javax.imageio.ImageIO /** * Contexto do comando executado */ class CommandContext( val loritta: LorittaBot, val config: ServerConfig, var lorittaUser: LorittaUser, val locale: BaseLocale, val i18nContext: I18nContext, var event: LorittaMessageEvent, var cmd: AbstractCommand, var args: Array<String>, var rawArgs: Array<String>, var strippedArgs: Array<String> ) { var metadata = HashMap<String, Any>() val isPrivateChannel: Boolean get() = event.isFromType(ChannelType.PRIVATE) val message: Message get() = event.message val handle: Member get() { if (lorittaUser is GuildLorittaUser) { return (lorittaUser as GuildLorittaUser).member } throw RuntimeException("Trying to use getHandle() in LorittaUser!") } val userHandle: User get() = lorittaUser.user val asMention: String get() = lorittaUser.asMention val guild: Guild get() = event.guild!! val guildOrNull: Guild? get() = event.guild suspend fun explain() { cmd.explain(this) } /** * Verifica se o usuário tem permissão para utilizar um comando */ fun canUseCommand(): Boolean { return lorittaUser.canUseCommand(this) } fun getAsMention(addSpace: Boolean): String { return lorittaUser.user.asMention + (if (addSpace) " " else "") } suspend fun reply(message: String, prefix: String? = null, addInlineReply: Boolean = true, forceMention: Boolean = false): Message { var send = "" if (prefix != null) { send = "$prefix **|** " } send = send + (if (forceMention) userHandle.asMention + " " else getAsMention(true)) + message return sendMessage(send, addInlineReply = addInlineReply) } suspend fun reply(vararg loriReplies: LorittaReply, addInlineReply: Boolean = true): Message { return reply(false, *loriReplies, addInlineReply = addInlineReply) } suspend fun reply(mentionUserBeforeReplies: Boolean, vararg loriReplies: LorittaReply, addInlineReply: Boolean = true): Message { val message = StringBuilder() if (mentionUserBeforeReplies) { message.append(LorittaReply().build(this)) message.append("\n") } for (loriReply in loriReplies) { message.append(loriReply.build(this)) message.append("\n") } return sendMessage(message.toString(), addInlineReply = addInlineReply) } suspend fun reply(image: BufferedImage, fileName: String, vararg loriReplies: LorittaReply): Message { val message = StringBuilder() for (loriReply in loriReplies) { message.append(loriReply.build(this) + "\n") } return sendFile(image, fileName, message.toString()) } suspend fun sendMessage(message: String, addInlineReply: Boolean = true): Message { return sendMessage( MessageCreateBuilder() .denyMentions( Message.MentionType.EVERYONE, Message.MentionType.HERE ) .addContent(if (message.isEmpty()) " " else message) .build(), addInlineReply = addInlineReply ) } suspend fun sendMessage(message: String, embed: MessageEmbed, addInlineReply: Boolean = true): Message { return sendMessage(MessageCreateBuilder() .denyMentions( Message.MentionType.EVERYONE, Message.MentionType.HERE ) .addEmbeds(embed) .addContent(if (message.isEmpty()) " " else message) .build(), addInlineReply = addInlineReply ) } suspend fun sendMessageEmbeds(embed: MessageEmbed, addInlineReply: Boolean = true): Message { return sendMessage( MessageCreateBuilder() .denyMentions( Message.MentionType.EVERYONE, Message.MentionType.HERE ) .addContent(getAsMention(true)) .addEmbeds(embed) .build(), addInlineReply = addInlineReply ) } suspend fun sendMessage(message: MessageCreateData, addInlineReply: Boolean = true): Message { if (isPrivateChannel || event.channel.canTalk()) { return event.channel.sendMessage(message) .referenceIfPossible(event.message, config, addInlineReply) .await() } else { throw RuntimeException("Sem permissão para enviar uma mensagem!") } } suspend fun sendMessage(webhook: WebhookClient?, message: WebhookMessage, addInlineReply: Boolean = true) { if (!isPrivateChannel && webhook != null) { // Se a webhook é diferente de null, então use a nossa webhook disponível! webhook.send(message) } else { // Se não, iremos usar embeds mesmo... val builder = EmbedBuilder() builder.setAuthor(message.username, null, message.avatarUrl) builder.setDescription(message.content) builder.setFooter("Não consigo usar as permissões de webhook aqui... então estou usando o modo de pobre!", null) sendMessageEmbeds(builder.build(), addInlineReply = addInlineReply) } } suspend fun sendFile(file: File, name: String, message: String, embed: MessageEmbed? = null): Message { // Corrigir erro ao construir uma mensagem vazia val builder = MessageCreateBuilder() .denyMentions( Message.MentionType.EVERYONE, Message.MentionType.HERE ) builder.addContent(if (message.isEmpty()) " " else message) if (embed != null) builder.addEmbeds(embed) return sendFile(file, name, builder.build()) } suspend fun sendFile(file: File, name: String, message: MessageCreateData): Message { val inputStream = file.inputStream() return sendFile(inputStream, name, MessageCreateBuilder.from(message)) } suspend fun sendFile(image: BufferedImage, name: String, embed: MessageEmbed): Message { return sendFile(image, name, "", embed) } suspend fun sendFile(image: BufferedImage, name: String, message: String, embed: MessageEmbed? = null): Message { val builder = MessageCreateBuilder() builder.addContent(if (message.isEmpty()) " " else message) if (embed != null) builder.addEmbeds(embed) return sendFile(image, name, builder.build()) } suspend fun sendFile(image: BufferedImage, name: String, message: MessageCreateData): Message { val output = ByteArrayOutputStream() ImageIO.write(image, "png", output) val inputStream = ByteArrayInputStream(output.toByteArray(), 0, output.size()) return sendFile(inputStream, name, MessageCreateBuilder.from(message)) } suspend fun sendFile(inputStream: InputStream, name: String, message: String): Message { // Corrigir erro ao construir uma mensagem vazia val builder = MessageCreateBuilder() builder.addContent(if (message.isEmpty()) " " else message) return sendFile(inputStream, name, builder) } suspend fun sendFile(inputStream: InputStream, name: String, embed: MessageEmbed): Message { return sendFile(inputStream, name, "", embed) } suspend fun sendFile(inputStream: InputStream, name: String, message: String, embed: MessageEmbed? = null): Message { // Corrigir erro ao construir uma mensagem vazia val builder = MessageCreateBuilder() .denyMentions( Message.MentionType.EVERYONE, Message.MentionType.HERE ) builder.addContent(if (message.isEmpty()) " " else message) if (embed != null) builder.addEmbeds(embed) return sendFile(inputStream, name, builder) } suspend fun sendFile(inputStream: InputStream, name: String, builder: MessageCreateBuilder): Message { if (isPrivateChannel || event.channel.canTalk()) { val sentMessage = event.channel.sendMessage(builder.addFiles(FileUpload.fromData(inputStream, name)).build()) .referenceIfPossible(event.message, config, true) .await() return sentMessage } else { throw RuntimeException("Sem permissão para enviar uma mensagem!") } } /** * Gets an user from the argument index via mentions, username#oldDiscriminator, effective name, username and user ID * * @param argument the argument index on the rawArgs array * @return the user object or null, if nothing was found * @see User */ suspend fun getUserAt(argument: Int) = this.rawArgs.getOrNull(argument) ?.let { DiscordUtils.extractUserFromString( loritta, it, message.mentions.users, if (isPrivateChannel) null else guild ) } /** * Gets an image URL from the argument index via valid URLs at the specified index * * @param argument the argument index on the rawArgs array * @param search how many messages will be retrieved from the past to get images (default: 25) * @param avatarSize the size of retrieved user avatars from Discord (default: 2048) * @return the image URL or null, if nothing was found */ suspend fun getImageUrlAt(argument: Int, search: Int = 25, avatarSize: Int = 256): String? { if (this.rawArgs.size > argument) { // Primeiro iremos verificar se existe uma imagem no argumento especificado val link = this.rawArgs[argument] // Ok, será que isto é uma URL? if (LorittaUtils.isValidUrl(link) && loritta.connectionManager.isTrusted(link)) return link // Se é um link, vamos enviar para o usuário agora // Vamos verificar por usuários no argumento especificado val user = getUserAt(argument) if (user != null) return user.getEffectiveAvatarUrl(ImageFormat.PNG, avatarSize) // Ainda não?!? Vamos verificar se é um emoji. // Um emoji custom do Discord é + ou - assim: <:loritta:324931508542504973> for (emote in this.message.mentions.customEmojis) { if (link.equals(emote.asMention, ignoreCase = true)) { return emote.imageUrl } } for (embed in this.message.embeds) { if (embed.image != null && loritta.connectionManager.isTrusted(embed.image!!.url!!)) return embed.image!!.url } for (attachment in this.message.attachments) { if (attachment.isImage && loritta.connectionManager.isTrusted(attachment.url)) return attachment.url } // Se não é nada... então talvez seja um emoji padrão do Discordão! // Na verdade é um emoji padrão... try { var unicodeEmoji = LorittaUtils.toUnicode(this.rawArgs[argument].codePointAt(0)) // Vamos usar codepoints porque emojis unicodeEmoji = unicodeEmoji.substring(2) // Remover coisas desnecessárias val toBeDownloaded = "https://twemoji.maxcdn.com/2/72x72/$unicodeEmoji.png" if (HttpRequest.get(toBeDownloaded).code() == 200) { return toBeDownloaded } } catch (e: Exception) { } } // Nothing found? Try retrieving the replied message content if (!this.isPrivateChannel && this.guild.selfMember.hasPermission(this.event.channel as GuildChannel, Permission.MESSAGE_HISTORY)) { val referencedMessage = message.referencedMessage if (referencedMessage != null) { for (embed in referencedMessage.embeds) { if (embed.image != null && loritta.connectionManager.isTrusted(embed.image!!.url!!)) return embed.image!!.url } for (attachment in referencedMessage.attachments) { if (attachment.isImage && loritta.connectionManager.isTrusted(attachment.url)) return attachment.url } } } // Ainda nada válido? Quer saber, desisto! Vamos pesquisar as mensagens antigas deste servidor & embeds então para encontrar attachments... if (search > 0 && !this.isPrivateChannel && this.guild.selfMember.hasPermission(this.event.channel as GuildChannel, Permission.MESSAGE_HISTORY)) { try { val message = this.message.channel.history.retrievePast(search).await() attach@ for (msg in message) { for (embed in msg.embeds) { if (embed.image != null && loritta.connectionManager.isTrusted(embed.image!!.url!!)) { return embed.image!!.url } } for (attachment in msg.attachments) { if (attachment.isImage && loritta.connectionManager.isTrusted(attachment.url)) { return attachment.url } } } } catch (e: PermissionException) { } } return null } /** * Gets an image from the argument index via valid URLs at the specified index * * @param argument the argument index on the rawArgs array * @param search how many messages will be retrieved from the past to get images (default: 25) * @param avatarSize the size of retrieved user avatars from Discord (default: 2048) * @return the image object or null, if nothing was found * @see BufferedImage */ suspend fun getImageAt(argument: Int, search: Int = 25, avatarSize: Int = 256, createTextAsImageIfNotFound: Boolean = true): BufferedImage? { var toBeDownloaded = getImageUrlAt(argument, 0, avatarSize) if (toBeDownloaded == null) { if (rawArgs.isNotEmpty() && createTextAsImageIfNotFound) { val textForTheImage = rawArgs.drop(argument) .joinToString(" ") if (textForTheImage.isNotBlank()) return ImageUtils.createTextAsImage(loritta, 256, 256, rawArgs.drop(argument).joinToString(" ")) } if (search != 0) { toBeDownloaded = getImageUrlAt(argument, search, avatarSize) } } if (toBeDownloaded == null) return null // Vamos baixar a imagem! try { // Workaround para imagens do prnt.scr/prntscr.com (mesmo que o Lightshot seja um lixo) if (toBeDownloaded.contains("prnt.sc") || toBeDownloaded.contains("prntscr.com")) { val document = Jsoup.connect(toBeDownloaded).get() val elements = document.getElementsByAttributeValue("property", "og:image") if (!elements.isEmpty()) { toBeDownloaded = elements.attr("content") } } return LorittaUtils.downloadImage(loritta, toBeDownloaded ?: return null) } catch (e: Exception) { return null } } }
agpl-3.0
ff18d1e8ebc8d4c1be8346a95c688266
34.033735
148
0.726322
3.622975
false
false
false
false
MichaelRocks/lightsaber
processor/src/main/java/io/michaelrocks/lightsaber/processor/analysis/ComponentsAnalyzer.kt
1
3205
/* * Copyright 2020 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.lightsaber.processor.analysis import io.michaelrocks.grip.Grip import io.michaelrocks.grip.annotatedWith import io.michaelrocks.grip.classes import io.michaelrocks.grip.mirrors.Type import io.michaelrocks.lightsaber.processor.ErrorReporter import io.michaelrocks.lightsaber.processor.commons.Types import io.michaelrocks.lightsaber.processor.graph.DirectedGraph import io.michaelrocks.lightsaber.processor.graph.HashDirectedGraph import io.michaelrocks.lightsaber.processor.graph.reversed import io.michaelrocks.lightsaber.processor.model.Component import java.io.File interface ComponentsAnalyzer { fun analyze(files: Collection<File>): Collection<Component> } class ComponentsAnalyzerImpl( private val grip: Grip, private val moduleRegistry: ModuleRegistry, private val errorReporter: ErrorReporter ) : ComponentsAnalyzer { override fun analyze(files: Collection<File>): Collection<Component> { val componentsQuery = grip select classes from files where annotatedWith(Types.COMPONENT_TYPE) val graph = buildComponentGraph(componentsQuery.execute().types) val reversedGraph = graph.reversed() return graph.vertices .filterNot { it == Types.COMPONENT_NONE_TYPE } .map { type -> val parent = reversedGraph.getAdjacentVertices(type)?.first()?.takeIf { it != Types.COMPONENT_NONE_TYPE } val defaultModule = moduleRegistry.getModule(type) val subcomponents = graph.getAdjacentVertices(type).orEmpty().toList() Component(type, parent, defaultModule, subcomponents) } } private fun buildComponentGraph(types: Collection<Type.Object>): DirectedGraph<Type.Object> { val graph = HashDirectedGraph<Type.Object>() for (type in types) { val mirror = grip.classRegistry.getClassMirror(type) if (mirror.signature.typeVariables.isNotEmpty()) { errorReporter.reportError("Component cannot have a type parameters: ${type.className}") continue } val annotation = mirror.annotations[Types.COMPONENT_TYPE] if (annotation == null) { errorReporter.reportError("Class ${type.className} is not a component") continue } val parent = annotation.values["parent"] as Type? if (parent != null && parent != Types.COMPONENT_NONE_TYPE) { if (parent is Type.Object) { graph.put(parent, type) } else { errorReporter.reportError("Parent component of ${type.className} is not a class") } } else { graph.put(Types.COMPONENT_NONE_TYPE, type) } } return graph } }
apache-2.0
bd9a12cd38f6ac32907b28ec70473117
36.705882
113
0.728549
4.432918
false
false
false
false
signed/intellij-community
plugins/stats-collector/src/com/intellij/stats/completion/CompletionLoggerImpl.kt
1
7585
package com.intellij.stats.completion import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementPresentation import com.intellij.codeInsight.lookup.impl.LookupImpl import com.intellij.ide.plugins.PluginManager import com.intellij.lang.Language import com.intellij.openapi.application.PermanentInstallationID import com.intellij.openapi.components.ApplicationComponent import com.intellij.psi.util.PsiUtilCore import com.intellij.stats.events.completion.* import java.util.* class CompletionFileLoggerProvider(filePathProvider: FilePathProvider) : ApplicationComponent, CompletionLoggerProvider() { private val logFileManager = LogFileManager(filePathProvider) override fun disposeComponent() { logFileManager.dispose() } private fun String.shortedUUID(): String { val start = this.lastIndexOf('-') if (start > 0 && start + 1 < this.length) { return this.substring(start + 1) } return this } override fun newCompletionLogger(): CompletionLogger { val installationUID = PermanentInstallationID.get() val completionUID = UUID.randomUUID().toString() return CompletionFileLogger(installationUID.shortedUUID(), completionUID.shortedUUID(), logFileManager) } } class CompletionFileLogger(private val installationUID: String, private val completionUID: String, private val logFileManager: LogFileManager) : CompletionLogger() { val elementToId = mutableMapOf<String, Int>() private fun LookupElement.toIdString(): String { val p = LookupElementPresentation() renderElement(p) return "${p.itemText} ${p.tailText} ${p.typeText}" } private fun registerElement(item: LookupElement): Int { val itemString = item.toIdString() val newId = elementToId.size elementToId[itemString] = newId return newId } private fun getElementId(item: LookupElement): Int? { val itemString = item.toIdString() return elementToId[itemString] } private fun logEvent(event: LogEvent) { val line = LogEventSerializer.toString(event) logFileManager.println(line) } private fun getRecentlyAddedLookupItems(items: List<LookupElement>): List<LookupElement> { val newElements = items.filter { getElementId(it) == null } newElements.forEach { registerElement(it) } return newElements } fun List<LookupElement>.toLookupInfos(lookup: LookupImpl): List<LookupEntryInfo> { val relevanceObjects = lookup.getRelevanceObjects(this, false) return this.map { val id = getElementId(it)!! val relevanceMap = relevanceObjects[it]?.map { Pair(it.first, it.second?.toString()) }?.toMap() LookupEntryInfo(id, it.lookupString.length, relevanceMap) } } override fun completionStarted(lookup: LookupImpl, isExperimentPerformed: Boolean, experimentVersion: Int) { val lookupItems = lookup.items lookupItems.forEach { registerElement(it) } val relevanceObjects = lookup.getRelevanceObjects(lookupItems, false) val lookupEntryInfos = lookupItems.map { val id = getElementId(it)!! val relevanceMap = relevanceObjects[it]?.map { Pair(it.first, it.second?.toString()) }?.toMap() LookupEntryInfo(id, it.lookupString.length, relevanceMap) } val language = getLanguage(lookup) val ideVersion = PluginManager.BUILD_NUMBER ?: "ideVersion" val pluginVersion = calcPluginVersion() ?: "pluginVersion" val mlRankingVersion: String = "NONE" val event = CompletionStartedEvent( ideVersion, pluginVersion, mlRankingVersion, installationUID, completionUID, language?.displayName, isExperimentPerformed, experimentVersion, lookupEntryInfos, selectedPosition = 0) event.isOneLineMode = lookup.editor.isOneLineMode logEvent(event) } private fun calcPluginVersion(): String? { val className = CompletionStartedEvent::class.java.name val id = PluginManager.getPluginByClassName(className) val plugin = PluginManager.getPlugin(id) return plugin?.version } private fun getLanguage(lookup: LookupImpl): Language? { val file = lookup.psiFile ?: return null val offset = lookup.editor.caretModel.offset return PsiUtilCore.getLanguageAtOffset(file, offset) } override fun customMessage(message: String) { val event = CustomMessageEvent(installationUID, completionUID, message) logEvent(event) } override fun afterCharTyped(c: Char, lookup: LookupImpl) { val lookupItems = lookup.items val newItems = getRecentlyAddedLookupItems(lookupItems).toLookupInfos(lookup) val ids = lookupItems.map { getElementId(it)!! } val currentPosition = lookupItems.indexOf(lookup.currentItem) val event = TypeEvent(installationUID, completionUID, ids, newItems, currentPosition) logEvent(event) } override fun downPressed(lookup: LookupImpl) { val lookupItems = lookup.items val newInfos = getRecentlyAddedLookupItems(lookupItems).toLookupInfos(lookup) val ids = if (newInfos.isNotEmpty()) lookupItems.map { getElementId(it)!! } else emptyList<Int>() val currentPosition = lookupItems.indexOf(lookup.currentItem) val event = DownPressedEvent(installationUID, completionUID, ids, newInfos, currentPosition) logEvent(event) } override fun upPressed(lookup: LookupImpl) { val lookupItems = lookup.items val newInfos = getRecentlyAddedLookupItems(lookupItems).toLookupInfos(lookup) val ids = if (newInfos.isNotEmpty()) lookupItems.map { getElementId(it)!! } else emptyList<Int>() val currentPosition = lookupItems.indexOf(lookup.currentItem) val event = UpPressedEvent(installationUID, completionUID, ids, newInfos, currentPosition) logEvent(event) } override fun completionCancelled() { val event = CompletionCancelledEvent(installationUID, completionUID) logEvent(event) } override fun itemSelectedByTyping(lookup: LookupImpl) { val current = lookup.currentItem val id = if (current != null) getElementId(current)!! else -1 val event = TypedSelectEvent(installationUID, completionUID, id) logEvent(event) } override fun itemSelectedCompletionFinished(lookup: LookupImpl) { val current = lookup.currentItem val (index, id) = if (current != null) { lookup.items.indexOf(current) to (getElementId(current) ?: -1) } else { -1 to -1 } val event = ExplicitSelectEvent(installationUID, completionUID, emptyList(), emptyList(), index, id) logEvent(event) } override fun afterBackspacePressed(lookup: LookupImpl) { val lookupItems = lookup.items val newInfos = getRecentlyAddedLookupItems(lookupItems).toLookupInfos(lookup) val ids = lookupItems.map { getElementId(it)!! } val currentPosition = lookupItems.indexOf(lookup.currentItem) val event = BackspaceEvent(installationUID, completionUID, ids, newInfos, currentPosition) logEvent(event) } }
apache-2.0
aaae8cfeb04acb47c2a607ba82eedc0d
36.369458
123
0.675939
5.188098
false
false
false
false
septemberboy7/kotlin_bmi
app/src/main/java/me/myatminsoe/bmicalculator/MainActivity.kt
1
3628
package me.myatminsoe.bmicalculator import android.graphics.drawable.GradientDrawable import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import android.view.View import android.webkit.WebView import android.widget.TextView import kotlinx.android.synthetic.main.activity_main.* import org.adw.library.widgets.discreteseekbar.DiscreteSeekBar class MainActivity : AppCompatActivity() { private val LICENSES_FILE_PATH: String = "file:///android_asset/licenses.html" companion object { private val CATEGORY_CODE_MAP: HashMap<Int, String> = HashMap(5) init { CATEGORY_CODE_MAP.put(R.color.blue, "Underweight") CATEGORY_CODE_MAP.put(R.color.green, "Healthy") CATEGORY_CODE_MAP.put(R.color.yellow, "Overweight") CATEGORY_CODE_MAP.put(R.color.orange, "Obese") CATEGORY_CODE_MAP.put(R.color.red, "Extremely Obese") } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) sbWeight.setOnProgressChangeListener(BMIProgressChangeListener(tvWeight, getString(R.string.unit_kg))) sbHeight.setOnProgressChangeListener(BMIProgressChangeListener(tvHeight, getString(R.string.unit_cm))) } fun calculate(v: View) { val weight = sbWeight.progress.toDouble() val height = sbHeight.progress.toDouble() / 100 // Calculate bmi val bmiDetails = BMIUtils.calculateBMI(weight, height) // Update the TextView content tvBMI.text = bmiDetails.first // Fetch the category identifier color code val categoryIdentifierColorCode: Int = BMIUtils.getCategoryIdentifier(bmiDetails.second) // Update Category TextView's text and background updateViews(CATEGORY_CODE_MAP.get(categoryIdentifierColorCode), categoryIdentifierColorCode) } private fun updateViews(category: String?, colorCode: Int) { tvResult.text = category; // tvResult.setTextColor(ContextCompat.getColor(this, colorCode)) (tvBMI.background as GradientDrawable).setColor(ContextCompat.getColor(this, colorCode)) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item?.itemId == R.id.action_license) { val wv = WebView(this) wv.loadUrl(LICENSES_FILE_PATH) val builder = AlertDialog.Builder(this) .setTitle(getString(R.string.licences)) .setView(wv) .setPositiveButton(getString(R.string.ok)) { dialog, which -> dialog.dismiss() } builder.show() } return super.onOptionsItemSelected(item) } /** * Inner class for monitoring changes in seek bar progress */ inner class BMIProgressChangeListener(var tv: TextView, var unit: String) : DiscreteSeekBar.OnProgressChangeListener { override fun onProgressChanged(seekBar: DiscreteSeekBar?, value: Int, fromUser: Boolean) { tv.text = [email protected](R.string.bmi_value_formatted, value, unit) } override fun onStartTrackingTouch(seekBar: DiscreteSeekBar?) { } override fun onStopTrackingTouch(seekBar: DiscreteSeekBar?) { } } }
apache-2.0
094e746d6720d6a876f327a459df28d7
35.646465
122
0.689361
4.360577
false
false
false
false
darakeon/dfm
android/TestUtils/src/main/kotlin/com/darakeon/dfm/testutils/api/CallMock.kt
1
1610
package com.darakeon.dfm.testutils.api import okhttp3.MediaType import okhttp3.Request import okhttp3.ResponseBody import okio.Timeout import retrofit2.Call import retrofit2.Callback import retrofit2.Response open class CallMock<Body>( private val newBody: (String) -> Body, private val result: String?, private val error: Exception?, ) : Call<Body> { private val callbacks = ArrayList<Callback<Body>>() private var executed = false private var cancelled = false protected constructor(newBody: (String) -> Body) : this(newBody, "", null) protected constructor(newBody: (String) -> Body, result: String) : this(newBody, result, null) protected constructor(newBody: (String) -> Body, error: Exception) : this(newBody, null, error) override fun enqueue(callback: Callback<Body>) { callbacks.add(callback) } override fun isExecuted() = executed override fun clone() = this override fun isCanceled() = cancelled override fun cancel() { cancelled = true } override fun execute(): Response<Body> { executed = true if (result != null) { val body = newBody(result) val success = Response.success(body) callbacks.forEach { it.onResponse(this, success) } return success } if (error != null) { callbacks.forEach { it.onFailure(this, error) } } val errorBody = ResponseBody.create( MediaType.get("text/plain"), error?.message ?: "" ) return Response.error(500, errorBody) } override fun request(): Request { return Request.Builder() .url("http://dontflymoney.com/tests") .build() } override fun timeout() = Timeout() }
gpl-3.0
bc3ab8c2e4d7d09fa8a22e442501bb9d
20.466667
67
0.701242
3.515284
false
false
false
false
gatheringhallstudios/MHGenDatabase
app/src/main/java/com/ghstudios/android/features/armorsetbuilder/ArmorSetCalculator.kt
1
7028
package com.ghstudios.android.features.armorsetbuilder import android.util.Log import com.ghstudios.android.data.DataManager import com.ghstudios.android.data.classes.* import java.util.* private const val MINIMUM_SKILL_ACTIVATION_POINTS = 10 private const val SECRET_ARTS_BOOST = 2 // todo: move this to some sort of data constants location private const val TORSO_UP_ID = 203L // Skilltree ID for the TorsoUp skill private const val SECRET_ARTS_ID = 204L // Skilltree ID. Needs 10 points in the skill for +2 to all other skills private const val TALISMAN_BOOST_ID = 205L // Skilltree Id. Needs 10 points in the skill for x2 talisman skills /** * Calculates the skill totals of a given armor set, storing the results * in the "results" variable. After updating the armor set, call "recalculate()" * to update the results. */ class ArmorSetCalculator(val set: ArmorSet) { /** * Internal backing data for the list of results. This allows results * to be exposed as immutable */ private val data = mutableListOf<SkillTreeInSet>() private var torsoUpCount: Int = 0 private var secretArtsActivated: Boolean = false private var talismanBoostActivated: Boolean = false /** * Contains the list of results. The contents are calculated * on construction, and updated everytime "recalculate()" is called. */ val results: List<SkillTreeInSet> = Collections.unmodifiableList(data) init { recalculate() } /** * Adds any skills to the armor set's skill trees that were not there before, and removes those no longer there. * Adding decorations and armor does not update skilltrees unless this method is called */ fun recalculate() { // Reset data data.clear() // A map of the skill trees in the set and their associated SkillTreePointsSets val skillTreeToResult = mutableMapOf<Long, SkillTreeInSet>() // Iterate over set pieces, accumulating results into the above result map for (piece in set.pieces) { val idx = piece.idx Log.v("ASB", "Reading skills from armor piece $idx") val armorSkillTreePoints = getSkillsFromArmorPiece(piece) // A map of the current piece of armor's skills, localized so we don't have to keep calling it for (skillTreePoints in armorSkillTreePoints) { val skillTree = skillTreePoints.skillTree val points = skillTreePoints.points // Retrieve the existing result row...or create if it doesn't exist val skillRow = skillTreeToResult.getOrPut(skillTree.id) { Log.v("ASB", "Adding skill tree ${skillTree.name} to the list of Skill Trees in the armor set.") SkillTreeInSet(skillTree) } // Set the points for the given "set slot" skillRow.setPoints(idx, points) } } // do some final checks (torso up, secret arts, talisman boost) torsoUpCount = skillTreeToResult[TORSO_UP_ID]?.getTotal() ?: 0 secretArtsActivated = skillTreeToResult[SECRET_ARTS_ID]?.active ?: false talismanBoostActivated = skillTreeToResult[TALISMAN_BOOST_ID]?.active ?: false // Add the results, and sort from largest to smallest data.addAll(skillTreeToResult.values) data.sortByDescending { it.getTotal() } } /** * A helper method that converts an armor piece present in the current set into a map of the skills it provides and the respective points in each. * @return A map of all the skills the armor piece provides along with the number of points in each. */ private fun getSkillsFromArmorPiece(armorSetPiece: ArmorSetPiece): List<SkillTreePoints> { val dataManager = DataManager.get() val equipment = armorSetPiece.equipment val decorations = armorSetPiece.decorations // mapping of skilltree id to skilltree points. The values are returned in the end val skillCache = mutableMapOf<Long, SkillTreePoints>() // Get points from the equipment/talisman itself first if (equipment is ASBTalisman) { equipment.firstSkill?.let { skillCache[it.skillTree.id] = it } equipment.secondSkill?.let { skillCache[it.skillTree.id] = it } } else { val equipmentSkills = dataManager.queryItemToSkillTreeArrayItem(equipment.id) for (itemToSkillTree in equipmentSkills) { // We add skills for armor skillCache[itemToSkillTree.skillTree.id] = itemToSkillTree } } // Add decorations for (d in decorations) { val decorationSkills = dataManager.queryItemToSkillTreeArrayItem(d.id) for (itemToSkillTree in decorationSkills) { val skillTree = itemToSkillTree.skillTree val points = itemToSkillTree.points // SkillPoints are immmutable, so if we're adding, create a new entry val totalPoints = points + (skillCache[skillTree.id]?.points ?: 0) skillCache[skillTree.id] = SkillTreePoints(skillTree, totalPoints) } } return skillCache.values.toList() } /** * A container class that represents a skill tree as well as a specific number of points provided by each armor piece in a set. * TODO: More descriptive name */ inner class SkillTreeInSet(val skillTree: SkillTree) { // note: points will likely change to a different object once weapon decos are live private val points = sortedMapOf<Int, Int>() val active get() = getTotal() >= MINIMUM_SKILL_ACTIVATION_POINTS fun getPoints(pieceIndex: Int): Int { val basePoints = points[pieceIndex] ?: 0 return if (pieceIndex == ArmorSet.BODY) { // TorsoUp stacks, so you multiply the skill * number of occurrences basePoints * (torsoUpCount + 1) } else if (pieceIndex == ArmorSet.TALISMAN && talismanBoostActivated) { // if talisman boost is activated, talisman skills are doubled basePoints * 2 } else { basePoints } } /** * @return The total number of skill points provided to the skill by all pieces in the set. */ fun getTotal(): Int { var total = 0 for (pieceIndex in points.keys) { total += getPoints(pieceIndex) } // If Secret Arts is active, proc it // note that secret arts also adds to itself if (secretArtsActivated && skillTree.id != TORSO_UP_ID) { total += SECRET_ARTS_BOOST } return total } fun setPoints(pieceIndex: Int, piecePoints: Int) { points[pieceIndex] = piecePoints } } }
mit
b69c94d57320e0df02aafb7fcc8e240c
39.165714
164
0.635031
4.581486
false
false
false
false
jiangkang/KTools
tools/src/main/java/com/jiangkang/tools/system/ContactsLoaderCallback.kt
1
3349
package com.jiangkang.tools.system import android.content.Context import android.database.Cursor import android.os.Bundle import android.provider.ContactsContract import androidx.loader.app.LoaderManager import androidx.loader.content.CursorLoader import androidx.loader.content.Loader import com.jiangkang.tools.struct.JsonGenerator import okhttp3.internal.closeQuietly import org.json.JSONArray import org.json.JSONObject import kotlin.concurrent.thread /** * Created by jiangkang on 2017/9/13. */ class ContactsLoaderCallback(private val context: Context) : LoaderManager.LoaderCallbacks<Cursor> { private var result: JSONObject? = null private var listener: QueryListener? = null override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> { //指定获取_id和display_name两列数据,display_name即为姓名 val projection = arrayOf( ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME ) return CursorLoader( context, ContactsContract.Contacts.CONTENT_URI, projection, null, null, null ) } override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor) { if (data.isClosed) { return } thread { handleCursor(data) } } private fun handleCursor(data: Cursor?) { val jsonArray = JSONArray() if (data != null && data.moveToFirst()) { do { val name = data.getString(data.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)) val id = data.getInt(data.getColumnIndex(ContactsContract.Contacts._ID)) //指定获取NUMBER这一列数据 val phoneProjection = arrayOf( ContactsContract.CommonDataKinds.Phone.NUMBER ) val cursor = context.contentResolver.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, phoneProjection, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id, null, null ) if (cursor != null && cursor.moveToFirst()) { do { val number = cursor.getString( cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER) ) jsonArray.put( JsonGenerator() .put("name", name) .put("tel", number) .gen() ) } while (cursor.moveToNext()) } cursor?.closeQuietly() } while (data.moveToNext()) } result = JsonGenerator() .put("list", jsonArray) .gen() listener?.success(result) } override fun onLoaderReset(loader: Loader<Cursor>) {} fun setQueryListener(listener: QueryListener?) { this.listener = listener } interface QueryListener { fun success(json: JSONObject?) } }
mit
299f8bdfbbef919cabc87032e3c30e76
33.416667
102
0.544959
5.477612
false
false
false
false
yschimke/oksocial
src/main/kotlin/com/baulsupp/okurl/ws/OkWsCommand.kt
1
1111
package com.baulsupp.okurl.ws import com.baulsupp.oksocial.output.UsageException import com.baulsupp.okurl.Main import com.baulsupp.okurl.commands.MainAware import com.baulsupp.okurl.commands.ShellCommand import com.baulsupp.okurl.kotlin.request import okhttp3.OkHttpClient import okhttp3.Request import java.util.Scanner class OkWsCommand : ShellCommand, MainAware { private var main: Main? = null override fun setMain(main: Main) { this.main = main } override fun name(): String { return "okws" } override fun handlesRequests(): Boolean { return true } override fun buildRequests(client: OkHttpClient, arguments: List<String>): List<Request> { if (arguments.size != 1) { throw UsageException("usage: okws wss://host") } val request = request(arguments[0]) val printer = WebSocketPrinter(main!!.outputHandler) val websocket = client.newWebSocket(request, printer) val sc = Scanner(System.`in`) while (sc.hasNextLine()) { val line = sc.nextLine() websocket.send(line) } printer.waitForExit() return listOf() } }
apache-2.0
dc4b51f330f961e631cd9d03213d0f5f
22.638298
92
0.709271
3.967857
false
false
false
false
GyrosWorkshop/WukongAndroid
wukong/src/main/java/com/senorsen/wukong/utils/Debounce.kt
1
463
package com.senorsen.wukong.utils; import kotlin.concurrent.thread class Debounce(val delay: Long) { private var posted = false private var action: (() -> Unit)? = null val runnable = Runnable { Thread.sleep(delay) posted = false action?.invoke() } fun run(action: (() -> Unit)?) { this.action = action if (!posted) { posted = true thread { runnable.run() } } } }
agpl-3.0
ff31e7a92d533eb956dd15387ecb05ff
21.047619
44
0.544276
4.133929
false
false
false
false
fnouama/intellij-community
platform/diff-impl/tests/com/intellij/diff/merge/MergeTestBase.kt
13
15594
/* * 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 com.intellij.diff.merge import com.intellij.diff.DiffContentFactoryImpl import com.intellij.diff.DiffTestCase import com.intellij.diff.DiffTestCase.Trio import com.intellij.diff.assertEquals import com.intellij.diff.assertTrue import com.intellij.diff.contents.DocumentContent import com.intellij.diff.merge.MergeTestBase.SidesState.BOTH import com.intellij.diff.merge.MergeTestBase.SidesState.LEFT import com.intellij.diff.merge.MergeTestBase.SidesState.NONE import com.intellij.diff.merge.MergeTestBase.SidesState.RIGHT import com.intellij.diff.merge.TextMergeTool.TextMergeViewer import com.intellij.diff.merge.TextMergeTool.TextMergeViewer.MyThreesideViewer import com.intellij.diff.util.DiffUtil import com.intellij.diff.util.Side import com.intellij.diff.util.TextDiffType import com.intellij.diff.util.ThreeSide import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider import com.intellij.openapi.project.Project import com.intellij.openapi.util.Couple import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.text.StringUtil import com.intellij.testFramework.fixtures.IdeaProjectTestFixture import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory import com.intellij.util.ui.UIUtil public abstract class MergeTestBase : DiffTestCase() { private var projectFixture: IdeaProjectTestFixture? = null private var project: Project? = null override fun setUp() { super.setUp() projectFixture = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(getTestName(true)).getFixture() projectFixture!!.setUp() project = projectFixture!!.getProject() } override fun tearDown() { projectFixture?.tearDown() project = null super.tearDown() } public fun test1(left: String, base: String, right: String, f: TestBuilder.() -> Unit) { test(left, base, right, 1, f) } public fun test2(left: String, base: String, right: String, f: TestBuilder.() -> Unit) { test(left, base, right, 2, f) } public fun testN(left: String, base: String, right: String, f: TestBuilder.() -> Unit) { test(left, base, right, -1, f) } public fun test(left: String, base: String, right: String, changesCount: Int, f: TestBuilder.() -> Unit) { val contentFactory = DiffContentFactoryImpl() val leftContent: DocumentContent = contentFactory.create(parseSource(left)) val baseContent: DocumentContent = contentFactory.create(parseSource(base)) val rightContent: DocumentContent = contentFactory.create(parseSource(right)) val outputContent: DocumentContent = contentFactory.create(parseSource("")) outputContent.getDocument().setReadOnly(false) val context = MockMergeContext(project) val request = MockMergeRequest(leftContent, baseContent, rightContent, outputContent) val viewer = TextMergeTool.INSTANCE.createComponent(context, request) as TextMergeViewer try { val toolbar = viewer.init() UIUtil.dispatchAllInvocationEvents() val builder = TestBuilder(viewer, toolbar.toolbarActions ?: emptyList()) builder.assertChangesCount(changesCount) builder.f() } finally { Disposer.dispose(viewer) } } public inner class TestBuilder(public val mergeViewer: TextMergeViewer, private val actions: List<AnAction>) { public val viewer: MyThreesideViewer = mergeViewer.getViewer() public val changes: List<TextMergeChange> = viewer.getAllChanges() public val editor: EditorEx = viewer.getEditor(ThreeSide.BASE) public val document: Document = editor.getDocument() private val textEditor = TextEditorProvider.getInstance().getTextEditor(editor); private val undoManager = UndoManager.getInstance(project!!) public fun change(num: Int): TextMergeChange { if (changes.size() < num) throw Exception("changes: ${changes.size()}, index: $num") return changes.get(num) } public fun activeChanges(): List<TextMergeChange> = viewer.getChanges() // // Actions // public fun runActionByTitle(name: String): Boolean { val action = actions.filter { name.equals(it.getTemplatePresentation().getText()) } assertTrue(action.size() == 1, action.toString()) return runAction(action.get(0)) } private fun runAction(action: AnAction): Boolean { val actionEvent = AnActionEvent.createFromAnAction(action, null, ActionPlaces.MAIN_MENU, editor.getDataContext()) action.update(actionEvent) val success = actionEvent.getPresentation().isEnabledAndVisible() if (success) action.actionPerformed(actionEvent) return success } // // Modification // public fun command(affected: TextMergeChange, f: () -> Unit): Unit { command(listOf(affected), f) } public fun command(affected: List<TextMergeChange>? = null, f: () -> Unit): Unit { viewer.executeMergeCommand(null, affected, f) UIUtil.dispatchAllInvocationEvents() } public fun write(f: () -> Unit): Unit { ApplicationManager.getApplication().runWriteAction({ CommandProcessor.getInstance().executeCommand(project, f, null, null) }) UIUtil.dispatchAllInvocationEvents() } public fun Int.ignore(side: Side, modifier: Boolean = false) { val change = change(this) command(change) { viewer.ignoreChange(change, side, modifier) } } public fun Int.apply(side: Side, modifier: Boolean = false) { val change = change(this) command(change) { viewer.replaceChange(change, side, modifier) } } // // Text modification // public fun insertText(offset: Int, newContent: CharSequence) { replaceText(offset, offset, newContent) } public fun deleteText(startOffset: Int, endOffset: Int) { replaceText(startOffset, endOffset, "") } public fun replaceText(startOffset: Int, endOffset: Int, newContent: CharSequence) { write { document.replaceString(startOffset, endOffset, parseSource(newContent)) } } public fun insertText(offset: LineCol, newContent: CharSequence) { replaceText(offset.toOffset(), offset.toOffset(), newContent) } public fun deleteText(startOffset: LineCol, endOffset: LineCol) { replaceText(startOffset.toOffset(), endOffset.toOffset(), "") } public fun replaceText(startOffset: LineCol, endOffset: LineCol, newContent: CharSequence) { write { replaceText(startOffset.toOffset(), endOffset.toOffset(), newContent) } } public fun replaceText(oldContent: CharSequence, newContent: CharSequence) { write { val range = findRange(parseSource(oldContent)) replaceText(range.first, range.second, newContent) } } public fun deleteText(oldContent: CharSequence) { write { val range = findRange(parseSource(oldContent)) replaceText(range.first, range.second, "") } } public fun insertTextBefore(oldContent: CharSequence, newContent: CharSequence) { write { insertText(findRange(parseSource(oldContent)).first, newContent) } } public fun insertTextAfter(oldContent: CharSequence, newContent: CharSequence) { write { insertText(findRange(parseSource(oldContent)).second, newContent) } } private fun findRange(oldContent: CharSequence): Couple<Int> { val text = document.getImmutableCharSequence() val index1 = StringUtil.indexOf(text, oldContent) assertTrue(index1 >= 0, "content - '\n$oldContent\n'\ntext - '\n$text'") val index2 = StringUtil.indexOf(text, oldContent, index1 + 1) assertTrue(index2 == -1, "content - '\n$oldContent\n'\ntext - '\n$text'") return Couple(index1, index1 + oldContent.length()) } // // Undo // public fun undo(count: Int = 1) { if (count == -1) { while (undoManager.isUndoAvailable(textEditor)) { undoManager.undo(textEditor) } } else { for (i in 1..count) { assertTrue(undoManager.isUndoAvailable(textEditor)) undoManager.undo(textEditor) } } } public fun redo(count: Int = 1) { if (count == -1) { while (undoManager.isRedoAvailable(textEditor)) { undoManager.redo(textEditor) } } else { for (i in 1..count) { assertTrue(undoManager.isRedoAvailable(textEditor)) undoManager.redo(textEditor) } } } public fun checkUndo(count: Int = -1, f: TestBuilder.() -> Unit) { val initialState = ViewerState.recordState(viewer) f() UIUtil.dispatchAllInvocationEvents() val afterState = ViewerState.recordState(viewer) undo(count) UIUtil.dispatchAllInvocationEvents() val undoState = ViewerState.recordState(viewer) redo(count) UIUtil.dispatchAllInvocationEvents() val redoState = ViewerState.recordState(viewer) assertEquals(initialState, undoState) assertEquals(afterState, redoState) } // // Checks // public fun assertChangesCount(expected: Int) { if (expected == -1) return val actual = activeChanges().size() assertEquals(expected, actual) } public fun Int.assertType(type: TextDiffType, changeType: SidesState) { assertType(type) assertType(changeType) } public fun Int.assertType(type: TextDiffType) { val change = change(this) assertEquals(change.getDiffType(), type) } public fun Int.assertType(changeType: SidesState) { assertTrue(changeType != NONE) val change = change(this) val actual = change.getType() val isLeftChange = changeType != RIGHT val isRightChange = changeType != LEFT assertEquals(Pair(isLeftChange, isRightChange), Pair(actual.isLeftChange(), actual.isRightChange())) } public fun Int.assertResolved(type: SidesState) { val change = change(this) val isLeftResolved = type == LEFT || type == BOTH val isRightResolved = type == RIGHT || type == BOTH assertEquals(Pair(isLeftResolved, isRightResolved), Pair(change.isResolved(Side.LEFT), change.isResolved(Side.RIGHT))) } public fun Int.assertRange(start: Int, end: Int) { val change = change(this) assertEquals(Pair(start, end), Pair(change.getStartLine(ThreeSide.BASE), change.getEndLine(ThreeSide.BASE))) } public fun Int.assertContent(expected: String, start: Int, end: Int) { assertContent(expected) assertRange(start, end) } public fun Int.assertContent(expected: String) { val change = change(this) val document = editor.getDocument() val actual = DiffUtil.getLinesContent(document, change.getStartLine(ThreeSide.BASE), change.getEndLine(ThreeSide.BASE)) assertEquals(parseSource(expected), actual) } public fun assertContent(expected: String) { val actual = viewer.getEditor(ThreeSide.BASE).getDocument().getImmutableCharSequence() assertEquals(parseSource(expected), actual) } // // Helpers // public fun Int.not(): LineColHelper = LineColHelper(this) public fun LineColHelper.minus(col: Int): LineCol = LineCol(this.line, col) public inner class LineColHelper(val line: Int) { } public inner data class LineCol(val line: Int, val col: Int) { public fun toOffset(): Int = editor.getDocument().getLineStartOffset(line) + col } } private class MockMergeContext(private val myProject: Project?) : MergeContext() { override fun getProject(): Project? = myProject override fun isFocused(): Boolean = false override fun requestFocus() { } override fun finishMerge(result: MergeResult) { } } private class MockMergeRequest(val left: DocumentContent, val base: DocumentContent, val right: DocumentContent, val output: DocumentContent) : TextMergeRequest() { override fun getTitle(): String? = null override fun applyResult(result: MergeResult) { } override fun getContents(): List<DocumentContent> = listOf(left, base, right) override fun getOutputContent(): DocumentContent = output override fun getContentTitles(): List<String?> = listOf(null, null, null) } public enum class SidesState { LEFT, RIGHT, BOTH, NONE } private data class ViewerState private constructor(private val content: CharSequence, private val changes: List<ViewerState.ChangeState>) { companion object { public fun recordState(viewer: MyThreesideViewer): ViewerState { val content = viewer.getEditor(ThreeSide.BASE).getDocument().getImmutableCharSequence() val changes = viewer.getAllChanges().map { recordChangeState(viewer, it) } return ViewerState(content, changes) } private fun recordChangeState(viewer: MyThreesideViewer, change: TextMergeChange): ChangeState { val document = viewer.getEditor(ThreeSide.BASE).getDocument(); val content = DiffUtil.getLinesContent(document, change.getStartLine(ThreeSide.BASE), change.getEndLine(ThreeSide.BASE)) val resolved = if (change.isResolved()) BOTH else if (change.isResolved(Side.LEFT)) LEFT else if (change.isResolved(Side.RIGHT)) RIGHT else NONE val starts = Trio.from { change.getStartLine(it) } val ends = Trio.from { change.getStartLine(it) } return ChangeState(content, starts, ends, resolved) } } override fun equals(other: Any?): Boolean { if (this identityEquals other) return true if (other !is ViewerState) return false if (!StringUtil.equals(content, other.content)) return false if (!changes.equals(other.changes)) return false return true } override fun hashCode(): Int = StringUtil.hashCode(content) private data class ChangeState(private val content: CharSequence, private val starts: Trio<Int>, private val ends: Trio<Int>, private val resolved: SidesState) { override fun equals(other: Any?): Boolean { if (this identityEquals other) return true if (other !is ChangeState) return false if (!StringUtil.equals(content, other.content)) return false if (!starts.equals(other.starts)) return false if (!ends.equals(other.ends)) return false if (!resolved.equals(other.resolved)) return false return true } } } }
apache-2.0
48c51848b4ea5f023faf73ad20d7eec7
35.265116
152
0.692189
4.678668
false
true
false
false
epabst/kotlin-showcase
src/jvmMain/kotlin/sample/SampleJvm.kt
1
899
package sample import io.ktor.application.* import io.ktor.html.* import io.ktor.http.content.* import io.ktor.routing.* import io.ktor.server.engine.* import io.ktor.server.netty.* import kotlinx.html.* fun main() { embeddedServer(Netty, port = 8080, host = "127.0.0.1") { routing { get("/") { call.respondHtml { head { title("Hello from Ktor!") } body { +"Hello from Ktor" div { id = "js-response" +"Loading..." } script(src = "/static/mpp.js") {} } } } static("/static") { resource("mpp.js") } } }.start(wait = true) }
apache-2.0
5637c08fbefd00f9f160e298591e4551
25.470588
60
0.384872
4.833333
false
false
false
false
xfournet/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/cellReader/ExtendedCellReaders.kt
1
4640
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testGuiFramework.cellReader import com.intellij.testGuiFramework.framework.GuiTestUtil import com.intellij.testGuiFramework.impl.GuiTestUtilKt.findAllWithBFS import com.intellij.ui.SimpleColoredComponent import com.intellij.ui.components.JBList import org.fest.swing.cell.JComboBoxCellReader import org.fest.swing.cell.JListCellReader import org.fest.swing.cell.JTableCellReader import org.fest.swing.cell.JTreeCellReader import org.fest.swing.driver.BasicJComboBoxCellReader import org.fest.swing.driver.BasicJListCellReader import org.fest.swing.driver.BasicJTableCellReader import org.fest.swing.driver.BasicJTreeCellReader import org.fest.swing.edt.GuiActionRunner import org.fest.swing.edt.GuiQuery import org.fest.swing.exception.ComponentLookupException import java.awt.Component import java.awt.Container import java.lang.Error import java.util.* import javax.annotation.Nonnull import javax.annotation.Nullable import javax.swing.* import javax.swing.tree.DefaultMutableTreeNode /** * @author Sergey Karashevich */ class ExtendedJTreeCellReader : BasicJTreeCellReader(), JTreeCellReader { override fun valueAt(tree: JTree, modelValue: Any?): String? { if (modelValue == null) return null val isLeaf = try { modelValue is DefaultMutableTreeNode && modelValue.leafCount == 1 } catch (e: Error) { false } val cellRendererComponent = tree.cellRenderer.getTreeCellRendererComponent(tree, modelValue, false, false, isLeaf, 0, false) return getValueWithCellRenderer(cellRendererComponent) } } class ExtendedJListCellReader : BasicJListCellReader(), JListCellReader { @Nullable override fun valueAt(@Nonnull list: JList<*>, index: Int): String? { val element = list.model.getElementAt(index) val cellRendererComponent = GuiTestUtil.getListCellRendererComponent(list, element, index) return getValueWithCellRenderer(cellRendererComponent) } } class ExtendedJTableCellReader : BasicJTableCellReader(), JTableCellReader { override fun valueAt(table: JTable, row: Int, column: Int): String? { val cellRendererComponent = table.prepareRenderer(table.getCellRenderer(row, column), row, column) return super.valueAt(table, row, column) ?: getValueWithCellRenderer(cellRendererComponent) } } class ExtendedJComboboxCellReader : BasicJComboBoxCellReader(), JComboBoxCellReader { private val REFERENCE_JLIST = newJList() override fun valueAt(comboBox: JComboBox<*>, index: Int): String? { val item: Any = comboBox.getItemAt(index) val listCellRenderer: ListCellRenderer<Any?> = comboBox.renderer as ListCellRenderer<Any?> val cellRendererComponent = listCellRenderer.getListCellRendererComponent(REFERENCE_JLIST, item, index, true, true) return getValueWithCellRenderer(cellRendererComponent) } @Nonnull private fun newJList(): JList<out Any?> { return GuiActionRunner.execute(object : GuiQuery<JList<out Any?>>() { override fun executeInEDT(): JList<out Any?> = JBList() })!! } } private fun getValueWithCellRenderer(cellRendererComponent: Component): String? { val result = when (cellRendererComponent) { is JLabel -> cellRendererComponent.text is SimpleColoredComponent -> cellRendererComponent.getText() else -> cellRendererComponent.findText() } return result?.trimEnd() } private fun SimpleColoredComponent.getText(): String? = this.iterator().asSequence().joinToString() private fun Component.findText(): String? { try { assert(this is Container) val container = this as Container val resultList = ArrayList<String>() resultList.addAll( findAllWithBFS(container, JLabel::class.java) .filter { !it.text.isNullOrEmpty() } .map { it.text } ) resultList.addAll( findAllWithBFS(container, SimpleColoredComponent::class.java) .filter { !it.getText().isNullOrEmpty() } .map { it.getText()!! } ) return resultList.firstOrNull { !it.isEmpty() } } catch (ignored: ComponentLookupException) { return null } }
apache-2.0
d357a1977d8f807578969b4c8980a4c2
34.968992
128
0.761422
4.491772
false
false
false
false
tsegismont/vertx-hawkular-metrics
src/main/kotlin/io/vertx/kotlin/ext/hawkular/MetricTagsMatch.kt
1
963
package io.vertx.kotlin.ext.hawkular import io.vertx.ext.hawkular.MetricTagsMatch import io.vertx.ext.hawkular.MetricTagsMatch.MatchType /** * A function providing a DSL for building [io.vertx.ext.hawkular.MetricTagsMatch] objects. * * Tags to apply to any metric which name matches the criteria. * * @param tags Set the tags to apply if metric name matches the criteria. * @param type Set the type of matching to apply. * @param value Set the matched value. * * <p/> * NOTE: This function has been automatically generated from the [io.vertx.ext.hawkular.MetricTagsMatch original] using Vert.x codegen. */ fun MetricTagsMatch( tags: io.vertx.core.json.JsonObject? = null, type: MatchType? = null, value: String? = null): MetricTagsMatch = io.vertx.ext.hawkular.MetricTagsMatch().apply { if (tags != null) { this.setTags(tags) } if (type != null) { this.setType(type) } if (value != null) { this.setValue(value) } }
apache-2.0
b685fbe70ddedd76bd0e3f7851dde310
28.181818
135
0.711319
3.286689
false
false
false
false
Reyurnible/gitsalad-android
app/src/debug/kotlin/com/hosshan/android/salad/DebugDataModule.kt
1
1327
package com.hosshan.android.salad import android.app.Application import android.content.Context import android.content.SharedPreferences import com.f2prateek.rx.preferences.RxSharedPreferences import com.hosshan.android.salad.repository.RepositoryModule import dagger.Module import dagger.Provides import javax.inject.Named import javax.inject.Singleton /** * Created by shunhosaka on 15/10/02. */ @Module(includes = arrayOf(RepositoryModule::class)) // ApiModule::class, class DebugDataModule : BaseDataModule { companion object { private const val PREF_NAME: String = "gitsalad_debug" private const val DB_NAME: String = "gitsalad_debug" private const val DB_VERSION: Long = 0L } @Named(BaseDataModule.Name.DB_NAME) @Provides override fun provideDatabaseName(): String = DB_NAME @Named(BaseDataModule.Name.DB_VERSION) @Provides override fun provideDatabaseVersion(): Long = DB_VERSION @Singleton @Provides override fun provideSharedPreferences(app: Application): SharedPreferences = app.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) @Singleton @Provides override fun provideRxSharedPreferences(sharedPreferences: SharedPreferences): RxSharedPreferences = RxSharedPreferences.create(sharedPreferences) }
mit
20a811fc4bb279e7a1039ef7029a95ca
29.860465
104
0.75358
4.575862
false
false
false
false
AerisG222/maw_photos_android
MaWPhotos/src/main/java/us/mikeandwan/photos/ui/controls/toolbar/ToolbarViewModel.kt
1
1858
package us.mikeandwan.photos.ui.controls.toolbar import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import us.mikeandwan.photos.domain.NavigationStateRepository import us.mikeandwan.photos.domain.SearchRepository import us.mikeandwan.photos.domain.models.NavigationArea import us.mikeandwan.photos.domain.models.SearchRequest import us.mikeandwan.photos.domain.models.SearchSource import javax.inject.Inject @HiltViewModel class ToolbarViewModel @Inject constructor( private val navigationStateRepository: NavigationStateRepository, private val searchRepository: SearchRepository, ): ViewModel() { val showAppIcon = navigationStateRepository.enableDrawer val toolbarTitle = navigationStateRepository.toolbarTitle private val _closeKeyboardSignal = MutableStateFlow(false) val closeKeyboardSignal = _closeKeyboardSignal.asStateFlow() val showSearch = navigationStateRepository .navArea .map { it == NavigationArea.Search } .stateIn(viewModelScope, SharingStarted.Eagerly, false) val searchRequest = searchRepository .searchRequest .stateIn(viewModelScope, SharingStarted.Eagerly, SearchRequest("", SearchSource.None)) fun onAppIconClicked() { navigationStateRepository.requestNavDrawerOpen() } fun onBackClicked() { navigationStateRepository.requestNavigateBack() } fun search(query: String) { _closeKeyboardSignal.value = true viewModelScope.launch { searchRepository .performSearch(query, SearchSource.QueryInterface) .collect { } } } fun closeKeyboardSignalHandled() { _closeKeyboardSignal.value = false } }
mit
92720c1e3126a44c3dd1a615ee7256ee
32.196429
94
0.753498
5.161111
false
false
false
false
vase4kin/TeamCityApp
app/src/main/java/com/github/vase4kin/teamcityapp/dagger/modules/ActivityBindingModule.kt
1
6759
/* * Copyright 2020 Andrey Tolpeev * * 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.github.vase4kin.teamcityapp.dagger.modules import com.github.vase4kin.teamcityapp.account.create.dagger.CreateAccountActivityScope import com.github.vase4kin.teamcityapp.account.create.dagger.CreateAccountModule import com.github.vase4kin.teamcityapp.account.create.view.CreateAccountActivity import com.github.vase4kin.teamcityapp.artifact.dagger.ArtifactActivityScope import com.github.vase4kin.teamcityapp.artifact.dagger.ArtifactsActivityModule import com.github.vase4kin.teamcityapp.artifact.view.ArtifactListActivity import com.github.vase4kin.teamcityapp.build_details.dagger.BuildDetailsActivityScope import com.github.vase4kin.teamcityapp.build_details.dagger.BuildDetailsFragmentsBindingModule import com.github.vase4kin.teamcityapp.build_details.dagger.BuildDetailsModule import com.github.vase4kin.teamcityapp.build_details.view.BuildDetailsActivity import com.github.vase4kin.teamcityapp.buildlist.dagger.BuildListActivityScope import com.github.vase4kin.teamcityapp.buildlist.dagger.BuildListAdapterModule import com.github.vase4kin.teamcityapp.buildlist.dagger.BuildListModule import com.github.vase4kin.teamcityapp.buildlist.view.BuildListActivity import com.github.vase4kin.teamcityapp.dagger.modules.about.AboutRepositoryModule import com.github.vase4kin.teamcityapp.dagger.modules.manage_accounts.ManageAccountsRouterModule import com.github.vase4kin.teamcityapp.dagger.modules.test_details.TestDetailsRepositoryModule import com.github.vase4kin.teamcityapp.filter_builds.dagger.FilterBuildsActivityScope import com.github.vase4kin.teamcityapp.filter_builds.dagger.FilterBuildsModule import com.github.vase4kin.teamcityapp.filter_builds.view.FilterBuildsActivity import com.github.vase4kin.teamcityapp.home.dagger.HomeActivityBindingModule import com.github.vase4kin.teamcityapp.home.dagger.HomeActivityScope import com.github.vase4kin.teamcityapp.home.dagger.HomeModule import com.github.vase4kin.teamcityapp.home.view.HomeActivity import com.github.vase4kin.teamcityapp.navigation.dagger.NavigationActivityScope import com.github.vase4kin.teamcityapp.navigation.dagger.NavigationBaseModule import com.github.vase4kin.teamcityapp.navigation.dagger.NavigationModule import com.github.vase4kin.teamcityapp.navigation.view.NavigationActivity import com.github.vase4kin.teamcityapp.runbuild.dagger.RunBuildActivityScope import com.github.vase4kin.teamcityapp.runbuild.dagger.RunBuildModule import com.github.vase4kin.teamcityapp.runbuild.view.RunBuildActivity import dagger.Module import dagger.android.ContributesAndroidInjector import teamcityapp.features.about.AboutActivity import teamcityapp.features.about.dagger.AboutActivityBindingModule import teamcityapp.features.about.dagger.AboutActivityScope import teamcityapp.features.change.dagger.ChangeActivityModule import teamcityapp.features.change.dagger.ChangeActivityScope import teamcityapp.features.change.view.ChangeActivity import teamcityapp.features.manage_accounts.dagger.ManageAccountsActivityScope import teamcityapp.features.manage_accounts.dagger.ManageAccountsModule import teamcityapp.features.manage_accounts.view.ManageAccountsActivity import teamcityapp.features.settings.dagger.SettingsActivityBindingModule import teamcityapp.features.settings.dagger.SettingsActivityModule import teamcityapp.features.settings.dagger.SettingsActivityScope import teamcityapp.features.settings.view.SettingsActivity import teamcityapp.features.test_details.dagger.TestDetailsActivityScope import teamcityapp.features.test_details.dagger.TestDetailsModule import teamcityapp.features.test_details.view.TestDetailsActivity @Module abstract class ActivityBindingModule { @AboutActivityScope @ContributesAndroidInjector( modules = [ AboutActivityBindingModule::class, AboutRepositoryModule::class ] ) abstract fun aboutActivity(): AboutActivity @TestDetailsActivityScope @ContributesAndroidInjector( modules = [ TestDetailsModule::class, TestDetailsRepositoryModule::class ] ) abstract fun testDetailsActivity(): TestDetailsActivity @ChangeActivityScope @ContributesAndroidInjector(modules = [ChangeActivityModule::class]) abstract fun changeActivity(): ChangeActivity @CreateAccountActivityScope @ContributesAndroidInjector(modules = [CreateAccountModule::class]) abstract fun createAccountActivity(): CreateAccountActivity @ManageAccountsActivityScope @ContributesAndroidInjector( modules = [ ManageAccountsModule::class, ManageAccountsRouterModule::class ] ) abstract fun accountListActivity(): ManageAccountsActivity @BuildDetailsActivityScope @ContributesAndroidInjector( modules = [ BuildDetailsModule::class, BuildDetailsFragmentsBindingModule::class ] ) abstract fun buildDetailsActivity(): BuildDetailsActivity @BuildListActivityScope @ContributesAndroidInjector(modules = [BuildListModule::class, BuildListAdapterModule::class]) abstract fun buildListActivity(): BuildListActivity @FilterBuildsActivityScope @ContributesAndroidInjector(modules = [FilterBuildsModule::class]) abstract fun filterBuildsActivity(): FilterBuildsActivity @RunBuildActivityScope @ContributesAndroidInjector(modules = [RunBuildModule::class]) abstract fun runBuildActivity(): RunBuildActivity @HomeActivityScope @ContributesAndroidInjector(modules = [HomeModule::class, HomeActivityBindingModule::class]) abstract fun homeActivity(): HomeActivity @NavigationActivityScope @ContributesAndroidInjector(modules = [NavigationModule::class, NavigationBaseModule::class]) abstract fun navigationActivity(): NavigationActivity @ArtifactActivityScope @ContributesAndroidInjector(modules = [ArtifactsActivityModule::class]) abstract fun artifactListActivity(): ArtifactListActivity @SettingsActivityScope @ContributesAndroidInjector( modules = [ SettingsActivityModule::class, SettingsActivityBindingModule::class ] ) abstract fun settingsActivity(): SettingsActivity }
apache-2.0
ca74ee882ff687f5ec59aac71cd11ac2
46.265734
98
0.82453
4.904935
false
true
false
false
OurFriendIrony/MediaNotifier
app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/musicbrainz/release/get/ReleaseGetCoverArtArchive.kt
1
925
package uk.co.ourfriendirony.medianotifier.clients.musicbrainz.release.get import com.fasterxml.jackson.annotation.* @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @JsonPropertyOrder("darkened", "front", "count", "artwork", "back") class ReleaseGetCoverArtArchive { @get:JsonProperty("darkened") @set:JsonProperty("darkened") @JsonProperty("darkened") var darkened: Boolean? = null @get:JsonProperty("front") @set:JsonProperty("front") @JsonProperty("front") var front: Boolean? = null @get:JsonProperty("count") @set:JsonProperty("count") @JsonProperty("count") var count: Int? = null @get:JsonProperty("artwork") @set:JsonProperty("artwork") @JsonProperty("artwork") var artwork: Boolean? = null @get:JsonProperty("back") @set:JsonProperty("back") @JsonProperty("back") var back: Boolean? = null }
apache-2.0
9c866cc71aecdd51be3158643a91c505
27.060606
74
0.694054
3.987069
false
false
false
false
roylanceMichael/yaorm
yaorm/src/main/java/org/roylance/yaorm/services/sqlite/SQLiteGeneratorService.kt
1
18696
package org.roylance.yaorm.services.sqlite import org.roylance.yaorm.models.ColumnNameTuple import org.roylance.yaorm.YaormModel import org.roylance.yaorm.services.ISQLGeneratorService import org.roylance.yaorm.utilities.ProjectionUtilities import org.roylance.yaorm.utilities.YaormUtils import java.util.* class SQLiteGeneratorService(override val bulkInsertSize: Int = 500, private val emptyAsNull: Boolean = false) : ISQLGeneratorService { override val textTypeName: String get() = SqlTextName override val integerTypeName: String get() = SqlIntegerName override val realTypeName: String get() = SqlRealName override val blobTypeName: String get() = SqlBlobName override val protoTypeToSqlType = HashMap<YaormModel.ProtobufType, String>() override val sqlTypeToProtoType = HashMap<String, YaormModel.ProtobufType>() init { protoTypeToSqlType.put(YaormModel.ProtobufType.STRING, SqlTextName) protoTypeToSqlType.put(YaormModel.ProtobufType.INT32, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.INT64, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.UINT32, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.UINT64, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.SINT32, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.SINT64, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.FIXED32, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.FIXED64, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.SFIXED32, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.SFIXED64, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.BOOL, SqlIntegerName) protoTypeToSqlType.put(YaormModel.ProtobufType.BYTES, SqlBlobName) protoTypeToSqlType.put(YaormModel.ProtobufType.DOUBLE, SqlRealName) protoTypeToSqlType.put(YaormModel.ProtobufType.FLOAT, SqlRealName) sqlTypeToProtoType.put(SqlTextName, YaormModel.ProtobufType.STRING) sqlTypeToProtoType.put(SqlIntegerName, YaormModel.ProtobufType.INT64) sqlTypeToProtoType.put(SqlRealName, YaormModel.ProtobufType.DOUBLE) sqlTypeToProtoType.put(SqlBlobName, YaormModel.ProtobufType.BYTES) } override fun buildJoinSql(joinTable: YaormModel.JoinTable): String { return """select * from ${this.buildKeyword(joinTable.firstTable.name)} a join ${this.buildKeyword(joinTable.secondTable.name)} b on a.${buildKeyword(joinTable.firstColumn.name)} = b.${buildKeyword(joinTable.secondColumn.name)} """ } override val insertSameAsUpdate: Boolean get() = true override fun buildSelectIds(definition: YaormModel.TableDefinition): String { return "select \"id\" from ${definition.name}" } override fun buildCountSql(definition: YaormModel.TableDefinition): String { return "select count(1) as ${this.buildKeyword("longVal")} from ${this.buildKeyword(definition.name)}" } override fun buildCreateColumn( definition: YaormModel.TableDefinition, propertyDefinition: YaormModel.ColumnDefinition): String? { if (protoTypeToSqlType.containsKey(propertyDefinition.type)) { return "alter table ${this.buildKeyword(definition.name)} add column ${this.buildKeyword(propertyDefinition.name)} ${protoTypeToSqlType[propertyDefinition.type]}" } return null } override fun buildDropColumn( definition: YaormModel.TableDefinition, propertyDefinition: YaormModel.ColumnDefinition): String? { val createTableSql = this.buildCreateTable(definition) ?: return null val returnList = ArrayList<String>() returnList.add("drop table if exists temp_${definition.name}") returnList.add("alter table ${this.buildKeyword(definition.name)} rename to temp_${definition.name}") returnList.add(createTableSql.replace(YaormUtils.SemiColon, YaormUtils.EmptyString)) val nameTypes = YaormUtils.getNameTypes( definition, YaormModel.ProtobufType.STRING, this.protoTypeToSqlType) val columnsWithId = nameTypes .map { this.buildKeyword(it.sqlColumnName) } .joinToString(YaormUtils.Comma) val selectIntoStatement = "replace into ${this.buildKeyword(definition.name)} ($columnsWithId) select $columnsWithId from temp_${definition.name}" returnList.add(selectIntoStatement) return returnList.joinToString(YaormUtils.SemiColon) + YaormUtils.SemiColon } override fun buildDropIndex( definition: YaormModel.TableDefinition, columns: Map<String, YaormModel.ColumnDefinition>): String? { val indexName = YaormUtils.buildIndexName(definition.name, columns.values.map { it.name }) return "drop index if exists ${this.buildKeyword(indexName)} on ${this.buildKeyword(definition.name)}" } override fun buildCreateIndex( definition: YaormModel.TableDefinition, properties: Map<String, YaormModel.ColumnDefinition>, includes: Map<String, YaormModel.ColumnDefinition>): String? { val indexName = YaormUtils.buildIndexName(definition.name, properties.values.map { it.name }) val joinedColumnNames = properties.values.map { this.buildKeyword(it.name) }.joinToString(YaormUtils.Comma) val sqlStatement = "create index if not exists ${this.buildKeyword(indexName)} on ${this.buildKeyword(definition.name)} ($joinedColumnNames)" if (includes.isEmpty()) { return sqlStatement } val joinedIncludeColumnNames = includes.values.map { this.buildKeyword(it.name) }.joinToString(YaormUtils.Comma) return "$sqlStatement include ($joinedIncludeColumnNames)" } override fun buildDeleteWithCriteria( definition: YaormModel.TableDefinition, whereClauseItem: YaormModel.WhereClause): String { val whereClause = YaormUtils.buildWhereClause(whereClauseItem, this) return "delete from ${this.buildKeyword(definition.name)} where $whereClause" } override fun buildUpdateWithCriteria( definition: YaormModel.TableDefinition, record: YaormModel.Record, whereClauseItem: YaormModel.WhereClause): String? { val whereClauseStr = YaormUtils.buildWhereClause(whereClauseItem, this) val newValuesWorkspace = StringBuilder() record.columnsList.forEach { if (newValuesWorkspace.isNotEmpty()) { newValuesWorkspace.append(YaormUtils.Comma) } newValuesWorkspace.append(this.buildKeyword(it.definition.name)) newValuesWorkspace.append(YaormUtils.Equals) newValuesWorkspace.append(YaormUtils.getFormattedString(it, emptyAsNull)) } return "update ${this.buildKeyword(definition.name)} set $newValuesWorkspace where $whereClauseStr${YaormUtils.SemiColon}" } override fun buildDropTable(definition: YaormModel.TableDefinition): String { return "drop table if exists ${this.buildKeyword(definition.name)}" } override fun buildDeleteAll(definition: YaormModel.TableDefinition) : String { return "delete from ${this.buildKeyword(definition.name)}" } override fun buildBulkInsert( definition: YaormModel.TableDefinition, records: YaormModel.Records) : String { val sortedColumns = definition.columnDefinitionsList.sortedBy { it.order } val columnNames = sortedColumns.map { this.buildKeyword(it.name) } val commaSeparatedColumnNames = columnNames.joinToString(YaormUtils.Comma) val initialStatement = "replace into ${this.buildKeyword(definition.name)} ($commaSeparatedColumnNames) " val selectStatements = ArrayList<String>() records .recordsList .forEach { instance -> val valueColumnPairs = ArrayList<String>() sortedColumns .forEach { columnDefinition -> val foundColumn = instance.columnsList.firstOrNull { column -> column.definition.name == columnDefinition.name } if (foundColumn != null) { val formattedValue = YaormUtils.getFormattedString(foundColumn, emptyAsNull) if (valueColumnPairs.isEmpty()) { valueColumnPairs.add("select $formattedValue as ${this.buildKeyword(foundColumn.definition.name)}") } else { valueColumnPairs.add("$formattedValue as ${this.buildKeyword(foundColumn.definition.name)}") } } else { val actualColumn = YaormUtils.buildColumn(YaormUtils.EmptyString, columnDefinition) val formattedValue = YaormUtils.getFormattedString(actualColumn, emptyAsNull) if (valueColumnPairs.isEmpty()) { valueColumnPairs.add("select $formattedValue as ${this.buildKeyword(columnDefinition.name)}") } else { valueColumnPairs.add("$formattedValue as ${this.buildKeyword(columnDefinition.name)}") } } } selectStatements.add(valueColumnPairs.joinToString(YaormUtils.Comma)) } val unionSeparatedStatements = selectStatements.joinToString(YaormUtils.SpacedUnion) return "$initialStatement $unionSeparatedStatements${YaormUtils.SemiColon}" } override fun buildSelectAll(definition: YaormModel.TableDefinition, limit: Int, offset: Int): String { return java.lang.String.format( SelectAllTemplate, this.buildKeyword(definition.name), limit, offset) } override fun buildWhereClause( definition: YaormModel.TableDefinition, whereClauseItem: YaormModel.WhereClause): String? { val whereSql = java.lang.String.format( WhereClauseTemplate, this.buildKeyword(definition.name), YaormUtils.buildWhereClause(whereClauseItem, this)) return whereSql } override fun buildDeleteTable(definition: YaormModel.TableDefinition, primaryKey: YaormModel.Column): String? { val deleteSql = java.lang.String.format( DeleteTableTemplate, this.buildKeyword(definition.name), YaormUtils.getFormattedString(primaryKey, emptyAsNull)) return deleteSql } override fun buildUpdateTable( definition: YaormModel.TableDefinition, record: YaormModel.Record): String? { try { val nameTypeMap = HashMap<String, ColumnNameTuple<String>>() YaormUtils.getNameTypes( definition, YaormModel.ProtobufType.STRING, this.protoTypeToSqlType) .forEach { nameTypeMap.put(it.sqlColumnName, it) } if (nameTypeMap.size == 0) { return null } var stringId: String? = null val updateKvp = ArrayList<String>() record .columnsList .sortedBy { it.definition.order } .forEach { val formattedValue = YaormUtils.getFormattedString(it, emptyAsNull) if (it.definition.name == YaormUtils.IdName) { stringId = formattedValue } else { updateKvp.add(this.buildKeyword(it.definition.name) + YaormUtils.Equals + formattedValue) } } if (stringId == null) { return null } val updateSql = java.lang.String.format( UpdateTableSingleTemplate, this.buildKeyword(definition.name), updateKvp.joinToString(YaormUtils.Comma + YaormUtils.Space), stringId!!) return updateSql } catch (e: Exception) { e.printStackTrace() return null } } override fun buildInsertIntoTable( definition: YaormModel.TableDefinition, record: YaormModel.Record): String? { try { val columnNames = ArrayList<String>() val values = ArrayList<String>() record .columnsList .sortedBy { it.definition.order } .forEach { columnNames.add(this.buildKeyword(it.definition.name)) values.add(YaormUtils.getFormattedString(it, emptyAsNull)) } val insertSql = java.lang.String.format( InsertIntoTableSingleTemplate, this.buildKeyword(definition.name), columnNames.joinToString(YaormUtils.Comma), values.joinToString(YaormUtils.Comma)) return insertSql } catch (e: Exception) { e.printStackTrace() return null } } override fun buildCreateTable(definition: YaormModel.TableDefinition): String? { val nameTypes = YaormUtils.getNameTypes( definition, YaormModel.ProtobufType.STRING, this.protoTypeToSqlType) if (nameTypes.isEmpty()) { return null } val workspace = StringBuilder() for (nameType in nameTypes) { if (YaormUtils.IdName == nameType.sqlColumnName) { workspace .append(this.buildKeyword(nameType.sqlColumnName)) .append(YaormUtils.Space) .append(nameType.dataType) .append(YaormUtils.Space) .append(PrimaryKey) } } for (nameType in nameTypes) { if (YaormUtils.IdName != nameType.sqlColumnName) { workspace .append(YaormUtils.Comma) .append(YaormUtils.Space) .append(this.buildKeyword(nameType.sqlColumnName)) .append(YaormUtils.Space) .append(nameType.dataType) } } val createTableSql = java.lang.String.format( CreateInitialTableTemplate, this.buildKeyword(definition.name), workspace.toString()) return createTableSql } override fun buildKeyword(keyword: String): String { return "${YaormUtils.DoubleQuote}$keyword${YaormUtils.DoubleQuote}" } override fun getSchemaNames(): String { return "" } override fun getTableNames(schemaName: String): String { return "select * from sqlite_master where type='table';" } override fun buildTableDefinitionSQL(schemaName: String, tableName: String): String { return "select sql from sqlite_master where type='table' and name='$tableName';" } override fun buildTableDefinition(tableName: String, records: YaormModel.Records): YaormModel.TableDefinition { val firstRecord = records.recordsList.firstOrNull { it.columnsCount > 0 } ?: return YaormModel.TableDefinition.getDefaultInstance() val actualRecord = firstRecord.columnsList.firstOrNull { it.hasDefinition() && it.definition.name != YaormUtils.IdName } ?: return YaormModel.TableDefinition.getDefaultInstance() val foundMatch = SchemaTableRegex.matchEntire(actualRecord.stringHolder) if (foundMatch == null || foundMatch.groupValues.size != 3) { return YaormModel.TableDefinition.getDefaultInstance() } val returnTable = YaormModel.TableDefinition.newBuilder() .setName(tableName) var position = 0 foundMatch.groupValues[2].split(Comma) .forEach { columnInfo -> val columnSplitInfo = columnInfo.trim().replace(DoubleQuote, Empty).split(Space) if (columnInfo.length < 2) { return@forEach } val columnDefinition = YaormModel.ColumnDefinition.newBuilder() columnDefinition.name = columnSplitInfo[0].replace(DoubleQuote, Empty) columnDefinition.order = position val type = columnSplitInfo[1].toLowerCase() if (sqlTypeToProtoType.containsKey(type)) { columnDefinition.type = sqlTypeToProtoType[type]!! } else { columnDefinition.type = YaormModel.ProtobufType.STRING } returnTable.addColumnDefinitions(columnDefinition) position += 1 } return returnTable.build() } override fun buildProjectionSQL(projection: YaormModel.Projection): String { return ProjectionUtilities.buildProjectionSQL(projection, this) } companion object { private const val Empty = "" private const val DoubleQuote = "\"" private const val Comma = "," private const val Space = " " private const val CreateInitialTableTemplate = "create table if not exists %s (%s);" private const val InsertIntoTableSingleTemplate = "replace into %s (%s) values (%s);" private const val UpdateTableSingleTemplate = "update %s set %s where id=%s;" private const val DeleteTableTemplate = "delete from %s where \"id\"=%s;" private const val WhereClauseTemplate = "select * from %s where %s;" private const val SelectAllTemplate = "select * from %s limit %s offset %s;" private const val PrimaryKey = "primary key" private const val SqlIntegerName = "integer" private const val SqlTextName = "text" private const val SqlRealName = "real" private const val SqlBlobName = "blob" private const val SchemaTableRegexStr = """CREATE TABLE "(.+)" \((.+)\)""" private val SchemaTableRegex = Regex(SchemaTableRegexStr) } }
mit
69d1bfac5b40a08caa5189365551698d
41.684932
174
0.629279
5.134853
false
false
false
false
Zukkari/nirdizati-training-ui
src/main/kotlin/cs/ut/util/Upload.kt
1
1929
package cs.ut.util import cs.ut.configuration.ConfigurationReader import org.apache.logging.log4j.LogManager import java.io.File import java.io.FileOutputStream import java.io.FileWriter import java.io.InputStream import java.io.Reader interface UploadItem { val bufferSize: Int get() = ConfigurationReader.findNode("fileUpload").valueWithIdentifier("uploadBufferSize").value() fun write(file: File) } class NirdizatiReader(private val reader: Reader) : UploadItem { override fun write(file: File) { var total = 0 val buffer = CharArray(bufferSize) var read = reader.read(buffer) FileWriter(file).use { while (read != -1) { if (read < bufferSize) { it.write(buffer.sliceArray(0 until read)) } else { it.write(buffer) } total += read read = reader.read(buffer) } } log.debug("Read total of $total bytes for file ${file.name}") } companion object { private val log = LogManager.getLogger(NirdizatiReader::class) } } class NirdizatiInputStream(private val inputStream: InputStream) : UploadItem { override fun write(file: File) { val buffer = ByteArray(bufferSize) var total = 0 var read = inputStream.read(buffer) FileOutputStream(file).use { while (read != -1) { if (read < bufferSize) { it.write(buffer.sliceArray(0 until read)) } else { it.write(buffer) } total += read read = inputStream.read(buffer) } } log.debug("Read total of $total bytes for file ${file.name}") } companion object { private val log = LogManager.getLogger(NirdizatiInputStream::class) } }
lgpl-3.0
2094a28db3e031bef986b1062de7eac3
24.064935
106
0.573354
4.507009
false
false
false
false
matiuri/AdvancedGDX
src/kotlin/mati/advancedgdx/assets/AssetLoader.kt
1
6155
/** * Copyright 2015 Matías Steinberg * * 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 mati.advancedgdx.assets import com.badlogic.gdx.assets.AssetLoaderParameters import com.badlogic.gdx.assets.AssetManager import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver import com.badlogic.gdx.graphics.g2d.BitmapFont import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator import com.badlogic.gdx.utils.Disposable import mati.advancedgdx.AdvancedGame import java.util.* import kotlin.reflect.KClass /** * This class manages the assets of you game, allowing you to replace the long file name with an "alias" (actually a * key). You shouldn't instance it, because it's already instanced in [AdvancedGame], as [AdvancedGame.astManager]. */ class AssetLoader(private val game: AdvancedGame) : Disposable { private val map: MutableMap<String, String> = HashMap() private val manager: AssetManager = AssetManager() var screen: Class<out LoadingScreen> = LoadingScreen::class.java init { manager.setLoader(FreeTypeFontGenerator::class.java, FontGeneratorLoader(InternalFileHandleResolver())) manager.setLoader(BitmapFont::class.java, FontLoader(InternalFileHandleResolver())) } /** * This method adds an asset in the [manager]'s queue. An asset must be queued so that it can be loaded. * * @param key The "alias" of the asset * @param path The path of the asset * @param clazz The asset type's [Class] * * @return this, so you can chain calls */ fun <T> queue(key: String, path: String, clazz: Class<T>, par: AssetLoaderParameters<T>? = null) : AssetLoader { if (map.containsKey(key)) throw IllegalArgumentException("The key $key already exists") map.put(key, path) if (par != null) manager.load(path, clazz, par) else manager.load(path, clazz) return this } /** * This method adds an asset in the [manager]'s queue. An asset must be queued so that it can be loaded. * * @param key The "alias" of the asset * @param path The path of the asset * @param clazz The asset type's [KClass] */ fun <T : Any> queue(key: String, path: String, clazz: KClass<T>, par: AssetLoaderParameters<T>? = null) : AssetLoader { queue(key, path, clazz.java, par) return this } /** * This method adds assets from a min number to a max one * TODO: Complete KDoc */ fun <T> queue(key: String, path1: String, path2: String, clazz: Class<T>, min: Int, max: Int, par: AssetLoaderParameters<T>? = null): AssetLoader { for (i in min..max) queue("$key$i", "$path1$i$path2", clazz, par) return this } fun <T : Any> queue(key: String, path1: String, path2: String, clazz: KClass<T>, min: Int, max: Int, par: AssetLoaderParameters<T>? = null): AssetLoader { return queue(key, path1, path2, clazz.java, min, max, par) } /** * This method loads all the queued assets, via [LoadingScreen]. You can create your own screen that extends * [LoadingScreen], and set the variable [screen] as the [Class] of your own one. * * @param after A lambda which contains the code that will be executed after loading the assets. You should * load the screens using the ScreenManager here. */ fun load(after: () -> Unit = { game.setCurrentScreen(null) }) { game.scrManager.add("Loading", screen.constructors[0].newInstance(game, manager, after) as LoadingScreen) game.scrManager.change("Loading") } /** * This methods returns the asset that you want. * * In Kotlin, you can call it as "astManager[]", with the parameters between the [], because it's an operator * method. * * @param key The "alias" of the asset * @param clazz The asset type's [Class] * * @return An asset */ operator fun <T> get(key: String, clazz: Class<T>): T { if (!map.containsKey(key)) throw IllegalArgumentException("The key $key doesn't exist") return manager.get(map[key], clazz) } /** * This methods returns the asset that you want. * * In Kotlin, you can call it as "astManager[]", with the parameters between the [], because it's an operator * method. * * @param key The "alias" of the asset * @param clazz The asset type's [KClass] * * @return An asset */ operator fun <T : Any> get(key: String, clazz: KClass<T>): T { return get(key, clazz.java) } /** * Return the path of an asset. * * @param key The "alias" of the asset. * * @return The path, as string. */ operator fun get(key: String): String = map[key]!! /** * This method disposes an asset and deletes its "alias". * * @param key The "alias" of the asset * * @return this, so you can chain calls */ fun remove(key: String): AssetLoader { if (!map.containsKey(key)) throw IllegalArgumentException("The key $key doesn't exist") manager.unload(map[key]) return this } /** * This method disposes all the assets and deletes its "aliases" */ fun clear() { manager.clear() map.clear() } /** * This method disposes the [manager], so you mustn't call any method of an instance of this class if you've * already called [dispose]. */ override fun dispose() { manager.dispose() map.clear() } }
apache-2.0
f4ec4a833a84d6b0c0fb4a90faf866c8
34.77907
116
0.641696
4.086321
false
false
false
false
requery/requery
requery-android/src/main/java/io/requery/android/sqlite/SqlitePreparedStatement.kt
1
4682
/* * Copyright 2018 requery.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.requery.android.sqlite import android.database.sqlite.SQLiteCursor import android.database.sqlite.SQLiteStatement import java.sql.ResultSet import java.sql.SQLException import java.sql.Statement /** * [java.sql.PreparedStatement] implementation using Android's local SQLite database. */ internal class SqlitePreparedStatement @Throws(SQLException::class) constructor(private val sqliteConnection: SqliteConnection, sql: String, autoGeneratedKeys: Int) : BasePreparedStatement(sqliteConnection, sql, autoGeneratedKeys) { private val statement: SQLiteStatement = sqliteConnection.database.compileStatement(sql) private var cursor: SQLiteCursor? = null override fun bindNullOrString(index: Int, value: Any?) { if (value == null) { statement.bindNull(index) bindings?.add(null) } else { val string = value.toString() statement.bindString(index, string) bindings?.add(string) } } override fun bindLong(index: Int, value: Long) { statement.bindLong(index, value) bindings?.add(value) } override fun bindDouble(index: Int, value: Double) { statement.bindDouble(index, value) bindings?.add(value) } override fun bindBlob(index: Int, value: ByteArray?) { if (value == null) { statement.bindNull(index) bindings?.add(null) } else { statement.bindBlob(index, value) if (bindings != null) { bindBlobLiteral(index, value) } } } @Throws(SQLException::class) override fun close() { clearParameters() statement.close() cursor?.close() super.close() } override fun execute(sql: String, autoGeneratedKeys: Int): Boolean { throw UnsupportedOperationException() } override fun executeQuery(sql: String): ResultSet { throw UnsupportedOperationException() } override fun executeUpdate(sql: String, autoGeneratedKeys: Int): Int { throw UnsupportedOperationException() } @Throws(SQLException::class) override fun clearParameters() { throwIfClosed() statement.clearBindings() bindings?.clear() } @Throws(SQLException::class) override fun execute(): Boolean { throwIfClosed() try { statement.execute() } catch (e: android.database.SQLException) { BaseConnection.throwSQLException(e) } return false } @Throws(SQLException::class) override fun executeQuery(): ResultSet? { throwIfClosed() try { val args = bindingsToArray() if (cursor != null) { cursor!!.setSelectionArguments(args) if (!cursor!!.requery()) { cursor!!.close() cursor = null // close/set to null try to recreate it } } if (cursor == null) { cursor = sqliteConnection.database.rawQuery(sql, args) as SQLiteCursor } queryResult = CursorResultSet(this, cursor!!, false) return queryResult } catch (e: android.database.SQLException) { BaseConnection.throwSQLException(e) } return null } @Throws(SQLException::class) override fun executeUpdate(): Int { throwIfClosed() if (autoGeneratedKeys == Statement.RETURN_GENERATED_KEYS) { try { val rowId = statement.executeInsert() insertResult = SingleResultSet(this, rowId) updateCount = 1 } catch (e: android.database.SQLException) { BaseConnection.throwSQLException(e) } } else { try { updateCount = statement.executeUpdateDelete() } catch (e: android.database.SQLException) { BaseConnection.throwSQLException(e) } } return updateCount } }
apache-2.0
a02e2ae00e9f2b83c7cddd77843f7553
29.402597
96
0.611918
4.872008
false
false
false
false
jeffcharles/visitor-detector
app/src/main/kotlin/com/beyondtechnicallycorrect/visitordetector/deviceproviders/DevicesOnRouterProviderImpl.kt
1
5756
package com.beyondtechnicallycorrect.visitordetector.deviceproviders import android.net.wifi.WifiManager import android.os.Build import com.beyondtechnicallycorrect.visitordetector.BuildConfig import com.beyondtechnicallycorrect.visitordetector.settings.RouterSettings import com.beyondtechnicallycorrect.visitordetector.settings.RouterSettingsGetter import com.google.common.net.InetAddresses import dagger.Module import dagger.Provides import org.funktionale.either.Either import retrofit2.Call import retrofit2.Response import timber.log.Timber import java.io.IOException import java.util.* import javax.inject.Inject import javax.inject.Singleton class DevicesOnRouterProviderImpl @Inject constructor( private val routerSettingsGetter: RouterSettingsGetter, private val routerApiFactory: RouterApiFactory, private val onHomeWifi: DevicesOnRouterProvider.OnHomeWifi ) : DevicesOnRouterProvider { override fun getDevicesOnRouter(): Either<DeviceFetchingFailure, List<RouterDevice>> { return getDevicesOnRouter(routerSettingsGetter.getRouterSettings()) } override fun getDevicesOnRouter( routerSettings: RouterSettings ): Either<DeviceFetchingFailure, List<RouterDevice>> { if (!onHomeWifi.isOnHomeWifi(routerSettings.homeNetworkSsids)) { Timber.d("Not on home network") return Either.Right(listOf<RouterDevice>()) } val routerApi = routerApiFactory.createRouterApi(routerSettings.routerIpAddress) val auth = processRequest( routerApi.login( loginBody = JsonRpcRequest( jsonrpc = "2.0", id = UUID.randomUUID().toString(), method = "login", params = arrayOf(routerSettings.routerUsername, routerSettings.routerPassword) ) ), "login" ) if (auth.isLeft()) { return Either.Left(auth.left().get()) } val arpTable = processRequest( routerApi.arp( body = JsonRpcRequest( jsonrpc = "2.0", id = UUID.randomUUID().toString(), method = "net.arptable", params = arrayOf<String>() ), auth = auth.right().get() ), "arptable" ) if (arpTable.isLeft()) { return Either.Left(arpTable.left().get()) } val activeConnections = processRequest( routerApi.conntrack( body = JsonRpcRequest( jsonrpc = "2.0", id = UUID.randomUUID().toString(), method = "net.conntrack", params = arrayOf<String>() ), auth = auth.right().get() ), "conntrack" ) if (activeConnections.isLeft()) { return Either.Left(activeConnections.left().get()) } val activeIps = activeConnections.right().get().map { it.src } val machints = processRequest( routerApi.macHints( body = JsonRpcRequest( jsonrpc = "2.0", id = UUID.randomUUID().toString(), method = "net.mac_hints", params = arrayOf<String>() ), auth = auth.right().get() ), "mac_hints" ) if (machints.isLeft()) { return Either.Left(machints.left().get()) } val macToHostName = machints.right().get().associate { Pair(it[0].toLowerCase(), it[1]) } return Either.Right( arpTable.right().get().filter { activeIps.contains(it.ipAddress) }.map { RouterDevice(macAddress = it.hwAddress, hostName = macToHostName.getOrElse(it.hwAddress, { it.ipAddress })) } ) } private fun <T> processRequest(request: Call<JsonRpcResponse<T>>, descriptionForLog: String): Either<DeviceFetchingFailure, T> { val response: Response<JsonRpcResponse<T>> try { response = request.execute() } catch (e: IOException) { Timber.w(e, "IO exception during %s", descriptionForLog) return Either.Left(DeviceFetchingFailure.Error) } if (!response.isSuccessful) { Timber.w("Got status code of %d during %s", descriptionForLog) return Either.Left(DeviceFetchingFailure.Error) } val result = response.body().result if (result == null) { Timber.w("%s didn't return result", descriptionForLog) return Either.Left(DeviceFetchingFailure.Error) } return Either.Right(result) } class OnHomeWifiImpl @Inject constructor( private val wifiManager: WifiManager ) : DevicesOnRouterProvider.OnHomeWifi { override fun isOnHomeWifi(homeSsids: List<String>): Boolean { // see http://stackoverflow.com/questions/2799097/how-can-i-detect-when-an-android-application-is-running-in-the-emulator/13815880#13815880 val isRunningInEmulator = Build.HARDWARE.equals("goldfish") || Build.HARDWARE.equals("ranchu") return isRunningInEmulator || homeSsids .map { "\"$it\"" } .contains(wifiManager.connectionInfo.ssid) } } @Module class DevicesOnRouterProviderImplModule() { @Provides @Singleton fun provideOnHomeWifi( onHomeWifiImpl: OnHomeWifiImpl ): DevicesOnRouterProvider.OnHomeWifi { return onHomeWifiImpl } } }
mit
40c104a7d80093302687b701ed917013
35.897436
151
0.592425
4.691117
false
false
false
false
RyotaMurohoshi/KotLinq
src/main/kotlin/com/muhron/kotlinq/average.kt
1
10184
package com.muhron.kotlinq import com.muhron.kotlinq.inner.Calculator @JvmName("averageOfByte") fun Sequence<Byte>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfShort") fun Sequence<Short>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfInt") fun Sequence<Int>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfLong") fun Sequence<Long>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfFloat") fun Sequence<Float>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfDouble") fun Sequence<Double>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfByte") fun Iterable<Byte>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfShort") fun Iterable<Short>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfInt") fun Iterable<Int>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfLong") fun Iterable<Long>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfFloat") fun Iterable<Float>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfDouble") fun Iterable<Double>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfByte") fun Array<Byte>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfShort") fun Array<Short>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfInt") fun Array<Int>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfLong") fun Array<Long>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfFloat") fun Array<Float>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfDouble") fun Array<Double>.average(): Double { require(any()) { "empty." } return Calculator.average(this) } fun ByteArray.average(): Double { require(any()) { "empty." } return Calculator.average(this) } fun ShortArray.average(): Double { require(any()) { "empty." } return Calculator.average(this) } fun IntArray.average(): Double { require(any()) { "empty." } return Calculator.average(this) } fun LongArray.average(): Double { require(any()) { "empty." } return Calculator.average(this) } fun FloatArray.average(): Double { require(any()) { "empty." } return Calculator.average(this) } fun DoubleArray.average(): Double { require(any()) { "empty." } return Calculator.average(this) } @JvmName("averageOfByte") fun <T> Sequence<T>.average(selector: (T) -> Byte): Double = map(selector).average() @JvmName("averageOfShort") fun <T> Sequence<T>.average(selector: (T) -> Short): Double = map(selector).average() @JvmName("averageOfInt") fun <T> Sequence<T>.average(selector: (T) -> Int): Double = map(selector).average() @JvmName("averageOfLong") fun <T> Sequence<T>.average(selector: (T) -> Long): Double = map(selector).average() @JvmName("averageOfFloat") fun <T> Sequence<T>.average(selector: (T) -> Float): Double = map(selector).average() @JvmName("averageOfDouble") fun <T> Sequence<T>.average(selector: (T) -> Double): Double = map(selector).average() @JvmName("averageOfByte") fun <T> Iterable<T>.average(selector: (T) -> Byte): Double = map(selector).average() @JvmName("averageOfShort") fun <T> Iterable<T>.average(selector: (T) -> Short): Double = map(selector).average() @JvmName("averageOfInt") fun <T> Iterable<T>.average(selector: (T) -> Int): Double = map(selector).average() @JvmName("averageOfLong") fun <T> Iterable<T>.average(selector: (T) -> Long): Double = map(selector).average() @JvmName("averageOfFloat") fun <T> Iterable<T>.average(selector: (T) -> Float): Double = map(selector).average() @JvmName("averageOfDouble") fun <T> Iterable<T>.average(selector: (T) -> Double): Double = map(selector).average() @JvmName("averageOfByte") fun <T> Array<T>.average(selector: (T) -> Byte): Double = map(selector).average() @JvmName("averageOfShort") fun <T> Array<T>.average(selector: (T) -> Short): Double = map(selector).average() @JvmName("averageOfInt") fun <T> Array<T>.average(selector: (T) -> Int): Double = map(selector).average() @JvmName("averageOfLong") fun <T> Array<T>.average(selector: (T) -> Long): Double = map(selector).average() @JvmName("averageOfFloat") fun <T> Array<T>.average(selector: (T) -> Float): Double = map(selector).average() @JvmName("averageOfDouble") fun <T> Array<T>.average(selector: (T) -> Double): Double = map(selector).average() @JvmName("averageOfByte") fun ByteArray.average(selector: (Byte) -> Byte): Double = map(selector).average() @JvmName("averageOfShort") fun ByteArray.average(selector: (Byte) -> Short): Double = map(selector).average() @JvmName("averageOfInt") fun ByteArray.average(selector: (Byte) -> Int): Double = map(selector).average() @JvmName("averageOfLong") fun ByteArray.average(selector: (Byte) -> Long): Double = map(selector).average() @JvmName("averageOfFloat") fun ByteArray.average(selector: (Byte) -> Float): Double = map(selector).average() @JvmName("averageOfDouble") fun ByteArray.average(selector: (Byte) -> Double): Double = map(selector).average() @JvmName("averageOfByte") fun ShortArray.average(selector: (Short) -> Byte): Double = map(selector).average() @JvmName("averageOfShort") fun ShortArray.average(selector: (Short) -> Short): Double = map(selector).average() @JvmName("averageOfInt") fun ShortArray.average(selector: (Short) -> Int): Double = map(selector).average() @JvmName("averageOfLong") fun ShortArray.average(selector: (Short) -> Long): Double = map(selector).average() @JvmName("averageOfFloat") fun ShortArray.average(selector: (Short) -> Float): Double = map(selector).average() @JvmName("averageOfDouble") fun ShortArray.average(selector: (Short) -> Double): Double = map(selector).average() @JvmName("averageOfByte") fun IntArray.average(selector: (Int) -> Byte): Double = map(selector).average() @JvmName("averageOfShort") fun IntArray.average(selector: (Int) -> Short): Double = map(selector).average() @JvmName("averageOfInt") fun IntArray.average(selector: (Int) -> Int): Double = map(selector).average() @JvmName("averageOfLong") fun IntArray.average(selector: (Int) -> Long): Double = map(selector).average() @JvmName("averageOfFloat") fun IntArray.average(selector: (Int) -> Float): Double = map(selector).average() @JvmName("averageOfDouble") fun IntArray.average(selector: (Int) -> Double): Double = map(selector).average() @JvmName("averageOfByte") fun LongArray.average(selector: (Long) -> Byte): Double = map(selector).average() @JvmName("averageOfShort") fun LongArray.average(selector: (Long) -> Short): Double = map(selector).average() @JvmName("averageOfInt") fun LongArray.average(selector: (Long) -> Int): Double = map(selector).average() @JvmName("averageOfLong") fun LongArray.average(selector: (Long) -> Long): Double = map(selector).average() @JvmName("averageOfFloat") fun LongArray.average(selector: (Long) -> Float): Double = map(selector).average() @JvmName("averageOfDouble") fun LongArray.average(selector: (Long) -> Double): Double = map(selector).average() @JvmName("averageOfByte") fun FloatArray.average(selector: (Float) -> Byte): Double = map(selector).average() @JvmName("averageOfShort") fun FloatArray.average(selector: (Float) -> Short): Double = map(selector).average() @JvmName("averageOfInt") fun FloatArray.average(selector: (Float) -> Int): Double = map(selector).average() @JvmName("averageOfLong") fun FloatArray.average(selector: (Float) -> Long): Double = map(selector).average() @JvmName("averageOfFloat") fun FloatArray.average(selector: (Float) -> Float): Double = map(selector).average() @JvmName("averageOfDouble") fun FloatArray.average(selector: (Float) -> Double): Double = map(selector).average() @JvmName("averageOfByte") fun DoubleArray.average(selector: (Double) -> Byte): Double = map(selector).average() @JvmName("averageOfShort") fun DoubleArray.average(selector: (Double) -> Short): Double = map(selector).average() @JvmName("averageOfInt") fun DoubleArray.average(selector: (Double) -> Int): Double = map(selector).average() @JvmName("averageOfLong") fun DoubleArray.average(selector: (Double) -> Long): Double = map(selector).average() @JvmName("averageOfFloat") fun DoubleArray.average(selector: (Double) -> Float): Double = map(selector).average() @JvmName("averageOfDouble") fun DoubleArray.average(selector: (Double) -> Double): Double = map(selector).average() @JvmName("averageOfByte") fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.average(selector: (Map.Entry<TSourceK, TSourceV>) -> Byte): Double = map(selector).average() @JvmName("averageOfShort") fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.average(selector: (Map.Entry<TSourceK, TSourceV>) -> Short): Double = map(selector).average() @JvmName("averageOfInt") fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.average(selector: (Map.Entry<TSourceK, TSourceV>) -> Int): Double = map(selector).average() @JvmName("averageOfLong") fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.average(selector: (Map.Entry<TSourceK, TSourceV>) -> Long): Double = map(selector).average() @JvmName("averageOfFloat") fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.average(selector: (Map.Entry<TSourceK, TSourceV>) -> Float): Double = map(selector).average() @JvmName("averageOfDouble") fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.average(selector: (Map.Entry<TSourceK, TSourceV>) -> Double): Double = map(selector).average()
mit
c13ac4392115c098d713da2dee54e2db
30.725857
143
0.701394
3.469847
false
false
false
false
loloof64/BasicChessEndGamesTrainer
app/src/main/java/com/loloof64/android/basicchessendgamestrainer/ui/theme/Theme.kt
1
1151
package com.loloof64.android.basicchessendgamestrainer.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun BasicChessEndgamesTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
gpl-3.0
9a147c20d14eb7558e222806cd8abb77
23.510638
63
0.708949
4.659919
false
false
false
false
openMF/android-client
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/collectionsheet/CollectionSheetFragment.kt
1
8156
/* * This project is licensed under the open source MPL V2. * See https://github.com/openMF/android-client/blob/master/LICENSE.md */ package com.mifos.mifosxdroid.online.collectionsheet import android.os.Bundle import android.util.Log import android.view.* import android.widget.ExpandableListView import android.widget.Toast import butterknife.BindView import butterknife.ButterKnife import com.joanzapata.iconify.IconDrawable import com.joanzapata.iconify.fonts.MaterialIcons import com.mifos.api.model.BulkRepaymentTransactions import com.mifos.api.model.CollectionSheetPayload import com.mifos.api.model.Payload import com.mifos.mifosxdroid.R import com.mifos.mifosxdroid.adapters.CollectionListAdapter import com.mifos.mifosxdroid.core.MifosBaseActivity import com.mifos.mifosxdroid.core.MifosBaseFragment import com.mifos.objects.db.CollectionSheet import com.mifos.objects.response.SaveResponse import com.mifos.utils.Constants import retrofit2.adapter.rxjava.HttpException import java.util.* import javax.inject.Inject /** * A simple [Fragment] subclass. * Use the [CollectionSheetFragment.newInstance] factory method to * create an instance of this fragment. */ class CollectionSheetFragment : MifosBaseFragment(), CollectionSheetMvpView { val LOG_TAG = javaClass.simpleName @JvmField @BindView(R.id.exlv_collection_sheet) var expandableListView: ExpandableListView? = null @JvmField @Inject var mCollectionSheetPresenter: CollectionSheetPresenter? = null var collectionListAdapter: CollectionListAdapter? = null private var centerId: Int? = null // Center for which collection sheet is being generated = 0 private var dateOfCollection // Date of Meeting on which collection has to be done. : String? = null private var calendarInstanceId = 0 private lateinit var rootView: View //Called from within the Adapters to show changes when payment amounts are updated fun refreshFragment() { collectionListAdapter!!.notifyDataSetChanged() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (activity as MifosBaseActivity?)!!.activityComponent.inject(this) if (arguments != null) { centerId = requireArguments().getInt(Constants.CENTER_ID) dateOfCollection = requireArguments().getString(Constants.DATE_OF_COLLECTION) calendarInstanceId = requireArguments().getInt(Constants.CALENDAR_INSTANCE_ID) } setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment rootView = inflater.inflate(R.layout.fragment_collection_sheet, container, false) ButterKnife.bind(this, rootView) mCollectionSheetPresenter!!.attachView(this) fetchCollectionSheet() return rootView } override fun onPrepareOptionsMenu(menu: Menu) { menu.clear() val mItemSearch = menu.add(Menu.NONE, MENU_ITEM_SEARCH, Menu.NONE, getString(R.string.search)) // mItemSearch.setIcon(new IconDrawable(getActivity(), MaterialIcons.md_search) // .colorRes(Color.WHITE) // .actionBarSize()); mItemSearch.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER) val mItemRefresh = menu.add(Menu.NONE, MENU_ITEM_REFRESH, Menu.NONE, getString(R.string.refresh)) mItemRefresh.icon = IconDrawable(activity, MaterialIcons.md_refresh) .colorRes(R.color.white) .actionBarSize() mItemRefresh.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM) val mItemSave = menu.add(Menu.NONE, MENU_ITEM_SAVE, Menu.NONE, getString(R.string.save)) mItemSave.icon = IconDrawable(activity, MaterialIcons.md_save) .colorRes(R.color.white) .actionBarSize() mItemSave.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM) super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId when (id) { MENU_ITEM_REFRESH -> refreshFragment() MENU_ITEM_SAVE -> saveCollectionSheet() MENU_ITEM_SEARCH -> { } } return super.onOptionsItemSelected(item) } fun fetchCollectionSheet() { val payload = Payload() payload.calendarId = calendarInstanceId.toLong() payload.transactionDate = dateOfCollection payload.dateFormat = "dd-MM-YYYY" mCollectionSheetPresenter!!.loadCollectionSheet(centerId!!.toLong(), payload) } @Synchronized fun saveCollectionSheet() { val collectionSheetPayload = CollectionSheetPayload() val bulkRepaymentTransactions: MutableList<BulkRepaymentTransactions> = ArrayList() val iterator: MutableIterator<*> = CollectionListAdapter.sRepaymentTransactions.entries.iterator() while (iterator.hasNext()) { val repaymentTransaction = iterator.next() as Map.Entry<*, *> bulkRepaymentTransactions.add(BulkRepaymentTransactions((repaymentTransaction.key as Int?)!!, (repaymentTransaction.value as Double?)!!)) iterator.remove() } collectionSheetPayload.bulkRepaymentTransactions = arrayOfNulls(bulkRepaymentTransactions.size) bulkRepaymentTransactions.toArray(collectionSheetPayload.bulkRepaymentTransactions) collectionSheetPayload.calendarId = calendarInstanceId.toLong() collectionSheetPayload.transactionDate = dateOfCollection collectionSheetPayload.dateFormat = "dd-MM-YYYY" //Saving Collection Sheet centerId?.let { mCollectionSheetPresenter!!.saveCollectionSheet(it, collectionSheetPayload) } } override fun showCollectionSheet(collectionSheet: CollectionSheet) { Log.i(COLLECTION_SHEET_ONLINE, "Received") val mifosGroups = collectionSheet.groups collectionListAdapter = CollectionListAdapter(activity, mifosGroups) expandableListView!!.setAdapter(collectionListAdapter) } override fun showCollectionSheetSuccessfullySaved(saveResponse: SaveResponse?) { if (saveResponse != null) { Toast.makeText(activity, "Collection Sheet Saved Successfully", Toast.LENGTH_SHORT).show() } } override fun showFailedToSaveCollectionSheet(response: HttpException?) { if (response != null) { if (response.code() == 400 || response.code() == 403) { //TODO for now, It is commented //MFErrorParser.parseError(response.response().body()); } Toast.makeText(activity, "Collection Sheet could not be saved.", Toast.LENGTH_SHORT).show() } } override fun showFetchingError(s: String?) { Toast.makeText(activity, s, Toast.LENGTH_SHORT).show() } override fun showProgressbar(b: Boolean) { if (b) { showMifosProgressDialog() } else { hideMifosProgressDialog() } } override fun onDestroyView() { super.onDestroyView() mCollectionSheetPresenter!!.detachView() } companion object { const val COLLECTION_SHEET_ONLINE = "Collection Sheet Online" private const val MENU_ITEM_SEARCH = 2000 private const val MENU_ITEM_REFRESH = 2001 private const val MENU_ITEM_SAVE = 2002 @JvmStatic fun newInstance(centerId: Int, dateOfCollection: String?, calendarInstanceId: Int): CollectionSheetFragment { val fragment = CollectionSheetFragment() val args = Bundle() args.putInt(Constants.CENTER_ID, centerId) args.putString(Constants.DATE_OF_COLLECTION, dateOfCollection) args.putInt(Constants.CALENDAR_INSTANCE_ID, calendarInstanceId) fragment.arguments = args return fragment } } } private fun <E> MutableList<E>.toArray(bulkRepaymentTransactions: Array<E?>) { }
mpl-2.0
72524872e2063e24210e5e77894d350d
39.984925
149
0.691515
4.831754
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/ui/AnimationUtil.kt
1
3221
/* * Copyright (c) 2020 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.ui import android.view.View import android.view.animation.AlphaAnimation import android.view.animation.Animation import android.view.animation.AnimationSet import android.view.animation.ScaleAnimation object AnimationUtil { // please test this on Huawei devices (if possible) and not just on the emulator - // having view.setVisibility(View.VISIBLE); on the expand worked fine on the emulator, but looked bad on my phone /** This is a fast animation - We don't want the user incorrectly selecting the current position * for the next collapse operation */ private const val DURATION_MILLIS = 200 fun collapseView(view: View, animationEnabled: Boolean) { view.animate().cancel() if (!animationEnabled) { view.visibility = View.GONE return } val set = AnimationSet(true) val expandAnimation = ScaleAnimation( 1f, 1f, 1f, 0.5f ) expandAnimation.duration = DURATION_MILLIS.toLong() expandAnimation.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(animation: Animation) {} override fun onAnimationEnd(animation: Animation) { view.visibility = View.GONE } override fun onAnimationRepeat(animation: Animation) {} }) val alphaAnimation = AlphaAnimation(1.0f, 0f) alphaAnimation.duration = DURATION_MILLIS.toLong() alphaAnimation.fillAfter = true set.addAnimation(expandAnimation) set.addAnimation(alphaAnimation) view.startAnimation(set) } fun expandView(view: View, enableAnimation: Boolean) { view.animate().cancel() if (!enableAnimation) { view.visibility = View.VISIBLE view.alpha = 1.0f view.scaleY = 1.0f return } // Sadly this seems necessary - yScale didn't work. val set = AnimationSet(true) val resetEditTextScale = ScaleAnimation( 1f, 1f, 1f, 1f ) resetEditTextScale.duration = DURATION_MILLIS.toLong() val alphaAnimation = AlphaAnimation(0.0f, 1.0f) alphaAnimation.fillAfter = true alphaAnimation.duration = DURATION_MILLIS.toLong() set.addAnimation(resetEditTextScale) set.addAnimation(alphaAnimation) view.startAnimation(set) view.visibility = View.VISIBLE } }
gpl-3.0
fa5356d3ad879e62e78f1ba6d5c673a7
38.280488
117
0.668115
4.549435
false
false
false
false
BrianLusina/MovieReel
app/src/main/kotlin/com/moviereel/ui/main/MainActivity.kt
1
14921
package com.moviereel.ui.main import android.os.Bundle import android.support.v4.content.ContextCompat import com.mikepenz.aboutlibraries.Libs import com.mikepenz.aboutlibraries.LibsBuilder import com.mikepenz.fontawesome_typeface_library.FontAwesome import com.mikepenz.itemanimators.AlphaCrossFadeAnimator import com.mikepenz.materialdrawer.Drawer import com.mikepenz.materialdrawer.DrawerBuilder import com.mikepenz.materialdrawer.model.PrimaryDrawerItem import com.mikepenz.materialdrawer.model.SecondaryDrawerItem import com.mikepenz.materialdrawer.model.SectionDrawerItem import com.mikepenz.materialdrawer.model.interfaces.Nameable import com.moviereel.R import com.moviereel.ui.base.BaseActivity import com.moviereel.ui.entertain.movie.MoviesFragment import com.moviereel.ui.settings.SettingsActivity import kotlinx.android.synthetic.main.activity_main.* import org.jetbrains.anko.startActivity import javax.inject.Inject class MainActivity : BaseActivity(), MainView { lateinit var drawer: Drawer @Inject lateinit var mainPresenter: MainPresenter<MainView> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) activityComponent?.inject(this) mainPresenter.onAttach(this) setUp() setUpNavigationMenu(savedInstanceState) } /** * Abstract method that will be implemented by child activity classes * used to setup the views in the activity */ override fun setUp() { setSupportActionBar(toolbar_id) supportActionBar?.setDisplayUseLogoEnabled(false) supportActionBar?.title = "Movies" //sets the default fragment val fragment = MoviesFragment() val fragmentManager = supportFragmentManager val fragmentTransaction = fragmentManager.beginTransaction() fragmentTransaction.replace(R.id.frame_container, fragment) fragmentTransaction.commit() } /** * Sets up the navigation menu * @param savedInstanceState Bundle with the current state of the activity * * */ private fun setUpNavigationMenu(savedInstanceState: Bundle?) { //this layout have to contain child layouts drawer = DrawerBuilder(this) .withToolbar(toolbar_id) .withActivity(this) .withItemAnimator(AlphaCrossFadeAnimator()) .withSliderBackgroundColorRes(R.color.background_drawer_color) .addDrawerItems( /*movies section*/ PrimaryDrawerItem().withName(R.string.main_drawer_movie_title) .withIcon(FontAwesome.Icon.faw_play) .withIconColor(ContextCompat.getColor(this, R.color.white)) .withSelectedIconColor(ContextCompat.getColor(this, R.color.light_red3)).withSelectedTextColor( ContextCompat.getColor(this, R.color.light_red3)) .withTextColor(ContextCompat.getColor(this, R.color.white)) .withSelectedColor(ContextCompat.getColor(this, R.color.background_drawer_color)) .withIdentifier(1), /*Tv series section*/ SectionDrawerItem().withName(R.string.main_drawer_series_title) .withTextColor(ContextCompat.getColor(this, R.color.light_red3)), /*Latest series*/ SecondaryDrawerItem().withName(R.string.main_drawer_series_latest) .withIcon(FontAwesome.Icon.faw_clock_o) .withIconColor(ContextCompat.getColor(this, R.color.white)) .withSelectedIconColor(ContextCompat.getColor(this, R.color.light_red3)) .withSelectedTextColor(ContextCompat.getColor(this, R.color.light_red3)) .withTextColor(ContextCompat.getColor(this, R.color.white)) .withSelectedColor(ContextCompat .getColor(this, R.color.background_drawer_color)) .withIdentifier(5), /*On the air*/ SecondaryDrawerItem().withName(R.string.main_drawer_series_ontheair) .withIcon(FontAwesome.Icon.faw_television) .withIconColor(ContextCompat.getColor(this, R.color.white)) .withSelectedIconColor(ContextCompat.getColor(this, R.color.light_red3)) .withSelectedTextColor(ContextCompat.getColor(this, R.color.light_red3)) .withTextColor(ContextCompat.getColor(this, R.color.white)) .withSelectedColor(ContextCompat .getColor(this, R.color.background_drawer_color)) .withIdentifier(6), /*Airing today*/ SecondaryDrawerItem().withName(R.string.main_drawer_series_airing_today) .withIcon(FontAwesome.Icon.faw_hourglass_start) .withIconColor(ContextCompat.getColor(this, R.color.white)) .withSelectedIconColor(ContextCompat.getColor(this, R.color.light_red3)) .withSelectedTextColor(ContextCompat.getColor(this, R.color.light_red3)) .withTextColor(ContextCompat.getColor(this, R.color.white)) .withSelectedColor(ContextCompat .getColor(this, R.color.background_drawer_color)) .withIdentifier(7), /*top rated*/ SecondaryDrawerItem().withName(R.string.main_drawer_series_top_rated) .withIcon(FontAwesome.Icon.faw_star) .withIconColor(ContextCompat.getColor(this, R.color.white)) .withSelectedIconColor(ContextCompat.getColor(this, R.color.light_red3)).withSelectedTextColor(ContextCompat.getColor(this, R.color.light_red3)) .withTextColor(ContextCompat.getColor(this, R.color.white)) .withSelectedColor(ContextCompat .getColor(this, R.color.background_drawer_color)) .withIdentifier(8), /*Popular tv shows*/ SecondaryDrawerItem().withName(R.string.main_drawer_series_popular) .withIcon(FontAwesome.Icon.faw_bullhorn) .withIconColor(ContextCompat.getColor(this, R.color.white)) .withSelectedIconColor(ContextCompat.getColor(this, R.color.light_red3)) .withSelectedTextColor(ContextCompat.getColor(this, R.color.light_red3)) .withTextColor(ContextCompat.getColor(this, R.color.white)) .withSelectedColor(ContextCompat .getColor(this, R.color.background_drawer_color)) .withIdentifier(9), /*HELP section*/ SecondaryDrawerItem().withName(R.string.main_drawer_help) .withIcon(FontAwesome.Icon.faw_question) .withIconColor(ContextCompat.getColor(this, R.color.white)) .withSelectedIconColor(ContextCompat.getColor(this, R.color.light_red3)) .withSelectedTextColor(ContextCompat.getColor(this, R.color.light_red3)) .withTextColor(ContextCompat.getColor(this, R.color.white)) .withSelectedColor(ContextCompat .getColor(this, R.color.background_drawer_color)) .withIdentifier(10), /*settings*/ SecondaryDrawerItem().withName(R.string.main_drawer_settings) .withIcon(FontAwesome.Icon.faw_cogs) .withIconColor(ContextCompat.getColor(this, R.color.white)) .withSelectedIconColor(ContextCompat.getColor(this, R.color.light_red3)) .withSelectedTextColor(ContextCompat.getColor(this, R.color.light_red3)) .withTextColor(ContextCompat.getColor(this, R.color.white)) .withSelectedColor(ContextCompat .getColor(this, R.color.background_drawer_color)) .withIdentifier(11), /*About*/ SecondaryDrawerItem().withName(R.string.main_drawer_about) .withIcon(FontAwesome.Icon.faw_exclamation) .withIconColor(ContextCompat.getColor(this, R.color.white)) .withSelectedIconColor(ContextCompat.getColor(this, R.color.light_red3)) .withSelectedTextColor(ContextCompat.getColor(this, R.color.light_red3)) .withTextColor(ContextCompat.getColor(this, R.color.white)) .withSelectedColor(ContextCompat .getColor(this, R.color.background_drawer_color)) .withIdentifier(12) ).withOnDrawerItemClickListener( Drawer.OnDrawerItemClickListener { view, position, drawerItem -> if (drawerItem is Nameable<*>) { val name = (drawerItem as Nameable<*>).name.getText(this) supportActionBar?.title = name when (drawerItem.identifier.toInt()) { //movies 1 -> { mainPresenter.onDrawerOptionMoviesClicked() return@OnDrawerItemClickListener true } /*Latest series*/ 5 -> { mainPresenter.onDrawerOptionLatestSeriesClicked() return@OnDrawerItemClickListener true } /*series On the air*/ 6 -> { mainPresenter.onDrawerOptionOnTheAirSeriesClicked() return@OnDrawerItemClickListener true } /*Series airing today*/ 7 -> { mainPresenter.onDrawerOptionAiringTodaySeriesClicked() return@OnDrawerItemClickListener true } /*top rated series*/ 8 -> { mainPresenter.onDrawerOptionTopRatedSeriesClicked() return@OnDrawerItemClickListener true } /*Popular series*/ 9 -> { mainPresenter.onDrawerOptionPopularSeriesClicked() return@OnDrawerItemClickListener true } /*help*/ 10 -> { mainPresenter.onDrawerOptionHelpClicked() return@OnDrawerItemClickListener true } /*settings*/ 11 -> { mainPresenter.onDrawerOptionSettingsClicked() return@OnDrawerItemClickListener true } /*about*/ 12 -> { mainPresenter.onDrawerOptionAboutClicked() return@OnDrawerItemClickListener true } } } false }) .withSavedInstance(savedInstanceState) .build() } override fun onSaveInstanceState(outState: Bundle) { //add the values which need to be saved from the drawer to the bundle val state = drawer.saveInstanceState(outState) super.onSaveInstanceState(state) } override fun onBackPressed() { //handle the back press :D close the drawer first and if the drawer is closed close the activity if (drawer != null && drawer.isDrawerOpen) { drawer.closeDrawer() } else { super.onBackPressed() } } /** * Shows the movies that are now playing */ override fun showMoviesFragment() { supportFragmentManager.beginTransaction().disallowAddToBackStack() .add(R.id.frame_container, MoviesFragment(), MoviesFragment.TAG).commit() } /** * Show the series that are the latest */ override fun showLatestSeriesFragment() { } /** * Show the tv series that are on the air currently */ override fun showOnTheAirSeriesFragment() { } /** * Display the tv series that are airing today */ override fun showAiringTodaySeriesFragment() { } /** * Display the top rated series */ override fun showTopRatedSeriesFragment() { } /** * Displays the popular series fragment */ override fun showPopularSeriesFragment() { } /** * Display a help section */ override fun showHelpSection() { } /** * Displays the setting screen */ override fun showSettingsScreen() { startActivity<SettingsActivity>() } /** * displays an about fragment */ override fun showAboutFragment() { LibsBuilder() .withActivityStyle(Libs.ActivityStyle.DARK) .withVersionShown(true) .withAboutAppName(getString(R.string.app_name)) .withAboutDescription(getString(R.string.about_app)) .withAboutIconShown(true) .start(this@MainActivity) } }
mit
92f84d4dc0cd5f130b7625475f353dd5
44.215152
176
0.531198
5.966014
false
false
false
false
youkai-app/Youkai
app/src/main/kotlin/app/youkai/data/models/Category.kt
1
1725
package app.youkai.data.models import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.github.jasminb.jsonapi.Links import com.github.jasminb.jsonapi.annotations.Relationship import com.github.jasminb.jsonapi.annotations.RelationshipLinks import com.github.jasminb.jsonapi.annotations.Type @Type("categories") @JsonIgnoreProperties(ignoreUnknown = true) class Category : BaseJsonModel(JsonType("categories")) { companion object FieldNames { val CREATED_AT = "createdAt" val UPDATED_AT = "updatedAt" val TITLE = "title" val DESCRIPTION = "description" val TOTAL_MEDIA_COUNT = "totalMediaCount" val SLUG = "slug" val NSFW = "nsfw" val CHILD_COUNT = "childCount" val IMAGE = "image" } var createdAt: String? = null var updatedAt: String? = null var title: String? = null var description: String? = null var totalMediaCount: Int? = null var slug: String? = null var nsfw: Boolean? = null var childCount: Int? = null /** * I'm guessing this is of type [Image] since I couldn't find any with it actually set. */ var image: Image? = null @Relationship("parent") var parent: Category? = null @RelationshipLinks("parent") var parentLinks: Links? = null @Relationship("anime") var animes: List<Anime>? = null @RelationshipLinks("anime") var animesLinks: Links? = null @Relationship("manga") var mangas: List<Manga>? = null @RelationshipLinks("manga") var mangasLinks: Links? = null /** @Relationship("drama") var drama: Drama? = null @RelationshipLinks("drama") var dramaLinks: Links? = null */ }
gpl-3.0
414ba22b88f1244eba64a9c3ac3fbde0
23.309859
91
0.65913
4.186893
false
false
false
false
shkschneider/android_Skeleton
core/src/main/kotlin/me/shkschneider/skeleton/helperx/Logger.kt
1
2918
package me.shkschneider.skeleton.helperx import android.util.Log import androidx.annotation.IntRange import me.shkschneider.skeleton.extensions.ellipsize import me.shkschneider.skeleton.helper.ApplicationHelper import me.shkschneider.skeleton.helper.ContextHelper object Logger { private const val VERBOSE = Log.VERBOSE private const val DEBUG = Log.DEBUG private const val INFO = Log.INFO private const val WARN = Log.WARN private const val ERROR = Log.ERROR private const val WTF = Log.ASSERT private fun log(@IntRange(from = VERBOSE.toLong(), to = WTF.toLong()) level: Int, msg: String, throwable: Throwable?) { // <https://developer.android.com/reference/android/util/Log.html> // <https://developer.android.com/studio/debug/am-logcat> val tag = ContextHelper.applicationContext().packageName.ellipsize(23, reverse = true) var prefix = "" if (ApplicationHelper.debuggable()) { Throwable().stackTrace.dropWhile { it.className == this.javaClass.name }.also { elements -> elements[0]?.let { element -> val parent = element.className.substringAfterLast(".").substringBefore("$") val child = element.methodName.substringBefore("$").takeIf { it != "invoke" } ?: "$" prefix = "[$parent.$child():${element.lineNumber}] " } } } msg.split("\n").forEach { line -> when (level) { VERBOSE -> Log.v(tag, prefix + line, throwable) DEBUG -> Log.d(tag, prefix + line, throwable) INFO -> Log.i(tag, prefix + line, throwable) WARN -> Log.w(tag, prefix + line, throwable) ERROR -> Log.e(tag, prefix + line, throwable) WTF -> Log.wtf(tag, prefix + line, throwable) } } } // Debug logs are compiled in but stripped at runtime. fun debug(msg: String, throwable: Throwable? = null): Logger { log(DEBUG, msg, throwable) return this } // You should never compile verbose logs into your app, except during development. fun verbose(msg: String, throwable: Throwable? = null): Logger { log(VERBOSE, msg, throwable) return this } fun info(msg: String, throwable: Throwable? = null): Logger { log(INFO, msg, throwable) return this } fun warning(msg: String, throwable: Throwable? = null): Logger { log(WARN, msg, throwable) return this } fun error(msg: String, throwable: Throwable? = null): Logger { log(ERROR, msg, throwable) return this } // Useful to log exceptions (avoids Exception.printStackTrace()) fun wtf(throwable: Throwable): Logger { // "What a Terrible Failure" log(WTF, throwable::class.java.simpleName, throwable) return this } }
apache-2.0
571137072edd1c0cef6f89222055d730
36.896104
123
0.612063
4.421212
false
false
false
false
andrei-heidelbacher/algoventure-core
src/main/kotlin/com/aheidelbacher/algoventure/core/generation/dungeon/DungeonMapGenerator.kt
1
9360
/* * Copyright 2016 Andrei Heidelbacher <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aheidelbacher.algoventure.core.generation.dungeon import com.aheidelbacher.algostorm.engine.Engine.Companion.getResourceStream import com.aheidelbacher.algostorm.engine.serialization.Deserializer.Companion.readValue import com.aheidelbacher.algostorm.state.MapObject import com.aheidelbacher.algostorm.state.Property import com.aheidelbacher.algostorm.state.TileSet import com.aheidelbacher.algostorm.systems.geometry2d.Point import com.aheidelbacher.algostorm.systems.graphics2d.camera.Camera.Companion.CAMERA_X import com.aheidelbacher.algostorm.systems.graphics2d.camera.Camera.Companion.CAMERA_Y import com.aheidelbacher.algoventure.core.damage.HealthBarSystem.Companion.DAMAGEABLE_OBJECT_ID import com.aheidelbacher.algoventure.core.generation.MapGenerator import com.aheidelbacher.algoventure.core.generation.PrototypeObject import com.aheidelbacher.algoventure.core.generation.PrototypeObject.Companion.createObject import com.aheidelbacher.algoventure.core.generation.Random import com.aheidelbacher.algoventure.core.generation.dungeon.DungeonLevel.Companion.ADJACENT_DIRECTIONS import com.aheidelbacher.algoventure.core.generation.dungeon.DungeonLevel.Companion.DOOR import com.aheidelbacher.algoventure.core.generation.dungeon.DungeonLevel.Companion.FLOOR import com.aheidelbacher.algoventure.core.generation.dungeon.DungeonLevel.Companion.WALL import com.aheidelbacher.algoventure.core.serialization.JsonSerializer import com.aheidelbacher.algoventure.core.state.PLAYER_OBJECT_ID_PROPERTY import com.aheidelbacher.algoventure.core.state.floor import com.aheidelbacher.algoventure.core.state.healthBars import com.aheidelbacher.algoventure.core.state.objectGroup class DungeonMapGenerator( width: Int, height: Int, tileWidth: Int, tileHeight: Int, tileSets: List<String>, prototypes: List<String>, private val floorGid: List<Long>, private val wallMaskGid: Map<Int, List<Long>> ) : MapGenerator<DungeonLevel>( width = width, height = height, tileWidth = tileWidth, tileHeight = tileHeight, orientation = MapObject.Orientation.ORTHOGONAL, tileSets = tileSets.map { path -> getResourceStream(path).use { stream -> JsonSerializer.readValue<TileSet>(stream) } }, prototypes = prototypes.associate { path -> val prototype = getResourceStream(path).use { stream -> JsonSerializer.readValue<PrototypeObject>(stream) } prototype.type to prototype }, levelGenerator = DungeonGenerator( levelWidth = width, levelHeight = height, minRoomSize = Math.min(width, height) / 8, maxRoomSize = Math.min(width, height) / 4, roomPlacementAttempts = width * height / 8, corridorStraightness = 0.8F ) ) { companion object { fun newMap(playerPrototype: String): MapObject { val tiles = getResourceStream("/tile_sets.json").use { JsonSerializer.readValue<List<String>>(it) } val prototypes = getResourceStream("/prototypes.json").use { JsonSerializer.readValue<List<String>>(it) } return DungeonMapGenerator( width = 32, height = 32, tileWidth = 24, tileHeight = 24, tileSets = tiles, prototypes = prototypes, floorGid = listOf(79, 79, 79, 79, 80), wallMaskGid = mapOf( 0 to listOf(81L), 1 to listOf(87L), 2 to listOf(82L), 3 to listOf(90L), 4 to listOf(85L), 5 to listOf(86L, 86L, 86L, 86L, 97L), 6 to listOf(88L), 7 to listOf(95L), 8 to listOf(84L), 9 to listOf(91L), 10 to listOf(83L, 83L, 83L, 83L, 98L), 11 to listOf(96L), 12 to listOf(89L), 13 to listOf(94L), 14 to listOf(93L), 15 to listOf(92L) ) ).generate(playerPrototype) } } private val wallPrototype = this.prototypes["wall"] ?: error("Missing wall prototype!") private val doorPrototype = this.prototypes["door"] ?: error("Missing door prototype!") private val wallTorchPrototype = this.prototypes["wallTorch"] ?: error("Missing wall torch prototype!") private val skeletonPrototype = this.prototypes["skeleton"] ?: error("Missing skeleton prototype!") private fun generatePoint(width: Int, height: Int): Point = Point( x = (Math.random() * width).toInt(), y = (Math.random() * height).toInt() ) override fun MapObject.decorate() { val actors = 8 val actorLocations = mutableSetOf<Point>() for (i in 1..actors) { var point: Point do { point = generatePoint(width, height) val isFloor = floor.data[point.y * width + point.x] != 0L } while (!isFloor || point in actorLocations) actorLocations.add(point) } var isPlayer = true for ((px, py) in actorLocations) { val x = px * tileWidth val y = py * tileHeight val obj = if (isPlayer) createObject(playerPrototype, x, y) else createObject(skeletonPrototype, x, y) objectGroup.add(obj) healthBars.add(create( x = obj.x, y = obj.y + obj.height - obj.height / 12, width = obj.width, height = obj.height / 12, properties = mapOf(DAMAGEABLE_OBJECT_ID to Property(obj.id)) )) if (isPlayer) { set(PLAYER_OBJECT_ID_PROPERTY, obj.id) set(CAMERA_X, obj.x + obj.width / 2) set(CAMERA_Y, obj.y + obj.height / 2) } isPlayer = false } } private fun DungeonLevel.getAdjacencyMask(x: Int, y: Int, tile: Int): Int = ADJACENT_DIRECTIONS.foldIndexed(0) { i, mask, direction -> val nx = x + direction.dx val ny = y + direction.dy if (contains(nx, ny) && get(nx, ny) == tile) mask.or(1.shl(i)) else mask } private fun MapObject.inflateTile(level: DungeonLevel, x: Int, y: Int) { val tile = level[x, y] floor.data[y * width + x] = 0 when (tile) { FLOOR -> floor.data[y * width + x] = floorGid[Random.nextInt(0, floorGid.size)] WALL -> { val mask = level.getAdjacencyMask(x, y, WALL) val gid = wallMaskGid[mask]?.let { it[Random.nextInt(0, it.size)] } ?: error("Missing wall gid mask $mask!") val obj = createObject( prototype = wallPrototype, x = x * tileWidth, y = y * tileHeight ) obj.gid = gid objectGroup.add(obj) val canPlaceTorch = (mask and 4) == 0 && y + 1 < height && level[x, y + 1] == FLOOR if (canPlaceTorch && Random.nextInt(0, 100) < 10) { objectGroup.add(createObject( prototype = wallTorchPrototype, x = x * tileWidth, y = y * tileHeight )) } } DOOR -> { objectGroup.add(createObject( prototype = doorPrototype, x = x * tileWidth, y = y * tileHeight )) floor.data[y * width + x] = floorGid[Random.nextInt(0, floorGid.size)] } DungeonLevel.ENTRANCE -> { } DungeonLevel.EXIT -> { } else -> {} } } override fun MapObject.inflateLevel(level: DungeonLevel) { for (y in 0 until level.height) { for (x in 0 until level.width) { inflateTile(level, x, y) } } } }
apache-2.0
558798579a667822dd215b11a807984e
41.162162
103
0.557479
4.599509
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/world/gamerule/GameRuleContainer.kt
1
2428
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.world.gamerule import org.lanternpowered.api.registry.CatalogRegistry import org.lanternpowered.api.registry.getAllOf import org.spongepowered.api.world.gamerule.GameRule import org.spongepowered.api.world.gamerule.GameRuleHolder import java.util.function.Consumer @Suppress("UNCHECKED_CAST") class GameRuleContainer : GameRuleHolder { private val values = hashMapOf<GameRule<*>, ValueHolder<*>>() override fun <V> getGameRule(gameRule: GameRule<V>): V { return (this.values[gameRule]?.value as? V) ?: gameRule.defaultValue } override fun <V> setGameRule(gameRule: GameRule<V>, value: V) { val holder = this.values.computeIfAbsent(gameRule) { ValueHolder(gameRule.defaultValue, arrayListOf()) } as ValueHolder<V> if (holder.value != value) { holder.listeners.forEach { it(value) } } holder.value = value } override fun getGameRules(): Map<GameRule<*>, *> { val gameRules = hashMapOf<GameRule<*>, Any>() for (gameRule in CatalogRegistry.getAllOf<GameRule<*>>()) { gameRules[gameRule] = this.values[gameRule]?.value ?: gameRule.defaultValue } return gameRules } /** * Adds a listener which tracks changes to the specified [GameRule]. * * @param gameRule The game rule * @param listener The listener */ fun <V> addGameRuleListener(gameRule: GameRule<V>, listener: Consumer<V>) = apply { addGameRuleListener(gameRule, listener::accept) } /** * Adds a listener which tracks changes to the specified [GameRule]. * * @param gameRule The game rule * @param listener The listener */ fun <V> addGameRuleListener(gameRule: GameRule<V>, listener: (V) -> Unit) = apply { val holder = this.values.computeIfAbsent(gameRule) { ValueHolder(gameRule.defaultValue, arrayListOf()) } as ValueHolder<V> holder.listeners.add(listener) } private data class ValueHolder<V>( var value: V, var listeners: MutableList<(V) -> Unit> ) }
mit
62d6e4d45147c61876af49f1135afe9a
34.188406
130
0.669687
4
false
false
false
false
KDatabases/Kuery
src/main/kotlin/com/sxtanna/database/struct/obj/Target.kt
1
3830
package com.sxtanna.database.struct.obj import com.sxtanna.database.ext.value import com.sxtanna.database.struct.obj.Target.Position.* import java.sql.PreparedStatement sealed class Target { protected abstract val data : Any? protected abstract val column : String protected open var not : Boolean = false override fun toString() = "$column${if (not) "!" else ""}=?" open fun data() = data fun not() = apply { this.not = true } internal open fun prep(statement : PreparedStatement, pos : Int) = statement.setObject(pos, data()).let { 0 } private class Equal(override var not : Boolean, override val data : Any?, override val column : String) : Target() private class Between(override var not : Boolean, override val data : Any, private val other : Any, override val column : String) : Target() { override fun prep(statement : PreparedStatement, pos : Int) : Int { statement.setObject(pos, data) statement.setObject(pos + 1, other) return 1 } override fun toString() = "$column ${not.value("NOT ")}BETWEEN ? AND ?" } private class Like(private val pos : Position, override var not : Boolean, override val data : Any, override val column : String) : Target() { override fun data() = pos.place.replace("?", data.toString()) override fun toString() = "$column ${not.value("NOT ")}LIKE ?" } abstract class Relational(private val orEqual : Boolean, private val symbol : Char) : Target() { override final var not = false override fun toString() = "$column $symbol${orEqual.value("=")} ?" } private class Lesser(orEqual : Boolean, override val data : Any, override val column : String) : Relational(orEqual, '<') private class Greater(orEqual : Boolean, override val data : Any, override val column : String) : Relational(orEqual, '>') enum class Position(val place : String) { END ("%?"), START ("?%"), CONTAINS ("%?%") } companion object Where { @JvmSynthetic operator fun <R> invoke(block : Where.() -> R) = this.block() @JvmSynthetic operator fun get(vararg target : Target) = target //region Equals and Between @JvmStatic @JvmOverloads fun equals(column : String, data : Any?, not : Boolean = false) : Target = Equal(not, data, column) @JvmSynthetic @JvmName("equalW") infix fun String.equals(data : Any?) = equals(this, data) @JvmStatic @JvmOverloads fun <O : Any> between(column : String, first : O, second : O, not : Boolean = false) : Target = Between(not, first, second, column) @JvmSynthetic infix fun <O : Any> String.between(data : Pair<O, O>) = between(this, data.first, data.second) //endregion //region Likes @JvmStatic @JvmOverloads fun like(column : String, data : Any, pos : Position, not : Boolean = false) : Target = Like(pos, not, data, column) @JvmStatic @JvmOverloads fun ends(column : String, data : Any, not : Boolean = false) = like(column, data, END, not) @JvmSynthetic @JvmName("endW") infix fun String.ends(data : Any) = ends(this, data) @JvmStatic @JvmOverloads fun starts(column : String, data : Any, not : Boolean = false) = like(column, data, START, not) @JvmSynthetic @JvmName("startW") infix fun String.starts(data : Any) = starts(this, data) @JvmStatic @JvmOverloads fun contains(column : String, data : Any, not : Boolean = false) = like(column, data, CONTAINS, not) @JvmSynthetic @JvmName("containW") infix fun String.contains(data : Any) = contains(this, data) //endregion //region Relationals @JvmStatic @JvmOverloads fun lesser(column : String, data : Any, orEqual : Boolean = false) : Relational = Lesser(orEqual, data, column) @JvmStatic @JvmOverloads fun greater(column : String, data : Any, orEqual : Boolean = false) : Relational = Greater(orEqual, data, column) //endregion } }
apache-2.0
2d894caa8b5998bd3cb75d2748074ece
25.239726
143
0.678068
3.552876
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/ui/SettingsFragment.kt
1
8032
package com.pr0gramm.app.ui import android.app.Activity import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.graphics.drawable.DrawableCompat import androidx.preference.Preference import androidx.preference.PreferenceGroup import com.pr0gramm.app.* import com.pr0gramm.app.services.* import com.pr0gramm.app.services.preloading.PreloadManager import com.pr0gramm.app.ui.base.BaseAppCompatActivity import com.pr0gramm.app.ui.base.BasePreferenceFragment import com.pr0gramm.app.ui.base.launchUntilPause import com.pr0gramm.app.ui.base.launchWhenStarted import com.pr0gramm.app.ui.dialogs.UpdateDialogFragment import com.pr0gramm.app.ui.intro.IntroActivity import com.pr0gramm.app.util.AndroidUtility import com.pr0gramm.app.util.di.instance import com.pr0gramm.app.util.doInBackground import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runInterruptible class SettingsFragment : BasePreferenceFragment("SettingsFragment"), SharedPreferences.OnSharedPreferenceChangeListener { private val userService: UserService by instance() private val bookmarkService: BookmarkService by instance() private val preloadManager: PreloadManager by instance() private val recentSearchesServices: RecentSearchesServices by instance() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (!userService.isAuthorized) { // reset those content types - better be sure! Settings.resetContentTypeSettings() } } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.preferences, rootKey) if (!BuildConfig.DEBUG) { hidePreferenceByName("prefcat_debug") } if (!bookmarkService.canEdit) { hidePreferenceByName("pref_pseudo_restore_bookmarks") } tintPreferenceIcons(color = 0xffd0d0d0.toInt()) } private fun hidePreferenceByName(name: String) { removeIf { it.key == name } } private fun removeIf(group: PreferenceGroup = preferenceScreen, predicate: (Preference) -> Boolean) { for (idx in (0 until group.preferenceCount).reversed()) { val pref = group.getPreference(idx) when { predicate(pref) -> { logger.debug { "Removing preference ${pref.key}" } group.removePreference(pref) // remove all preferences that have this pref as their dependency removeIf { it.dependency == pref.key } } pref is PreferenceGroup -> removeIf(pref, predicate) } } } private fun tintPreferenceIcons(color: Int, group: PreferenceGroup = preferenceScreen) { for (idx in (0 until group.preferenceCount).reversed()) { val pref = group.getPreference(idx) if (pref is PreferenceGroup) { tintPreferenceIcons(color, pref) } pref.icon?.let { icon -> DrawableCompat.setTint(icon, color) } } } private fun updatePreloadInfo() { val preference: Preference = preferenceManager.findPreference("pref_pseudo_clean_preloaded") ?: return launchUntilPause { preloadManager.items.collect { items -> val totalSize = runInterruptible(Dispatchers.IO) { items.values().sumOf { item -> item.media.length().toInt() + item.thumbnail.length().toInt() + (item.thumbnailFull?.length()?.toInt() ?: 0) } } preference.summary = getString( R.string.pseudo_clean_preloaded_summary_with_size, totalSize / (1024f * 1024f) ) } } } override fun onResume() { super.onResume() preferenceScreen.sharedPreferences ?.registerOnSharedPreferenceChangeListener(this) updatePreloadInfo() } override fun onPause() { preferenceScreen.sharedPreferences ?.unregisterOnSharedPreferenceChangeListener(this) super.onPause() } override fun onPreferenceTreeClick(preference: Preference): Boolean { when (preference.key) { "pref_pseudo_update" -> { val activity = activity as BaseAppCompatActivity UpdateDialogFragment.checkForUpdatesInteractive(activity) return true } "pref_pseudo_changelog" -> { val activity = activity as AppCompatActivity ChangeLogDialog().show(activity.supportFragmentManager, null) return true } "pref_pseudo_recommend" -> { val text = "Probiere mal die offizielle pr0gramm App aus: https://app.pr0gramm.com/" val intent = Intent(Intent.ACTION_SEND) intent.type = "text/plain" intent.putExtra(Intent.EXTRA_SUBJECT, "pr0gramm app") intent.putExtra(Intent.EXTRA_TEXT, text) startActivity(Intent.createChooser(intent, getString(R.string.share_using))) return true } "pref_pseudo_clean_preloaded" -> { doInBackground { preloadManager.deleteOlderThan(Instant.now()) } return true } "pref_pseudo_clear_tag_suggestions" -> { recentSearchesServices.clearHistory() val msg = context?.getString(R.string.pref_pseudo_clear_tag_suggestions_notification) Toast.makeText(context, msg, Toast.LENGTH_SHORT).show() return true } "pref_pseudo_onboarding" -> { IntroActivity.launch(requireActivity()) return true } "pref_pseudo_restore_bookmarks" -> { launchWhenStarted(busyIndicator = true) { bookmarkService.restore() } return true } "pref_pseudo_download_target" -> { val intent = Storage.openTreeIntent(requireContext()) startActivityForResult(intent, RequestCodes.SELECT_DOWNLOAD_PATH) return true } else -> return super.onPreferenceTreeClick(preference) } } private fun showNoFileManagerAvailable() { showDialog(this) { content(R.string.hint_no_file_manager_available) positive(R.string.okay) } } override fun onActivityResult(requestCode: Int, resultCode: Int, resultIntent: Intent?) { if (requestCode == RequestCodes.SELECT_DOWNLOAD_PATH && resultCode == Activity.RESULT_OK) { if (!Storage.persistTreeUri( requireContext(), resultIntent ?: return ) ) { showInvalidDownloadDirectorySelected() } } else { super.onActivityResult(requestCode, resultCode, resultIntent) } } private fun showInvalidDownloadDirectorySelected() { showDialog(this) { content(R.string.error_invalid_download_directory) positive(R.string.okay) } } override fun onSharedPreferenceChanged(preferences: SharedPreferences, key: String) { // get the correct theme for the app! when (key) { "pref_theme" -> { // get the correct theme for the app! ThemeHelper.updateTheme() // and apply to parent activity activity?.let { AndroidUtility.recreateActivity(it) } } } } }
mit
b5b444be6d6bef83bb81d9d2b0c3830c
33.774892
105
0.603461
5.142125
false
false
false
false
ykrank/S1-Next
app/src/main/java/me/ykrank/s1next/view/page/app/AppPostListFragment.kt
1
13427
package me.ykrank.s1next.view.page.app import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Bundle import android.text.TextUtils import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import androidx.fragment.app.FragmentManager import com.github.ykrank.androidautodispose.AndroidRxDispose import com.github.ykrank.androidlifecycle.event.FragmentEvent import com.github.ykrank.androidtools.ui.internal.CoordinatorLayoutAnchorDelegate import com.github.ykrank.androidtools.util.ClipboardUtil import com.github.ykrank.androidtools.util.StringUtil import com.github.ykrank.androidtools.widget.RxBus import me.ykrank.s1next.App import me.ykrank.s1next.R import me.ykrank.s1next.data.api.Api import me.ykrank.s1next.data.api.app.model.AppThread import me.ykrank.s1next.data.pref.DownloadPreferencesManager import me.ykrank.s1next.data.pref.GeneralPreferencesManager import me.ykrank.s1next.util.IntentUtil import me.ykrank.s1next.view.activity.BaseActivity import me.ykrank.s1next.view.activity.NewRateActivity import me.ykrank.s1next.view.activity.NewReportActivity import me.ykrank.s1next.view.activity.ReplyActivity import me.ykrank.s1next.view.dialog.LoginPromptDialogFragment import me.ykrank.s1next.view.dialog.PostSelectableChangeDialogFragment import me.ykrank.s1next.view.dialog.ThreadFavouritesAddDialogFragment import me.ykrank.s1next.view.dialog.VoteDialogFragment import me.ykrank.s1next.view.event.* import me.ykrank.s1next.view.fragment.BaseViewPagerFragment import me.ykrank.s1next.view.internal.PagerScrollState import me.ykrank.s1next.view.internal.RequestCode import me.ykrank.s1next.view.page.edit.EditPostActivity import javax.inject.Inject /** * A Fragment includes [android.support.v4.view.ViewPager] * to represent each page of post lists. */ class AppPostListFragment : BaseViewPagerFragment(), AppPostListPagerFragment.PagerCallback, View.OnClickListener { @Inject internal lateinit var mRxBus: RxBus @Inject internal lateinit var mGeneralPreferencesManager: GeneralPreferencesManager @Inject internal lateinit var mDownloadPrefManager: DownloadPreferencesManager private lateinit var mThreadId: String private var mThreadTitle: String? = null private val scrollState = PagerScrollState() private val mPostListPagerAdapter: PostListPagerAdapter by lazy { PostListPagerAdapter(childFragmentManager) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) App.appComponent.inject(this) val bundle = arguments!! val type = bundle.getInt(ARG_TYPE) mThreadId = bundle.getString(ARG_THREAD_ID) as String leavePageMsg("AppPostListFragment##ThreadTitle:$mThreadTitle,ThreadId:$mThreadId,Type:$type") if (savedInstanceState == null) { val jumpPage = bundle.getInt(ARG_JUMP_PAGE, 0) if (jumpPage != 0) { currentPage = jumpPage - 1 } } (activity as CoordinatorLayoutAnchorDelegate).setupFloatingActionButton( R.drawable.ic_insert_comment_black_24dp, this) } override fun onResume() { super.onResume() mRxBus.get() .ofType(QuoteEvent::class.java) .to(AndroidRxDispose.withObservable(this, FragmentEvent.PAUSE)) .subscribe { quoteEvent -> startReplyActivity(quoteEvent.quotePostId, quoteEvent.quotePostCount) } mRxBus.get() .ofType(RateEvent::class.java) .to(AndroidRxDispose.withObservable(this, FragmentEvent.PAUSE)) .subscribe { event -> startRateActivity(event.threadId, event.postId) } mRxBus.get() .ofType(ReportEvent::class.java) .to(AndroidRxDispose.withObservable(this, FragmentEvent.PAUSE)) .subscribe { event -> startReportActivity(event.threadId, event.postId, event.pageNum) } mRxBus.get() .ofType(EditPostEvent::class.java) .to(AndroidRxDispose.withObservable(this, FragmentEvent.PAUSE)) .subscribe { val thread = it.thread val post = it.post EditPostActivity.startActivityForResultMessage(this, RequestCode.REQUEST_CODE_EDIT_POST, thread, post) } mRxBus.get() .ofType(VotePostEvent::class.java) .to(AndroidRxDispose.withObservable(this, FragmentEvent.PAUSE)) .subscribe { if (!LoginPromptDialogFragment.showAppLoginPromptDialogIfNeeded(fragmentManager!!, mUser)) { VoteDialogFragment.newInstance(it.threadId, it.vote).show(fragmentManager!!, VoteDialogFragment.TAG) } } mRxBus.get() .ofType(BlackListChangeEvent::class.java) .to(AndroidRxDispose.withObservable(this, FragmentEvent.PAUSE)) .subscribe { activity?.setResult(Activity.RESULT_OK) } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.fragment_post, menu) menu.findItem(R.id.menu_thread_attachment).isVisible = false menu.findItem(R.id.menu_save_progress).isVisible = false menu.findItem(R.id.menu_load_progress).isVisible = false } override fun onPrepareOptionsMenu(menu: Menu) { super.onPrepareOptionsMenu(menu) val mMenuPostSelectable = menu.findItem(R.id.menu_post_selectable) mMenuPostSelectable?.isChecked = mGeneralPreferencesManager.isPostSelectable val mMenuQuickSideBarEnable = menu.findItem(R.id.menu_quick_side_bar_enable) mMenuQuickSideBarEnable?.isChecked = mGeneralPreferencesManager.isQuickSideBarEnable } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_favourites_add -> { if (!LoginPromptDialogFragment.showLoginPromptDialogIfNeeded(fragmentManager!!, mUser)) { ThreadFavouritesAddDialogFragment.newInstance(mThreadId, mThreadTitle).show( activity!!.supportFragmentManager, ThreadFavouritesAddDialogFragment.TAG) } return true } R.id.menu_link -> { ClipboardUtil.copyText(context, "Url of $mThreadTitle", Api.getPostListUrlForBrowser(mThreadId, currentPage)) (activity as CoordinatorLayoutAnchorDelegate).showShortSnackbar( R.string.message_thread_link_copy) return true } R.id.menu_share -> { val value: String val url = Api.getPostListUrlForBrowser(mThreadId, currentPage) if (TextUtils.isEmpty(mThreadTitle)) { value = url } else { value = StringUtil.concatWithTwoSpaces(mThreadTitle, url) } val intent = Intent(Intent.ACTION_SEND) intent.putExtra(Intent.EXTRA_TEXT, value) intent.type = "text/plain" startActivity(Intent.createChooser(intent, getString(R.string.menu_title_share))) return true } R.id.menu_browser -> { IntentUtil.startViewIntentExcludeOurApp(context, Uri.parse( Api.getPostListUrlForBrowser(mThreadId, currentPage + 1))) return true } R.id.menu_post_selectable -> { //Switch text selectable PostSelectableChangeDialogFragment.newInstance(!item.isChecked) .setPositiveListener { dialog, which -> //reload all data item.isChecked = !item.isChecked mGeneralPreferencesManager.isPostSelectable = item.isChecked mRxBus.post(PostSelectableChangeEvent()) } .show(fragmentManager!!, null) return true } R.id.menu_quick_side_bar_enable -> { item.isChecked = !item.isChecked mGeneralPreferencesManager.isQuickSideBarEnable = item.isChecked mRxBus.post(QuickSidebarEnableChangeEvent()) return true } else -> return super.onOptionsItemSelected(item) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == RequestCode.REQUEST_CODE_EDIT_POST) { if (resultCode == Activity.RESULT_OK) { val msg = data?.getStringExtra(BaseActivity.EXTRA_MESSAGE) showShortSnackbar(msg) val fragment = curPostPageFragment fragment?.startSwipeRefresh() } } else { super.onActivityResult(requestCode, resultCode, data) } } override fun getPagerAdapter(fragmentManager: FragmentManager): FragmentStatePagerAdapter<*> { return mPostListPagerAdapter } override fun getTitleWithoutPosition(): CharSequence? { return mThreadTitle } override var threadInfo: AppThread? = null set(value) { if (value != null && field != value) { field = value setThreadTitle(value.subject) } } override fun setTotalPages(page: Int?) { if (page != null) { super.setTotalPages(page) } } private fun setThreadTitle(title: CharSequence?) { if (!title.isNullOrEmpty() && mThreadTitle != title.toString()) { mThreadTitle = title.toString() setTitleWithPosition(currentPage) } } override fun onClick(v: View) { startReplyActivity(null, null) } /** * 获取当前的具体帖子fragment */ internal val curPostPageFragment: AppPostListPagerFragment? get() = mPostListPagerAdapter.currentFragment private fun startReplyActivity(quotePostId: String?, quotePostCount: String?) { val fm = fragmentManager ?: return val activity = activity ?: return if (LoginPromptDialogFragment.showLoginPromptDialogIfNeeded(fm, mUser)) { return } ReplyActivity.startReplyActivityForResultMessage(activity, mThreadId, mThreadTitle, quotePostId, quotePostCount) } private fun startRateActivity(threadId: String, postId: String) { val fm = fragmentManager ?: return val activity = activity ?: return if (LoginPromptDialogFragment.showLoginPromptDialogIfNeeded(fm, mUser)) { return } NewRateActivity.start(activity, threadId, postId) } private fun startReportActivity(threadId: String, postId: String, pageNum: Int) { val fm = fragmentManager ?: return val activity = activity ?: return if (LoginPromptDialogFragment.showLoginPromptDialogIfNeeded(fm, mUser)) { return } NewReportActivity.start(activity, threadId, postId, pageNum) } /** * Returns a Fragment corresponding to one of the pages of posts. */ private inner class PostListPagerAdapter constructor(fm: FragmentManager) : FragmentStatePagerAdapter<AppPostListPagerFragment>(fm) { override fun getItem(i: Int): AppPostListPagerFragment { val bundle = arguments!! val jumpPage = bundle.getInt(ARG_JUMP_PAGE, -1) val quotePostId = bundle.getString(ARG_QUOTE_POST_ID) if (jumpPage == i + 1 && !TextUtils.isEmpty(quotePostId)) { // clear this arg string because we only need to tell AppPostListPagerFragment once arguments?.putString(ARG_QUOTE_POST_ID, null) return AppPostListPagerFragment.newInstance(mThreadId, jumpPage, quotePostId) } else { return AppPostListPagerFragment.newInstance(mThreadId, i + 1, quotePostId) } } } companion object { val TAG: String = AppPostListFragment::class.java.name const val Type_Thread = 0 const val Type_Thread_One_Author = 3 private const val ARG_TYPE = "type" private const val ARG_THREAD_ID = "thread_id" /** * ARG_JUMP_PAGE takes precedence over [.ARG_SHOULD_GO_TO_LAST_PAGE]. */ private const val ARG_JUMP_PAGE = "jump_page" private const val ARG_QUOTE_POST_ID = "quote_post_id" fun newInstance(threadId: String, jumpPage: Int?, quotePostId: String?): AppPostListFragment { val fragment = AppPostListFragment() val bundle = Bundle() bundle.putInt(ARG_TYPE, Type_Thread_One_Author) bundle.putString(ARG_THREAD_ID, threadId) if (jumpPage != null) { bundle.putInt(ARG_JUMP_PAGE, jumpPage) } bundle.putString(ARG_QUOTE_POST_ID, quotePostId) fragment.arguments = bundle return fragment } } }
apache-2.0
ebb7a1d72e42be47da0c406dd5ff1101
38.789318
137
0.642852
4.729806
false
false
false
false
jamieadkins95/Roach
database/src/main/java/com/jamieadkins/gwent/database/entity/DeckEntity.kt
1
447
package com.jamieadkins.gwent.database.entity import androidx.room.Entity import androidx.room.PrimaryKey import com.jamieadkins.gwent.database.GwentDatabase import java.util.* @Entity(tableName = GwentDatabase.DECK_TABLE) data class DeckEntity( val name: String, val factionId: String, val leaderId: String, val deleted: Boolean = false, val created: Date = Date()) { @PrimaryKey(autoGenerate = true) var id: Long = 0 }
apache-2.0
3bbc6bda39908f93d65094a71fcf1516
25.352941
53
0.742729
3.955752
false
false
false
false
PaulWoitaschek/Voice
data/src/main/kotlin/voice/data/repo/internals/migrations/Migration32to34.kt
1
2380
package voice.data.repo.internals.migrations import android.annotation.SuppressLint import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import android.provider.BaseColumns import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import com.squareup.anvil.annotations.ContributesMultibinding import voice.common.AppScope import voice.data.repo.internals.getLong import voice.data.repo.internals.getString import voice.data.repo.internals.mapRows import voice.data.repo.internals.transaction import voice.logging.core.Logger import javax.inject.Inject private const val BOOKMARK_TABLE_NAME = "tableBookmarks" private const val BM_PATH = "bookmarkPath" private const val BM_TITLE = "bookmarkTitle" private const val BM_TIME = "bookmarkTime" private const val PATH = "bookmarkPath" private const val TITLE = "bookmarkTitle" private const val TABLE_NAME = "tableBookmarks" private const val TIME = "bookmarkTime" private const val ID = BaseColumns._ID private const val CREATE_TABLE_BOOKMARKS = """ CREATE TABLE $TABLE_NAME ( $ID INTEGER PRIMARY KEY AUTOINCREMENT, $PATH TEXT NOT NULL, $TITLE TEXT NOT NULL, $TIME INTEGER NOT NULL ) """ @ContributesMultibinding(AppScope::class) class Migration32to34 @Inject constructor() : Migration(32, 34) { @SuppressLint("Recycle") override fun migrate(db: SupportSQLiteDatabase) { // retrieve old bookmarks val cursor = db.query("SELECT * FROM BOOKMARK_TABLE_NAME") val entries = cursor.mapRows { val path = getString(BM_PATH) val title = getString(BM_TITLE) val time = getLong(BM_TIME) Holder(path, title, time) } Logger.i("Restored bookmarks=$entries") // delete table db.execSQL("DROP TABLE $BOOKMARK_TABLE_NAME") // create new bookmark scheme db.execSQL(CREATE_TABLE_BOOKMARKS) Logger.i("Created $CREATE_TABLE_BOOKMARKS") // add old bookmarks to new bookmark scheme db.transaction { entries.forEach { val cv = ContentValues().apply { put(PATH, it.path) put(TITLE, it.title) put(TIME, it.time) } db.insert(TABLE_NAME, SQLiteDatabase.CONFLICT_FAIL, cv) Logger.i("Inserted $cv to $TABLE_NAME") } } } private data class Holder(val path: String, val title: String, val time: Long) }
gpl-3.0
1754d94e514b3b160df43cc57f7f0bf2
30.733333
80
0.723109
4.082333
false
false
false
false
googlesamples/mlkit
android/material-showcase/app/src/main/java/com/google/mlkit/md/CustomModelObjectDetectionActivity.kt
1
16895
package com.google.mlkit.md /* * 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. */ import android.animation.AnimatorInflater import android.animation.AnimatorSet import android.content.Intent import android.graphics.Bitmap import android.graphics.Color import android.hardware.Camera import android.os.Bundle import android.util.Log import android.view.View import android.view.View.OnClickListener import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.chip.Chip import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton import com.google.common.base.Objects import com.google.common.collect.ImmutableList import com.google.mlkit.md.camera.GraphicOverlay import com.google.mlkit.md.camera.WorkflowModel import com.google.mlkit.md.camera.WorkflowModel.WorkflowState import com.google.mlkit.md.camera.CameraSource import com.google.mlkit.md.camera.CameraSourcePreview import com.google.mlkit.md.objectdetection.MultiObjectProcessor import com.google.mlkit.md.objectdetection.ProminentObjectProcessor import com.google.mlkit.md.productsearch.BottomSheetScrimView import com.google.mlkit.md.productsearch.Product import com.google.mlkit.md.productsearch.ProductAdapter import com.google.mlkit.md.settings.PreferenceUtils import com.google.mlkit.md.settings.SettingsActivity import java.io.IOException /** Demonstrates the object detection and custom classification workflow using camera preview. * Modeled after LiveObjectDetectionActivity.java */ class CustomModelObjectDetectionActivity : AppCompatActivity(), OnClickListener { private var cameraSource: CameraSource? = null private var preview: CameraSourcePreview? = null private var graphicOverlay: GraphicOverlay? = null private var settingsButton: View? = null private var flashButton: View? = null private var promptChip: Chip? = null private var promptChipAnimator: AnimatorSet? = null private var searchButton: ExtendedFloatingActionButton? = null private var searchButtonAnimator: AnimatorSet? = null private var workflowModel: WorkflowModel? = null private var currentWorkflowState: WorkflowState? = null private var bottomSheetBehavior: BottomSheetBehavior<View>? = null private var bottomSheetScrimView: BottomSheetScrimView? = null private var productRecyclerView: RecyclerView? = null private var bottomSheetTitleView: TextView? = null private var objectThumbnailForBottomSheet: Bitmap? = null private var slidingSheetUpFromHiddenState: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_live_object) preview = findViewById(R.id.camera_preview) graphicOverlay = findViewById<GraphicOverlay>(R.id.camera_preview_graphic_overlay).apply { setOnClickListener(this@CustomModelObjectDetectionActivity) cameraSource = CameraSource(this) } promptChip = findViewById(R.id.bottom_prompt_chip) promptChipAnimator = (AnimatorInflater.loadAnimator(this, R.animator.bottom_prompt_chip_enter) as AnimatorSet).apply { setTarget(promptChip) } searchButton = findViewById<ExtendedFloatingActionButton>(R.id.product_search_button).apply { setOnClickListener(this@CustomModelObjectDetectionActivity) } searchButtonAnimator = (AnimatorInflater.loadAnimator(this, R.animator.search_button_enter) as AnimatorSet).apply { setTarget(searchButton) } setUpBottomSheet() findViewById<View>(R.id.close_button).setOnClickListener(this) flashButton = findViewById<View>(R.id.flash_button).apply { setOnClickListener(this@CustomModelObjectDetectionActivity) } settingsButton = findViewById<View>(R.id.settings_button).apply { setOnClickListener(this@CustomModelObjectDetectionActivity) } setUpWorkflowModel() } override fun onResume() { super.onResume() workflowModel?.markCameraFrozen() settingsButton?.isEnabled = true bottomSheetBehavior?.state = BottomSheetBehavior.STATE_HIDDEN currentWorkflowState = WorkflowState.NOT_STARTED cameraSource?.setFrameProcessor( if (PreferenceUtils.isMultipleObjectsMode(this)) { MultiObjectProcessor( graphicOverlay!!, workflowModel!!, CUSTOM_MODEL_PATH ) } else { ProminentObjectProcessor( graphicOverlay!!, workflowModel!!, CUSTOM_MODEL_PATH ) } ) workflowModel?.setWorkflowState(WorkflowState.DETECTING) } override fun onPause() { super.onPause() currentWorkflowState = WorkflowState.NOT_STARTED stopCameraPreview() } override fun onDestroy() { super.onDestroy() cameraSource?.release() cameraSource = null } override fun onBackPressed() { if (bottomSheetBehavior?.state != BottomSheetBehavior.STATE_HIDDEN) { bottomSheetBehavior?.setState(BottomSheetBehavior.STATE_HIDDEN) } else { super.onBackPressed() } } override fun onClick(view: View) { when (view.id) { R.id.product_search_button -> { searchButton?.isEnabled = false workflowModel?.onSearchButtonClicked() } R.id.bottom_sheet_scrim_view -> bottomSheetBehavior?.setState(BottomSheetBehavior.STATE_HIDDEN) R.id.close_button -> onBackPressed() R.id.flash_button -> { if (flashButton?.isSelected == true) { flashButton?.isSelected = false cameraSource?.updateFlashMode(Camera.Parameters.FLASH_MODE_OFF) } else { flashButton?.isSelected = true cameraSource?.updateFlashMode(Camera.Parameters.FLASH_MODE_TORCH) } } R.id.settings_button -> { settingsButton?.isEnabled = false startActivity(Intent(this, SettingsActivity::class.java)) } } } private fun startCameraPreview() { val cameraSource = this.cameraSource ?: return val workflowModel = this.workflowModel ?: return if (!workflowModel.isCameraLive) { try { workflowModel.markCameraLive() preview?.start(cameraSource) } catch (e: IOException) { Log.e(TAG, "Failed to start camera preview!", e) cameraSource.release() this.cameraSource = null } } } private fun stopCameraPreview() { if (workflowModel?.isCameraLive == true) { workflowModel!!.markCameraFrozen() flashButton?.isSelected = false preview?.stop() } } private fun setUpBottomSheet() { bottomSheetBehavior = BottomSheetBehavior.from(findViewById(R.id.bottom_sheet)) bottomSheetBehavior?.setBottomSheetCallback( object : BottomSheetBehavior.BottomSheetCallback() { override fun onStateChanged(bottomSheet: View, newState: Int) { Log.d(TAG, "Bottom sheet new state: $newState") bottomSheetScrimView?.visibility = if (newState == BottomSheetBehavior.STATE_HIDDEN) View.GONE else View.VISIBLE graphicOverlay?.clear() when (newState) { BottomSheetBehavior.STATE_HIDDEN -> workflowModel?.setWorkflowState(WorkflowState.DETECTING) BottomSheetBehavior.STATE_COLLAPSED, BottomSheetBehavior.STATE_EXPANDED, BottomSheetBehavior.STATE_HALF_EXPANDED -> slidingSheetUpFromHiddenState = false BottomSheetBehavior.STATE_DRAGGING, BottomSheetBehavior.STATE_SETTLING -> { } } } override fun onSlide(bottomSheet: View, slideOffset: Float) { val searchedObject = workflowModel!!.searchedObject.value if (searchedObject == null || java.lang.Float.isNaN(slideOffset)) { return } val graphicOverlay = graphicOverlay ?: return val bottomSheetBehavior = bottomSheetBehavior ?: return val collapsedStateHeight = bottomSheetBehavior.peekHeight.coerceAtMost(bottomSheet.height) val bottomBitmap = objectThumbnailForBottomSheet ?: return if (slidingSheetUpFromHiddenState) { val thumbnailSrcRect = graphicOverlay.translateRect(searchedObject.boundingBox) bottomSheetScrimView?.updateWithThumbnailTranslateAndScale( bottomBitmap, collapsedStateHeight, slideOffset, thumbnailSrcRect ) } else { bottomSheetScrimView?.updateWithThumbnailTranslate( bottomBitmap, collapsedStateHeight, slideOffset, bottomSheet ) } } }) bottomSheetScrimView = findViewById<BottomSheetScrimView>(R.id.bottom_sheet_scrim_view).apply { setOnClickListener(this@CustomModelObjectDetectionActivity) } bottomSheetTitleView = findViewById(R.id.bottom_sheet_title) productRecyclerView = findViewById<RecyclerView>(R.id.product_recycler_view).apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(this@CustomModelObjectDetectionActivity) adapter = ProductAdapter(ImmutableList.of()) } } private fun setUpWorkflowModel() { workflowModel = ViewModelProviders.of(this).get(WorkflowModel::class.java).apply { // Observes the workflow state changes, if happens, update the overlay view indicators and // camera preview state. workflowState.observe(this@CustomModelObjectDetectionActivity, Observer { workflowState -> if (workflowState == null || Objects.equal(currentWorkflowState, workflowState)) { return@Observer } currentWorkflowState = workflowState Log.d(TAG, "Current workflow state: ${workflowState.name}") if (PreferenceUtils.isAutoSearchEnabled(this@CustomModelObjectDetectionActivity)) { stateChangeInAutoSearchMode(workflowState) } else { stateChangeInManualSearchMode(workflowState) } }) // Observes changes on the object to search, if happens, show detected object labels as // product search results. objectToSearch.observe(this@CustomModelObjectDetectionActivity, Observer { detectObject -> val productList: List<Product> = detectObject.labels.map { label -> Product("" /* imageUrl */, label.text, "" /* subtitle */) } workflowModel?.onSearchCompleted(detectObject, productList) }) // Observes changes on the object that has search completed, if happens, show the bottom sheet // to present search result. searchedObject.observe(this@CustomModelObjectDetectionActivity, Observer { searchedObject -> objectThumbnailForBottomSheet = searchedObject.getObjectThumbnail() bottomSheetTitleView?.text = getString(R.string.buttom_sheet_custom_model_title) productRecyclerView?.adapter = ProductAdapter(searchedObject.productList) slidingSheetUpFromHiddenState = true bottomSheetBehavior?.peekHeight = preview?.height?.div(2) ?: BottomSheetBehavior.PEEK_HEIGHT_AUTO bottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED }) } } private fun stateChangeInAutoSearchMode(workflowState: WorkflowState) { val wasPromptChipGone = promptChip!!.visibility == View.GONE searchButton?.visibility = View.GONE when (workflowState) { WorkflowState.DETECTING, WorkflowState.DETECTED, WorkflowState.CONFIRMING -> { promptChip?.visibility = View.VISIBLE promptChip?.setText( if (workflowState == WorkflowState.CONFIRMING) R.string.prompt_hold_camera_steady else R.string.prompt_point_at_a_bird ) startCameraPreview() } WorkflowState.CONFIRMED -> { promptChip?.visibility = View.VISIBLE promptChip?.setText(R.string.prompt_searching) stopCameraPreview() } WorkflowState.SEARCHING -> { promptChip?.visibility = View.GONE stopCameraPreview() } WorkflowState.SEARCHED -> { stopCameraPreview() } else -> promptChip?.visibility = View.GONE } val shouldPlayPromptChipEnteringAnimation = wasPromptChipGone && promptChip?.visibility == View.VISIBLE if (shouldPlayPromptChipEnteringAnimation && promptChipAnimator?.isRunning == false) { promptChipAnimator?.start() } } private fun stateChangeInManualSearchMode(workflowState: WorkflowState) { val wasPromptChipGone = promptChip?.visibility == View.GONE val wasSearchButtonGone = searchButton?.visibility == View.GONE when (workflowState) { WorkflowState.DETECTING, WorkflowState.DETECTED, WorkflowState.CONFIRMING -> { promptChip?.visibility = View.VISIBLE promptChip?.setText(R.string.prompt_point_at_an_object) searchButton?.visibility = View.GONE startCameraPreview() } WorkflowState.CONFIRMED -> { promptChip?.visibility = View.GONE searchButton?.visibility = View.VISIBLE searchButton?.isEnabled = true searchButton?.setBackgroundColor(Color.WHITE) startCameraPreview() } WorkflowState.SEARCHING -> { promptChip?.visibility = View.GONE searchButton?.visibility = View.VISIBLE searchButton?.isEnabled = false searchButton?.setBackgroundColor(Color.GRAY) stopCameraPreview() } WorkflowState.SEARCHED -> { promptChip?.visibility = View.GONE searchButton?.visibility = View.GONE stopCameraPreview() } else -> { promptChip?.visibility = View.GONE searchButton?.visibility = View.GONE } } val shouldPlayPromptChipEnteringAnimation = wasPromptChipGone && promptChip?.visibility == View.VISIBLE promptChipAnimator?.let { if (shouldPlayPromptChipEnteringAnimation && !it.isRunning) it.start() } val shouldPlaySearchButtonEnteringAnimation = wasSearchButtonGone && searchButton?.visibility == View.VISIBLE searchButtonAnimator?.let { if (shouldPlaySearchButtonEnteringAnimation && !it.isRunning) it.start() } } companion object { private const val TAG = "CustomModelODActivity" private const val CUSTOM_MODEL_PATH = "custom_models/bird_classifier.tflite" } }
apache-2.0
3d061f0b8007825c553c12301c488305
42.76943
117
0.635987
5.474725
false
false
false
false
ken-kentan/student-portal-plus
app/src/main/java/jp/kentan/studentportalplus/view/widget/DividerItemDecoration.kt
1
1912
package jp.kentan.studentportalplus.view.widget import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable import android.view.View import androidx.recyclerview.widget.RecyclerView class DividerItemDecoration(context: Context) : RecyclerView.ItemDecoration() { private val bounds = Rect() private val divider: Drawable init { val attrs = context.obtainStyledAttributes(intArrayOf(android.R.attr.listDivider)) divider = attrs.getDrawable(0) ?: throw IllegalArgumentException("@android:attr/listDivider was not set.") attrs.recycle() } override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) { canvas.save() val left: Int val right: Int if (parent.clipToPadding) { left = parent.paddingLeft right = parent.width - parent.paddingRight canvas.clipRect(left, parent.paddingTop, right, parent.height - parent.paddingBottom) } else { left = 0 right = parent.width } val childCount = parent.childCount for (i in 0..childCount - 2) { val child = parent.getChildAt(i) parent.getDecoratedBoundsWithMargins(child, bounds) val bottom = bounds.bottom + Math.round(child.translationY) val top = bottom - divider.intrinsicHeight divider.setBounds(left, top, right, bottom) divider.draw(canvas) } canvas.restore() } override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { // Last position if (parent.getChildAdapterPosition(view) == state.itemCount - 1) { outRect.set(0, 0, 0, 0) return } outRect.set(0, 0, 0, divider.intrinsicHeight) } }
gpl-3.0
b8918a84ec3a3f3137303287bddad774
30.360656
114
0.648013
4.697789
false
false
false
false
AoEiuV020/PaNovel
app/src/main/java/cc/aoeiuv020/panovel/App.kt
1
4129
package cc.aoeiuv020.panovel import android.annotation.SuppressLint import android.app.ActivityManager import android.content.Context import android.os.Process import androidx.appcompat.app.AppCompatDelegate import androidx.multidex.MultiDexApplication import cc.aoeiuv020.gson.GsonUtils import cc.aoeiuv020.jsonpath.JsonPathUtils import cc.aoeiuv020.panovel.ad.AdHelper import cc.aoeiuv020.panovel.data.DataManager import cc.aoeiuv020.panovel.report.Reporter import cc.aoeiuv020.panovel.settings.AdSettings import cc.aoeiuv020.panovel.util.DnsUtils import cc.aoeiuv020.ssl.TLSSocketFactory import cc.aoeiuv020.ssl.TrustManagerUtils import com.bumptech.glide.Glide import com.google.gson.Gson import org.jetbrains.anko.AnkoLogger import java.net.URL import javax.net.ssl.HttpsURLConnection import kotlin.properties.Delegates /** * * Created by AoEiuV020 on 2017.10.03-17:04:22. */ @Suppress("MemberVisibilityCanPrivate") class App : MultiDexApplication(), AnkoLogger { companion object { @SuppressLint("StaticFieldLeak") lateinit var ctx: Context /** * 当前进程是否主进程,部分操作需要判断只在主进程执行一次, */ var isMainProcess: Boolean by Delegates.notNull() /** * 用于app不同页面传递数据时的序列化, */ val gson: Gson = GsonUtils.gsonBuilder .disableHtmlEscaping() .setPrettyPrinting() .create() } override fun onCreate() { super.onCreate() ctx = applicationContext isMainProcess = isMainProcess() initDnsUtils() initJson() initDataSources() initSsl() initVector() initReporter() initAd() initGlide() initJar() } private fun initDnsUtils() { DnsUtils.init(ctx) } /** * 初始化要放在用到JsonPath之前, */ private fun initJson() { JsonPathUtils.initGson() } /** * 低版本api(<=20)默认不能用矢量图的selector, 要这样设置, * 还有ContextCompat.getDrawable也不行, * it's not a BUG, it's a FEATURE, * https://issuetracker.google.com/issues/37100284 * * 这个设置只对AppCompatActivity有效,其他context没用, */ private fun initVector() { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) } /** * android4连接https可能抛SSLHandshakeException,各种毛病, * 只这样不能完全修复,但是app里主要是用okhttp3, 那边配置好了, */ private fun initSsl() { HttpsURLConnection.setDefaultSSLSocketFactory( TLSSocketFactory( TrustManagerUtils.include( emptySet() ) ) ) } private fun initJar() { // 禁用默认缓存连接,对任意URLConnection实例使用都可以, // 否则jar打开的文件不会被关闭,从而导致文件被覆盖了依然能读到旧文件, // 多少会影响性能, URL("jar:file:/fake.jar!/fake.file").openConnection().defaultUseCaches = false } private fun initGlide() { Glide.get(ctx).registry } private fun initDataSources() { DataManager.init(ctx) } /** * 初始化异常上报封装类, */ private fun initReporter() { Reporter.init(ctx) } private fun initAd() { if (AdSettings.adEnabled) { AdHelper.init(this) } } private fun getCurrentProcessName(): String { val pid = Process.myPid() var processName = "" val manager = applicationContext.getSystemService(ACTIVITY_SERVICE) as ActivityManager for (process in manager.runningAppProcesses) { if (process.pid == pid) { processName = process.processName } } return processName } private fun isMainProcess(): Boolean { return applicationContext.packageName == getCurrentProcessName() } }
gpl-3.0
1253814e86eee639b935aff511dcca85
22.916667
94
0.637363
4.073144
false
false
false
false
cloose/luftbild4p3d
src/main/kotlin/org/luftbild4p3d/p3d/AutogenProducer.kt
1
1045
package org.luftbild4p3d.p3d import org.luftbild4p3d.app.Area import org.luftbild4p3d.app.WorkFolder import org.luftbild4p3d.bing.Tile import org.luftbild4p3d.osm.BoundingBox import org.luftbild4p3d.osm.OverpassOsmApi import java.io.File class AutogenProducer(val workFolder: WorkFolder, val log: (String) -> Unit) { val osmTags = mapOf("building" to "", "roof:shape" to "", "landuse" to "", "natural" to "tree") fun createAutogen(startTile: Tile) { val osmFileName = "${startTile.x}_${startTile.y}.osm" val osmFile = File("${workFolder.name}/$osmFileName") if (!osmFile.exists()) { log("Download missing Osm Data $osmFileName for autogen") val boundingBox = BoundingBox.create(startTile, Area.IMAGES_PER_BGL_FILE_ROW_AND_COLUMN * Area.TILES_PER_IMAGE_ROW_AND_COLUMN) val osmData = OverpassOsmApi().getOsmData(boundingBox, osmTags) osmFile.writeText(osmData) } ScenProcBatchProcess.run(osmFileName, workFolder, { line -> log(line) }) } }
gpl-3.0
3781c1f06ea7d69e323c0f05aa990697
36.357143
138
0.688038
3.235294
false
false
false
false
nemerosa/ontrack
ontrack-extension-ldap/src/test/java/net/nemerosa/ontrack/extension/ldap/LDAPSettingsManagerIT.kt
1
2715
package net.nemerosa.ontrack.extension.ldap import net.nemerosa.ontrack.it.AbstractDSLTestJUnit4Support import net.nemerosa.ontrack.model.security.GlobalSettings import org.junit.Test import org.springframework.beans.factory.annotation.Autowired import kotlin.test.assertEquals class LDAPSettingsManagerIT : AbstractDSLTestJUnit4Support() { @Autowired private lateinit var service: LDAPSettingsManager @Test fun `LDAP settings save and restore`() { // Settings to save val settings = createSettings() val restoredSettings = asUserWith<GlobalSettings, LDAPSettings> { // Saves the settings service.saveSettings(settings) // Gets them back service.settings } // Checks they are the same assertEquals(restoredSettings, settings) } @Test fun `Minimal LDAP settings save and restore`() { // Settings to save val settings = LDAPSettings( true, "ldap://server", "searchBase", "searchFilter", "user", "verysecret" ) val restoredSettings = asUserWith<GlobalSettings, LDAPSettings> { // Saves the settings service.saveSettings(settings) // Gets them back service.settings } // Checks they are the same assertEquals(restoredSettings, settings) } @Test fun `LDAP settings password not saved when blank`() { // Settings to save val settings = createSettings() val restoredSettings = asUserWith<GlobalSettings, LDAPSettings> { // Saves the settings once service.saveSettings(settings) // Saves them again, without the password service.saveSettings(createSettings("")) // Gets the settings back... service.settings } // Checks they are the same assertEquals(restoredSettings, settings) } companion object { protected fun createSettings(): LDAPSettings = createSettings("verysecret") protected fun createSettings(password: String) = LDAPSettings( true, "ldap://server", "searchBase", "searchFilter", "user", password, "fullName", "email", "", "", "cn", "ou=groups", "(uniqueMember={0})" ) } }
mit
78061d8704fc972f1b243d2e69755700
29.863636
83
0.539595
5.691824
false
true
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mixin/inspection/reference/InvalidMemberReferenceInspection.kt
1
2874
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection.reference import com.demonwav.mcdev.platform.mixin.inspection.MixinInspection import com.demonwav.mcdev.platform.mixin.reference.MethodReference import com.demonwav.mcdev.platform.mixin.reference.MixinReference import com.demonwav.mcdev.platform.mixin.reference.isMiscDynamicSelector import com.demonwav.mcdev.platform.mixin.reference.parseMixinSelector import com.demonwav.mcdev.platform.mixin.reference.target.TargetReference import com.demonwav.mcdev.util.annotationFromNameValuePair import com.demonwav.mcdev.util.constantStringValue import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.JavaElementVisitor import com.intellij.psi.PsiArrayInitializerMemberValue import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiLiteral import com.intellij.psi.PsiNameValuePair class InvalidMemberReferenceInspection : MixinInspection() { override fun getStaticDescription() = """ |Reports invalid usages of member references in Mixin annotations. Two different formats are supported by Mixin: | - Lcom/example/ExampleClass;execute(II)V | - com.example.ExampleClass.execute(II)V """.trimMargin() override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder) private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() { override fun visitNameValuePair(pair: PsiNameValuePair) { val name = pair.name ?: return val resolver: MixinReference = when (name) { "method" -> MethodReference "target" -> TargetReference else -> return } // Check if valid annotation val qualifiedName = pair.annotationFromNameValuePair?.qualifiedName ?: return if (!resolver.isValidAnnotation(qualifiedName)) { return } val value = pair.value ?: return // Attempt to parse the reference when (value) { is PsiLiteral -> checkMemberReference(value, value.constantStringValue) is PsiArrayInitializerMemberValue -> value.initializers.forEach { checkMemberReference(it, it.constantStringValue) } } } private fun checkMemberReference(element: PsiElement, value: String?) { val validSelector = value != null && (parseMixinSelector(value, element) != null || isMiscDynamicSelector(element.project, value)) if (!validSelector) { holder.registerProblem(element, "Invalid member reference") } } } }
mit
378829a296f0e420a5b34958c46e9a93
36.815789
120
0.691719
5.113879
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/RxCaptcha.kt
1
8329
package com.tamsiree.rxui.view import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.widget.ImageView import java.util.* /** * 随机生成验证码,使用方法: * * * 拿到验证码图片ImageView * mIvCode.setImageBitmap(RxCaptcha.getInstance().createBitmap()); * int code=RxCaptcha.getInstance().getCode(); * * * 只需生成验证码值 String * * * * * RxCaptcha * 2015年2月10日 上午11:32:34 * * @author tamsiree * @version 1.0.0 */ class RxCaptcha { private var type = TYPE.CHARS enum class TYPE { //数字 NUMBER, //字母 LETTER, //数字 加 字母 CHARS } private constructor() private constructor(types: TYPE) { type = types } //默认背景颜色值 private var defaultColor = 0xdf // settings decided by the layout xml // canvas width and height private var width = DEFAULT_WIDTH private var height = DEFAULT_HEIGHT // random word space and pading_top private val basePaddingLeft = BASE_PADDING_LEFT private val rangePaddingLeft = RANGE_PADDING_LEFT private val basePaddingTop = BASE_PADDING_TOP private val rangePaddingTop = RANGE_PADDING_TOP // number of chars, lines; font size private var codeLength = DEFAULT_CODE_LENGTH private var lineNumber = DEFAULT_LINE_NUMBER private var fontSize = DEFAULT_FONT_SIZE // variables // 保存生成的验证码 private var code: String? = null private var paddingLeft = 0 private var paddingTop = 0 private val random = Random() /** * @param length 验证码的长度 * @return */ fun codeLength(length: Int): RxCaptcha? { codeLength = length return rxCaptcha } /** * @param size 字体大小 * @return */ fun fontSize(size: Int): RxCaptcha? { fontSize = size return rxCaptcha } /** * @param number 干扰线 数量 * @return */ fun lineNumber(number: Int): RxCaptcha? { lineNumber = number return rxCaptcha } /** * @return 背景颜色值 */ fun backColor(colorInt: Int): RxCaptcha? { defaultColor = colorInt return rxCaptcha } fun type(type: TYPE): RxCaptcha? { this.type = type return rxCaptcha } fun size(width: Int, height: Int): RxCaptcha? { this.width = width this.height = height return rxCaptcha } private fun makeBitmap(): Bitmap { paddingLeft = 0 val bp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) val c = Canvas(bp) code = makeCode() c.drawColor(Color.rgb(defaultColor, defaultColor, defaultColor)) val paint = Paint() paint.textSize = fontSize.toFloat() for (i in 0 until code!!.length) { randomTextStyle(paint) randomPadding() c.drawText(code!![i].toString() + "", paddingLeft.toFloat(), paddingTop.toFloat(), paint) } for (i in 0 until lineNumber) { drawLine(c, paint) } // 保存 c.save() //Canvas.ALL_SAVE_FLAG c.restore() // return bp } fun getCode(): String { return code!!.toLowerCase() } fun into(imageView: ImageView?): Bitmap? { val bitmap = createBitmap() imageView?.setImageBitmap(bitmap) return bitmap } fun createCode(): String { return makeCode() } private var mBitmapCode: Bitmap? = null fun createBitmap(): Bitmap? { mBitmapCode = makeBitmap() return mBitmapCode } private fun makeCode(): String { val buffer = StringBuilder() when (type) { TYPE.NUMBER -> { var i = 0 while (i < codeLength) { buffer.append(CHARS_NUMBER[random.nextInt(CHARS_NUMBER.size)]) i++ } } TYPE.LETTER -> { var i = 0 while (i < codeLength) { buffer.append(CHARS_LETTER[random.nextInt(CHARS_LETTER.size)]) i++ } } TYPE.CHARS -> { var i = 0 while (i < codeLength) { buffer.append(CHARS_ALL[random.nextInt(CHARS_ALL.size)]) i++ } } else -> { var i = 0 while (i < codeLength) { buffer.append(CHARS_ALL[random.nextInt(CHARS_ALL.size)]) i++ } } } return buffer.toString() } private fun drawLine(canvas: Canvas, paint: Paint) { val color = randomColor() val startX = random.nextInt(width) val startY = random.nextInt(height) val stopX = random.nextInt(width) val stopY = random.nextInt(height) paint.strokeWidth = 1f paint.color = color canvas.drawLine(startX.toFloat(), startY.toFloat(), stopX.toFloat(), stopY.toFloat(), paint) } private fun randomColor(rate: Int = 1): Int { val red = random.nextInt(256) / rate val green = random.nextInt(256) / rate val blue = random.nextInt(256) / rate return Color.rgb(red, green, blue) } private fun randomTextStyle(paint: Paint) { val color = randomColor() paint.color = color // true为粗体,false为非粗体 paint.isFakeBoldText = random.nextBoolean() var skewX = random.nextInt(11) / 10.toFloat() skewX = if (random.nextBoolean()) skewX else -skewX // paint.setTextSkewX(skewX); // float类型参数,负数表示右斜,整数左斜 // paint.setUnderlineText(true); //true为下划线,false为非下划线 // paint.setStrikeThruText(true); //true为删除线,false为非删除线 } private fun randomPadding() { paddingLeft += basePaddingLeft + random.nextInt(rangePaddingLeft) paddingTop = basePaddingTop + random.nextInt(rangePaddingTop) } companion object { fun build(): RxCaptcha? { if (rxCaptcha == null) { rxCaptcha = RxCaptcha() } return rxCaptcha } private val CHARS_NUMBER = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') private val CHARS_LETTER = charArrayOf('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z') private val CHARS_ALL = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z') private var rxCaptcha: RxCaptcha? = null fun getInstance(types: TYPE): RxCaptcha? { if (rxCaptcha == null) { rxCaptcha = RxCaptcha(types) } return rxCaptcha } //default settings //验证码的长度 这里是4位 private const val DEFAULT_CODE_LENGTH = 4 //字体大小 private const val DEFAULT_FONT_SIZE = 60 //多少条干扰线 private const val DEFAULT_LINE_NUMBER = 0 //左边距 private const val BASE_PADDING_LEFT = 20 //左边距范围值 private const val RANGE_PADDING_LEFT = 20 //上边距 private const val BASE_PADDING_TOP = 42 //上边距范围值 private const val RANGE_PADDING_TOP = 15 //默认宽度.图片的总宽 private const val DEFAULT_WIDTH = 200 //默认高度.图片的总高 private const val DEFAULT_HEIGHT = 70 } }
apache-2.0
22ed1f71aad6e512e08f0edf1eb477ff
26.874126
101
0.523021
3.795714
false
false
false
false
vondear/RxTools
RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityMain.kt
1
4597
package com.tamsiree.rxdemo.activity import android.Manifest import android.os.Bundle import androidx.viewpager.widget.ViewPager import com.tamsiree.rxdemo.R import com.tamsiree.rxdemo.fragment.FragmentDemoType import com.tamsiree.rxkit.RxDeviceTool import com.tamsiree.rxkit.RxPermissionsTool import com.tamsiree.rxkit.view.RxToast import com.tamsiree.rxui.activity.ActivityBase import com.tamsiree.rxui.adapter.AdapterFVP import com.tamsiree.rxui.fragment.FragmentPlaceholder import com.tamsiree.rxui.model.ModelFVP import com.tamsiree.rxui.model.ModelTab import com.tamsiree.rxui.view.tablayout.listener.OnTabSelectListener import com.tamsiree.rxui.view.tablayout.listener.TabLayoutModel import kotlinx.android.synthetic.main.activity_main.* import java.util.* /** * @author tamsiree */ class ActivityMain : ActivityBase() { private var mBackPressed: Long = 0 private val mTabEntities = ArrayList<TabLayoutModel>() private val mIconUnselectIds = intArrayOf( R.drawable.ic_contact_gray, R.drawable.ic_home_unselect, R.drawable.ic_colleague_unselect ) private val mIconSelectIds = intArrayOf(R.drawable.ic_contact_blue, R.drawable.ic_home, R.drawable.ic_colleague_select) private val modelFVPList: MutableList<ModelFVP> = ArrayList() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) RxDeviceTool.setPortrait(this) RxPermissionsTool .with(mContext) .addPermission(Manifest.permission.ACCESS_FINE_LOCATION) .addPermission(Manifest.permission.ACCESS_COARSE_LOCATION) .addPermission(Manifest.permission.READ_EXTERNAL_STORAGE) .addPermission(Manifest.permission.CAMERA) .addPermission(Manifest.permission.CALL_PHONE) .addPermission(Manifest.permission.READ_PHONE_STATE) .initPermission() } override fun initView() { mTabEntities.clear() //---------------------------------------TabLayout设置--------------------------------------- if (modelFVPList.isEmpty()) { modelFVPList.add(ModelFVP("我的", FragmentPlaceholder.newInstance())) modelFVPList.add(ModelFVP("Demo", FragmentDemoType.newInstance())) modelFVPList.add(ModelFVP("设置", FragmentPlaceholder.newInstance())) } //========================================================================================== for (i in modelFVPList.indices) { mTabEntities.add(ModelTab(modelFVPList[i].name, mIconSelectIds[i], mIconUnselectIds[i])) } view_pager.adapter = AdapterFVP(supportFragmentManager, modelFVPList) initTabLayout() } private fun initTabLayout() { tab_layout1!!.setTabData(mTabEntities) tab_layout1!!.setOnTabSelectListener(object : OnTabSelectListener { override fun onTabSelect(position: Int) { view_pager.currentItem = position } override fun onTabReselect(position: Int) { if (position == 0) { //mTabLayout1.showMsg(0, mRandom.nextInt(100) + 1); //UnreadMsgUtils.show(mTabLayout_2.getMsgView(0), mRandom.nextInt(100) + 1); } } }) view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int ) { } override fun onPageSelected(position: Int) { tab_layout1!!.currentTab = position } override fun onPageScrollStateChanged(state: Int) {} }) view_pager.currentItem = 1 } override fun initData() { } override fun onBackPressed() { if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) { super.onBackPressed() return } else { RxToast.info("再次点击返回键退出") } mBackPressed = System.currentTimeMillis() } //============================================================================================== companion object { //双击返回键 退出 //---------------------------------------------------------------------------------------------- private const val TIME_INTERVAL = 2000 // # milliseconds, desired time passed between two back presses. } }
apache-2.0
4b5bd6b88230e8170eb1238e2573ad71
35.142857
104
0.603338
4.895699
false
false
false
false
openstreetview/android
app/src/main/java/com/telenav/osv/tasks/fragments/TasksFragment.kt
1
7134
package com.telenav.osv.tasks.fragments import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.content.res.AppCompatResources import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import com.telenav.osv.R import com.telenav.osv.application.ApplicationPreferences import com.telenav.osv.application.KVApplication import com.telenav.osv.common.Injection import com.telenav.osv.common.dialog.KVDialog import com.telenav.osv.common.model.base.KVBaseFragment import com.telenav.osv.common.toolbar.KVToolbar import com.telenav.osv.common.toolbar.ToolbarSettings import com.telenav.osv.databinding.FragmentTasksBinding import com.telenav.osv.jarvis.login.utils.LoginUtils import com.telenav.osv.tasks.adapter.TasksAdapter import com.telenav.osv.tasks.viewmodels.TasksViewModel import com.telenav.osv.utils.LogUtils import com.telenav.osv.utils.NetworkUtils import com.telenav.osv.utils.recyclerview.DividerItemDecoration import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable /** * This fragment helps in displaying assigned tasks for user. * Also it displays total amount paid and pending for a user. */ class TasksFragment : KVBaseFragment() { private lateinit var tasksAdapter: TasksAdapter private lateinit var fragmentTasksBinding: FragmentTasksBinding private lateinit var appPrefs: ApplicationPreferences private lateinit var tasksFragmentListener: TasksFragmentListener private lateinit var tasksViewModel: TasksViewModel private var sessionExpireDialog: KVDialog? = null private val disposables: CompositeDisposable = CompositeDisposable() init { TAG = TasksFragment::class.java.simpleName } override fun onAttach(context: Context) { super.onAttach(context) if (context is TasksFragmentListener) { tasksFragmentListener = context activity?.let { appPrefs = (it.application as KVApplication).appPrefs } tasksViewModel = ViewModelProviders.of(this, Injection.provideTasksViewModelFactory( Injection.provideFetchAssignedTasksUseCase( Injection.provideTasksApi(true, appPrefs)), Injection.provideCurrencyUtil(), Injection.provideGenericJarvisApiErrorHandler(context, appPrefs))) .get(TasksViewModel::class.java) } else { throw RuntimeException("$context must implement TasksFragmentListener.") } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) fragmentTasksBinding = FragmentTasksBinding.inflate(inflater, container, false).apply { tasksVm = tasksViewModel lifecycleOwner = this@TasksFragment } return fragmentTasksBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setTasksRecyclerView(view) tasksViewModel.fetchAssignedTasks() tasksViewModel.assignedTasks.observe(viewLifecycleOwner, Observer { assignedTasks -> tasksAdapter.updateData(assignedTasks) }) tasksViewModel.isLoaderVisible.observe(viewLifecycleOwner, Observer { isLoaderVisible -> tasksAdapter.setIsClickable(!isLoaderVisible) }) tasksViewModel.shouldReLogin.observe(viewLifecycleOwner, Observer { shouldReLogin -> if (shouldReLogin) { context?.let { showSessionExpiredDialog(it) } } }) fragmentTasksBinding.tvExploreNearby.setOnClickListener { activity?.onBackPressed() } } override fun getToolbarSettings(kvToolbar: KVToolbar?): ToolbarSettings? { return ToolbarSettings.Builder() .setTitle(getString(R.string.tasks_toolbar_title)) .setNavigationIcon(R.drawable.vector_back_arrow) .build() } private fun setTasksRecyclerView(view: View) { fragmentTasksBinding.rvTasks.let { tasksAdapter = TasksAdapter(Injection.provideCurrencyUtil()) tasksAdapter.setOnTaskItemClick { taskId -> tasksFragmentListener.onTaskItemClick(taskId) } tasksAdapter.setHasStableIds(true) it.adapter = tasksAdapter it.layoutManager = LinearLayoutManager(view.context, LinearLayoutManager.VERTICAL, false) it.addItemDecoration(DividerItemDecoration(view.context, null, true, false)) } } /** * This method displays alert dialog for expired session */ private fun showSessionExpiredDialog(context: Context) { if (sessionExpireDialog == null) { sessionExpireDialog = LoginUtils.getSessionExpiredDialog(context) } sessionExpireDialog?.show() } override fun onStart() { super.onStart() val context = activity?.applicationContext if (context != null) { disposables.add(NetworkUtils.isInternetAvailableStream(context) .observable() .distinctUntilChanged() .observeOn(AndroidSchedulers.mainThread()) .subscribe( { isInternetAvailable -> val tvInternetConnectivityMessage = fragmentTasksBinding.tvInternetConnectivityMessage if (isInternetAvailable as Boolean) { tvInternetConnectivityMessage.visibility = View.GONE } else { tvInternetConnectivityMessage.text = getString(R.string.no_internet_connection_label) tvInternetConnectivityMessage.background = AppCompatResources.getDrawable(context, R.color.default_red) tvInternetConnectivityMessage.visibility = View.VISIBLE } }, { throwable -> LogUtils.logDebug(TAG, String.format("Status: error on internet. Message: %s.", throwable.message)) })) } } override fun onStop() { super.onStop() disposables.clear() } override fun handleBackPressed(): Boolean { return false } companion object { lateinit var TAG: String /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * @return A new instance of fragment TasksFragment. */ @JvmStatic fun newInstance() = TasksFragment() } interface TasksFragmentListener { fun onTaskItemClick(taskId: String) } }
lgpl-3.0
02158a29e26d3121854723f8b1a1133a
40.725146
139
0.668068
5.454128
false
false
false
false
sugnakys/UsbSerialConsole
UsbSerialConsole/app/src/main/java/jp/sugnakys/usbserialconsole/presentation/home/HomeViewModel.kt
1
3207
package jp.sugnakys.usbserialconsole.presentation.home import android.app.Application import androidx.lifecycle.AndroidViewModel import dagger.hilt.android.lifecycle.HiltViewModel import java.io.File import java.io.FileOutputStream import java.io.IOException import java.io.UnsupportedEncodingException import java.nio.charset.Charset import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import java.util.regex.Pattern import javax.inject.Inject import jp.sugnakys.usbserialconsole.device.DeviceRepository import jp.sugnakys.usbserialconsole.log.LogRepository import jp.sugnakys.usbserialconsole.preference.DefaultPreference import jp.sugnakys.usbserialconsole.usb.UsbRepository import timber.log.Timber @HiltViewModel class HomeViewModel @Inject constructor( private val logRepository: LogRepository, private val deviceRepository: DeviceRepository, private val usbRepository: UsbRepository, private val preference: DefaultPreference, application: Application ) : AndroidViewModel(application) { val receivedMessage = usbRepository.receivedData val isUSBReady get() = usbRepository.isUSBReady val isConnect = usbRepository.isConnect fun sendMessage(message: String) { if (message.isNotEmpty()) { val pattern = Pattern.compile("\n$") val matcher = pattern.matcher(message) val strResult = matcher.replaceAll("") + deviceRepository.getLineFeedCode(preference.lineFeedCodeSend) try { usbRepository.sendData(strResult) Timber.d("SendMessage: $message") usbRepository.updateReceivedData(message) } catch (e: UnsupportedEncodingException) { Timber.e(e.toString()) } } } fun clearReceivedMessage() = usbRepository.clearReceivedData() fun changeConnection(isConnect: Boolean) = usbRepository.changeConnection(isConnect) fun writeToFile(file: File, isTimestamp: Boolean): Boolean { val text = receivedMessage.value?.joinToString(System.lineSeparator()) { val timestamp = if (isTimestamp) { val formatTime = SimpleDateFormat( preference.timestampFormat, Locale.US ).format(Date(it.timestamp)) "[$formatTime] " } else { "" } timestamp + it.text } ?: return false var result = false var fos: FileOutputStream? = null try { fos = FileOutputStream(file) fos.write(text.toByteArray(Charset.defaultCharset())) result = true } catch (e: IOException) { Timber.e(e.toString()) } finally { try { fos?.close() } catch (e: IOException) { Timber.e(e.toString()) } } return result } fun getFileName(date: Date): String { val dateText = SimpleDateFormat( "yyyyMMdd_HHmmss", Locale.US ).format(date) return "$dateText.txt" } fun getLogDir() = logRepository.getLogDir() }
mit
1f7d43ddf21cad84b90edefb08faac07
31.734694
102
0.646087
4.744083
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/talk/ArchivedTalkPagesActivity.kt
1
8812
package org.wikipedia.talk import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.activity.viewModels import androidx.annotation.StringRes import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import androidx.paging.LoadState import androidx.paging.LoadStateAdapter import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import org.wikipedia.Constants.InvokeSource import org.wikipedia.R import org.wikipedia.activity.BaseActivity import org.wikipedia.databinding.ActivityArchivedTalkPagesBinding import org.wikipedia.history.HistoryEntry import org.wikipedia.page.LinkMovementMethodExt import org.wikipedia.page.PageActivity import org.wikipedia.page.PageTitle import org.wikipedia.readinglist.database.ReadingList import org.wikipedia.richtext.RichTextUtil import org.wikipedia.util.* import org.wikipedia.views.DrawableItemDecoration import org.wikipedia.views.PageItemView import org.wikipedia.views.WikiErrorView class ArchivedTalkPagesActivity : BaseActivity() { private lateinit var binding: ActivityArchivedTalkPagesBinding private val archivedTalkPagesAdapter = ArchivedTalkPagesAdapter() private val archivedTalkPagesLoadHeader = LoadingItemAdapter { archivedTalkPagesAdapter.retry(); } private val archivedTalkPagesLoadFooter = LoadingItemAdapter { archivedTalkPagesAdapter.retry(); } private val archivedTalkPagesConcatAdapter = archivedTalkPagesAdapter.withLoadStateHeaderAndFooter(archivedTalkPagesLoadHeader, archivedTalkPagesLoadFooter) private val itemCallback = ItemCallback() private val viewModel: ArchivedTalkPagesViewModel by viewModels { ArchivedTalkPagesViewModel.Factory(intent.extras!!) } public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityArchivedTalkPagesBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) setToolbarTitle(viewModel.pageTitle) supportActionBar?.setDisplayHomeAsUpEnabled(true) binding.recyclerView.layoutManager = LinearLayoutManager(this) binding.recyclerView.addItemDecoration(DrawableItemDecoration(this, R.attr.list_separator_drawable, drawStart = false, drawEnd = false)) binding.recyclerView.adapter = archivedTalkPagesConcatAdapter lifecycleScope.launch { viewModel.archivedTalkPagesFlow.collectLatest { archivedTalkPagesAdapter.submitData(it) } } lifecycleScope.launchWhenCreated { archivedTalkPagesAdapter.loadStateFlow.collectLatest { archivedTalkPagesLoadHeader.loadState = it.refresh archivedTalkPagesLoadFooter.loadState = it.append val showEmpty = (it.append is LoadState.NotLoading && it.append.endOfPaginationReached && archivedTalkPagesAdapter.itemCount == 0) if (showEmpty) { archivedTalkPagesConcatAdapter.addAdapter(EmptyItemAdapter(R.string.archive_empty)) } } } } private fun setToolbarTitle(pageTitle: PageTitle) { binding.toolbarTitle.text = StringUtil.fromHtml(getString(R.string.talk_archived_title, "<a href='#'>${StringUtil.removeNamespace(pageTitle.displayText)}</a>")) binding.toolbarTitle.contentDescription = binding.toolbarTitle.text binding.toolbarTitle.movementMethod = LinkMovementMethodExt { _ -> val entry = HistoryEntry(TalkTopicsActivity.getNonTalkPageTitle(viewModel.pageTitle), HistoryEntry.SOURCE_ARCHIVED_TALK) startActivity(PageActivity.newIntentForNewTab(this, entry, entry.title)) } RichTextUtil.removeUnderlinesFromLinks(binding.toolbarTitle) FeedbackUtil.setButtonLongPressToast(binding.toolbarTitle) } private inner class LoadingItemAdapter(private val retry: () -> Unit) : LoadStateAdapter<LoadingViewHolder>() { override fun onBindViewHolder(holder: LoadingViewHolder, loadState: LoadState) { holder.bindItem(loadState, retry) } override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): LoadingViewHolder { return LoadingViewHolder(layoutInflater.inflate(R.layout.item_list_progress, parent, false)) } } private inner class EmptyItemAdapter(@StringRes private val text: Int) : RecyclerView.Adapter<EmptyViewHolder>() { override fun onBindViewHolder(holder: EmptyViewHolder, position: Int) { holder.bindItem(text) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EmptyViewHolder { return EmptyViewHolder(layoutInflater.inflate(R.layout.item_list_progress, parent, false)) } override fun getItemCount(): Int { return 1 } } private inner class ArchivedTalkPagesDiffCallback : DiffUtil.ItemCallback<PageTitle>() { override fun areItemsTheSame(oldItem: PageTitle, newItem: PageTitle): Boolean { return oldItem.prefixedText == newItem.prefixedText && oldItem.namespace == newItem.namespace } override fun areContentsTheSame(oldItem: PageTitle, newItem: PageTitle): Boolean { return areItemsTheSame(oldItem, newItem) } } private inner class ArchivedTalkPagesAdapter : PagingDataAdapter<PageTitle, RecyclerView.ViewHolder>(ArchivedTalkPagesDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, pos: Int): ArchivedTalkPageItemHolder { val view = PageItemView<PageTitle>(this@ArchivedTalkPagesActivity) view.callback = itemCallback return ArchivedTalkPageItemHolder(view) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { getItem(position)?.let { (holder as ArchivedTalkPageItemHolder).bindItem(it) } } } private inner class LoadingViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bindItem(loadState: LoadState, retry: () -> Unit) { val errorView = itemView.findViewById<WikiErrorView>(R.id.errorView) val progressBar = itemView.findViewById<View>(R.id.progressBar) progressBar.isVisible = loadState is LoadState.Loading errorView.isVisible = loadState is LoadState.Error errorView.retryClickListener = View.OnClickListener { retry() } if (loadState is LoadState.Error) { errorView.setError(loadState.error, viewModel.pageTitle) } } } private inner class EmptyViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bindItem(@StringRes text: Int) { val errorView = itemView.findViewById<WikiErrorView>(R.id.errorView) val progressBar = itemView.findViewById<View>(R.id.progressBar) val emptyMessage = itemView.findViewById<TextView>(R.id.emptyMessage) progressBar.isVisible = false errorView.isVisible = false emptyMessage.text = getString(text) emptyMessage.isVisible = true } } private inner class ArchivedTalkPageItemHolder constructor(val view: PageItemView<PageTitle>) : RecyclerView.ViewHolder(view) { fun bindItem(title: PageTitle) { view.item = title view.setTitle(title.displayText) view.setImageUrl(title.thumbUrl) view.setImageVisible(!title.thumbUrl.isNullOrEmpty()) view.setDescription(title.description) } } private inner class ItemCallback : PageItemView.Callback<PageTitle?> { override fun onClick(item: PageTitle?) { item?.let { startActivity(TalkTopicsActivity.newIntent(this@ArchivedTalkPagesActivity, it, InvokeSource.ARCHIVED_TALK_ACTIVITY)) } } override fun onLongClick(item: PageTitle?): Boolean { return false } override fun onActionClick(item: PageTitle?, view: View) {} override fun onListChipClick(readingList: ReadingList) {} } companion object { const val EXTRA_TITLE = "talkTopicTitle" fun newIntent(context: Context, talkTopicTitle: PageTitle): Intent { return Intent(context, ArchivedTalkPagesActivity::class.java) .putExtra(EXTRA_TITLE, talkTopicTitle) } } }
apache-2.0
b860ca83bf4f012bfacda151ef8fae3e
44.658031
168
0.721176
5.208038
false
false
false
false
noloman/keddit
app/src/main/java/me/manulorenzo/keddit/adapter/NewsAdapter.kt
1
2363
package me.manulorenzo.keddit.adapter import android.support.v7.widget.RecyclerView import android.util.SparseArray import android.view.ViewGroup import me.manulorenzo.keddit.constants.AdapterConstants import me.manulorenzo.keddit.model.RedditNewsItem import java.util.* /** * Created by Manuel Lorenzo on 04/11/2016. */ class NewsAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var items: ArrayList<ViewType> private var delegateAdapters = SparseArray<ViewTypeDelegateAdapter>() private val loadingItem = object : ViewType { override fun getViewType(): Int = AdapterConstants.LOADING } private fun getLastPosition() = if (items.lastIndex == -1) 0 else items.lastIndex init { delegateAdapters.put(AdapterConstants.LOADING, LoadingDelegateAdapter()) delegateAdapters.put(AdapterConstants.NEWS, NewsDelegateAdapter()) items = ArrayList() items.add(loadingItem) } override fun getItemCount(): Int { return items.size } override fun getItemViewType(position: Int): Int { return items[position].getViewType() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return delegateAdapters.get(viewType).onCreateViewHolder(parent) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { return delegateAdapters.get(getItemViewType(position)).onBindViewHolder(holder, items.get(position)) } fun addNews(aNews: List<RedditNewsItem>) { // first remove loading and notify val initPosition = items.size - 1 items.removeAt(initPosition) notifyItemRemoved(initPosition) // insert aNews and the loading at the end of the list items.addAll(aNews) items.add(loadingItem) notifyItemRangeChanged(initPosition, items.size + 1) // plus loading item } fun clearAndAddNews(aNews: List<RedditNewsItem>) { items.clear() notifyItemRangeRemoved(0, getLastPosition()) items.addAll(aNews) items.add(loadingItem) notifyItemRangeInserted(0, items.size) } fun getNews(): List<RedditNewsItem> { return items .filter { it.getViewType() == AdapterConstants.NEWS } .map { it as RedditNewsItem } } }
mit
ecbe2c5bcbe98bd14fbae12843222086
32.295775
108
0.696572
4.679208
false
false
false
false
peterLaurence/TrekAdvisor
app/src/main/java/com/peterlaurence/trekme/viewmodel/mapimport/MapImportViewModel.kt
1
4035
package com.peterlaurence.trekme.viewmodel.mapimport import android.net.Uri import androidx.documentfile.provider.DocumentFile import androidx.lifecycle.* import com.peterlaurence.trekme.core.map.Map import com.peterlaurence.trekme.core.map.maparchiver.unarchive import com.peterlaurence.trekme.core.map.mapimporter.MapImporter import com.peterlaurence.trekme.core.settings.Settings import com.peterlaurence.trekme.util.UnzipProgressionListener import com.peterlaurence.trekme.viewmodel.mapimport.MapImportViewModel.ItemData import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.launch import java.io.File import java.io.InputStream /** * This view-model manages [ItemData]s, which are wrappers around [DocumentFile]s. * The view supplies the list of [DocumentFile]s when the user selects a directory. */ class MapImportViewModel : ViewModel() { private val _itemLiveData = MutableLiveData<List<ItemData>>() val itemLiveData: LiveData<List<ItemData>> = _itemLiveData private var viewModelsMap = mapOf<Int, ItemData>() private val _unzipEvents = MutableLiveData<UnzipEvent>() /** * Only emit distinct [UnzipEvent]. For example, sending multiple times an [UnzipProgressEvent] * with a progress of 30% is useless. */ val unzipEvents: LiveData<UnzipEvent> = _unzipEvents.asFlow().distinctUntilChanged().asLiveData() /** * The view gives the view-model the list of [DocumentFile]. * Then we prepare the model and notify the view with the corresponding list of [ItemData]. */ fun updateUriList(docs: List<DocumentFile>) { viewModelsMap = docs.mapNotNull { if (it.name != null) { ItemData(it.name!!, it.uri, it.length()) } else null }.associateBy { it.id } _itemLiveData.postValue(viewModelsMap.values.toList()) } /** * Launch the unzip of an archive. */ fun unarchiveAsync(inputStream: InputStream, item: ItemData) { viewModelScope.launch { val rootFolder = Settings.getAppDir() ?: return@launch val outputFolder = File(rootFolder, "imported") /* If the document has no name, give it one */ val name = item.name ?: "mapImported" unarchive(inputStream, outputFolder, name, item.length, object : UnzipProgressionListener { override fun onProgress(p: Int) { _unzipEvents.postValue(UnzipProgressEvent(item.id, p)) } /** * Import the extracted map. * For instance, only support extraction of [Map.MapOrigin.VIPS] maps. */ override fun onUnzipFinished(outputDirectory: File) { viewModelScope.launch { val res = MapImporter.importFromFile(outputDirectory, Map.MapOrigin.VIPS) _unzipEvents.postValue(UnzipMapImportedEvent(item.id, res.map, res.status)) } _unzipEvents.postValue(UnzipFinishedEvent(item.id, outputDirectory)) } override fun onUnzipError() { _unzipEvents.postValue(UnzipErrorEvent(item.id)) } } ) } } class ItemData(val name: String, val uri: Uri, val length: Long) { val id: Int = uri.hashCode() } } sealed class UnzipEvent { abstract val itemId: Int } data class UnzipProgressEvent(override val itemId: Int, val p: Int): UnzipEvent() data class UnzipErrorEvent(override val itemId: Int): UnzipEvent() data class UnzipFinishedEvent(override val itemId: Int, val outputFolder: File): UnzipEvent() data class UnzipMapImportedEvent(override val itemId: Int, val map: Map?, val status: MapImporter.MapParserStatus): UnzipEvent()
gpl-3.0
5fa4a9fcb6d2f41ce64ed89e064c39e2
39.35
128
0.633705
4.780806
false
false
false
false
RobertoArtiles/KittenGIFs
app/src/main/java/com/the_roberto/kittengifs/model/Settings.kt
1
3127
package com.the_roberto.kittengifs.model import android.content.Context import android.content.Context.MODE_PRIVATE import com.the_roberto.kittengifs.dagger.ForApplication import javax.inject.Inject import javax.inject.Singleton @Singleton class Settings @Inject constructor(@ForApplication private val context: Context) { private val PREFS_NAME = "pref_setting" private val PREF_LAST_OPENED_KITTEN = "pref_last_opened_kitten" private val PREF_KITTEN_TO_SHARE_URL = "pref_kitten_to_share_url" private val PREF_MAX_OFFSET = "pref_max_offset" private val PREF_VIEWS_COUNT = "pref_views_count" private val PREF_KITTENS_BEFORE_ASKING_TO_RATE = "pref_kittens_before_asking_to_rate" private val PREF_CURRENT_VERSION = "pref_current_version" fun setLastOpenedKitten(url: String?) { val prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE) prefs.edit().putString(PREF_LAST_OPENED_KITTEN, url).apply() } fun getLastOpenedKitten(): String? { val prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE) return prefs.getString(PREF_LAST_OPENED_KITTEN, null) } fun setKittenToShareUrl(url: String?) { val prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE) prefs.edit().putString(PREF_KITTEN_TO_SHARE_URL, url).apply() } fun getKittenToShareUrl(): String? { val prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE) return prefs.getString(PREF_KITTEN_TO_SHARE_URL, null) } fun setMaxOffset(maxOffset: Int?) { val prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE) prefs.edit().putInt(PREF_MAX_OFFSET, maxOffset ?: 0).apply() } fun getMaxOffset(): Int { val prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE) return Math.min(prefs.getInt(PREF_MAX_OFFSET, 100), 4998) //5000 is a limit for the public API } fun getViewsCount(): Long { val prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE) return prefs.getLong(PREF_VIEWS_COUNT, 0) } fun setViewsCount(viewsCount: Long) { val prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE) prefs.edit().putLong(PREF_VIEWS_COUNT, viewsCount).apply() } fun setKittensBeforeAskingToRate(kittens: Int) { val prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE) prefs.edit().putInt(PREF_KITTENS_BEFORE_ASKING_TO_RATE, kittens).apply() } fun getKittensBeforeAskingToRate(): Int { val prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE) return prefs.getInt(PREF_KITTENS_BEFORE_ASKING_TO_RATE, 10) } fun setCurrentVersion(version: Int) { val prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE) prefs.edit().putInt(PREF_CURRENT_VERSION, version).apply() } fun getCurrentVersion(): Int { val prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE) return prefs.getInt(PREF_CURRENT_VERSION, 0) } enum class ContentType { GIF, MP4 } }
apache-2.0
619f12be8207e69ef91dc5e5f641e429
35.360465
102
0.696194
3.850985
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/lang/utils/snapshot/SnapshotListTest.kt
4
1152
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.utils.snapshot import junit.framework.TestCase class SnapshotListTest : TestCase() { private sealed class Value { object Value1 : Value() object Value2 : Value() } fun `test simple add`() { val list = SnapshotList<Value>() list.add(Value.Value1) check(list.toList() == listOf(Value.Value1)) } fun `test snapshot-rollback add 1`() { val list = SnapshotList<Value>() val snapshot = list.startSnapshot() list.add(Value.Value1) snapshot.rollback() check(list.isEmpty()) } fun `test snapshot-rollback add 2`() { val list = SnapshotList<Value>() list.add(Value.Value1) val snapshot = list.startSnapshot() list.add(Value.Value2) check(list.toList() == listOf(Value.Value1, Value.Value2)) snapshot.rollback() check(list.toList() == listOf(Value.Value1)) } private fun <E> SnapshotList<E>.toList(): List<E> = iterator().asSequence().toList() }
mit
ee6e7b14dd0ccf8610e23ec208b577e4
25.790698
69
0.610243
3.931741
false
true
false
false
TeamWizardry/LibrarianLib
buildSrc/src/main/kotlin/com/teamwizardry/gradle/task/GenerateFabricModJson.kt
1
8307
@file:Suppress("UnstableApiUsage") package com.teamwizardry.gradle.task import org.gradle.api.DefaultTask import org.gradle.api.provider.Property import org.gradle.api.tasks.* import java.io.File import com.teamwizardry.gradle.util.DslContext import org.gradle.api.file.FileCollection import org.gradle.api.provider.ListProperty import org.gradle.api.provider.MapProperty open class GenerateFabricModJson : DefaultTask() { private val ctx = DslContext(project) /** * The root resources directory (e.g. `$buildDir/generated/main/resources`) */ @Input val outputRoot: Property<File> = ctx.property() @Input val id: Property<String> = ctx.property() @Input val version: Property<String> = ctx.property() @Input val name: Property<String> = ctx.property() { project.displayName } @Optional @Input val icon: Property<String> = ctx.property() @Optional @InputFile val iconFile: Property<File> = ctx.property() @Input val description: Property<String> = ctx.property() { "" } @Internal val entrypoints: ListProperty<Entrypoint> = ctx.listProperty() { listOf() } @Input val mixins: ListProperty<String> = ctx.listProperty() { listOf() } @Internal val dependencies: ListProperty<Dependency> = ctx.listProperty() { listOf() } @Nested val modMenu: ModMenuData = ModMenuData() @Input val jars: ListProperty<String> = ctx.listProperty() { listOf() } fun entrypoint(type: String, adapter: String? = null, value: String) { entrypoints.add(Entrypoint(type, adapter, value)) } fun mixin(path: String) { mixins.add(path) } fun depends(id: String, version: String) { dependencies.add(Dependency(id, version)) } @get:Input protected val inputEntrypoints: List<String> get() = entrypoints.get().map { "${it.type}\uE000${it.adapter}\uE000${it.value}" } @get:Input protected val inputDependencies: List<String> get() = dependencies.get().map { "${it.id}\uE000${it.version}" } @get:OutputFiles protected val outputFile: FileCollection get() { val root = outputRoot.get() val files = ctx.project.files() files.from(root.resolve("fabric.mod.json")) if(iconFile.orNull != null) icon.orNull?.also { root.resolve(it) } return files } @TaskAction private fun runTask() { val root = outputRoot.get() root.mkdirs() root.resolve("fabric.mod.json").writeText(makeJson()) val icon = this.icon.orNull val iconFile = this.iconFile.orNull if(icon != null && iconFile != null) { root.resolve(icon).parentFile.mkdirs() iconFile.copyTo(root.resolve(icon), overwrite = true) } } private fun makeJson(): String { val entrypoints = this.entrypoints.get().groupBy { it.type } /* | "icon": { |${iconScales.joinToString(",\n") { "\"$it\": \"assets/${id.get()}/logo_$it.png\"" }.prependIndent(" ")} | }, */ return """ |{ | "schemaVersion": 1, | "id": "${id.get()}", | "version": "${version.get()}", | | "name": "${name.get()}", | "description": "${description.get()}", | "authors": [ | "thecodewarrior" | ], | "contact": { | "homepage": "https://github.com/TeamWizardry/LibrarianLib", | "sources": "https://github.com/TeamWizardry/LibrarianLib" | }, | | "license": "LGPL-3.0", | "icon": "${icon.getOrElse("")}", | | "environment": "*", | "entrypoints": { |${entrypoints.entries.joinToString(",\n") { makeEntrypointTypeJson(it.key, it.value) }.prependIndent(" ")} | }, | "mixins": [ |${mixins.get().joinToString(",\n") { "\"$it\"" }.prependIndent(" ")} | ], | "depends": { |${dependencies.get().joinToString(",\n") { "\"${it.id}\": \"${it.version}\"" }.prependIndent(" ")} | }, | "custom": { |${makeModMenuJson().prependIndent(" ")} | }${makeJarsJson()} |} """.trimMargin() } private fun makeEntrypointTypeJson(type: String, entrypoints: List<Entrypoint>): String { return """ |"$type": [ |${entrypoints.joinToString(",\n") { makeEntrypointJson(it) }.prependIndent(" ")} |] """.trimMargin() } private fun makeEntrypointJson(entrypoint: Entrypoint): String { return if (entrypoint.adapter == null) { "\"${entrypoint.value}\"" } else { """ |{ | "adapter": "${entrypoint.adapter}", | "value": "${entrypoint.value}" |} """.trimMargin() } } private fun makeJarsJson(): String { val jars = this.jars.get() return if (jars.isEmpty()) { "" } else { ",\n \"jars\": [\n" + jars.joinToString(",\n") { """ | { | "file": "META-INF/jars/$it" | } """.trimMargin() } + "\n ]" } } private fun makeModMenuJson(): String { if(modMenu.hidden.get()) return "" val links = modMenu.links.get() val linkBlock = if(links.isEmpty()) null else """ |"links": { |${links.entries.joinToString(",\n") { "\"${it.key}\": \"${it.value}\"" }.prependIndent(" ")} |} """.trimMargin() val badges = modMenu.badges.get() val badgeBlock = if (badges.isEmpty()) null else """ |"badges": [${badges.joinToString(", ") { "\"$it\"" }}] """.trimMargin() val parent = modMenu.parent.get() val fakeParent = modMenu.fakeParent val parentBlock = if(fakeParent.id.get() != "") { """ |"parent": { | "id": "${fakeParent.id.get()}", | "name": "${fakeParent.name.get()}", | "description": "${fakeParent.description.get()}", | "icon": "${icon.getOrElse("")}", | "badges": [${fakeParent.badges.get().joinToString(", ") { "\"$it\"" }}] |} """.trimMargin() } else if(parent != "") { "\"parent\": \"$parent\"" } else { null } return """ |"modmenu": { |${listOfNotNull(linkBlock, badgeBlock, parentBlock).joinToString(",\n").prependIndent(" ")} |} """.trimMargin() } data class Dependency(val id: String, val version: String) data class Entrypoint(val type: String, val adapter: String?, val value: String) inner class ModMenuData { @Input val hidden: Property<Boolean> = ctx.property() { false } @Input val links: MapProperty<String, String> = ctx.mapProperty() { mapOf() } @Input val badges: ListProperty<String> = ctx.listProperty() { listOf() } @Input val parent: Property<String> = ctx.property() { "" } @Nested val fakeParent: FakeParentData = FakeParentData() fun parent(id: String) { parent.set(id) fakeParent.id.set("") } fun parent(id: String, name: String, description: String, badges: List<String>) { parent.set("") fakeParent.id.set(id) fakeParent.name.set(name) fakeParent.description.set(description) fakeParent.badges.set(badges) } } inner class FakeParentData { @Input val id: Property<String> = ctx.property() { "" } @Input val name: Property<String> = ctx.property() { "" } @Input val description: Property<String> = ctx.property() { "" } @Input val badges: ListProperty<String> = ctx.listProperty() { listOf() } } companion object { val iconScales: List<Int> = listOf(64, 128, 256, 512) } }
lgpl-3.0
b2efd17a394e9aeb7db9cfa07893f7dd
28.565836
118
0.520645
4.110341
false
false
false
false
mhsjlw/AndroidSnap
app/src/main/java/me/keegan/snap/InboxFragment.kt
1
3446
package me.keegan.snap import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v4.app.ListFragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ListView import com.parse.FindCallback import com.parse.ParseException import com.parse.ParseFile import com.parse.ParseObject import com.parse.ParseQuery import com.parse.ParseUser import java.util.ArrayList class InboxFragment : ListFragment() { protected lateinit var mMessages: MutableList<ParseObject> override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_inbox, container, false) } override fun onResume() { super.onResume() activity!!.setProgressBarIndeterminateVisibility(true) val query = ParseQuery<ParseObject>(ParseConstants.CLASS_MESSAGES) query.whereEqualTo(ParseConstants.KEY_RECIPIENT_IDS, ParseUser.getCurrentUser().objectId) query.addDescendingOrder(ParseConstants.KEY_CREATED_AT) query.findInBackground { messages, e -> activity!!.setProgressBarIndeterminateVisibility(false) if (e == null) { // We found messages! mMessages = messages val usernames = arrayOfNulls<String>(mMessages.size) var i = 0 for (message in mMessages) { usernames[i] = message.getString(ParseConstants.KEY_SENDER_NAME) i++ } if (listView.adapter == null) { val adapter = MessageAdapter( listView.context, mMessages) listAdapter = adapter } else { // refill the adapter! (listView.adapter as MessageAdapter).refill(mMessages) } } } } override fun onListItemClick(l: ListView?, v: View?, position: Int, id: Long) { super.onListItemClick(l, v, position, id) val message = mMessages[position] val messageType = message.getString(ParseConstants.KEY_FILE_TYPE) val file = message.getParseFile(ParseConstants.KEY_FILE) val fileUri = Uri.parse(file!!.url) if (messageType == ParseConstants.TYPE_IMAGE) { // view the image val intent = Intent(activity, ViewImageActivity::class.java) intent.data = fileUri startActivity(intent) } else { // view the video val intent = Intent(Intent.ACTION_VIEW, fileUri) intent.setDataAndType(fileUri, "video/*") startActivity(intent) } // Delete it! val ids = message.getList<String>(ParseConstants.KEY_RECIPIENT_IDS) if (ids!!.size == 1) { // last recipient - delete the whole thing! message.deleteInBackground() } else { // remove the recipient and save ids.remove(ParseUser.getCurrentUser().objectId) val idsToRemove = ArrayList<String>() idsToRemove.add(ParseUser.getCurrentUser().objectId) message.removeAll(ParseConstants.KEY_RECIPIENT_IDS, idsToRemove) message.saveInBackground() } } }
mit
54d05b4d6006b8427de66eede2f34eff
33.118812
116
0.614335
4.958273
false
false
false
false
IRA-Team/VKPlayer
app/src/main/java/com/irateam/vkplayer/database/AudioVKCacheDatabase.kt
1
4476
/* * Copyright (C) 2015 IRA-Team * * 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.irateam.vkplayer.database import android.content.ContentValues import android.content.Context import android.database.Cursor import com.irateam.vkplayer.model.VKAudio import com.irateam.vkplayer.util.extension.use import java.util.* class AudioVKCacheDatabase(context: Context) : DatabaseHelper(context) { fun insert(audio: VKAudio): Long = writableDatabase.use { it.insert(Tables.AudioVKCache.NAME, null, audio.toContentValues()) } fun update(audio: VKAudio): Long = writableDatabase.use { val id = it.update( Tables.AudioVKCache.NAME, audio.toContentValues(), idWhereClause(audio), null) id.toLong() } fun delete(audio: VKAudio): Long = writableDatabase.use { val id = it.delete(Tables.AudioVKCache.NAME, idWhereClause(audio), null) id.toLong() } fun cache(audio: VKAudio): Long = writableDatabase.use { db -> db.query(Tables.AudioVKCache.NAME, null, idWhereClause(audio), null, null, null, null) .use { cursor -> if (cursor.count <= 0) { insert(audio) } else { update(audio) } } } fun getAll(): List<VKAudio> = readableDatabase.use { db -> db.query(Tables.AudioVKCache.NAME, null, null, null, null, null, "_id DESC") .use { cursor -> val audios = ArrayList<VKAudio>() if (cursor.moveToFirst()) { do { audios.add(cursor.toAudio()) } while (cursor.moveToNext()) } audios } } fun removeAll(): Unit = writableDatabase.use { it.delete(Tables.AudioVKCache.NAME, null, null) } private fun idWhereClause(audio: VKAudio): String { return "${Tables.AudioVKCache.Columns.AUDIO_ID} = ${audio.audioId} AND " + "${Tables.AudioVKCache.Columns.OWNER_ID} = ${audio.ownerId}" } companion object { fun VKAudio.toContentValues(): ContentValues { val cv = ContentValues() cv.put(Tables.AudioVKCache.Columns.AUDIO_ID, audioId) cv.put(Tables.AudioVKCache.Columns.OWNER_ID, ownerId) cv.put(Tables.AudioVKCache.Columns.ARTIST, artist) cv.put(Tables.AudioVKCache.Columns.TITLE, title) cv.put(Tables.AudioVKCache.Columns.DURATION, duration) cv.put(Tables.AudioVKCache.Columns.URL, url) cv.put(Tables.AudioVKCache.Columns.CACHE_PATH, cachePath) cv.put(Tables.AudioVKCache.Columns.LYRICS_ID, lyricsId) cv.put(Tables.AudioVKCache.Columns.ALBUM_ID, albumId) cv.put(Tables.AudioVKCache.Columns.GENRE, genre) cv.put(Tables.AudioVKCache.Columns.ACCESS_KEY, accessKey) return cv } fun Cursor.toAudio(): VKAudio { var i = 1 val audioId = getInt(i++) val ownerId = getInt(i++) val artist = getString(i++) val title = getString(i++) val duration = getInt(i++) val url = getString(i++) val cachePath = getString(i++) val lyricsId = getInt(i++) val albumId = getInt(i++) val genre = getInt(i++) val accessKey = getString(i) val audio = VKAudio( audioId, ownerId, artist, title, duration, url, lyricsId, albumId, genre, accessKey) audio.cachePath = cachePath return audio } } }
apache-2.0
71c0dfd332d004aea9be7ab6b0a4b90b
34.244094
94
0.561439
4.418559
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/chat/prv/sync/MessengerDao.kt
1
6935
package me.proxer.app.chat.prv.sync import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.RoomWarnings import androidx.room.Transaction import io.reactivex.Maybe import me.proxer.app.auth.LocalUser import me.proxer.app.chat.prv.ConferenceWithMessage import me.proxer.app.chat.prv.LocalConference import me.proxer.app.chat.prv.LocalMessage import me.proxer.library.enums.Device import me.proxer.library.enums.MessageAction import org.koin.core.KoinComponent import org.threeten.bp.Instant /** * @author Ruben Gees */ @Dao abstract class MessengerDao : KoinComponent { @Transaction open fun insertMessageToSend(user: LocalUser, text: String, conferenceId: Long): LocalMessage { val message = LocalMessage( calculateNextMessageToSendId(), conferenceId, user.id, user.name, text, MessageAction.NONE, Instant.now(), Device.MOBILE ) insertMessage(message) markConferenceAsRead(conferenceId) return message } @Transaction open fun clear() { clearMessages() clearConferences() } open fun getMessagesLiveDataForConference(conferenceId: Long): MediatorLiveData<List<LocalMessage>> { val sentLiveData = getSentMessagesLiveDataForConference(conferenceId) val unsentLiveData = getUnsentMessagesLiveDataForConference(conferenceId) return MediatorLiveData<List<LocalMessage>>().apply { addSource(sentLiveData) { value = (unsentLiveData.value ?: emptyList()) + (it ?: emptyList()) } addSource(unsentLiveData) { // Prevent duplicate update when detecting sent messages. // If the amount of unsent messages is lower than before, these messages have been sent. // Without this check, both sources would update (racy) and potentially cause weird visual effects. if (it?.size ?: 0 >= value?.takeWhile { message -> message.id < 0 }?.size ?: 0) { value = (it ?: emptyList()) + (sentLiveData.value ?: emptyList()) } } } } @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun insertConferences(conference: List<LocalConference>): List<Long> @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun insertMessages(messages: List<LocalMessage>): List<Long> @Insert(onConflict = OnConflictStrategy.ABORT) abstract fun insertMessage(message: LocalMessage): Long @Query("SELECT * FROM conferences ORDER BY date DESC") abstract fun getConferences(): List<LocalConference> @Query("SELECT * FROM conferences ORDER BY date DESC LIMIT :amount") abstract fun getMostRecentConferences(amount: Int): List<LocalConference> @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH) @Query( "SELECT * " + "FROM conferences " + "LEFT JOIN ( " + "SELECT * FROM ( " + "SELECT id AS messageId, " + "conferenceId, " + "userId, " + "message AS messageText, " + "username, " + "`action` as messageAction from messages " + "ORDER BY date, id) " + "GROUP BY conferenceId) AS messages " + "ON conferences.id = messages.conferenceId " + "WHERE topic LIKE '%' " + "|| :searchQuery " + "|| '%' " + "ORDER BY date DESC" ) abstract fun getConferencesLiveData(searchQuery: String): LiveData<List<ConferenceWithMessage>?> @Query("SELECT * FROM conferences WHERE id = :id LIMIT 1") abstract fun getConferenceLiveData(id: Long): LiveData<LocalConference?> @Query("SELECT * FROM conferences WHERE id = :id LIMIT 1") abstract fun getConferenceMaybe(id: Long): Maybe<LocalConference> @Query("SELECT * FROM conferences WHERE localIsRead = 0 AND isRead = 0 ORDER BY id DESC") abstract fun getUnreadConferences(): List<LocalConference> @Query("SELECT * FROM conferences WHERE localIsRead != 0 AND isRead = 0") abstract fun getConferencesToMarkAsRead(): List<LocalConference> @Query("SELECT * FROM conferences WHERE id = :id LIMIT 1") abstract fun getConference(id: Long): LocalConference @Query("SELECT * FROM conferences WHERE id = :id LIMIT 1") abstract fun findConference(id: Long): LocalConference? @Query("SELECT * FROM conferences WHERE topic = :username LIMIT 1") abstract fun findConferenceForUser(username: String): LocalConference? @Query("SELECT * FROM (SELECT * FROM messages WHERE conferenceId = :conferenceId AND id >= 0 ORDER BY id DESC) ") abstract fun getSentMessagesLiveDataForConference(conferenceId: Long): LiveData<List<LocalMessage>> @Query("SELECT * FROM (SELECT * FROM messages WHERE conferenceId = :conferenceId AND id < 0 ORDER BY id ASC)") abstract fun getUnsentMessagesLiveDataForConference(conferenceId: Long): LiveData<List<LocalMessage>> @Query("SELECT COUNT(*) FROM messages WHERE conferenceId = :conferenceId AND id = :lastReadMessageId") abstract fun getUnreadMessageAmountForConference(conferenceId: Long, lastReadMessageId: Long): Int @Query("SELECT * FROM messages WHERE conferenceId = :conferenceId AND id >= 0 ORDER BY id DESC LIMIT :amount") abstract fun getMostRecentMessagesForConference(conferenceId: Long, amount: Int): List<LocalMessage> @Query("SELECT * FROM messages WHERE conferenceId = :conferenceId AND id >= 0 ORDER BY id DESC LIMIT 1") abstract fun findMostRecentMessageForConference(conferenceId: Long): LocalMessage? @Query("SELECT * FROM messages WHERE conferenceId = :conferenceId AND id >= 0 ORDER BY id ASC LIMIT 1") abstract fun findOldestMessageForConference(conferenceId: Long): LocalMessage? @Query("SELECT MIN(id) FROM messages") abstract fun findLowestMessageId(): Long? @Query("SELECT * FROM messages WHERE id < 0 ORDER BY id DESC") abstract fun getMessagesToSend(): List<LocalMessage> @Query("DELETE FROM messages WHERE id = :messageId") abstract fun deleteMessageToSend(messageId: Long) @Query("UPDATE conferences SET localIsRead = 1 WHERE id = :conferenceId") abstract fun markConferenceAsRead(conferenceId: Long) @Query("UPDATE conferences SET isFullyLoaded = 1 WHERE id = :conferenceId") abstract fun markConferenceAsFullyLoaded(conferenceId: Long) @Query("DELETE FROM conferences") abstract fun clearConferences() @Query("DELETE FROM messages") abstract fun clearMessages() private fun calculateNextMessageToSendId(): Long { val candidate = findLowestMessageId() ?: -1L return when (candidate < 0) { true -> candidate - 1 false -> -1L } } }
gpl-3.0
c66f2ddc5a266d73bc23c95b8426f772
39.555556
117
0.689257
4.638796
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/stats/dto/StatsWallpostStat.kt
1
2969
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.stats.dto import com.google.gson.annotations.SerializedName import kotlin.Int import kotlin.collections.List /** * @param postId * @param hide - Hidings number * @param joinGroup - People have joined the group * @param links - Link clickthrough * @param reachSubscribers - Subscribers reach * @param reachSubscribersCount * @param reachTotal - Total reach * @param reachTotalCount * @param reachViral * @param reachAds * @param report - Reports number * @param toGroup - Clickthrough to community * @param unsubscribe - Unsubscribed members * @param sexAge */ data class StatsWallpostStat( @SerializedName("post_id") val postId: Int? = null, @SerializedName("hide") val hide: Int? = null, @SerializedName("join_group") val joinGroup: Int? = null, @SerializedName("links") val links: Int? = null, @SerializedName("reach_subscribers") val reachSubscribers: Int? = null, @SerializedName("reach_subscribers_count") val reachSubscribersCount: Int? = null, @SerializedName("reach_total") val reachTotal: Int? = null, @SerializedName("reach_total_count") val reachTotalCount: Int? = null, @SerializedName("reach_viral") val reachViral: Int? = null, @SerializedName("reach_ads") val reachAds: Int? = null, @SerializedName("report") val report: Int? = null, @SerializedName("to_group") val toGroup: Int? = null, @SerializedName("unsubscribe") val unsubscribe: Int? = null, @SerializedName("sex_age") val sexAge: List<StatsSexAge>? = null )
mit
49313afca8560121f5057a43a83857a3
36.582278
81
0.682721
4.193503
false
false
false
false
inorichi/tachiyomi-extensions
src/en/eggporncomics/src/eu/kanade/tachiyomi/extension/en/eggporncomics/Eggporncomics.kt
1
10725
package eu.kanade.tachiyomi.extension.en.eggporncomics import eu.kanade.tachiyomi.annotations.Nsfw import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.asObservable import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import eu.kanade.tachiyomi.util.asJsoup import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import rx.Observable import java.util.Calendar @Nsfw class Eggporncomics : ParsedHttpSource() { override val name = "Eggporncomics" override val baseUrl = "https://eggporncomics.com" override val lang = "en" override val supportsLatest = true override val client: OkHttpClient = network.cloudflareClient // Popular // couldn't find a page with popular comics, defaulting to the popular "anime-comics" category override fun popularMangaRequest(page: Int): Request { return GET("$baseUrl/category/1/anime-comics?page=$page", headers) } override fun popularMangaSelector() = "div.preview:has(div.name)" override fun popularMangaFromElement(element: Element): SManga { return SManga.create().apply { element.select("a:has(img)").let { setUrlWithoutDomain(it.attr("href")) title = it.text() thumbnail_url = it.select("img").attr("abs:src") } } } override fun popularMangaNextPageSelector() = "ul.ne-pe li.next:not(.disabled)" // Latest override fun latestUpdatesRequest(page: Int): Request { return GET("$baseUrl/latest-comics?page=$page", headers) } override fun latestUpdatesSelector() = popularMangaSelector() override fun latestUpdatesFromElement(element: Element): SManga = popularMangaFromElement(element) override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector() // Search override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> { return client.newCall(searchMangaRequest(page, query, filters)) .asObservable().doOnNext { response -> if (!response.isSuccessful) { // when combining a category filter and comics filter, if there are no results the source // issues a 404, override that so as not to confuse users if (response.request.url.toString().contains("category-tag") && response.code == 404) { Observable.just(MangasPage(emptyList(), false)) } else { response.close() throw Exception("HTTP error ${response.code}") } } } .map { response -> searchMangaParse(response) } } private val queryRegex = Regex("""[\s']""") override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { return if (query.isNotBlank()) { GET("$baseUrl/search/${query.replace(queryRegex, "-")}?page=$page", headers) } else { val url = baseUrl.toHttpUrlOrNull()!!.newBuilder() val filterList = if (filters.isEmpty()) getFilterList() else filters val category = filterList.find { it is CategoryFilter } as UriPartFilter val comics = filterList.find { it is ComicsFilter } as UriPartFilter when { category.isNotNull() && comics.isNotNull() -> { url.addPathSegments("category-tag/${category.toUriPart()}/${comics.toUriPart()}") } category.isNotNull() -> { url.addPathSegments("category/${category.toUriPart()}") } comics.isNotNull() -> { url.addPathSegments("comics-tag/${comics.toUriPart()}") } } url.addQueryParameter("page", page.toString()) GET(url.toString(), headers) } } override fun searchMangaSelector() = popularMangaSelector() override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element) override fun searchMangaNextPageSelector() = popularMangaNextPageSelector() // Details private val descriptionPrefixRegex = Regex(""":.*""") override fun mangaDetailsParse(document: Document): SManga { return SManga.create().apply { thumbnail_url = document.select(pageListSelector).first().toFullSizeImage() description = document.select("div.links ul").joinToString("\n") { element -> element.select("a") .joinToString(prefix = element.select("span").text().replace(descriptionPrefixRegex, ": ")) { it.text() } } } } // Chapters override fun chapterListParse(response: Response): List<SChapter> { return listOf( SChapter.create().apply { setUrlWithoutDomain(response.request.url.toString()) name = "Chapter" date_upload = response.asJsoup().select("div.info > div.meta li:contains(days ago)").firstOrNull() ?.let { Calendar.getInstance().apply { add(Calendar.DAY_OF_YEAR, -(it.text().substringBefore(" ").toIntOrNull() ?: 0)) }.timeInMillis } ?: 0 } ) } override fun chapterListSelector() = throw UnsupportedOperationException("Not used") override fun chapterFromElement(element: Element): SChapter = throw UnsupportedOperationException("Not used") // Pages private fun Element.toFullSizeImage() = this.attr("abs:src").replace("thumb300_", "") private val pageListSelector = "div.grid div.image img" override fun pageListParse(document: Document): List<Page> { return document.select(pageListSelector).mapIndexed { i, img -> Page(i, "", img.toFullSizeImage()) } } override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException("Not used") // Filters override fun getFilterList() = FilterList( Filter.Header("Leave query blank to use filters"), Filter.Separator(), CategoryFilter("Category", getCategoryList), ComicsFilter("Comics", getComicsList) ) private class CategoryFilter(name: String, vals: Array<Pair<String, String?>>) : UriPartFilter(name, vals) private class ComicsFilter(name: String, vals: Array<Pair<String, String?>>) : UriPartFilter(name, vals) private val getCategoryList: Array<Pair<String, String?>> = arrayOf( Pair("Any", null), Pair("3d comics", "7/3d-comics"), Pair("8muses", "18/8muses"), Pair("Anime", "1/anime"), Pair("Cartoon", "2/cartoon"), Pair("Dickgirls & Shemale", "6/dickgirls-shemale"), Pair("Furry", "4/furry"), Pair("Games comics", "3/games-comics"), Pair("Hentai manga", "10/hentai-manga"), Pair("Interracial", "14/interracial"), Pair("Milf", "11/milf"), Pair("Mindcontrol", "15/mindcontrol"), Pair("Porn Comix", "16/porn-comix"), Pair("Western", "12/western"), Pair("Yaoi/Gay", "8/yaoigay"), Pair("Yuri and Lesbian", "9/yuri-and-lesbian") ) private val getComicsList: Array<Pair<String, String?>> = arrayOf( Pair("Any", null), Pair("3d", "85/3d"), Pair("Adventure Time", "2950/adventure-time"), Pair("Anal", "13/anal"), Pair("Ben 10", "641/ben10"), Pair("Big boobs", "3025/big-boobs"), Pair("Big breasts", "6/big-breasts"), Pair("Big cock", "312/big-cock"), Pair("Bigass", "604/big-ass-porn-comics-new"), Pair("Black cock", "2990/black-cock"), Pair("Blowjob", "7/blowjob"), Pair("Bondage", "24/bondage"), Pair("Breast expansion hentai", "102/breast-expansion-new"), Pair("Cumshot", "427/cumshot"), Pair("Dark skin", "29/dark-skin"), Pair("Dofantasy", "1096/dofantasy"), Pair("Double penetration", "87/double-penetration"), Pair("Doujin moe", "3028/doujin-moe"), Pair("Erotic", "602/erotic"), Pair("Fairy tail porn", "3036/fairy-tail"), Pair("Fakku", "1712/Fakku-Comics-new"), Pair("Fakku comics", "1712/fakku-comics-new"), Pair("Family Guy porn", "774/family-guy"), Pair("Fansadox", "1129/fansadox-collection"), Pair("Feminization", "385/feminization"), Pair("Forced", "315/forced"), Pair("Full color", "349/full-color"), Pair("Furry", "19/furry"), Pair("Futanari", "2994/futanari"), Pair("Group", "58/group"), Pair("Hardcore", "304/hardcore"), Pair("Harry Potter porn", "338/harry-potter"), Pair("Hentai", "321/hentai"), Pair("Incest", "3007/incest"), Pair("Incest - Family Therapy Top", "3007/family-therapy-top"), Pair("Incognitymous", "545/incognitymous"), Pair("Interracical", "608/interracical"), Pair("Jab Comix", "1695/JAB-Comics-NEW-2"), Pair("Kaos comics", "467/kaos"), Pair("Kim Possible porn", "788/kim-possible"), Pair("Lesbian", "313/lesbian"), Pair("Locofuria", "343/locofuria"), Pair("Milf", "48/milf"), Pair("Milftoon", "1678/milftoon-comics"), Pair("Muscle", "2/muscle"), Pair("Nakadashi", "10/nakadashi"), Pair("PalComix", "373/palcomix"), Pair("Pokemon hentai", "657/pokemon"), Pair("Shadbase", "1717/shadbase-comics"), Pair("Shemale", "126/shemale"), Pair("Slut", "301/slut"), Pair("Sparrow hentai", "3035/sparrow-hentai"), Pair("Star Wars hentai", "1344/star-wars"), Pair("Stockings", "51/stockings"), Pair("Superheroine Central", "615/superheroine-central"), Pair("The Cummoner", "3034/the-cummoner"), Pair("The Rock Cocks", "3031/the-rock-cocks"), Pair("ZZZ Comics", "1718/zzz-comics") ) private open class UriPartFilter(displayName: String, val vals: Array<Pair<String, String?>>) : Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) { fun toUriPart() = vals[state].second fun isNotNull(): Boolean = toUriPart() != null } }
apache-2.0
856c07d68563181577433af3fb2a59d6
39.018657
155
0.614359
4.136136
false
false
false
false
soulnothing/HarmonyGen
src/main/kotlin/HarmonyGen/MessageBus/Helpers.kt
1
1726
package HarmonyGen.MessageBus import HarmonyGen.DB.getDBConn import HarmonyGen.Util.getQueryBase import com.rethinkdb.RethinkDB import com.rethinkdb.net.Cursor import kotlin.concurrent.thread /** * Created by on 7/27/16. */ val r = RethinkDB.r val table = getQueryBase("events") inline fun <T : BaseEvent, reified C : Any> addEvent(event: T) = table.insert(event.toRethinkDB()).run<Any>(getDBConn()) inline fun <T : BaseEvent, reified C : Any> updateEvent(event: T) = table.get(event.id).update(event.toRethinkDB()).run<Any>(getDBConn()) fun ProcessStaleEvents() { val task = thread { println("Processing stale events") val r = RethinkDB.r var events = r.db("HarmonyGen").table("events") .filter(r.hashMap("completed", false)) .run<Cursor<MutableMap<String, Any?>>>(getDBConn()) for (event: MutableMap<String, Any?> in events) { eventMatcher(event, UndeterminedEvent(event)) } } if (!task.isAlive) task.start() } fun eventMatcher(event: MutableMap<String, Any?>, obj: UndeterminedEvent) { when (obj.type) { "GetArtist" -> dispatchGetArtist(GetArtist(event)) "InitializePlayList" -> dispatchInitializePlayList(InitializePlayList(event)) } } fun EventListener(): Thread { val task = thread { val r = RethinkDB.r val events = r.db("HarmonyGen").table("events") .filter(r.hashMap("completed", false)) .changes().run<Cursor<MutableMap<String, Any?>>>(getDBConn()) for (c: MutableMap<String, Any?> in events) { val event = c?.get("new_val") as MutableMap<String, Any?> if (event !== null) { eventMatcher(event, UndeterminedEvent(event)) } } } if (!task.isAlive) task.start() return task }
bsd-3-clause
48884a73a74e72c26390847cb6e2f37c
29.298246
137
0.673233
3.438247
false
false
false
false
Kiandr/CrackingCodingInterview
Kotlin/src/Chapter01/_04_palindrome_perm/IsPalindromePerm.kt
1
464
package Chapter01._04_palindrome_perm fun main(args: Array<String>) { //println(IsPalindromePerm().isPalindromePerm("tactcoapapa")) } class IsPalindromePerm { fun isPalindromePerm(str: String): Boolean { val strMap = HashMap<Char, Int>() str.replace("[^A-Za-z]".toRegex(), "").forEach { strMap[it] = (strMap [it] ?: 0) + 1 } val oddCharacters = strMap.count { it.value.rem(2) == 1 } return oddCharacters <= 1 } }
mit
d48a2f50d63c9aeca52ff7a488f14c33
22.25
94
0.62069
3.411765
false
false
false
false
kvakil/venus
src/main/kotlin/venus/riscv/insts/divu.kt
1
397
package venus.riscv.insts import venus.riscv.insts.dsl.RTypeInstruction val divu = RTypeInstruction( name = "divu", opcode = 0b0110011, funct3 = 0b101, funct7 = 0b0000001, eval32 = { a, b -> val x = a.toLong() shl 32 ushr 32 val y = b.toLong() shl 32 ushr 32 if (y == 0L) a else (x / y).toInt() } )
mit
be7e0c126e33d9dcf3518213da7d925c
23.8125
45
0.511335
3.364407
false
false
false
false
Maccimo/intellij-community
platform/statistics/devkit/src/com/intellij/internal/statistic/devkit/actions/ShowChangedStateEventsAction.kt
3
4085
// 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.statistic.devkit.actions import com.google.common.collect.Maps import com.intellij.icons.AllIcons import com.intellij.idea.ActionsBundle import com.intellij.internal.statistic.StatisticsBundle import com.intellij.internal.statistic.devkit.StatisticsDevKitUtil import com.intellij.internal.statistic.devkit.toolwindow.ChangedStateEventsPanel import com.intellij.internal.statistic.devkit.toolwindow.eventLogToolWindowsId import com.intellij.internal.statistic.eventLog.fus.FeatureUsageLogger import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.wm.ToolWindowManager import com.intellij.ui.content.ContentFactory import com.jetbrains.fus.reporting.model.lion3.LogEvent internal class ShowChangedStateEventsAction(private val recorderId: String) : DumbAwareAction( ActionsBundle.message("action.ShowChangedStateStatisticsAction.text"), ActionsBundle.message("action.ShowChangedStateStatisticsAction.description"), AllIcons.Actions.Diff) { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return if (!RecordStateStatisticsEventLogAction.checkLogRecordingEnabled(project, recorderId)) return val message = StatisticsBundle.message("stats.collecting.feature.usages.in.event.log") runBackgroundableTask(message, project, false) { indicator -> FeatureUsageLogger.rollOver() val oldState = FusStatesRecorder.getCurrentState() val newState = FusStatesRecorder.recordStateAndWait(project, indicator, recorderId) if (newState == null) { StatisticsDevKitUtil.showNotification(project, NotificationType.ERROR, StatisticsBundle.message("stats.failed.recording.state")) } else { val difference = newState.filter { newEvent -> oldState.all { !isEventsEquals(newEvent, it) } } ApplicationManager.getApplication().invokeLater { showResults(project, difference) } } } } private fun showResults(project: Project, difference: Collection<LogEvent>) { if (difference.isEmpty()) { StatisticsDevKitUtil.showNotification(project, NotificationType.INFORMATION, StatisticsBundle.message("stats.no.changed.events")) return } val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(eventLogToolWindowsId) ?: return val displayName = "Changed events: $recorderId" val changedEventsComponent = ChangedStateEventsPanel(project, toolWindow.disposable, difference, recorderId).component val content = ContentFactory.getInstance().createContent(changedEventsComponent, displayName, true) content.preferredFocusableComponent = changedEventsComponent val contentManager = toolWindow.contentManager contentManager.addContent(content) contentManager.setSelectedContent(content) } override fun update(event: AnActionEvent) { super.update(event) event.presentation.isEnabled = FusStatesRecorder.isComparisonAvailable() } companion object { private val SYSTEM_FIELDS = arrayOf("created", "last", "system_event_id", "system_headless") fun isEventsEquals(newEvent: LogEvent, oldEvent: LogEvent): Boolean { if (newEvent == oldEvent) return true if (newEvent.group != oldEvent.group) return false if (newEvent.event.id != oldEvent.event.id) return false if (newEvent.event.data.size != oldEvent.event.data.size) return false val difference = Maps.difference(newEvent.event.data, oldEvent.event.data) for (key in difference.entriesDiffering().keys) { if (newEvent.group.id == "settings" && key == "id") continue if (key !in SYSTEM_FIELDS) { return false } } return true } } }
apache-2.0
7157aa292c508d1fb040682012fe241d
46.5
136
0.773072
4.668571
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/motion/leftright/MotionLastColumnAction.kt
1
2144
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.action.motion.leftright import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimMotionGroupBase import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.MotionType import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.handler.Motion import com.maddyhome.idea.vim.handler.MotionActionHandler import com.maddyhome.idea.vim.helper.enumSetOf import com.maddyhome.idea.vim.helper.inVisualMode import com.maddyhome.idea.vim.helper.isEndAllowed import com.maddyhome.idea.vim.options.OptionConstants import com.maddyhome.idea.vim.options.OptionScope import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString import java.util.* class MotionLastColumnInsertAction : MotionLastColumnAction() { override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_SAVE_STROKE) } open class MotionLastColumnAction : MotionActionHandler.ForEachCaret() { override val motionType: MotionType = MotionType.INCLUSIVE override fun getOffset( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument?, operatorArguments: OperatorArguments, ): Motion { val allow = if (editor.inVisualMode) { val opt = ( injector.optionService.getOptionValue( OptionScope.LOCAL(editor), OptionConstants.selectionName ) as VimString ).value opt != "old" } else { if (operatorArguments.isOperatorPending) false else editor.isEndAllowed } val offset = injector.motion.moveCaretToRelativeLineEnd(editor, caret, operatorArguments.count1 - 1, allow) return Motion.AdjustedOffset(offset, VimMotionGroupBase.LAST_COLUMN) } }
mit
a309e0d42f0deef2a366cb86b0e3569f
35.338983
111
0.777052
4.123077
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ReplaceContainsIntention.kt
1
3428
// 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.intentions.conventionNameCalls import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.intentions.* import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.util.OperatorNameConventions class ReplaceContainsIntention : SelfTargetingRangeIntention<KtDotQualifiedExpression>( KtDotQualifiedExpression::class.java, KotlinBundle.lazyMessage("replace.contains.call.with.in.operator") ), HighPriorityAction { override fun applicabilityRange(element: KtDotQualifiedExpression): TextRange? { if (element.calleeName != OperatorNameConventions.CONTAINS.asString()) return null val resolvedCall = element.toResolvedCall(BodyResolveMode.PARTIAL) ?: return null if (!resolvedCall.isReallySuccess()) return null val argument = resolvedCall.call.valueArguments.singleOrNull() ?: return null if ((resolvedCall.getArgumentMapping(argument) as ArgumentMatch).valueParameter.index != 0) return null val target = resolvedCall.resultingDescriptor val returnType = target.returnType ?: return null if (!target.builtIns.isBooleanOrSubtype(returnType)) return null if (!element.isReceiverExpressionWithValue()) return null val functionDescriptor = getFunctionDescriptor(element) ?: return null if (!functionDescriptor.isOperatorOrCompatible) return null return element.callExpression!!.calleeExpression!!.textRange } override fun applyTo(element: KtDotQualifiedExpression, editor: Editor?) { val argument = element.callExpression!!.valueArguments.single().getArgumentExpression()!! val receiver = element.receiverExpression val psiFactory = KtPsiFactory(element) val prefixExpression = element.parent as? KtPrefixExpression val expression = if (prefixExpression != null && prefixExpression.operationToken == KtTokens.EXCL) { prefixExpression.replace(psiFactory.createExpressionByPattern("$0 !in $1", argument, receiver)) } else { element.replace(psiFactory.createExpressionByPattern("$0 in $1", argument, receiver)) } // Append semicolon to previous statement if needed if (argument is KtLambdaExpression) { psiFactory.appendSemicolonBeforeLambdaContainingElement(expression) } } private fun getFunctionDescriptor(element: KtDotQualifiedExpression): FunctionDescriptor? { val resolvedCall = element.resolveToCall() ?: return null return resolvedCall.resultingDescriptor as? FunctionDescriptor } }
apache-2.0
3a07932ba7290dfaad775cb0ac33d6aa
49.411765
158
0.771295
5.449921
false
false
false
false
ingokegel/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/untypedUnresolvedAccess/UnresolvedReferenceInspectionSink.kt
7
3179
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.codeInspection.untypedUnresolvedAccess import com.intellij.codeHighlighting.HighlightDisplayLevel import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemHighlightType.* import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.util.InspectionMessage import com.intellij.openapi.application.ApplicationManager import com.intellij.psi.PsiElement import org.jetbrains.plugins.groovy.highlighter.GroovySyntaxHighlighter import org.jetbrains.plugins.groovy.highlighting.HighlightSink internal class UnresolvedReferenceInspectionSink(private val problemsHolder: ProblemsHolder) : HighlightSink { override fun registerProblem(highlightElement: PsiElement, highlightType: ProblemHighlightType, message: String, vararg fixes: LocalQuickFix?) { if (problemsHolder.isOnTheFly && highlightType === LIKE_UNKNOWN_SYMBOL && handleSpecial(highlightElement, message, *fixes)) { return } problemsHolder.registerProblem(highlightElement, message, highlightType, *fixes) } private fun handleSpecial(element: PsiElement, @InspectionMessage message: String, vararg fixes: LocalQuickFix?): Boolean { // at this point we register the problem with LIKE_UNKNOWN_SYMBOL type. when (GrUnresolvedAccessInspection.getHighlightDisplayLevel(element)) { HighlightDisplayLevel.ERROR -> { // If we override LIKE_UNKNOWN_SYMBOL with GENERIC_ERROR_OR_WARNING (i.e. go into else branch of this statement), // and the level is ERROR, then the reference would be highlighted with red waved line [HighlightInfoType#ERROR]. // But is case of ERROR we actually want the reference to be red, and coincidentally // LIKE_UNKNOWN_SYMBOL + ERROR already results in [HighlightInfoType#WRONG_REF], so we just do nothing. // @see com.intellij.codeInspection.ProblemDescriptorUtil.getHighlightInfoType return false } HighlightDisplayLevel.WEAK_WARNING -> { // WEAK_WARNING is default inspection level, and in this case we override text attributes and severity of the reference val newHighlightType = if (ApplicationManager.getApplication().isUnitTestMode) WARNING else INFORMATION val descriptor = problemsHolder.manager.createProblemDescriptor( element, message, problemsHolder.isOnTheFly, fixes, newHighlightType ) descriptor.setTextAttributes(GroovySyntaxHighlighter.UNRESOLVED_ACCESS) problemsHolder.registerProblem(descriptor) return true } else -> { // In all other cases we want the reference to be highlighted using inspection settings, // so we use GENERIC_ERROR_OR_WARNING instead of LIKE_UNKNOWN_SYMBOL problemsHolder.registerProblem(element, message, GENERIC_ERROR_OR_WARNING, *fixes) return true } } } }
apache-2.0
c02acdc893aab3db8a3f000188c6a3be
55.767857
140
0.747405
5.263245
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/rename/renameKotlinBaseMethod/after/RenameKotlinBaseMethod.kt
14
284
package testing.rename interface A { fun second() : Int } public open class B: A { override fun second() = 1 } class C: B() { override fun second() = 2 } fun usages() { val b = B() val a: A = b val c = C() a.second() b.second() c.second() }
apache-2.0
129273b88e1a64ac10628353888b908f
10.36
29
0.521127
2.989474
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorOpenOptions.kt
2
1257
// 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.openapi.fileEditor.impl import org.jetbrains.annotations.ApiStatus @ApiStatus.Internal data class FileEditorOpenOptions( @JvmField var selectAsCurrent: Boolean = true, @JvmField var reuseOpen: Boolean = false, @JvmField var usePreviewTab: Boolean = false, @JvmField var requestFocus: Boolean = false, @JvmField var pin: Boolean? = null, @JvmField var index: Int = -1, @JvmField val isExactState: Boolean = false, @JvmField var isReopeningOnStartup: Boolean = false, ) { fun clone() = copy() // no arg copying for Java // @formatter:off @JvmOverloads fun withSelectAsCurrent(value: Boolean = true) = apply { selectAsCurrent = value } @JvmOverloads fun withReuseOpen(value: Boolean = true) = apply { reuseOpen = value } @JvmOverloads fun withUsePreviewTab(value: Boolean = true) = apply { usePreviewTab = value } @JvmOverloads fun withRequestFocus(value: Boolean = true) = apply { requestFocus = value } fun withPin(value: Boolean?) = apply { pin = value } fun withIndex(value: Int) = apply { index = value } // @formatter:on }
apache-2.0
d43bca5bc3ac5b8a06edac49f5d4f763
45.592593
140
0.713604
4.003185
false
false
false
false