repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
zdary/intellij-community
platform/platform-tests/testSrc/com/intellij/configurationStore/LoadInvalidProjectTest.kt
1
4368
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.openapi.module.ConfigurationErrorDescription import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.impl.ProjectLoadingErrorsHeadlessNotifier import com.intellij.openapi.project.Project import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.project.stateStore import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.DisposableRule import com.intellij.testFramework.TemporaryDirectory import com.intellij.testFramework.loadProjectAndCheckResults import com.intellij.testFramework.rules.ProjectModelRule import com.intellij.util.io.assertMatches import com.intellij.util.io.directoryContentOf import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity import kotlinx.coroutines.runBlocking import org.assertj.core.api.Assertions.assertThat import org.junit.Assume.assumeTrue import org.junit.Before import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.nio.file.Path import java.nio.file.Paths class LoadInvalidProjectTest { companion object { @JvmField @ClassRule val appRule = ApplicationRule() private val testDataRoot: Path get() = Paths.get(PathManagerEx.getCommunityHomePath()).resolve("platform/platform-tests/testData/configurationStore/invalid") } @JvmField @Rule val tempDirectory = TemporaryDirectory() @JvmField @Rule val disposable = DisposableRule() private val errors = ArrayList<ConfigurationErrorDescription>() @Before fun setUp() { ProjectLoadingErrorsHeadlessNotifier.setErrorHandler(errors::add, disposable.disposable) } @Test fun `load empty iml`() { loadProjectAndCheckResults("empty-iml-file") { project -> assertThat(ModuleManager.getInstance(project).modules).hasSize(1) assertThat(WorkspaceModel.getInstance(project).entityStorage.current.entities(ModuleEntity::class.java).single().name).isEqualTo("foo") assertThat(errors.single().description).contains("foo.iml") } } @Test fun `malformed xml in iml`() { loadProjectAndCheckResults("malformed-xml-in-iml") { project -> assertThat(ModuleManager.getInstance(project).modules).hasSize(1) assertThat(WorkspaceModel.getInstance(project).entityStorage.current.entities(ModuleEntity::class.java).single().name).isEqualTo("foo") assertThat(errors.single().description).contains("foo.iml") } } @Test fun `no iml file`() { loadProjectAndCheckResults("no-iml-file") { project -> //this repeats behavior in the old model: if iml files doesn't exist we create a module with empty configuration and report no errors assertThat(ModuleManager.getInstance(project).modules.single().name).isEqualTo("foo") assertThat(errors).isEmpty() } } @Test fun `empty library xml`() { loadProjectAndCheckResults("empty-library-xml") { project -> //this repeats behavior in the old model: if library configuration file cannot be parsed it's silently ignored assertThat(LibraryTablesRegistrar.getInstance().getLibraryTable(project).libraries).isEmpty() assertThat(errors).isEmpty() } } @Test fun `duplicating libraries`() { loadProjectAndCheckResults("duplicating-libraries") { project -> assertThat(LibraryTablesRegistrar.getInstance().getLibraryTable(project).libraries.single().name).isEqualTo("foo") assertThat(errors).isEmpty() project.stateStore.save() val expected = directoryContentOf(testDataRoot.resolve("duplicating-libraries-fixed")) .mergeWith(directoryContentOf(testDataRoot.resolve ("common"))) val projectDir = project.stateStore.directoryStorePath!!.parent projectDir.assertMatches(expected) } } private fun loadProjectAndCheckResults(testDataDirName: String, checkProject: suspend (Project) -> Unit) { assumeTrue(ProjectModelRule.isWorkspaceModelEnabled) return loadProjectAndCheckResults(listOf(testDataRoot.resolve("common"), testDataRoot.resolve(testDataDirName)), tempDirectory, checkProject) } }
apache-2.0
e6bb3bb4f56672da5a44017acbd4eaf8
39.444444
145
0.775641
4.837209
false
true
false
false
blokadaorg/blokada
android5/app/src/main/java/service/MonitorService.kt
1
8405
/* * This file is part of Blokada. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * Copyright © 2021 Blocka AB. All rights reserved. * * @author Karol Gusak ([email protected]) */ package service import android.app.Service import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Binder import android.os.IBinder import engine.Host import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import model.AppState import model.BlokadaException import model.HistoryEntry import model.TunnelStatus import ui.utils.cause import utils.Logger import utils.MonitorNotification object MonitorService { private var strategy: MonitorServiceStrategy = SimpleMonitorServiceStrategy() fun setup(useForeground: Boolean) { if (useForeground) { strategy = ForegroundMonitorServiceStrategy() } strategy.setup() } fun setCounter(counter: Long) = strategy.setCounter(counter) fun setHistory(history: List<HistoryEntry>) = strategy.setHistory(history) fun setTunnelStatus(tunnelStatus: TunnelStatus) = strategy.setTunnelStatus(tunnelStatus) fun setAppState(appState: AppState) = strategy.setAppState(appState) fun setWorking(working: Boolean) = strategy.setWorking(working) } private interface MonitorServiceStrategy { fun setup() fun setCounter(counter: Long) fun setHistory(history: List<HistoryEntry>) fun setTunnelStatus(tunnelStatus: TunnelStatus) fun setAppState(appState: AppState) fun setWorking(working: Boolean) } // This strategy just shows the notification private class SimpleMonitorServiceStrategy: MonitorServiceStrategy { private val notification = NotificationService private var counter: Long = 0 private var lastDenied: List<Host> = emptyList() private var tunnelStatus: TunnelStatus = TunnelStatus.off() private var dnsLabel: String = "" private var appState: AppState = AppState.Deactivated private var working: Boolean = false override fun setup() {} override fun setCounter(counter: Long) { this.counter = counter updateNotification() } override fun setHistory(history: List<HistoryEntry>) { lastDenied = history.sortedByDescending { it.time }.take(3).map { it.name } updateNotification() } override fun setTunnelStatus(tunnelStatus: TunnelStatus) { this.tunnelStatus = tunnelStatus updateNotification() } override fun setAppState(appState: AppState) { this.appState = appState updateNotification() } override fun setWorking(working: Boolean) { this.working = working updateNotification() } private fun updateNotification() { val prototype = MonitorNotification(tunnelStatus, counter, lastDenied, appState, working) notification.show(prototype) } } // This strategy keeps the app alive while showing the notification private class ForegroundMonitorServiceStrategy: MonitorServiceStrategy { private val log = Logger("Monitor") private val context = ContextService private val scope = GlobalScope private var connection: ForegroundConnection? = null @Synchronized get @Synchronized set override fun setup() { try { log.v("Starting Foreground Service") val ctx = context.requireAppContext() ctx.startService(Intent(ctx, ForegroundService::class.java)) } catch (ex: Exception) { log.w("Could not start ForegroundService".cause(ex)) } scope.launch { // To initially bind to the ForegroundService getConnection() } } override fun setCounter(counter: Long) { scope.launch { getConnection().binder.onNewStats(counter, null, null, null, null, null) } } override fun setHistory(history: List<HistoryEntry>) { scope.launch { val lastDenied = history.sortedByDescending { it.time }.take(3).map { it.name } getConnection().binder.onNewStats(null, lastDenied, null, null, null, null) } } override fun setTunnelStatus(tunnelStatus: TunnelStatus) { scope.launch { getConnection().binder.onNewStats(null, null, tunnelStatus, null, null, null) } } override fun setAppState(appState: AppState) { scope.launch { getConnection().binder.onNewStats(null, null, null, null, appState, null) } } override fun setWorking(working: Boolean) { scope.launch { getConnection().binder.onNewStats(null, null, null, null, null, working) } } private suspend fun getConnection(): ForegroundConnection { return connection ?: run { val deferred = CompletableDeferred<ForegroundBinder>() val connection = bind(deferred) deferred.await() this.connection = connection connection } } private suspend fun bind(deferred: ConnectDeferred): ForegroundConnection { val ctx = context.requireAppContext() val intent = Intent(ctx, ForegroundService::class.java).apply { action = FOREGROUND_BINDER_ACTION } val connection = ForegroundConnection(deferred, onConnectionClosed = { this.connection = null }) if (!ctx.bindService(intent, connection, Context.BIND_AUTO_CREATE or Context.BIND_ABOVE_CLIENT or Context.BIND_IMPORTANT )) { deferred.completeExceptionally(BlokadaException("Could not bindService()")) } return connection } } class ForegroundService: Service() { private val notification = NotificationService private var binder: ForegroundBinder? = null private var counter: Long = 0 private var lastDenied: List<Host> = emptyList() private var tunnelStatus: TunnelStatus = TunnelStatus.off() private var appState: AppState = AppState.Deactivated private var working: Boolean = false override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { ContextService.setApp(this.application) updateNotification() return START_STICKY } override fun onBind(intent: Intent?): IBinder? { if (FOREGROUND_BINDER_ACTION == intent?.action) { ContextService.setApp(this.application) binder = ForegroundBinder { counter, lastDenied, tunnelStatus, dnsLabel, appState, working -> this.counter = counter ?: this.counter this.lastDenied = lastDenied ?: this.lastDenied this.tunnelStatus = tunnelStatus ?: this.tunnelStatus this.appState = appState ?: this.appState this.working = working ?: this.working updateNotification() } return binder } return null } private fun updateNotification() { val prototype = MonitorNotification(tunnelStatus, counter, lastDenied, appState, working) val n = notification.build(prototype) startForeground(prototype.id, n) } } class ForegroundBinder( val onNewStats: ( counter: Long?, lastDenied: List<Host>?, tunnelStatus: TunnelStatus?, dnsLabel: String?, appState: AppState?, working: Boolean? ) -> Unit ) : Binder() const val FOREGROUND_BINDER_ACTION = "ForegroundBinder" private class ForegroundConnection( private val deferred: ConnectDeferred, val onConnectionClosed: () -> Unit ): ServiceConnection { private val log = Logger("ForegroundConnection") lateinit var binder: ForegroundBinder override fun onServiceConnected(name: ComponentName, binder: IBinder) { this.binder = binder as ForegroundBinder deferred.complete(this.binder) } override fun onServiceDisconnected(name: ComponentName?) { log.w("onServiceDisconnected") onConnectionClosed() } } private typealias ConnectDeferred = CompletableDeferred<ForegroundBinder>
mpl-2.0
ed55ff8f90c689aec80e070e3ea0be33
30.241636
105
0.674798
4.813288
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/framework/KotlinTemplatesFactory.kt
1
3072
// 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.framework import com.intellij.ide.util.projectWizard.ModuleBuilder import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.roots.ui.configuration.actions.NewModuleAction import com.intellij.platform.ProjectTemplate import com.intellij.platform.ProjectTemplatesFactory import com.intellij.platform.templates.BuilderBasedTemplate import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.KotlinJvmBundle import org.jetbrains.kotlin.platform.js.JsPlatforms import org.jetbrains.kotlin.platform.jvm.JvmPlatforms class KotlinTemplatesFactory : ProjectTemplatesFactory() { companion object { val EP_NAME = ExtensionPointName.create<ModuleBuilder>("org.jetbrains.kotlin.moduleBuilder") const val KOTLIN_GROUP_NAME: String = "Kotlin" const val KOTLIN_PARENT_GROUP_NAME = "Kotlin Group" } override fun getGroups() = arrayOf(KOTLIN_GROUP_NAME) override fun getGroupIcon(group: String) = KotlinIcons.SMALL_LOGO override fun getParentGroup(group: String?): String = KOTLIN_PARENT_GROUP_NAME override fun getGroupWeight(group: String?): Int = 1 override fun createTemplates(group: String?, context: WizardContext): Array<out ProjectTemplate> { val result = mutableListOf<ProjectTemplate>() if (isNewModuleAction()) { result.add( BuilderBasedTemplate( KotlinModuleBuilder( JvmPlatforms.unspecifiedJvmPlatform, "JVM | IDEA", KotlinJvmBundle.message("presentable.name.jvm.idea"), KotlinJvmBundle.message("kotlin.project.with.a.jvm.target.based.on.the.intellij.idea.build.system"), KotlinIcons.SMALL_LOGO, context ) ) ) result.add( BuilderBasedTemplate( KotlinModuleBuilder( JsPlatforms.defaultJsPlatform, "JS | IDEA", KotlinJvmBundle.message("presentable.name.js.idea"), KotlinJvmBundle.message("kotlin.project.with.a.javascript.target.based.on.the.intellij.idea.build.system"), KotlinIcons.JS, context ) ) ) } @Suppress("DEPRECATION") result.addAll(Extensions.getExtensions(EP_NAME).map { BuilderBasedTemplate(it) }) return result.toTypedArray() } private fun isNewModuleAction(): Boolean { return Thread.currentThread().stackTrace.any { element -> element.className == NewModuleAction::class.java.name } } }
apache-2.0
09cd466663e2100ce7d366fa02746290
42.885714
158
0.650716
5.060956
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/compilingEvaluator/ceAnonymousObject.kt
13
1435
package ceAnonymousObject public val publicTopLevelObject: Any = object { fun test() = 1 } private val privateTopLevelObject = object { fun test() = 1 } fun main(args: Array<String>) { MyClass().foo() } class MyClass { public val publicObject: Any = object { fun test() = 1 } protected val protectedObject: Any = object { fun test() = 1 } private val privateObject = object { fun test() = 1 } fun foo() { val localObject = object { fun test() = 1 } //Breakpoint! val a = 1 } } // EXPRESSION: publicTopLevelObject // RESULT: instance of ceAnonymousObject.CeAnonymousObjectKt$publicTopLevelObject$1(id=ID): LceAnonymousObject/CeAnonymousObjectKt$publicTopLevelObject$1; // -EXPRESSION: privateTopLevelObject // -RESULT: 1 // -EXPRESSION: privateTopLevelObject.test() // -RESULT: 1: I // EXPRESSION: publicObject // RESULT: instance of ceAnonymousObject.MyClass$publicObject$1(id=ID): LceAnonymousObject/MyClass$publicObject$1; // EXPRESSION: protectedObject // RESULT: instance of ceAnonymousObject.MyClass$protectedObject$1(id=ID): LceAnonymousObject/MyClass$protectedObject$1; // -EXPRESSION: privateObject // -RESULT: 1 // -EXPRESSION: privateObject.test() // -RESULT: 1: I // EXPRESSION: localObject // RESULT: instance of ceAnonymousObject.MyClass$foo$localObject$1(id=ID): LceAnonymousObject/MyClass$foo$localObject$1; // EXPRESSION: localObject.test() // RESULT: 1: I
apache-2.0
a09ff01686a20c1ce95410094c97adf2
28.895833
154
0.720557
3.756545
false
true
false
false
Flank/flank
check_version_updated/src/main/kotlin/com/github/flank/gradle/CheckVersionUpdated.kt
1
1323
package com.github.flank.gradle import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.get import java.io.ByteArrayOutputStream class CheckVersionUpdated : Plugin<Project> { private val taskName = "checkIfVersionUpdated" override fun apply(project: Project) { project.tasks.register(taskName, CheckVersionUpdatedTask::class.java) // project.afterEvaluate { // project.tasks["lintKotlin"].dependsOn(taskName) // } } private fun Project.execAndGetStdout(vararg args: String): String { val stdout = ByteArrayOutputStream() exec { commandLine(*args) standardOutput = stdout workingDir = projectDir } return stdout.toString().trimEnd() } private fun Project.isVersionChangedInBuildGradle(): Boolean { val localResultsStream = execAndGetStdout("git", "diff", "origin/master", "HEAD", "--", "build.gradle.kts") .split("\n") val commitedResultsStream = execAndGetStdout("git", "diff", "origin/master", "--", "build.gradle.kts") .split("\n") return (commitedResultsStream + localResultsStream) .filter { it.startsWith("-version = ") || it.startsWith("+version = ") } .isNotEmpty() } }
apache-2.0
6963e577dc232049febd559543865a48
30.5
115
0.637188
4.484746
false
false
false
false
DanielGrech/anko
dsl/static/src/OtherWidgets.kt
3
4221
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.anko import android.view.View import android.view.ViewManager import android.widget.LinearLayout import android.widget.ImageView import android.widget.TextView import android.content.Context import android.app.Fragment import android.app.Activity import android.content.BroadcastReceiver import android.graphics.drawable.Drawable import android.widget.EditText import android.widget.RelativeLayout import android.text.* import android.util.TypedValue import org.jetbrains.anko.custom.* import org.jetbrains.anko.internals.noBinding @suppress("NOTHING_TO_INLINE") public inline fun ViewManager.verticalLayout(): LinearLayout = verticalLayout({}) public inline fun ViewManager.verticalLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _LinearLayout.() -> Unit): LinearLayout = addView<_LinearLayout> { ctx -> val view = _LinearLayout(ctx) view.setOrientation(LinearLayout.VERTICAL) view.init() view } @suppress("NOTHING_TO_INLINE") public inline fun Context.verticalLayout(): LinearLayout = verticalLayout({}) public inline fun Context.verticalLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _LinearLayout.() -> Unit): LinearLayout = addView { ctx -> val view = _LinearLayout(ctx) view.setOrientation(LinearLayout.VERTICAL) view.init() view } @suppress("NOTHING_TO_INLINE") public inline fun Activity.verticalLayout(): LinearLayout = verticalLayout({}) public inline fun Activity.verticalLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _LinearLayout.() -> Unit): LinearLayout = addView { ctx -> val view = _LinearLayout(ctx) view.setOrientation(LinearLayout.VERTICAL) view.init() view } @suppress("NOTHING_TO_INLINE") public inline fun Fragment.verticalLayout(): LinearLayout = verticalLayout({}) public inline fun Fragment.verticalLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _LinearLayout.() -> Unit): LinearLayout = addView { ctx -> val view = _LinearLayout(ctx) view.setOrientation(LinearLayout.VERTICAL) view.init() view } @suppress("NOTHING_TO_INLINE") public inline fun <T: View> ViewManager.include(layoutId: Int): T = include(layoutId, {}) public inline fun <T: View> ViewManager.include(layoutId: Int, inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: T.() -> Unit): T = addView<T> { ctx -> @suppress("UNCHECKED_CAST") val view = ctx.layoutInflater.inflate(layoutId, null) as T view.init() view } @suppress("NOTHING_TO_INLINE") public inline fun <T: View> Activity.include(layoutId: Int): T = include(layoutId, {}) public inline fun <T: View> Activity.include(layoutId: Int, inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: T.() -> Unit): T = addView { ctx -> @suppress("UNCHECKED_CAST") val view = ctx.layoutInflater.inflate(layoutId, null) as T view.init() view } @suppress("NOTHING_TO_INLINE") public inline fun <T: View> Fragment.include(layoutId: Int): T = include(layoutId, {}) public inline fun <T: View> Fragment.include(layoutId: Int, inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: T.() -> Unit): T = addView { ctx -> @suppress("UNCHECKED_CAST") val view = ctx.layoutInflater.inflate(layoutId, null) as T view.init() view } @suppress("NOTHING_TO_INLINE") public inline fun <T: View> Context.include(layoutId: Int): T = include(layoutId, {}) public inline fun <T: View> Context.include(layoutId: Int, inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: T.() -> Unit): T = addView { ctx -> @suppress("UNCHECKED_CAST") val view = ctx.layoutInflater.inflate(layoutId, null) as T view.init() view }
apache-2.0
28b4d8f44d585700f4e8e50bd27577e3
38.830189
170
0.741294
3.967105
false
false
false
false
mvysny/vaadin-on-kotlin
vok-example-crud/src/main/kotlin/example/crudflow/Bootstrap.kt
1
2028
package example.crudflow import com.vaadin.flow.component.page.AppShellConfigurator import com.vaadin.flow.server.PWA import com.zaxxer.hikari.HikariConfig import com.zaxxer.hikari.HikariDataSource import eu.vaadinonkotlin.VaadinOnKotlin import eu.vaadinonkotlin.vokdb.dataSource import org.flywaydb.core.Flyway import org.h2.Driver import org.slf4j.LoggerFactory import javax.servlet.ServletContextEvent import javax.servlet.ServletContextListener import javax.servlet.annotation.WebListener /** * Boots the app: * * * Makes sure that the database is up-to-date, by running migration scripts with Flyway. This will work even in cluster as Flyway * automatically obtains a cluster-wide database lock. * * Initializes the VaadinOnKotlin framework. * * Maps Vaadin to `/`, maps REST server to `/rest` * @author mvy */ @WebListener class Bootstrap: ServletContextListener { override fun contextInitialized(sce: ServletContextEvent?) { log.info("Starting up") val config = HikariConfig().apply { driverClassName = Driver::class.java.name // the org.h2.Driver class jdbcUrl = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1" username = "sa" password = "" } VaadinOnKotlin.dataSource = HikariDataSource(config) log.info("Initializing VaadinOnKotlin") VaadinOnKotlin.init() log.info("Running DB migrations") val flyway = Flyway.configure() .dataSource(VaadinOnKotlin.dataSource) .load() flyway.migrate() log.info("Initialization complete") } override fun contextDestroyed(sce: ServletContextEvent?) { log.info("Shutting down"); log.info("Destroying VaadinOnKotlin") VaadinOnKotlin.destroy() log.info("Shutdown complete") } companion object { private val log = LoggerFactory.getLogger(Bootstrap::class.java) } } @PWA(name = "Project Base for Vaadin", shortName = "Project Base") class AppShell: AppShellConfigurator
mit
fdb2c6ddae672840742966a093a8c270
33.372881
131
0.705128
4.198758
false
true
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/liftOut/ifToAssignment/cascadeIf.kt
4
412
// WITH_RUNTIME fun test(x: Any) { var res: String <caret>if (x is String) when { x.length > 3 -> res = "long string" else -> res = "short string" } else if (x is Int) when { x > 999 || x < -99 -> res = "long int" else -> res = "short int" } else if (x is Long) TODO() else res = "I don't know" }
apache-2.0
bf91c3e27fc40cdc9c2a9952c6a13c5f
21.944444
50
0.42233
3.521368
false
true
false
false
siosio/intellij-community
platform/lang-impl/src/com/intellij/ide/actions/searcheverywhere/ml/SearchEverywhereMlSearchState.kt
1
3227
// 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 import com.intellij.ide.actions.searcheverywhere.SearchEverywhereContributor import com.intellij.ide.actions.searcheverywhere.SearchRestartReason import com.intellij.ide.actions.searcheverywhere.ml.features.SearchEverywhereActionFeaturesProvider import com.intellij.ide.actions.searcheverywhere.ml.features.SearchEverywhereElementFeaturesProvider import com.intellij.ide.actions.searcheverywhere.ml.model.SearchEverywhereActionsRankingModel import com.intellij.ide.actions.searcheverywhere.ml.model.SearchEverywhereActionsRankingModelProvider import com.intellij.ide.util.gotoByName.GotoActionModel import com.intellij.internal.statistic.local.ActionsGlobalSummaryManager import com.intellij.internal.statistic.local.ActionsLocalSummary import com.intellij.openapi.application.ApplicationManager internal class SearchEverywhereMlSearchState( val sessionStartTime: Long, val searchStartTime: Long, val searchIndex: Int, val searchStartReason: SearchRestartReason, val tabId: String, val keysTyped: Int, val backspacesTyped: Int, val queryLength: Int ) { private val cachedElementsInfo: MutableMap<Int, SearchEverywhereMLItemInfo> = hashMapOf() private val cachedMLWeight: MutableMap<Int, Double> = hashMapOf() private val model: SearchEverywhereActionsRankingModel = SearchEverywhereActionsRankingModel(SearchEverywhereActionsRankingModelProvider()) private val featuresProvider: SearchEverywhereElementFeaturesProvider = SearchEverywhereActionFeaturesProvider() @Synchronized fun getElementFeatures(elementId: Int, element: GotoActionModel.MatchedValue, contributor: SearchEverywhereContributor<*>, queryLength: Int): SearchEverywhereMLItemInfo { return cachedElementsInfo.computeIfAbsent(elementId) { val localSummary = ApplicationManager.getApplication().getService(ActionsLocalSummary::class.java) val globalSummary = ApplicationManager.getApplication().getService(ActionsGlobalSummaryManager::class.java) val features = featuresProvider.getElementFeatures(element, sessionStartTime, queryLength, localSummary, globalSummary) return@computeIfAbsent SearchEverywhereMLItemInfo(elementId, contributor.searchProviderId, features) } } @Synchronized fun getMLWeightIfDefined(elementId: Int): Double? { return cachedMLWeight[elementId] } @Synchronized fun getMLWeight(elementId: Int, element: GotoActionModel.MatchedValue, contributor: SearchEverywhereContributor<*>, context: SearchEverywhereMLContextInfo): Double { return cachedMLWeight.computeIfAbsent(elementId) { val features = hashMapOf<String, Any>() features.putAll(context.features) features.putAll(getElementFeatures(elementId, element, contributor, queryLength).features) model.predict(features) } } } internal data class SearchEverywhereMLItemInfo(val id: Int, val contributorId: String, val features: Map<String, Any>)
apache-2.0
e60c94be7a78ea753b05cdc3f26b04fd
54.655172
158
0.795166
5.2557
false
false
false
false
jovr/imgui
core/src/main/kotlin/imgui/demo/showExampleApp/Documents.kt
2
9752
package imgui.demo.showExampleApp import glm_.vec2.Vec2 import glm_.vec4.Vec4 import imgui.* import imgui.ImGui.begin import imgui.ImGui.beginMenu import imgui.ImGui.beginMenuBar import imgui.ImGui.beginPopupContextItem import imgui.ImGui.beginPopupModal import imgui.ImGui.beginTabBar import imgui.ImGui.beginTabItem import imgui.ImGui.button import imgui.ImGui.checkbox import imgui.ImGui.closeCurrentPopup import imgui.ImGui.colorEdit3 import imgui.ImGui.end import imgui.ImGui.endMenu import imgui.ImGui.endMenuBar import imgui.ImGui.endPopup import imgui.ImGui.endTabBar import imgui.ImGui.endTabItem import imgui.ImGui.isPopupOpen import imgui.ImGui.listBoxFooter import imgui.ImGui.listBoxHeader import imgui.ImGui.menuItem import imgui.ImGui.openPopup import imgui.ImGui.popID import imgui.ImGui.popStyleColor import imgui.ImGui.pushID import imgui.ImGui.pushItemWidth import imgui.ImGui.pushStyleColor import imgui.ImGui.sameLine import imgui.ImGui.separator import imgui.ImGui.setTabItemClosed import imgui.ImGui.text import imgui.ImGui.textWrapped import kotlin.reflect.KMutableProperty0 //----------------------------------------------------------------------------- // [SECTION] Example App: Documents Handling / ShowExampleAppDocuments() //----------------------------------------------------------------------------- // Simplified structure to mimic a Document model class MyDocument( /** Document title */ val name: String, /** Set when open (we keep an array of all available documents to simplify demo code!) */ var open: Boolean = true, /** An arbitrary variable associated to the document */ val color: Vec4 = Vec4(1f) ) { /** Copy of Open from last update. */ var openPrev = open /** Set when the document has been modified */ var dirty = false /** Set when the document */ var wantClose = false fun doOpen() { open = true } fun doQueueClose() { wantClose = true } fun doForceClose() { open = false dirty = false } fun doSave() { dirty = false } // Display placeholder contents for the Document fun displayContents() { pushID(this) text("Document \"$name\"") pushStyleColor(Col.Text, color) textWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.") popStyleColor() if (button("Modify", Vec2(100, 0))) dirty = true sameLine() if (button("Save", Vec2(100, 0))) doSave() colorEdit3("color", color) // Useful to test drag and drop and hold-dragged-to-open-tab behavior. popID() } // Display context menu for the Document fun displayContextMenu() { if (!beginPopupContextItem()) return if (menuItem("Save $name", "CTRL+S", false, open)) doSave() if (menuItem("Close", "CTRL+W", false, open)) doQueueClose() endPopup() } } object Documents { val documents = arrayOf( MyDocument("Lettuce", true, Vec4(0.4f, 0.8f, 0.4f, 1.0f)), MyDocument("Eggplant", true, Vec4(0.8f, 0.5f, 1.0f, 1.0f)), MyDocument("Carrot", true, Vec4(1.0f, 0.8f, 0.5f, 1.0f)), MyDocument("Tomato", false, Vec4(1.0f, 0.3f, 0.4f, 1.0f)), MyDocument("A Rather Long Title", false), MyDocument("Some Document", false) ) // [Optional] Notify the system of Tabs/Windows closure that happened outside the regular tab interface. // If a tab has been closed programmatically (aka closed from another source such as the Checkbox() in the demo, // as opposed to clicking on the regular tab closing button) and stops being submitted, it will take a frame for // the tab bar to notice its absence. During this frame there will be a gap in the tab bar, and if the tab that has // disappeared was the selected one, the tab bar will report no selected tab during the frame. This will effectively // give the impression of a flicker for one frame. // We call SetTabItemClosed() to manually notify the Tab Bar or Docking system of removed tabs to avoid this glitch. // Note that this completely optional, and only affect tab bars with the ImGuiTabBarFlags_Reorderable flag. fun notifyOfDocumentsClosedElsewhere() { for (doc in documents) { if (!doc.open && doc.openPrev) setTabItemClosed(doc.name) doc.openPrev = doc.open } } // Options var optReorderable = true var optFittingFlags: TabBarFlags = TabBarFlag.FittingPolicyDefault_.i val closeQueue = ArrayList<MyDocument>() operator fun invoke(pOpen: KMutableProperty0<Boolean>) { val windowContentsVisible = begin("Example: Documents", pOpen, WindowFlag.MenuBar.i) if (!windowContentsVisible) { end() return } // Menu if (beginMenuBar()) { if (beginMenu("File")) { val openCount = documents.count { it.open } if (beginMenu("Open", openCount < documents.size)) { for (doc in documents) { if (!doc.open) if (menuItem(doc.name)) doc.doOpen() } endMenu() } if (menuItem("Close All Documents", "", false, openCount > 0)) for (doc in documents) doc.doQueueClose() if (menuItem("Exit", "Alt+F4")) { } endMenu() } endMenuBar() } // [Debug] List documents with one checkbox for each for (docN in documents.indices) { val doc = documents[docN] if (docN > 0) sameLine() pushID(doc) if (checkbox(doc.name, doc::open)) if (!doc.open) doc.doForceClose() popID() } separator() // Submit Tab Bar and Tabs run { val tabBarFlags: TabBarFlags = optFittingFlags or if (optReorderable) TabBarFlag.Reorderable else TabBarFlag.None if (beginTabBar("##tabs", tabBarFlags)) { if (optReorderable) notifyOfDocumentsClosedElsewhere() // [DEBUG] Stress tests //if ((ImGui::GetFrameCount() % 30) == 0) docs[1].Open ^= 1; // [DEBUG] Automatically show/hide a tab. Test various interactions e.g. dragging with this on. //if (ImGui::GetIO().KeyCtrl) ImGui::SetTabItemSelected(docs[1].Name); // [DEBUG] Test SetTabItemSelected(), probably not very useful as-is anyway.. // Submit Tabs for (doc in documents) { if (!doc.open) continue val tabFlags: TabItemFlags = if (doc.dirty) TabItemFlag.UnsavedDocument.i else TabItemFlag.None.i val visible = beginTabItem(doc.name, doc::open, tabFlags) // Cancel attempt to close when unsaved add to save queue so we can display a popup. if (!doc.open && doc.dirty) { doc.open = true doc.doQueueClose() } doc.displayContextMenu() if (visible) { doc.displayContents() endTabItem() } } endTabBar() } } // Update closing queue if (closeQueue.isEmpty()) { // Close queue is locked once we started a popup for (doc in documents) if (doc.wantClose) { doc.wantClose = false closeQueue += doc } } // Display closing confirmation UI if (closeQueue.isNotEmpty()) { val closeQueueUnsavedDocuments = closeQueue.count { it.dirty } if (closeQueueUnsavedDocuments == 0) { // Close documents when all are unsaved closeQueue.forEach { it.doForceClose() } closeQueue.clear() } else { if (!isPopupOpen("Save?")) openPopup("Save?") if (beginPopupModal("Save?")) { text("Save change to the following items?") pushItemWidth(-1f) if (listBoxHeader("##", closeQueueUnsavedDocuments, 6)) { closeQueue.forEach { if (it.dirty) text(it.name) } listBoxFooter() } if (button("Yes", Vec2(80, 0))) { closeQueue.forEach { if (it.dirty) it.doSave() it.doForceClose() } closeQueue.clear() closeCurrentPopup() } sameLine() if (button("No", Vec2(80, 0))) { closeQueue.forEach { it.doForceClose() } closeQueue.clear() closeCurrentPopup() } sameLine() if (button("Cancel", Vec2(80, 0))) { closeQueue.clear() closeCurrentPopup() } endPopup() } } } end() } }
mit
008de5f7ab53b68167fb9c2aaecfe20e
34.209386
183
0.541017
4.632779
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/resolve/AbstractReferenceResolveTest.kt
1
7749
// 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.resolve import com.intellij.openapi.application.ApplicationManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiPolyVariantReference import com.intellij.psi.PsiReference import com.intellij.testFramework.UsefulTestCase import com.intellij.util.PathUtil import org.jetbrains.kotlin.idea.completion.test.configureWithExtraFile import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils import org.jetbrains.kotlin.test.util.renderAsGotoImplementation import org.jetbrains.kotlin.test.utils.IgnoreTests import org.junit.Assert import kotlin.test.assertTrue abstract class AbstractReferenceResolveTest : KotlinLightCodeInsightFixtureTestCase() { class ExpectedResolveData(private val shouldBeUnresolved: Boolean?, val referenceString: String) { fun shouldBeUnresolved(): Boolean { return shouldBeUnresolved!! } } protected open fun doTest(path: String) { assert(path.endsWith(".kt")) { path } myFixture.configureWithExtraFile(path, ".Data") val controlDirective = if (isFirPlugin()) { IgnoreTests.DIRECTIVES.IGNORE_FIR } else { IgnoreTests.DIRECTIVES.IGNORE_FE10 } IgnoreTests.runTestIfNotDisabledByFileDirective(testDataFile().toPath(), controlDirective) { performChecks() } } protected fun performChecks() { if (InTextDirectivesUtils.isDirectiveDefined(myFixture.file.text, MULTIRESOLVE)) { doMultiResolveTest() } else { doSingleResolveTest() } } private fun doSingleResolveTest() { forEachCaret { index, offset -> val expectedResolveData = readResolveData(myFixture.file.text, index, refMarkerText) val psiReference = wrapReference(myFixture.file.findReferenceAt(offset)) checkReferenceResolve(expectedResolveData, offset, psiReference) { checkResolvedTo(it) } } } open fun checkResolvedTo(element: PsiElement) { // do nothing } open fun wrapReference(reference: PsiReference?): PsiReference? = reference open fun wrapReference(reference: PsiPolyVariantReference): PsiPolyVariantReference = reference private fun doMultiResolveTest() { forEachCaret { index, offset -> val expectedReferences = getExpectedReferences(myFixture.file.text, index, refMarkerText) val psiReference = myFixture.file.findReferenceAt(offset) assertTrue(psiReference is PsiPolyVariantReference) psiReference as PsiPolyVariantReference val results = executeOnPooledThreadInReadAction { wrapReference(psiReference).multiResolve(true) } val actualResolvedTo = mutableListOf<String>() for (result in results) { actualResolvedTo.add(result.element!!.renderAsGotoImplementation()) } UsefulTestCase.assertOrderedEquals("Not matching for reference #$index", actualResolvedTo.sorted(), expectedReferences.sorted()) } } private fun forEachCaret(action: (index: Int, offset: Int) -> Unit) { val offsets = myFixture.editor.caretModel.allCarets.map { it.offset } val singleCaret = offsets.size == 1 for ((index, offset) in offsets.withIndex()) { action(if (singleCaret) -1 else index + 1, offset) } } override fun getDefaultProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_NO_SOURCES open val refMarkerText: String = "REF" companion object { const val MULTIRESOLVE: String = "MULTIRESOLVE" const val REF_EMPTY: String = "REF_EMPTY" fun readResolveData(fileText: String, index: Int, refMarkerText: String = "REF"): ExpectedResolveData { val shouldBeUnresolved = InTextDirectivesUtils.isDirectiveDefined(fileText, REF_EMPTY) val refs = getExpectedReferences(fileText, index, refMarkerText) val referenceToString: String if (shouldBeUnresolved) { Assert.assertTrue("REF: directives will be ignored for $REF_EMPTY test: $refs", refs.isEmpty()) referenceToString = "<empty>" } else { assertTrue( refs.size == 1, "Must be a single ref: $refs.\nUse $MULTIRESOLVE if you need multiple refs\nUse $REF_EMPTY for an unresolved reference" ) referenceToString = refs[0] Assert.assertNotNull("Test data wasn't found, use \"// REF: \" directive", referenceToString) } return ExpectedResolveData(shouldBeUnresolved, referenceToString) } // purpose of this helper is to deal with the case when navigation element is a file // see ReferenceResolveInJavaTestGenerated.testPackageFacade() private fun getExpectedReferences(text: String, index: Int, refMarkerText: String): List<String> { val prefix = if (index > 0) "// $refMarkerText$index:" else "// $refMarkerText:" return InTextDirectivesUtils.findLinesWithPrefixesRemoved(text, prefix) } fun checkReferenceResolve( expectedResolveData: ExpectedResolveData, offset: Int, psiReference: PsiReference?, checkResolvedTo: (PsiElement) -> Unit = {} ) { val expectedString = expectedResolveData.referenceString if (psiReference != null) { val resolvedTo = executeOnPooledThreadInReadAction { psiReference.resolve() } if (resolvedTo != null) { checkResolvedTo(resolvedTo) val resolvedToElementStr = replacePlaceholders(resolvedTo.renderAsGotoImplementation()) assertEquals( "Found reference to '$resolvedToElementStr', but '$expectedString' was expected", expectedString, resolvedToElementStr ) } else { if (!expectedResolveData.shouldBeUnresolved()) { assertNull( "Element $psiReference (${psiReference.element .text}) wasn't resolved to anything, but $expectedString was expected", expectedString ) } } } else { assertNull("No reference found at offset: $offset, but one resolved to $expectedString was expected", expectedString) } } private fun replacePlaceholders(actualString: String): String { val replaced = PathUtil.toSystemIndependentName(actualString) .replace(IDEA_TEST_DATA_DIR.path, "/<test dir>") .replace("//", "/") // additional slashes to fix discrepancy between windows and unix if ("!/" in replaced) { return replaced.replace(replaced.substringBefore("!/"), "<jar>") } return replaced } } } private fun <R> executeOnPooledThreadInReadAction(action: () -> R): R = ApplicationManager.getApplication().executeOnPooledThread<R> { runReadAction(action) }.get()
apache-2.0
202da41352690628a1ab69bd4c20a85e
43.791908
158
0.651826
5.39624
false
true
false
false
scenerygraphics/scenery
src/test/kotlin/graphics/scenery/tests/examples/basic/TexturedCubeExample.kt
1
1751
package graphics.scenery.tests.examples.basic import org.joml.Vector3f import graphics.scenery.* import graphics.scenery.backends.Renderer import graphics.scenery.textures.Texture import graphics.scenery.utils.Image import kotlin.concurrent.thread /** * <Description> * * @author Ulrik Günther <[email protected]> */ class TexturedCubeExample : SceneryBase("TexturedCubeExample") { override fun init() { renderer = hub.add(SceneryElement.Renderer, Renderer.createRenderer(hub, applicationName, scene, windowWidth, windowHeight)) val box = Box(Vector3f(1.0f, 1.0f, 1.0f)) box.name = "le box du win" box.material { textures["diffuse"] = Texture.fromImage(Image.fromResource("textures/helix.png", TexturedCubeExample::class.java)) metallic = 0.3f roughness = 0.9f } scene.addChild(box) val light = PointLight(radius = 15.0f) light.spatial().position = Vector3f(0.0f, 0.0f, 2.0f) light.intensity = 5.0f light.emissionColor = Vector3f(1.0f, 1.0f, 1.0f) scene.addChild(light) val cam: Camera = DetachedHeadCamera() with(cam) { spatial { position = Vector3f(0.0f, 0.0f, 5.0f) } perspectiveCamera(50.0f, 512, 512) scene.addChild(this) } thread { while (running) { box.spatial { rotation.rotateY(0.01f) needsUpdate = true } Thread.sleep(20) } } } companion object { @JvmStatic fun main(args: Array<String>) { TexturedCubeExample().main() } } }
lgpl-3.0
ac719aca5d4dba14ac00be0a270d643c
26.34375
126
0.574286
3.923767
false
false
false
false
androidx/androidx
camera/integration-tests/timingtestapp/src/main/java/androidx/camera/integration/antelope/SingleTestSettingsFragment.kt
3
3755
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.integration.antelope import android.content.SharedPreferences import android.os.Bundle import androidx.preference.ListPreference import androidx.preference.PreferenceFragmentCompat /** * Fragment that shows the settings for the "Single test" option */ class SingleTestSettingsFragment( internal val cameraNames: Array<String>, internal val cameraIds: Array<String> ) : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.single_test_settings, rootKey) val cameraPref = preferenceManager.findPreference<ListPreference>( getString(R.string.settings_single_test_camera_key) ) cameraPref?.entries = cameraNames cameraPref?.entryValues = cameraIds if (cameraIds.isNotEmpty()) cameraPref?.setDefaultValue(cameraIds[0]) if (null == cameraPref?.value) cameraPref?.value = cameraIds[0] // En/disable needed controls toggleNumTests() togglePreviewBuffer() } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) { if (key.equals(getString(R.string.settings_single_test_type_key))) { toggleNumTests() togglePreviewBuffer() } } override fun onResume() { super.onResume() preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(this) } override fun onPause() { super.onPause() preferenceManager.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) } /** Some tests do not allow for multiple repetitions, If one of these selected, * disable the number of tests control. */ fun toggleNumTests() { val typePref = preferenceManager.findPreference<ListPreference>( getString(R.string.settings_single_test_type_key) ) val numberPref = preferenceManager .findPreference<ListPreference>(getString(R.string.settings_numtests_key)) when (typePref?.value) { "INIT", "PREVIEW", "SWITCH_CAMERA", "PHOTO" -> { numberPref?.isEnabled = false } else -> { numberPref?.isEnabled = true } } } /** Some tests do not require the preview stream to run, If one of these selected, * disable the preview buffer control. */ fun togglePreviewBuffer() { val typePref = preferenceManager .findPreference<ListPreference>(getString(R.string.settings_single_test_type_key)) val previewPref = preferenceManager .findPreference<ListPreference>(getString(R.string.settings_previewbuffer_key)) when (typePref?.value) { "INIT" -> { previewPref?.isEnabled = false } else -> { previewPref?.isEnabled = true } } } }
apache-2.0
6c15c8a3c5c4fa96341b9e4a79a2ca6b
33.777778
98
0.65486
5.067476
false
true
false
false
androidx/androidx
work/work-runtime/src/androidTest/java/androidx/work/worker/TestForegroundWorker.kt
3
1808
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.work.worker import android.content.Context import androidx.core.app.NotificationCompat import androidx.work.ForegroundInfo import androidx.work.Worker import androidx.work.WorkerParameters public open class TestForegroundWorker( private val context: Context, private val parameters: WorkerParameters ) : Worker(context, parameters) { override fun doWork(): Result { return Result.success() } override fun getForegroundInfo(): ForegroundInfo { return getNotification() } private fun getNotification(): ForegroundInfo { val notification = NotificationCompat.Builder(context, ChannelId) .setOngoing(true) .setTicker(Ticker) .setContentText(Content) .build() return ForegroundInfo(NotificationId, notification) } internal companion object { // Notification Id private const val NotificationId = 42 // Channel id private const val ChannelId = "Channel" // Ticker private const val Ticker = "StopAwareForegroundWorker" // Content private const val Content = "Test Notification" } }
apache-2.0
867fb0adaab38505ee619f0c95b778d7
28.16129
75
0.697456
4.926431
false
false
false
false
androidx/androidx
compose/foundation/foundation/samples/src/main/java/androidx/compose/foundation/samples/ImageSamples.kt
3
2877
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.samples import androidx.annotation.Sampled import androidx.compose.foundation.Image import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.Paint import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.painter.BitmapPainter import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp @Sampled @Composable fun ImageSample() { val ImageBitmap = createTestImage() // Lays out and draws an image sized to the dimensions of the ImageBitmap Image(bitmap = ImageBitmap, contentDescription = "Localized description") } @Sampled @Composable fun BitmapPainterSubsectionSample() { val ImageBitmap = createTestImage() // Lays out and draws an image sized to the rectangular subsection of the ImageBitmap Image( painter = BitmapPainter( ImageBitmap, IntOffset(10, 12), IntSize(50, 60) ), contentDescription = "Localized description" ) } @Sampled @Composable fun BitmapPainterSample() { val customPainter = remember { object : Painter() { override val intrinsicSize: Size get() = Size(100.0f, 100.0f) override fun DrawScope.onDraw() { drawRect(color = Color.Cyan) } } } Image( painter = customPainter, contentDescription = "Localized description", modifier = Modifier.size(100.dp, 100.dp) ) } /** * Helper method to create an ImageBitmap with some content in it */ private fun createTestImage(): ImageBitmap { val ImageBitmap = ImageBitmap(100, 100) Canvas(ImageBitmap).drawCircle( Offset(50.0f, 50.0f), 50.0f, Paint().apply { this.color = Color.Cyan } ) return ImageBitmap }
apache-2.0
fd8da20c24bc6e6df49e11fa8211c5d1
29.946237
89
0.719152
4.31982
false
false
false
false
siosio/intellij-community
plugins/kotlin/jps/jps-plugin/tests/testData/incremental/lookupTracker/jsKlib/localDeclarations/locals.kt
5
1622
package local.declarations import bar.* /*p:local.declarations*/fun f(p: /*p:bar p:kotlin p:kotlin.annotation p:kotlin.collections p:kotlin.comparisons p:kotlin.io p:kotlin.js p:kotlin.ranges p:kotlin.sequences p:kotlin.text p:local.declarations*/Any) /*p:kotlin(Int)*/{ /*p:kotlin(Any) p:kotlin(String)*/p./*c:kotlin.Any*/toString() val a = /*p:kotlin(Int)*/1 val b = /*p:kotlin(Int)*/a fun localFun() = /*p:kotlin(Int)*/b fun /*p:bar p:kotlin p:kotlin.annotation p:kotlin.collections p:kotlin.comparisons p:kotlin.io p:kotlin.js p:kotlin.ranges p:kotlin.sequences p:kotlin.text p:local.declarations*/Int.localExtFun() = /*p:kotlin(Int)*/localFun() abstract class LocalI { abstract var a: /*p:bar p:kotlin p:kotlin.annotation p:kotlin.collections p:kotlin.comparisons p:kotlin.io p:kotlin.js p:kotlin.ranges p:kotlin.sequences p:kotlin.text p:local.declarations*/Int abstract fun foo() } class LocalC : LocalI() { override var a = /*p:kotlin(Int)*/1 override fun foo() {} var b = /*p:kotlin(String)*/"bbb" fun bar() = /*p:kotlin(Int)*/b } val o = object { val a = /*p:kotlin(String)*/"aaa" fun foo(): LocalI = /*p:kotlin(Nothing)*/null as LocalI } /*p:kotlin(Int)*/localFun() /*p:kotlin(Int)*/1./*c:kotlin.Int c:kotlin.Number*/localExtFun() val c = LocalC() /*p:kotlin(Int)*/c.a /*p:kotlin(String)*/c.b c.foo() /*p:kotlin(Int)*/c.bar() val i: LocalI = c /*p:kotlin(Int)*/i.a i.foo() /*p:kotlin(String)*/o.a val ii = o.foo() /*p:kotlin(Int)*/ii.a }
apache-2.0
4ad802ae6eed1e4921b58abe7d9e959e
32.102041
230
0.620838
3.089524
false
false
false
false
prttstft/MaterialMensa
app/src/main/java/de/prttstft/materialmensa/model/Meal.kt
1
2550
@file:JvmName("Meal") package de.prttstft.materialmensa.model import com.google.gson.annotations.SerializedName import java.util.* import kotlin.comparisons.compareValuesBy @SuppressWarnings("unused") class Meal : Comparable<Meal> { @SerializedName("allergens") val allergens: List<String> = ArrayList() @SerializedName("badges") val badges: List<String> = ArrayList() @SerializedName("category") val category: String = "" @SerializedName("category_de") val categoryDe: String = "" @SerializedName("category_en") val categoryEn: String = "" @SerializedName("date") val date: String = "" @SerializedName("description_de") val descriptionDe: String = "" @SerializedName("description_en") val descriptionEn: String = "" @SerializedName("image") val image: String = "" @SerializedName("name_de") var nameDe: String = "" @SerializedName("name_en") var nameEn: String = "" @SerializedName("order_info") val orderInfo: Int = 0 @SerializedName("priceGuests") val priceGuests: Float = 0.toFloat() @SerializedName("priceStudents") val priceStudents: Float = 0.toFloat() @SerializedName("priceWorkers") val priceWorkers: Float = 0.toFloat() @SerializedName("pricetype") val pricetype: String = "" @SerializedName("restaurant") val restaurant: String = "" @SerializedName("subcategory") val subcategory: String = "" @SerializedName("subcategory_en") val subcategoryEn: String = "" @SerializedName("thumbnail") val thumbnail: String = "" var customDescription: String = "" var downvotes: HashMap<String, Any> = HashMap() var isDownvoted: Boolean = false var isFiltered: Boolean = false var isUpvoted: Boolean = false var orderNumber: Int = 0 var priceString: String = "" var score: Int = 0 var upvotes: HashMap<String, Any> = HashMap() var hasScores: Boolean = false val badge: String get() { if (badges.size > 0) { return badges[0] } else { return "" } } override fun compareTo(other: Meal): Int { return compareValuesBy(this, other, { it.customSort() }) } private fun customSort(): Int { if (isUpvoted) { return -1000000000 - score } if (isDownvoted) { return +1000000000 - score } if (score > 0) { return score * 10000 * (-1) } if (score < 0) { return score * 10000 * (-1) } return orderNumber } }
mit
b23071e8b038d33732fc15960473f752
33.013333
75
0.625882
4.228856
false
false
false
false
GunoH/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/impl.kt
7
3624
// 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.plugins.groovy.annotator import com.intellij.codeInsight.intention.QuickFixFactory import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixProvider import com.intellij.codeInspection.ProblemHighlightType import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.HighlightSeverity import com.intellij.psi.PsiClass import com.intellij.psi.util.PsiUtil.isInnerClass import com.intellij.psi.util.parentOfType import org.jetbrains.plugins.groovy.GroovyBundle.message import org.jetbrains.plugins.groovy.annotator.GrReferenceHighlighterFactory.shouldHighlight import org.jetbrains.plugins.groovy.codeInspection.untypedUnresolvedAccess.generateAddImportActions import org.jetbrains.plugins.groovy.codeInspection.untypedUnresolvedAccess.generateCreateClassActions import org.jetbrains.plugins.groovy.lang.groovydoc.psi.api.GroovyDocPsiElement import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging.GrPackageDefinition import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil.hasArguments import org.jetbrains.plugins.groovy.lang.psi.util.GrStaticChecker.isInStaticContext import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.hasEnclosingInstanceInScope fun checkUnresolvedCodeReference(ref: GrCodeReferenceElement, annotationHolder: AnnotationHolder) { if (!shouldHighlight(annotationHolder.currentAnnotationSession.file)) return if (ref.parentOfType<GroovyDocPsiElement>() != null) return if (ref.parent is GrPackageDefinition) return val nameElement = ref.referenceNameElement ?: return val referenceName = ref.referenceName ?: return if (isResolvedStaticImport(ref)) return if (ref.resolve() != null) return val builder = annotationHolder.newAnnotation(HighlightSeverity.ERROR, message("cannot.resolve", referenceName)).range(nameElement) .highlightType(ProblemHighlightType.LIKE_UNKNOWN_SYMBOL) generateCreateClassActions(ref).forEach { builder.withFix(it) } generateAddImportActions(ref).forEach { builder.withFix(it) } val fixRegistrar = AnnotationFixRegistrar(builder) UnresolvedReferenceQuickFixProvider.registerReferenceFixes(ref, fixRegistrar) QuickFixFactory.getInstance().registerOrderEntryFixes(fixRegistrar, ref) builder.create() } private fun isResolvedStaticImport(refElement: GrCodeReferenceElement): Boolean { val parent = refElement.parent return parent is GrImportStatement && parent.isStatic && refElement.multiResolve(false).isNotEmpty() } fun checkInnerClassReferenceFromInstanceContext(ref: GrCodeReferenceElement, holder: AnnotationHolder) { val nameElement = ref.referenceNameElement ?: return val parent = ref.parent if (parent !is GrNewExpression || hasArguments(parent)) return if (!isInStaticContext(ref)) return val resolved = ref.resolve() as? PsiClass ?: return if (!isInnerClass(resolved)) return val qname = resolved.qualifiedName ?: return val outerClass = resolved.containingClass ?: return if (hasEnclosingInstanceInScope(outerClass, parent, true)) return holder.newAnnotation(HighlightSeverity.ERROR, message("cannot.reference.non.static", qname)).range(nameElement).create() } internal val illegalJvmNameSymbols: Regex = "[.;\\[/<>]".toRegex()
apache-2.0
73cc139cd7a1dc3cbbf2a0dfc3a35aa7
48.643836
132
0.824503
4.622449
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/editor/quickDoc/ExtensionReceiverEnd.kt
9
611
interface Foo fun foo(a: Any) {} fun Foo.bar() { foo(this<caret>) } //INFO: <div class='definition'><pre><span style="color:#000080;font-weight:bold;">public</span> <span style="color:#000080;font-weight:bold;">fun</span> <span style="color:#000000;"><a href="psi_element://Foo">Foo</a></span><span style="">.</span><span style="color:#000000;">bar</span>()<span style="">: </span><span style="color:#000000;">Unit</span></pre></div></pre></div><table class='sections'><p></table><div class='bottom'><icon src="/org/jetbrains/kotlin/idea/icons/kotlin_file.svg"/>&nbsp;ExtensionReceiverEnd.kt<br/></div>
apache-2.0
9dc9db995dc1e7c753c9a994e5cc12c4
60.1
534
0.667758
3.25
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionManagerSettings.kt
5
7652
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("unused", "ReplacePutWithAssignment") package com.intellij.codeInsight.intention.impl.config import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.IntentionActionBean import com.intellij.ide.ui.TopHitCache import com.intellij.ide.ui.search.SearchableOptionContributor import com.intellij.ide.ui.search.SearchableOptionProcessor import com.intellij.openapi.components.* import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.extensions.ExtensionPointListener import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.util.containers.Interner import org.jdom.Element import java.io.IOException import java.util.* import java.util.regex.Pattern private const val IGNORE_ACTION_TAG = "ignoreAction" private const val NAME_ATT = "name" @State(name = "IntentionManagerSettings", storages = [Storage("intentionSettings.xml")], category = SettingsCategory.CODE) class IntentionManagerSettings : PersistentStateComponent<Element> { companion object { @JvmStatic fun getInstance() = service<IntentionManagerSettings>() } private class MetaDataKey(categoryNames: Array<String>, familyName: String) : AbstractMap.SimpleImmutableEntry<String?, String?>(categoryNames.joinToString(separator = ":"), interner.intern(familyName)) { companion object { private val interner = Interner.createWeakInterner<String>() } } @Volatile private var ignoredActions = emptySet<String>() // guarded by this private val metadataMap: MutableMap<MetaDataKey, IntentionActionMetaData> // guarded by this private val extensionMapping: MutableMap<IntentionActionBean, MetaDataKey> init { val size = IntentionManagerImpl.EP_INTENTION_ACTIONS.point.size() metadataMap = LinkedHashMap(size) extensionMapping = HashMap(size) IntentionManagerImpl.EP_INTENTION_ACTIONS.forEachExtensionSafe { registerMetaDataForEp(it) } IntentionManagerImpl.EP_INTENTION_ACTIONS.addExtensionPointListener(object : ExtensionPointListener<IntentionActionBean?> { override fun extensionAdded(extension: IntentionActionBean, pluginDescriptor: PluginDescriptor) { // on each plugin load/unload SearchableOptionsRegistrarImpl drops the cache, so, it will be recomputed later on demand registerMetaDataForEp(extension) serviceIfCreated<TopHitCache>()?.invalidateCachedOptions(IntentionsOptionsTopHitProvider::class.java) } override fun extensionRemoved(extension: IntentionActionBean, pluginDescriptor: PluginDescriptor) { if (extension.categories == null) { return } unregisterMetaDataForEP(extension) serviceIfCreated<TopHitCache>()?.invalidateCachedOptions(IntentionsOptionsTopHitProvider::class.java) } }, null) } private fun registerMetaDataForEp(extension: IntentionActionBean) { val categories = extension.categories ?: return val instance = IntentionActionWrapper(extension) val descriptionDirectoryName = extension.getDescriptionDirectoryName() ?: instance.descriptionDirectoryName try { val metadata = IntentionActionMetaData(instance, extension.loaderForClass, categories, descriptionDirectoryName) val key = MetaDataKey(metadata.myCategory, metadata.family) synchronized(this) { metadataMap.put(key, metadata) extensionMapping.put(extension, key) } } catch (ignore: ExtensionNotApplicableException) { } } fun registerIntentionMetaData(intentionAction: IntentionAction, category: Array<String?>, descriptionDirectoryName: String) { val classLoader = if (intentionAction is IntentionActionWrapper) { intentionAction.implementationClassLoader } else { intentionAction.javaClass.classLoader } val metadata = IntentionActionMetaData(intentionAction, classLoader, category, descriptionDirectoryName) val key = MetaDataKey(metadata.myCategory, metadata.family) synchronized(this) { // not added as searchable option - this method is deprecated and intentionAction extension point must be used instead metadataMap.put(key, metadata) } } fun isShowLightBulb(action: IntentionAction) = !ignoredActions.contains(action.familyName) override fun loadState(element: Element) { val children = element.getChildren(IGNORE_ACTION_TAG) val ignoredActions = LinkedHashSet<String>(children.size) for (e in children) { ignoredActions.add(e.getAttributeValue(NAME_ATT)!!) } this.ignoredActions = ignoredActions } override fun getState(): Element { val element = Element("state") for (name in ignoredActions) { element.addContent(Element(IGNORE_ACTION_TAG).setAttribute(NAME_ATT, name)) } return element } @Synchronized fun getMetaData(): List<IntentionActionMetaData> = java.util.List.copyOf(metadataMap.values) fun isEnabled(metaData: IntentionActionMetaData) = !ignoredActions.contains(getFamilyName(metaData)) fun setEnabled(metaData: IntentionActionMetaData, enabled: Boolean) { ignoredActions = if (enabled) ignoredActions - getFamilyName(metaData) else ignoredActions + getFamilyName(metaData) } fun isEnabled(action: IntentionAction): Boolean { val familyName = try { getFamilyName(action) } catch (ignored: ExtensionNotApplicableException) { return false } return !ignoredActions.contains(familyName) } fun setEnabled(action: IntentionAction, enabled: Boolean) { ignoredActions = if (enabled) ignoredActions - getFamilyName(action) else ignoredActions + getFamilyName(action) } @Synchronized fun unregisterMetaData(intentionAction: IntentionAction) { for ((key, value) in metadataMap) { if (value.action === intentionAction) { metadataMap.remove(key) break } } } @Synchronized private fun unregisterMetaDataForEP(extension: IntentionActionBean) { extensionMapping.remove(extension)?.let { key -> metadataMap.remove(key) } } private class IntentionSearchableOptionContributor : SearchableOptionContributor() { companion object { private val HTML_PATTERN = Pattern.compile("<[^<>]*>") } override fun processOptions(processor: SearchableOptionProcessor) { for (metaData in getInstance().getMetaData()) { try { val descriptionText = HTML_PATTERN.matcher(metaData.description.text.lowercase(Locale.ENGLISH)).replaceAll(" ") val displayName = IntentionSettingsConfigurable.getDisplayNameText() val configurableId = IntentionSettingsConfigurable.HELP_ID val family = metaData.family processor.addOptions(descriptionText, family, family, configurableId, displayName, false) processor.addOptions(family, family, family, configurableId, displayName, true) } catch (e: IOException) { logger<IntentionManagerSettings>().error(e) } } } } } private fun getFamilyName(metaData: IntentionActionMetaData): String { val joiner = StringJoiner("/") for (category in metaData.myCategory) { joiner.add(category) } joiner.add(metaData.action.familyName) return joiner.toString() } private fun getFamilyName(action: IntentionAction): String { return if (action is IntentionActionWrapper) action.fullFamilyName else action.familyName }
apache-2.0
db8f159527dcfd1304fb38b9ff3be9a0
38.040816
130
0.743858
4.889457
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ide/plugins/marketplace/PluginChunkDataSource.kt
9
5641
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.plugins.marketplace import com.intellij.ide.IdeBundle import com.intellij.openapi.diagnostic.logger import com.intellij.util.io.HttpRequests import com.jetbrains.plugin.blockmap.core.BlockMap import com.jetbrains.plugin.blockmap.core.Chunk import java.io.BufferedInputStream import java.io.ByteArrayOutputStream import java.io.IOException import java.nio.charset.Charset private const val MAX_HTTP_HEADERS_LENGTH: Int = 19000 private const val MAX_RANGE_BYTES: Int = 10_000_000 private const val MAX_STRING_LENGTH: Int = 1024 private val LOG = logger<PluginChunkDataSource>() class PluginChunkDataSource( oldBlockMap: BlockMap, newBlockMap: BlockMap, private val newPluginUrl: String ) : Iterator<ByteArray> { private val oldSet = oldBlockMap.chunks.toSet() private val chunks = newBlockMap.chunks.filter { chunk -> !oldSet.contains(chunk) } private var pos = 0 private var chunkSequences = ArrayList<MutableList<Chunk>>() private var curChunkData = getRange(nextRange()) private var pointer: Int = 0 override fun hasNext() = curChunkData.size != 0 override fun next(): ByteArray { return if (curChunkData.size != 0) { if (pointer < curChunkData.size) { curChunkData[pointer++] } else { curChunkData = getRange(nextRange()) pointer = 0 next() } } else throw NoSuchElementException() } private fun nextRange(): String { val range = StringBuilder() chunkSequences.clear() var bytes = 0 while (pos < chunks.size && range.length < MAX_HTTP_HEADERS_LENGTH && bytes < MAX_RANGE_BYTES) { val chunkSequence = nextChunkSequence(bytes) chunkSequences.add(chunkSequence) bytes += chunkSequence.last().offset + chunkSequence.last().length - chunkSequence[0].offset range.append("${chunkSequence[0].offset}-${chunkSequence.last().offset + chunkSequence.last().length - 1},") } return range.removeSuffix(",").toString() } private fun nextChunkSequence(bytes: Int): MutableList<Chunk> { val result = ArrayList<Chunk>() result.add(chunks[pos]) pos++ var sum = result[0].length while (pos < chunks.size - 1 && chunks[pos].offset == chunks[pos - 1].offset + chunks[pos - 1].length && sum + bytes < MAX_RANGE_BYTES) { result.add(chunks[pos]) sum += chunks[pos].length pos++ } return result } private fun getRange(range: String): MutableList<ByteArray> { val result = ArrayList<ByteArray>() if (range.isEmpty()) { LOG.warn("Empty range: request '$newPluginUrl' range '$range'") } else { HttpRequests .requestWithRange(newPluginUrl, range) .productNameAsUserAgent() .setHeadersViaTuner() .connect { request -> val boundary = request.connection.contentType.removePrefix("multipart/byteranges; boundary=") request.inputStream.buffered().use { input -> when { chunkSequences.size > 1 -> { for (sequence in chunkSequences) { parseHttpMultirangeHeaders(input, boundary) parseHttpRangeBody(input, sequence, result) } } chunkSequences.size == 1 -> parseHttpRangeBody(input, chunkSequences[0], result) else -> { LOG.warn("Zero chunks: request '$newPluginUrl' range '$range'") } } } } } return result } private fun parseHttpMultirangeHeaders(input: BufferedInputStream, boundary: String) { val openingEmptyLine = nextLine(input) if (openingEmptyLine.trim().isNotEmpty()) { throw IOException(IdeBundle.message("http.multirange.response.doesnt.include.line.separator")) } val boundaryLine = nextLine(input) if (!boundaryLine.contains(boundary)) { throw IOException(IdeBundle.message("http.multirange.response.doesnt.contain.boundary", boundaryLine, boundary)) } val contentTypeLine = nextLine(input) if (!contentTypeLine.startsWith("Content-Type")) { throw IOException(IdeBundle.message("http.multirange.response.includes.incorrect.header", contentTypeLine, "Content-Type")) } val contentRangeLine = nextLine(input) if (!contentRangeLine.startsWith("Content-Range")) { throw IOException(IdeBundle.message("http.multirange.response.includes.incorrect.header", contentRangeLine, "Content-Range")) } val closingEmptyLine = nextLine(input) if (closingEmptyLine.trim().isNotEmpty()) { throw IOException(IdeBundle.message("http.multirange.response.doesnt.include.line.separator")) } } private fun parseHttpRangeBody( input: BufferedInputStream, sequence: MutableList<Chunk>, result: MutableList<ByteArray> ) { for (chunk in sequence) { val data = ByteArray(chunk.length) for (i in 0 until chunk.length) data[i] = input.read().toByte() result.add(data) } } private fun nextLine(input: BufferedInputStream): String { ByteArrayOutputStream().use { baos -> do { val byte = input.read() baos.write(byte) if (baos.size() >= MAX_STRING_LENGTH) { throw IOException(IdeBundle.message("wrong.http.range.response", String(baos.toByteArray(), Charset.defaultCharset()))) } } while (byte.toChar() != '\n') return String(baos.toByteArray(), Charset.defaultCharset()) } } }
apache-2.0
56ae785a974f1fbc1535df4eca121f07
34.708861
140
0.664421
4.234985
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedMainParameterInspection.kt
3
1673
// 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.inspections import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.quickfix.RemoveUnusedFunctionParameterFix import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.parameterVisitor import org.jetbrains.kotlin.resolve.BindingContext.UNUSED_MAIN_PARAMETER class UnusedMainParameterInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) = parameterVisitor(fun(parameter: KtParameter) { val function = parameter.ownerFunction as? KtNamedFunction ?: return if (function.name != "main") return val context = function.analyzeWithContent() if (context[UNUSED_MAIN_PARAMETER, parameter] == true) { holder.registerProblem( parameter, KotlinBundle.message("since.kotlin.1.3.main.parameter.is.not.necessary"), ProblemHighlightType.LIKE_UNUSED_SYMBOL, IntentionWrapper(RemoveUnusedFunctionParameterFix(parameter)) ) } }) }
apache-2.0
74a871b39ab64147463a1bcfcbcc8758
49.727273
158
0.74477
5.16358
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/hierarchy/calls/callees/kotlinAnonymousObject/main0.kt
13
583
class KA { val name = "A" fun foo(s: String): String = "A: $s" } fun packageFun(s: String): String = s val packageVal = "" fun client() { val obj = <caret>object { val bar = run { val localVal = packageFun("") KA().foo(KA().name) JA().foo(JA().name) packageFun(localVal) } fun bar() { KA().foo(KA().name) JA().foo(JA().name) } } fun localFun(s: String): String = packageFun(s) KA().foo(KA().name) JA().foo(JA().name) localFun(packageVal) }
apache-2.0
4cd64ee2243ec6212591c0fe61c7ef26
17.25
51
0.471698
3.256983
false
false
false
false
smmribeiro/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/diff/ShowCombinedDiffAction.kt
1
1493
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.actions.diff import com.intellij.diff.editor.DiffEditorTabFilesManager import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.VcsDataKeys import com.intellij.openapi.vcs.changes.Change class ShowCombinedDiffAction : DumbAwareAction() { override fun update(e: AnActionEvent) { val changes = e.getData(VcsDataKeys.CHANGES) val project = e.project e.presentation.isEnabledAndVisible = Registry.`is`("enable.combined.diff") && project != null && changes != null && changes.size > 1 } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val changes = e.getRequiredData(VcsDataKeys.CHANGES) showDiff(project, changes.toList()) } companion object { fun showDiff(project: Project, changes: List<Change>) { val producers = changes.mapNotNull { ChangeDiffRequestProducer.create(project, it) } val allInOneDiffFile = CombinedChangeDiffVirtualFile(CombinedChangeDiffRequestProducer(project, producers)) DiffEditorTabFilesManager.getInstance(project).showDiffFile(allInOneDiffFile, true) } } }
apache-2.0
c9f2a02862d670c70cdacccc965d6217
40.472222
158
0.753516
4.41716
false
false
false
false
DuckDeck/AndroidDemo
app/src/main/java/stan/androiddemo/project/petal/Model/FacetsInfo.kt
1
1584
package stan.androiddemo.project.petal.Model /** * Created by stanhu on 12/8/2017. */ class FacetsInfo{ private var missing: Int = 0 private var total: Int = 0 private var other: Int = 0 private var results: ResultsBean? = null class ResultsBean { private var pets: Int = 0 private var funny: Int = 0 private var travel_places: Int = 0 private var other: Int = 0 private var photography: Int = 0 private var design: Int = 0 private var illustration: Int = 0 private var apparel: Int = 0 private var web_app_icon: Int = 0 private var home: Int = 0 private var diy_crafts: Int = 0 private var desire: Int = 0 private var beauty: Int = 0 private var industrial_design: Int = 0 private var kids: Int = 0 private var people: Int = 0 private var anime: Int = 0 private var film_music_books: Int = 0 private var tips: Int = 0 private var quotes: Int = 0 private var food_drink: Int = 0 private var wedding_events: Int = 0 private var art: Int = 0 private var modeling_hair: Int = 0 private var games: Int = 0 private var men: Int = 0 private var architecture: Int = 0 private var data_presentation: Int = 0 private var education: Int = 0 private var fitness: Int = 0 private var geek: Int = 0 private var sports: Int = 0 private var digital: Int = 0 private var cars_motorcycles: Int = 0 } }
mit
95aa262540b67a5d3199c8b0ad9c6f00
32.020833
46
0.589646
4.071979
false
false
false
false
ThiagoGarciaAlves/intellij-community
plugins/git4idea/tests/git4idea/push/GitPushOperationMultiRepoTest.kt
2
5916
/* * Copyright 2000-2014 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 git4idea.push import com.intellij.dvcs.push.PushSpec import com.intellij.openapi.vcs.Executor.cd import com.intellij.util.containers.ContainerUtil import git4idea.commands.GitCommandResult import git4idea.repo.GitRepository import git4idea.test.* import git4idea.update.GitUpdateResult import java.io.File import java.util.* class GitPushOperationMultiRepoTest : GitPushOperationBaseTest() { private lateinit var community: GitRepository private lateinit var ultimate: GitRepository private lateinit var brultimate: File private lateinit var brommunity: File @Throws(Exception::class) override fun setUp() { super.setUp() val mainRepo = setupRepositories(projectPath, "parent", "bro") ultimate = mainRepo.projectRepo brultimate = mainRepo.bro val communityDir = File(projectPath, "community") assertTrue(communityDir.mkdir()) val enclosingRepo = setupRepositories(communityDir.path, "community_parent", "community_bro") community = enclosingRepo.projectRepo brommunity = enclosingRepo.bro cd(projectPath) refresh() updateRepositories() } fun `test try push from all roots even if one fails`() { // fail in the first repo git.onPush { if (it == ultimate) GitCommandResult(false, 128, false, listOf("Failed to push to origin"), listOf<String>()) else null } cd(ultimate) makeCommit("file.txt") cd(community) makeCommit("com.txt") val spec1 = makePushSpec(ultimate, "master", "origin/master") val spec2 = makePushSpec(community, "master", "origin/master") val map = ContainerUtil.newHashMap<GitRepository, PushSpec<GitPushSource, GitPushTarget>>() map.put(ultimate, spec1) map.put(community, spec2) val result = GitPushOperation(project, pushSupport, map, null, false, false).execute() val result1 = result.results[ultimate]!! val result2 = result.results[community]!! assertResult(GitPushRepoResult.Type.ERROR, -1, "master", "origin/master", null, result1) assertEquals("Error text is incorrect", "Failed to push to origin", result1.error) assertResult(GitPushRepoResult.Type.SUCCESS, 1, "master", "origin/master", null, result2) } fun `test update all roots on reject when needed even if only one in push spec`() { cd(brultimate) val broHash = makeCommit("bro.txt") git("push") cd(brommunity) val broCommunityHash = makeCommit("bro_com.txt") git("push") cd(ultimate) makeCommit("file.txt") val mainSpec = makePushSpec(ultimate, "master", "origin/master") agreeToUpdate(GitRejectedPushUpdateDialog.MERGE_EXIT_CODE) // auto-update-all-roots is selected by default val result = GitPushOperation(project, pushSupport, Collections.singletonMap<GitRepository, PushSpec<GitPushSource, GitPushTarget>>(ultimate, mainSpec), null, false, false).execute() val result1 = result.results[ultimate]!! val result2 = result.results[community] assertResult(GitPushRepoResult.Type.SUCCESS, 2, "master", "origin/master", GitUpdateResult.SUCCESS, result1) assertNull(result2) // this was not pushed => no result should be generated cd(community) val lastHash = last() assertEquals("Update in community didn't happen", broCommunityHash, lastHash) cd(ultimate) val lastCommitParents = git("log -1 --pretty=%P").split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() assertEquals("Merge didn't happen in main repository", 2, lastCommitParents.size) assertRemoteCommitMerged("Commit from bro repository didn't arrive", broHash) } // IDEA-169877 fun `test push rejected in one repo when branch is deleted in another, should finally succeed`() { listOf(brultimate, brommunity).forEach { cd(it) git("checkout -b feature") git("push -u origin feature") } listOf(ultimate, community).forEach { cd(it) git("pull") git("checkout -b feature origin/feature") } // commit in one repo to reject the push cd(brultimate) val broHash = tac("bro.txt") git("push") // remove branch in another repo cd(brommunity) git("push origin :feature") cd(ultimate) val commitToPush = tac("file.txt") listOf(ultimate, community).forEach { it.update() } agreeToUpdate(GitRejectedPushUpdateDialog.MERGE_EXIT_CODE) // auto-update-all-roots is selected by default // push only to 1 repo, otherwise the push would recreate the deleted branch, and the error won't reproduce val pushSpecs = mapOf(ultimate to makePushSpec(ultimate, "feature", "origin/feature")) val result = GitPushOperation(project, pushSupport, pushSpecs, null, false, false).execute() val result1 = result.results[ultimate]!! assertResult(GitPushRepoResult.Type.SUCCESS, 2, "feature", "origin/feature", GitUpdateResult.SUCCESS, result1) assertRemoteCommitMerged("Commit from bro repository didn't arrive", broHash) cd(brultimate) git("pull origin feature") assertEquals("Commit from ultimate repository wasn't pushed", commitToPush, git("log --no-walk HEAD^1 --pretty=%H")) } private fun assertRemoteCommitMerged(message: String, expectedHash: String) { assertEquals(message, expectedHash, git("log --no-walk HEAD^2 --pretty=%H")) } }
apache-2.0
04521c61af38e24250fb93bacdb7935f
36.443038
164
0.715517
4.195745
false
false
false
false
bhubie/Expander
app/src/main/kotlin/com/wanderfar/expander/DynamicValue/DynamicValueEditText.kt
1
4661
/* * Expander: Text Expansion Application * Copyright (C) 2016 Brett Huber * * 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.wanderfar.expander.DynamicValue import android.content.Context import android.support.v7.widget.AppCompatEditText import android.text.Editable import android.text.TextWatcher import android.util.AttributeSet import com.wanderfar.expander.R class DynamicValueEditText : AppCompatEditText { var displayDrawableForDynamicValue : Boolean = true var mIconSize: Int = 0 var mIconAlignment: Int = 0 var mIconTextSize: Int = 0 var mTextLengthBefore: Int = 0 lateinit var mCurrentSpanStarts: MutableList<Int> lateinit var mCurrentSpanEnds: MutableList<Int> constructor(context: Context) : super(context) { mIconSize = textSize.toInt() mIconAlignment = textSize.toInt() mIconTextSize = textSize.toInt() } constructor(context: Context, attrs: AttributeSet): super(context, attrs){ init(attrs) } constructor(context: Context, attrs: AttributeSet, defStyle: Int): super(context, attrs, defStyle) { init(attrs) } fun init(attrs: AttributeSet) { val array = context.obtainStyledAttributes(attrs, R.styleable.DynamicValueEditText) displayDrawableForDynamicValue = array.getBoolean( R.styleable.DynamicValueEditText_displayDrawableForDynamicValue, true) mIconSize = textSize.toInt() mIconAlignment = textSize.toInt() mIconTextSize = textSize.toInt() this.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { //get the current length of the text before its changes so we can see if the user was deleting text mTextLengthBefore = text.length //get current spans and their locations. This will then help on deletion of span val currentSpans = text.getSpans(0, text.length, DynamicValueDrawableSpan::class.java) mCurrentSpanStarts = mutableListOf() mCurrentSpanEnds = mutableListOf() for (i in currentSpans.indices) { mCurrentSpanStarts.add(text.getSpanStart(currentSpans[i])) mCurrentSpanEnds.add(text.getSpanEnd(currentSpans[i])) } } override fun onTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { if(displayDrawableForDynamicValue){ updateDynamicTextWithDrawable() } } override fun afterTextChanged(s: Editable) { //Detect if they were deleting text if we are. delete the whole dynamic phrase we are deleting if( text.length < mTextLengthBefore){ var i = 0 while (i < mCurrentSpanStarts.size){ if (selectionEnd > mCurrentSpanStarts[i] && selectionEnd < mCurrentSpanEnds[i]){ val updatedText: CharSequence try { updatedText = text.removeRange(mCurrentSpanStarts[i], mCurrentSpanEnds[i] - 1) setText(updatedText) } catch(e: Exception) { } setSelection(text.length) } i++ } mCurrentSpanStarts.clear() mCurrentSpanEnds.clear() } } }) array.recycle() } fun updateDynamicTextWithDrawable() { DynamicValueDrawableGenerator.addDynamicDrawables(context, text, mIconSize, mIconAlignment, mIconTextSize, 5.0f, 35.0f) } fun setDisplayDynamicDrawable (displayDynamicDrawable : Boolean){ this.displayDrawableForDynamicValue = displayDynamicDrawable } }
gpl-3.0
7602d69a3343c05966f335a4e6c374c1
32.782609
115
0.62154
5.088428
false
false
false
false
intrigus/jtransc
jtransc-utils/src/com/jtransc/text/escape.kt
2
2646
/* * Copyright 2016 Carlos Ballesteros Velasco * * 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.jtransc.text fun String.escape(): String { val out = StringBuilder() for (n in 0 until this.length) { val c = this[n] when (c) { '\\' -> out.append("\\\\") '"' -> out.append("\\\"") '\n' -> out.append("\\n") '\r' -> out.append("\\r") '\t' -> out.append("\\t") in '\u0000'..'\u001f' -> out.append("\\x" + "%02x".format(c.toInt())) else -> out.append(c) } } return out.toString() } fun String.uescape(): String { val out = StringBuilder() for (n in 0 until this.length) { val c = this[n] when (c) { 0.toChar() -> out.append("\\0") '\\' -> out.append("\\\\") '"' -> out.append("\\\"") '\n' -> out.append("\\n") '\r' -> out.append("\\r") '\t' -> out.append("\\t") //else -> if (c.isPrintable()) { // out.append(c) //} else { // out.append("\\u" + "%04x".format(c.toInt())) //} in 'a' .. 'z', in 'A' .. 'Z', in '0' .. '9', '_', '.', ',', ';', ':', '<', '>', '{', '}', '[', ']', '/', ' ', '=', '!', '%', '&' -> out.append(c) else -> out.append("\\u" + "%04x".format(c.toInt())) } } return out.toString() } fun String.unescape(): String { val out = StringBuilder() var n = 0 while (n < this.length) { val c = this[n++] when (c) { '\\' -> { val c2 = this[n++] when (c2) { '\\' -> out.append('\\') '"' -> out.append('\"') 'n' -> out.append('\n') 'r' -> out.append('\r') 't' -> out.append('\t') 'u' -> { val chars = this.substring(n, n + 4) n += 4 out.append(Integer.parseInt(chars, 16).toChar()) } else -> { out.append("\\$c2") } } } else -> out.append(c) } } return out.toString() } fun String?.uquote(): String = if (this != null) "\"${this.uescape()}\"" else "null" fun String?.quote(): String = if (this != null) "\"${this.escape()}\"" else "null" fun String.isQuoted(): Boolean = this.startsWith('"') && this.endsWith('"') fun String.unquote(): String = if (isQuoted()) { this.substring(1, this.length - 1).unescape() } else { "$this" }
apache-2.0
2c29101288053969730efa1f3a3c30e2
26
148
0.534392
2.936737
false
false
false
false
aosp-mirror/platform_frameworks_support
room/compiler/src/main/kotlin/androidx/room/solver/types/PrimitiveBooleanToIntConverter.kt
1
1910
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.solver.types import androidx.room.ext.L import androidx.room.solver.CodeGenScope import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.type.TypeKind.BOOLEAN import javax.lang.model.type.TypeKind.INT /** * int to boolean adapter. */ object PrimitiveBooleanToIntConverter { fun create(processingEnvironment: ProcessingEnvironment): List<TypeConverter> { val tBoolean = processingEnvironment.typeUtils.getPrimitiveType(BOOLEAN) val tInt = processingEnvironment.typeUtils.getPrimitiveType(INT) return listOf( object : TypeConverter(tBoolean, tInt) { override fun convert(inputVarName: String, outputVarName: String, scope: CodeGenScope) { scope.builder().addStatement("$L = $L ? 1 : 0", outputVarName, inputVarName) } }, object : TypeConverter(tInt, tBoolean) { override fun convert(inputVarName: String, outputVarName: String, scope: CodeGenScope) { scope.builder().addStatement("$L = $L != 0", outputVarName, inputVarName) } }) } }
apache-2.0
7e97af1f4d0d76f9f95e85dde51094d0
40.521739
100
0.647644
4.811083
false
false
false
false
koma-im/koma
src/main/kotlin/link/continuum/desktop/action/startChat.kt
1
1140
package link.continuum.desktop.action import koma.Server import koma.gui.view.ChatWindowBars import koma.koma_app.AppData import koma.koma_app.AppStore import koma.koma_app.appState import koma.matrix.UserId import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi import link.continuum.desktop.database.KeyValueStore import link.continuum.desktop.gui.JFX import mu.KotlinLogging import okhttp3.HttpUrl import okhttp3.OkHttpClient private val logger = KotlinLogging.logger {} /** * show the chat window after login is done * updates the list of recently used accounts */ @ExperimentalCoroutinesApi suspend fun startChat(httpClient: OkHttpClient, userId: UserId, token: String, url: HttpUrl, keyValueStore: KeyValueStore, appData: Deferred<AppData> ) { val app = appState val server = Server(url, httpClient) val account = server.account(userId, token) app.apiClient = account val primary = ChatWindowBars(account, keyValueStore, app.job, appData) JFX.primaryPane.setChild(primary.root) keyValueStore.updateAccountUsage(userId) }
gpl-3.0
50ebd66f057c1ffb24226e5ad3c76a46
29.810811
92
0.765789
4.334601
false
false
false
false
blademainer/intellij-community
plugins/settings-repository/src/settings/upstreamEditor.kt
4
4188
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository import com.intellij.notification.NotificationType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import com.intellij.util.ArrayUtil import org.jetbrains.settingsRepository.actions.NOTIFICATION_GROUP import java.awt.Container import java.awt.event.ActionEvent import javax.swing.AbstractAction import javax.swing.Action fun updateSyncButtonState(url: String?, syncActions: Array<Action>) { val enabled: Boolean try { enabled = url != null && url.length() > 1 && icsManager.repositoryService.checkUrl(url, null); } catch (e: Throwable) { enabled = false; } for (syncAction in syncActions) { syncAction.isEnabled = enabled; } } fun createMergeActions(project: Project?, urlTextField: TextFieldWithBrowseButton, dialogParent: Container, okAction: (() -> Unit)): Array<Action> { var syncTypes = SyncType.values() if (SystemInfo.isMac) { syncTypes = ArrayUtil.reverseArray(syncTypes) } val icsManager = icsManager return Array(3) { val syncType = syncTypes[it] object : AbstractAction(IcsBundle.message("action.${if (syncType == SyncType.MERGE) "Merge" else (if (syncType == SyncType.OVERWRITE_LOCAL) "ResetToTheirs" else "ResetToMy")}Settings.text")) { private fun saveRemoteRepositoryUrl(): Boolean { val url = StringUtil.nullize(urlTextField.text) if (url != null && !icsManager.repositoryService.checkUrl(url, dialogParent)) { return false } val repositoryManager = icsManager.repositoryManager repositoryManager.createRepositoryIfNeed() repositoryManager.setUpstream(url, null) return true } override fun actionPerformed(event: ActionEvent) { val repositoryWillBeCreated = !icsManager.repositoryManager.isRepositoryExists() var upstreamSet = false try { if (!saveRemoteRepositoryUrl()) { if (repositoryWillBeCreated) { // remove created repository icsManager.repositoryManager.deleteRepository() } return } upstreamSet = true if (repositoryWillBeCreated && syncType != SyncType.OVERWRITE_LOCAL) { ApplicationManager.getApplication().saveSettings() icsManager.sync(syncType, project, { copyLocalConfig() }) } else { icsManager.sync(syncType, project, null) } } catch (e: Throwable) { if (repositoryWillBeCreated) { // remove created repository icsManager.repositoryManager.deleteRepository() } LOG.warn(e) if (!upstreamSet || e is NoRemoteRepositoryException) { Messages.showErrorDialog(dialogParent, IcsBundle.message("set.upstream.failed.message", e.getMessage()), IcsBundle.message("set.upstream.failed.title")) } else { Messages.showErrorDialog(dialogParent, StringUtil.notNullize(e.getMessage(), "Internal error"), IcsBundle.message(if (e is AuthenticationException) "sync.not.authorized.title" else "sync.rejected.title")) } return } NOTIFICATION_GROUP.createNotification(IcsBundle.message("sync.done.message"), NotificationType.INFORMATION).notify(project) okAction() } } } }
apache-2.0
a62482f518995dac48defdea7be14a87
35.745614
216
0.691977
4.700337
false
false
false
false
CarrotCodes/Kuroda
src/main/java/engineer/carrot/warren/kuroda/IrcWrapper.kt
1
5809
package engineer.carrot.warren.kuroda import engineer.carrot.warren.kale.irc.message.rfc1459.NoticeMessage import engineer.carrot.warren.kale.irc.message.rfc1459.PrivMsgMessage import engineer.carrot.warren.warren.* import engineer.carrot.warren.warren.event.ConnectionLifecycleEvent import engineer.carrot.warren.warren.event.WarrenEventDispatcher import engineer.carrot.warren.warren.event.internal.SendSomethingEvent import engineer.carrot.warren.warren.state.LifecycleState import hudson.EnvVars import hudson.model.TaskListener import java.util.concurrent.ConcurrentLinkedQueue import kotlin.concurrent.thread interface IIrcWrapper { fun connect() fun send(message: String, listener: TaskListener) fun sendBuildStartedMessage(vars: EnvVars, listener: TaskListener) fun sendBuildSucceededMessage(vars: EnvVars, listener: TaskListener) fun sendBuildFailedMessage(vars: EnvVars, listener: TaskListener) fun sendBuildAbortedMessage(vars: EnvVars, listener: TaskListener) fun sendBuildUnstableMessage(vars: EnvVars, listener: TaskListener) } class IrcWrapper(private val server: String, private val port: Int, private val useTLS: Boolean, private val nick: String, private val channels: Map<String, String?>) : IIrcWrapper { private @Volatile var ircRunner: IrcRunner? = null private val queuedMessages = ConcurrentLinkedQueue<String>() override fun connect() { println("getting or creating new irc runner") getOrCreateCurrentRunner() } override fun send(message: String, listener: TaskListener) { sendIrcMessage(message, listener) } override fun sendBuildStartedMessage(vars: EnvVars, listener: TaskListener) { val message = listOf("Build started:", vars["JOB_NAME"], vars["BUILD_DISPLAY_NAME"], "🕑", vars["BUILD_URL"]).filterNotNull().joinToString(separator = " ") sendIrcMessage(message, listener) } override fun sendBuildSucceededMessage(vars: EnvVars, listener: TaskListener) { val message = listOf("Build succeeded:", vars["JOB_NAME"], vars["BUILD_DISPLAY_NAME"], "⭐️", vars["BUILD_URL"]).filterNotNull().joinToString(separator = " ") sendIrcMessage(message, listener) } override fun sendBuildFailedMessage(vars: EnvVars, listener: TaskListener) { val message = listOf("Build failed:", vars["JOB_NAME"], vars["BUILD_DISPLAY_NAME"], "⛈", vars["BUILD_URL"]).filterNotNull().joinToString(separator = " ") sendIrcMessage(message, listener) } override fun sendBuildAbortedMessage(vars: EnvVars, listener: TaskListener) { val message = listOf("Build aborted:", vars["JOB_NAME"], vars["BUILD_DISPLAY_NAME"], "⛔️", vars["BUILD_URL"]).filterNotNull().joinToString(separator = " ") sendIrcMessage(message, listener) } override fun sendBuildUnstableMessage(vars: EnvVars, listener: TaskListener) { val message = listOf("Build unstable:", vars["JOB_NAME"], vars["BUILD_DISPLAY_NAME"], "🌧", vars["BUILD_URL"]).filterNotNull().joinToString(separator = " ") sendIrcMessage(message, listener) } private fun sendIrcMessage(message: String, listener: TaskListener) { val irc: IrcRunner = getOrCreateCurrentRunner() if (irc.lastStateSnapshot?.connection?.lifecycle != LifecycleState.CONNECTED) { listener.logger.println("waiting to connect - added to queued messages") queuedMessages += message } else { val channels = (irc.lastStateSnapshot?.channels?.joining?.all?.keys ?: setOf()) + (irc.lastStateSnapshot?.channels?.joined?.all?.keys ?: setOf()) channels.forEach { listener.logger.println("sending to $it: $message") irc.eventSink.add(SendSomethingEvent(NoticeMessage(target = it, message = message), irc.sink)) } } } private fun getOrCreateCurrentRunner(): IrcRunner { var currentRunner = ircRunner if (currentRunner?.lastStateSnapshot?.connection?.lifecycle == LifecycleState.DISCONNECTED) { currentRunner?.sink?.tearDown() currentRunner = null } return if (currentRunner != null) { currentRunner } else { val events = WarrenEventDispatcher() events.onAnything { println("irc event: $it") } val factory = WarrenFactory(ServerConfiguration(server, port, useTLS = useTLS), UserConfiguration(nick), ChannelsConfiguration(channels), EventConfiguration(events, fireIncomingLineEvent = false)) val connection = factory.create() events.on(ConnectionLifecycleEvent::class) { val lifecycle = it.lifecycle if (lifecycle == LifecycleState.CONNECTED) { for (queuedMessage in queuedMessages) { val channels = (connection.lastStateSnapshot?.channels?.joining?.all?.keys ?: setOf()) + (connection.lastStateSnapshot?.channels?.joined?.all?.keys ?: setOf()) channels.forEach { println("sending queued messages to $it: $queuedMessages") connection.eventSink.add(SendSomethingEvent(PrivMsgMessage(target = it, message = queuedMessage), connection.sink)) } } } else if (lifecycle == LifecycleState.DISCONNECTED) { queuedMessages.clear() } } ircRunner = connection thread { println("irc connection started") connection.run() ircRunner = null println("irc connection ended") } connection } } }
isc
d28f0fc98e98b238aec4ded0f5fc71c2
41.602941
183
0.658553
4.831526
false
false
false
false
seventhroot/elysium
bukkit/rpk-economy-bukkit/src/main/kotlin/com/rpkit/economy/bukkit/command/money/MoneyCommand.kt
1
2718
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.economy.bukkit.command.money import com.rpkit.economy.bukkit.RPKEconomyBukkit import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender /** * Money command. * Parent command for all money management commands. */ class MoneyCommand(val plugin: RPKEconomyBukkit): CommandExecutor { private val moneySubtractCommand = MoneySubtractCommand(plugin) private val moneyAddCommand = MoneyAddCommand(plugin) private val moneySetCommand = MoneySetCommand(plugin) private val moneyViewCommand = MoneyViewCommand(plugin) private val moneyPayCommand = MoneyPayCommand(plugin) private val moneyWalletCommand = MoneyWalletCommand(plugin) override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (args.isNotEmpty()) { val newArgs = args.drop(1).toTypedArray() if (args[0].equals("subtract", ignoreCase = true) || args[0].equals("sub", ignoreCase = true)) { return moneySubtractCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("add", ignoreCase = true)) { return moneyAddCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("set", ignoreCase = true)) { return moneySetCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("view", ignoreCase = true)) { return moneyViewCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("pay", ignoreCase = true)) { return moneyPayCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("wallet", ignoreCase = true)) { return moneyWalletCommand.onCommand(sender, command, label, newArgs) } else { sender.sendMessage(plugin.messages["money-usage"]) } } else { return moneyViewCommand.onCommand(sender, command, label, arrayOf()) } return true } }
apache-2.0
ffe394b1c989fd5c34a296241c29c0c4
43.57377
118
0.682487
4.433931
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/problem/graphql/builder/GraphQLActionBuilder.kt
1
48196
package org.evomaster.core.problem.graphql.builder import com.google.gson.Gson import org.evomaster.core.logging.LoggingUtil import org.evomaster.core.problem.api.service.param.Param import org.evomaster.core.problem.graphql.GQMethodType import org.evomaster.core.problem.graphql.GqlConst import org.evomaster.core.problem.graphql.GraphQLAction import org.evomaster.core.problem.graphql.param.GQInputParam import org.evomaster.core.problem.graphql.param.GQReturnParam import org.evomaster.core.problem.graphql.schema.* import org.evomaster.core.problem.graphql.schema.__TypeKind.* import org.evomaster.core.remote.SutProblemException import org.evomaster.core.search.Action import org.evomaster.core.search.gene.* import org.evomaster.core.search.gene.collection.ArrayGene import org.evomaster.core.search.gene.collection.EnumGene import org.evomaster.core.search.gene.collection.TupleGene import org.evomaster.core.search.gene.datetime.DateGene import org.evomaster.core.search.gene.numeric.FloatGene import org.evomaster.core.search.gene.numeric.IntegerGene import org.evomaster.core.search.gene.numeric.LongGene import org.evomaster.core.search.gene.optional.NullableGene import org.evomaster.core.search.gene.optional.OptionalGene import org.evomaster.core.search.gene.placeholder.CycleObjectGene import org.evomaster.core.search.gene.placeholder.LimitObjectGene import org.evomaster.core.search.gene.string.StringGene import org.evomaster.core.search.gene.utils.GeneUtils import org.slf4j.Logger import org.slf4j.LoggerFactory import java.util.* import java.util.concurrent.atomic.AtomicInteger object GraphQLActionBuilder { private val log: Logger = LoggerFactory.getLogger(GraphQLActionBuilder::class.java) /** * Used to create unique IDs */ private val idGenerator = AtomicInteger() /** * Cache to avoid rebuilding the same genes again and again. * * Key: id of element in schema * Value: a gene for it * * Note: this is NOT thread-safe */ private val cache = mutableMapOf<String, Gene>() private val depthBasedCache = mutableMapOf<String, Gene>() /** * @param schema: the schema extracted from a GraphQL API, as a JSON string * @param actionCluster: for each mutation/query in the schema, populate this map with * new action templates. * @param treeDepth: maximum depth for the created objects, to avoid HUGE data structures */ fun addActionsFromSchema( schema: String, actionCluster: MutableMap<String, Action>, treeDepth: Int = Int.MAX_VALUE //no restrictions by default ) { cache.clear() depthBasedCache.clear() val schemaObj: SchemaObj = try { Gson().fromJson(schema, SchemaObj::class.java) } catch (e: Exception) { throw SutProblemException("Failed to parse the schema of the SUT as a JSON object: ${e.message}") } val state = StateBuilder.initTablesInfo(schemaObj) if (schemaObj.data.__schema.queryType != null || schemaObj.data.__schema.mutationType != null) { for (element in state.tables) { if (schemaObj.data.__schema.queryType?.name?.toLowerCase() == element.typeName.lowercase()) { handleOperation(state, actionCluster, treeDepth, element, GQMethodType.QUERY) } else if (schemaObj.data.__schema.mutationType?.name?.toLowerCase() == element.typeName.lowercase()) { handleOperation(state, actionCluster, treeDepth, element, GQMethodType.MUTATION) } } } else { throw SutProblemException("The given GraphQL schema has no Query nor Mutation operation") } } private fun handleOperation( state: TempState, actionCluster: MutableMap<String, Action>, treeDepth: Int, element: Table, type: GQMethodType ) { val actionId = "${element.fieldName}${idGenerator.incrementAndGet()}" /* For this operation, we extract the inputs (if any) and return object (if any) as parameter that the search can evolve */ val params = extractParams(state, treeDepth, element) //Note: if a return param is a primitive type it will be null //Get the boolean selection of the constructed return param val returnGene = params.find { p -> p is GQReturnParam }?.gene val selection = returnGene?.let { GeneUtils.getBooleanSelection(it) } //remove the constructed return param params.remove(params.find { p -> p is GQReturnParam }) //add constructed return param selection instead selection?.name?.let { GQReturnParam(it, selection) }?.let { params.add(it) } /* all fields are optional in GraphQL, so should always be possible to prevent cycles, unless the schema is wrong (eg, must still satisfy that at least one field is selected) */ params.map { it.gene }.forEach { GeneUtils.preventCycles(it, true) } params.map { it.gene }.forEach { GeneUtils.preventLimit(it, true) } /* In some cases object gene (optional or not) with all fields as cycle object gene (optional or not) are generated. Also, in some cases (ex: in AnigList) object gene (optional or not) with all fields as tuples gene with all their last elements as kind of Limit gene are generated. So we need to deactivate it by looking into its ancestors (e.g., Optional set to false, Array set length to 0) */ handleAllCyclesAndLimitInObjectFields(params) /* In some cases when fixing the depth to n. The return object gives paths to only Limit genes. In this case the return gene should not be repaired but rather removed from the actions (as a simple solution). *Note: It seems like a very edge case, since the limit gene was added to avoid too large trees. */ if (params.any { p -> p is GQReturnParam }) { if (!params.find { p -> p is GQReturnParam }?.let { isAllLimitInObjectFields(it) }!!) createAction(actionId, element, type, params, actionCluster) } else createAction(actionId, element, type, params, actionCluster) } private fun createAction( actionId: String, element: Table, type: GQMethodType, params: MutableList<Param>, actionCluster: MutableMap<String, Action> ) { val action = GraphQLAction(actionId, element.fieldName, type, params) actionCluster[action.getName()] = action } private fun handleAllCyclesAndLimitInObjectFields( params: MutableList<Param> ) { params.map { it.gene }.forEach { when { it is ObjectGene -> it.flatView().forEach { g -> if (g is OptionalGene && g.gene is ObjectGene) handleAllCyclesAndLimitInObjectFields(g.gene) else if (g is ObjectGene) handleAllCyclesAndLimitInObjectFields( g ) } it is OptionalGene && it.gene is ObjectGene -> it.flatView().forEach { g -> if (g is OptionalGene && g.gene is ObjectGene) handleAllCyclesAndLimitInObjectFields(g.gene) else if (g is ObjectGene) handleAllCyclesAndLimitInObjectFields( g ) } it is ArrayGene<*> && it.template is ObjectGene -> it.flatView().forEach { g -> it.template.fields.forEach { f -> if (f is OptionalGene && f.gene is ObjectGene) handleAllCyclesAndLimitInObjectFields( f.gene ) else if (f is ObjectGene) handleAllCyclesAndLimitInObjectFields(f) } } it is OptionalGene && it.gene is ArrayGene<*> && it.gene.template is ObjectGene -> it.flatView() .forEach { g -> it.gene.template.fields.forEach { f -> if (f is OptionalGene && f.gene is ObjectGene) handleAllCyclesAndLimitInObjectFields( f.gene ) else if (f is ObjectGene) handleAllCyclesAndLimitInObjectFields(f) } } } } } /** * Check if there is any top gene in any param for which we cannot make a selection due to limit genes */ private fun isAllLimitInObjectFields( params: Param ): Boolean { return params.genes .any { isAllLimitInObjectFields(it) } } /** * @return true if we get the limit pattern, false if not. */ private fun isAllLimitInObjectFields( gene: Gene ): Boolean { val obj = gene.getWrappedGene(ObjectGene::class.java) ?: return false return obj.fields.all { val childObj = it.getWrappedGene(ObjectGene::class.java) val childLim = it.getWrappedGene(LimitObjectGene::class.java) if(childObj == null && childLim == null){ false } else if(childLim != null){ true } else if(childObj != null){ isAllLimitInObjectFields(childObj) } else { //should never be reached false } } } fun handleAllCyclesAndLimitInObjectFields(gene: ObjectGene) { if (gene.fields.all { ((it is CycleObjectGene)) || (it is OptionalGene && it.gene is CycleObjectGene) || (it is LimitObjectGene) || ((it is OptionalGene && it.gene is LimitObjectGene) || ((it is OptionalGene && it.gene is LimitObjectGene) || (it is OptionalGene && it.gene is ObjectGene && it.gene.fields.all { it is OptionalGene && it.gene is LimitObjectGene })) || /* The Object gene contains: All fields as tuples, need to check if theirs last elements are kind of limit gene. If it is the case, need to prevent selection on them */ (it is TupleGene && it.lastElementTreatedSpecially && isLastContainsAllLimitGenes(it)) || (it is OptionalGene && it.gene is TupleGene && it.gene.lastElementTreatedSpecially && isLastContainsAllLimitGenes( it.gene ))) }) { GeneUtils.tryToPreventSelection(gene) } } /* Check if the last element in the tuple (the return) either is: optional limit gene, optional Object with all fields as limit gene or optional Object with all fields as Optional limit gene */ private fun isLastContainsAllLimitGenes(tuple: TupleGene): Boolean { val lastElement = tuple.elements.last() return (lastElement is OptionalGene && lastElement is LimitObjectGene) || (lastElement is OptionalGene && lastElement.gene is ObjectGene && lastElement.gene.fields.all { it is LimitObjectGene } ) || (lastElement is OptionalGene && lastElement.gene is ObjectGene && lastElement.gene.fields.all { it is OptionalGene && it.gene is LimitObjectGene } ) } private fun extractParams( state: TempState, maxTreeDepth: Int, element: Table ): MutableList<Param> { val params = mutableListOf<Param>() val selectionInArgs = state.argsTablesIndexedByName[element.fieldName] ?: listOf() if (element.isFieldNameWithArgs) { for (input in selectionInArgs) { if (input.kindOfFieldType == SCALAR.toString() || input.kindOfFieldType == ENUM.toString()) {//array scalar type or array enum type, the gene is constructed from getInputGene to take the correct names val gene = getInputScalarListOrEnumListGene(state, input) params.add(GQInputParam(input.fieldName, gene)) } else {//for input objects types and objects types val gene = getInputGene( state, ArrayDeque(), maxTreeDepth, input ) params.add(GQInputParam(input.fieldName, gene)) } } } //handling the return param, should put all the fields optional val gene = getReturnGene( state, ArrayDeque(), 0, maxTreeDepth, element ) //Remove primitive types (scalar and enum) from return params if (isReturnNotPrimitive(gene)) params.add(GQReturnParam(element.fieldName, gene)) return params } private fun isReturnNotPrimitive( gene: Gene, ) = ( !(gene is OptionalGene && isScalar(gene.gene)) && !(gene is OptionalGene && gene.gene is ArrayGene<*> && gene.gene.template is OptionalGene && isScalar( gene.gene.template.gene )) && !(gene is ArrayGene<*> && isScalar(gene.template)) && !(gene is ArrayGene<*> && gene.template is OptionalGene && isScalar(gene.template.gene)) && !(gene is OptionalGene && gene.gene is ArrayGene<*> && isScalar(gene.gene.template)) //enum cases && !(gene is OptionalGene && gene.gene is ArrayGene<*> && gene.gene.template is OptionalGene && gene.gene.template.gene is EnumGene<*>) && !(gene is ArrayGene<*> && gene.template is EnumGene<*>) && !(gene is ArrayGene<*> && gene.template is OptionalGene && gene.template.gene is EnumGene<*>) && !(gene is OptionalGene && gene.gene is ArrayGene<*> && gene.gene.template is EnumGene<*>) && gene !is EnumGene<*> && !(gene is OptionalGene && gene.gene is EnumGene<*>) ) private fun isScalar(gene: Gene) = gene is IntegerGene || gene is StringGene || gene is FloatGene || gene is BooleanGene || gene is LongGene || gene is DateGene /**Note: There are tree functions containing blocs of "when": two functions for inputs and one for return. *For the inputs: blocs of "when" could not be refactored since they are different because the names are different. *And for the return: it could not be refactored with inputs because we do not consider optional/non optional cases (unlike in inputs) . */ /** * For Scalar arrays types and Enum arrays types */ private fun getInputScalarListOrEnumListGene( state: TempState, element: Table ): Gene { val gene = cache[element.uniqueId] if (gene != null) { return gene.copy() } val created: Gene = when (element.KindOfFieldName.lowercase()) { GqlConst.LIST -> if (element.isKindOfFieldNameOptional) { val copy = element.copy( fieldType = element.typeName, KindOfFieldName = element.kindOfFieldType, kindOfFieldType = element.KindOfFieldName, typeName = element.fieldType ) val template = getInputScalarListOrEnumListGene(state, copy) OptionalGene(element.fieldName, NullableGene(element.fieldName, ArrayGene(element.fieldName, template))) } else { val copy = element.copy( fieldType = element.typeName, KindOfFieldName = element.kindOfFieldType, kindOfFieldType = element.KindOfFieldName, typeName = element.fieldType ) val template = getInputScalarListOrEnumListGene(state, copy) ArrayGene(element.fieldName, template) } "int" -> if (element.isKindOfFieldTypeOptional) OptionalGene(element.fieldName, NullableGene( element.fieldName,IntegerGene(element.fieldName))) else IntegerGene(element.fieldName) "string" -> if (element.isKindOfFieldTypeOptional) OptionalGene(element.fieldName, NullableGene(element.fieldName,(StringGene(element.fieldName)))) else StringGene(element.fieldName) "float" -> if (element.isKindOfFieldTypeOptional) OptionalGene(element.fieldName, NullableGene(element.fieldName,FloatGene(element.fieldName))) else FloatGene(element.fieldName) "boolean" -> if (element.isKindOfFieldTypeOptional) OptionalGene(element.fieldName,NullableGene(element.fieldName, BooleanGene(element.fieldName))) else BooleanGene(element.fieldName) "long" -> if (element.isKindOfFieldTypeOptional) OptionalGene(element.fieldName,NullableGene(element.fieldName, LongGene(element.fieldName))) else LongGene(element.fieldName) "null" -> { val copy = element.copy( fieldType = element.typeName, KindOfFieldName = element.kindOfFieldType, kindOfFieldType = element.KindOfFieldName, typeName = element.fieldType ) getInputScalarListOrEnumListGene(state, copy) } "date" -> if (element.isKindOfFieldTypeOptional) OptionalGene(element.fieldName, NullableGene(element.fieldName, BooleanGene(element.fieldName))) else DateGene(element.fieldName) GqlConst.SCALAR -> { val copy = element.copy( KindOfFieldName = element.typeName, typeName = element.KindOfFieldName ) getInputScalarListOrEnumListGene(state, copy) } "id" -> if (element.isKindOfFieldTypeOptional) OptionalGene(element.fieldName, NullableGene(element.fieldName, StringGene(element.fieldName))) else StringGene(element.fieldName) GqlConst.ENUM -> if (element.isKindOfFieldTypeOptional) OptionalGene(element.fieldName, NullableGene(element.fieldName, EnumGene(element.fieldName, element.enumValues))) else EnumGene(element.fieldName, element.enumValues) GqlConst.UNION -> { LoggingUtil.uniqueWarn(log, "GQL does not support union in input type: ${element.KindOfFieldName}") StringGene("Not supported type") } GqlConst.INTERFACE -> { LoggingUtil.uniqueWarn(log, "GQL does not support union in input type: ${element.KindOfFieldName}") StringGene("Not supported type") } else -> if (element.isKindOfFieldTypeOptional) OptionalGene(element.fieldName, NullableGene(element.fieldName, StringGene(element.fieldName))) else StringGene(element.fieldName) } cache[element.uniqueId] = created return created } /** * Used to extract the input gene: representing arguments in the GQL query/mutation. * From an implementation point of view, it represents a GQL input param. we can have 0 or n argument for one action. */ private fun getInputGene( state: TempState, history: Deque<String>, maxTreeDepth: Int, element: Table ): Gene { when (element.KindOfFieldName.lowercase()) { GqlConst.LIST -> return if (element.isKindOfFieldNameOptional) { val copy = element.copy( fieldType = element.typeName, KindOfFieldName = element.kindOfFieldType, kindOfFieldType = element.KindOfFieldName, typeName = element.fieldType, ) val template = getInputGene(state, history, maxTreeDepth, copy) OptionalGene(element.fieldName, NullableGene(element.fieldName, ArrayGene(element.fieldName, template))) } else { val copy = element.copy( fieldType = element.typeName, KindOfFieldName = element.kindOfFieldType, kindOfFieldType = element.KindOfFieldName, typeName = element.fieldType ) val template = getInputGene(state, history, maxTreeDepth, copy) ArrayGene(element.fieldName, template) } GqlConst.OBJECT -> return if (element.isKindOfFieldTypeOptional) { val optObjGene = createObjectGene(state, history, 0, maxTreeDepth, element) OptionalGene(element.fieldName, NullableGene(element.fieldName, optObjGene)) } else createObjectGene(state, history, 0, maxTreeDepth, element) GqlConst.INPUT_OBJECT -> return if (element.isKindOfFieldTypeOptional) { val optInputObjGene = createInputObjectGene(state, history, maxTreeDepth, element) OptionalGene(element.fieldName, NullableGene(element.fieldName, optInputObjGene)) } else createInputObjectGene(state, history, maxTreeDepth, element) "int" -> return if (element.isKindOfFieldTypeOptional) OptionalGene(element.typeName, NullableGene(element.typeName,IntegerGene(element.typeName))) else IntegerGene(element.typeName) "string" -> return if (element.isKindOfFieldTypeOptional) OptionalGene(element.typeName, NullableGene(element.typeName, StringGene(element.typeName))) else StringGene(element.typeName) "float" -> return if (element.isKindOfFieldTypeOptional) OptionalGene(element.typeName, NullableGene(element.typeName, FloatGene(element.typeName))) else FloatGene(element.typeName) "boolean" -> return if (element.isKindOfFieldTypeOptional) OptionalGene(element.typeName, NullableGene(element.typeName, BooleanGene(element.typeName))) else BooleanGene(element.typeName) "long" -> return if (element.isKindOfFieldTypeOptional) OptionalGene(element.typeName, NullableGene(element.typeName, LongGene(element.typeName))) else LongGene(element.typeName) "null" -> { val copy = element.copy( fieldType = element.typeName, KindOfFieldName = element.kindOfFieldType, kindOfFieldType = element.KindOfFieldName, typeName = element.fieldType, ) return getInputGene(state, history, maxTreeDepth, copy) } "date" -> return if (element.isKindOfFieldTypeOptional) OptionalGene(element.typeName, NullableGene(element.typeName, DateGene(element.typeName))) else DateGene(element.typeName) GqlConst.ENUM -> return if (element.isKindOfFieldTypeOptional) OptionalGene(element.typeName, NullableGene(element.typeName, EnumGene(element.typeName, element.enumValues))) else EnumGene(element.typeName, element.enumValues) GqlConst.SCALAR -> { val copy = element.copy( fieldType = element.fieldType, KindOfFieldName = element.typeName, typeName = element.KindOfFieldName ) return getInputGene(state, history, maxTreeDepth, copy) } "id" -> return if (element.isKindOfFieldTypeOptional) OptionalGene(element.typeName, NullableGene(element.typeName, StringGene(element.typeName))) else StringGene(element.typeName) GqlConst.UNION -> { LoggingUtil.uniqueWarn(log, " GQL does not support union in input type: ${element.KindOfFieldName}") return StringGene("Not supported type") } GqlConst.INTERFACE -> { LoggingUtil.uniqueWarn( log, "GQL does not support interface in input type: ${element.KindOfFieldName}" ) return StringGene("Not supported type") } else -> return if (element.isKindOfFieldTypeOptional) OptionalGene(element.typeName, NullableGene(element.typeName, StringGene(element.typeName))) else StringGene(element.typeName) } } /** * Create input object gene */ private fun createInputObjectGene( state: TempState, history: Deque<String>, maxTreeDepth: Int, element: Table ): Gene { val fields: MutableList<Gene> = mutableListOf() val selectionInArgs = state.argsTablesIndexedByName[element.typeName] ?: listOf() for (element in selectionInArgs) { if (element.kindOfFieldType.lowercase() == GqlConst.SCALAR) { val copy = element.copy( fieldType = element.typeName, KindOfFieldName = element.fieldType, typeName = element.fieldName ) val template = getInputGene(state, history, maxTreeDepth, copy) fields.add(template) } else if (element.KindOfFieldName.lowercase() == GqlConst.LIST) { val copy = copyTableElement(element, element) val template = getInputGene(state, history, maxTreeDepth, copy) fields.add(template) } else if (element.kindOfFieldType.lowercase() == GqlConst.INPUT_OBJECT) { val copy = copyTableElement(element, element) val template = getInputGene(state, history, maxTreeDepth, copy) fields.add(template) } else if (element.kindOfFieldType.lowercase() == GqlConst.ENUM) { val copy = element.copy( fieldType = element.typeName, KindOfFieldName = element.kindOfFieldType, typeName = element.fieldName ) val template = getInputGene(state, history, maxTreeDepth, copy) fields.add(template) } } return ObjectGene(element.fieldName, fields) } private fun copyTableElement( element: Table, secondElement: Table ): Table { return element.copy( typeName = element.fieldType, isKindOfFieldTypeOptional = secondElement.isKindOfFieldTypeOptional, isKindOfFieldNameOptional = secondElement.isKindOfFieldNameOptional ) } /** * Extract the return gene: representing the return value in the GQL query/mutation. * From an implementation point of view, it represents a GQL return param. In contrast to input param, we can have only one return param. */ private fun getReturnGene( state: TempState, history: Deque<String>, initAccum: Int, treeDepth: Int, element: Table ): Gene { when (element.KindOfFieldName.lowercase()) { GqlConst.LIST -> { val copy = element.copy( fieldType = element.typeName, KindOfFieldName = element.kindOfFieldType, kindOfFieldType = element.KindOfFieldName, typeName = element.fieldType, ) val template = getReturnGene(state, history, initAccum, treeDepth, copy) return OptionalGene(element.fieldName, ArrayGene(element.fieldName, template)) } GqlConst.OBJECT -> { val accum = initAccum + 1 return if (checkDepthIsOK(accum, treeDepth)) { history.addLast(element.typeName) if (history.count { it == element.typeName } == 1) { val id = "$accum:${element.uniqueId}" val gene = depthBasedCache[id] val objGene = if (gene != null) { gene.copy() as ObjectGene } else { val g = createObjectGene(state, history, accum, treeDepth, element) depthBasedCache[id] = g g } history.removeLast() if (state.inputTypeName[element.fieldName]?.isNotEmpty() == true) {OptionalGene(state.inputTypeName[element.fieldName].toString(), objGene)} else {OptionalGene(element.fieldName, objGene)} } else { //we have a cycle, in which same object has been seen in ancestor history.removeLast() (OptionalGene(element.fieldName, CycleObjectGene(element.fieldName))) } } else { //we reached the limit of depth we want to have in the created objects OptionalGene(element.fieldName, LimitObjectGene(element.fieldName)) } } GqlConst.UNION -> { history.addLast(element.typeName) return if (history.count { it == element.typeName } == 1) { val optObjGene = createUnionObjectsGene( state, history, initAccum, treeDepth, element ) history.removeLast() OptionalGene(element.fieldName + GqlConst.UNION_TAG, optObjGene) } else { history.removeLast() (OptionalGene(element.fieldName, CycleObjectGene(element.fieldName))) } } GqlConst.INTERFACE -> { history.addLast(element.typeName) return if (history.count { it == element.typeName } == 1) { var accum = initAccum + 1 if (checkDepthIsOK(accum, treeDepth)) { val id = "$accum:${element.uniqueId}" val gene = depthBasedCache[id] if (gene != null) { gene.copy() } else { //will contain basic interface fields, and had as name the methode name var interfaceBaseOptObjGene = createObjectGene( state, history, accum, treeDepth, element ) interfaceBaseOptObjGene = interfaceBaseOptObjGene as ObjectGene interfaceBaseOptObjGene.name = interfaceBaseOptObjGene.name.plus(GqlConst.INTERFACE_BASE_TAG) accum = initAccum //because #Base# and additional interface fields are in the same level //will contain additional interface fields, and had as name the name of the objects val interfaceAdditionalOptObjGene = createInterfaceObjectGene( state, history, interfaceBaseOptObjGene, accum, treeDepth, element ) //merge basic interface fields with additional interface fields interfaceAdditionalOptObjGene.add( OptionalGene( element.fieldName + GqlConst.INTERFACE_BASE_TAG, interfaceBaseOptObjGene ) ) history.removeLast() //will return a single optional object gene with optional basic interface fields and optional additional interface fields val g = OptionalGene( element.fieldName + GqlConst.INTERFACE_TAG, ObjectGene(element.fieldName + GqlConst.INTERFACE_TAG, interfaceAdditionalOptObjGene) ) depthBasedCache[id] = g g } } else { history.removeLast() OptionalGene(element.fieldName, LimitObjectGene(element.fieldName)) } } else { history.removeLast() (OptionalGene(element.fieldName, CycleObjectGene(element.fieldName))) } } "null" -> { val copy = element.copy( fieldType = element.typeName, KindOfFieldName = element.kindOfFieldType, kindOfFieldType = element.KindOfFieldName, typeName = element.fieldType ) return getReturnGene(state, history, initAccum, treeDepth, copy) } GqlConst.ENUM -> return createEnumGene( element.KindOfFieldName, element.enumValues, ) GqlConst.SCALAR -> { if (element.kindOfFieldType.lowercase() == GqlConst.LIST) return createScalarGene( element.typeName, element.fieldName, ) else return createScalarGene( element.typeName, element.KindOfFieldName, ) } else -> return OptionalGene(element.fieldName, StringGene(element.fieldName)) } } private fun createObjectGene( state: TempState, /** * This history store the names of the object, union and interface types (i.e. tableFieldType in Table.kt ). * It is used in cycles managements (detecting cycles due to object, union and interface types). */ history: Deque<String>, accum: Int, maxTreeDepth: Int, element: Table ): ObjectGene { val fields: MutableList<Gene> = mutableListOf() //Look after each field (not tuple) and construct it recursively val selection = state.tablesIndexedByName[element.typeName] ?: listOf() for (tableElement in selection) { val selectionInArgs = state.argsTablesIndexedByName[tableElement.fieldName] ?: listOf() //Contains the elements of a tuple val tupleElements: MutableList<Gene> = mutableListOf() /* The field is with arguments (it is a tuple): construct its arguments (n-1 elements) and; its last element (return) */ if (tableElement.isFieldNameWithArgs) { //Construct field s arguments (the n-1 elements of the tuple) first for (argElement in selectionInArgs) { if (argElement.kindOfFieldType == SCALAR.toString() || argElement.kindOfFieldType == ENUM.toString()) { //array scalar type or array enum type, the gene is constructed from getInputGene to take the correct names val gene = getInputScalarListOrEnumListGene(state, argElement) tupleElements.add(gene) } else { //for input objects types and objects types val gene = getInputGene( state, ArrayDeque(history), maxTreeDepth, argElement ) tupleElements.add(gene) } } //Construct the last element (the return) constructReturn( state, tableElement, ArrayDeque(history), element.isKindOfFieldTypeOptional, element.isKindOfFieldNameOptional, accum, maxTreeDepth, tupleElements ) val constructedTuple = if (isLastNotPrimitive(tupleElements.last())) if (state.inputTypeName[tupleElements.last().name]?.isNotEmpty() == true) OptionalGene( state.inputTypeName[tupleElements.last().name].toString(), TupleGene( state.inputTypeName[tupleElements.last().name].toString(), tupleElements, lastElementTreatedSpecially = true ) )else OptionalGene( tupleElements.last().name, TupleGene( tupleElements.last().name, tupleElements, lastElementTreatedSpecially = true ) ) else //Dropping the last element since it is a primitive type if (state.inputTypeName[tupleElements.last().name]?.isNotEmpty() == true) OptionalGene( state.inputTypeName[tupleElements.last().name].toString(), TupleGene( state.inputTypeName[tupleElements.last().name].toString(), tupleElements.dropLast(1), lastElementTreatedSpecially = false ) ) else OptionalGene( tupleElements.last().name, TupleGene( tupleElements.last().name, tupleElements.dropLast(1), lastElementTreatedSpecially = false ) ) fields.add(constructedTuple) } else /* The field is without arguments. regular object field (the return) */ constructReturn( state, tableElement, ArrayDeque(history), element.isKindOfFieldTypeOptional, element.isKindOfFieldNameOptional, accum, maxTreeDepth, fields ) } return if (state.inputTypeName[element.fieldName]?.isNotEmpty() == true) ObjectGene(state.inputTypeName[element.fieldName].toString(), fields) else ObjectGene(element.fieldName, fields) } private fun isLastNotPrimitive(lastElements: Gene) = ((lastElements is ObjectGene) || ((lastElements is OptionalGene) && (lastElements.gene is ObjectGene)) || ((lastElements is ArrayGene<*>) && (lastElements.template is ObjectGene)) || ((lastElements is ArrayGene<*>) && (lastElements.template is OptionalGene) && (lastElements.template.gene is ObjectGene)) || ((lastElements is OptionalGene) && (lastElements.gene is ArrayGene<*>) && (lastElements.gene.template is ObjectGene)) || ((lastElements is OptionalGene) && (lastElements.gene is ArrayGene<*>) && (lastElements.gene.template is OptionalGene) && (lastElements.gene.template.gene is ObjectGene)) ) private fun constructReturn( state: TempState, tableElement: Table, history: Deque<String>, isKindOfTableFieldTypeOptional: Boolean, isKindOfTableFieldOptional: Boolean, accum: Int, maxTreeDepth: Int, tupleElements: MutableList<Gene> ) { if (tableElement.KindOfFieldName.lowercase() == GqlConst.LIST) { val copy = tableElement.copy( typeName = tableElement.fieldType, isKindOfFieldTypeOptional = isKindOfTableFieldTypeOptional, isKindOfFieldNameOptional = isKindOfTableFieldOptional ) val gene = getReturnGene(state, history, accum, maxTreeDepth, copy) tupleElements.add(gene) return } when (tableElement.kindOfFieldType.lowercase()) { GqlConst.OBJECT -> { val copy = tableElement.copy( isKindOfFieldTypeOptional = isKindOfTableFieldTypeOptional, isKindOfFieldNameOptional = isKindOfTableFieldOptional ) val gene = getReturnGene(state, history, accum, maxTreeDepth, copy) tupleElements.add(gene) } GqlConst.SCALAR -> { val gene = createScalarGene( tableElement.fieldType, tableElement.fieldName, ) tupleElements.add(gene) } GqlConst.ENUM -> { val gene = createEnumGene( tableElement.fieldName, tableElement.enumValues ) tupleElements.add(gene) } GqlConst.UNION -> { val copy = tableElement.copy( isKindOfFieldTypeOptional = isKindOfTableFieldTypeOptional, isKindOfFieldNameOptional = isKindOfTableFieldOptional ) val template = getReturnGene(state, history, accum, maxTreeDepth, copy) tupleElements.add(template) } GqlConst.INTERFACE -> { val copy = tableElement.copy( isKindOfFieldTypeOptional = isKindOfTableFieldTypeOptional, isKindOfFieldNameOptional = isKindOfTableFieldOptional ) val template = getReturnGene(state, history, accum, maxTreeDepth, copy) tupleElements.add(template) } } } /** * Create the correspondent object gene for each object defining the union type */ private fun createUnionObjectsGene( state: TempState, history: Deque<String>, accum: Int, maxTreeDepth: Int, element: Table ): Gene { val fields: MutableList<Gene> = mutableListOf() var accum = accum val initAccum = accum // needed since we restore the accumulator each time we construct one object defining the union for (elementInUnionTypes in element.unionTypes) {//Browse all objects defining the union accum += 1 if (checkDepthIsOK(accum, maxTreeDepth)) { history.addLast(elementInUnionTypes) val copy = element.copy( typeName = elementInUnionTypes, fieldName = elementInUnionTypes ) val objGeneTemplate = createObjectGene(state, history, accum, maxTreeDepth, copy) history.removeLast() fields.add(OptionalGene(objGeneTemplate.name, objGeneTemplate)) } else { fields.add(OptionalGene(elementInUnionTypes, LimitObjectGene(elementInUnionTypes))) } accum = initAccum } return ObjectGene(element.fieldName + GqlConst.UNION_TAG, fields) } private fun createInterfaceObjectGene( state: TempState, history: Deque<String>, interfaceBaseOptObjGene: Gene, currentDepth: Int, maxTreeDepth: Int, element: Table ): MutableList<Gene> { val fields: MutableList<Gene> = mutableListOf() for (elementInInterfaceTypes in element.interfaceTypes) {//Browse all additional objects in the interface val accum = currentDepth + 1 if (checkDepthIsOK(accum, maxTreeDepth)) { history.addLast(elementInInterfaceTypes) //todo need better id for the interfaces val id = "$accum:${element.uniqueId}.${elementInInterfaceTypes}" val gene = depthBasedCache[id] var objGeneTemplate = if (gene != null) { gene.copy() as ObjectGene } else { val copy = element.copy( typeName = elementInInterfaceTypes, fieldName = elementInInterfaceTypes ) val g = createObjectGene(state, history, accum, maxTreeDepth, copy) depthBasedCache[id] = g g } history.removeLast() objGeneTemplate = objGeneTemplate.copyFields(interfaceBaseOptObjGene as ObjectGene)//remove useless fields if (objGeneTemplate.fields.isNotEmpty()) fields.add(OptionalGene(objGeneTemplate.name, objGeneTemplate)) } else { fields.add( OptionalGene( elementInInterfaceTypes, LimitObjectGene(elementInInterfaceTypes) ) ) } } return fields } private fun checkDepthIsOK(count: Int, maxTreeDepth: Int): Boolean { return count <= maxTreeDepth } fun createScalarGene( kindOfTableField: String?, tableType: String, ): Gene { when (kindOfTableField?.lowercase()) { "int" -> return OptionalGene(tableType, IntegerGene(tableType)) "string" -> return OptionalGene(tableType, StringGene(tableType)) "float" -> return OptionalGene(tableType, FloatGene(tableType)) "boolean" -> return OptionalGene(tableType, BooleanGene(tableType)) "long" -> return OptionalGene(tableType, LongGene(tableType)) "date" -> return OptionalGene(tableType, DateGene(tableType)) "id" -> return OptionalGene(tableType, StringGene(tableType)) else -> return OptionalGene(tableType, StringGene(tableType)) } } private fun createEnumGene( tableType: String, enumValues: List<String>, ): Gene { return OptionalGene(tableType, EnumGene(tableType, enumValues)) } }
lgpl-3.0
f5f62a82793e4f1df22e33d8c84d2e49
40.620035
216
0.553075
5.371823
false
false
false
false
johan12345/opacclient
opacclient/libopac/src/main/java/de/geeksfactory/opacclient/apis/Arena.kt
1
18779
package de.geeksfactory.opacclient.apis import de.geeksfactory.opacclient.i18n.StringProvider import de.geeksfactory.opacclient.networking.HttpClientFactory import de.geeksfactory.opacclient.networking.NotReachableException import de.geeksfactory.opacclient.objects.* import de.geeksfactory.opacclient.searchfields.DropdownSearchField import de.geeksfactory.opacclient.searchfields.SearchField import de.geeksfactory.opacclient.searchfields.SearchQuery import de.geeksfactory.opacclient.searchfields.TextSearchField import de.geeksfactory.opacclient.utils.get import de.geeksfactory.opacclient.utils.html import de.geeksfactory.opacclient.utils.text import okhttp3.FormBody import org.joda.time.format.DateTimeFormat import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.net.URL /** * OpacApi implementation for the Arena OPAC developed by Axiell. https://www.axiell.de/arena/ * * @author Johan von Forstner, January 2019 */ open class Arena : OkHttpBaseApi() { protected lateinit var opacUrl: String protected val ENCODING = "UTF-8" protected var searchDoc: Document? = null override fun init(library: Library, factory: HttpClientFactory) { super.init(library, factory) opacUrl = library.data.getString("baseurl") } override fun parseSearchFields(): List<SearchField> { val doc = httpGet("$opacUrl/extended-search", ENCODING).html // text fields val textFields = doc.select(".arena-extended-search-original-field-container") .map { container -> TextSearchField().apply { id = container.select("input").first()["name"] displayName = container.select("span, label").first().text() } } // dropdown fields val dropdownFields = listOf("category", "media-class", "target-audience", "accession-date").map { doc.select(".arena-extended-search-$it-container") }.filter { it.size > 0 }.map { it.first() }.map { container -> DropdownSearchField().apply { val select = container.select("select").first() id = select["name"] displayName = container.select("label").first().text() val options = select.select("option").map { option -> DropdownSearchField.Option( option["value"], option.text) }.toMutableList() if (select.hasAttr("multiple")) { options.add(0, DropdownSearchField.Option("", "")) } dropdownValues = options } } // year field val yearFields = listOf("from", "to").map { doc.select(".arena-extended-search-publication-year-$it-container") }.filter { it.size > 0 }.map { it.first() }.mapIndexed {i, container -> TextSearchField().apply { id = container.select("input").first()["name"] displayName = container.parent().child(0).ownText() hint = container.select("label").first().text() isHalfWidth = i == 1 } } return textFields + dropdownFields + yearFields } override fun search(query: MutableList<SearchQuery>): SearchRequestResult { val searchForm = httpGet("$opacUrl/extended-search", ENCODING).html .select(".arena-extended-search-original").first() val formData = FormBody.Builder().apply { searchForm.select("input[type=hidden]").forEach { hidden -> add(hidden["name"], hidden["value"]) } val submit = searchForm.select("input[type=submit]").first() add(submit["name"], submit["value"]) query.forEach { q -> add(q.key, q.value) } }.build() val doc = httpPost(searchForm["action"], formData, ENCODING).html return parseSearch(doc) } protected open fun parseSearch(doc: Document, page: Int = 1): SearchRequestResult { searchDoc = doc val countRegex = Regex("\\d+-\\d+ (?:von|of|av) (\\d+)") val count = countRegex.find(doc.select(".arena-record-counter").text)?.groups?.get(1)?.value?.toInt() ?: 0 val coverAjaxUrls = getAjaxUrls(doc) val results = doc.select(".arena-record").map{ record -> parseSearchResult(record, coverAjaxUrls) } return SearchRequestResult(results, count, page) } protected fun parseSearchResult(record: Element, coverAjaxUrls: Map<String, String>): SearchResult { return SearchResult().apply { val title = record.select(".arena-record-title").text val year = record.select(".arena-record-year .arena-value").first()?.text val author = record.select(".arena-record-author .arena-value").map { it.text }.joinToString(", ") innerhtml = "<b>$title</b><br>$author ${year ?: ""}" id = record.select(".arena-record-id").first().text cover = getCover(record, coverAjaxUrls) } } internal fun getCover(record: Element, coverAjaxUrls: Map<String, String>? = null): String? { val coverHolder = record.select(".arena-record-cover").first() if (coverHolder != null) { val id = coverHolder["id"] if (coverAjaxUrls != null && coverAjaxUrls.containsKey(id)) { // get cover via ajax val xml = httpGet(coverAjaxUrls[id], ENCODING) val url = Regex("<img src=\"([^\"]+)").find(xml)?.groups?.get(1) ?.value?.replace("&amp;", "&") return if (url != null) URL(URL(opacUrl), url).toString() else null } else if (coverHolder.select("img:not([src*=indicator.gif])").size > 0) { // cover is included as img tag val url = coverHolder.select("img:not([src*=indicator.gif])").first()["src"] return URL(URL(opacUrl), url).toString() } } return null } internal fun getAjaxUrls(doc: Document): Map<String, String> { val scripts = doc.select("script").map { it.html() } val regex = Regex("wicketAjaxGet\\(['\"]([^\"']+)[\"'](?:.|[\\r\\n])*Wicket\\.\\\$\\([\"']([^\"']+)[\"']\\)\\s*!=\\s*null;?\\}\\.bind\\(this\\)\\)") val map = HashMap<String, String>() scripts.forEach { script -> regex.findAll(script).forEach { match -> val url = match.groups[1]!!.value.replace("\\x3d", "=").replace("\\x26", "&") map[match.groups[2]!!.value] = url } } return map } override fun filterResults(filter: Filter, option: Filter.Option): SearchRequestResult { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun searchGetPage(page: Int): SearchRequestResult { val doc = searchDoc ?: throw NotReachableException() val pageLinks = doc.select(".arena-record-navigation").first() .select(".arena-page-number > a, .arena-page-number > span") // determining the link to get to the right page is not straightforward, so we try to find // the link to the right page. val from = Integer.valueOf(pageLinks.first().text()) val to = Integer.valueOf(pageLinks.last().text()) val linkToClick: Element val willBeCorrectPage: Boolean if (page < from) { linkToClick = pageLinks.first() willBeCorrectPage = false } else if (page > to) { linkToClick = pageLinks.last() willBeCorrectPage = false } else { linkToClick = pageLinks.get(page - from) willBeCorrectPage = true } if (linkToClick.tagName() == "span") { // we are trying to get the page we are already on return parseSearch(doc, page) } val newDoc = httpGet(linkToClick["href"], ENCODING).html if (willBeCorrectPage) { return parseSearch(newDoc, page) } else { searchDoc = newDoc return searchGetPage(page) } } override fun getResultById(id: String, homebranch: String?): DetailedItem { val url = getUrl(id) val doc = httpGet(url, ENCODING).html doc.setBaseUri(url) return parseDetail(doc) } private fun parseDetail(doc: Document): DetailedItem { val urls = getAjaxUrls(doc).filterKeys { it.contains("crDetailWicket") } val holdingsUrl = if (urls.isNotEmpty()) urls.values.iterator().next() else null val holdingsDoc = if (holdingsUrl != null) { val ajaxResp = httpGet(URL(URL(opacUrl), holdingsUrl).toString(), ENCODING).html ajaxResp.select("component").first().text.html } else null return DetailedItem().apply { title = doc.select(".arena-detail-title").text doc.select(".arena-catalogue-detail .arena-field").forEach { field -> addDetail(Detail(field.text, field.nextElementSibling().text)) } doc.select(".arena-detail-link > a").forEach { link -> val href = link["href"] if (href.contains("onleihe") && href.contains("mediaInfo")) { addDetail(Detail(link.text(), href)); } } id = doc.select(".arena-record-id").first().text cover = doc.select(".arena-detail-cover img").first()?.absUrl("href") copies = holdingsDoc?.select(".arena-row")?.map { row -> Copy().apply { department = row.select(".arena-holding-department .arena-value").text shelfmark = row.select(".arena-holding-shelf-mark .arena-value").text status = row.select(".arena-availability-right").text } } ?: emptyList() isReservable = doc.select(".arena-reservation-button-login, a[href*=reservationButton]").first() != null reservation_info = if (isReservable) id else null } } override fun getResult(position: Int): DetailedItem? { return null } override fun reservation(item: DetailedItem, account: Account, useraction: Int, selection: String?): OpacApi.ReservationResult { login(account) val details = httpGet(getUrl(item.id), ENCODING).html val url = details.select(" a[href*=reservationButton]").first()?.attr("href") val doc = httpGet(url, ENCODING).html val form = doc.select("form[action*=reservationForm]").first() if (selection == null) { return OpacApi.ReservationResult(OpacApi.MultiStepResult.Status.SELECTION_NEEDED).apply { actionIdentifier = OpacApi.ReservationResult.ACTION_BRANCH this.selection = form.select(".arena-select").first().select("option").map { option -> hashMapOf( "key" to option["value"], "value" to option.text ) } } } val formData = FormBody.Builder() form.select("input[type=hidden]").forEach { input -> formData.add(input["name"], input["value"]) } formData.add("branch", selection) val resultDoc = httpPost(form["action"], formData.build(), ENCODING).html val errorPanel = resultDoc.select(".feedbackPanelWARNING").first() if (errorPanel != null) { return OpacApi.ReservationResult(OpacApi.MultiStepResult.Status.ERROR, errorPanel.text) } else { return OpacApi.ReservationResult(OpacApi.MultiStepResult.Status.OK) } } override fun prolong(media: String, account: Account, useraction: Int, selection: String?): OpacApi.ProlongResult { login(account) val loansDoc = httpGet("$opacUrl/protected/loans", ENCODING).html val internalError = OpacApi.ProlongResult(OpacApi.MultiStepResult.Status.ERROR, stringProvider.getString(StringProvider.INTERNAL_ERROR)) val row = loansDoc.select("tr:has(.arena-record-id:contains($media)").first() ?: return internalError val js = row.select(".arena-renewal-status input[type=submit]").first()["onclick"] val url = Regex("window\\.location\\.href='([^']+)'").find(js)?.groups?.get(1)?.value ?: return internalError val doc = httpGet(url, ENCODING).html val error = doc.select(".arena-internal-error-description-value").first() return if (error != null) { OpacApi.ProlongResult(OpacApi.MultiStepResult.Status.ERROR, error.text) } else if (doc.select(".arena-renewal-fail-table").size > 0) { OpacApi.ProlongResult(OpacApi.MultiStepResult.Status.ERROR, stringProvider.getString(StringProvider.PROLONGING_IMPOSSIBLE)) } else { OpacApi.ProlongResult(OpacApi.MultiStepResult.Status.OK) } } override fun prolongAll(account: Account, useraction: Int, selection: String?): OpacApi.ProlongAllResult { // it seems that this does not work without JavaScript, and I couldn't find out why. return OpacApi.ProlongAllResult(OpacApi.MultiStepResult.Status.ERROR) } override fun cancel(media: String, account: Account, useraction: Int, selection: String?): OpacApi.CancelResult { val resDoc = httpGet("$opacUrl/protected/reservations", ENCODING).html val internalError = OpacApi.CancelResult(OpacApi.MultiStepResult.Status.ERROR, stringProvider.getString(StringProvider.INTERNAL_ERROR)) val record = resDoc.select(".arena-record-container:has(.arena-record-id:contains($media)") .first() ?: return internalError // find the URL that needs to be called to select the item val url = record.select(".arena-select-item a").first()?.attr("href") val selectedDoc = httpGet(url, ENCODING).html val cancelUrl = selectedDoc.select(".arena-delete").first().attr("href") val resultDoc = httpGet(cancelUrl, ENCODING).html val errorPanel = resultDoc.select(".feedbackPanelWARNING").first() if (errorPanel != null) { return OpacApi.CancelResult(OpacApi.MultiStepResult.Status.ERROR, errorPanel.text) } else { return OpacApi.CancelResult(OpacApi.MultiStepResult.Status.OK) } } override fun account(account: Account): AccountData { login(account) val profileDoc = httpGet("$opacUrl/protected/profile", ENCODING).html val feesDoc = httpGet("$opacUrl/protected/debts", ENCODING).html val loansDoc = httpGet("$opacUrl/protected/loans", ENCODING).html val reservationsDoc = httpGet("$opacUrl/protected/reservations", ENCODING).html return AccountData(account.id).apply { pendingFees = parseFees(feesDoc) lent = parseLent(loansDoc) reservations = parseReservations(reservationsDoc) //validUntil = parseValidUntil(profileDoc) } } internal fun parseReservations(doc: Document): List<ReservedItem> { return doc.select(".arena-record").map { record -> ReservedItem().apply { id = record.select(".arena-record-id").first().text title = record.select(".arena-record-title").first()?.text author = record.select(".arena-record-author .arena-value") .map { it.text }.joinToString(", ") format = record.select(".arena-record-media .arena-value").first()?.text cover = getCover(record) branch = record.select(".arena-record-branch .arena-value").first()?.text status = record.select(".arena-result-info .arena-value").first()?.text cancelData = id } } } internal fun parseLent(doc: Document): List<LentItem> { val df = DateTimeFormat.forPattern("dd.MM.yy") return doc.select("#loansTable > tbody > tr").map { tr -> LentItem().apply { id = tr.select(".arena-record-id").first().text title = tr.select(".arena-record-title").first()?.text author = tr.select(".arena-record-author .arena-value") .map { it.text }.joinToString(", ") format = tr.select(".arena-record-media .arena-value").first()?.text lendingBranch = tr.select(".arena-renewal-branch .arena-value").first()?.text deadline = df.parseLocalDate(tr.select(".arena-renewal-date-value").first().text) isRenewable = tr.hasClass("arena-renewal-true") prolongData = id status = tr.select(".arena-renewal-status-message").first()?.text } } } internal fun parseFees(feesDoc: Document): String? { return feesDoc.select(".arena-charges-total-debt span:eq(1)").first()?.text } /*internal fun parseValidUntil(profileDoc: Document): String? { return profileDoc.select(".arena-charges-total-debt span:eq(2)").first()?.text }*/ override fun checkAccountData(account: Account) { login(account) } fun login(account: Account) { val loginForm = httpGet("$opacUrl/welcome", ENCODING).html .select(".arena-patron-signin form").first() ?: return val formData = FormBody.Builder() .add("openTextUsernameContainer:openTextUsername", account.name) .add("textPassword", account.password) loginForm.select("input[type=hidden]").forEach { input -> formData.add(input["name"], input["value"]) } val doc = httpPost(loginForm["action"], formData.build(), ENCODING).html val errorPanel = doc.select(".feedbackPanelWARNING").first() if (errorPanel != null) { throw OpacApi.OpacErrorException(errorPanel.text) } } override fun getShareUrl(id: String, title: String?): String { return getUrl(id) } private fun getUrl(id: String) = "$opacUrl/results?p_p_id=searchResult_WAR_arenaportlets" + "&p_r_p_arena_urn%3Aarena_search_item_id=$id" override fun getSupportFlags(): Int { return OpacApi.SUPPORT_FLAG_ENDLESS_SCROLLING } override fun getSupportedLanguages(): MutableSet<String>? { return null } override fun setLanguage(language: String) { } }
mit
ae5e8a0b89802cf2fd39e4cff6edbb5c
42.878505
156
0.59886
4.254418
false
false
false
false
tommyettinger/SquidSetup
src/main/kotlin/com/github/czyzby/setup/views/advanced.kt
1
3050
package com.github.czyzby.setup.views import com.badlogic.gdx.scenes.scene2d.ui.Button import com.github.czyzby.kiwi.util.common.Strings import com.github.czyzby.lml.annotation.LmlActor import com.kotcrab.vis.ui.widget.VisTextField import com.kotcrab.vis.ui.widget.spinner.IntSpinnerModel import com.kotcrab.vis.ui.widget.spinner.Spinner /** * Stores data from "advanced" tab. * @author MJ */ class AdvancedData { @LmlActor("version") private lateinit var versionField: VisTextField @LmlActor("javaVersion") private lateinit var javaVersionField: Spinner @LmlActor("sdkVersion") private lateinit var sdkVersionField: Spinner @LmlActor("androidPluginVersion") private lateinit var androidPluginVersionField: VisTextField @LmlActor("robovmVersion") private lateinit var robovmVersionField: VisTextField @LmlActor("gwtPlugin") private lateinit var gwtPluginVersionField: VisTextField @LmlActor("serverJavaVersion") private lateinit var serverJavaVersionField: Spinner @LmlActor("desktopJavaVersion") private lateinit var desktopJavaVersionField: Spinner @LmlActor("generateSkin") private lateinit var generateSkinButton: Button @LmlActor("generateReadme") private lateinit var generateReadmeButton: Button @LmlActor("gradleTasks") private lateinit var gradleTasksField: VisTextField val version: String get() = versionField.text val gdxVersion: String get() = "1.10.0" val javaVersion: String get() = if(javaVersionField.model.text.length == 1) "1." + javaVersionField.model.text else javaVersionField.model.text var androidSdkVersion: String get() = sdkVersionField.model.text set(value) { val model = sdkVersionField.model as IntSpinnerModel model.value = value.toInt() sdkVersionField.notifyValueChanged(false) } val androidPluginVersion: String get() = androidPluginVersionField.text val robovmVersion: String get() = robovmVersionField.text val gwtVersion: String get() = "2.9.0" val gwtPluginVersion: String get() = gwtPluginVersionField.text val serverJavaVersion: String get() = if(serverJavaVersionField.model.text.length == 1) "1." + serverJavaVersionField.model.text else serverJavaVersionField.model.text val desktopJavaVersion: String get() = if(desktopJavaVersionField.model.text.length == 1) "1." + desktopJavaVersionField.model.text else desktopJavaVersionField.model.text val generateSkin: Boolean get() = generateSkinButton.isChecked val generateReadme: Boolean get() = generateReadmeButton.isChecked val addGradleWrapper: Boolean get() = true val gradleTasks: List<String> get() = if (gradleTasksField.isEmpty) listOf() else gradleTasksField.text.split(Regex(Strings.WHITESPACE_SPLITTER_REGEX)).filter { it.isNotBlank() } fun forceSkinGeneration() { generateSkinButton.isChecked = true } }
apache-2.0
7836997e5c2102a05f30c39203742a16
36.654321
109
0.722295
4.394813
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/firstball/AcesStatistic.kt
1
1162
package ca.josephroque.bowlingcompanion.statistics.impl.firstball import android.os.Parcel import android.os.Parcelable import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator import ca.josephroque.bowlingcompanion.games.lane.Deck import ca.josephroque.bowlingcompanion.games.lane.isAce /** * Copyright (C) 2018 Joseph Roque * * Percentage of shots which are aces. */ class AcesStatistic(numerator: Int = 0, denominator: Int = 0) : FirstBallStatistic(numerator, denominator) { // MARK: Modifiers /** @Override */ override fun isModifiedBy(deck: Deck) = deck.isAce override val titleId = Id override val id = Id.toLong() // MARK: Parcelable companion object { /** Creator, required by [Parcelable]. */ @Suppress("unused") @JvmField val CREATOR = parcelableCreator(::AcesStatistic) /** Unique ID for the statistic. */ const val Id = R.string.statistic_aces } /** * Construct this statistic from a [Parcel]. */ private constructor(p: Parcel): this(numerator = p.readInt(), denominator = p.readInt()) }
mit
070d3721268aad897fd75ad9547e6da7
28.05
108
0.701377
4.319703
false
false
false
false
AlekseyZhelo/LBM
LWJGL_APP/src/main/java/com/alekseyzhelo/lbm/gui/lwjgl/LauncherBoxWithSlidingLid.kt
1
4059
package com.alekseyzhelo.lbm.gui.lwjgl import com.alekseyzhelo.lbm.boundary.BoundaryType import com.alekseyzhelo.lbm.cli.CLISettings import com.alekseyzhelo.lbm.cli.collectArguments import com.alekseyzhelo.lbm.core.cell.CellD2Q9 import com.alekseyzhelo.lbm.functions.columnPressureWaveRho import com.alekseyzhelo.lbm.functions.multiplePressureWaveRho import com.alekseyzhelo.lbm.functions.rowPressureWaveRho import com.alekseyzhelo.lbm.gui.lwjgl.cli.CMSettings import com.alekseyzhelo.lbm.gui.lwjgl.render.GL30Renderer import com.alekseyzhelo.lbm.statistics.LatticeStatistics import com.alekseyzhelo.lbm.util.lattice.createBoundaries import com.alekseyzhelo.lbm.util.lattice.setupLattice import com.alekseyzhelo.lbm.util.maxVelocityNorm import com.alekseyzhelo.lbm.util.timing.printExecutionTime /** * @author Aleks on 18-05-2016. */ fun main(args: Array<String>) { val cli = CLISettings() val cm = CMSettings() collectArguments("LWJGL_LBM.jar", arrayOf(cli, cm), args) val boundaries = createBoundaries( BoundaryType.NO_SLIP, // left BoundaryType.NO_SLIP, // top BoundaryType.NO_SLIP, // right BoundaryType.NO_SLIP, // bottom // ZHOU_HE_UX does not work :(((( tParam = Pair(-0.0, doubleArrayOf(0.40, 0.0)), //0.61, //0.01, bParam = Pair(-0.0, doubleArrayOf(0.10, 0.0)) ) val inletUX = 0.10 val density = 1.0 // val boundaries = createBoundaries( // BoundaryType.INLET, // left // BoundaryType.NO_SLIP, // top // BoundaryType.OUTLET, // right // BoundaryType.NO_SLIP, // bottom // ZHOU_HE_UX does not work :(((( // lParam = Pair(density, doubleArrayOf(inletUX, 0.0)), //0.61, //0.01, // tParam = Pair(density, doubleArrayOf(-0.1, 0.0)), // rParam = Pair(inletUX, doubleArrayOf(-0.0, -0.0)), // bParam = Pair(density, doubleArrayOf(-0.1, 0.0)) // ) val force = 0.00001 val lattice = setupLattice( cli, boundaries ) //, ConstantXForce_BGK_D2Q9(cli.omega, force), boundaries) // lattice.iniEquilibrium(multiplePressureWaveRho(cli.lx, cli.ly, 4, 4, 4.5), doubleArrayOf(0.0, 0.0)) // lattice.iniEquilibrium(squareEmptyRho(cli.lx, cli.ly, 4, 4, 0.1), doubleArrayOf(0.0, 0.0)) lattice.iniEquilibrium(columnPressureWaveRho(cli.lx, cli.ly, 100, 10.5), doubleArrayOf(0.0, 0.0)) // lattice.iniEquilibrium(rowPressureWaveRho(cli.lx, cli.ly, 100, 1.05), doubleArrayOf(0.0, 0.0)) // lattice.iniEquilibrium(density, doubleArrayOf(0.0, 0.0)) // lattice.iniEquilibrium(density, doubleArrayOf(inletUX, 0.0)) val printLine = { x: Any -> if (cli.verbose) println(x) } val renderer = GL30Renderer<CellD2Q9>(cli, cm, 512, 512) renderer.initialize() renderer.frame(lattice.cells) printLine("Total density: ${lattice.totalDensity()}") if (cli.stop) readLine() val noCollisions = cli.noCollisions var time = 0 val start = System.currentTimeMillis() while (time++ < cli.time && !renderer.windowShouldClose()) { lattice.stream() if (noCollisions) lattice.swapCellBuffers() else lattice.bulkCollideParallel(0, cli.lx - 1, 0, cli.ly - 1) if (time == 1) { LatticeStatistics.initVerbose(lattice) } // if (time > 20000) { renderer.frame(lattice.cells) LatticeStatistics.reset() // } else if (time % 1000 == 0) { // println(time) // } if (time % 100 == 0) { printLine("time: $time, max velocity: ${lattice.maxVelocityNorm()}") printLine("Total density: ${lattice.totalDensity()}") } // if(time == 5000) { // val field = sampleVectorField(lattice) // field.toDoubleArrFile("vectorField5000_works.txt") // break // } } time-- val end = System.currentTimeMillis() printExecutionTime(end, start, time) println("Executed $time LBM steps.") printLine("Total density: ${lattice.totalDensity()}") renderer.terminate() }
apache-2.0
43171446e15fa69c49fe0dddcaeb5d49
36.583333
105
0.652624
3.388147
false
false
false
false
lena0204/Plattenspieler
app/src/main/java/com/lk/plattenspieler/main/MainActivityNew.kt
1
9934
package com.lk.plattenspieler.main import android.app.ActionBar import android.content.* import android.content.pm.PackageManager import android.content.res.ColorStateList import android.media.AudioManager import android.media.browse.MediaBrowser import android.media.session.PlaybackState import android.os.* import android.util.Log import android.view.* import android.widget.TextView import android.widget.Toast import androidx.annotation.RequiresApi import androidx.core.os.bundleOf import androidx.fragment.app.* import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.preference.PreferenceManager import com.lk.musicservicelibrary.models.MusicList import com.lk.musicservicelibrary.utils.SharedPrefsWrapper import com.lk.plattenspieler.R import com.lk.plattenspieler.fragments.* import com.lk.plattenspieler.musicbrowser.* import com.lk.plattenspieler.observables.* import com.lk.plattenspieler.utils.* import kotlinx.android.synthetic.main.activity_main.* /** * Erstellt von Lena am 12.05.18. * Hauptklasse, verwaltet Menü, Observer, Berechtigungen und den MusicClient */ class MainActivityNew : FragmentActivity(), Observer<Any>, LyricsAddingDialog.OnSaveLyrics { // TODO fix backup and restore of playing list // TODO tidy up logs // TODO Duration is missing (partly?) when loading form backup companion object { const val PREF_DESIGN = "design" // not used currently -- const val PREF_LYRICS = "lyrics" fun isVersionGreaterThan(versionCode: Int): Boolean = Build.VERSION.SDK_INT >= versionCode } private val TAG = "com.lk.pl-MainActNew" private var design = EnumTheme.THEME_LIGHT private var menu: Menu? = null private var controllerAccess: ControllerAccess? = null private var albumsSet = false private lateinit var sharedPreferences: SharedPreferences private lateinit var permissionRequester: PermissionRequester private lateinit var mediaViewModel: MediaViewModel private lateinit var playbackViewModel: PlaybackViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) permissionRequester = PermissionRequester(this) changeDesign() setContentView(R.layout.activity_main) setupForMusicHandling() finishSetupIfPermissionGranted() } private fun changeDesign(){ sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this) design = ThemeChanger.readThemeFromPreferences(sharedPreferences) ThemeChanger.setThemeAfterCreatingActivity(this, design) if(canMakeAdaptionsToLineageDesign(design)) { changeActionbarTitleColor() } } private fun canMakeAdaptionsToLineageDesign(design: EnumTheme): Boolean = (design == EnumTheme.THEME_LINEAGE && isVersionGreaterThan(Build.VERSION_CODES.M) && permissionRequester.requestDesignReadPermission()) private fun changeActionbarTitleColor(){ val tv = View.inflate(this, R.layout.action_bar_custom, null) as TextView val color = ThemeChanger.getAccentColorLinage(this) if (color != 0) { tv.setTextColor(ColorStateList.valueOf(color)) } actionBar?.customView = tv actionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM } private fun setupForMusicHandling(){ mediaViewModel = ViewModelProviders.of(this).get(MediaViewModel::class.java) mediaViewModel.setObserversToAll(this, this) playbackViewModel = ViewModelProviders.of(this).get(PlaybackViewModel::class.java) playbackViewModel.setObserverToPlaybackState(this, this) playbackViewModel.setObserverToShowBar(this, this) controllerAccess = ControllerAccess(this) this.volumeControlStream = AudioManager.STREAM_MUSIC setupMusicBar() } private fun setupMusicBar(){ // TODO hide bar necessary supportFragmentManager.commit { replace(R.id.fl_main_bar, MusicBarFragment(), "MusicBarFragment") } val pf = PlayingFragment() fl_main_bar.setOnClickListener { if(!pf.isVisible){ supportFragmentManager.commit { addToBackStack(null) replace(R.id.fl_main_content, pf, "TAG_PLAYING") } } } } fun showBar() { fl_main_bar.visibility = View.VISIBLE } fun hideBar() { fl_main_bar.visibility = View.GONE } private fun finishSetupIfPermissionGranted(){ if(isVersionGreaterThan(Build.VERSION_CODES.M) && permissionRequester.checkReadPermission()) { controllerAccess?.completeSetup() } else if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { controllerAccess?.completeSetup() } } override fun onChanged(update: Any?){ if(update is MusicList) { when (update.getMediaType()) { MediaBrowser.MediaItem.FLAG_BROWSABLE -> showAlbums() MediaBrowser.MediaItem.FLAG_PLAYABLE -> showTitles() } } else if (update is PlaybackState && update.state == PlaybackState.STATE_STOPPED) { hideBar() // TODO Should also close PlayingFragment if open } else if(update is Boolean) { if(update) { showBar() } else { hideBar() } } } private fun showAlbums(){ supportFragmentManager.commit { replace(R.id.fl_main_content, AlbumFragment()) } } private fun showTitles(){ supportFragmentManager.commit { addToBackStack(null) replace(R.id.fl_main_content, AlbumDetailsFragment()) } } override fun onSaveLyrics(lyrics: String) { Log.v(TAG, "Lyrics schreiben, noch nicht korrekt implementiert") // PROBLEM_ seit Android 10 kein Schreiben möglich // LyricsAccess.writeLyrics(lyrics, playbackViewModel.getMetadata().path) } fun setDesignFromPref(design: EnumTheme){ controllerAccess?.applyTheme(design) } override fun onResume() { super.onResume() if(albumsSet) showAlbums() } override fun onDestroy() { super.onDestroy() Log.i(TAG, "onDestroy") controllerAccess?.clear() controllerAccess = null } // TODO einheitlich Design oder Theme benutzen im Code // Permissions @RequiresApi(23) override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when(requestCode){ PermissionRequester.PERMISSION_REQUEST_READ -> { if(isPermissionGranted(grantResults)) controllerAccess?.completeSetup() else showToast(R.string.toast_no_permission) } PermissionRequester.PERMISSION_REQUEST_WRITE -> { if(isPermissionGranted(grantResults)) // TODO weitermachen mit dialog anzeigen für lyrics else showToast(R.string.toast_no_permission_write) } PermissionRequester.PERMISSION_REQUEST_DESIGN -> { if(isPermissionGranted(grantResults)){ setDesignFromPref(EnumTheme.THEME_LINEAGE) } else { showToast(R.string.toast_no_permission_design) controllerAccess?.applyTheme(EnumTheme.THEME_LIGHT) } } } } private fun isPermissionGranted(grantResults: IntArray): Boolean = (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) private fun showToast(stringResource: Int) { Toast.makeText(this, stringResource, Toast.LENGTH_LONG).show() } // ------------- Menü ------------- override fun onPrepareOptionsMenu(menu: Menu?): Boolean { this.menu = menu // IDEA_ Lyrics hinzufügen nur anzeigen wenn PlayingFragment sichtbar ist menu?.findItem(R.id.menu_add_lyrics)?.isVisible = false return true } override fun onCreateOptionsMenu(pmenu: Menu?): Boolean { menuInflater.inflate(R.menu.options_menu_main, pmenu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId){ R.id.menu_settings -> launchPreferences() R.id.menu_shuffle_all -> { val action = ControllerAction(EnumActions.SHUFFLE_ALL) SharedPrefsWrapper.writeShuffle(this.applicationContext, true) playbackViewModel.callAction(action) } R.id.menu_remove_playing -> { val action = ControllerAction(EnumActions.STOP) playbackViewModel.callAction(action) } R.id.menu_add_lyrics -> controllerAccess?.addLyrics() } return super.onOptionsItemSelected(item) } private fun launchPreferences(){ val pf = PrefFragment() pf.arguments = prepareBundleForPrefFragment() supportFragmentManager.commit { addToBackStack(null) replace(R.id.fl_main_content, pf, "PrefFragment") } } private fun prepareBundleForPrefFragment(): Bundle { val losSupport = isVersionGreaterThan(Build.VERSION_CODES.O) && checkLineageSDK() return bundleOf("LOS" to losSupport) } private fun checkLineageSDK() : Boolean { val sdkInt = lineageos.os.Build.LINEAGE_VERSION.SDK_INT Log.d(TAG, "Lineage-Version: " + lineageos.os.Build.getNameForSDKInt(sdkInt)) return sdkInt >= lineageos.os.Build.LINEAGE_VERSION_CODES.ILAMA } }
gpl-3.0
1f2454caf572a5331389129c90022644
35.910781
119
0.657972
4.641889
false
false
false
false
RyotaMurohoshi/snippets
kotlin/kotlin_java_interpolator/src/main/kotlin/com/muhron/kotlin_java_interpolator/KotlinMain.kt
1
886
package com.muhron.kotlin_java_interpolator fun main(args: Array<String>) { val shortPrimitive = JavaPrimitives.getShortPrimitive() val shortWrapper = JavaPrimitives.getShortWrapper() val intPrimitive = JavaPrimitives.getIntPrimitive() val intWrapper = JavaPrimitives.getIntWrapper() val longPrimitive = JavaPrimitives.getLongPrimitive() val longWrapper = JavaPrimitives.getLongWrapper() val flotPrimitive = JavaPrimitives.getFloatPrimitive() val floatWrapper = JavaPrimitives.getFloatWrapper() val doublePrimitive = JavaPrimitives.getDoublePrimitive() val doubleWrapper = JavaPrimitives.getDoubleWrapper() val charPrimitive = JavaPrimitives.getCharPrimitive() val charWrapper = JavaPrimitives.getCharWrapper() val booleanPrimitive = JavaPrimitives.getBooleanPrimitive() val booleanWrapper = JavaPrimitives.getBooleanWrapper() }
mit
41bb5b0ead87df480494a428e244c80f
48.222222
63
0.788939
5.034091
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/utils/packtracker/FollowPackageButtonClickExecutor.kt
1
4844
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.packtracker import dev.kord.common.entity.ButtonStyle import net.perfectdreams.discordinteraktions.common.builder.message.actionRow import dev.kord.core.entity.User import net.perfectdreams.loritta.cinnamon.emotes.Emotes import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.utils.ComponentExecutorIds import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.declarations.PackageCommand import net.perfectdreams.loritta.cinnamon.discord.interactions.components.ButtonExecutorDeclaration import net.perfectdreams.loritta.cinnamon.discord.interactions.components.CinnamonButtonExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.components.ComponentContext import net.perfectdreams.loritta.cinnamon.discord.interactions.components.interactiveButton import net.perfectdreams.loritta.cinnamon.discord.utils.ComponentDataUtils import net.perfectdreams.loritta.cinnamon.discord.utils.correios.CorreiosClient import net.perfectdreams.loritta.cinnamon.discord.utils.correios.entities.CorreiosFoundObjeto import net.perfectdreams.loritta.cinnamon.discord.utils.correios.entities.CorreiosUnknownObjeto import net.perfectdreams.loritta.cinnamon.discord.utils.correios.entities.EventType import net.perfectdreams.loritta.cinnamon.pudding.data.UserId import net.perfectdreams.loritta.cinnamon.pudding.services.PackagesTrackingService class FollowPackageButtonClickExecutor( loritta: LorittaBot, val correios: CorreiosClient ) : CinnamonButtonExecutor(loritta) { companion object : ButtonExecutorDeclaration(ComponentExecutorIds.FOLLOW_PACKAGE_BUTTON_EXECUTOR) override suspend fun onClick(user: User, context: ComponentContext) { context.deferUpdateMessage() val decoded = context.decodeDataFromComponentAndRequireUserToMatch<FollowPackageData>() // Check if the package is already delivered and, if it is, don't allow the user to track it! val correiosResponse = correios.getPackageInfo(decoded.trackingId) when (val firstObject = correiosResponse.objeto.first()) { is CorreiosFoundObjeto -> { // Some Correios' packages are super wonky and while they are marked as delivered, they have duplicate events "package delievered to recipient" events (See: AA123456785BR) if (firstObject.events.any { it.type == EventType.PackageDeliveredToRecipient }) context.failEphemerally( context.i18nContext.get(PackageCommand.I18N_PREFIX.Track.FollowPackage.PackageAlreadyDelivered), Emotes.LoriSob ) try { loritta.pudding.packagesTracking.trackCorreiosPackage(UserId(user.id.value), decoded.trackingId) context.updateMessage { actionRow { interactiveButton( ButtonStyle.Primary, context.i18nContext.get(PackageCommand.I18N_PREFIX.Track.UnfollowPackageUpdates), UnfollowPackageButtonClickExecutor, ComponentDataUtils.encode( UnfollowPackageData( context.user.id, decoded.trackingId ) ) ) } } context.sendEphemeralReply( context.i18nContext.get(PackageCommand.I18N_PREFIX.Track.FollowPackage.YouAreNowFollowingThePackage(decoded.trackingId, loritta.commandMentions.packageList)), Emotes.LoriSunglasses ) } catch (e: PackagesTrackingService.UserIsAlreadyTrackingPackageException) { context.failEphemerally( context.i18nContext.get(PackageCommand.I18N_PREFIX.Track.FollowPackage.YouAreAlreadyFollowingThePackage), Emotes.LoriSob ) } catch (e: PackagesTrackingService.UserIsAlreadyTrackingTooManyPackagesException) { context.failEphemerally( context.i18nContext.get(PackageCommand.I18N_PREFIX.Track.FollowPackage.YouAreAlreadyFollowingTooManyPackages), Emotes.LoriSob ) } } is CorreiosUnknownObjeto -> context.failEphemerally( context.i18nContext.get(PackageCommand.I18N_PREFIX.ObjectNotFoundCorreios), Emotes.LoriSob ) } } }
agpl-3.0
f57e7aed03cf6c60a051cb66b53c5b2d
54.689655
187
0.669694
5.436588
false
false
false
false
izumin5210/Sunazuri
app/src/test/kotlin/info/izumin/android/sunazuri/infrastructure/dao/AccessTokenDaoTest.kt
1
1713
package info.izumin.android.sunazuri.infrastructure.dao import info.izumin.android.sunazuri.infrastructure.entity.AccessTokenEntity import info.izumin.android.sunazuri.infrastructure.mock.DataFactory import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricGradleTestRunner import org.robolectric.RuntimeEnvironment import kotlin.test.expect /** * Created by izumin on 5/21/2016 AD. */ @RunWith(RobolectricGradleTestRunner::class) class AccessTokenDaoTest { val context = RuntimeEnvironment.application.applicationContext lateinit var orma: OrmaProvider lateinit var dao: AccessTokenDao lateinit var token: AccessTokenEntity @Before fun setUp() { orma = OrmaProvider(context, null) dao = AccessTokenDao(orma) token = DataFactory.createAccessTokenEntity() } @Test fun testInsert() { dao.upsert(token) expect(1, { orma.db.selectFromAuthorizedUserEntity().count() }) expect(1, { orma.db.selectFromAccessTokenEntity().count() }) expect(1, { orma.db.selectFromAccessTokenEntity().userEq(token.user).count() }) } @Test fun testUpdate() { dao.upsert(token) token.accessToken = "newtesttoken" token.user.name = "new test user" dao.upsert(token) expect(1, { orma.db.selectFromAuthorizedUserEntity().count() }) expect(1, { orma.db.selectFromAccessTokenEntity().count() }) expect("newtesttoken", { orma.db.selectFromAccessTokenEntity().userEq(token.user).value().accessToken }) expect("new test user", { orma.db.selectFromAuthorizedUserEntity().idEq(token.user.id).value().name }) } }
apache-2.0
e92c009f82228daab1aa5073e0d29606
30.740741
112
0.709866
4.078571
false
true
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/appointment/gcal/repository.kt
1
7381
package at.cpickl.gadsu.appointment.gcal import at.cpickl.gadsu.service.LOG import com.google.api.client.googleapis.json.GoogleJsonResponseException import com.google.api.services.calendar.Calendar import com.google.api.services.calendar.model.Event import org.apache.http.HttpStatus import org.joda.time.DateTime import org.slf4j.LoggerFactory private val XPROP_GADSU_ID = "GADSU_ID" private val XPROP_CLIENT_ID = "CLIENT_ID" data class GCalEvent( val id: String?, /** private extended property*/ val gadsuId: String?, /** private extended property*/ val clientId: String?, /** Title of event. */ val summary: String, /** Note field. */ val description: String, val start: org.joda.time.DateTime, val end: org.joda.time.DateTime, val url: String? ) { companion object {} // for test extensions } data class GCalUpdateEvent( val id: String, /** private extended property*/ val gadsuId: String, /** private extended property*/ val clientId: String, val summary: String, val description: String, val start: org.joda.time.DateTime, val end: org.joda.time.DateTime ) { companion object {} // for extensions fun updateFields(gevent: Event) { gevent .setSummary(summary) .setDescription(description) .setStart(start.toGEventDateTime()) .setEnd(end.toGEventDateTime()) .setPrivateExtendedProperties(mapOf(XPROP_GADSU_ID to gadsuId, XPROP_CLIENT_ID to clientId)) } } interface GCalRepository { val isOnline: Boolean fun listEvents(start: DateTime, end: DateTime): List<GCalEvent> /** * @return the GCal event ID if was saved, null otherwise (offline or GCal not enabled) */ fun createEvent(gCalEvent: GCalEvent): GCalEventMeta? /** * Even if the event was in the meanwhile deleted at google, this goes still ok. */ fun updateEvent(gCalEvent: GCalUpdateEvent) fun deleteEvent(eventId: String) } object OfflineGCalRepository : GCalRepository { private val log = LOG(javaClass) override val isOnline = false override fun listEvents(start: DateTime, end: DateTime): List<GCalEvent> { log.debug("listEvents() ... no-op as offline") return emptyList() } override fun createEvent(gCalEvent: GCalEvent): GCalEventMeta? { log.debug("createEvent() ... no-op as offline") return null } override fun updateEvent(gCalEvent: GCalUpdateEvent) { log.debug("updateEvent() ... no-op as offline") } override fun deleteEvent(eventId: String) { log.debug("deleteEvent() ... no-op as offline") } } private val LOG_Event = LoggerFactory.getLogger(Event::class.java)!! fun Event.toGCalEvent(): GCalEvent { LOG_Event.trace("toGCalEvent() for: {}", this) return GCalEvent( id = this.id, gadsuId = getPrivateExtendedProperty(XPROP_GADSU_ID), clientId = getPrivateExtendedProperty(XPROP_CLIENT_ID), summary = this.summary ?: "", description = this.description ?: "", start = this.start.toDateTime(), end = this.end.toDateTime(), url = this.htmlLink // this.updated ) } private fun Event.getPrivateExtendedProperty(key: String): String? { return if (extendedProperties == null || extendedProperties.private == null) { null } else { val storedValue = extendedProperties.private[key] if (storedValue == null) { null } else { storedValue } } } class RealGCalRepository constructor( val calendar: Calendar, val calendarId: String ) : GCalRepository { private val log = LOG(javaClass) override val isOnline = true // https://developers.google.com/google-apps/calendar/create-events override fun createEvent(gCalEvent: GCalEvent): GCalEventMeta? { log.info("createEvent(gCalEvent={})", gCalEvent) val newEvent = gCalEvent.toEvent() val savedEvent = calendar.events().insert(calendarId, newEvent).execute() log.info("Saved event (ID=${savedEvent.id}): ${savedEvent.htmlLink}") return GCalEventMeta(savedEvent.id, savedEvent.htmlLink) } // https://developers.google.com/google-apps/calendar/v3/reference/events/list override fun listEvents(start: DateTime, end: DateTime): List<GCalEvent> { val events = calendar.events().list(calendarId).apply { // fields = "items(iCalUID,start,end,description,htmlLink,extendedProperties),summary" timeMin = start.toGDateTime() timeMax = end.toGDateTime() showDeleted = false // this strangely does NOT filter out events with status=cancelled }.execute() val nonCancelledEvents = events.items.filter { it.status == "confirmed" } log.debug("listEvents() returning ${nonCancelledEvents.size} events") return nonCancelledEvents.map(Event::toGCalEvent) } // https://developers.google.com/google-apps/calendar/v3/reference/events/update#examples override fun updateEvent(gCalEvent: GCalUpdateEvent) { log.info("updateEvent(gCalEvent={})", gCalEvent) val eventId = gCalEvent.id val updateEvent = calendar.events().get(calendarId, eventId).execute() if (updateEvent.status == "confirmed") { gCalEvent.updateFields(updateEvent) calendar.events().update(calendarId, eventId, updateEvent).execute() } // else: cancelled (meaning it was deleted in gcal) } // https://developers.google.com/google-apps/calendar/v3/reference/events/delete#examples override fun deleteEvent(eventId: String) { log.info("deleteEvent(eventId={})", eventId) try { calendar.events().delete(calendarId, eventId).execute() } catch(e: GoogleJsonResponseException) { if (e.statusCode == HttpStatus.SC_GONE) { // 410 log.warn("The event with ID ($eventId) was already deleted remotely.") } else { throw e } } } private fun GCalEvent.toEvent(): Event { return Event() // .setId(UUID.randomUUID().toString()) // possible to set custom ID (which will be the same as the AppointmentID) .setSummary(this.summary) .setDescription(this.description) .setStart(this.start.toGEventDateTime()) .setEnd(this.end.toGEventDateTime()) // .setAttendees() // .setReminders() .apply { val extendedProps = mutableMapOf<String, String>() if (gadsuId != null) { extendedProps.put(XPROP_GADSU_ID, gadsuId) } if (clientId != null) { extendedProps.put(XPROP_CLIENT_ID, clientId) } setPrivateExtendedProperties(extendedProps) } } } private fun Event.setPrivateExtendedProperties(properties: Map<String, String>) { extendedProperties = Event.ExtendedProperties().apply { private = properties } }
apache-2.0
eaabf72013bbff0fc5ab215eb29827b0
32.55
129
0.623357
4.308815
false
false
false
false
christophpickl/kpotpourri
common4k/src/test/kotlin/com/github/christophpickl/kpotpourri/common/web/web_test.kt
1
1445
package com.github.christophpickl.kpotpourri.common.web import com.github.christophpickl.kpotpourri.test4k.hamkrest_matcher.shouldMatchValue import org.testng.annotations.DataProvider import org.testng.annotations.Test @Test class WebTest { @DataProvider fun provideParsedUrls(): Array<Array<out Any>> = arrayOf( arrayOf("url", "url" to emptyMap<String, String>()), arrayOf("url?k=v", "url" to mapOf("k" to "v")), arrayOf("url?k1=v1&k2=v2", "url" to mapOf("k1" to "v1", "k2" to "v2")) ) @Test(dataProvider = "provideParsedUrls") fun `parseUrl - sunshine`(url: String, expected: Pair<String, Map<String, String>>) { parseUrl(url) shouldMatchValue expected } @DataProvider fun provideConstructUrls(): Array<Array<out Any>> = arrayOf( arrayOf("", emptyMap<String, String>(), ""), arrayOf("", mapOf("k" to "v"), "?k=v"), arrayOf("", mapOf("k1" to "v1", "k2" to "v2"), "?k1=v1&k2=v2"), arrayOf("", mapOf("key\"key" to "val=&val"), "?key%22key=val%3D%26val"), arrayOf("?x=1", mapOf("k" to "v"), "?x=1&k=v"), arrayOf("?x=1&y=2", mapOf("k" to "v"), "?x=1&y=2&k=v") ) @Test(dataProvider = "provideConstructUrls") fun `constructUrl - sunshine`(givenUrl: String, addParams: QueryParams, expectedUrl: String) { constructUrl(givenUrl, addParams) shouldMatchValue expectedUrl } }
apache-2.0
88e53a8b00f45edb53cd4618b02a94dc
39.138889
98
0.613841
3.416076
false
true
false
false
STUDIO-apps/GeoShare_Android
mobile/src/main/java/uk/co/appsbystudio/geoshare/base/adapters/FriendsNavAdapter.kt
1
5837
package uk.co.appsbystudio.geoshare.base.adapters import android.content.Context import android.content.SharedPreferences import android.support.constraint.ConstraintLayout import android.support.transition.TransitionManager import android.support.v4.content.res.ResourcesCompat import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.LinearLayout import android.widget.RelativeLayout import android.widget.TextView import com.google.firebase.auth.FirebaseAuth import de.hdodenhof.circleimageview.CircleImageView import uk.co.appsbystudio.geoshare.R import uk.co.appsbystudio.geoshare.utils.setProfilePicture class FriendsNavAdapter(private val context: Context, private val recyclerView: RecyclerView, private val friends: LinkedHashMap<String, String>, private val hasTracking: HashMap<String, Boolean>, private val callback: Callback) : RecyclerView.Adapter<FriendsNavAdapter.ViewHolder>() { private var sharedPreferences: SharedPreferences? = null private var showOnMapPreference: SharedPreferences? = null private var expandedPosition = -1 interface Callback { fun setMarkerHidden(friendId: String, visible: Boolean) fun findOnMapClicked(friendId: String) fun sendLocationDialog(name: String, friendId: String) fun stopSharing(friendId: String) } override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): FriendsNavAdapter.ViewHolder { val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.friends_nav_item, viewGroup, false) sharedPreferences = context.getSharedPreferences("tracking", Context.MODE_PRIVATE) showOnMapPreference = context.getSharedPreferences("showOnMap", Context.MODE_PRIVATE) return FriendsNavAdapter.ViewHolder(view) } override fun onBindViewHolder(holder: FriendsNavAdapter.ViewHolder, position: Int) { holder.friendName.text = friends.values.toTypedArray()[position] val uid = friends.keys.toTypedArray()[position] //Set friends profile picture holder.friendsPictures.setProfilePicture(uid, context.cacheDir.toString()) if (hasTracking.containsKey(uid) && hasTracking.getValue(uid)) { holder.trackingIndicator.visibility = View.VISIBLE } else { holder.trackingIndicator.visibility = View.GONE } val isExpanded = position == expandedPosition holder.expandedView.visibility = if (isExpanded) View.VISIBLE else View.GONE holder.nameItem.isActivated = isExpanded if (isExpanded) { holder.friendName.setTextColor(ResourcesCompat.getColor(context.resources, R.color.colorAccent, null)) } else { holder.friendName.setTextColor(ResourcesCompat.getColor(context.resources, android.R.color.white, null)) } holder.nameItem.setOnClickListener { expandedPosition = if (isExpanded) -1 else holder.adapterPosition TransitionManager.beginDelayedTransition(recyclerView) notifyDataSetChanged() } holder.showOnMapCheckBox.isChecked = showOnMapPreference!!.getBoolean(uid, true) holder.showOnMapLayout.setOnClickListener { holder.showOnMapCheckBox.isChecked = !holder.showOnMapCheckBox.isChecked } holder.showOnMapCheckBox.setOnCheckedChangeListener { compoundButton, b -> callback.setMarkerHidden(uid, b) } if (sharedPreferences!!.getBoolean(uid, false)) { holder.sendLocationText.setText(R.string.stop_sharing) holder.sendLocation.setOnClickListener { val user = FirebaseAuth.getInstance().currentUser if (user != null) { callback.stopSharing(uid) expandedPosition = if (isExpanded) -1 else holder.adapterPosition TransitionManager.beginDelayedTransition(recyclerView) notifyDataSetChanged() } } } else { holder.sendLocationText.setText(R.string.share_current_location) holder.sendLocation.setOnClickListener { callback.sendLocationDialog(holder.friendName.text as String, uid) expandedPosition = if (isExpanded) -1 else holder.adapterPosition TransitionManager.beginDelayedTransition(recyclerView) notifyDataSetChanged() } } holder.findLocation.setOnClickListener { callback.findOnMapClicked(uid) } } override fun getItemCount(): Int { return friends.size } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val friendName: TextView = itemView.findViewById(R.id.friend_name) val friendsPictures: CircleImageView = itemView.findViewById(R.id.friend_profile_image) val trackingIndicator: CircleImageView = itemView.findViewById(R.id.trackingIndicator) val sendLocation: RelativeLayout = itemView.findViewById(R.id.sendLocation) val sendLocationText: TextView = itemView.findViewById(R.id.sendLocationText) val findLocation: RelativeLayout = itemView.findViewById(R.id.findLocation) val findLocationText: TextView = itemView.findViewById(R.id.findLocationText) val nameItem: ConstraintLayout = itemView.findViewById(R.id.name_item) val showOnMapLayout: RelativeLayout = itemView.findViewById(R.id.showOnMapLayout) val showOnMapCheckBox: CheckBox = itemView.findViewById(R.id.showOnMapCheckBox) val expandedView: LinearLayout = itemView.findViewById(R.id.expandedView) } }
apache-2.0
e2a324d2aeb3946706d4987b71ea97a2
43.557252
126
0.709782
4.959218
false
false
false
false
world-federation-of-advertisers/common-jvm
src/main/kotlin/org/wfanet/measurement/common/db/r2dbc/postgres/testing/EmbeddedPostgresDatabaseProvider.kt
1
2863
/* * Copyright 2022 The Cross-Media Measurement Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wfanet.measurement.common.db.r2dbc.postgres.testing import com.opentable.db.postgres.embedded.DatabasePreparer import com.opentable.db.postgres.embedded.PreparedDbProvider import io.r2dbc.spi.ConnectionFactories import io.r2dbc.spi.ConnectionFactoryOptions import java.net.URI import java.nio.file.Path import java.util.logging.Level import javax.sql.DataSource import kotlinx.coroutines.reactive.awaitFirst import liquibase.Contexts import liquibase.Scope import org.wfanet.measurement.common.db.liquibase.Liquibase import org.wfanet.measurement.common.db.liquibase.setLogLevel import org.wfanet.measurement.common.db.r2dbc.postgres.PostgresDatabaseClient import org.wfanet.measurement.common.queryMap class EmbeddedPostgresDatabaseProvider(changelogPath: Path) { private val dbProvider: PreparedDbProvider = PreparedDbProvider.forPreparer(LiquibasePreparer(changelogPath)) fun createNewDatabase(): PostgresDatabaseClient { val jdbcConnectionUri = URI(dbProvider.createDatabase().removePrefix(JDBC_SCHEME_PREFIX)) val queryParams: Map<String, String> = jdbcConnectionUri.queryMap val connectionFactory = ConnectionFactories.get( ConnectionFactoryOptions.builder() .option(ConnectionFactoryOptions.DRIVER, "postgresql") .option(ConnectionFactoryOptions.HOST, jdbcConnectionUri.host) .option(ConnectionFactoryOptions.PORT, jdbcConnectionUri.port) .option(ConnectionFactoryOptions.USER, queryParams.getValue("user")) .option(ConnectionFactoryOptions.PASSWORD, queryParams.getValue("password")) .option(ConnectionFactoryOptions.DATABASE, jdbcConnectionUri.path.trimStart('/')) .build() ) return PostgresDatabaseClient { connectionFactory.create().awaitFirst() } } companion object { private const val JDBC_SCHEME_PREFIX = "jdbc:" } private class LiquibasePreparer(private val changelogPath: Path) : DatabasePreparer { override fun prepare(ds: DataSource) { ds.connection.use { connection -> Liquibase.fromPath(connection, changelogPath).use { liquibase -> Scope.getCurrentScope().setLogLevel(Level.FINE) liquibase.update(Contexts()) } } } } }
apache-2.0
ba16de0eb61eb169011cdd7f2206e6e0
39.323944
93
0.761788
4.452566
false
false
false
false
facebook/litho
litho-widget-kotlin/src/main/kotlin/com/facebook/litho/kotlin/widget/HorizontalScroll.kt
1
1728
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.litho.kotlin.widget import android.view.View import com.facebook.litho.Component import com.facebook.litho.Dimen import com.facebook.litho.ResourcesScope import com.facebook.litho.widget.HorizontalScroll import com.facebook.litho.widget.HorizontalScrollEventsController /** Builder function for creating [HorizontalScrollSpec] components. */ @Suppress("FunctionName") inline fun ResourcesScope.HorizontalScroll( initialScrollPosition: Dimen? = null, scrollbarEnabled: Boolean = true, fillViewport: Boolean = false, eventsController: HorizontalScrollEventsController? = null, noinline onScrollChange: ((View, scrollX: Int, oldScrollX: Int) -> Unit)? = null, child: ResourcesScope.() -> Component ): HorizontalScroll = HorizontalScroll.create(context) .contentProps(child()) .apply { initialScrollPosition?.let { initialScrollPosition(it.toPixels()) } } .scrollbarEnabled(scrollbarEnabled) .fillViewport(fillViewport) .eventsController(eventsController) .onScrollChangeListener(onScrollChange) .build()
apache-2.0
5a31c03fdcc0e714de57f1e70600f28f
39.186047
86
0.748264
4.430769
false
false
false
false
ze-pequeno/okhttp
samples/guide/src/main/java/okhttp3/recipes/kt/CustomTrust.kt
2
9059
/* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 okhttp3.recipes.kt import java.io.IOException import java.security.cert.X509Certificate import okhttp3.OkHttpClient import okhttp3.Request.Builder import okhttp3.tls.HandshakeCertificates import okhttp3.tls.decodeCertificatePem class CustomTrust { // PEM files for root certificates of Comodo and Entrust. These two CAs are sufficient to view // https://publicobject.com (Comodo) and https://squareup.com (Entrust). But they aren't // sufficient to connect to most HTTPS sites including https://godaddy.com and https://visa.com. // Typically developers will need to get a PEM file from their organization's TLS administrator. val comodoRsaCertificationAuthority = """ -----BEGIN CERTIFICATE----- MIIF2DCCA8CgAwIBAgIQTKr5yttjb+Af907YWwOGnTANBgkqhkiG9w0BAQwFADCB hTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNV BAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMTE5 MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgT EkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNh dGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCR 6FSS0gpWsawNJN3Fz0RndJkrN6N9I3AAcbxT38T6KhKPS38QVr2fcHK3YX/JSw8X pz3jsARh7v8Rl8f0hj4K+j5c+ZPmNHrZFGvnnLOFoIJ6dq9xkNfs/Q36nGz637CC 9BR++b7Epi9Pf5l/tfxnQ3K9DADWietrLNPtj5gcFKt+5eNu/Nio5JIk2kNrYrhV /erBvGy2i/MOjZrkm2xpmfh4SDBF1a3hDTxFYPwyllEnvGfDyi62a+pGx8cgoLEf Zd5ICLqkTqnyg0Y3hOvozIFIQ2dOciqbXL1MGyiKXCJ7tKuY2e7gUYPDCUZObT6Z +pUX2nwzV0E8jVHtC7ZcryxjGt9XyD+86V3Em69FmeKjWiS0uqlWPc9vqv9JWL7w qP/0uK3pN/u6uPQLOvnoQ0IeidiEyxPx2bvhiWC4jChWrBQdnArncevPDt09qZah SL0896+1DSJMwBGB7FY79tOi4lu3sgQiUpWAk2nojkxl8ZEDLXB0AuqLZxUpaVIC u9ffUGpVRr+goyhhf3DQw6KqLCGqR84onAZFdr+CGCe01a60y1Dma/RMhnEw6abf Fobg2P9A3fvQQoh/ozM6LlweQRGBY84YcWsr7KaKtzFcOmpH4MN5WdYgGq/yapiq crxXStJLnbsQ/LBMQeXtHT1eKJ2czL+zUdqnR+WEUwIDAQABo0IwQDAdBgNVHQ4E FgQUu69+Aj36pvE8hI6t7jiY7NkyMtQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB /wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAArx1UaEt65Ru2yyTUEUAJNMnMvl wFTPoCWOAvn9sKIN9SCYPBMtrFaisNZ+EZLpLrqeLppysb0ZRGxhNaKatBYSaVqM 4dc+pBroLwP0rmEdEBsqpIt6xf4FpuHA1sj+nq6PK7o9mfjYcwlYRm6mnPTXJ9OV 2jeDchzTc+CiR5kDOF3VSXkAKRzH7JsgHAckaVd4sjn8OoSgtZx8jb8uk2Intzna FxiuvTwJaP+EmzzV1gsD41eeFPfR60/IvYcjt7ZJQ3mFXLrrkguhxuhoqEwWsRqZ CuhTLJK7oQkYdQxlqHvLI7cawiiFwxv/0Cti76R7CZGYZ4wUAc1oBmpjIXUDgIiK boHGhfKppC3n9KUkEEeDys30jXlYsQab5xoq2Z0B15R97QNKyvDb6KkBPvVWmcke jkk9u+UJueBPSZI9FoJAzMxZxuY67RIuaTxslbH9qh17f4a+Hg4yRvv7E491f0yL S0Zj/gA0QHDBw7mh3aZw4gSzQbzpgJHqZJx64SIDqZxubw5lT2yHh17zbqD5daWb QOhTsiedSrnAdyGN/4fy3ryM7xfft0kL0fJuMAsaDk527RH89elWsn2/x20Kk4yl 0MC2Hb46TpSi125sC8KKfPog88Tk5c0NqMuRkrF8hey1FGlmDoLnzc7ILaZRfyHB NVOFBkpdn627G190 -----END CERTIFICATE----- """.trimIndent().decodeCertificatePem() // CN=Entrust Root Certification Authority, OU="(c) 2006 Entrust, Inc.", OU=www.entrust.net/CPS is incorporated by reference, O="Entrust, Inc.", C=US val entrustRootCertificateAuthority = """ -----BEGIN CERTIFICATE----- MIIEkTCCA3mgAwIBAgIERWtQVDANBgkqhkiG9w0BAQUFADCBsDELMAkGA1UEBhMC VVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xOTA3BgNVBAsTMHd3dy5lbnRydXN0 Lm5ldC9DUFMgaXMgaW5jb3Jwb3JhdGVkIGJ5IHJlZmVyZW5jZTEfMB0GA1UECxMW KGMpIDIwMDYgRW50cnVzdCwgSW5jLjEtMCsGA1UEAxMkRW50cnVzdCBSb290IENl cnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA2MTEyNzIwMjM0MloXDTI2MTEyNzIw NTM0MlowgbAxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMTkw NwYDVQQLEzB3d3cuZW50cnVzdC5uZXQvQ1BTIGlzIGluY29ycG9yYXRlZCBieSBy ZWZlcmVuY2UxHzAdBgNVBAsTFihjKSAyMDA2IEVudHJ1c3QsIEluYy4xLTArBgNV BAMTJEVudHJ1c3QgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASIwDQYJ KoZIhvcNAQEBBQADggEPADCCAQoCggEBALaVtkNC+sZtKm9I35RMOVcF7sN5EUFo Nu3s/poBj6E4KPz3EEZmLk0eGrEaTsbRwJWIsMn/MYszA9u3g3s+IIRe7bJWKKf4 4LlAcTfFy0cOlypowCKVYhXbR9n10Cv/gkvJrT7eTNuQgFA/CYqEAOwwCj0Yzfv9 KlmaI5UXLEWeH25DeW0MXJj+SKfFI0dcXv1u5x609mhF0YaDW6KKjbHjKYD+JXGI rb68j6xSlkuqUY3kEzEZ6E5Nn9uss2rVvDlUccp6en+Q3X0dgNmBu1kmwhH+5pPi 94DkZfs0Nw4pgHBNrziGLp5/V6+eF67rHMsoIV+2HNjnogQi+dPa2MsCAwEAAaOB sDCBrTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zArBgNVHRAEJDAi gA8yMDA2MTEyNzIwMjM0MlqBDzIwMjYxMTI3MjA1MzQyWjAfBgNVHSMEGDAWgBRo kORnpKZTgMeGZqTx90tD+4S9bTAdBgNVHQ4EFgQUaJDkZ6SmU4DHhmak8fdLQ/uE vW0wHQYJKoZIhvZ9B0EABBAwDhsIVjcuMTo0LjADAgSQMA0GCSqGSIb3DQEBBQUA A4IBAQCT1DCw1wMgKtD5Y+iRDAUgqV8ZyntyTtSx29CW+1RaGSwMCPeyvIWonX9t O1KzKtvn1ISMY/YPyyYBkVBs9F8U4pN0wBOeMDpQ47RgxRzwIkSNcUesyBrJ6Zua AGAT/3B+XxFNSRuzFVJ7yVTav52Vr2ua2J7p8eRDjeIRRDq/r72DQnNSi6q7pynP 9WQcCk3RvKqsnyrQ/39/2n3qse0wJcGE2jTSW3iDVuycNsMm4hH2Z0kdkquM++v/ eu6FSqdQgPCnXEqULl8FmTxSQeDNtGPPAUO6nIPcj2A781q0tHuu2guQOHXvgR1m 0vdXcDazv/wor3ElhVsT/h5/WrQ8 -----END CERTIFICATE----- """.trimIndent().decodeCertificatePem() // CN=Let's Encrypt Authority X3, O=Let's Encrypt, C=US val letsEncryptCertificateAuthority = """ -----BEGIN CERTIFICATE----- MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/ MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8 SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0 Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj /PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/ wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6 KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg== -----END CERTIFICATE----- """.trimIndent().decodeCertificatePem() private val client: OkHttpClient init { // This implementation just embeds the PEM files in Java strings; most applications will // instead read this from a resource file that gets bundled with the application. val certificates = HandshakeCertificates.Builder() .addTrustedCertificate(letsEncryptCertificateAuthority) .addTrustedCertificate(entrustRootCertificateAuthority) .addTrustedCertificate(comodoRsaCertificationAuthority) // Uncomment if standard certificates are also required. // .addPlatformTrustedCertificates() .build() client = OkHttpClient.Builder() .sslSocketFactory(certificates.sslSocketFactory(), certificates.trustManager) .build() } fun run() { showUrl("https://squareup.com/robots.txt") showUrl("https://publicobject.com/helloworld.txt") } private fun showUrl(url: String) { val request = Builder().url(url).build() client.newCall(request) .execute() .use { response -> if (!response.isSuccessful) { val responseHeaders = response.headers for (i in 0 until responseHeaders.size) { println(responseHeaders.name(i) + ": " + responseHeaders.value(i)) } throw IOException("Unexpected code $response") } println(response.body.string()) for (peerCertificate in response.handshake?.peerCertificates.orEmpty()) { println((peerCertificate as X509Certificate).subjectDN) } } } } fun main() { CustomTrust().run() }
apache-2.0
08277c156da1c05b2496605fa8c7e6fd
50.765714
151
0.82338
2.239001
false
false
false
false
epabst/kotlin-showcase
src/jsMain/kotlin/bootstrap/ListGroup.kt
1
739
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "unused") @file:JsModule("react-bootstrap") package bootstrap import react.RProps external interface ListGroupProps : RProps { var variant: String /* 'flush' */ var activeKey: Any? get() = definedExternally; set(value) = definedExternally var defaultActiveKey: Any? get() = definedExternally; set(value) = definedExternally var onSelect: SelectCallback? get() = definedExternally; set(value) = definedExternally } abstract external class ListGroup<As : React.ElementType> : BsPrefixComponent<As, ListGroupProps> { companion object { var Item: Any } }
apache-2.0
e6ed6c96a0b9c908136a1bf4100fa3da
42.529412
164
0.741543
4.175141
false
false
false
false
googlemaps/android-samples
snippets/app/src/gms/java/com/google/maps/example/kotlin/MapsCompose.kt
1
2038
package com.google.maps.example.kotlin import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.Switch import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.LatLng import com.google.maps.android.compose.GoogleMap import com.google.maps.android.compose.MapProperties import com.google.maps.android.compose.MapType import com.google.maps.android.compose.MapUiSettings import com.google.maps.android.compose.Marker import com.google.maps.android.compose.MarkerState import com.google.maps.android.compose.rememberCameraPositionState @Composable fun AddAMap() { // [START maps_android_compose_add_a_map] val singapore = LatLng(1.35, 103.87) val cameraPositionState = rememberCameraPositionState { position = CameraPosition.fromLatLngZoom(singapore, 10f) } GoogleMap( modifier = Modifier.fillMaxSize(), cameraPositionState = cameraPositionState ) { Marker( state = MarkerState(position = singapore), title = "Singapore", snippet = "Marker in Singapore" ) } // [END maps_android_compose_add_a_map] } @Composable fun Properties() { // [START maps_android_compose_set_properties] var uiSettings by remember { mutableStateOf(MapUiSettings()) } var properties by remember { mutableStateOf(MapProperties(mapType = MapType.SATELLITE)) } Box(Modifier.fillMaxSize()) { GoogleMap( modifier = Modifier.matchParentSize(), properties = properties, uiSettings = uiSettings ) Switch( checked = uiSettings.zoomControlsEnabled, onCheckedChange = { uiSettings = uiSettings.copy(zoomControlsEnabled = it) } ) } // [END maps_android_compose_set_properties] }
apache-2.0
91fba99daeed40cbafbeac6b399db7f2
30.84375
66
0.761531
4.108871
false
false
false
false
Kotlin/dokka
plugins/kotlin-as-java/src/main/kotlin/jvmOverloads.kt
1
515
package org.jetbrains.dokka.kotlinAsJava import org.jetbrains.dokka.model.Annotations import org.jetbrains.dokka.model.Documentable import org.jetbrains.dokka.model.properties.WithExtraProperties internal fun WithExtraProperties<out Documentable>.hasJvmOverloads(): Boolean { return extra[Annotations] ?.directAnnotations ?.entries ?.any { (_, annotations) -> annotations.any { it.dri.packageName == "kotlin.jvm" && it.dri.classNames == "JvmOverloads" } } == true }
apache-2.0
5690e60b454d34cde4b98d7d4d7a161b
35.857143
105
0.716505
4.517544
false
false
false
false
AerisG222/maw_photos_android
MaWPhotos/src/main/java/us/mikeandwan/photos/ui/controls/imagegrid/ImageGridFragment.kt
1
5272
package us.mikeandwan.photos.ui.controls.imagegrid import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.ViewTreeObserver import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.recyclerview.widget.RecyclerView import com.google.android.flexbox.* import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import us.mikeandwan.photos.R import us.mikeandwan.photos.databinding.FragmentImageGridBinding import us.mikeandwan.photos.domain.models.GridThumbnailSize @AndroidEntryPoint class ImageGridFragment : Fragment() { companion object { fun newInstance() = ImageGridFragment() } private val _screenWidth = MutableStateFlow(-1) private val _clickHandlerForwarder = ImageGridRecyclerAdapter.ClickListener { _clickHandler?.onClick(it) } private var _clickHandler: ImageGridRecyclerAdapter.ClickListener? = null private var _listener: ViewTreeObserver.OnGlobalLayoutListener? = null private lateinit var binding: FragmentImageGridBinding val viewModel by viewModels<ImageGridViewModel>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentImageGridBinding.inflate(inflater) binding.lifecycleOwner = viewLifecycleOwner binding.viewModel = viewModel binding.imageGridRecyclerView.setHasFixedSize(true) // TODO: i believe space_between should push the start and end images against the edges, but this is not working // if i wrap the ImageView in the item layout in a LinearLayout, then the first image will be flush on the left // but the right image has a full padding of space at the end. If I remove the wrapping layout, then the padding // is evenly spaced on both left and right, which is more visually appealing binding.imageGridRecyclerView.layoutManager = FlexboxLayoutManager(activity).apply { flexWrap = FlexWrap.WRAP flexDirection = FlexDirection.ROW alignItems = AlignItems.FLEX_START justifyContent = JustifyContent.SPACE_BETWEEN } val adapter = ImageGridRecyclerAdapter(_clickHandlerForwarder) adapter.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY binding.imageGridRecyclerView.adapter = adapter initStateObservers() listenForWidth() return binding.root } private fun initStateObservers() { viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { combine( _screenWidth, viewModel.requestedThumbnailSize ) { screenWidth, thumbnailSize -> Pair(screenWidth, thumbnailSize) } .filter { (screenWidth, thumbnailSize) -> screenWidth > 0 && thumbnailSize != GridThumbnailSize.Unspecified } .onEach { (screenWidth, thumbnailSize) -> viewModel.setThumbnailSize(getThumbnailSize(screenWidth, thumbnailSize)) } .launchIn(this) } } } private fun listenForWidth() { _listener = ViewTreeObserver.OnGlobalLayoutListener { binding.container.viewTreeObserver.removeOnGlobalLayoutListener(_listener) _screenWidth.value = binding.container.width } binding.container.viewTreeObserver.addOnGlobalLayoutListener(_listener) } fun setClickHandler(handler: ImageGridRecyclerAdapter.ClickListener) { _clickHandler = handler } fun setThumbnailSize(thumbnailSize: GridThumbnailSize) { viewModel.setRequestedThumbnailSize(thumbnailSize) } fun setGridItems(data: List<ImageGridItem>) { viewModel.setGridItems(data) } private fun getThumbnailSize(screenWidth: Int, thumbnailSize: GridThumbnailSize): Int { if(thumbnailSize == GridThumbnailSize.Unspecified) { return 0 } val thumbSize = getThumbnailSizeInDps(thumbnailSize) val cols = maxOf(1, screenWidth / thumbSize) val totalInteriorMargins = (cols - 1) * resources.getDimension(R.dimen._2dp) val remainingSpaceForImages = screenWidth - totalInteriorMargins return (remainingSpaceForImages / cols).toInt() } private fun getThumbnailSizeInDps(thumbnailSize: GridThumbnailSize): Int { return when(thumbnailSize) { GridThumbnailSize.ExtraSmall -> resources.getDimension(R.dimen.image_grid_thumbnail_size_extra_small).toInt() GridThumbnailSize.Small -> resources.getDimension(R.dimen.image_grid_thumbnail_size_small).toInt() GridThumbnailSize.Medium -> resources.getDimension(R.dimen.image_grid_thumbnail_size_medium).toInt() GridThumbnailSize.Large -> resources.getDimension(R.dimen.image_grid_thumbnail_size_large).toInt() GridThumbnailSize.Unspecified -> 0 } } }
mit
1dea2aa6ce2d80ab3080d25b04ae6680
40.519685
132
0.719272
5.163565
false
false
false
false
AllanWang/Frost-for-Facebook
app/src/main/kotlin/com/pitchedapps/frost/db/CookiesDb.kt
1
2938
/* * Copyright 2018 Allan Wang * * 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.pitchedapps.frost.db import android.os.Parcelable import androidx.room.ColumnInfo import androidx.room.Dao import androidx.room.Entity import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import com.pitchedapps.frost.prefs.Prefs import kotlinx.android.parcel.Parcelize /** Created by Allan Wang on 2017-05-30. */ @Entity(tableName = "cookies") @Parcelize data class CookieEntity( @androidx.room.PrimaryKey @ColumnInfo(name = "cookie_id") val id: Long, val name: String?, val cookie: String?, val cookieMessenger: String? = null // Version 2 ) : Parcelable { override fun toString(): String = "CookieEntity(${hashCode()})" fun toSensitiveString(): String = "CookieEntity(id=$id, name=$name, cookie=$cookie cookieMessenger=$cookieMessenger)" } @Dao interface CookieDao { @Query("SELECT * FROM cookies") fun _selectAll(): List<CookieEntity> @Query("SELECT * FROM cookies WHERE cookie_id = :id") fun _selectById(id: Long): CookieEntity? @Insert(onConflict = OnConflictStrategy.REPLACE) fun _save(cookie: CookieEntity) @Insert(onConflict = OnConflictStrategy.REPLACE) fun _save(cookies: List<CookieEntity>) @Query("DELETE FROM cookies WHERE cookie_id = :id") fun _deleteById(id: Long) @Query("UPDATE cookies SET cookieMessenger = :cookie WHERE cookie_id = :id") fun _updateMessengerCookie(id: Long, cookie: String?) } suspend fun CookieDao.selectAll() = dao { _selectAll() } suspend fun CookieDao.selectById(id: Long) = dao { _selectById(id) } suspend fun CookieDao.save(cookie: CookieEntity) = dao { _save(cookie) } suspend fun CookieDao.save(cookies: List<CookieEntity>) = dao { _save(cookies) } suspend fun CookieDao.deleteById(id: Long) = dao { _deleteById(id) } suspend fun CookieDao.currentCookie(prefs: Prefs) = selectById(prefs.userId) suspend fun CookieDao.updateMessengerCookie(id: Long, cookie: String?) = dao { _updateMessengerCookie(id, cookie) } val COOKIES_MIGRATION_1_2 = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE cookies ADD COLUMN cookieMessenger TEXT") } }
gpl-3.0
7b819a492dd40dcdd26f2ae1e8aa70c2
33.97619
96
0.746426
3.875989
false
false
false
false
vsch/idea-multimarkdown
src/test/java/com/vladsch/md/nav/util/MdIndentConverterTest.kt
1
23092
/* * Copyright (c) 2015-2020 Vladimir Schneider <[email protected]>, all rights reserved. * * This code is private property of the copyright holder and cannot be used without * having obtained a license or prior written permission of the copyright holder. * * 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.vladsch.md.nav.util import com.intellij.openapi.util.TextRange import com.vladsch.flexmark.util.sequence.BasedSequence import com.vladsch.flexmark.util.sequence.LineAppendableImpl import org.junit.Assert.assertEquals import org.junit.Test class MdIndentConverterTest { private fun originalLines(lines: String): List<BasedSequence> { return LineAppendableImpl(0).append(lines).lines.toList() } private fun lines(lines: String): List<BasedSequence> { return LineAppendableImpl(0).append(lines).linesInfo.map { it.textNoEOL }.toList() } @Test @Throws(Exception::class) fun test_Basic() { val original = """0123456789 0123456789 0123456789 0123456789 """ val decoded = """0123456789 0123456789 0123456789 0123456789 """ val encoded = """ 0123456789 0123456789 0123456789 0123456789 """ val converter = MdIndentConverter(original, 0, originalLines(original), null, null) val outChars = StringBuilder() val range = TextRange.allOf(original) val wasDecoded = converter.decode(range, outChars) assertEquals(true, wasDecoded) assertEquals(decoded, outChars.toString()) assertEquals(encoded, MdIndentConverter.encode(original, "", "", false, null, null)) for (i in 0 .. decoded.length) { assertEquals("$i should be $i", i, converter.getOffsetInHost(i, range)) } assertEquals(44, converter.getOffsetInHost(45, range)) assertEquals(-1, converter.getOffsetInHost(46, range)) } @Test @Throws(Exception::class) fun test_Basic0() { val original = """0123456789 0123456789 0123456789 0123456789 """ val encoded = """ 0123456789 0123456789 0123456789 0123456789 """ val converter = MdIndentConverter(original, 0, originalLines(original), lines(original), null) val outChars = StringBuilder() val range = TextRange.allOf(original) val wasDecoded = converter.decode(range, outChars) assertEquals(true, wasDecoded) assertEquals(original, outChars.toString()) assertEquals(encoded, MdIndentConverter.encode(original, "", "", false, null, null)) assertEquals(0, converter.getOffsetInHost(0, range)) assertEquals(9, converter.getOffsetInHost(9, range)) assertEquals(10, converter.getOffsetInHost(10, range)) assertEquals(24, converter.getOffsetInHost(24, range)) assertEquals(42, converter.getOffsetInHost(42, range)) assertEquals(43, converter.getOffsetInHost(43, range)) assertEquals(44, converter.getOffsetInHost(44, range)) assertEquals(44, converter.getOffsetInHost(45, range)) assertEquals(-1, converter.getOffsetInHost(46, range)) } @Test @Throws(Exception::class) fun test_Basic1() { val original = """ 0123456789 0123456789 0123456789 0123456789 """ val decoded = """0123456789 0123456789 0123456789 0123456789 """ val encoded = """ 0123456789 0123456789 0123456789 0123456789 """ val converter = MdIndentConverter(original, 0, originalLines(original), lines(decoded), null) val outChars = StringBuilder() val range = TextRange.allOf(original) val wasDecoded = converter.decode(range, outChars) assertEquals(true, wasDecoded) assertEquals(decoded, outChars.toString()) assertEquals(encoded, MdIndentConverter.encode(decoded, "", "", false, null, null)) assertEquals(4, converter.getOffsetInHost(0, range)) assertEquals(13, converter.getOffsetInHost(9, range)) assertEquals(14, converter.getOffsetInHost(10, range)) assertEquals(19, converter.getOffsetInHost(11, range)) assertEquals(20, converter.getOffsetInHost(12, range)) assertEquals(29, converter.getOffsetInHost(21, range)) assertEquals(34, converter.getOffsetInHost(22, range)) assertEquals(43, converter.getOffsetInHost(31, range)) assertEquals(44, converter.getOffsetInHost(32, range)) assertEquals(49, converter.getOffsetInHost(33, range)) assertEquals(58, converter.getOffsetInHost(42, range)) assertEquals(59, converter.getOffsetInHost(43, range)) assertEquals(60, converter.getOffsetInHost(44, range)) assertEquals(60, converter.getOffsetInHost(45, range)) assertEquals(-1, converter.getOffsetInHost(46, range)) } @Test @Throws(Exception::class) fun test_Basic2() { val original = """ 0123456789 > 0123456789 > 0123456789 > 0123456789 """ val decoded = """0123456789 0123456789 0123456789 0123456789 """ val encoded = """ 0123456789 > 0123456789 > 0123456789 > 0123456789 """ val converter = MdIndentConverter(original, 0, originalLines(original), lines(decoded), null) val outChars = StringBuilder() val range = TextRange.allOf(original) val wasDecoded = converter.decode(range, outChars) assertEquals(true, wasDecoded) assertEquals(decoded, outChars.toString()) assertEquals(encoded, MdIndentConverter.encode(decoded, "", "> ", false, null, null)) assertEquals(4, converter.getOffsetInHost(0, range)) assertEquals(13, converter.getOffsetInHost(9, range)) assertEquals(14, converter.getOffsetInHost(10, range)) assertEquals(21, converter.getOffsetInHost(11, range)) assertEquals(22, converter.getOffsetInHost(12, range)) assertEquals(31, converter.getOffsetInHost(21, range)) assertEquals(38, converter.getOffsetInHost(22, range)) assertEquals(47, converter.getOffsetInHost(31, range)) assertEquals(48, converter.getOffsetInHost(32, range)) assertEquals(55, converter.getOffsetInHost(33, range)) assertEquals(64, converter.getOffsetInHost(42, range)) assertEquals(65, converter.getOffsetInHost(43, range)) assertEquals(66, converter.getOffsetInHost(44, range)) assertEquals(66, converter.getOffsetInHost(45, range)) assertEquals(-1, converter.getOffsetInHost(46, range)) } @Test @Throws(Exception::class) fun test_Fenced1() { val original = """0123456789 > 0123456789 > 0123456789 > 0123456789 """ val decoded = """0123456789 0123456789 0123456789 0123456789 """ val encoded = """0123456789 > 0123456789 > 0123456789 > 0123456789 """ val converter = MdIndentConverter(original, 0, originalLines(original), lines(decoded), null) val outChars = StringBuilder() val range = TextRange.allOf(original) val wasDecoded = converter.decode(range, outChars) assertEquals(true, wasDecoded) assertEquals(decoded, outChars.toString()) assertEquals(encoded, MdIndentConverter.encode(decoded, "", "> ", true, null, null)) assertEquals(0, converter.getOffsetInHost(0, range)) assertEquals(9, converter.getOffsetInHost(9, range)) assertEquals(10, converter.getOffsetInHost(10, range)) assertEquals(13, converter.getOffsetInHost(11, range)) assertEquals(14, converter.getOffsetInHost(12, range)) assertEquals(23, converter.getOffsetInHost(21, range)) assertEquals(26, converter.getOffsetInHost(22, range)) assertEquals(35, converter.getOffsetInHost(31, range)) assertEquals(36, converter.getOffsetInHost(32, range)) assertEquals(39, converter.getOffsetInHost(33, range)) assertEquals(48, converter.getOffsetInHost(42, range)) assertEquals(49, converter.getOffsetInHost(43, range)) assertEquals(50, converter.getOffsetInHost(44, range)) assertEquals(50, converter.getOffsetInHost(45, range)) assertEquals(-1, converter.getOffsetInHost(46, range)) } @Test @Throws(Exception::class) fun test_BasicSemi() { val original = """0123456789; 0123456789; 0123456789; 0123456789; """ val decoded = """0123456789 0123456789 0123456789 0123456789 """ val encoded = """ 0123456789; 0123456789; 0123456789; 0123456789; """ val converter = MdIndentConverter(original, 0, originalLines(original), lines(original), lines(decoded)) val outChars = StringBuilder() val range = TextRange.allOf(original) val wasDecoded = converter.decode(range, outChars) assertEquals(true, wasDecoded) assertEquals(decoded, outChars.toString()) assertEquals(encoded, MdIndentConverter.encode(decoded, "", "", false, ";", null)) assertEquals(0, converter.getOffsetInHost(0, range)) assertEquals(9, converter.getOffsetInHost(9, range)) assertEquals(10, converter.getOffsetInHost(10, range)) assertEquals(12, converter.getOffsetInHost(11, range)) assertEquals(13, converter.getOffsetInHost(12, range)) assertEquals(22, converter.getOffsetInHost(21, range)) assertEquals(24, converter.getOffsetInHost(22, range)) assertEquals(33, converter.getOffsetInHost(31, range)) assertEquals(34, converter.getOffsetInHost(32, range)) assertEquals(36, converter.getOffsetInHost(33, range)) assertEquals(45, converter.getOffsetInHost(42, range)) assertEquals(46, converter.getOffsetInHost(43, range)) assertEquals(48, converter.getOffsetInHost(44, range)) assertEquals(48, converter.getOffsetInHost(45, range)) assertEquals(-1, converter.getOffsetInHost(46, range)) } @Test @Throws(Exception::class) fun test_Basic1Semi() { val original = """ 0123456789; 0123456789; 0123456789; 0123456789; """ val unprefixed = """0123456789; 0123456789; 0123456789; 0123456789; """ val decoded = """0123456789 0123456789 0123456789 0123456789 """ val encoded = """ 0123456789; 0123456789; 0123456789; 0123456789; """ val converter = MdIndentConverter(original, 0, originalLines(original), lines(unprefixed), lines(decoded)) val outChars = StringBuilder() val range = TextRange.allOf(original) val wasDecoded = converter.decode(range, outChars) assertEquals(true, wasDecoded) assertEquals(decoded, outChars.toString()) assertEquals(encoded, MdIndentConverter.encode(decoded, "", "", false, ";", null)) assertEquals(4, converter.getOffsetInHost(0, range)) assertEquals(13, converter.getOffsetInHost(9, range)) assertEquals(14, converter.getOffsetInHost(10, range)) assertEquals(20, converter.getOffsetInHost(11, range)) assertEquals(21, converter.getOffsetInHost(12, range)) assertEquals(30, converter.getOffsetInHost(21, range)) assertEquals(36, converter.getOffsetInHost(22, range)) assertEquals(45, converter.getOffsetInHost(31, range)) assertEquals(46, converter.getOffsetInHost(32, range)) assertEquals(52, converter.getOffsetInHost(33, range)) assertEquals(61, converter.getOffsetInHost(42, range)) assertEquals(62, converter.getOffsetInHost(43, range)) assertEquals(64, converter.getOffsetInHost(44, range)) assertEquals(64, converter.getOffsetInHost(45, range)) assertEquals(-1, converter.getOffsetInHost(46, range)) } @Test @Throws(Exception::class) fun test_Basic2Semi() { val original = """ 0123456789; > 0123456789; > 0123456789; > 0123456789; """ val unprefixed = """0123456789; 0123456789; 0123456789; 0123456789; """ val decoded = """0123456789 0123456789 0123456789 0123456789 """ val encoded = """ 0123456789; > 0123456789; > 0123456789; > 0123456789; """ val converter = MdIndentConverter(original, 0, originalLines(original), lines(unprefixed), lines(decoded)) val outChars = StringBuilder() val range = TextRange.allOf(original) val wasDecoded = converter.decode(range, outChars) assertEquals(true, wasDecoded) assertEquals(decoded, outChars.toString()) assertEquals(encoded, MdIndentConverter.encode(decoded, "", "> ", false, ";", null)) assertEquals(4, converter.getOffsetInHost(0, range)) assertEquals(13, converter.getOffsetInHost(9, range)) assertEquals(14, converter.getOffsetInHost(10, range)) assertEquals(22, converter.getOffsetInHost(11, range)) assertEquals(23, converter.getOffsetInHost(12, range)) assertEquals(32, converter.getOffsetInHost(21, range)) assertEquals(40, converter.getOffsetInHost(22, range)) assertEquals(49, converter.getOffsetInHost(31, range)) assertEquals(50, converter.getOffsetInHost(32, range)) assertEquals(58, converter.getOffsetInHost(33, range)) assertEquals(67, converter.getOffsetInHost(42, range)) assertEquals(68, converter.getOffsetInHost(43, range)) assertEquals(70, converter.getOffsetInHost(44, range)) assertEquals(70, converter.getOffsetInHost(45, range)) assertEquals(-1, converter.getOffsetInHost(46, range)) } @Test @Throws(Exception::class) fun test_Fenced1Semi() { val original = """0123456789; > 0123456789; > 0123456789; > 0123456789; """ val unprefixed = """0123456789; 0123456789; 0123456789; 0123456789; """ val decoded = """0123456789 0123456789 0123456789 0123456789 """ val encoded = """0123456789; > 0123456789; > 0123456789; > 0123456789; """ val converter = MdIndentConverter(original, 0, originalLines(original), lines(unprefixed), lines(decoded)) val outChars = StringBuilder() val range = TextRange.allOf(original) val wasDecoded = converter.decode(range, outChars) assertEquals(true, wasDecoded) assertEquals(decoded, outChars.toString()) assertEquals(encoded, MdIndentConverter.encode(decoded, "", "> ", true, ";", null)) assertEquals(0, converter.getOffsetInHost(0, range)) assertEquals(9, converter.getOffsetInHost(9, range)) assertEquals(10, converter.getOffsetInHost(10, range)) assertEquals(14, converter.getOffsetInHost(11, range)) assertEquals(15, converter.getOffsetInHost(12, range)) assertEquals(24, converter.getOffsetInHost(21, range)) assertEquals(28, converter.getOffsetInHost(22, range)) assertEquals(37, converter.getOffsetInHost(31, range)) assertEquals(38, converter.getOffsetInHost(32, range)) assertEquals(42, converter.getOffsetInHost(33, range)) assertEquals(51, converter.getOffsetInHost(42, range)) assertEquals(52, converter.getOffsetInHost(43, range)) assertEquals(54, converter.getOffsetInHost(44, range)) assertEquals(54, converter.getOffsetInHost(45, range)) assertEquals(-1, converter.getOffsetInHost(46, range)) } @Test fun test_Basic1Semi2() { val original = """ 0123456789;; 0123456789;; 0123456789;; 0123456789;; """ val unprefixed = """0123456789;; 0123456789;; 0123456789;; 0123456789;; """ val decoded = """0123456789 0123456789 0123456789 0123456789 """ val encoded = """ 0123456789; 0123456789; 0123456789; 0123456789; """ val converter = MdIndentConverter(original, 0, originalLines(original), lines(unprefixed), lines(decoded)) val outChars = StringBuilder() val range = TextRange.allOf(original) val wasDecoded = converter.decode(range, outChars) assertEquals(true, wasDecoded) assertEquals(decoded, outChars.toString()) assertEquals(encoded, MdIndentConverter.encode(decoded, "", "", false, ";", null)) assertEquals(4, converter.getOffsetInHost(0, range)) assertEquals(13, converter.getOffsetInHost(9, range)) assertEquals(14, converter.getOffsetInHost(10, range)) assertEquals(21, converter.getOffsetInHost(11, range)) assertEquals(22, converter.getOffsetInHost(12, range)) assertEquals(31, converter.getOffsetInHost(21, range)) assertEquals(38, converter.getOffsetInHost(22, range)) assertEquals(47, converter.getOffsetInHost(31, range)) assertEquals(48, converter.getOffsetInHost(32, range)) assertEquals(55, converter.getOffsetInHost(33, range)) assertEquals(64, converter.getOffsetInHost(42, range)) assertEquals(65, converter.getOffsetInHost(43, range)) assertEquals(68, converter.getOffsetInHost(44, range)) assertEquals(68, converter.getOffsetInHost(45, range)) assertEquals(-1, converter.getOffsetInHost(46, range)) } @Test @Throws(Exception::class) fun test_Basic2Semi2() { val original = """ 0123456789; > 0123456789; > 0123456789; > 0123456789; """ val unprefixed = """0123456789; 0123456789; 0123456789; 0123456789; """ val decoded = """0123456789 0123456789 0123456789 0123456789 """ val encoded = """ 0123456789; > 0123456789; > 0123456789; > 0123456789; """ val converter = MdIndentConverter(original, 0, originalLines(original), lines(unprefixed), lines(decoded)) val outChars = StringBuilder() val range = TextRange.allOf(original) val wasDecoded = converter.decode(range, outChars) assertEquals(true, wasDecoded) assertEquals(decoded, outChars.toString()) assertEquals(encoded, MdIndentConverter.encode(decoded, "", "> ", false, ";", null)) assertEquals(4, converter.getOffsetInHost(0, range)) assertEquals(13, converter.getOffsetInHost(9, range)) assertEquals(14, converter.getOffsetInHost(10, range)) assertEquals(22, converter.getOffsetInHost(11, range)) assertEquals(23, converter.getOffsetInHost(12, range)) assertEquals(32, converter.getOffsetInHost(21, range)) assertEquals(40, converter.getOffsetInHost(22, range)) assertEquals(49, converter.getOffsetInHost(31, range)) assertEquals(50, converter.getOffsetInHost(32, range)) assertEquals(58, converter.getOffsetInHost(33, range)) assertEquals(67, converter.getOffsetInHost(42, range)) assertEquals(68, converter.getOffsetInHost(43, range)) assertEquals(70, converter.getOffsetInHost(44, range)) assertEquals(70, converter.getOffsetInHost(45, range)) assertEquals(-1, converter.getOffsetInHost(46, range)) } @Test @Throws(Exception::class) fun test_Fenced1Semi2() { val original = """0123456789; > 0123456789; > 0123456789; > 0123456789; """ val unprefixed = """0123456789; 0123456789; 0123456789; 0123456789; """ val decoded = """0123456789 0123456789 0123456789 0123456789 """ val encoded = """0123456789; > 0123456789; > 0123456789; > 0123456789; """ val converter = MdIndentConverter(original, 0, originalLines(original), lines(unprefixed), lines(decoded)) val outChars = StringBuilder() val range = TextRange.allOf(original) val wasDecoded = converter.decode(range, outChars) assertEquals(true, wasDecoded) assertEquals(decoded, outChars.toString()) assertEquals(encoded, MdIndentConverter.encode(decoded, "", "> ", true, ";", null)) assertEquals(0, converter.getOffsetInHost(0, range)) assertEquals(9, converter.getOffsetInHost(9, range)) assertEquals(10, converter.getOffsetInHost(10, range)) assertEquals(14, converter.getOffsetInHost(11, range)) assertEquals(15, converter.getOffsetInHost(12, range)) assertEquals(24, converter.getOffsetInHost(21, range)) assertEquals(28, converter.getOffsetInHost(22, range)) assertEquals(37, converter.getOffsetInHost(31, range)) assertEquals(38, converter.getOffsetInHost(32, range)) assertEquals(42, converter.getOffsetInHost(33, range)) assertEquals(51, converter.getOffsetInHost(42, range)) assertEquals(52, converter.getOffsetInHost(43, range)) assertEquals(54, converter.getOffsetInHost(44, range)) assertEquals(54, converter.getOffsetInHost(45, range)) assertEquals(-1, converter.getOffsetInHost(46, range)) } @Test @Throws(Exception::class) fun test_Fenced2Semi2() { val original = """0123456789; > 0123456789; >, > 0123456789; > 0123456789; """.replace(',', ' ') val unprefixed = """0123456789; 0123456789; 0123456789; 0123456789; """ val decoded = """0123456789 0123456789 0123456789 0123456789 """ val encoded = """0123456789; > 0123456789; >, > 0123456789; > 0123456789; """.replace(',', ' ') val converter = MdIndentConverter(original, 0, originalLines(original), lines(unprefixed), lines(decoded)) val outChars = StringBuilder() val range = TextRange.allOf(original) val wasDecoded = converter.decode(range, outChars) assertEquals(true, wasDecoded) assertEquals(decoded, outChars.toString()) assertEquals(encoded, MdIndentConverter.encode(decoded, "", "> ", true, ";", null)) // line 1 assertEquals(0, converter.getOffsetInHost(0, range)) assertEquals(9, converter.getOffsetInHost(9, range)) assertEquals(10, converter.getOffsetInHost(10, range)) // line 2 assertEquals(14, converter.getOffsetInHost(11, range)) assertEquals(15, converter.getOffsetInHost(12, range)) assertEquals(24, converter.getOffsetInHost(21, range)) // line 3 assertEquals(28, converter.getOffsetInHost(22, range)) assertEquals(31, converter.getOffsetInHost(23, range)) // line 4 assertEquals(32, converter.getOffsetInHost(24, range)) assertEquals(33, converter.getOffsetInHost(25, range)) assertEquals(41, converter.getOffsetInHost(33, range)) assertEquals(45, converter.getOffsetInHost(34, range)) // line 5 assertEquals(46, converter.getOffsetInHost(35, range)) assertEquals(55, converter.getOffsetInHost(44, range)) assertEquals(57, converter.getOffsetInHost(45, range)) assertEquals(57, converter.getOffsetInHost(46, range)) assertEquals(-1, converter.getOffsetInHost(47, range)) } }
apache-2.0
764f4640dfcba223b846c9b6b5265781
30.763411
114
0.676208
4.406029
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/flex/psi/FlexmarkExampleOptionImpl.kt
1
7525
// Copyright (c) 2017-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.flex.psi import com.intellij.lang.ASTNode import com.intellij.navigation.ItemPresentation import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.stubs.IStubElementType import com.intellij.util.IncorrectOperationException import com.vladsch.flexmark.test.util.ExampleOption import com.vladsch.md.nav.parser.MdFactoryContext import com.vladsch.md.nav.psi.element.MdElementItemPresentation import com.vladsch.md.nav.psi.element.MdRenameElement import com.vladsch.md.nav.psi.element.MdStructureViewPresentableElement import com.vladsch.md.nav.psi.element.MdStructureViewPresentableItem import com.vladsch.md.nav.psi.util.MdElementFactory import com.vladsch.md.nav.psi.util.MdTokenSets import com.vladsch.plugin.util.nullIf import icons.FlexmarkIcons import java.util.* import javax.swing.Icon class FlexmarkExampleOptionImpl(stub: FlexmarkExampleOptionStub?, nodeType: IStubElementType<FlexmarkExampleOptionStub, FlexmarkExampleOption>?, node: ASTNode?) : FlexmarkStubElementImpl<FlexmarkExampleOptionStub>(stub, nodeType, node), FlexmarkExampleOption, MdStructureViewPresentableElement, MdStructureViewPresentableItem { constructor(stub: FlexmarkExampleOptionStub, nodeType: IStubElementType<FlexmarkExampleOptionStub, FlexmarkExampleOption>) : this(stub, nodeType, null) constructor(node: ASTNode) : this(null, null, node) override fun getNameIdentifier(): PsiElement? { val nameElement = findChildByType<PsiElement>(MdTokenSets.FLEXMARK_EXAMPLE_OPTION_NAME_OR_DISABLED_SET) return nameElement?.nullIf(nameElement.node.findChildByType(MdTokenSets.FLEXMARK_EXAMPLE_OPTION_NAME_OR_DISABLED_SET) == null) } override fun isRenameAvailable(): Boolean { return nameIdentifier != null } override fun setName(newName: String): FlexmarkExampleOption { // preserve params and disabled status return setName(newName, MdRenameElement.REASON_FILE_RENAMED) } override fun handleContentChange(newContent: String): FlexmarkExampleOption { val parent = parent as FlexmarkExampleOptions val optionElements = parent.optionElements val options = ArrayList<String>() var self = 0 for ((i, element) in optionElements.withIndex()) { if (element === this) { val useContent = optionInfo.getOptionText(newContent) options.add(useContent) self = i } else { val name = element.optionName options.add(name) } } val example: FlexmarkExample = parent.parent as FlexmarkExample val factoryContext = MdFactoryContext(this) val newExample = MdElementFactory.createFlexmarkExample(factoryContext, FlexmarkExampleParams(example).withOptions(options)) ?: return this val contentNodes = newExample.optionsList?.optionElements ?: return this if (self < contentNodes.size) { replace(contentNodes[self]) return contentNodes[self] } return this } override fun isInplaceRenameAvailable(context: PsiElement?): Boolean { return true // val elementType = context?.node?.elementType // return isRenameAvailable && (context is FlexmarkExampleOption) } override fun isMemberInplaceRenameAvailable(context: PsiElement?): Boolean { return true // val elementType = context?.node?.elementType // return isRenameAvailable && (context is FlexmarkExampleOption) } @Throws(IncorrectOperationException::class) override fun handleContentChange(range: TextRange, newContent: String): FlexmarkExampleOption { val optionRange = optionInfo.optionNameRange if (!range.equalsToRange(optionRange.startOffset, optionRange.endOffset)) { throw IncorrectOperationException() } return handleContentChange(newContent) } override fun createReference(textRange: TextRange, exactReference: Boolean): FlexmarkPsiReferenceExampleOption { return FlexmarkPsiReferenceExampleOption(this, textRange, exactReference) } override fun getReference(): FlexmarkPsiReferenceExampleOption { val optionRange = optionInfo.optionNameRange return createReference(optionRange, false) } override fun getExactReference(): FlexmarkPsiReferenceExampleOption { val optionRange = optionInfo.optionNameRange return createReference(optionRange, true) } override fun getOptionParams(): String? { val exampleOption = ExampleOption.of(text) return exampleOption.getCustomParams() } override fun getOptionName(): String { val stub = stub if (stub != null) { return stub.optionName } val exampleOption = ExampleOption.of(text) return exampleOption.getOptionName() } override fun getDisplayName(): String { return optionName } override fun getLocationString(): String? { return null } override fun getStructureViewPresentation(): ItemPresentation { val grandParent = parent.parent if (grandParent is FlexmarkExampleImpl) { return MdElementItemPresentation(this, grandParent.getIcon(0) ?: FlexmarkIcons.Element.FLEXMARK_SPEC_EXAMPLE) } return MdElementItemPresentation(this) } override fun getPresentation(): ItemPresentation { return structureViewPresentation } override fun getPresentableText(): String? { val grandParent = parent.parent if (grandParent is FlexmarkExampleImpl) { return "options(" + (parent as FlexmarkExampleOptions).optionsString + ") " + containingFile.name + " " + grandParent.presentableText } return null } override fun getIcon(flags: Int): Icon? { val grandParent = parent.parent if (grandParent is FlexmarkExampleImpl) { return grandParent.getIcon(flags) } val flexmarkOption = FlexmarkPsi.getBuiltInFlexmarkOption(optionName) return if (flexmarkOption != null) flexmarkOption.icon else FlexmarkIcons.Element.FLEXMARK_SPEC_EXAMPLE } override fun isIgnore(): Boolean { return optionInfo.isIgnore } override fun isFail(): Boolean { return optionInfo.isFail } override fun isBuiltIn(): Boolean { return optionInfo.isBuiltIn } override fun isDisabled(): Boolean { return optionInfo.isDisabled } override fun getOptionInfo(): FlexmarkOptionInfo { return FlexmarkPsi.getFlexmarkOptionInfo(text) } override fun getName(): String { return optionName } override fun setName(newName: String, reason: Int): FlexmarkExampleOption { return handleContentChange(newName) } override fun toString(): String { return "FLEXMARK_EXAMPLE_OPTION '" + optionName + "' " + super.hashCode() } override fun accept(visitor: PsiElementVisitor) { // if (visitor is MdPsiVisitor) // visitor.visitNamedElement(this) // else super.accept(visitor) } }
apache-2.0
ef64a040a94e95796dee3dacc70af67c
36.068966
177
0.698472
4.96372
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/lang/refactoring/RsNameSuggestions.kt
1
3272
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.refactoring import com.intellij.psi.PsiElement import com.intellij.psi.codeStyle.NameUtil import com.intellij.psi.util.PsiTreeUtil import org.rust.ide.inspections.toSnakeCase import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.valueParameters import org.rust.lang.core.psi.ext.parentOfType import org.rust.lang.core.types.ty.TyUnknown import org.rust.lang.core.types.type import java.util.* /** * This suggests names for an expression about to be bound to a local variable * * If the type is resolved suggest the first letter of the type name. * If its an argument to a function call, suggest the name of the argument in the function definition. * If its a function call suggest the name of the function and the enclosing name space (if any). * If the expression is in a struct literal (Foo {x: 5, y: 6}) suggest the tag for the expression as a name * If a name is already bound in the local scope do not suggest it. */ fun RsExpr.suggestNames(): LinkedHashSet<String> { val names = LinkedHashSet<String>() nameForType(this)?.let { names.addAll(rustNameUtil(it)) } val parent = this.parent val foundNames = when { this.isArgument() -> rustNameUtil(nameForArgument()) this is RsCallExpr -> nameForCall(this).flatMap(::rustNameUtil) parent is RsStructLiteralField -> rustNameUtil(parent.identifier.text) else -> emptyList() } names.addAll(foundNames) val usedNames = findNamesInLocalScope(this) names.removeAll(usedNames) return names } private fun nameForType(expr: RsExpr): String? { val type = expr.type if (type is TyUnknown) { return null } return type.toString().take(1) } private fun nameForCall(expr: RsCallExpr): List<String> { val pathElement = expr.expr if (pathElement is RsPathExpr) { val path = pathElement.path //path.path.identifier gives us the x's out of: Xxx::<T>::yyy return listOf(path.identifier, path.path?.identifier).filterNotNull().map(PsiElement::getText).reverseNew() } return listOf(pathElement.text) } private fun List<String>.reverseNew() = if (this.firstOrNull() == "new") { this.reversed() } else { this } private fun PsiElement.nameForArgument(): String { val call = this.parentOfType<RsCallExpr>(strict = true) ?: return "" val parameterIndex = call.valueArgumentList.children.indexOf(this) val fn = call.findFnImpl() return fn?.valueParameters?.get(parameterIndex)?.pat?.text ?: "" } private fun RsCallExpr.findFnImpl(): RsFunction? { val path = expr as? RsPathExpr return path?.path?.reference?.resolve() as? RsFunction } fun findNamesInLocalScope(expr: PsiElement): List<String> { val blockScope = expr.parentOfType<RsBlock>(strict = false) val letDecls = PsiTreeUtil.findChildrenOfType(blockScope, RsLetDecl::class.java) return letDecls.map { it.pat?.text }.filterNotNull() } private fun PsiElement.isArgument() = this.parent is RsValueArgumentList private fun rustNameUtil(name: String) = NameUtil.getSuggestionsByName(name, "", "", false, false, false).map { it.toSnakeCase(false) }
mit
14d80764d222ec0ac808461f2d273a0e
31.72
135
0.71791
3.927971
false
false
false
false
tutao/tutanota
app-android/app/src/main/java/de/tutao/tutanota/alarms/EncryptedRepeatRule.kt
1
1030
package de.tutao.tutanota.alarms import de.tutao.tutanota.AndroidNativeCryptoFacade import de.tutao.tutanota.decryptNumber import de.tutao.tutanota.decryptString import kotlinx.serialization.Serializable import java.util.* @Serializable class EncryptedRepeatRule( val frequency: String, val interval: String, val timeZone: String, val endType: String, val endValue: String?, ) fun EncryptedRepeatRule.decrypt(crypto: AndroidNativeCryptoFacade, sessionKey: ByteArray): RepeatRule { val repeatPeriodNumber = crypto.decryptNumber(frequency, sessionKey) val repeatPeriod = RepeatPeriod[repeatPeriodNumber] val endTypeNumber = crypto.decryptNumber(endType, sessionKey) val endType = EndType[endTypeNumber] return RepeatRule( frequency = repeatPeriod, interval = crypto.decryptNumber(interval, sessionKey).toInt(), timeZone = TimeZone.getTimeZone(crypto.decryptString(timeZone, sessionKey)), endValue = if (endValue != null) crypto.decryptNumber(endValue, sessionKey) else null, endType = endType, ) }
gpl-3.0
1ad24b3515550379ccb159b1aecc3757
32.258065
103
0.798058
3.800738
false
false
false
false
rei-m/android_hyakuninisshu
feature/question/src/main/java/me/rei_m/hyakuninisshu/feature/question/ui/QuestionViewModel.kt
1
5279
/* * Copyright (c) 2020. Rei Matsushita. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package me.rei_m.hyakuninisshu.feature.question.ui import android.content.Context import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import me.rei_m.hyakuninisshu.feature.corecomponent.ext.combineLatest import me.rei_m.hyakuninisshu.feature.corecomponent.ext.map import me.rei_m.hyakuninisshu.feature.corecomponent.ui.AbstractViewModel import me.rei_m.hyakuninisshu.feature.question.R import me.rei_m.hyakuninisshu.state.core.Dispatcher import me.rei_m.hyakuninisshu.state.question.action.QuestionActionCreator import me.rei_m.hyakuninisshu.state.question.model.QuestionState import me.rei_m.hyakuninisshu.state.question.store.QuestionStore import me.rei_m.hyakuninisshu.state.training.model.DisplayStyleCondition import me.rei_m.hyakuninisshu.state.training.model.InputSecondCondition import java.util.Date import java.util.Timer import java.util.TimerTask import javax.inject.Inject class QuestionViewModel( private val questionId: String, private val kamiNoKuStyle: DisplayStyleCondition, private val shimoNoKuStyle: DisplayStyleCondition, private val inputSecond: InputSecondCondition, dispatcher: Dispatcher, private val actionCreator: QuestionActionCreator, private val store: QuestionStore, private val context: Context ) : AbstractViewModel(dispatcher) { val question = store.question val position = question.map { it.position } val yomiFudaWithState = question.map { it.yomiFuda }.combineLatest(store.state) val toriFudaList = question.map { it.toriFudaList } val inputSecondCounter: MutableLiveData<Int> = MutableLiveData(-1) val state = store.state val isVisibleWaitingMask = state.map { it is QuestionState.Ready } val isVisibleResult = state.map { it is QuestionState.Answered } val selectedTorifudaIndex = state.map { if (it is QuestionState.Answered) { return@map it.selectedToriFudaIndex } else { return@map null } } val isCorrectResId = state.map { val resId = if (it is QuestionState.Answered && it.isCorrect) R.drawable.check_correct else R.drawable.check_incorrect context.getDrawable(resId) } private var isSelected = false private val stateObserver = Observer<QuestionState> { when (it) { is QuestionState.Ready -> { timer.scheduleAtFixedRate(timerTask, 0, 1000) } is QuestionState.InAnswer -> { } is QuestionState.Answered -> { } } } private val timer = Timer() private val timerTask = object : TimerTask() { private var count = inputSecond.value override fun run() { if (count == 0) { timer.cancel() dispatchAction { actionCreator.startAnswer(questionId, Date()) } } inputSecondCounter.postValue(count) count -= 1 } } init { state.observeForever(stateObserver) dispatchAction { actionCreator.start(questionId, kamiNoKuStyle, shimoNoKuStyle) } } override fun onCleared() { state.removeObserver(stateObserver) store.dispose() timer.cancel() super.onCleared() } fun onSelected(position: Int) { if (state.value !== QuestionState.InAnswer) { return } question.value?.let { if (isSelected) { return@let } isSelected = true dispatchAction { actionCreator.answer(questionId, it.toriFudaList[position], Date()) } } } fun onClickedMask() { return } class Factory @Inject constructor( private val dispatcher: Dispatcher, private val actionCreator: QuestionActionCreator, private val store: QuestionStore, private val context: Context ) : ViewModelProvider.Factory { lateinit var questionId: String lateinit var kamiNoKuStyle: DisplayStyleCondition lateinit var shimoNoKuStyle: DisplayStyleCondition lateinit var inputSecond: InputSecondCondition @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T = QuestionViewModel( questionId, kamiNoKuStyle, shimoNoKuStyle, inputSecond, dispatcher, actionCreator, store, context ) as T } }
apache-2.0
1eb44752f9d0e7352c7acb5cb200b537
30.422619
118
0.663573
4.574523
false
false
false
false
Yubyf/QuoteLock
app/src/main/java/com/crossbowffs/quotelock/app/MainActivity.kt
1
5410
package com.crossbowffs.quotelock.app import android.annotation.SuppressLint import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.os.PowerManager import android.provider.Settings import android.widget.Toast import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import com.crossbowffs.quotelock.R import com.crossbowffs.quotelock.components.ProgressAlertDialog import com.crossbowffs.quotelock.consts.Urls import com.crossbowffs.quotelock.utils.WorkUtils.createQuoteDownloadWork import com.crossbowffs.quotelock.utils.XposedUtils import com.crossbowffs.quotelock.utils.XposedUtils.isModuleEnabled import com.crossbowffs.quotelock.utils.XposedUtils.isModuleUpdated import com.crossbowffs.quotelock.utils.XposedUtils.startXposedActivity import com.crossbowffs.quotelock.utils.mainScope import com.google.android.material.appbar.MaterialToolbar import com.google.android.material.dialog.MaterialAlertDialogBuilder import kotlinx.coroutines.CancellationException import kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { private lateinit var mDialog: ProgressAlertDialog override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Toolbar findViewById<MaterialToolbar>(R.id.toolbar).setOnMenuItemClickListener { if (it.itemId == R.id.refesh_quote) { refreshQuote() } true } supportFragmentManager .beginTransaction() .replace(R.id.preview_frame, PreviewFragment()) .commit() supportFragmentManager .beginTransaction() .replace(R.id.settings_frame, SettingsFragment()) .commit() // In case the user opens the app for the first time *after* rebooting, // we want to make sure the background work has been created. createQuoteDownloadWork(this, false) if (savedInstanceState == null) { if (!isModuleEnabled) { showEnableModuleDialog() } else if (isModuleUpdated) { showModuleUpdatedDialog() } } checkBatteryOptimization() } private fun refreshQuote() { mainScope.launch { mDialog = ProgressAlertDialog(this@MainActivity, getString(R.string.downloading_quote), false) mDialog.show() val quote = try { downloadQuote() } catch (e: CancellationException) { null } mDialog.dismiss() Toast.makeText(this@MainActivity, if (quote == null) R.string.quote_download_failed else R.string.quote_download_success, Toast.LENGTH_SHORT).show() } } private fun startBrowserActivity(url: String) { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(intent) } private fun startXposedPage(section: String) { if (!this.startXposedActivity(section)) { Toast.makeText(this, R.string.xposed_not_installed, Toast.LENGTH_SHORT).show() startBrowserActivity(Urls.XPOSED_FORUM) } } private fun showEnableModuleDialog() { MaterialAlertDialogBuilder(this) .setTitle(R.string.enable_xposed_module_title) .setMessage(R.string.enable_xposed_module_message) .setIcon(R.drawable.ic_baseline_warning_24dp) .setPositiveButton(R.string.enable) { _, _ -> startXposedPage(XposedUtils.XPOSED_SECTION_MODULES) } .setNeutralButton(R.string.report_bug) { _, _ -> startBrowserActivity(Urls.GITHUB_QUOTELOCK_CURRENT_ISSUES) } .setNegativeButton(R.string.ignore, null) .show() } private fun showModuleUpdatedDialog() { MaterialAlertDialogBuilder(this) .setTitle(R.string.module_outdated_title) .setMessage(R.string.module_outdated_message) .setIcon(R.drawable.ic_baseline_warning_24dp) .setPositiveButton(R.string.reboot) { _, _ -> startXposedPage(XposedUtils.XPOSED_SECTION_INSTALL) } .setNegativeButton(R.string.ignore, null) .show() } private fun checkBatteryOptimization() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val packageName = packageName val pm = getSystemService(POWER_SERVICE) as PowerManager if (!pm.isIgnoringBatteryOptimizations(packageName)) { showBatteryOptimizationDialog() } } } @SuppressLint("BatteryLife") @RequiresApi(api = Build.VERSION_CODES.M) private fun showBatteryOptimizationDialog() { MaterialAlertDialogBuilder(this) .setTitle(R.string.battery_optimization_title) .setMessage(R.string.battery_optimization_message) .setPositiveButton(R.string.disable) { _, _ -> val intent = Intent() intent.action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS intent.data = Uri.parse("package:$packageName") startActivity(intent) } .setNegativeButton(R.string.cancel, null) .show() } }
mit
9d68f4681d1af81d6b68d7455c0695da
37.105634
121
0.656192
4.696181
false
false
false
false
infinum/android_dbinspector
dbinspector/src/test/kotlin/com/infinum/dbinspector/domain/pragma/PragmaRepositoryTest.kt
1
4982
package com.infinum.dbinspector.domain.pragma import com.infinum.dbinspector.domain.Control import com.infinum.dbinspector.domain.Interactors import com.infinum.dbinspector.shared.BaseTest import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.mockk import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.koin.core.module.Module import org.koin.dsl.module import org.koin.test.get import org.mockito.kotlin.any @DisplayName("PragmaRepository tests") internal class PragmaRepositoryTest : BaseTest() { override fun modules(): List<Module> = listOf( module { factory { mockk<Interactors.GetUserVersion>() } factory { mockk<Interactors.GetTableInfo>() } factory { mockk<Interactors.GetForeignKeys>() } factory { mockk<Interactors.GetIndexes>() } factory { mockk<Control.Pragma>() } } ) @Test fun `Get user version calls interactor and control once`() { val interactor: Interactors.GetUserVersion = get() val control: Control.Pragma = get() val repository = PragmaRepository( interactor, get(), get(), get(), control ) coEvery { interactor.invoke(any()) } returns mockk() coEvery { control.converter version any() } returns mockk() coEvery { control.mapper.invoke(any()) } returns mockk() test { repository.getUserVersion(any()) } coVerify(exactly = 1) { interactor.invoke(any()) } coVerify(exactly = 1) { control.converter version any() } coVerify(exactly = 1) { control.mapper.invoke(any()) } } @Test fun `Get table info calls interactor and control once`() { val interactor: Interactors.GetTableInfo = get() val control: Control.Pragma = get() val repository = PragmaRepository( get(), interactor, get(), get(), control ) coEvery { interactor.invoke(any()) } returns mockk() coEvery { control.converter pragma any() } returns mockk() coEvery { control.mapper.invoke(any()) } returns mockk() test { repository.getTableInfo(any()) } coVerify(exactly = 1) { interactor.invoke(any()) } coVerify(exactly = 1) { control.converter pragma any() } coVerify(exactly = 1) { control.mapper.invoke(any()) } } @Test @Disabled("This repository call is untestable and needs to be refactored first.") fun `Get trigger info uses TriggerInfoColumns enum and Pragma control mapper transformToHeader`() { val control: Control.Pragma = get() val repository = PragmaRepository( get(), get(), get(), get(), control ) coEvery { control.converter pragma any() } returns mockk() every { control.mapper.transformToHeader() } returns mockk() coEvery { repository.getTriggerInfo() } returns mockk { every { cells } returns listOf() } test { repository.getTriggerInfo() } coVerify(exactly = 0) { control.converter pragma any() } // verify(exactly = 0) { control.mapper.transformToHeader() } } @Test fun `Get foreign keys calls interactor and control once`() { val interactor: Interactors.GetForeignKeys = get() val control: Control.Pragma = get() val repository = PragmaRepository( get(), get(), interactor, get(), control ) coEvery { interactor.invoke(any()) } returns mockk() coEvery { control.converter pragma any() } returns mockk() coEvery { control.mapper.invoke(any()) } returns mockk() test { repository.getForeignKeys(any()) } coVerify(exactly = 1) { interactor.invoke(any()) } coVerify(exactly = 1) { control.converter pragma any() } coVerify(exactly = 1) { control.mapper.invoke(any()) } } @Test fun `Get indexes calls interactor and control once`() { val interactor: Interactors.GetIndexes = get() val control: Control.Pragma = get() val repository = PragmaRepository( get(), get(), get(), interactor, control ) coEvery { interactor.invoke(any()) } returns mockk() coEvery { control.converter pragma any() } returns mockk() coEvery { control.mapper.invoke(any()) } returns mockk() test { repository.getIndexes(any()) } coVerify(exactly = 1) { interactor.invoke(any()) } coVerify(exactly = 1) { control.converter pragma any() } coVerify(exactly = 1) { control.mapper.invoke(any()) } } }
apache-2.0
407cf3743516a08ae34e2b80822dcfb2
30.935897
103
0.592533
4.677934
false
true
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/servicelayer/scopedstorage/MoveConflictedFile.kt
1
7760
/* * Copyright (c) 2022 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.anki.servicelayer.scopedstorage import androidx.annotation.CheckResult import androidx.annotation.VisibleForTesting import com.ichi2.anki.model.Directory import com.ichi2.anki.model.DiskFile import com.ichi2.anki.model.RelativeFilePath import com.ichi2.anki.servicelayer.scopedstorage.migrateuserdata.MigrateUserData.* import com.ichi2.anki.servicelayer.scopedstorage.migrateuserdata.NumberOfBytes import com.ichi2.anki.servicelayer.scopedstorage.migrateuserdata.operationCompleted import com.ichi2.compat.CompatHelper import java.io.File /** * Moves a file from [sourceFile] to [proposedDestinationFile]. * * Ensures that the folder underneath [proposedDestinationFile] exists, and renames the destination file. * if the file at [proposedDestinationFile] exists and has a distinct content, it will increment the filename, attempting to find a filename which is not in use. * if the file at [proposedDestinationFile] exists and has the same content, [sourceFile] is deleted and move is assumed to be successful. * * This does not handle other exceptions, such as a file existing as a directory in the relative path. * * Throws [FileConflictResolutionFailedException] if [proposedDestinationFile] exists, as do all * the other candidate destination files for conflict resolution. * This is unlikely to occur, and is expected to represent an application logic error. * * @see MoveFile for the definition of move */ /* In AnkiDroid planned use, proposedDestinationFile is assumed to be topLevel/conflict/relativePathOfSourceFile */ class MoveConflictedFile private constructor( val sourceFile: DiskFile, val proposedDestinationFile: File ) : Operation() { override fun execute(context: MigrationContext): List<Operation> { // create the "conflict" folder if it didn't exist, and the relative path to the file // example: "AnkiDroid/conflict/collection.media/subfolder" createDirectory(proposedDestinationFile.parentFile!!) // wrap the context so we can handle internal file conflict exceptions, and set the correct // 'operation' if an error occurs. val wrappedContext = ContextHandlingFileConflictException(context, this) // loop from "filename.ext", then "filename (1).ext" to "filename (${MAX_RENAMES - 1}).ext" to ensure we transfer the file for (potentialDestinationFile in queryCandidateFilenames(proposedDestinationFile)) { return try { moveFile(potentialDestinationFile, wrappedContext) if (wrappedContext.handledFileConflictSinceLastReset) { wrappedContext.reset() continue // we had a conflict, try the next name } // the operation completed, with or without an error report. Don't try again operationCompleted() } catch (ex: Exception) { // We had an exception not handled by Operation, // or one that ContextHandlingFileConflictException decided to re-throw. // Don't try a different name wrappedContext.reportError(this, ex) operationCompleted() } } throw FileConflictResolutionFailedException(sourceFile, proposedDestinationFile) } @VisibleForTesting internal fun moveFile(potentialDestinationFile: File, wrappedContext: ContextHandlingFileConflictException) { MoveFile(sourceFile, potentialDestinationFile).execute(wrappedContext) } private fun createDirectory(folder: File) = CompatHelper.compat.createDirectories(folder) companion object { const val CONFLICT_DIRECTORY = "conflict" /** * @param sourceFile The file to move from * @param destinationTopLevel The top level directory to move to (non-relative path). "/storage/emulated/0/AnkiDroid/" * @param sourceRelativePath The relative path of the file. Does not start with /conflict/. * Is a suffix of [sourceFile]'s path: "/collection.media/image.jpg" */ fun createInstance( sourceFile: DiskFile, destinationTopLevel: Directory, sourceRelativePath: RelativeFilePath ): MoveConflictedFile { // we add /conflict/ to the path inside this method. If this already occurred, something was wrong if (sourceRelativePath.path.firstOrNull() == CONFLICT_DIRECTORY) { throw IllegalStateException("can't move from a root path of 'conflict': $sourceRelativePath") } val conflictedPath = sourceRelativePath.unsafePrependDirectory(CONFLICT_DIRECTORY) val destinationFile = conflictedPath.toFile(baseDir = destinationTopLevel) return MoveConflictedFile(sourceFile, destinationFile) } @VisibleForTesting @CheckResult internal fun queryCandidateFilenames(templateFile: File) = sequence { yield(templateFile) // examples from a file named: "helloWorld.tmp". the dot between name and extension isn't included val filename = templateFile.nameWithoutExtension // 'helloWorld' val extension = templateFile.extension // 'tmp' for (i in 1 until MAX_DESTINATION_NAMES) { // 1..4 val newFileName = "$filename ($i).$extension" // 'helloWorld (1).tmp' yield(File(templateFile.parent, newFileName)) } } /** * The max number of attempts to rename a file * * "filename.ext", then "filename (1).ext" ... "filename (4).ext" * where 4 = MAX_DESTINATION_NAMES - 1 */ const val MAX_DESTINATION_NAMES = 5 } /** * Wrapper around [MigrateUserData.MigrationContext]. * Ignores [FileConflictException], behaves as [MigrateUserData.MigrationContext] otherwise. * Reports errors using the provided [operation] */ class ContextHandlingFileConflictException( private val wrappedContext: MigrationContext, private val operation: Operation ) : MigrationContext() { /** Whether at least one [FileConflictException] was handled and ignored */ var handledFileConflictSinceLastReset = false /** Resets the status of [handledFileConflictSinceLastReset] */ fun reset() { handledFileConflictSinceLastReset = false } override fun reportError(throwingOperation: Operation, ex: Exception) { if (ex is FileConflictException || ex is FileDirectoryConflictException) { handledFileConflictSinceLastReset = true return } // report error using the operation passed into the ContextHandlingFileConflictException // (MoveConflictedFile) wrappedContext.reportError(operation, ex) } override fun reportProgress(transferred: NumberOfBytes) = wrappedContext.reportProgress(transferred) } }
gpl-3.0
30e2716835d058e450ff883320639445
44.91716
161
0.691753
4.94898
false
false
false
false
Aidanvii7/Toolbox
redux/src/main/java/com/aidanvii/toolbox/redux/SideEffects.kt
1
2162
package com.aidanvii.toolbox.redux import com.aidanvii.toolbox.rxutils.RxSchedulers import com.aidanvii.toolbox.rxutils.disposeOnReassign import io.reactivex.disposables.Disposable import io.reactivex.rxkotlin.subscribeBy import java.util.concurrent.atomic.AtomicBoolean import kotlin.reflect.KClass abstract class SideEffects<Action : Any, State>( private val store: Store<Action, State>, protected val rxSchedulers: RxSchedulers ) : Disposable { private var storeDisposable by disposeOnReassign() private val initialised = AtomicBoolean(false) private val disposed = AtomicBoolean(false) fun init() { if (!initialised.getAndSet(true)) { storeDisposable = subscribeToStore() } } final override fun isDisposed() = disposed.get() final override fun dispose() { if (!disposed.getAndSet(true)) { storeDisposable = null onDisposed() } } private fun subscribeToStore(): Disposable { return store.actionsObservable .subscribeOn(rxSchedulers.single) .subscribeBy { actions -> handleActions(actions) } } private fun handleActions(actions: List<Action>) { actionDispatcherFor(actions).let { actionDispatcher -> actions.forEach { action -> actionDispatcher.handleAction(action) } } } open fun actionDispatcherFor(actions: List<Action>): ActionDispatcher<Action> = SimpleActionDispatcher(store) protected fun List<Action>.bufferedActionDispatcherWhenContains(vararg actionTypes: KClass<*>): ActionDispatcher<Action> = if (containsActionTypes(*actionTypes)) BufferedActionDispatcher( store, actionTypes.size ) else SimpleActionDispatcher(store) protected fun List<Action>.containsActionTypes(vararg actionTypes: KClass<*>): Boolean = actionTypes.all { actionType -> firstOrNull { action -> action::class == actionType } != null } abstract fun ActionDispatcher<Action>.handleAction(action: Action) abstract fun onDisposed() }
apache-2.0
38cf890aa4dced2687c8e77889e76ac9
31.268657
126
0.675301
5.027907
false
false
false
false
FarbodSalamat-Zadeh/TimetableApp
app/src/main/java/co/timetableapp/data/query/Filters.kt
1
1574
/* * Copyright 2017 Farbod Salamat-Zadeh * * 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 co.timetableapp.data.query /** * A collection of static helper functions for creating or combining filters. * * @see Filter * @see Query */ object Filters { @JvmStatic fun equal(property: String, value: String)= Filter("$property = $value") @JvmStatic fun and(filter1: Filter, filter2: Filter, vararg moreFilters: Filter) = joinFilters("AND", filter1, filter2, *moreFilters) @JvmStatic fun or(filter1: Filter, filter2: Filter, vararg moreFilters: Filter) = joinFilters("OR", filter1, filter2, *moreFilters) @JvmStatic private fun joinFilters(sqlKeyword: String, filter1: Filter, filter2: Filter, vararg moreFilters: Filter): Filter { var sql: String = "${filter1.sqlStatement} $sqlKeyword ${filter2.sqlStatement}" for ((sqlStatement) in moreFilters) { sql = "$sql $sqlKeyword $sqlStatement" } return Filter(sql) } }
apache-2.0
e4fd522f5bd9274ae9948ca7004769fd
30.48
87
0.677891
4.120419
false
false
false
false
kikermo/Things-Audio-Renderer
renderer/src/main/java/org/kikermo/thingsaudio/renderer/nowplaying/NowPlayingFragment.kt
1
1571
package org.kikermo.thingsaudio.renderer.nowplaying import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.fragment_now_playing.* import org.kikermo.thingsaudio.core.base.BaseFragmentWithPresenter import org.kikermo.thingsaudio.core.model.PlayState import org.kikermo.thingsaudio.core.model.Track import org.kikermo.thingsaudio.core.utils.toFormattedSeconds import org.kikermo.thingsaudioreceiver.R class NowPlayingFragment : BaseFragmentWithPresenter<NowPlayingContract.View, NowPlayingContract.Presenter>(), NowPlayingContract.View { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_now_playing, container, false) override fun updateTrack(track: Track) { now_playing_track_name.text = track.title now_playing_artist_name.text = track.artist now_playing_artist_name.text = track.album now_playing_track_lenght.text = track.length.toFormattedSeconds() now_playing_progress_bar.max = track.length Picasso.with(context) .load(track.art) .into(now_playing_art) } override fun updatePosition(position: Int) { now_playing_progress_bar.progress = position now_playing_progress_text.text = position.toFormattedSeconds() } override fun updatePlayState(playState: PlayState) { } }
gpl-3.0
8b58a7dbd1aab17f204fce5aba16d1ea
36.404762
110
0.742202
4.101828
false
false
false
false
udevbe/westmalle
compositor/src/main/kotlin/org/westford/nativ/linux/InputEventCodes.kt
3
8334
/* * Westford Wayland Compositor. * Copyright (C) 2016 Erik De Rijcke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.westford.nativ.linux /** * input-event-codes.h */ object InputEventCodes { val BTN_LEFT = 0x110 val BTN_RIGHT = 0x111 val BTN_MIDDLE = 0x112 val BTN_SIDE = 0x113 val KEY_RESERVED = 0 val KEY_ESC = 1 val KEY_1 = 2 val KEY_2 = 3 val KEY_3 = 4 val KEY_4 = 5 val KEY_5 = 6 val KEY_6 = 7 val KEY_7 = 8 val KEY_8 = 9 val KEY_9 = 10 val KEY_0 = 11 val KEY_MINUS = 12 val KEY_EQUAL = 13 val KEY_BACKSPACE = 14 val KEY_TAB = 15 val KEY_Q = 16 val KEY_W = 17 val KEY_E = 18 val KEY_R = 19 val KEY_T = 20 val KEY_Y = 21 val KEY_U = 22 val KEY_I = 23 val KEY_O = 24 val KEY_P = 25 val KEY_LEFTBRACE = 26 val KEY_RIGHTBRACE = 27 val KEY_ENTER = 28 val KEY_LEFTCTRL = 29 val KEY_A = 30 val KEY_S = 31 val KEY_D = 32 val KEY_F = 33 val KEY_G = 34 val KEY_H = 35 val KEY_J = 36 val KEY_K = 37 val KEY_L = 38 val KEY_SEMICOLON = 39 val KEY_APOSTROPHE = 40 val KEY_GRAVE = 41 val KEY_LEFTSHIFT = 42 val KEY_BACKSLASH = 43 val KEY_Z = 44 val KEY_X = 45 val KEY_C = 46 val KEY_V = 47 val KEY_B = 48 val KEY_N = 49 val KEY_M = 50 val KEY_COMMA = 51 val KEY_DOT = 52 val KEY_SLASH = 53 val KEY_RIGHTSHIFT = 54 val KEY_KPASTERISK = 55 val KEY_LEFTALT = 56 val KEY_SPACE = 57 val KEY_CAPSLOCK = 58 val KEY_F1 = 59 val KEY_F2 = 60 val KEY_F3 = 61 val KEY_F4 = 62 val KEY_F5 = 63 val KEY_F6 = 64 val KEY_F7 = 65 val KEY_F8 = 66 val KEY_F9 = 67 val KEY_F10 = 68 val KEY_NUMLOCK = 69 val KEY_SCROLLLOCK = 70 val KEY_KP7 = 71 val KEY_KP8 = 72 val KEY_KP9 = 73 val KEY_KPMINUS = 74 val KEY_KP4 = 75 val KEY_KP5 = 76 val KEY_KP6 = 77 val KEY_KPPLUS = 78 val KEY_KP1 = 79 val KEY_KP2 = 80 val KEY_KP3 = 81 val KEY_KP0 = 82 val KEY_KPDOT = 83 val KEY_ZENKAKUHANKAKU = 85 val KEY_102ND = 86 val KEY_F11 = 87 val KEY_F12 = 88 val KEY_RO = 89 val KEY_KATAKANA = 90 val KEY_HIRAGANA = 91 val KEY_HENKAN = 92 val KEY_KATAKANAHIRAGANA = 93 val KEY_MUHENKAN = 94 val KEY_KPJPCOMMA = 95 val KEY_KPENTER = 96 val KEY_RIGHTCTRL = 97 val KEY_KPSLASH = 98 val KEY_SYSRQ = 99 val KEY_RIGHTALT = 100 val KEY_LINEFEED = 101 val KEY_HOME = 102 val KEY_UP = 103 val KEY_PAGEUP = 104 val KEY_LEFT = 105 val KEY_RIGHT = 106 val KEY_END = 107 val KEY_DOWN = 108 val KEY_PAGEDOWN = 109 val KEY_INSERT = 110 val KEY_DELETE = 111 val KEY_MACRO = 112 val KEY_MUTE = 113 val KEY_VOLUMEDOWN = 114 val KEY_VOLUMEUP = 115 val KEY_POWER = 116 /* SC System Power Down */ val KEY_KPEQUAL = 117 val KEY_KPPLUSMINUS = 118 val KEY_PAUSE = 119 val KEY_SCALE = 120 /* AL Compiz Scale (Expose) */ val KEY_KPCOMMA = 121 val KEY_HANGEUL = 122 val KEY_HANGUEL = KEY_HANGEUL val KEY_HANJA = 123 val KEY_YEN = 124 val KEY_LEFTMETA = 125 val KEY_RIGHTMETA = 126 val KEY_COMPOSE = 127 val KEY_STOP = 128 /* AC Stop */ val KEY_AGAIN = 129 val KEY_PROPS = 130/* AC Properties */ val KEY_UNDO = 131 /* AC Undo */ val KEY_FRONT = 132 val KEY_COPY = 133 /* AC Copy */ val KEY_OPEN = 134 /* AC Open */ val KEY_PASTE = 135 /* AC Paste */ val KEY_FIND = 136 /* AC Search */ val KEY_CUT = 137 /* AC Cut */ val KEY_HELP = 138 /* AL Integrated Help Center */ val KEY_MENU = 139 /* Menu (show menu) */ val KEY_CALC = 140 /* AL Calculator */ val KEY_SETUP = 141 val KEY_SLEEP = 142 /* SC System Sleep */ val KEY_WAKEUP = 143 /* System Wake Up */ val KEY_FILE = 144 /* AL Local Machine Browser */ val KEY_SENDFILE = 145 val KEY_DELETEFILE = 146 val KEY_XFER = 147 val KEY_PROG1 = 148 val KEY_PROG2 = 149 val KEY_WWW = 150 /* AL Internet Browser */ val KEY_MSDOS = 151 val KEY_COFFEE = 152 /* AL Terminal Lock/Screensaver */ val KEY_SCREENLOCK = KEY_COFFEE val KEY_ROTATE_DISPLAY = 153 /* Display orientation for e.g. tablets */ val KEY_DIRECTION = KEY_ROTATE_DISPLAY val KEY_CYCLEWINDOWS = 154 val KEY_MAIL = 155 val KEY_BOOKMARKS = 156 /* AC Bookmarks */ val KEY_COMPUTER = 157 val KEY_BACK = 158 /* AC Back */ val KEY_FORWARD = 159 /* AC Forward */ val KEY_CLOSECD = 160 val KEY_EJECTCD = 161 val KEY_EJECTCLOSECD = 162 val KEY_NEXTSONG = 163 val KEY_PLAYPAUSE = 164 val KEY_PREVIOUSSONG = 165 val KEY_STOPCD = 166 val KEY_RECORD = 167 val KEY_REWIND = 168 val KEY_PHONE = 169 /* Media Select Telephone */ val KEY_ISO = 170 val KEY_CONFIG = 171 /* AL Consumer Control Configuration */ val KEY_HOMEPAGE = 172 /* AC Home */ val KEY_REFRESH = 173 /* AC Refresh */ val KEY_EXIT = 174 /* AC Exit */ val KEY_MOVE = 175 val KEY_EDIT = 176 val KEY_SCROLLUP = 177 val KEY_SCROLLDOWN = 178 val KEY_KPLEFTPAREN = 179 val KEY_KPRIGHTPAREN = 180 val KEY_NEW = 181 /* AC New */ val KEY_REDO = 182 /* AC Redo/Repeat */ val KEY_F13 = 183 val KEY_F14 = 184 val KEY_F15 = 185 val KEY_F16 = 186 val KEY_F17 = 187 val KEY_F18 = 188 val KEY_F19 = 189 val KEY_F20 = 190 val KEY_F21 = 191 val KEY_F22 = 192 val KEY_F23 = 193 val KEY_F24 = 194 val KEY_PLAYCD = 200 val KEY_PAUSECD = 201 val KEY_PROG3 = 202 val KEY_PROG4 = 203 val KEY_DASHBOARD = 204 /* AL Dashboard */ val KEY_SUSPEND = 205 val KEY_CLOSE = 206 /* AC Close */ val KEY_PLAY = 207 val KEY_FASTFORWARD = 208 val KEY_BASSBOOST = 209 val KEY_PRINT = 210 /* AC Print */ val KEY_HP = 211 val KEY_CAMERA = 212 val KEY_SOUND = 213 val KEY_QUESTION = 214 val KEY_EMAIL = 215 val KEY_CHAT = 216 val KEY_SEARCH = 217 val KEY_CONNECT = 218 val KEY_FINANCE = 219 /* AL Checkbook/Finance */ val KEY_SPORT = 220 val KEY_SHOP = 221 val KEY_ALTERASE = 222 val KEY_CANCEL = 223 /* AC Cancel */ val KEY_BRIGHTNESSDOWN = 224 val KEY_BRIGHTNESSUP = 225 val KEY_MEDIA = 226 val KEY_SWITCHVIDEOMODE = 227 /* Cycle between available video outputs (Monitor/LCD/TV-out/etc) */ val KEY_KBDILLUMTOGGLE = 228 val KEY_KBDILLUMDOWN = 229 val KEY_KBDILLUMUP = 230 val KEY_SEND = 231 /* AC Send */ val KEY_REPLY = 232 /* AC Reply */ val KEY_FORWARDMAIL = 233 /* AC Forward Msg */ val KEY_SAVE = 234 /* AC Save */ val KEY_DOCUMENTS = 235 val KEY_BATTERY = 236 val KEY_BLUETOOTH = 237 val KEY_WLAN = 238 val KEY_UWB = 239 val KEY_UNKNOWN = 240 val KEY_VIDEO_NEXT = 241 /* drive next video source */ val KEY_VIDEO_PREV = 242 /* drive previous video source */ val KEY_BRIGHTNESS_CYCLE = 243 /* brightness up, after max is min */ val KEY_BRIGHTNESS_AUTO = 244 /* Set Auto Brightness: manual brightness control is off, rely on ambient */ val KEY_BRIGHTNESS_ZERO = KEY_BRIGHTNESS_AUTO val KEY_DISPLAY_OFF = 245 /* display device to off state */ val KEY_WWAN = 246 /* Wireless WAN (LTE, UMTS, GSM, etc.) */ val KEY_WIMAX = KEY_WWAN val KEY_RFKILL = 247 /* Key that controls all radios */ val KEY_MICMUTE = 248 /* Mute / unmute the microphone */ }
agpl-3.0
c6d4f8e046bc8e72d7adff8fb7cc5325
27.346939
78
0.590593
3.317675
false
false
false
false
binaryfoo/emv-bertlv
src/main/java/io/github/binaryfoo/tlv/BerTlv.kt
1
6948
package io.github.binaryfoo.tlv import java.nio.ByteBuffer import java.util.* /** * Model data elements encoded using the Basic Encoding Rules: http://en.wikipedia.org/wiki/X.690#BER_encoding. */ abstract class BerTlv(val tag: Tag) { fun toBinary(): ByteArray { val value = getValue() val encodedTag = tag.bytes val encodedLength = getLength(value) val b = ByteBuffer.allocate(encodedTag.size + encodedLength.size + value.size) b.put(encodedTag.toByteArray()) b.put(encodedLength) b.put(value) b.flip() return b.array() } /** * The whole object (the T, L and V components) as a hex string. */ fun toHexString(): String = ISOUtil.hexString(toBinary()) /** * The value of V in TLV as a hex string. */ val valueAsHexString: String get() = ISOUtil.hexString(getValue()) /** * The number of bytes used to encode the L (length) in TLV. * Eg 1 byte might be used to encode a length of 12, whilst at least 2 bytes would be used for a length of 300. */ val lengthInBytesOfEncodedLength: Int get() = getLength(getValue()).size /** * The value of L (length) in TLV. Length in bytes of the value. */ val length: Int get() = getValue().size /** * Skip the tag and length bytes. */ val startIndexOfValue: Int get() = tag.bytes.size + lengthInBytesOfEncodedLength abstract fun findTlv(tag: Tag): BerTlv? abstract fun findTlvs(tag: Tag): List<BerTlv> /** * The value of V in TLV as a byte array. */ abstract fun getValue(): ByteArray /** * For a constructed TLV the child elements that make up the V. For a primitive, an empty list. */ abstract fun getChildren(): List<BerTlv> private fun getLength(value: ByteArray?): ByteArray { val length: ByteArray if (value == null) { return byteArrayOf(0.toByte()) } if (value.size <= 0x7F) { length = byteArrayOf(value.size.toByte()) } else { val wanted = value.size var expected = 256 var needed = 1 while (wanted >= expected) { needed++ expected = expected shl 8 if (expected == 0) { // just to be sure throw IllegalArgumentException() } } length = ByteArray(needed + 1) length[0] = (0x80 or needed).toByte() for (i in 1..length.size - 1) { length[length.size - i] = ((wanted shr (8 * (i - 1))) and 255).toByte() } } return length } companion object { @JvmStatic fun newInstance(tag: Tag, value: ByteArray): BerTlv { return PrimitiveBerTlv(tag, value) } @JvmStatic fun newInstance(tag: Tag, hexString: String): BerTlv { return PrimitiveBerTlv(tag, ISOUtil.hex2byte(hexString)) } @JvmStatic fun newInstance(tag: Tag, value: Int): BerTlv { if (value > 255) { throw IllegalArgumentException("Value greater than 255 must be encoded in a byte array") } return PrimitiveBerTlv(tag, byteArrayOf(value.toByte())) } @JvmStatic fun newInstance(tag: Tag, value: List<BerTlv>): BerTlv { return ConstructedBerTlv(tag, value) } @JvmStatic fun newInstance(tag: Tag, tlv1: BerTlv, tlv2: BerTlv): BerTlv { return ConstructedBerTlv(tag, Arrays.asList<BerTlv>(tlv1, tlv2)) } @JvmStatic fun parse(data: ByteArray): BerTlv { return parseList(ByteBuffer.wrap(data), true)[0] } @JvmStatic fun parseAsPrimitiveTag(data: ByteArray): BerTlv { return parseList(ByteBuffer.wrap(data), false)[0] } @JvmStatic fun parseList(data: ByteArray, parseConstructedTags: Boolean): List<BerTlv> { return parseList(ByteBuffer.wrap(data), parseConstructedTags) } @JvmStatic fun parseList(data: ByteArray, parseConstructedTags: Boolean, recognitionMode: TagRecognitionMode): List<BerTlv> { return parseList(ByteBuffer.wrap(data), parseConstructedTags, recognitionMode) } private fun parseList(data: ByteBuffer, parseConstructedTags: Boolean, recognitionMode: TagRecognitionMode = CompliantTagMode): List<BerTlv> { val tlvs = ArrayList<BerTlv>() while (data.hasRemaining()) { val tag = Tag.parse(data, recognitionMode) if (isPaddingByte(tag)) { continue } try { val length = parseLength(data) val value = readUpToLength(data, length) if (tag.constructed && parseConstructedTags) { try { tlvs.add(newInstance(tag, parseList(value, true, recognitionMode))) } catch (e: Exception) { tlvs.add(newInstance(tag, value)) } } else { tlvs.add(newInstance(tag, value)) } } catch (e: Exception) { throw TlvParseException(tlvs, "Failed parsing TLV with tag $tag: " + e.message, e) } } return tlvs } private fun readUpToLength(data: ByteBuffer, length: Int): ByteArray { val value = ByteArray(if (length > data.remaining()) data.remaining() else length) data.get(value) return value } // Specification Update No. 69, 2009, Padding of BER-TLV Encoded Constructed Data Objects private fun isPaddingByte(tag: Tag): Boolean { return tag.bytes.size == 1 && tag.bytes[0] == 0.toByte() } private fun parseLength(data: ByteBuffer): Int { val firstByte = data.get().toInt() val numberOfBytesToEncodeLength = additionalBytesToEncodeLength(firstByte) return if (numberOfBytesToEncodeLength != null) { var length = 0 for (i in 1..numberOfBytesToEncodeLength) { if (!data.hasRemaining()) { throw IllegalArgumentException("Bad length: expected to read $numberOfBytesToEncodeLength (0x${firstByte.toByte().toHexString()}) bytes. Only have ${i - 1}.") } length += (data.get().toInt() and 0xFF) if (i != numberOfBytesToEncodeLength) { length *= 256 } if (length < 0) { throw IllegalArgumentException("Bad length: $length < 0. Read $i of $numberOfBytesToEncodeLength (0x${firstByte.toByte().toHexString()}) bytes used to encode length of TLV.") } } length } else { firstByte and 0x000000FF } } private fun additionalBytesToEncodeLength(firstByte: Int): Int? { val numberOfBytesToEncodeLength = (firstByte and 0x7F) // Bit 8 == 1 indicates length is encoded in a variable number of bytes // Bit 8 == 0 indicates length is encoded in a single byte (<128) // Assumption: Bit 8 == 1 and >5 bytes implies a single byte (128..254) return if ((firstByte and 0x80) == 0x80 && numberOfBytesToEncodeLength <= 5) { numberOfBytesToEncodeLength } else { null } } @JvmStatic fun findTlv(tlvs: List<BerTlv>, tag: Tag): BerTlv? = tlvs.firstOrNull { it.tag == tag } } }
mit
af1e4c2d8d02dca48654ff6c29f8d514
29.743363
186
0.627231
4.020833
false
false
false
false
prof18/YoutubeParser
youtubeparser/src/main/java/com/prof/youtubeparser/models/videos/internal/Snippet.kt
1
958
/* * Copyright 2016 Marco Gomiero * * 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.prof.youtubeparser.models.videos.internal internal data class Snippet( val publishedAt: String? = null, val channelId: String? = null, val title: String? = null, val description: String? = null, val thumbnails: Thumbnails? = null, val channelTitle: String? = null, val liveBroadcastContent: String? = null )
apache-2.0
926e9b9a0a5db787301d7d9126549205
33.214286
76
0.715031
3.92623
false
false
false
false
Kotlin/kotlinx.serialization
core/commonTest/src/kotlinx/serialization/SerialDescriptorEqualityTest.kt
1
3254
/* * Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization import kotlinx.serialization.builtins.* import kotlinx.serialization.descriptors.* import kotlin.test.* class SerialDescriptorEqualityTest { @Serializable class TypeParamUsedOnce<T>(val t: T) @Serializable @SerialName("TypeParamUsedTwice") class TypeParamUsedTwice<T>(val t: T, val l: List<T>) @Serializable class TypeParamInList<T>(val l: List<T>) @Serializable class RecursiveSimple(val desc: String, var node: RecursiveSimple?) @Serializable class Recursive<T>(val desc: T, var node: Recursive<T>?) @Serializable open class RecursiveGeneric<T : RecursiveGeneric<T>>() @Serializable class RecursiveGenericImpl(var other: RecursiveGeneric<RecursiveGenericImpl>? = null) : RecursiveGeneric<RecursiveGenericImpl>() private fun doTestWith(factory: (KSerializer<*>, KSerializer<*>) -> Pair<SerialDescriptor, SerialDescriptor>) { val (a, b) = factory(Int.serializer(), Int.serializer()) assertEquals(a, b) val (c, d) = factory(Int.serializer(), String.serializer()) assertNotEquals(c, d) } @Test fun testUsedOnce() = doTestWith { d1, d2 -> TypeParamUsedOnce.serializer(d1).descriptor to TypeParamUsedOnce.serializer(d2).descriptor } @Test fun testUsedTwice() = doTestWith { d1, d2 -> TypeParamUsedTwice.serializer(d1).descriptor to TypeParamUsedTwice.serializer(d2).descriptor } @Test fun testUsedInList() = doTestWith { d1, d2 -> TypeParamInList.serializer(d1).descriptor to TypeParamInList.serializer(d2).descriptor } @Test fun testRecursive() = doTestWith { d1, d2 -> Recursive.serializer(d1).descriptor to Recursive.serializer(d2).descriptor } @Test fun testRecursiveSimple() { val desc = RecursiveSimple.serializer().descriptor assertEquals(desc, desc) assertNotEquals(desc, Recursive.serializer(String.serializer()).descriptor) } @Test fun testRecursiveGeneric() { val descriptor1 = RecursiveGeneric.serializer(RecursiveGenericImpl.serializer()).descriptor val descriptor2 = RecursiveGeneric.serializer(RecursiveGenericImpl.serializer()).descriptor val descriptor3 = RecursiveGeneric.serializer(RecursiveGeneric.serializer(RecursiveGenericImpl.serializer())).descriptor assertNotEquals(descriptor1, descriptor3) assertEquals(descriptor1, descriptor2) } @Test fun testCantBeComparedToUserDescriptor() { val typeParam = Int.serializer().descriptor val userDefinedWithInt = buildClassSerialDescriptor("TypeParamUsedTwice", typeParam) { element("t", typeParam) element("l", listSerialDescriptor(typeParam)) } val generatedWithInt = TypeParamUsedTwice.serializer(Int.serializer()).descriptor val generatedWithString = TypeParamUsedTwice.serializer(String.serializer()).descriptor assertNotEquals(generatedWithInt, userDefinedWithInt) assertNotEquals(generatedWithString, userDefinedWithInt) } }
apache-2.0
bb837cc2de8054f22d24715d283144e9
33.989247
115
0.700676
4.570225
false
true
false
false
davidwhitman/changelogs
playstoreapi/src/test/java/com/thunderclouddev/playstoreapi/RxOkHttpClientTest.kt
1
2737
/* * Copyright (c) 2017. * Distributed under the GNU GPLv3 by David Whitman. * https://www.gnu.org/licenses/gpl-3.0.en.html * * This source code is made available to help others learn. Please don't clone my app. */ package com.thunderclouddev.playstoreapi import com.nhaarman.mockito_kotlin.mock import okhttp3.Call import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.context import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.junit.Assert import org.junit.platform.runner.JUnitPlatform import org.junit.runner.RunWith import org.mockito.Mockito.`when` @RunWith(JUnitPlatform::class) object RxOkHttpClientTest : Spek({ given("an RxOkHttpClient") { var httpClient = mock<OkHttpClient>() var client = RxOkHttpClient(httpClient) var response = mock<Response>() beforeEachTest { val call = mock<Call>() httpClient = mock<OkHttpClient>() client = RxOkHttpClient(httpClient) response = mock<Response>() `when`(httpClient.newCall(anyKt<Request>())) .thenReturn(call) `when`(call.execute()).thenReturn(response) } context("is that the api calls succeed") { beforeEachTest { `when`(response.code()).thenReturn(200) } it("should be that the value is returned") { client.rxecute(mock<Request>()) .subscribe { response, error -> Assert.assertNull(error) Assert.assertNotNull(response) } } } context("is that the api calls fail with 400") { beforeEachTest { `when`(response.code()).thenReturn(400) } it("should be that the single throws an error") { client.rxecute(mock<Request>()) .subscribe { response, error -> Assert.assertNull(response) Assert.assertNotNull(error) } } } context("is that the api calls fail with 500") { beforeEachTest { `when`(response.code()).thenReturn(500) } it("should be that the single throws an error") { client.rxecute(mock<Request>()) .subscribe { response, error -> Assert.assertNull(response) Assert.assertNotNull(error) } } } } })
gpl-3.0
c5b45fe8aeb3bcf422aa686ad792399a
31.211765
86
0.551699
4.870107
false
true
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/templates/LatexTemplatesFactory.kt
1
3901
package nl.hannahsten.texifyidea.templates import com.intellij.ide.fileTemplates.FileTemplateDescriptor import com.intellij.ide.fileTemplates.FileTemplateGroupDescriptor import com.intellij.ide.fileTemplates.FileTemplateGroupDescriptorFactory import com.intellij.ide.fileTemplates.FileTemplateManager import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.project.Project import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileFactory import nl.hannahsten.texifyidea.TeXception import nl.hannahsten.texifyidea.TexifyIcons import nl.hannahsten.texifyidea.util.Container import java.io.IOException import java.util.* /** * @author Hannah Schellekens */ open class LatexTemplatesFactory : FileTemplateGroupDescriptorFactory { companion object { const val descriptor = "LaTeX" const val fileTemplateTex = "LaTeX Source.tex" const val fileTemplateTexWithBib = "LaTeX Source With BibTeX.tex" const val fileTemplateSty = "LaTeX Package.sty" const val fileTemplateCls = "LaTeX Document class.cls" const val fileTemplateBib = "BibTeX Bibliography.bib" const val fileTemplateTikz = "TikZ Picture.tikz" @JvmStatic fun createFromTemplate( directory: PsiDirectory, fileName: String, templateName: String, fileType: FileType ): PsiFile { val project = directory.project val templateText = getTemplateText(project, templateName, fileName) val fileFactory = PsiFileFactory.getInstance(project) val file = fileFactory.createFileFromText(fileName, fileType, templateText) val createdFile = Container<PsiFile>() val application = ApplicationManager.getApplication() application.runWriteAction { createdFile.item = directory.add(file) as PsiFile } return createdFile.item ?: throw TeXception("No created file in container.") } /** * Get the text from a certain template. * * @param project * The IntelliJ project that contains the templates. * @param templateName * The name of the template. Use the constants prefixed with `FILE_TEMPLATE_` from * [LatexTemplatesFactory]. * @return The contents of the template with applied properties. */ @JvmStatic fun getTemplateText(project: Project, templateName: String, fileName: String): String { val templateManager = FileTemplateManager.getInstance(project) val template = templateManager.getInternalTemplate(templateName) val properties = Properties(templateManager.defaultProperties) properties["FILE_NAME"] = fileName try { return template.getText(properties) } catch (e: IOException) { throw TeXception("Could not load template $templateName", e) } } } override fun getFileTemplatesDescriptor(): FileTemplateGroupDescriptor { val descriptor = FileTemplateGroupDescriptor( descriptor, TexifyIcons.LATEX_FILE ) descriptor.addTemplate(FileTemplateDescriptor(fileTemplateTex, TexifyIcons.LATEX_FILE)) descriptor.addTemplate(FileTemplateDescriptor(fileTemplateTexWithBib, TexifyIcons.LATEX_FILE)) descriptor.addTemplate(FileTemplateDescriptor(fileTemplateSty, TexifyIcons.STYLE_FILE)) descriptor.addTemplate(FileTemplateDescriptor(fileTemplateCls, TexifyIcons.CLASS_FILE)) descriptor.addTemplate(FileTemplateDescriptor(fileTemplateBib, TexifyIcons.BIBLIOGRAPHY_FILE)) descriptor.addTemplate(FileTemplateDescriptor(fileTemplateTikz, TexifyIcons.TIKZ_FILE)) return descriptor } }
mit
8c78d3052f1b0ea8fe2f2ab8595b87c0
40.946237
102
0.710587
5.278755
false
false
false
false
actorapp/actor-bots
actor-bots/src/main/java/im/actor/bots/framework/traits/HTTPTrait.kt
1
4076
package im.actor.bots.framework.traits import org.apache.commons.io.IOUtils import org.apache.http.client.methods.HttpGet import org.apache.http.client.methods.HttpPost import org.apache.http.entity.ContentType import org.apache.http.entity.StringEntity import org.apache.http.impl.client.CloseableHttpClient import org.apache.http.impl.client.HttpClients import org.json.JSONArray import org.json.JSONObject import java.io.IOException /** * HTTP Requesting Trait */ interface HTTPTrait { fun urlGetText(url: String, vararg headers: String): String? fun urlPostUrlEncodedText(url: String, content: String, vararg headers: String): String? fun urlPostJson(url: String, content: Json, vararg headers: String): Json? fun urlGetJson(url: String, vararg headers: String): Json? } class HTTPTraitImpl : HTTPTrait { private var client: CloseableHttpClient? = null override fun urlGetText(url: String, vararg headers: String): String? { assumeHttp() try { val get = HttpGet(url) for (i in 0..headers.size / 2 - 1) { get.addHeader(headers[i * 2], headers[i * 2 + 1]) } val res = client!!.execute(get) val text = IOUtils.toString(res.entity.content) res.close() if (res.statusLine.statusCode >= 200 && res.statusLine.statusCode < 300) { return text } return null } catch (e: IOException) { e.printStackTrace() } return null } override fun urlPostUrlEncodedText(url: String, content: String, vararg headers: String): String? { assumeHttp() try { val post = HttpPost(url) for (i in 0..headers.size / 2 - 1) { post.addHeader(headers[i * 2], headers[i * 2 + 1]) } post.entity = StringEntity(content, ContentType.APPLICATION_FORM_URLENCODED) val res = client!!.execute(post) val text = IOUtils.toString(res.entity.content) res.close() if (res.statusLine.statusCode >= 200 && res.statusLine.statusCode < 300) { return text } return null } catch (e: IOException) { e.printStackTrace() } return null } override fun urlPostJson(url: String, content: Json, vararg headers: String): Json? { assumeHttp() try { val post = HttpPost(url) for (i in 0..headers.size / 2 - 1) { post.addHeader(headers[i * 2], headers[i * 2 + 1]) } post.entity = StringEntity(content.toString(), ContentType.APPLICATION_JSON) val res = client!!.execute(post) val text = IOUtils.toString(res.entity.content) res.close() if (res.statusLine.statusCode >= 200 && res.statusLine.statusCode < 300) { return parseJson(text) } return null } catch (e: IOException) { e.printStackTrace() } return null } override fun urlGetJson(url: String, vararg headers: String): Json? { val res = urlGetText(url, *headers) ?: return null try { return parseJson(res) } catch (e: Exception) { e.printStackTrace() } return null } private fun assumeHttp() { if (client == null) { client = HttpClients.createDefault() } } } fun parseJson(text: String): Json? { try { return Json.JsonObject(JSONObject(text)) } catch(e: Exception) { } try { return Json.JsonArray(JSONArray(text)) } catch(e: Exception) { } return null } sealed class Json { class JsonObject(val json: JSONObject) : Json() { override fun toString(): String { return json.toString() } } class JsonArray(val json: JSONArray) : Json() { override fun toString(): String { return json.toString() } } }
apache-2.0
095d4f938d5d3a4f3b4949d979f4221b
28.543478
103
0.578018
4.272537
false
false
false
false
googlesamples/mlkit
android/material-showcase/app/src/main/java/com/google/mlkit/md/productsearch/ProductAdapter.kt
1
2618
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mlkit.md.productsearch import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.Adapter import com.google.mlkit.md.R import com.google.mlkit.md.productsearch.ProductAdapter.ProductViewHolder /** Presents the list of product items from cloud product search. */ class ProductAdapter(private val productList: List<Product>) : Adapter<ProductViewHolder>() { class ProductViewHolder private constructor(view: View) : RecyclerView.ViewHolder(view) { private val imageView: ImageView = view.findViewById(R.id.product_image) private val titleView: TextView = view.findViewById(R.id.product_title) private val subtitleView: TextView = view.findViewById(R.id.product_subtitle) private val imageSize: Int = view.resources.getDimensionPixelOffset(R.dimen.product_item_image_size) fun bindProduct(product: Product) { imageView.setImageDrawable(null) if (!TextUtils.isEmpty(product.imageUrl)) { ImageDownloadTask(imageView, imageSize).execute(product.imageUrl) } else { imageView.setImageResource(R.drawable.logo_google_cloud) } titleView.text = product.title subtitleView.text = product.subtitle } companion object { fun create(parent: ViewGroup) = ProductViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.product_item, parent, false)) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder = ProductViewHolder.create(parent) override fun onBindViewHolder(holder: ProductViewHolder, position: Int) { holder.bindProduct(productList[position]) } override fun getItemCount(): Int = productList.size }
apache-2.0
a8e2697d0fe532aac70288e28dc92170
39.276923
116
0.726127
4.617284
false
false
false
false
ansman/okhttp
okhttp/src/main/kotlin/okhttp3/ConnectionSpec.kt
6
13454
/* * Copyright (C) 2014 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 okhttp3 import java.util.Arrays import java.util.Objects import javax.net.ssl.SSLSocket import okhttp3.ConnectionSpec.Builder import okhttp3.internal.concat import okhttp3.internal.effectiveCipherSuites import okhttp3.internal.hasIntersection import okhttp3.internal.indexOf import okhttp3.internal.intersect /** * Specifies configuration for the socket connection that HTTP traffic travels through. For `https:` * URLs, this includes the TLS version and cipher suites to use when negotiating a secure * connection. * * The TLS versions configured in a connection spec are only be used if they are also enabled in the * SSL socket. For example, if an SSL socket does not have TLS 1.3 enabled, it will not be used even * if it is present on the connection spec. The same policy also applies to cipher suites. * * Use [Builder.allEnabledTlsVersions] and [Builder.allEnabledCipherSuites] to defer all feature * selection to the underlying SSL socket. * * The configuration of each spec changes with each OkHttp release. This is annoying: upgrading * your OkHttp library can break connectivity to certain web servers! But it’s a necessary annoyance * because the TLS ecosystem is dynamic and staying up to date is necessary to stay secure. See * [OkHttp's TLS Configuration History][tls_history] to track these changes. * * [tls_history]: https://square.github.io/okhttp/tls_configuration_history/ */ class ConnectionSpec internal constructor( @get:JvmName("isTls") val isTls: Boolean, @get:JvmName("supportsTlsExtensions") val supportsTlsExtensions: Boolean, internal val cipherSuitesAsString: Array<String>?, private val tlsVersionsAsString: Array<String>? ) { /** * Returns the cipher suites to use for a connection. Returns null if all of the SSL socket's * enabled cipher suites should be used. */ @get:JvmName("cipherSuites") val cipherSuites: List<CipherSuite>? get() { return cipherSuitesAsString?.map { CipherSuite.forJavaName(it) }?.toList() } @JvmName("-deprecated_cipherSuites") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "cipherSuites"), level = DeprecationLevel.ERROR) fun cipherSuites(): List<CipherSuite>? = cipherSuites /** * Returns the TLS versions to use when negotiating a connection. Returns null if all of the SSL * socket's enabled TLS versions should be used. */ @get:JvmName("tlsVersions") val tlsVersions: List<TlsVersion>? get() { return tlsVersionsAsString?.map { TlsVersion.forJavaName(it) }?.toList() } @JvmName("-deprecated_tlsVersions") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "tlsVersions"), level = DeprecationLevel.ERROR) fun tlsVersions(): List<TlsVersion>? = tlsVersions @JvmName("-deprecated_supportsTlsExtensions") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "supportsTlsExtensions"), level = DeprecationLevel.ERROR) fun supportsTlsExtensions(): Boolean = supportsTlsExtensions /** Applies this spec to [sslSocket]. */ internal fun apply(sslSocket: SSLSocket, isFallback: Boolean) { val specToApply = supportedSpec(sslSocket, isFallback) if (specToApply.tlsVersions != null) { sslSocket.enabledProtocols = specToApply.tlsVersionsAsString } if (specToApply.cipherSuites != null) { sslSocket.enabledCipherSuites = specToApply.cipherSuitesAsString } } /** * Returns a copy of this that omits cipher suites and TLS versions not enabled by [sslSocket]. */ private fun supportedSpec(sslSocket: SSLSocket, isFallback: Boolean): ConnectionSpec { val socketEnabledCipherSuites = sslSocket.enabledCipherSuites var cipherSuitesIntersection: Array<String> = effectiveCipherSuites(socketEnabledCipherSuites) val tlsVersionsIntersection = if (tlsVersionsAsString != null) { sslSocket.enabledProtocols.intersect(tlsVersionsAsString, naturalOrder()) } else { sslSocket.enabledProtocols } // In accordance with https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00 the SCSV // cipher is added to signal that a protocol fallback has taken place. val supportedCipherSuites = sslSocket.supportedCipherSuites val indexOfFallbackScsv = supportedCipherSuites.indexOf( "TLS_FALLBACK_SCSV", CipherSuite.ORDER_BY_NAME) if (isFallback && indexOfFallbackScsv != -1) { cipherSuitesIntersection = cipherSuitesIntersection.concat( supportedCipherSuites[indexOfFallbackScsv]) } return Builder(this) .cipherSuites(*cipherSuitesIntersection) .tlsVersions(*tlsVersionsIntersection) .build() } /** * Returns `true` if the socket, as currently configured, supports this connection spec. In * order for a socket to be compatible the enabled cipher suites and protocols must intersect. * * For cipher suites, at least one of the [required cipher suites][cipherSuites] must match the * socket's enabled cipher suites. If there are no required cipher suites the socket must have at * least one cipher suite enabled. * * For protocols, at least one of the [required protocols][tlsVersions] must match the socket's * enabled protocols. */ fun isCompatible(socket: SSLSocket): Boolean { if (!isTls) { return false } if (tlsVersionsAsString != null && !tlsVersionsAsString.hasIntersection(socket.enabledProtocols, naturalOrder())) { return false } if (cipherSuitesAsString != null && !cipherSuitesAsString.hasIntersection( socket.enabledCipherSuites, CipherSuite.ORDER_BY_NAME)) { return false } return true } override fun equals(other: Any?): Boolean { if (other !is ConnectionSpec) return false if (other === this) return true if (this.isTls != other.isTls) return false if (isTls) { if (!Arrays.equals(this.cipherSuitesAsString, other.cipherSuitesAsString)) return false if (!Arrays.equals(this.tlsVersionsAsString, other.tlsVersionsAsString)) return false if (this.supportsTlsExtensions != other.supportsTlsExtensions) return false } return true } override fun hashCode(): Int { var result = 17 if (isTls) { result = 31 * result + (cipherSuitesAsString?.contentHashCode() ?: 0) result = 31 * result + (tlsVersionsAsString?.contentHashCode() ?: 0) result = 31 * result + if (supportsTlsExtensions) 0 else 1 } return result } override fun toString(): String { if (!isTls) return "ConnectionSpec()" return ("ConnectionSpec(" + "cipherSuites=${Objects.toString(cipherSuites, "[all enabled]")}, " + "tlsVersions=${Objects.toString(tlsVersions, "[all enabled]")}, " + "supportsTlsExtensions=$supportsTlsExtensions)") } class Builder { internal var tls: Boolean = false internal var cipherSuites: Array<String>? = null internal var tlsVersions: Array<String>? = null internal var supportsTlsExtensions: Boolean = false internal constructor(tls: Boolean) { this.tls = tls } constructor(connectionSpec: ConnectionSpec) { this.tls = connectionSpec.isTls this.cipherSuites = connectionSpec.cipherSuitesAsString this.tlsVersions = connectionSpec.tlsVersionsAsString this.supportsTlsExtensions = connectionSpec.supportsTlsExtensions } fun allEnabledCipherSuites() = apply { require(tls) { "no cipher suites for cleartext connections" } this.cipherSuites = null } fun cipherSuites(vararg cipherSuites: CipherSuite): Builder = apply { require(tls) { "no cipher suites for cleartext connections" } val strings = cipherSuites.map { it.javaName }.toTypedArray() return cipherSuites(*strings) } fun cipherSuites(vararg cipherSuites: String) = apply { require(tls) { "no cipher suites for cleartext connections" } require(cipherSuites.isNotEmpty()) { "At least one cipher suite is required" } this.cipherSuites = cipherSuites.clone() as Array<String> // Defensive copy. } fun allEnabledTlsVersions() = apply { require(tls) { "no TLS versions for cleartext connections" } this.tlsVersions = null } fun tlsVersions(vararg tlsVersions: TlsVersion): Builder = apply { require(tls) { "no TLS versions for cleartext connections" } val strings = tlsVersions.map { it.javaName }.toTypedArray() return tlsVersions(*strings) } fun tlsVersions(vararg tlsVersions: String) = apply { require(tls) { "no TLS versions for cleartext connections" } require(tlsVersions.isNotEmpty()) { "At least one TLS version is required" } this.tlsVersions = tlsVersions.clone() as Array<String> // Defensive copy. } @Deprecated("since OkHttp 3.13 all TLS-connections are expected to support TLS extensions.\n" + "In a future release setting this to true will be unnecessary and setting it to false\n" + "will have no effect.") fun supportsTlsExtensions(supportsTlsExtensions: Boolean) = apply { require(tls) { "no TLS extensions for cleartext connections" } this.supportsTlsExtensions = supportsTlsExtensions } fun build(): ConnectionSpec = ConnectionSpec( tls, supportsTlsExtensions, cipherSuites, tlsVersions ) } @Suppress("DEPRECATION") companion object { // Most secure but generally supported list. private val RESTRICTED_CIPHER_SUITES = arrayOf( // TLSv1.3. CipherSuite.TLS_AES_128_GCM_SHA256, CipherSuite.TLS_AES_256_GCM_SHA384, CipherSuite.TLS_CHACHA20_POLY1305_SHA256, // TLSv1.0, TLSv1.1, TLSv1.2. CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256) // This is nearly equal to the cipher suites supported in Chrome 72, current as of 2019-02-24. // See https://tinyurl.com/okhttp-cipher-suites for availability. private val APPROVED_CIPHER_SUITES = arrayOf( // TLSv1.3. CipherSuite.TLS_AES_128_GCM_SHA256, CipherSuite.TLS_AES_256_GCM_SHA384, CipherSuite.TLS_CHACHA20_POLY1305_SHA256, // TLSv1.0, TLSv1.1, TLSv1.2. CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, // Note that the following cipher suites are all on HTTP/2's bad cipher suites list. We'll // continue to include them until better suites are commonly available. CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384, CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA, CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA) /** A secure TLS connection that requires a recent client platform and a recent server. */ @JvmField val RESTRICTED_TLS = Builder(true) .cipherSuites(*RESTRICTED_CIPHER_SUITES) .tlsVersions(TlsVersion.TLS_1_3, TlsVersion.TLS_1_2) .supportsTlsExtensions(true) .build() /** * A modern TLS configuration that works on most client platforms and can connect to most servers. * This is OkHttp's default configuration. */ @JvmField val MODERN_TLS = Builder(true) .cipherSuites(*APPROVED_CIPHER_SUITES) .tlsVersions(TlsVersion.TLS_1_3, TlsVersion.TLS_1_2) .supportsTlsExtensions(true) .build() /** * A backwards-compatible fallback configuration that works on obsolete client platforms and can * connect to obsolete servers. When possible, prefer to upgrade your client platform or server * rather than using this configuration. */ @JvmField val COMPATIBLE_TLS = Builder(true) .cipherSuites(*APPROVED_CIPHER_SUITES) .tlsVersions(TlsVersion.TLS_1_3, TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0) .supportsTlsExtensions(true) .build() /** Unencrypted, unauthenticated connections for `http:` URLs. */ @JvmField val CLEARTEXT = Builder(false).build() } }
apache-2.0
f838c127d00ac9dea5607438ba66ce2e
37.766571
102
0.704431
4.113761
false
false
false
false
misaochan/apps-android-commons
app/src/main/java/fr/free/nrw/commons/explore/paging/BasePagingPresenter.kt
8
2129
package fr.free.nrw.commons.explore.paging import androidx.lifecycle.MutableLiveData import fr.free.nrw.commons.upload.depicts.proxy import io.reactivex.Scheduler import io.reactivex.disposables.CompositeDisposable import timber.log.Timber abstract class BasePagingPresenter<T>( val mainThreadScheduler: Scheduler, val pageableBaseDataSource: PageableBaseDataSource<T> ) : PagingContract.Presenter<T> { private val DUMMY: PagingContract.View<T> = proxy() private var view: PagingContract.View<T> = DUMMY private val compositeDisposable = CompositeDisposable() override val listFooterData = MutableLiveData<List<FooterItem>>().apply { value = emptyList() } override fun onAttachView(view: PagingContract.View<T>) { this.view = view compositeDisposable.addAll( pageableBaseDataSource.pagingResults.subscribe(view::observePagingResults), pageableBaseDataSource.loadingStates .observeOn(mainThreadScheduler) .subscribe(::onLoadingState, Timber::e), pageableBaseDataSource.noItemsLoadedQueries.subscribe(view::showEmptyText) ) } private fun onLoadingState(it: LoadingState) = when (it) { LoadingState.Loading -> { view.hideEmptyText() listFooterData.postValue(listOf(FooterItem.LoadingItem)) } LoadingState.Complete -> { listFooterData.postValue(emptyList()) view.hideInitialLoadProgress() } LoadingState.InitialLoad -> { view.hideEmptyText() view.showInitialLoadInProgress() } LoadingState.Error -> { view.showSnackbar() view.hideInitialLoadProgress() listFooterData.postValue(listOf(FooterItem.RefreshItem)) } } override fun retryFailedRequest() { pageableBaseDataSource.retryFailedRequest() } override fun onDetachView() { view = DUMMY compositeDisposable.clear() } override fun onQueryUpdated(query: String) { pageableBaseDataSource.onQueryUpdated(query) } }
apache-2.0
7f3f184af2e24629fc066c19e29de1bb
31.753846
99
0.678253
4.894253
false
false
false
false
ken-kentan/student-portal-plus
app/src/main/java/jp/kentan/studentportalplus/data/component/LectureAttend.kt
1
351
package jp.kentan.studentportalplus.data.component enum class LectureAttend { PORTAL, // ポータル取得 USER, // ユーザー登録 SIMILAR, // 類似 NOT, // 未受講 UNKNOWN; // 未確認 fun isAttend() = this == PORTAL || this == USER || this == SIMILAR fun canAttend() = this == SIMILAR || this == NOT }
gpl-3.0
128cd39f409f33d4e58645afc4384746
23
70
0.59164
3.079208
false
false
false
false
dafi/photoshelf
birthday/src/main/java/com/ternaryop/photoshelf/birthday/browser/adapter/BirthdayShowFlags.kt
1
2599
package com.ternaryop.photoshelf.birthday.browser.adapter import com.ternaryop.photoshelf.api.ApiManager import com.ternaryop.photoshelf.api.Response import com.ternaryop.photoshelf.api.birthday.Birthday import com.ternaryop.photoshelf.api.birthday.BirthdayResult import com.ternaryop.photoshelf.api.birthday.FindParams import com.ternaryop.photoshelf.api.birthday.ListResult class BirthdayShowFlags { private var flags = SHOW_ALL private val birthdayService = ApiManager.birthdayService() val isShowIgnored: Boolean get() = flags and SHOW_IGNORED != 0 val isShowInSameDay: Boolean get() = flags and SHOW_IN_SAME_DAY != 0 val isShowMissing: Boolean get() = flags and SHOW_MISSING != 0 val isWithoutPost: Boolean get() = flags and SHOW_WITHOUT_POSTS != 0 fun isOn(value: Int): Boolean = flags and value != 0 @Suppress("ComplexMethod") fun setFlag(value: Int, show: Boolean) { flags = when { // SHOW_ALL is the default value and it can't be hidden value and SHOW_ALL != 0 -> SHOW_ALL value and SHOW_IGNORED != 0 -> if (show) SHOW_IGNORED else SHOW_ALL value and SHOW_IN_SAME_DAY != 0 -> if (show) SHOW_IN_SAME_DAY else SHOW_ALL value and SHOW_MISSING != 0 -> if (show) SHOW_MISSING else SHOW_ALL value and SHOW_WITHOUT_POSTS != 0 -> if (show) SHOW_WITHOUT_POSTS else SHOW_ALL else -> throw AssertionError("value $value not supported") } } suspend fun find(pattern: String, month: Int, offset: Int, limit: Int): Response<BirthdayResult> { val params = FindParams(name = pattern, month = month + 1, offset = offset, limit = limit).toQueryMap() return when { isShowIgnored -> wrapBirthdayResult(birthdayService.findIgnored(params)) isShowInSameDay -> birthdayService.findSameDay(params) isShowMissing -> wrapBirthdayResult((birthdayService.findMissingNames(params))) isWithoutPost -> birthdayService.findOrphans(params) else -> birthdayService.findByDate(params) } } private fun wrapBirthdayResult(response: Response<ListResult>): Response<BirthdayResult> { val listResult = response.response.names return Response(BirthdayResult(0, listResult.map { Birthday(it) })) } companion object { const val SHOW_ALL = 1 const val SHOW_IGNORED = 1 shl 1 const val SHOW_IN_SAME_DAY = 1 shl 2 const val SHOW_MISSING = 1 shl 3 const val SHOW_WITHOUT_POSTS = 1 shl 4 } }
mit
476229a0f5ab1d32b65312569f9e1dc3
39.609375
111
0.668334
4.253682
false
false
false
false
ledao/chatbot
src/main/kotlin/com/davezhao/odds/TrainWoedVec.kt
1
2186
package com.davezhao.odds import com.davezhao.models.Connector import com.davezhao.models.StdQaInfoTable import com.davezhao.nlp.WordBreaker import com.hankcs.hanlp.HanLP import com.hankcs.hanlp.mining.word2vec.Word2VecTrainer import org.jetbrains.exposed.sql.selectAll import org.jetbrains.exposed.sql.transactions.transaction import org.slf4j.LoggerFactory import java.io.BufferedWriter import java.io.File import java.io.FileWriter object TrainWoedVec { val log = LoggerFactory.getLogger(this::class.java) fun segmentWord(rawFilepath: String): String { val outFilepath = "./seg_data.csv" val fout = BufferedWriter(FileWriter(File(outFilepath))) File(rawFilepath).readLines().forEach { line -> val trim = line.trim() if (trim.isNotEmpty() && !trim.startsWith("#")) { val segLine = WordBreaker.segment(line).map { seg -> seg.word }/*.filter { word -> !StopWords.data.contains(word) }*/ .joinToString(" ") fout.write(segLine + "\n") } } fout.close() return outFilepath } fun trainModel(dataPath: String) { val trainerBuilder = Word2VecTrainer(); trainerBuilder.setNumIterations(50); trainerBuilder.setLayerSize(100); trainerBuilder.useNumThreads(4) val wordVectorModel = trainerBuilder.train(dataPath, "./word_vector_model.bin") } fun pullTrainedData() { Connector.open() val fout = BufferedWriter(FileWriter("./data/w2v/seg_data.txt")) transaction { StdQaInfoTable.selectAll().forEach { val coreMsg = it[StdQaInfoTable.question] + " " + it[StdQaInfoTable.answer] + " " + it[StdQaInfoTable.evidence] val seggedSentence = HanLP.segment(coreMsg).map { it.word } .joinToString(" ") log.info(seggedSentence) fout.write(seggedSentence + "\n") } } fout.close() } } fun main(args: Array<String>) { // TrainWoedVec.segmentWord("./raw_data_0125.csv") // TrainWoedVec.trainModel("./seg_data.csv") TrainWoedVec.pullTrainedData() }
gpl-3.0
4a389d37e51edd86a2080233f0bfb7c4
33.171875
127
0.638609
3.717687
false
false
false
false
cwoolner/flex-poker
src/main/kotlin/com/flexpoker/game/command/aggregate/eventproducers/JoinGameEventProducer.kt
1
4110
package com.flexpoker.game.command.aggregate.eventproducers import com.flexpoker.game.command.aggregate.GameState import com.flexpoker.game.command.aggregate.applyEvent import com.flexpoker.game.command.events.GameEvent import com.flexpoker.game.command.events.GameJoinedEvent import com.flexpoker.game.command.events.GameMovedToStartingStageEvent import com.flexpoker.game.command.events.GameStartedEvent import com.flexpoker.game.command.events.GameTablesCreatedAndPlayersAssociatedEvent import com.flexpoker.game.query.dto.GameStage import com.flexpoker.util.toPMap import org.pcollections.HashTreePSet import org.pcollections.PMap import org.pcollections.PSet import java.util.UUID fun joinGame(state: GameState, playerId: UUID): List<GameEvent> { val events = mutableListOf<GameEvent>() val gameCreatedEvent = createJoinGameEvent(state, playerId) events.add(gameCreatedEvent) var updatedState = applyEvent(state, gameCreatedEvent) // if the game is at the max capacity, start the game if (updatedState.registeredPlayerIds.size == updatedState.maxNumberOfPlayers) { val event2 = createGameMovedToStartingStageEvent(updatedState) events.add(event2) updatedState = applyEvent(updatedState, event2) val event3 = createGameTablesCreatedAndPlayersAssociatedEvent(updatedState) events.add(event3) updatedState = applyEvent(updatedState, event3) val event4 = createGameStartedEvent(updatedState) events.add(event4) } return events } private fun createJoinGameEvent(state: GameState, playerId: UUID): GameEvent { require(state.stage === GameStage.REGISTERING) { "game must be in registering stage" } require(!state.registeredPlayerIds.contains(playerId)) { "You are already in this game." } return GameJoinedEvent(state.aggregateId, playerId) } private fun createGameMovedToStartingStageEvent(state: GameState): GameMovedToStartingStageEvent { require (state.stage === GameStage.REGISTERING) { "to move to STARTING, the game stage must be REGISTERING" } return GameMovedToStartingStageEvent(state.aggregateId) } private fun createGameTablesCreatedAndPlayersAssociatedEvent(state: GameState): GameTablesCreatedAndPlayersAssociatedEvent { require (state.tableIdToPlayerIdsMap.isEmpty()) { "tableToPlayerIdsMap should be empty when initializing the tables" } val tableMap = createTableToPlayerMap(state) return GameTablesCreatedAndPlayersAssociatedEvent(state.aggregateId, tableMap, state.numberOfPlayersPerTable) } private fun createGameStartedEvent(state: GameState): GameStartedEvent { require(state.stage === GameStage.STARTING) { "to move to STARTED, the game stage must be STARTING" } require (state.tableIdToPlayerIdsMap.isNotEmpty()) { "tableToPlayerIdsMap should be filled at this point" } return GameStartedEvent(state.aggregateId, state.tableIdToPlayerIdsMap.keys, state.blindScheduleDTO) } private fun createTableToPlayerMap(state: GameState): PMap<UUID, PSet<UUID>> { val randomizedListOfPlayerIds = state.registeredPlayerIds.toList().shuffled() val numberOfTablesToCreate = determineNumberOfTablesToCreate(state) val tableMap = (0 until numberOfTablesToCreate) .fold(HashMap<UUID, PSet<UUID>>(), { acc, _ -> acc[UUID.randomUUID()] = HashTreePSet.empty() acc }) val tableIdList = ArrayList(tableMap.keys) randomizedListOfPlayerIds.indices.forEach { val tableIndex = it % tableIdList.size val players = tableMap[tableIdList[tableIndex]]!!.plus(randomizedListOfPlayerIds[it]) tableMap[tableIdList[tableIndex]] = players } return tableMap.toPMap() } private fun determineNumberOfTablesToCreate(state: GameState): Int { var numberOfTables = state.registeredPlayerIds.size / state.numberOfPlayersPerTable // if the number of people doesn't fit perfectly, then an additional // table is needed for the overflow if (state.registeredPlayerIds.size % state.numberOfPlayersPerTable != 0) { numberOfTables++ } return numberOfTables }
gpl-2.0
50db22ffcbe73c459a9d08c60d157d3e
43.193548
124
0.770803
4.312697
false
false
false
false
pedroSG94/rtmp-streamer-java
rtmp/src/main/java/com/pedro/rtmp/rtmp/message/WindowAcknowledgementSize.kt
2
1699
/* * Copyright (C) 2021 pedroSG94. * * 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.pedro.rtmp.rtmp.message import com.pedro.rtmp.rtmp.chunk.ChunkStreamId import com.pedro.rtmp.rtmp.chunk.ChunkType import com.pedro.rtmp.utils.readUInt32 import com.pedro.rtmp.utils.writeUInt32 import java.io.ByteArrayOutputStream import java.io.InputStream /** * Created by pedro on 21/04/21. */ class WindowAcknowledgementSize(var acknowledgementWindowSize: Int = 0, timeStamp: Int = 0): RtmpMessage(BasicHeader(ChunkType.TYPE_0, ChunkStreamId.PROTOCOL_CONTROL.mark)) { init { header.timeStamp = timeStamp } override fun readBody(input: InputStream) { acknowledgementWindowSize = input.readUInt32() } override fun storeBody(): ByteArray { val byteArrayOutputStream = ByteArrayOutputStream() byteArrayOutputStream.writeUInt32(acknowledgementWindowSize) return byteArrayOutputStream.toByteArray() } override fun getType(): MessageType = MessageType.WINDOW_ACKNOWLEDGEMENT_SIZE override fun getSize(): Int = 4 override fun toString(): String { return "WindowAcknowledgementSize(acknowledgementWindowSize=$acknowledgementWindowSize)" } }
apache-2.0
46f843d82a095887c3dc0126e1a99313
31.075472
92
0.763979
4.258145
false
false
false
false
nemerosa/ontrack
ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/support/GQLFieldUtils.kt
1
6023
package net.nemerosa.ontrack.graphql.support import graphql.Scalars.* import graphql.schema.* import net.nemerosa.ontrack.model.structure.Entity import kotlin.reflect.KClass // ============================================================================ // Single object field // ============================================================================ inline fun <reified T : Any> objectField( name: String, description: String? = null, nullable: Boolean = true, noinline fetcher: ((DataFetchingEnvironment) -> T?)? = null ) = objectField(T::class, name, description, nullable, fetcher) fun <T : Any> objectField( type: KClass<T>, name: String, description: String? = null, nullable: Boolean = true, fetcher: ((DataFetchingEnvironment) -> T?)? = null ) = objectField( type = type.toTypeRef(), name = name, description = description, nullable = nullable, fetcher = fetcher ) fun <T> objectField( type: GraphQLOutputType, name: String, description: String? = null, nullable: Boolean = true, fetcher: ((DataFetchingEnvironment) -> T?)? = null ): GraphQLFieldDefinition = GraphQLFieldDefinition.newFieldDefinition() .name(name) .description(description) .type(nullableType(type, nullable)) .apply { fetcher?.let { dataFetcher(it) } } .build() // ============================================================================ // List of objects // ============================================================================ inline fun <reified T : Any> listField( name: String, description: String, nullable: Boolean = false, noinline fetcher: (DataFetchingEnvironment) -> List<T> ) = listField( type = T::class, name = name, description = description, nullable = nullable, fetcher = fetcher ) fun <T : Any> listField( type: KClass<T>, name: String, description: String, nullable: Boolean = false, fetcher: (DataFetchingEnvironment) -> List<T> ) = listField( type = type.toTypeRef(), name = name, description = description, nullable = nullable, fetcher = fetcher ) fun <T> listField( type: GraphQLOutputType, name: String, description: String, nullable: Boolean = false, fetcher: (DataFetchingEnvironment) -> List<T> ): GraphQLFieldDefinition = GraphQLFieldDefinition.newFieldDefinition() .name(name) .description(description) .type(listType(type, nullable)) .dataFetcher(fetcher) .build() /** * List type */ fun listType(itemType: GraphQLOutputType, nullable: Boolean = false, nullableItem: Boolean = false): GraphQLOutputType = nullableType( GraphQLList(nullableType(itemType, nullableItem)), nullable ) /** * Argument to get the first N elements in a list field */ const val STD_LIST_ARG_FIRST = "first" /** * Argument to get the last N elements in a list field */ const val STD_LIST_ARG_LAST = "last" /** * First & last arguments for a list */ fun listArguments() = listOf( GraphQLArgument.newArgument() .name(STD_LIST_ARG_FIRST) .description("Number of items to return from the beginning of the list") .type(GraphQLInt) .build(), GraphQLArgument.newArgument() .name(STD_LIST_ARG_LAST) .description("Number of items to return from the end of the list") .type(GraphQLInt) .build(), ) /** * Filtering a list based on first & last arguments */ fun <T> stdListArgumentsFilter(list: List<T>, environment: DataFetchingEnvironment): List<T> { val first: Int? = environment.getArgument(STD_LIST_ARG_FIRST) val last: Int? = environment.getArgument(STD_LIST_ARG_LAST) return if (first != null) { if (last != null) { throw IllegalStateException("Only one of `${STD_LIST_ARG_FIRST}` or `${STD_LIST_ARG_LAST}` is expected as argument") } else { // First items... list.take(first) } } else if (last != null) { // Last items list.takeLast(last) } else { // No range list } } // ============================================================================ // Common fields // ============================================================================ @Suppress("DEPRECATION") fun idField(): GraphQLFieldDefinition = GraphQLFieldDefinition.newFieldDefinition() .name("id") .type(GraphQLInt.toNotNull()) .dataFetcher { environment: DataFetchingEnvironment -> val source = environment.getSource<Any>() if (source is Entity) { return@dataFetcher source.id.value } else { return@dataFetcher null } } .build() fun nameField(description: String = ""): GraphQLFieldDefinition = GraphQLFieldDefinition.newFieldDefinition() .name("name") .description(description) .type(GraphQLString) .build() fun descriptionField(): GraphQLFieldDefinition = GraphQLFieldDefinition.newFieldDefinition() .name("description") .type(GraphQLString) .build() fun disabledField(): GraphQLFieldDefinition = GraphQLFieldDefinition.newFieldDefinition() .name("disabled") .type(GraphQLNonNull(GraphQLBoolean)) .build() // ============================================================================ // General utilities // ============================================================================ /** * Adjust a type so that it becomes nullable or not according to the value * of [nullable]. */ fun nullableType(type: GraphQLOutputType, nullable: Boolean): GraphQLOutputType = if (nullable) { type } else { GraphQLNonNull(type) } /** * Adjust a type so that it becomes not nullable. */ fun notNullableType(type: GraphQLOutputType): GraphQLOutputType = nullableType(type, nullable = false) /** * Extension function for non nullable types */ fun GraphQLOutputType.toNotNull() = notNullableType(this)
mit
d8e0904557e7060612274c2e03d69d7a
27.956731
128
0.585755
4.559425
false
false
false
false
hypercube1024/firefly
firefly-net/src/main/kotlin/com/fireflysource/net/tcp/aio/AioSecureTcpConnection.kt
1
7235
package com.fireflysource.net.tcp.aio import com.fireflysource.common.concurrent.exceptionallyAccept import com.fireflysource.common.coroutine.consumeAll import com.fireflysource.common.sys.Result import com.fireflysource.common.sys.SystemLogger import com.fireflysource.net.tcp.TcpConnection import com.fireflysource.net.tcp.WrappedTcpConnection import com.fireflysource.net.tcp.buffer.* import com.fireflysource.net.tcp.secure.SecureEngine import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.future.await import kotlinx.coroutines.launch import java.nio.ByteBuffer import java.nio.channels.ClosedChannelException import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.atomic.AtomicBoolean import java.util.function.Consumer /** * @author Pengtao Qiu */ class AioSecureTcpConnection( private val tcpConnection: TcpConnection, private val secureEngine: SecureEngine ) : TcpConnection by tcpConnection, WrappedTcpConnection { companion object { private val log = SystemLogger.create(AioSecureTcpConnection::class.java) } private val encryptedOutChannel: Channel<OutputMessage> = Channel(Channel.UNLIMITED) private val stashedBuffers = LinkedList<ByteBuffer>() private val beginHandshake = AtomicBoolean(false) init { secureEngine .onHandshakeWrite { tcpConnection.write(it) } .onHandshakeRead { tcpConnection.read() } tcpConnection.onClose { secureEngine.close() } } override fun getRawTcpConnection(): TcpConnection = tcpConnection override fun read(): CompletableFuture<ByteBuffer> { if (!beginHandshake.get()) { val future = CompletableFuture<ByteBuffer>() future.completeExceptionally(IllegalStateException("The TLS handshake has not begun")) return future } val stashedBuf: ByteBuffer? = stashedBuffers.poll() return if (stashedBuf != null) { val future = CompletableFuture<ByteBuffer>() future.complete(stashedBuf) future } else { tcpConnection.read().thenApply(secureEngine::decrypt) } } private fun launchEncryptingAndFlushJob() = tcpConnection.coroutineScope.launch { while (true) { when (val message = encryptedOutChannel.receive()) { is OutputBuffer -> encryptAndFlushBuffer(message) is OutputBufferList -> encryptAndFlushBuffers(message) is OutputBuffers -> encryptAndFlushBuffers(message) is ShutdownOutput -> { shutdownOutput(message) break } else -> {} } } }.invokeOnCompletion { cause -> val e = cause ?: ClosedChannelException() encryptedOutChannel.consumeAll { message -> when (message) { is OutputBuffer -> message.result.accept(Result.createFailedResult(-1, e)) is OutputBufferList -> message.result.accept(Result.createFailedResult(-1, e)) is OutputBuffers -> message.result.accept(Result.createFailedResult(-1, e)) is ShutdownOutput -> message.result.accept(Result.createFailedResult(e)) else -> { } } } } private suspend fun encryptAndFlushBuffers(outputMessage: OutputBuffers) { val result = outputMessage.result try { val remaining = outputMessage.remaining() val buffers = outputMessage.buffers val offset = outputMessage.getCurrentOffset() val length = outputMessage.getCurrentLength() val encryptedBuffer = secureEngine.encrypt(buffers, offset, length) val size = encryptedBuffer.remaining() log.debug { "Encrypt and flush buffer. id: $id, src: $remaining, desc: $size, offset: $offset, length: $length" } if (remaining == 0L || size == 0) { result.accept(Result(true, 0, null)) } else { tcpConnection.write(encryptedBuffer).await() result.accept(Result(true, remaining, null)) } } catch (e: Exception) { result.accept(Result(false, -1, e)) } } private suspend fun encryptAndFlushBuffer(outputMessage: OutputBuffer) { val (buffer, result) = outputMessage try { val remaining = buffer.remaining() val encryptedBuffer = secureEngine.encrypt(buffer) val size = encryptedBuffer.remaining() log.debug { "Encrypt and flush buffer. id: $id, src: $remaining, desc: $size" } if (remaining == 0 || size == 0) { result.accept(Result(true, 0, null)) } else { tcpConnection.write(encryptedBuffer).await() result.accept(Result(true, remaining, null)) } } catch (e: Exception) { result.accept(Result(false, -1, e)) } } private fun shutdownOutput(message: ShutdownOutput) { tcpConnection.close(message.result) } override fun write(byteBuffer: ByteBuffer, result: Consumer<Result<Int>>): TcpConnection { encryptedOutChannel.trySend(OutputBuffer(byteBuffer, result)) return this } override fun write( byteBuffers: Array<ByteBuffer>, offset: Int, length: Int, result: Consumer<Result<Long>> ): TcpConnection { encryptedOutChannel.trySend(OutputBuffers(byteBuffers, offset, length, result)) return this } override fun write( byteBufferList: List<ByteBuffer>, offset: Int, length: Int, result: Consumer<Result<Long>> ): TcpConnection { encryptedOutChannel.trySend(OutputBufferList(byteBufferList, offset, length, result)) return this } override fun close(result: Consumer<Result<Void>>): TcpConnection { encryptedOutChannel.trySend(ShutdownOutput(result)) return this } override fun isSecureConnection(): Boolean = true override fun isClientMode(): Boolean { return secureEngine.isClientMode } override fun isHandshakeComplete(): Boolean = secureEngine.isHandshakeComplete override fun beginHandshake(result: Consumer<Result<String>>): TcpConnection { if (beginHandshake.compareAndSet(false, true)) { secureEngine.beginHandshake() .thenAccept { result.accept(Result(true, it.applicationProtocol, null)) it.stashedAppBuffers.forEach { b -> stashedBuffers.add(b) } launchEncryptingAndFlushJob() } .exceptionallyAccept { result.accept(Result(false, "", it)) } } else { result.accept(Result(false, "", IllegalStateException("The handshake has begun"))) } return this } override fun getSupportedApplicationProtocols(): List<String> { return secureEngine.supportedApplicationProtocols } override fun getApplicationProtocol(): String { return secureEngine.applicationProtocol } }
apache-2.0
fa351f3ef1a6e5d8d8246c13523e0a63
36.107692
125
0.640221
4.881916
false
false
false
false
nemerosa/ontrack
ontrack-ui/src/main/java/net/nemerosa/ontrack/boot/support/ResourceHttpMessageConverter.kt
1
2049
package net.nemerosa.ontrack.boot.support import com.fasterxml.jackson.databind.ObjectMapper import net.nemerosa.ontrack.json.ObjectMapperFactory import net.nemerosa.ontrack.model.security.SecurityService import net.nemerosa.ontrack.ui.controller.EntityURIBuilder import net.nemerosa.ontrack.ui.resource.DefaultResourceContext import net.nemerosa.ontrack.ui.resource.ResourceModule import net.nemerosa.ontrack.ui.resource.ResourceObjectMapper import net.nemerosa.ontrack.ui.resource.ResourceObjectMapperFactory import org.springframework.http.HttpInputMessage import org.springframework.http.HttpOutputMessage import org.springframework.http.MediaType import org.springframework.http.converter.AbstractHttpMessageConverter import java.nio.charset.Charset class ResourceHttpMessageConverter(uriBuilder: EntityURIBuilder, securityService: SecurityService, resourceModules: List<ResourceModule>) : AbstractHttpMessageConverter<Any>(MediaType("application", "json", DEFAULT_CHARSET), MediaType("application", "*+json", DEFAULT_CHARSET)) { private val resourceObjectMapper: ResourceObjectMapper private val mapper: ObjectMapper init { // Resource context val resourceContext = DefaultResourceContext(uriBuilder, securityService) // Object mapper mapper = ObjectMapperFactory.create() // Resource mapper resourceObjectMapper = ResourceObjectMapperFactory(mapper).resourceObjectMapper( resourceModules, resourceContext ) } override fun supports(clazz: Class<*>): Boolean { return true } override fun readInternal(clazz: Class<*>, inputMessage: HttpInputMessage): Any { return mapper.readValue(inputMessage.body, clazz) } public override fun writeInternal(`object`: Any, outputMessage: HttpOutputMessage) { val body = outputMessage.body resourceObjectMapper.write(body, `object`) body.flush() } companion object { val DEFAULT_CHARSET: Charset = Charsets.UTF_8 } }
mit
1591e432359d5f4becf22bd7f79590ea
38.403846
279
0.761347
4.866983
false
false
false
false
openHPI/android-app
app/src/main/java/de/xikolo/utils/extensions/FileExtensions.kt
1
4062
package de.xikolo.utils.extensions import android.content.Context import android.os.Environment import android.util.Log import de.xikolo.App import de.xikolo.R import java.io.File import java.text.DecimalFormat import java.util.ArrayList import kotlin.math.log10 import kotlin.math.pow object FileExtensions { val TAG: String = FileExtensions::class.java.simpleName } val <T : File?> T.fileSize: Long get() { var length: Long = 0 if (this != null && isFile) { length = length() } return length } val <T : File?> T.folderSize: Long get() { var length: Long = 0 if (this != null && listFiles() != null) { for (file in listFiles()) { length += if (file.isFile) { file.length() } else { file.folderSize } } } return length } val Long.asFormattedFileSize: String get() { if (this <= 0) return "0" val units = arrayOf("B", "KB", "MB", "GB", "TB") val digitGroups = (log10(this.toDouble()) / log10(1024.0)).toInt() return DecimalFormat("#,##0.#").format(this / 1024.0.pow(digitGroups.toDouble())) + " " + units[digitGroups] } val <T : File> T.foldersWithFiles: List<String> get() { val folders = ArrayList<String>() if (isDirectory) { val files = listFiles() ?: arrayOf<File>() for (file in files) { if (file.isDirectory) { folders.add(file.absolutePath) } } } return folders } val <T : File?> T.fileCount: Int get() { var files = 0 if (this != null && listFiles() != null) for (file in listFiles()) { if (file.isFile) { files++ } else { files += file.fileCount } } return files } fun <T : File> T.deleteAll() { if (isDirectory) { if (list().isEmpty()) { delete() } else { val files = list() for (temp in files) { val fileDelete = File(this, temp) fileDelete.deleteAll() } if (list().isEmpty()) { this.delete() } } } else { this.delete() } } fun <T : File> T.createIfNotExists() { var folder: File = this if (!exists()) { if (isFile) { folder = folder.parentFile } Log.d(FileExtensions.TAG, "Folder " + folder.absolutePath + " not exists") if (folder.mkdirs()) { Log.d(FileExtensions.TAG, "Created Folder " + folder.absolutePath) } else { Log.w(FileExtensions.TAG, "Failed creating Folder " + folder.absolutePath) } } else { Log.d(FileExtensions.TAG, "Folder " + folder.absolutePath + " already exists") } } val String.asEscapedFileName: String get() { // Source http://gordon.koefner.at/blog/coding/replacing-german-umlauts val input = this //replace all lower Umlauts var output = input.replace("ü", "ue") .replace("ö", "oe") .replace("ä", "ae") .replace("ß", "ss") //first replace all capital umlaute in a non-capitalized context (e.g. Übung) output = output.replace("Ü(?=[a-zäöüß ])", "Ue") .replace("Ö(?=[a-zäöüß ])", "Oe") .replace("Ä(?=[a-zäöüß ])", "Ae") //now replace all the other capital umlaute output = output.replace("Ü", "UE") .replace("Ö", "OE") .replace("Ä", "AE") return output.replace("[^a-zA-Z0-9\\(\\).-]".toRegex(), "_") } val <T : Context> T.publicAppStorageFolder: File get() { return File(Environment.getExternalStorageDirectory().absolutePath + File.separator + App.instance.getString(R.string.app_name)) }
bsd-3-clause
bbee26f8e6b36bdc3b09cc567ee0c05a
26.855172
116
0.509284
3.932814
false
false
false
false
codeka/weather
app/src/main/java/au/com/codeka/weather/model/Forecast.kt
1
1336
package au.com.codeka.weather.model /** * POJO that represents a "forecast". */ class Forecast { /** * Gets the "offset" of this forecast. 0 means it's todays, 1 means tomorrow, 2 the day after etc. */ var offset = 0 private set var description: String? = null private set var shortDescription: String? = null private set var highTemperature = 0.0 private set var lowTemperature = 0.0 private set var icon: WeatherIcon? = null private set class Builder { private val forecast: Forecast fun setOffset(offset: Int): Builder { forecast.offset = offset return this } fun setDescription(description: String?): Builder { forecast.description = description return this } fun setShortDescription(shortDescription: String?): Builder { forecast.shortDescription = shortDescription return this } fun setHighTemperature(temp: Double): Builder { forecast.highTemperature = temp return this } fun setLowTemperature(temp: Double): Builder { forecast.lowTemperature = temp return this } fun setIcon(icon: WeatherIcon?): Builder { forecast.icon = icon return this } fun build(): Forecast { return forecast } init { forecast = Forecast() } } }
apache-2.0
032bc53817bb19b06bc0611ac3bd5ee7
20.222222
100
0.642964
4.544218
false
false
false
false
synyx/calenope
modules/organizer/src/main/kotlin/de/synyx/calenope/organizer/ui/WeekviewLayout.kt
1
12603
package de.synyx.calenope.organizer.ui import android.graphics.Color import com.alamkanak.weekview.MonthLoader import com.alamkanak.weekview.WeekView import com.alamkanak.weekview.WeekViewEvent import com.encodeering.conflate.experimental.api.Storage import de.synyx.calenope.core.api.model.Event import de.synyx.calenope.organizer.Application import de.synyx.calenope.organizer.Interact import de.synyx.calenope.organizer.Interaction import de.synyx.calenope.organizer.Interaction.Create import de.synyx.calenope.organizer.Interaction.Inspect import de.synyx.calenope.organizer.R import de.synyx.calenope.organizer.State.Events import de.synyx.calenope.organizer.SynchronizeCalendar import de.synyx.calenope.organizer.color import de.synyx.calenope.organizer.component.Layouts.Collapsible import de.synyx.calenope.organizer.component.WeekviewEditor import de.synyx.calenope.organizer.component.WeekviewTouchProxy import de.synyx.calenope.organizer.floor import de.synyx.calenope.organizer.speech.Speech import org.joda.time.DateTime import org.joda.time.Instant import org.joda.time.Minutes import trikita.anvil.Anvil import trikita.anvil.DSL.alpha import trikita.anvil.DSL.dip import trikita.anvil.DSL.enabled import trikita.anvil.DSL.id import trikita.anvil.DSL.imageResource import trikita.anvil.DSL.onClick import trikita.anvil.DSL.sip import trikita.anvil.DSL.v import trikita.anvil.DSL.visibility import trikita.anvil.RenderableView import trikita.anvil.design.DesignDSL.collapsedTitleTextColor import trikita.anvil.design.DesignDSL.contentScrimResource import trikita.anvil.design.DesignDSL.expanded import trikita.anvil.design.DesignDSL.expandedTitleMarginBottom import trikita.anvil.design.DesignDSL.expandedTitleMarginStart import trikita.anvil.design.DesignDSL.title import trikita.anvil.support.v4.Supportv4DSL.onRefresh import trikita.anvil.support.v4.Supportv4DSL.refreshing import java.util.Calendar import java.util.Random import kotlin.properties.Delegates /** * @author clausen - [email protected] */ class WeekviewLayout (weekview : Weekview) : RenderableView (weekview), AutoCloseable { private val speech = object : Speech { override fun ask (prompt : String, callback : (String) -> Unit) { weekview.ask (prompt, prompt.sumBy { it.toInt () } % (2 * Short.MAX_VALUE), callback) } } private val store by lazy { Application.store } private lateinit var events : MonthLoaderAdapter private var swipeable by Delegates.observable (true) { property, previous, next -> if (next != previous) Anvil.render () } private val subscription : Runnable init { subscription = store.subscribe { events.update (store.state.events) } } override fun close () { subscription.run () } override fun view () { weekview.view () } val weekview by lazy { Collapsible ( fab = { once += { alpha (0.0f) } always += { visibility (true) onClick {} val visualize = store.state.events.visualize val interaction = store.state.events.interaction when (interaction) { is Create -> { if (visualize) { imageResource (R.drawable.ic_save) onClick { store.state.events.interaction.apply { when (this) { is Create -> store.dispatcher.dispatch (Interact (copy (draft = false))) } } } } else { imageResource (R.drawable.ic_add) onClick { store.state.events.interaction.apply { when (this) { is Create -> store.dispatcher.dispatch (Interact (this, visualize = true)) } } } } } is Inspect -> { imageResource (R.drawable.ic_subject) onClick { store.state.events.interaction.apply { when (this) { is Inspect -> store.dispatcher.dispatch (Interact (this, visualize = true)) } } } } } when (interaction) { is Interaction.Read -> if (alpha > 0) animate ().alpha (0.0f).setDuration (500L).start () else -> if (alpha == 0.0f) animate ().alpha (1.0f).setDuration (500L).start () } } }, content = { always += { v (WeekviewTouchProxy::class.java) { anvilonce<WeekviewTouchProxy> { id (R.id.weekview_proxy) scrolling = object : WeekviewTouchProxy.Scrolling { private var previous by Delegates.vetoable (Double.MIN_VALUE) { _, previous, next -> previous == Double.MIN_VALUE || next == Double.MIN_VALUE } override fun top (state : Boolean) { swipeable = state } override fun hour (earliest : Double) { if (store.state.events.interaction == Interaction.Read) return reset () if (store.state.events.visualize) return reset () previous = earliest val delta : Double = Math.abs (previous - earliest) if (delta > 1) { store.dispatcher.dispatch (Interact (Interaction.Read)) } } private fun reset () { previous = Double.MIN_VALUE } } events = MonthLoaderAdapter (this, store) monthChangeListener = events numberOfVisibleDays = 1 columnGap = dip (8) hourHeight = dip (600) headerColumnPadding = dip (8) headerRowPadding = dip (12) textSize = sip (10) eventTextSize = sip (10) eventTextColor = color (R.color.primary_text) defaultEventColor = color (R.color.primary) headerColumnTextColor = color (R.color.primary_text) headerColumnBackgroundColor = color (R.color.primary_dark) headerRowBackgroundColor = color (R.color.primary_dark) dayBackgroundColor = color (R.color.primary_light) todayBackgroundColor = color (R.color.primary_light) todayHeaderTextColor = color (R.color.primary_text) hourSeparatorColor = color (R.color.divider) setOnEventClickListener { event, _ -> events.convert (event)?.let { store.dispatcher.dispatch ( Interact (Inspect (it), visualize = store.state.events.visualize) ) } } setEmptyViewClickListener { calendar -> store.dispatcher.dispatch ( Interact (Create (draft = true, start = DateTime (calendar.time).floor (15)), visualize = store.state.events.visualize) ) } } } enabled (swipeable) refreshing (store.state.events.synchronizing) onRefresh { use<WeekviewTouchProxy> (R.id.weekview_proxy) { store.dispatcher.dispatch (SynchronizeCalendar ( year = firstVisibleDay.get (Calendar.YEAR), month = firstVisibleDay.get (Calendar.MONTH) + 1 )) } } } }, appbar = { always += { expanded (store.state.events.visualize) } }, collapsible = { always += { contentScrimResource (R.color.primary) collapsedTitleTextColor (Color.WHITE) expandedTitleMarginBottom (dip (20)) expandedTitleMarginStart (dip (20)) val subject = store.state.events.interaction.let { when (it) { is Create -> return@let it.start.toString ("HH:mm") + (it.end?.let { " - ${it.toString ("HH:mm")}" } ?: "") is Inspect -> return@let it.event.title () else -> return@let store.state.events.name } } title (subject) } pin ("editor") { WeekviewEditor (weekview, speech, store) } } ) } private class MonthLoaderAdapter (private val week : WeekView, private val store : Storage<*>) : MonthLoader.MonthChangeListener { private val map = mutableMapOf<Pair<Int, Int>, Pair<DateTime, Collection<Event>>> () private var maphash by Delegates.observable (map.hashCode ()) { _, previous, next -> if (previous == next) return@observable week.notifyDatasetChanged () } private val identifiers = mutableMapOf<String, Long> () override fun onMonthChange (year : Int, month : Int) : List<WeekViewEvent>? { val key = Pair (year, month) val value = map[key] if (value == null || outdates (value.first)) { store.dispatcher.dispatch (SynchronizeCalendar (year, month)) } return value?.second?.map (this::convert) ?: emptyList<WeekViewEvent> () } fun update (events : Events) { map += events.map maphash = map.hashCode () } fun convert (event : WeekViewEvent) = map.flatMap { it.value.second }.firstOrNull { identifiers[it.id ()] == event.id } private fun outdates (target : DateTime, minutes : Minutes = Minutes.TWO) = Minutes.minutesBetween (target, DateTime ()).isGreaterThan (minutes) private fun convert (event : Event) : WeekViewEvent { val id = identifiers.getOrPut (event.id ()) { Random ().nextLong () } return WeekViewEvent (id, event.title (), event.location (), calendar (event.start ()), calendar (event.end ())) } private fun calendar (instant : Instant?) : Calendar { val calendar = Calendar.getInstance () calendar.time = instant?.toDate () return calendar } } }
apache-2.0
92871a1f9c9072f1746002146969a140
39.524116
164
0.476791
5.496293
false
false
false
false
Ribesg/anko
dsl/static/src/common/Collections.kt
1
1428
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.anko.collections inline fun <T> List<T>.forEachByIndex(f: (T) -> Unit) { val lastIndex = size - 1 for (i in 0..lastIndex) { f(get(i)) } } inline fun <T> List<T>.forEachWithIndex(f: (Int, T) -> Unit) { val lastIndex = size - 1 for (i in 0..lastIndex) { f(i, get(i)) } } inline fun <T> List<T>.forEachReversed(f: (T) -> Unit) { var i = size - 1 while (i >= 0) { f(get(i)) i-- } } inline fun <T> List<T>.forEachReversedWithIndex(f: (Int, T) -> Unit) { var i = size - 1 while (i >= 0) { f(i, get(i)) i-- } } fun <F, S> android.util.Pair<F, S>.toKotlinPair(): Pair<F, S> { return first to second } fun <F, S> Pair<F, S>.toAndroidPair(): android.util.Pair<F, S> { return android.util.Pair(first, second) }
apache-2.0
1209d230edb5daa918acbb788d610c7c
24.981818
75
0.621849
3.201794
false
false
false
false
panpf/sketch
sketch/src/main/java/com/github/panpf/sketch/drawable/SketchCountBitmapDrawable.kt
1
2094
/* * Copyright (C) 2022 panpf <[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.github.panpf.sketch.drawable import android.content.res.Resources import android.graphics.drawable.BitmapDrawable import com.github.panpf.sketch.cache.CountBitmap import com.github.panpf.sketch.datasource.DataFrom import com.github.panpf.sketch.decode.ImageInfo import com.github.panpf.sketch.decode.internal.logString /** * BitmapDrawable with reference counting support */ class SketchCountBitmapDrawable constructor( resources: Resources, val countBitmap: CountBitmap, override val imageUri: String, override val requestKey: String, override val requestCacheKey: String, override val imageInfo: ImageInfo, override val transformedList: List<String>?, override val extras: Map<String, String>?, override val dataFrom: DataFrom, ) : BitmapDrawable(resources, countBitmap.bitmap!!), SketchDrawable { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SketchCountBitmapDrawable) return false if (countBitmap != other.countBitmap) return false if (dataFrom != other.dataFrom) return false return true } override fun hashCode(): Int { var result = countBitmap.hashCode() result = 31 * result + dataFrom.hashCode() return result } override fun toString(): String = "SketchCountBitmapDrawable(${bitmap.logString},${imageInfo.toShortString()},$dataFrom,$transformedList,$extras,'$requestKey')" }
apache-2.0
5ee4a91e8fcdf2092f94247ddedd2d3e
36.410714
134
0.730181
4.48394
false
false
false
false
project-chip/connectedhomeip
examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/setuppayloadscanner/BarcodeFragment.kt
1
10128
/* * Copyright (c) 2020 Project CHIP Authors * 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.google.chip.chiptool.setuppayloadscanner import android.Manifest import android.annotation.SuppressLint import android.content.pm.PackageManager import android.os.Bundle import android.os.Handler import android.os.Looper import android.util.DisplayMetrics import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.camera.core.* import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.view.PreviewView import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat.checkSelfPermission import androidx.fragment.app.Fragment import chip.setuppayload.SetupPayload import chip.setuppayload.SetupPayloadParser import chip.setuppayload.SetupPayloadParser.UnrecognizedQrCodeException import com.google.chip.chiptool.R import com.google.chip.chiptool.SelectActionFragment import com.google.chip.chiptool.util.FragmentUtil import com.google.mlkit.vision.barcode.BarcodeScanner import com.google.mlkit.vision.barcode.BarcodeScanning import com.google.mlkit.vision.barcode.common.Barcode import com.google.mlkit.vision.common.InputImage import kotlinx.android.synthetic.main.barcode_fragment.view.inputAddressBtn import java.util.concurrent.Executors import kotlin.math.abs import kotlin.math.max import kotlin.math.min /** Launches the camera to scan for QR code. */ class BarcodeFragment : Fragment() { private lateinit var previewView: PreviewView private var manualCodeEditText: EditText? = null private var manualCodeBtn: Button? = null private fun aspectRatio(width: Int, height: Int): Int { val previewRatio = max(width, height).toDouble() / min(width, height) if (abs(previewRatio - RATIO_4_3_VALUE) <= abs(previewRatio - RATIO_16_9_VALUE)) { return AspectRatio.RATIO_4_3 } return AspectRatio.RATIO_16_9 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (!hasCameraPermission()) { requestCameraPermission() } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return inflater.inflate(R.layout.barcode_fragment, container, false).apply { previewView = findViewById(R.id.camera_view) manualCodeEditText = findViewById(R.id.manualCodeEditText) manualCodeBtn = findViewById(R.id.manualCodeBtn) startCamera() inputAddressBtn.setOnClickListener { FragmentUtil.getHost( this@BarcodeFragment, SelectActionFragment.Callback::class.java )?.onShowDeviceAddressInput() } } } @SuppressLint("UnsafeOptInUsageError") private fun startCamera() { val cameraProviderFuture = ProcessCameraProvider.getInstance(requireActivity()) cameraProviderFuture.addListener({ val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get() val metrics = DisplayMetrics().also { previewView.display?.getRealMetrics(it) } val screenAspectRatio = aspectRatio(metrics.widthPixels, metrics.heightPixels) // Preview val preview: Preview = Preview.Builder() .setTargetAspectRatio(screenAspectRatio) .setTargetRotation(previewView.display.rotation) .build() preview.setSurfaceProvider(previewView.surfaceProvider) // Setup barcode scanner val imageAnalysis = ImageAnalysis.Builder() .setTargetAspectRatio(screenAspectRatio) .setTargetRotation(previewView.display.rotation) .build() val cameraExecutor = Executors.newSingleThreadExecutor() val barcodeScanner: BarcodeScanner = BarcodeScanning.getClient() imageAnalysis.setAnalyzer(cameraExecutor) { imageProxy -> processImageProxy(barcodeScanner, imageProxy) } // Select back camera as a default val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA try { // Unbind use cases before rebinding cameraProvider.unbindAll() // Bind use cases to camera cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalysis) } catch (exc: Exception) { Log.e(TAG, "Use case binding failed", exc) } }, ContextCompat.getMainExecutor(requireActivity())) //workaround: can not use gms to scan the code in China, added a EditText to debug manualCodeBtn?.setOnClickListener { val qrCode = manualCodeEditText?.text.toString() Log.d(TAG, "Submit Code:$qrCode") handleInputQrCode(qrCode) } } @ExperimentalGetImage private fun processImageProxy( barcodeScanner: BarcodeScanner, imageProxy: ImageProxy ) { val inputImage = InputImage.fromMediaImage(imageProxy.image!!, imageProxy.imageInfo.rotationDegrees) barcodeScanner.process(inputImage) .addOnSuccessListener { barcodes -> barcodes.forEach { handleScannedQrCode(it) } } .addOnFailureListener { Log.e(TAG, it.message ?: it.toString()) }.addOnCompleteListener { // When the image is from CameraX analysis use case, must call image.close() on received // images when finished using them. Otherwise, new images may not be received or the camera // may stall. imageProxy.close() } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { if (requestCode == REQUEST_CODE_CAMERA_PERMISSION) { if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_DENIED) { showCameraPermissionAlert() } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } private fun handleInputQrCode(qrCode: String) { lateinit var payload: SetupPayload try { payload = SetupPayloadParser().parseQrCode(qrCode) } catch (ex: UnrecognizedQrCodeException) { Log.e(TAG, "Unrecognized QR Code", ex) Toast.makeText(requireContext(), "Unrecognized QR Code", Toast.LENGTH_SHORT).show() } FragmentUtil.getHost(this, Callback::class.java) ?.onCHIPDeviceInfoReceived(CHIPDeviceInfo.fromSetupPayload(payload)) } private fun handleScannedQrCode(barcode: Barcode) { Handler(Looper.getMainLooper()).post { lateinit var payload: SetupPayload try { payload = SetupPayloadParser().parseQrCode(barcode.displayValue) } catch (ex: UnrecognizedQrCodeException) { Log.e(TAG, "Unrecognized QR Code", ex) Toast.makeText(requireContext(), "Unrecognized QR Code", Toast.LENGTH_SHORT).show() return@post } FragmentUtil.getHost(this, Callback::class.java) ?.onCHIPDeviceInfoReceived(CHIPDeviceInfo.fromSetupPayload(payload)) } } private fun showCameraPermissionAlert() { AlertDialog.Builder(requireContext()) .setTitle(R.string.camera_permission_missing_alert_title) .setMessage(R.string.camera_permission_missing_alert_subtitle) .setPositiveButton(R.string.camera_permission_missing_alert_try_again) { _, _ -> requestCameraPermission() } .setCancelable(false) .create() .show() } private fun showCameraUnavailableAlert() { AlertDialog.Builder(requireContext()) .setTitle(R.string.camera_unavailable_alert_title) .setMessage(R.string.camera_unavailable_alert_subtitle) .setPositiveButton(R.string.camera_unavailable_alert_exit) { _, _ -> requireActivity().finish() } .setCancelable(false) .create() .show() } private fun hasCameraPermission(): Boolean { return (PackageManager.PERMISSION_GRANTED == checkSelfPermission(requireContext(), Manifest.permission.CAMERA)) } private fun requestCameraPermission() { val permissions = arrayOf(Manifest.permission.CAMERA) requestPermissions(permissions, REQUEST_CODE_CAMERA_PERMISSION) } /** Interface for notifying the host. */ interface Callback { /** Notifies host of the [CHIPDeviceInfo] from the scanned QR code. */ fun onCHIPDeviceInfoReceived(deviceInfo: CHIPDeviceInfo) } companion object { private const val TAG = "BarcodeFragment" private const val REQUEST_CODE_CAMERA_PERMISSION = 100; @JvmStatic fun newInstance() = BarcodeFragment() private const val RATIO_4_3_VALUE = 4.0 / 3.0 private const val RATIO_16_9_VALUE = 16.0 / 9.0 } }
apache-2.0
b9e3b21fce4177c29eafd431dea790ab
37.957692
107
0.658768
4.962273
false
false
false
false
pennlabs/penn-mobile-android
PennMobile/src/main/java/com/pennapps/labs/pennmobile/FlingFragment.kt
1
3162
package com.pennapps.labs.pennmobile import android.net.Uri import android.os.Bundle import androidx.browser.customtabs.CustomTabsIntent.Builder import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import android.view.* import android.widget.Toast import com.google.firebase.analytics.FirebaseAnalytics import com.pennapps.labs.pennmobile.adapters.FlingRecyclerViewAdapter import kotlinx.android.synthetic.main.fragment_fling.* class FlingFragment : Fragment() { private lateinit var mActivity: MainActivity override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) mActivity = activity as MainActivity mActivity.supportActionBar?.setDisplayHomeAsUpEnabled(true) val bundle = Bundle() bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "7") bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "Spring Fling") bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "App Feature") FirebaseAnalytics.getInstance(mActivity).logEvent(FirebaseAnalytics.Event.VIEW_ITEM, bundle) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.fling_menu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle presses on the action bar items when (item.itemId) { android.R.id.home -> { mActivity.onBackPressed() return true } R.id.fling_raffle -> { val url = "https://docs.google.com/forms/d/e/1FAIpQLSexkehYfGgyAa7RagaCl8rze4KUKQSX9TbcvvA6iXp34TyHew/viewform" val builder = Builder() val customTabsIntent = builder.build() customTabsIntent.launchUrl(mActivity, Uri.parse(url)) true } } return super.onOptionsItemSelected(item) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_fling, container, false) val labs = MainActivity.studentLifeInstance labs.flingEvents.subscribe({ flingEvents -> activity?.runOnUiThread { fling_fragment_recyclerview?.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) fling_fragment_recyclerview?.adapter = FlingRecyclerViewAdapter(context, flingEvents) } }, { activity?.runOnUiThread { Toast.makeText(activity, "Could not retrieve Spring Fling schedule", Toast.LENGTH_LONG).show() } }) return view } override fun onDestroyView() { super.onDestroyView() mActivity.supportActionBar?.setDisplayHomeAsUpEnabled(false) } override fun onResume() { super.onResume() val mActivity : MainActivity? = activity as MainActivity mActivity?.removeTabs() mActivity?.setTitle(R.string.spring_fling) } }
mit
4c0bfc0cf3ce7d07571e45d403e06fd5
39.025316
138
0.683744
4.917574
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/wavesidebar/adapter/BaseViewHolder.kt
1
589
package com.tamsiree.rxui.view.wavesidebar.adapter import android.util.SparseArray import android.view.View import androidx.recyclerview.widget.RecyclerView open class BaseViewHolder(view: View?) : RecyclerView.ViewHolder(view!!) { /** * Views indexed with their IDs */ private val mViews: SparseArray<View?> = SparseArray() fun <V : View?> findViewById(viewId: Int): V? { var view = mViews[viewId] if (view == null) { view = itemView.findViewById(viewId) mViews.put(viewId, view) } return view as V? } }
apache-2.0
92fde5164b26bdc40b1dbfba21665aa3
27.095238
74
0.646859
4.118881
false
false
false
false
stripe/stripe-android
identity/src/main/java/com/stripe/android/identity/utils/DefaultIdentityIO.kt
1
5512
package com.stripe.android.identity.utils import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Rect import android.net.Uri import android.util.Size import androidx.core.content.FileProvider import com.stripe.android.camera.framework.image.constrainToSize import com.stripe.android.camera.framework.image.cropCenter import com.stripe.android.camera.framework.image.cropWithFill import com.stripe.android.camera.framework.image.size import com.stripe.android.camera.framework.image.toJpeg import com.stripe.android.camera.framework.util.maxAspectRatioInSize import com.stripe.android.identity.ml.BoundingBox import java.io.File import java.io.FileOutputStream import java.io.IOException import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import javax.inject.Inject /** * Default implementation of [IdentityIO]. */ internal class DefaultIdentityIO @Inject constructor(private val context: Context) : IdentityIO { override fun createInternalFileUri(): ContentUriResult { createImageFile().also { file -> return ContentUriResult( createUriForFile(file), file.absolutePath ) } } override fun createUriForFile(file: File): Uri = FileProvider.getUriForFile( context, "${context.packageName}.StripeIdentityFileprovider", file ) override fun resizeUriAndCreateFileToUpload( originalUri: Uri, verificationId: String, isFullFrame: Boolean, side: String?, maxDimension: Int, compressionQuality: Float ): File { context.contentResolver.openInputStream(originalUri).use { inputStream -> File( context.filesDir, StringBuilder().also { nameBuilder -> nameBuilder.append(verificationId) side?.let { nameBuilder.append("_$side") } if (isFullFrame) { nameBuilder.append("_full_frame") } nameBuilder.append(".jpeg") }.toString() ).let { fileToSave -> FileOutputStream(fileToSave, false).use { fileOutputStream -> fileOutputStream.write( BitmapFactory.decodeStream(inputStream).constrainToSize( Size( maxDimension, maxDimension ) ).toJpeg(quality = (compressionQuality * 100).toInt()) ) } return fileToSave } } } override fun resizeBitmapAndCreateFileToUpload( bitmap: Bitmap, verificationId: String, fileName: String, maxDimension: Int, compressionQuality: Float ): File { File( context.filesDir, fileName ).let { fileToSave -> FileOutputStream(fileToSave, false).use { fileOutputStream -> fileOutputStream.write( bitmap.constrainToSize( Size( maxDimension, maxDimension ) ).toJpeg(quality = (compressionQuality * 100).toInt()) ) } return fileToSave } } override fun cropAndPadBitmap( original: Bitmap, boundingBox: BoundingBox, paddingSize: Float ): Bitmap { val modelInput = original.cropCenter( maxAspectRatioInSize( original.size(), 1f ) ) return modelInput.cropWithFill( Rect( (modelInput.width * boundingBox.left - paddingSize).toInt(), (modelInput.height * boundingBox.top - paddingSize).toInt(), (modelInput.width * (boundingBox.left + boundingBox.width) + paddingSize).toInt(), (modelInput.height * (boundingBox.top + boundingBox.height) + paddingSize).toInt() ) ) } override fun createTFLiteFile(modelUrl: String): File { return File( context.cacheDir, generateTFLiteFileNameWithGitHash(modelUrl) ) } override fun createCacheFile(): File { return File.createTempFile( generalCacheFileName(), ".tmp", context.filesDir ) } @Throws(IOException::class) private fun createImageFile(): File { return File.createTempFile( "JPEG_${generalCacheFileName()}_", /* prefix */ ".jpg", /* suffix */ context.filesDir ) } private fun generalCacheFileName() = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date()) // Find the githash part of the model URL and general a tflite file name. // Example of modelUrl: https://b.stripecdn.com/gelato/assets/50e98374a70b71b2ee7ec8c3060f187ee1d833bd/assets/id_detectors/tflite/2022-02-23/model.tflite // TODO(ccen): Add name and versioning of the model, calculate MD5 and build a more descriptive caching machanism. private fun generateTFLiteFileNameWithGitHash(modelUrl: String): String { return "${modelUrl.split('/')[5]}.tflite" } }
mit
553aaeb8b4de95e366bb1e612a206064
33.236025
157
0.586538
5.024613
false
false
false
false
AndroidX/androidx
glance/glance-appwidget/integration-tests/demos/src/main/java/androidx/glance/appwidget/demos/ErrorUiAppWidget.kt
3
3074
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.glance.appwidget.demos import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.glance.GlanceModifier import androidx.glance.LocalSize import androidx.glance.appwidget.GlanceAppWidget import androidx.glance.appwidget.GlanceAppWidgetReceiver import androidx.glance.appwidget.SizeMode import androidx.glance.appwidget.background import androidx.glance.layout.Alignment import androidx.glance.layout.Box import androidx.glance.layout.Column import androidx.glance.layout.fillMaxSize import androidx.glance.layout.fillMaxWidth import androidx.glance.layout.padding import androidx.glance.layout.wrapContentHeight import androidx.glance.text.FontWeight import androidx.glance.text.Text import androidx.glance.text.TextAlign import androidx.glance.text.TextStyle import kotlin.math.roundToInt class ErrorUiAppWidget : GlanceAppWidget() { override val sizeMode: SizeMode = SizeMode.Exact @Composable override fun Content() { val size = LocalSize.current Column( modifier = GlanceModifier.fillMaxSize() .background(day = Color.LightGray, night = Color.DarkGray) .padding(8.dp), ) { Text( "Error UI Demo", modifier = GlanceModifier.fillMaxWidth().wrapContentHeight(), style = TextStyle( fontWeight = FontWeight.Bold, fontSize = 18.sp, textAlign = TextAlign.Center ) ) Box( modifier = GlanceModifier.fillMaxWidth().defaultWeight(), contentAlignment = Alignment.Center ) { Text( "Error UI triggers if width or height reach 400 dp in any orientation.", style = TextStyle(fontWeight = FontWeight.Medium, fontSize = 15.sp) ) check(size.width < 400.dp && size.height < 400.dp) { "Too large now!" } } Text( " Current size: ${size.width.value.roundToInt()} dp x " + "${size.height.value.roundToInt()} dp" ) } } } class ErrorUiAppWidgetReceiver : GlanceAppWidgetReceiver() { override val glanceAppWidget: GlanceAppWidget = ErrorUiAppWidget() }
apache-2.0
5fabeb47b275f969d68aa19f877dc0b2
35.595238
92
0.662329
4.833333
false
false
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/Expand.kt
1
3151
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations import org.nd4j.autodiff.samediff.SDVariable import org.nd4j.autodiff.samediff.SameDiff import org.nd4j.autodiff.samediff.internal.SameDiffOp import org.nd4j.linalg.api.buffer.DataType import org.nd4j.samediff.frameworkimport.ImportGraph import org.nd4j.samediff.frameworkimport.hooks.PreImportHook import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry import org.nd4j.shade.protobuf.GeneratedMessageV3 import org.nd4j.shade.protobuf.ProtocolMessageEnum /** * A port of expand.py from onnx tensorflow for samediff: * https://github.com/onnx/onnx-tensorflow/blob/master/onnx_tf/handlers/backend/expand.py * * @author Adam Gibson */ @PreHookRule(nodeNames = [],opNames = ["Expand"],frameworkName = "onnx") class Expand : PreImportHook { override fun doImport( sd: SameDiff, attributes: Map<String, Any>, outputNames: List<String>, op: SameDiffOp, mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>, importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>, dynamicVariables: Map<String, GeneratedMessageV3> ): Map<String, List<SDVariable>> { var inputVariable = sd.getVariable(op.inputsToOp[0]) val newShape = sd.getVariable(op.inputsToOp[1]) val outputVarName = outputNames[0] var outputVar: SDVariable = if(inputVariable.dataType() == DataType.BOOL) { val ones = sd.create(newShape,DataType.INT8) val assignedOnes = ones.assign(1.0) val r = sd.castTo(inputVariable,DataType.INT8).mul(assignedOnes) sd.castTo(outputVarName,r,DataType.BOOL) } else { val ones = sd.create(newShape,inputVariable.dataType()) val assignedOnes = ones.assign(1.0) assignedOnes.mul(outputVarName,inputVariable) } return mapOf(outputVar.name() to listOf(outputVar)) } }
apache-2.0
55e1c1512c6ec1bbc5c7754302fd01c5
43.394366
184
0.6947
4.201333
false
false
false
false
JoachimR/Bible2net
app/src/main/java/de/reiss/bible2net/theword/bible/BibleFragment.kt
1
3086
package de.reiss.bible2net.theword.bible import android.view.LayoutInflater import android.view.View.GONE import android.view.View.VISIBLE import android.view.ViewGroup import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import de.reiss.bible2net.theword.App import de.reiss.bible2net.theword.R import de.reiss.bible2net.theword.architecture.AppFragment import de.reiss.bible2net.theword.bible.list.BibleListItem import de.reiss.bible2net.theword.bible.list.BibleListItemAdapter import de.reiss.bible2net.theword.databinding.BibleFragmentBinding import de.reiss.bible2net.theword.model.Bible import de.reiss.bible2net.theword.util.extensions.onClick import de.reiss.bible2net.theword.util.sortBibles class BibleFragment : AppFragment<BibleFragmentBinding, BibleViewModel>(R.layout.bible_fragment), BibleClickListener { companion object { fun createInstance() = BibleFragment() } private val appPreferences by lazy { App.component.appPreferences } private lateinit var bibleListItemAdapter: BibleListItemAdapter override fun inflateViewBinding(inflater: LayoutInflater, container: ViewGroup?) = BibleFragmentBinding.inflate(inflater, container, false) override fun initViews() { bibleListItemAdapter = BibleListItemAdapter(bibleClickListener = this) with(binding.recyclerView) { layoutManager = LinearLayoutManager(context) adapter = bibleListItemAdapter } binding.noBiblesRefresh.onClick { tryRefresh() } } override fun defineViewModelProvider(): ViewModelProvider = ViewModelProviders.of( this, BibleViewModel.Factory( App.component.bibleRepository ) ) override fun defineViewModel(): BibleViewModel = loadViewModelProvider().get(BibleViewModel::class.java) override fun initViewModelObservers() { viewModel.biblesLiveData.observe(this, { onResourceChange() }) } override fun onAppFragmentReady() { tryRefresh() } override fun onBibleClicked(bible: Bible) { appPreferences.chosenBible = bible.key } private fun tryRefresh() { if (viewModel.isLoadingBibles().not()) { viewModel.refreshBibles() } } private fun onResourceChange() { binding.loading.visibility = GONE binding.noBibles.visibility = GONE binding.recyclerView.visibility = GONE if (viewModel.isLoadingBibles()) { binding.loading.visibility = VISIBLE } else { sortBibles(viewModel.bibles()).map { BibleListItem(it) }.let { listItems -> if (listItems.isEmpty()) { binding.noBibles.visibility = VISIBLE } else { binding.recyclerView.visibility = VISIBLE bibleListItemAdapter.updateContent(listItems) } } } } }
gpl-3.0
7af3cbfcf5eec832cda09e045fe93c97
30.814433
87
0.685353
4.791925
false
false
false
false
sksamuel/scrimage
scrimage-tests/src/test/kotlin/com/sksamuel/scrimage/core/nio/PngWriterTest.kt
1
2080
@file:Suppress("BlockingMethodInNonBlockingContext") package com.sksamuel.scrimage.core.nio import com.sksamuel.scrimage.ImmutableImage import com.sksamuel.scrimage.nio.PngReader import com.sksamuel.scrimage.nio.PngWriter import io.kotest.core.spec.style.WordSpec import io.kotest.matchers.shouldBe import org.apache.commons.io.IOUtils class PngWriterTest : WordSpec({ val writer: PngWriter = PngWriter.MaxCompression val original = ImmutableImage.loader().fromResource("/com/sksamuel/scrimage/bird.jpg").scaleTo(300, 200) "png write" should { "png output happy path" { val bytes = original.bytes(writer) val expected = ImmutableImage.loader().fromResource("/com/sksamuel/scrimage/io/bird_300_200.png") expected.pixels().size shouldBe ImmutableImage.loader().fromBytes(bytes).pixels().size expected.pixels().toList() shouldBe ImmutableImage.loader().fromBytes(bytes).pixels().toList() expected shouldBe ImmutableImage.loader().fromBytes(bytes) } "png compression happy path" { repeat(10) { k -> val w: PngWriter = PngWriter.NoCompression.withCompression(k) val bytes = original.bytes(w) val expected = ImmutableImage.loader().fromResource("/com/sksamuel/scrimage/io/bird_compressed_$k.png") expected.pixels().size shouldBe ImmutableImage.loader().fromBytes(bytes).pixels().size expected.pixels().toList() shouldBe ImmutableImage.loader().fromBytes(bytes).pixels().toList() expected shouldBe ImmutableImage.loader().fromBytes(bytes) } } "png reader reads an image correctly" { val expected = ImmutableImage.loader().fromResource("/com/sksamuel/scrimage/io/bird_300_200.png") val bytes = IOUtils.toByteArray(javaClass.getResourceAsStream("/com/sksamuel/scrimage/io/bird_300_200.png")) val actual = PngReader().read(bytes, null) actual.width shouldBe expected.width actual.height shouldBe expected.height actual shouldBe expected } } })
apache-2.0
537f32280ea17d54ac53e604a82c5c43
45.222222
117
0.702885
4.416136
false
true
false
false
vimeo/vimeo-networking-java
models/src/main/java/com/vimeo/networking2/VideoStatus.kt
1
911
@file:JvmName("VideoStatusUtils") package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import com.vimeo.networking2.enums.VideoStateType import com.vimeo.networking2.enums.asEnum /** * The current status of the video transcoding process. * * @param state The current state of the transcoding process. * @param progress The percentage of the transcoding process that is complete. * @param timeLeft The remaining time in seconds before transcoding is complete. */ @JsonClass(generateAdapter = true) data class VideoStatus( @Json(name = "state") val state: String? = null, @Json(name = "progress") val progress: Int? = null, @Json(name = "time_left") val timeLeft: Long? = null ) /** * @see VideoStatus.state * @see VideoStateType */ val VideoStatus.videoStateType: VideoStateType get() = state.asEnum(VideoStateType.UNKNOWN)
mit
5d90cc78e4a5901fdf235f0e784c4e61
25.028571
80
0.736553
3.780083
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/template/macros/RsSuggestIndexNameMacro.kt
6
1408
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.template.macros import com.intellij.codeInsight.template.Expression import com.intellij.codeInsight.template.ExpressionContext import com.intellij.codeInsight.template.Result import com.intellij.codeInsight.template.TextResult import com.intellij.codeInsight.template.macro.MacroBase import org.rust.lang.core.psi.ext.RsElement import org.rust.lang.core.psi.ext.ancestorStrict import org.rust.lang.core.resolve.processLocalVariables import java.util.* class RsSuggestIndexNameMacro : MacroBase("rustSuggestIndexName", "rustSuggestIndexName()") { override fun calculateResult(params: Array<out Expression>, context: ExpressionContext, quick: Boolean): Result? { if (params.isNotEmpty()) return null val pivot = context.psiElementAtStartOffset?.ancestorStrict<RsElement>() ?: return null val pats = getPatBindingNamesVisibleAt(pivot) return ('i'..'z') .map(Char::toString) .find { it !in pats } ?.let(::TextResult) } } private fun getPatBindingNamesVisibleAt(pivot: RsElement): Set<String> { val result = HashSet<String>() processLocalVariables(pivot) { patBinding -> val name = patBinding.name if (name != null) { result += name } } return result }
mit
33e4f1f463ff13d810c8dee89169ad4c
35.102564
118
0.715909
4.253776
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/utils/ExprUtils.kt
3
3456
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.utils import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.LogicOp import org.rust.lang.core.psi.ext.operatorType import org.rust.lang.core.psi.ext.unwrapParenExprs /** * Returns `true` if all elements are `true`, `false` if there exists * `false` element and `null` otherwise. */ private fun <T> List<T>.allMaybe(predicate: (T) -> Boolean?): Boolean? { val values = map(predicate) val nullsTrue = values.all { it ?: true } val nullsFalse = values.all { it ?: false } return if (nullsTrue == nullsFalse) nullsTrue else null } /** * Check if an expression is functionally pure * (has no side-effects and throws no errors). * * @return `true` if the expression is pure, `false` if * > it is not pure (has side-effects / throws errors) * > or `null` if it is unknown. */ fun RsExpr.isPure(): Boolean? { return when (this) { is RsArrayExpr -> when (semicolon) { null -> exprList.allMaybe(RsExpr::isPure) else -> exprList[0].isPure() // Array literal of form [expr; size], // size is a compile-time constant, so it is always pure } is RsStructLiteral -> when (structLiteralBody.dotdot) { null -> structLiteralBody.structLiteralFieldList .map { it.expr } .allMaybe { it?.isPure() } // TODO: Why `it` can be null? else -> null // TODO: handle update case (`Point{ y: 0, z: 10, .. base}`) } is RsBinaryExpr -> when (operatorType) { is LogicOp -> listOfNotNull(left, right).allMaybe(RsExpr::isPure) else -> null // Have to search if operation is overloaded } is RsTupleExpr -> exprList.allMaybe(RsExpr::isPure) is RsDotExpr -> if (methodCall != null) null else expr.isPure() is RsParenExpr -> expr?.isPure() == true is RsBreakExpr, is RsContExpr, is RsRetExpr, is RsTryExpr -> false // Changes execution flow is RsPathExpr, is RsLitExpr, is RsUnitExpr -> true // TODO: more complex analysis of blocks of code and search of implemented traits is RsBlockExpr, // Have to analyze lines, very hard case is RsCastExpr, // `expr.isPure()` maybe not true, think about side-effects, may panic while cast is RsCallExpr, // All arguments and function itself must be pure, very hard case is RsForExpr, // Always return (), if pure then can be replaced with it is RsIfExpr, is RsIndexExpr, // Index trait can be overloaded, can panic if out of bounds is RsLambdaExpr, is RsLoopExpr, is RsMacroExpr, is RsMatchExpr, is RsRangeExpr, is RsUnaryExpr, // May be overloaded is RsWhileExpr -> null else -> null } } /*** * Go to the RsExpr, which parent is not RsParenExpr. * * @return RsExpr, which parent is not RsParenExpr. */ fun RsExpr.skipParenExprUp(): RsExpr { var element = this var parent = element.parent while (parent is RsParenExpr) { element = parent parent = parent.parent } return element } /*** * Go down to the item below RsParenExpr. * * @return a child expression without parentheses. */ fun RsCondition.skipParenExprDown(): RsExpr? = expr?.let { unwrapParenExprs(it) }
mit
bc54ef2da169032a3f719a00183ee26a
33.909091
104
0.62934
4.013937
false
false
false
false
neva-dev/gradle-osgi-plugin
plugins/gradle-plugin/src/main/kotlin/com/neva/osgi/toolkit/gradle/internal/Formats.kt
1
1894
package com.neva.osgi.toolkit.gradle.internal import com.fasterxml.jackson.core.util.DefaultIndenter import com.fasterxml.jackson.core.util.DefaultPrettyPrinter import com.fasterxml.jackson.databind.ObjectMapper import java.util.* import java.util.concurrent.TimeUnit object Formats { val JSON_MAPPER = { val printer = DefaultPrettyPrinter() printer.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE) ObjectMapper().writer(printer) }() fun toJson(value: Any): String? { return JSON_MAPPER.writeValueAsString(value) } fun <T> fromJson(json: String, clazz: Class<T>): T? { return ObjectMapper().readValue(json, clazz) } fun toBase64(value: String): String { return Base64.getEncoder().encodeToString(value.toByteArray()) } fun bytesToHuman(bytes: Long): String { if (bytes < 1024) { return bytes.toString() + " B" } else if (bytes < 1024 * 1024) { return (bytes / 1024).toString() + " KB" } else if (bytes < 1024 * 1024 * 1024) { return String.format("%.2f MB", bytes / (1024.0 * 1024.0)) } else { return String.format("%.2f GB", bytes / (1024.0 * 1024.0 * 1024.0)) } } fun percent(current: Int, total: Int): String { return percent(current.toLong(), total.toLong()) } fun percent(current: Long, total: Long): String { val value: Double = if (total == 0L) 0.0 else current.toDouble() / total.toDouble() return "${"%.2f".format(value * 100.0)}%" } fun duration(millis: Long): String { return String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(millis), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)) ) } }
apache-2.0
76879f901c65a462f9ce5d8f60370050
31.101695
91
0.614572
4.073118
false
false
false
false
McGars/basekitk
basekitk/src/main/kotlin/com/mcgars/basekitk/features/drawer/BaseDrawerAdapter.kt
1
814
package com.mcgars.basekitk.features.drawer import android.content.Context import com.mcgars.basekitk.tools.SimpleBaseAdapter abstract class BaseDrawerAdapter<T, H>(context: Context, list: List<T>, layoutId: Int) : SimpleBaseAdapter<T, H>(context, list, layoutId) { var selectedPosition = NON_SELECTED protected set var selectedId: Int = 0 protected set init { initData() } fun setSelected(menuId: Int, selectedPos: Int = NON_SELECTED) { if (selectedId == menuId) return selectedId = menuId this.selectedPosition = selectedPos notifyDataSetChanged() } /** * Заполняем список менюшками */ protected abstract fun initData() companion object { val NON_SELECTED = -1 } }
apache-2.0
c1628f9c8c127842f65cbd82b0d510bf
22.235294
139
0.655696
4.247312
false
false
false
false