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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
smmribeiro/intellij-community | plugins/ide-features-trainer/src/training/statistic/FeatureUsageStatisticConsts.kt | 1 | 2228 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.statistic
object FeatureUsageStatisticConsts {
const val LESSON_ID = "lesson_id"
const val LANGUAGE = "language"
const val DURATION = "duration"
const val START = "start"
const val PASSED = "passed"
const val STOPPED = "stopped"
const val START_MODULE_ACTION = "start_module_action"
const val MODULE_NAME = "module_name"
const val PROGRESS = "progress"
const val COMPLETED_COUNT = "completed_count"
const val COURSE_SIZE = "course_size"
const val EXPAND_WELCOME_PANEL = "expand_welcome_screen"
const val SHORTCUT_CLICKED = "shortcut_clicked"
const val RESTORE = "restore"
const val LEARN_PROJECT_OPENED_FIRST_TIME = "learn_project_opened_first_time"
const val NON_LEARNING_PROJECT_OPENED = "non_learning_project_opened"
const val LEARN_PROJECT_OPENING_WAY = "learn_opening_way"
const val ACTION_ID = "action_id"
const val TASK_ID = "task_id"
const val KEYMAP_SCHEME = "keymap_scheme"
const val REASON = "reason"
const val NEW_LESSONS_NOTIFICATION_SHOWN = "new_lessons_notification_shown"
const val SHOW_NEW_LESSONS = "show_new_lessons"
const val NEED_SHOW_NEW_LESSONS_NOTIFICATIONS = "need_show_new_lessons_notifications"
const val NEW_LESSONS_COUNT = "new_lessons_count"
const val LAST_BUILD_LEARNING_OPENED = "last_build_learning_opened"
const val SHOULD_SHOW_NEW_LESSONS = "show_it"
const val TIP_FILENAME = "filename"
const val LESSON_LINK_CLICKED_FROM_TIP = "lesson_link_clicked_from_tip"
const val LESSON_STARTING_WAY = "starting_way"
const val HELP_LINK_CLICKED = "help_link_clicked"
const val ONBOARDING_FEEDBACK_NOTIFICATION_SHOWN = "onboarding_feedback_notification_shown"
const val ONBOARDING_FEEDBACK_DIALOG_RESULT = "onboarding_feedback_dialog_result"
const val FEEDBACK_ENTRY_PLACE = "feedback_entry_place"
const val FEEDBACK_HAS_BEEN_SENT = "feedback_has_been_sent"
const val FEEDBACK_OPENED_VIA_NOTIFICATION = "feedback_opened_via_notification"
const val FEEDBACK_LIKENESS_ANSWER = "feedback_likeness_answer"
const val FEEDBACK_EXPERIENCED_USER = "feedback_experienced_user"
}
| apache-2.0 | 6813f61e269275cf64db52bebc288dc4 | 50.813953 | 140 | 0.753142 | 3.514196 | false | false | false | false |
Pattonville-App-Development-Team/Android-App | app/src/main/java/org/pattonvillecs/pattonvilleapp/view/ui/calendar/LiveDataUtils.kt | 1 | 3839 | /*
* Copyright (C) 2017 - 2018 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District
*
* 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 org.pattonvillecs.pattonvilleapp.view.ui.calendar
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MediatorLiveData
import android.arch.lifecycle.Transformations
/**
* This function creates a [LiveData] of a [Pair] of the two types provided. The resulting LiveData is updated whenever either input LiveData updates and both LiveData have updated at least once before.
*
* If the zip of A and B is C, and A and B are updated in this pattern: `AABA`, C would be updated twice (once with the second A value and first B value, and once with the third A value and first B value).
*
* @param a the first LiveData
* @param b the second LiveData
* @since 1.2.0
* @author Mitchell Skaggs
*/
fun <A, B> zipLiveData(a: LiveData<A>, b: LiveData<B>): LiveData<Pair<A, B>> {
return MediatorLiveData<Pair<A, B>>().apply {
var lastA: A? = null
var lastB: B? = null
fun update() {
val localLastA = lastA
val localLastB = lastB
if (localLastA != null && localLastB != null)
this.value = Pair(localLastA, localLastB)
}
addSource(a) {
lastA = it
update()
}
addSource(b) {
lastB = it
update()
}
}
}
/**
* This is merely an extension function for [zipLiveData].
*
* @see zipLiveData
* @since 1.2.0
* @author Mitchell Skaggs
*/
fun <A, B> LiveData<A>.zipTo(b: LiveData<B>): LiveData<Pair<A, B>> = zipLiveData(this, b)
/**
* This is an extension function that calls to [Transformations.map]. If null is received, null is returned instead of calling the provided function.
*
* @see Transformations.map
* @since 1.2.0
* @author Mitchell Skaggs
*/
inline fun <A, B> LiveData<A>.map(crossinline function: (A) -> B): LiveData<B> =
Transformations.map(this) { it: A? ->
if (it == null) null else function(it)
}
/**
* This is an extension function that calls to [Transformations.map]. It exposes the possibilities of receiving and returning null.
*
* @see Transformations.map
* @since 1.2.0
* @author Mitchell Skaggs
*/
fun <A, B> LiveData<A>.mapNullable(function: (A?) -> B?): LiveData<B> =
Transformations.map(this, function)
/**
* This is an extension function that calls to [Transformations.switchMap]. If null is received, null is returned instead of calling the provided function.
*
* @see Transformations.switchMap
* @since 1.2.0
* @author Mitchell Skaggs
*/
fun <A, B> LiveData<A>.switchMap(function: (A) -> LiveData<B>): LiveData<B> =
Transformations.switchMap(this) {
if (it == null) null else function(it)
}
/**
* This is an extension function that calls to [Transformations.switchMap]. It exposes the possibilities of receiving and returning null.
*
* @see Transformations.switchMap
* @since 1.2.0
* @author Mitchell Skaggs
*/
fun <A, B> LiveData<A>.switchMapNullable(function: (A?) -> LiveData<B>?): LiveData<B> =
Transformations.switchMap(this, function)
| gpl-3.0 | 7fab4076964609ca62462be91ea3e0fd | 34.546296 | 205 | 0.674915 | 3.86996 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ui2/Colors.kt | 1 | 5685 | package de.fabmax.kool.modules.ui2
import de.fabmax.kool.math.clamp
import de.fabmax.kool.util.Color
import kotlin.math.roundToInt
/**
* UI colors. Somewhat based on the Material Design color system:
* https://material.io/design/color/the-color-system.html#color-theme-creation
* However, primary and secondary color are replaced by a single accent color.
*
* - [primary]: Accent color used by UI elements.
* - [primaryVariant]: A little less prominent than the primary accent color.
* - [secondary]: Secondary accent color used by UI elements.
* - [secondaryVariant]: A little less prominent than the secondary accent color.
* - [background]: Used on surfaces of components, such as menus.
* - [backgroundVariant]: Appears behind scrollable content.
* - [onPrimary]: Used for icons and text displayed on top of the primary accent color.
* - [onSecondary]: Used for icons and text displayed on top of the secondary accent color.
* - [onBackground]: Used for icons and text displayed on top of the background color.
* - [isLight]: Whether this color is considered as a 'light' or 'dark' set of colors.
*/
data class Colors(
val primary: Color,
val primaryVariant: Color,
val secondary: Color,
val secondaryVariant: Color,
val background: Color,
val backgroundVariant: Color,
val onPrimary: Color,
val onSecondary: Color,
val onBackground: Color,
val isLight: Boolean
) {
private val primaryAlpha = AlphaColorCache(primary)
private val primaryVariantAlpha = AlphaColorCache(primaryVariant)
private val secondaryAlpha = AlphaColorCache(secondary)
private val secondaryVariantAlpha = AlphaColorCache(secondaryVariant)
private val backgroundAlpha = AlphaColorCache(background)
private val backgroundVariantAlpha = AlphaColorCache(backgroundVariant)
private val onPrimaryAlpha = AlphaColorCache(onPrimary)
private val onSecondaryAlpha = AlphaColorCache(onSecondary)
private val onBackgroundAlpha = AlphaColorCache(onBackground)
fun primaryAlpha(alpha: Float) = primaryAlpha.getAlphaColor(alpha)
fun primaryVariantAlpha(alpha: Float) = primaryVariantAlpha.getAlphaColor(alpha)
fun secondaryAlpha(alpha: Float) = secondaryAlpha.getAlphaColor(alpha)
fun secondaryVariantAlpha(alpha: Float) = secondaryVariantAlpha.getAlphaColor(alpha)
fun backgroundAlpha(alpha: Float) = backgroundAlpha.getAlphaColor(alpha)
fun backgroundVariantAlpha(alpha: Float) = backgroundVariantAlpha.getAlphaColor(alpha)
fun onPrimaryAlpha(alpha: Float) = onPrimaryAlpha.getAlphaColor(alpha)
fun onSecondaryAlpha(alpha: Float) = onSecondaryAlpha.getAlphaColor(alpha)
fun onBackgroundAlpha(alpha: Float) = onBackgroundAlpha.getAlphaColor(alpha)
companion object {
fun singleColorLight(
accent: Color,
background: Color = Color("f3f3f3ff"),
onAccent: Color = Color.WHITE,
onBackground: Color = Color("343434ff"),
): Colors = Colors(
primary = accent,
primaryVariant = accent.mix(Color.BLACK, 0.3f),
secondary = accent.mix(Color.BLACK, 0.3f),
secondaryVariant = accent.mix(Color.BLACK, 0.5f),
background = background,
backgroundVariant = background.mix(Color.BLACK, 0.05f).mix(accent, 0.1f),
onPrimary = onAccent,
onSecondary = onAccent,
onBackground = onBackground,
isLight = true
)
fun singleColorDark(
accent: Color,
background: Color = Color("1a1a1aff"),
onAccent: Color = Color.WHITE,
onBackground: Color = Color("f2f2f2ff"),
): Colors = Colors(
primary = accent,
primaryVariant = accent.mix(Color.BLACK, 0.3f),
secondary = accent.mix(Color.BLACK, 0.3f),
secondaryVariant = accent.mix(Color.BLACK, 0.5f),
background = background,
backgroundVariant = background.mix(accent, 0.05f),
onPrimary = onAccent,
onSecondary = onAccent,
onBackground = onBackground,
isLight = false
)
fun darkColors(
primary: Color = Color("ffb703ff"),
primaryVariant: Color = Color("fb8500f0"),
secondary: Color = Color("8ecae6ff"),
secondaryVariant: Color = Color("219ebcff"),
background: Color = Color("023047ff"),
backgroundVariant: Color = Color("143d52ff"),
onPrimary: Color = Color.WHITE,
onSecondary: Color = Color.BLACK,
onBackground: Color = Color("dcf7ffff"),
isLight: Boolean = false
): Colors = Colors(
primary,
primaryVariant,
secondary,
secondaryVariant,
background,
backgroundVariant,
onPrimary,
onSecondary,
onBackground,
isLight
)
val neon = darkColors(
primary = Color("b2ff00"),
primaryVariant = Color("7cb200"),
secondary = Color("b2ff00").withAlpha(0.6f),
secondaryVariant = Color("7cb200").withAlpha(0.6f),
background = Color("101010d0"),
backgroundVariant = Color("202020d0"),
onPrimary = Color.BLACK
)
}
private class AlphaColorCache(baseColor: Color) {
val alphaColors = Array<Color>(20) { baseColor.withAlpha(it / 20f) }
fun getAlphaColor(alpha: Float): Color {
val alphaI = (alpha * 20f).roundToInt().clamp(0, alphaColors.lastIndex)
return alphaColors[alphaI]
}
}
}
| apache-2.0 | 6abb5e8532795be0e1d74ef9c4e691d2 | 40.801471 | 91 | 0.650484 | 4.526274 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/viewholders/EmptyCommentsViewHolder.kt | 1 | 1815 | package com.kickstarter.ui.viewholders
import android.util.Pair
import android.view.View
import androidx.annotation.StringRes
import com.kickstarter.R
import com.kickstarter.databinding.EmptyCommentsLayoutBinding
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.models.Project
import com.kickstarter.models.User
class EmptyCommentsViewHolder(private val binding: EmptyCommentsLayoutBinding, private val delegate: Delegate) : KSViewHolder(binding.root) {
private var project: Project? = null
private var user: User? = null
interface Delegate {
fun emptyCommentsLoginClicked(viewHolder: EmptyCommentsViewHolder?)
}
@Throws(Exception::class)
override fun bindData(data: Any?) {
val projectAndUser = ObjectUtils.requireNonNull(data as? Pair<Project, User>?)
project = ObjectUtils.requireNonNull(projectAndUser.first, Project::class.java)
user = projectAndUser.second
}
override fun onBind() {
when {
user == null -> {
bindView(View.VISIBLE, R.string.project_comments_empty_state_logged_out_message_log_in)
}
project?.isBacking() == true -> {
bindView(View.GONE, R.string.project_comments_empty_state_backer_message)
}
else -> {
bindView(View.GONE, R.string.update_comments_empty_state_non_backer_message)
}
}
binding.commentsLoginButton.setOnClickListener {
emptyCommentsLogin()
}
}
private fun bindView(hasVisibility: Int, @StringRes string: Int) {
binding.commentsLoginButton.visibility = hasVisibility
binding.noCommentsMessage.setText(string)
}
fun emptyCommentsLogin() {
delegate.emptyCommentsLoginClicked(this)
}
}
| apache-2.0 | 9c509534b4d35a350e0cf29cfe519f85 | 34.588235 | 141 | 0.68595 | 4.560302 | false | false | false | false |
zdary/intellij-community | platform/platform-impl/src/com/intellij/ide/impl/TrustedHosts.kt | 2 | 3922 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.impl
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.util.NlsSafe
import com.intellij.util.io.URLUtil
import com.intellij.util.io.URLUtil.SCHEME_SEPARATOR
import com.intellij.util.io.isAncestor
import com.intellij.util.xmlb.annotations.OptionTag
import org.jetbrains.annotations.VisibleForTesting
import java.net.URI
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
@NlsSafe
fun getProjectOriginUrl(projectDir: Path?): String? {
if (projectDir == null) return null
val epName = ExtensionPointName.create<ProjectOriginInfoProvider>("com.intellij.projectOriginInfoProvider")
for (extension in epName.extensions) {
val url = extension.getOriginUrl(projectDir)
if (url != null) {
return url
}
}
return null
}
private val KNOWN_HOSTINGS = listOf(
"git.jetbrains.space",
"github.com",
"bitbucket.org",
"gitlab.com")
@VisibleForTesting
data class Origin(val protocol: String?, val host: String)
@VisibleForTesting
fun getOriginFromUrl(url: String): Origin? {
try {
val urlWithScheme = if (URLUtil.containsScheme(url)) url else "ssh://$url"
val uri = URI(urlWithScheme)
var host = uri.host
if (host == null) {
if (uri.scheme == "ssh") {
if (uri.authority != null) {
// [email protected]:JetBrains
val at = uri.authority.split("@")
val hostAndOrg = if (at.size > 1) at[1] else at[0]
val comma = hostAndOrg.split(":")
host = comma[0]
if (comma.size > 1) {
val org = comma[1]
return Origin(uri.scheme, "$host/$org")
}
}
}
}
if (host == null) return null
if (KNOWN_HOSTINGS.contains(host)) {
val path = uri.path
val secondSlash = path.indexOf("/", 1) // path always starts with '/'
val organization = if (secondSlash >= 0) path.substring(0, secondSlash) else path
return Origin(uri.scheme, uri.host + organization)
}
return Origin(uri.scheme, uri.host)
}
catch (e: Exception) {
LOG.warn("Couldn't parse URL $url", e)
}
return null
}
@State(name = "Trusted.Hosts.Settings", storages = [Storage("trusted-hosts.xml")])
@Service(Service.Level.APP)
class TrustedHostsSettings : SimplePersistentStateComponent<TrustedHostsSettings.State>(State()) {
class State : BaseState() {
@get:OptionTag("TRUSTED_HOSTS")
var trustedHosts by list<String>()
}
fun isUrlTrusted(url: String): Boolean {
return false
}
fun setHostTrusted(host: String, value: Boolean) {
if (value) {
state.trustedHosts.add(host)
}
else {
state.trustedHosts.remove(host)
}
}
fun getTrustedHosts(): List<String> = Collections.unmodifiableList(state.trustedHosts)
fun setTrustedHosts(hosts: List<String>) {
state.trustedHosts = ArrayList<String>(hosts)
}
}
@State(name = "Trusted.Paths.Settings", storages = [Storage("trusted-paths.xml")])
@Service(Service.Level.APP)
internal class TrustedPathsSettings : SimplePersistentStateComponent<TrustedPathsSettings.State>(State()) {
class State : BaseState() {
@get:OptionTag("TRUSTED_PATHS")
var trustedPaths by list<String>()
}
fun isPathTrusted(path: Path): Boolean {
return state.trustedPaths.map { Paths.get(it) }.any { it.isAncestor(path) }
}
fun getTrustedPaths(): List<String> = Collections.unmodifiableList(state.trustedPaths)
fun setTrustedPaths(paths: List<String>) {
state.trustedPaths = ArrayList<String>(paths)
}
fun addTrustedPath(path: String) {
state.trustedPaths.add(path)
}
}
private val LOG = Logger.getInstance("com.intellij.ide.impl.TrustedHosts")
| apache-2.0 | e752536048f1e815054a1eed6e25673d | 28.712121 | 140 | 0.690209 | 3.767531 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/script/ScriptDefinitionsManager.kt | 1 | 22846 | // 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.core.script
import com.intellij.diagnostic.PluginException
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.scratch.ScratchFileService
import com.intellij.ide.scratch.ScratchRootType
import com.intellij.ide.script.IdeConsoleRootType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.extensions.ProjectExtensionPointName
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.progress.util.BackgroundTaskUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.projectRoots.ex.PathUtilEx
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.util.containers.SLRUMap
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.caches.project.SdkInfo
import org.jetbrains.kotlin.idea.caches.project.getScriptRelatedModuleInfo
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.script.configuration.CompositeScriptConfigurationManager
import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings
import org.jetbrains.kotlin.idea.core.util.CheckCanceledLock
import org.jetbrains.kotlin.idea.core.util.writeWithCheckCanceled
import org.jetbrains.kotlin.idea.util.application.getServiceSafe
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.getProjectJdkTableSafe
import org.jetbrains.kotlin.script.ScriptTemplatesProvider
import org.jetbrains.kotlin.scripting.definitions.*
import org.jetbrains.kotlin.scripting.resolve.VirtualFileScriptSource
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.kotlin.utils.addToStdlib.flattenTo
import java.io.File
import java.net.URLClassLoader
import java.nio.file.Path
import java.util.concurrent.locks.ReentrantLock
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.script.dependencies.Environment
import kotlin.script.dependencies.ScriptContents
import kotlin.script.experimental.api.SourceCode
import kotlin.script.experimental.dependencies.DependenciesResolver
import kotlin.script.experimental.dependencies.ScriptDependencies
import kotlin.script.experimental.dependencies.asSuccess
import kotlin.script.experimental.host.ScriptingHostConfiguration
import kotlin.script.experimental.host.configurationDependencies
import kotlin.script.experimental.host.toScriptSource
import kotlin.script.experimental.jvm.JvmDependency
import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration
import kotlin.script.experimental.jvm.util.ClasspathExtractionException
import kotlin.script.experimental.jvm.util.scriptCompilationClasspathFromContextOrStdlib
import kotlin.script.templates.standard.ScriptTemplateWithArgs
class LoadScriptDefinitionsStartupActivity : StartupActivity.Background {
override fun runActivity(project: Project) {
if (isUnitTestMode()) {
// In tests definitions are loaded synchronously because they are needed to analyze script
// In IDE script won't be highlighted before all definitions are loaded, then the highlighting will be restarted
ScriptDefinitionsManager.getInstance(project).reloadScriptDefinitionsIfNeeded()
} else {
BackgroundTaskUtil.runUnderDisposeAwareIndicator(KotlinPluginDisposable.getInstance(project)) {
ScriptDefinitionsManager.getInstance(project).reloadScriptDefinitionsIfNeeded()
ScriptConfigurationManager.getInstance(project).loadPlugins()
}
}
}
}
class ScriptDefinitionsManager(private val project: Project) : LazyScriptDefinitionProvider(), Disposable {
private val definitionsLock = ReentrantReadWriteLock()
private val definitionsBySource = mutableMapOf<ScriptDefinitionsSource, List<ScriptDefinition>>()
@Volatile
private var definitions: List<ScriptDefinition>? = null
private val sourcesToReload = mutableSetOf<ScriptDefinitionsSource>()
private val failedContributorsHashes = HashSet<Int>()
private val scriptDefinitionsCacheLock = CheckCanceledLock()
private val scriptDefinitionsCache = SLRUMap<String, ScriptDefinition>(10, 10)
// cache service as it's getter is on the hot path
// it is safe, since both services are in same plugin
@Volatile
private var configurations: CompositeScriptConfigurationManager? =
ScriptConfigurationManager.compositeScriptConfigurationManager(project)
override fun findDefinition(script: SourceCode): ScriptDefinition? {
val locationId = script.locationId ?: return null
if (nonScriptId(locationId)) return null
configurations?.tryGetScriptDefinitionFast(locationId)?.let { fastPath -> return fastPath }
if (!isReady()) return null
scriptDefinitionsCacheLock.withLock { scriptDefinitionsCache.get(locationId) }?.let { cached -> return cached }
val definition =
if (isScratchFile(script)) {
// Scratch should always have default script definition
getDefaultDefinition()
} else {
super.findDefinition(script) ?: return null
}
scriptDefinitionsCacheLock.withLock {
scriptDefinitionsCache.put(locationId, definition)
}
return definition
}
private fun isScratchFile(script: SourceCode): Boolean {
val virtualFile =
if (script is VirtualFileScriptSource) script.virtualFile
else script.locationId?.let { VirtualFileManager.getInstance().findFileByUrl(it) }
return virtualFile != null && ScratchFileService.getInstance().getRootType(virtualFile) is ScratchRootType
}
override fun findScriptDefinition(fileName: String): KotlinScriptDefinition? =
findDefinition(File(fileName).toScriptSource())?.legacyDefinition
fun reloadDefinitionsBy(source: ScriptDefinitionsSource) {
definitionsLock.writeWithCheckCanceled {
if (definitions == null) {
sourcesToReload.add(source)
return // not loaded yet
}
if (source !in definitionsBySource) error("Unknown script definition source: $source")
}
val safeGetDefinitions = source.safeGetDefinitions()
val updateDefinitionsResult = definitionsLock.writeWithCheckCanceled {
definitionsBySource[source] = safeGetDefinitions
definitions = definitionsBySource.values.flattenTo(mutableListOf())
updateDefinitions()
}
updateDefinitionsResult?.apply()
}
override val currentDefinitions: Sequence<ScriptDefinition>
get() {
val scriptingSettings = kotlinScriptingSettingsSafe() ?: return emptySequence()
return (definitions ?: run {
reloadScriptDefinitions()
definitions!!
}).asSequence().filter { scriptingSettings.isScriptDefinitionEnabled(it) }
}
private fun getSources(): List<ScriptDefinitionsSource> {
@Suppress("DEPRECATION")
val fromDeprecatedEP = Extensions.getArea(project).getExtensionPoint(ScriptTemplatesProvider.EP_NAME).extensions.toList()
.map { ScriptTemplatesProviderAdapter(it).asSource() }
val fromNewEp = ScriptDefinitionContributor.EP_NAME.getPoint(project).extensions.toList()
.map { it.asSource() }
return fromNewEp.dropLast(1) + fromDeprecatedEP + fromNewEp.last()
}
fun reloadScriptDefinitionsIfNeeded() {
definitions ?: loadScriptDefinitions()
}
fun reloadScriptDefinitions() = loadScriptDefinitions()
private fun loadScriptDefinitions() {
if (project.isDisposed) return
val newDefinitionsBySource = getSources().associateWith { it.safeGetDefinitions() }
val updateDefinitionsResult = definitionsLock.writeWithCheckCanceled {
definitionsBySource.putAll(newDefinitionsBySource)
definitions = definitionsBySource.values.flattenTo(mutableListOf())
updateDefinitions()
}
updateDefinitionsResult?.apply()
definitionsLock.writeWithCheckCanceled {
sourcesToReload.takeIf { it.isNotEmpty() }?.let {
val copy = ArrayList<ScriptDefinitionsSource>(it)
it.clear()
copy
}
}?.forEach(::reloadDefinitionsBy)
}
fun reorderScriptDefinitions() {
val scriptingSettings = kotlinScriptingSettingsSafe() ?: return
val updateDefinitionsResult = definitionsLock.writeWithCheckCanceled {
definitions?.let { list ->
list.forEach {
it.order = scriptingSettings.getScriptDefinitionOrder(it)
}
definitions = list.sortedBy(ScriptDefinition::order)
updateDefinitions()
}
}
updateDefinitionsResult?.apply()
}
private fun kotlinScriptingSettingsSafe() = runReadAction {
if (!project.isDisposed) KotlinScriptingSettings.getInstance(project) else null
}
fun getAllDefinitions(): List<ScriptDefinition> = definitions ?: run {
reloadScriptDefinitions()
definitions!!
}
fun isReady(): Boolean {
if (definitions == null) return false
val keys = definitionsLock.writeWithCheckCanceled { definitionsBySource.keys }
return keys.all { source ->
// TODO: implement another API for readiness checking
(source as? ScriptDefinitionContributor)?.isReady() != false
}
}
override fun getDefaultDefinition(): ScriptDefinition {
val standardScriptDefinitionContributor = ScriptDefinitionContributor.find<StandardScriptDefinitionContributor>(project)
?: error("StandardScriptDefinitionContributor should be registered in plugin.xml")
return ScriptDefinition.FromLegacy(getScriptingHostConfiguration(), standardScriptDefinitionContributor.getDefinitions().last())
}
private fun updateDefinitions(): UpdateDefinitionsResult? {
assert(definitionsLock.isWriteLocked) { "updateDefinitions should only be called under the write lock" }
if (project.isDisposed) return null
val fileTypeManager = FileTypeManager.getInstance()
val newExtensions = getKnownFilenameExtensions().toSet().filter {
val fileTypeByExtension = fileTypeManager.getFileTypeByFileName("xxx.$it")
val notKnown = fileTypeByExtension != KotlinFileType.INSTANCE
if (notKnown) {
scriptingWarnLog("extension $it file type [${fileTypeByExtension.name}] is not registered as ${KotlinFileType.INSTANCE.name}")
}
notKnown
}.toSet()
clearCache()
scriptDefinitionsCacheLock.withLock { scriptDefinitionsCache.clear() }
return UpdateDefinitionsResult(project, newExtensions)
}
private data class UpdateDefinitionsResult(val project: Project, val newExtensions: Set<String>) {
fun apply() {
if (newExtensions.isNotEmpty()) {
scriptingWarnLog("extensions ${newExtensions} is about to be registered as ${KotlinFileType.INSTANCE.name}")
// Register new file extensions
ApplicationManager.getApplication().invokeLater {
val fileTypeManager = FileTypeManager.getInstance()
runWriteAction {
newExtensions.forEach {
fileTypeManager.associateExtension(KotlinFileType.INSTANCE, it)
}
}
}
}
// TODO: clear by script type/definition
ScriptConfigurationManager.getInstance(project).updateScriptDefinitionReferences()
}
}
private fun ScriptDefinitionsSource.safeGetDefinitions(): List<ScriptDefinition> {
if (!failedContributorsHashes.contains([email protected]())) try {
return definitions.toList()
} catch (t: Throwable) {
if (t is ControlFlowException) throw t
// reporting failed loading only once
failedContributorsHashes.add([email protected]())
// Assuming that direct ClasspathExtractionException is the result of versions mismatch and missing subsystems, e.g. kotlin plugin
// so, it only results in warning, while other errors are severe misconfigurations, resulting it user-visible error
if (t.cause is ClasspathExtractionException || t is ClasspathExtractionException) {
scriptingWarnLog("Cannot load script definitions from $this: ${t.cause?.message ?: t.message}")
} else {
scriptingErrorLog("[kts] cannot load script definitions using $this", t)
}
}
return emptyList()
}
override fun dispose() {
super.dispose()
clearCache()
definitionsBySource.clear()
definitions = null
failedContributorsHashes.clear()
scriptDefinitionsCache.clear()
configurations = null
}
companion object {
fun getInstance(project: Project): ScriptDefinitionsManager =
project.getServiceSafe<ScriptDefinitionProvider>() as ScriptDefinitionsManager
}
}
fun loadDefinitionsFromTemplates(
templateClassNames: List<String>,
templateClasspath: List<File>,
baseHostConfiguration: ScriptingHostConfiguration,
// TODO: need to provide a way to specify this in compiler/repl .. etc
/*
* Allows to specify additional jars needed for DependenciesResolver (and not script template).
* Script template dependencies naturally become (part of) dependencies of the script which is not always desired for resolver dependencies.
* i.e. gradle resolver may depend on some jars that 'built.gradle.kts' files should not depend on.
*/
additionalResolverClasspath: List<File> = emptyList(),
defaultCompilerOptions: Iterable<String> = emptyList()
): List<ScriptDefinition> = loadDefinitionsFromTemplatesByPaths(
templateClassNames,
templateClasspath.map(File::toPath),
baseHostConfiguration,
additionalResolverClasspath.map(File::toPath),
defaultCompilerOptions
)
// TODO: consider rewriting to return sequence
fun loadDefinitionsFromTemplatesByPaths(
templateClassNames: List<String>,
templateClasspath: List<Path>,
baseHostConfiguration: ScriptingHostConfiguration,
// TODO: need to provide a way to specify this in compiler/repl .. etc
/*
* Allows to specify additional jars needed for DependenciesResolver (and not script template).
* Script template dependencies naturally become (part of) dependencies of the script which is not always desired for resolver dependencies.
* i.e. gradle resolver may depend on some jars that 'built.gradle.kts' files should not depend on.
*/
additionalResolverClasspath: List<Path> = emptyList(),
defaultCompilerOptions: Iterable<String> = emptyList()
): List<ScriptDefinition> {
val classpath = templateClasspath + additionalResolverClasspath
scriptingInfoLog("Loading script definitions $templateClassNames using classpath: ${classpath.joinToString(File.pathSeparator)}")
val baseLoader = ScriptDefinitionContributor::class.java.classLoader
val loader = if (classpath.isEmpty())
baseLoader
else
URLClassLoader(classpath.map { it.toUri().toURL() }.toTypedArray(), baseLoader)
return templateClassNames.mapNotNull { templateClassName ->
try {
// TODO: drop class loading here - it should be handled downstream
// as a compatibility measure, the asm based reading of annotations should be implemented to filter classes before classloading
val template = loader.loadClass(templateClassName).kotlin
val templateClasspathAsFiles = templateClasspath.map(Path::toFile)
val hostConfiguration = ScriptingHostConfiguration(baseHostConfiguration) {
configurationDependencies(JvmDependency(templateClasspathAsFiles))
}
when {
template.annotations.firstIsInstanceOrNull<kotlin.script.templates.ScriptTemplateDefinition>() != null -> {
ScriptDefinition.FromLegacyTemplate(hostConfiguration, template, templateClasspathAsFiles, defaultCompilerOptions)
}
template.annotations.firstIsInstanceOrNull<kotlin.script.experimental.annotations.KotlinScript>() != null -> {
ScriptDefinition.FromTemplate(hostConfiguration, template, ScriptDefinition::class, defaultCompilerOptions)
}
else -> {
scriptingWarnLog("Cannot find a valid script definition annotation on the class $template")
null
}
}
} catch (e: ClassNotFoundException) {
// Assuming that direct ClassNotFoundException is the result of versions mismatch and missing subsystems, e.g. gradle
// so, it only results in warning, while other errors are severe misconfigurations, resulting it user-visible error
scriptingWarnLog("Cannot load script definition class $templateClassName")
null
} catch (e: Throwable) {
if (e is ControlFlowException) throw e
val message = "Cannot load script definition class $templateClassName"
PluginManagerCore.getPluginByClassName(templateClassName)?.let {
scriptingErrorLog(message, PluginException(message, e, it))
} ?: scriptingErrorLog(message, e)
null
}
}
}
@Deprecated("migrating to new configuration refinement: use ScriptDefinitionsSource internally and kotlin.script.experimental.intellij.ScriptDefinitionsProvider as a providing extension point")
interface ScriptDefinitionContributor {
@Deprecated("migrating to new configuration refinement: drop usages")
val id: String
@Deprecated("migrating to new configuration refinement: use ScriptDefinitionsSource instead")
fun getDefinitions(): List<KotlinScriptDefinition>
@JvmDefault
@Deprecated("migrating to new configuration refinement: drop usages")
fun isReady() = true
companion object {
val EP_NAME: ProjectExtensionPointName<ScriptDefinitionContributor> =
ProjectExtensionPointName("org.jetbrains.kotlin.scriptDefinitionContributor")
inline fun <reified T> find(project: Project) =
EP_NAME.getPoint(project).extensionList.filterIsInstance<T>().firstOrNull()
}
}
@Deprecated("migrating to new configuration refinement: use ScriptDefinitionsSource directly instead")
interface ScriptDefinitionSourceAsContributor : ScriptDefinitionContributor, ScriptDefinitionsSource {
override fun getDefinitions(): List<KotlinScriptDefinition> = definitions.map { it.legacyDefinition }.toList()
}
@Deprecated("migrating to new configuration refinement: convert all contributors to ScriptDefinitionsSource/ScriptDefinitionsProvider")
class ScriptDefinitionSourceFromContributor(
val contributor: ScriptDefinitionContributor,
val hostConfiguration: ScriptingHostConfiguration = defaultJvmScriptingHostConfiguration
) : ScriptDefinitionsSource {
override val definitions: Sequence<ScriptDefinition>
get() =
if (contributor is ScriptDefinitionsSource) contributor.definitions
else contributor.getDefinitions().asSequence().map { ScriptDefinition.FromLegacy(hostConfiguration, it) }
override fun equals(other: Any?): Boolean {
return contributor.id == (other as? ScriptDefinitionSourceFromContributor)?.contributor?.id
}
override fun hashCode(): Int {
return contributor.id.hashCode()
}
}
fun ScriptDefinitionContributor.asSource(): ScriptDefinitionsSource =
if (this is ScriptDefinitionsSource) this
else ScriptDefinitionSourceFromContributor(this)
class StandardScriptDefinitionContributor(val project: Project) : ScriptDefinitionContributor {
private val standardIdeScriptDefinition = StandardIdeScriptDefinition(project)
override fun getDefinitions() = listOf(standardIdeScriptDefinition)
override val id: String = "StandardKotlinScript"
}
class StandardIdeScriptDefinition internal constructor(project: Project) : KotlinScriptDefinition(ScriptTemplateWithArgs::class) {
override val dependencyResolver = BundledKotlinScriptDependenciesResolver(project)
}
class BundledKotlinScriptDependenciesResolver(private val project: Project) : DependenciesResolver {
override fun resolve(
scriptContents: ScriptContents,
environment: Environment
): DependenciesResolver.ResolveResult {
val virtualFile = scriptContents.file?.let { VfsUtil.findFileByIoFile(it, true) }
val javaHome = getScriptSDK(project, virtualFile)
var classpath = with(KotlinArtifacts.instance) {
listOf(kotlinReflect, kotlinStdlib, kotlinScriptRuntime)
}
if (ScratchFileService.getInstance().getRootType(virtualFile) is IdeConsoleRootType) {
classpath = scriptCompilationClasspathFromContextOrStdlib(wholeClasspath = true) + classpath
}
return ScriptDependencies(javaHome = javaHome?.let(::File), classpath = classpath).asSuccess()
}
private fun getScriptSDK(project: Project, virtualFile: VirtualFile?): String? {
if (virtualFile != null) {
val dependentModuleSourceInfo = getScriptRelatedModuleInfo(project, virtualFile)
val sdk = dependentModuleSourceInfo?.dependencies()?.filterIsInstance<SdkInfo>()?.singleOrNull()?.sdk
if (sdk != null) {
return sdk.homePath
}
}
val jdk = ProjectRootManager.getInstance(project).projectSdk
?: getProjectJdkTableSafe().allJdks.firstOrNull { sdk -> sdk.sdkType is JavaSdk }
?: PathUtilEx.getAnyJdk(project)
return jdk?.homePath
}
} | apache-2.0 | 48674e04a6dbf962f2ad88ca941b5741 | 45.155556 | 193 | 0.723103 | 5.60638 | false | true | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/toolbar/MainMenuButton.kt | 1 | 2927 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl.customFrameDecorations.header.toolbar
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeBundle
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.PresentationFactory
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.Disposer
import com.intellij.ui.IconManager
import com.intellij.util.ui.JBUI
import org.jetbrains.annotations.ApiStatus
import java.awt.Dimension
import javax.swing.JComponent
@ApiStatus.Internal
internal class MainMenuButton {
private val menuAction = ShowMenuAction()
val button: ActionButton = createMenuButton(menuAction)
val menuShortcutHandler = MainMenuMnemonicHandler(menuAction)
private inner class ShowMenuAction : DumbAwareAction() {
private val icon = IconManager.getInstance().getIcon("expui/general/[email protected]", AllIcons::class.java)
override fun update(e: AnActionEvent) {
e.presentation.icon = icon
e.presentation.text = IdeBundle.message("main.toolbar.menu.button")
}
override fun actionPerformed(e: AnActionEvent) = createPopup(e.dataContext).showUnderneathOf(button)
private fun createPopup(context: DataContext): JBPopup {
val mainMenu = ActionManager.getInstance().getAction(IdeActions.GROUP_MAIN_MENU) as ActionGroup
return JBPopupFactory.getInstance()
.createActionGroupPopup(null, mainMenu, context, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, true,
ActionPlaces.MAIN_MENU_IN_POPUP)
.apply { setShowSubmenuOnHover(true) }
.apply { setMinimumSize(Dimension(JBUI.CurrentTheme.CustomFrameDecorations.menuPopupMinWidth(), 0)) }
}
}
companion object {
private fun createMenuButton(action: AnAction): ActionButton {
return ActionButton(action, PresentationFactory().getPresentation(action),
ActionPlaces.MAIN_MENU_IN_POPUP, Dimension(40, 40))
.apply { setLook(HeaderToolbarButtonLook()) }
}
}
}
class MainMenuMnemonicHandler(val action: AnAction) : Disposable {
private var disposable: Disposable? = null
fun registerShortcuts(component: JComponent) {
if (disposable == null) disposable = Disposer.newDisposable()
val shortcutSet = ActionUtil.getShortcutSet("MainMenuButton.ShowMenu")
action.registerCustomShortcutSet(shortcutSet, component, disposable)
}
fun unregisterShortcuts() {
disposable?.let { Disposer.dispose(it) }
}
override fun dispose() = unregisterShortcuts()
}
| apache-2.0 | 7c1978c3a840665ade6d692e780bc360 | 38.026667 | 120 | 0.765289 | 4.624013 | false | false | false | false |
jwren/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/RefsTable.kt | 1 | 24969 | // 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.workspaceModel.storage.impl
import com.google.common.collect.BiMap
import com.google.common.collect.HashBiMap
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.util.containers.HashSetInterner
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId.ConnectionType
import com.intellij.workspaceModel.storage.impl.containers.*
import it.unimi.dsi.fastutil.ints.IntArrayList
import java.util.function.IntFunction
class ConnectionId private constructor(
val parentClass: Int,
val childClass: Int,
val connectionType: ConnectionType,
val isParentNullable: Boolean
) {
enum class ConnectionType {
ONE_TO_ONE,
ONE_TO_MANY,
ONE_TO_ABSTRACT_MANY,
ABSTRACT_ONE_TO_ONE
}
/**
* This function returns true if this connection allows removing parent of child.
*
* E.g. parent is optional (nullable) for child entity, so the parent can be safely removed.
*/
fun canRemoveParent(): Boolean = isParentNullable
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ConnectionId
if (parentClass != other.parentClass) return false
if (childClass != other.childClass) return false
if (connectionType != other.connectionType) return false
if (isParentNullable != other.isParentNullable) return false
return true
}
override fun hashCode(): Int {
var result = parentClass.hashCode()
result = 31 * result + childClass.hashCode()
result = 31 * result + connectionType.hashCode()
result = 31 * result + isParentNullable.hashCode()
return result
}
override fun toString(): String {
return "Connection(parent=${ClassToIntConverter.INSTANCE.getClassOrDie(parentClass).simpleName} " +
"child=${ClassToIntConverter.INSTANCE.getClassOrDie(childClass).simpleName} $connectionType)"
}
fun debugStr(): String = """
ConnectionId info:
- Parent class: ${this.parentClass.findEntityClass<WorkspaceEntity>()}
- Child class: ${this.childClass.findEntityClass<WorkspaceEntity>()}
- Connection type: $connectionType
- Parent of child is nullable: $isParentNullable
""".trimIndent()
companion object {
/** This function should be [@Synchronized] because interner is not thread-save */
@Synchronized
fun <Parent : WorkspaceEntity, Child : WorkspaceEntity> create(
parentClass: Class<Parent>,
childClass: Class<Child>,
connectionType: ConnectionType,
isParentNullable: Boolean
): ConnectionId {
val connectionId = ConnectionId(parentClass.toClassId(), childClass.toClassId(), connectionType, isParentNullable)
return interner.intern(connectionId)
}
private val interner = HashSetInterner<ConnectionId>()
}
}
/**
* [oneToManyContainer]: [ImmutableNonNegativeIntIntBiMap] - key - child, value - parent
*/
internal class RefsTable internal constructor(
override val oneToManyContainer: Map<ConnectionId, ImmutableNonNegativeIntIntBiMap>,
override val oneToOneContainer: Map<ConnectionId, ImmutableIntIntUniqueBiMap>,
override val oneToAbstractManyContainer: Map<ConnectionId, LinkedBidirectionalMap<ChildEntityId, ParentEntityId>>,
override val abstractOneToOneContainer: Map<ConnectionId, BiMap<ChildEntityId, ParentEntityId>>
) : AbstractRefsTable() {
constructor() : this(HashMap(), HashMap(), HashMap(), HashMap())
}
internal class MutableRefsTable(
override val oneToManyContainer: MutableMap<ConnectionId, NonNegativeIntIntBiMap>,
override val oneToOneContainer: MutableMap<ConnectionId, IntIntUniqueBiMap>,
override val oneToAbstractManyContainer: MutableMap<ConnectionId, LinkedBidirectionalMap<ChildEntityId, ParentEntityId>>,
override val abstractOneToOneContainer: MutableMap<ConnectionId, BiMap<ChildEntityId, ParentEntityId>>
) : AbstractRefsTable() {
private val oneToAbstractManyCopiedToModify: MutableSet<ConnectionId> = HashSet()
private val abstractOneToOneCopiedToModify: MutableSet<ConnectionId> = HashSet()
private fun getOneToManyMutableMap(connectionId: ConnectionId): MutableNonNegativeIntIntBiMap {
val bimap = oneToManyContainer[connectionId] ?: run {
val empty = MutableNonNegativeIntIntBiMap()
oneToManyContainer[connectionId] = empty
return empty
}
return when (bimap) {
is MutableNonNegativeIntIntBiMap -> bimap
is ImmutableNonNegativeIntIntBiMap -> {
val copy = bimap.toMutable()
oneToManyContainer[connectionId] = copy
copy
}
}
}
private fun getOneToAbstractManyMutableMap(connectionId: ConnectionId): LinkedBidirectionalMap<ChildEntityId, ParentEntityId> {
if (connectionId !in oneToAbstractManyContainer) {
oneToAbstractManyContainer[connectionId] = LinkedBidirectionalMap()
}
return if (connectionId in oneToAbstractManyCopiedToModify) {
oneToAbstractManyContainer[connectionId]!!
}
else {
val copy = LinkedBidirectionalMap<ChildEntityId, ParentEntityId>()
val original = oneToAbstractManyContainer[connectionId]!!
original.forEach { (k, v) -> copy[k] = v }
oneToAbstractManyContainer[connectionId] = copy
oneToAbstractManyCopiedToModify.add(connectionId)
copy
}
}
private fun getAbstractOneToOneMutableMap(connectionId: ConnectionId): BiMap<ChildEntityId, ParentEntityId> {
if (connectionId !in abstractOneToOneContainer) {
abstractOneToOneContainer[connectionId] = HashBiMap.create()
}
return if (connectionId in abstractOneToOneCopiedToModify) {
abstractOneToOneContainer[connectionId]!!
}
else {
val copy = HashBiMap.create<ChildEntityId, ParentEntityId>()
val original = abstractOneToOneContainer[connectionId]!!
original.forEach { (k, v) -> copy[k] = v }
abstractOneToOneContainer[connectionId] = copy
abstractOneToOneCopiedToModify.add(connectionId)
copy
}
}
private fun getOneToOneMutableMap(connectionId: ConnectionId): MutableIntIntUniqueBiMap {
val bimap = oneToOneContainer[connectionId] ?: run {
val empty = MutableIntIntUniqueBiMap()
oneToOneContainer[connectionId] = empty
return empty
}
return when (bimap) {
is MutableIntIntUniqueBiMap -> bimap
is ImmutableIntIntUniqueBiMap -> {
val copy = bimap.toMutable()
oneToOneContainer[connectionId] = copy
copy
}
}
}
fun removeRefsByParent(connectionId: ConnectionId, parentId: ParentEntityId) {
@Suppress("IMPLICIT_CAST_TO_ANY")
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> getOneToManyMutableMap(connectionId).removeValue(parentId.id.arrayId)
ConnectionType.ONE_TO_ONE -> getOneToOneMutableMap(connectionId).removeValue(parentId.id.arrayId)
ConnectionType.ONE_TO_ABSTRACT_MANY -> getOneToAbstractManyMutableMap(connectionId).removeValue(parentId)
ConnectionType.ABSTRACT_ONE_TO_ONE -> getAbstractOneToOneMutableMap(connectionId).inverse().remove(parentId)
}.let { }
}
fun removeOneToOneRefByParent(connectionId: ConnectionId, parentId: Int) {
getOneToOneMutableMap(connectionId).removeValue(parentId)
}
fun removeOneToAbstractOneRefByParent(connectionId: ConnectionId, parentId: ParentEntityId) {
getAbstractOneToOneMutableMap(connectionId).inverse().remove(parentId)
}
fun removeOneToOneRefByChild(connectionId: ConnectionId, childId: Int) {
getOneToOneMutableMap(connectionId).removeKey(childId)
}
fun removeOneToManyRefsByChild(connectionId: ConnectionId, childId: Int) {
getOneToManyMutableMap(connectionId).removeKey(childId)
}
fun removeParentToChildRef(connectionId: ConnectionId, parentId: ParentEntityId, childId: ChildEntityId) {
@Suppress("IMPLICIT_CAST_TO_ANY")
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> getOneToManyMutableMap(connectionId).remove(childId.id.arrayId, parentId.id.arrayId)
ConnectionType.ONE_TO_ONE -> getOneToOneMutableMap(connectionId).remove(childId.id.arrayId, parentId.id.arrayId)
ConnectionType.ONE_TO_ABSTRACT_MANY -> getOneToAbstractManyMutableMap(connectionId).remove(childId, parentId)
ConnectionType.ABSTRACT_ONE_TO_ONE -> getAbstractOneToOneMutableMap(connectionId).remove(childId, parentId)
}.let { }
}
internal fun updateChildrenOfParent(connectionId: ConnectionId, parentId: ParentEntityId, childrenIds: List<ChildEntityId>) {
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeValue(parentId.id.arrayId)
val children = childrenIds.map { it.id.arrayId }.toIntArray()
copiedMap.putAll(children, parentId.id.arrayId)
}
ConnectionType.ONE_TO_ONE -> {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.putForce(childrenIds.single().id.arrayId, parentId.id.arrayId)
}
ConnectionType.ONE_TO_ABSTRACT_MANY -> {
val copiedMap = getOneToAbstractManyMutableMap(connectionId)
copiedMap.removeValue(parentId)
// In theory this removing can be avoided because keys will be replaced anyway, but without this cleanup we may get an
// incorrect ordering of the children
childrenIds.forEach { copiedMap.remove(it) }
childrenIds.forEach { copiedMap[it] = parentId }
}
ConnectionType.ABSTRACT_ONE_TO_ONE -> {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.inverse().remove(parentId)
childrenIds.forEach { copiedMap[it] = parentId }
}
}.let { }
}
fun updateOneToManyChildrenOfParent(connectionId: ConnectionId, parentId: Int, childrenEntityIds: Sequence<ChildEntityId>) {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeValue(parentId)
val children = childrenEntityIds.mapToIntArray { it.id.arrayId }
copiedMap.putAll(children, parentId)
}
fun updateOneToAbstractManyChildrenOfParent(connectionId: ConnectionId,
parentId: ParentEntityId,
childrenEntityIds: Sequence<ChildEntityId>) {
val copiedMap = getOneToAbstractManyMutableMap(connectionId)
copiedMap.removeValue(parentId)
childrenEntityIds.forEach { copiedMap[it] = parentId }
}
fun <Parent : WorkspaceEntityBase, OriginParent : Parent> updateOneToAbstractOneParentOfChild(connectionId: ConnectionId,
childId: ChildEntityId,
parentEntity: OriginParent) {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.remove(childId)
copiedMap[childId] = parentEntity.id.asParent()
}
fun updateOneToAbstractOneChildOfParent(connectionId: ConnectionId,
parentId: ParentEntityId,
childEntityId: ChildEntityId) {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.inverse().remove(parentId)
copiedMap[childEntityId.id.asChild()] = parentId
}
fun updateOneToOneChildOfParent(connectionId: ConnectionId, parentId: Int, childEntityId: ChildEntityId) {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.removeValue(parentId)
copiedMap.put(childEntityId.id.arrayId, parentId)
}
fun <Parent : WorkspaceEntityBase> updateOneToOneParentOfChild(connectionId: ConnectionId, childId: Int, parentEntity: Parent) {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.removeKey(childId)
copiedMap.putForce(childId, parentEntity.id.arrayId)
}
internal fun updateParentOfChild(connectionId: ConnectionId, childId: ChildEntityId, parentId: ParentEntityId) {
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeKey(childId.id.arrayId)
copiedMap.putAll(intArrayOf(childId.id.arrayId), parentId.id.arrayId)
}
ConnectionType.ONE_TO_ONE -> {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.removeKey(childId.id.arrayId)
copiedMap.putForce(childId.id.arrayId, parentId.id.arrayId)
}
ConnectionType.ONE_TO_ABSTRACT_MANY -> {
val copiedMap = getOneToAbstractManyMutableMap(connectionId)
copiedMap.remove(childId)
copiedMap[childId] = parentId
}
ConnectionType.ABSTRACT_ONE_TO_ONE -> {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.remove(childId)
copiedMap.forcePut(childId, parentId)
Unit
}
}.let { }
}
fun <Parent : WorkspaceEntityBase> updateOneToManyParentOfChild(connectionId: ConnectionId, childId: Int, parent: Parent) {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeKey(childId)
copiedMap.putAll(intArrayOf(childId), parent.id.arrayId)
}
fun toImmutable(): RefsTable = RefsTable(
oneToManyContainer.mapValues { it.value.toImmutable() },
oneToOneContainer.mapValues { it.value.toImmutable() },
oneToAbstractManyContainer.mapValues {
it.value.let { value ->
val map = LinkedBidirectionalMap<ChildEntityId, ParentEntityId>()
value.forEach { (k, v) -> map[k] = v }
map
}
},
abstractOneToOneContainer.mapValues {
it.value.let { value ->
val map = HashBiMap.create<ChildEntityId, ParentEntityId>()
value.forEach { (k, v) -> map[k] = v }
map
}
}
)
companion object {
fun from(other: RefsTable): MutableRefsTable = MutableRefsTable(
HashMap(other.oneToManyContainer), HashMap(other.oneToOneContainer),
HashMap(other.oneToAbstractManyContainer),
HashMap(other.abstractOneToOneContainer))
}
private fun <T> Sequence<T>.mapToIntArray(action: (T) -> Int): IntArray {
val intArrayList = IntArrayList()
this.forEach { item ->
intArrayList.add(action(item))
}
return intArrayList.toIntArray()
}
}
internal sealed class AbstractRefsTable {
internal abstract val oneToManyContainer: Map<ConnectionId, NonNegativeIntIntBiMap>
internal abstract val oneToOneContainer: Map<ConnectionId, IntIntUniqueBiMap>
internal abstract val oneToAbstractManyContainer: Map<ConnectionId, LinkedBidirectionalMap<ChildEntityId, ParentEntityId>>
internal abstract val abstractOneToOneContainer: Map<ConnectionId, BiMap<ChildEntityId, ParentEntityId>>
fun <Parent : WorkspaceEntity, Child : WorkspaceEntity> findConnectionId(parentClass: Class<Parent>, childClass: Class<Child>): ConnectionId? {
val parentClassId = parentClass.toClassId()
val childClassId = childClass.toClassId()
return (oneToManyContainer.keys.find { it.parentClass == parentClassId && it.childClass == childClassId }
?: oneToOneContainer.keys.find { it.parentClass == parentClassId && it.childClass == childClassId }
?: oneToAbstractManyContainer.keys.find {
it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) &&
it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass)
}
?: abstractOneToOneContainer.keys.find {
it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) &&
it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass)
})
}
fun getParentRefsOfChild(childId: ChildEntityId): Map<ConnectionId, ParentEntityId> {
val childArrayId = childId.id.arrayId
val childClassId = childId.id.clazz
val childClass = childId.id.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, ParentEntityId>()
val filteredOneToMany = oneToManyContainer.filterKeys { it.childClass == childClassId }
for ((connectionId, bimap) in filteredOneToMany) {
if (!bimap.containsKey(childArrayId)) continue
val value = bimap.get(childArrayId)
val existingValue = res.putIfAbsent(connectionId, createEntityId(value, connectionId.parentClass).asParent())
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredOneToOne = oneToOneContainer.filterKeys { it.childClass == childClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsKey(childArrayId)) continue
val value = bimap.get(childArrayId)
val existingValue = res.putIfAbsent(connectionId, createEntityId(value, connectionId.parentClass).asParent())
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredOneToAbstractMany = oneToAbstractManyContainer
.filterKeys { it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass) }
for ((connectionId, bimap) in filteredOneToAbstractMany) {
if (!bimap.containsKey(childId)) continue
val value = bimap[childId] ?: continue
val existingValue = res.putIfAbsent(connectionId, value)
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
if (!bimap.containsKey(childId)) continue
val value = bimap[childId] ?: continue
val existingValue = res.putIfAbsent(connectionId, value)
if (existingValue != null) thisLogger().error("This parent already exists")
}
return res
}
fun getParentOneToOneRefsOfChild(childId: ChildEntityId): Map<ConnectionId, ParentEntityId> {
val childArrayId = childId.id.arrayId
val childClassId = childId.id.clazz
val childClass = childId.id.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, ParentEntityId>()
val filteredOneToOne = oneToOneContainer.filterKeys { it.childClass == childClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsKey(childArrayId)) continue
val value = bimap.get(childArrayId)
val existingValue = res.putIfAbsent(connectionId, createEntityId(value, connectionId.parentClass).asParent())
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
if (!bimap.containsKey(childId)) continue
val value = bimap[childId] ?: continue
val existingValue = res.putIfAbsent(connectionId, value)
if (existingValue != null) thisLogger().error("This parent already exists")
}
return res
}
fun getChildrenRefsOfParentBy(parentId: ParentEntityId): Map<ConnectionId, List<ChildEntityId>> {
val parentArrayId = parentId.id.arrayId
val parentClassId = parentId.id.clazz
val parentClass = parentId.id.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, List<ChildEntityId>>()
val filteredOneToMany = oneToManyContainer.filterKeys { it.parentClass == parentClassId }
for ((connectionId, bimap) in filteredOneToMany) {
val keys = bimap.getKeys(parentArrayId)
if (!keys.isEmpty()) {
val children = keys.map { createEntityId(it, connectionId.childClass) }.mapTo(ArrayList()) { it.asChild() }
val existingValue = res.putIfAbsent(connectionId, children)
if (existingValue != null) thisLogger().error("These children already exist")
}
}
val filteredOneToOne = oneToOneContainer.filterKeys { it.parentClass == parentClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsValue(parentArrayId)) continue
val key = bimap.getKey(parentArrayId)
val existingValue = res.putIfAbsent(connectionId, listOf(createEntityId(key, connectionId.childClass).asChild()))
if (existingValue != null) thisLogger().error("These children already exist")
}
val filteredOneToAbstractMany = oneToAbstractManyContainer
.filterKeys { it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) }
for ((connectionId, bimap) in filteredOneToAbstractMany) {
val keys = bimap.getKeysByValue(parentId) ?: continue
if (keys.isNotEmpty()) {
val existingValue = res.putIfAbsent(connectionId, keys.map { it })
if (existingValue != null) thisLogger().error("These children already exist")
}
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
val key = bimap.inverse()[parentId]
if (key == null) continue
val existingValue = res.putIfAbsent(connectionId, listOf(key))
if (existingValue != null) thisLogger().error("These children already exist")
}
return res
}
fun getChildrenOneToOneRefsOfParentBy(parentId: ParentEntityId): Map<ConnectionId, ChildEntityId> {
val parentArrayId = parentId.id.arrayId
val parentClassId = parentId.id.clazz
val parentClass = parentId.id.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, ChildEntityId>()
val filteredOneToOne = oneToOneContainer.filterKeys { it.parentClass == parentClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsValue(parentArrayId)) continue
val key = bimap.getKey(parentArrayId)
val existingValue = res.putIfAbsent(connectionId, createEntityId(key, connectionId.childClass).asChild())
if (existingValue != null) thisLogger().error("These children already exist")
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
val key = bimap.inverse()[parentId]
if (key == null) continue
val existingValue = res.putIfAbsent(connectionId, key)
if (existingValue != null) thisLogger().error("These children already exist")
}
return res
}
fun getOneToManyChildren(connectionId: ConnectionId, parentId: Int): NonNegativeIntIntMultiMap.IntSequence? {
return oneToManyContainer[connectionId]?.getKeys(parentId)
}
fun getOneToAbstractManyChildren(connectionId: ConnectionId, parentId: ParentEntityId): List<ChildEntityId>? {
val map = oneToAbstractManyContainer[connectionId]
return map?.getKeysByValue(parentId)
}
fun getAbstractOneToOneChildren(connectionId: ConnectionId, parentId: ParentEntityId): ChildEntityId? {
val map = abstractOneToOneContainer[connectionId]
return map?.inverse()?.get(parentId)
}
fun getOneToAbstractOneParent(connectionId: ConnectionId, childId: ChildEntityId): ParentEntityId? {
return abstractOneToOneContainer[connectionId]?.get(childId)
}
fun <Child : WorkspaceEntity> getOneToOneChild(connectionId: ConnectionId, parentId: Int, transformer: IntFunction<Child?>): Child? {
val bimap = oneToOneContainer[connectionId] ?: return null
if (!bimap.containsValue(parentId)) return null
return transformer.apply(bimap.getKey(parentId))
}
fun <Parent : WorkspaceEntity> getOneToOneParent(connectionId: ConnectionId, childId: Int, transformer: IntFunction<Parent?>): Parent? {
val bimap = oneToOneContainer[connectionId] ?: return null
if (!bimap.containsKey(childId)) return null
return transformer.apply(bimap.get(childId))
}
fun <Parent : WorkspaceEntity> getOneToManyParent(connectionId: ConnectionId, childId: Int, transformer: IntFunction<Parent?>): Parent? {
val bimap = oneToManyContainer[connectionId] ?: return null
if (!bimap.containsKey(childId)) return null
return transformer.apply(bimap.get(childId))
}
}
// TODO: 25.05.2021 Make it value class
internal data class ChildEntityId(val id: EntityId) {
override fun toString(): String {
return "ChildEntityId(id=${id.asString()})"
}
}
internal data class ParentEntityId(val id: EntityId) {
override fun toString(): String {
return "ParentEntityId(id=${id.asString()})"
}
}
internal fun EntityId.asChild(): ChildEntityId = ChildEntityId(this)
internal fun EntityId.asParent(): ParentEntityId = ParentEntityId(this)
| apache-2.0 | 39200976201f7863a8f4b4efc3935aea | 42.424348 | 145 | 0.726301 | 5.218182 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitTypeArgumentsIntention.kt | 1 | 8582 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ValueDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.core.copied
import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DelegatingBindingTrace
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
@Suppress("DEPRECATION")
class RemoveExplicitTypeArgumentsInspection : IntentionBasedInspection<KtTypeArgumentList>(RemoveExplicitTypeArgumentsIntention::class) {
override fun problemHighlightType(element: KtTypeArgumentList): ProblemHighlightType = ProblemHighlightType.LIKE_UNUSED_SYMBOL
override fun additionalFixes(element: KtTypeArgumentList): List<LocalQuickFix>? {
val declaration = element.getStrictParentOfType<KtCallableDeclaration>() ?: return null
if (!RemoveExplicitTypeIntention.isApplicableTo(declaration)) return null
return listOf(RemoveExplicitTypeFix(declaration.nameAsSafeName.asString()))
}
private class RemoveExplicitTypeFix(private val declarationName: String) : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.explicit.type.specification.from.0", declarationName)
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? KtTypeArgumentList ?: return
val declaration = element.getStrictParentOfType<KtCallableDeclaration>() ?: return
RemoveExplicitTypeIntention.removeExplicitType(declaration)
}
}
}
class RemoveExplicitTypeArgumentsIntention : SelfTargetingOffsetIndependentIntention<KtTypeArgumentList>(
KtTypeArgumentList::class.java,
KotlinBundle.lazyMessage("remove.explicit.type.arguments")
) {
companion object {
fun isApplicableTo(element: KtTypeArgumentList, approximateFlexible: Boolean): Boolean {
val callExpression = element.parent as? KtCallExpression ?: return false
val typeArguments = callExpression.typeArguments
if (typeArguments.isEmpty() || typeArguments.any { it.typeReference?.annotationEntries?.isNotEmpty() == true }) return false
val resolutionFacade = callExpression.getResolutionFacade()
val bindingContext = resolutionFacade.analyze(callExpression, BodyResolveMode.PARTIAL_WITH_CFA)
val originalCall = callExpression.getResolvedCall(bindingContext) ?: return false
val (contextExpression, expectedType) = findContextToAnalyze(callExpression, bindingContext)
val resolutionScope = contextExpression.getResolutionScope(bindingContext, resolutionFacade)
val key = Key<Unit>("RemoveExplicitTypeArgumentsIntention")
callExpression.putCopyableUserData(key, Unit)
val expressionToAnalyze = contextExpression.copied()
callExpression.putCopyableUserData(key, null)
val newCallExpression = expressionToAnalyze.findDescendantOfType<KtCallExpression> { it.getCopyableUserData(key) != null }!!
newCallExpression.typeArgumentList!!.delete()
val newBindingContext = expressionToAnalyze.analyzeInContext(
resolutionScope,
contextExpression,
trace = DelegatingBindingTrace(bindingContext, "Temporary trace"),
dataFlowInfo = bindingContext.getDataFlowInfoBefore(contextExpression),
expectedType = expectedType ?: TypeUtils.NO_EXPECTED_TYPE,
isStatement = contextExpression.isUsedAsStatement(bindingContext)
)
val newCall = newCallExpression.getResolvedCall(newBindingContext) ?: return false
val args = originalCall.typeArguments
val newArgs = newCall.typeArguments
fun equalTypes(type1: KotlinType, type2: KotlinType): Boolean {
return if (approximateFlexible) {
KotlinTypeChecker.DEFAULT.equalTypes(type1, type2)
} else {
type1 == type2
}
}
return args.size == newArgs.size && args.values.zip(newArgs.values).all { (argType, newArgType) ->
equalTypes(argType, newArgType)
}
}
private fun findContextToAnalyze(expression: KtExpression, bindingContext: BindingContext): Pair<KtExpression, KotlinType?> {
for (element in expression.parentsWithSelf) {
if (element !is KtExpression) continue
if (element.getQualifiedExpressionForSelector() != null) continue
if (element is KtFunctionLiteral) continue
if (!element.isUsedAsExpression(bindingContext)) return element to null
when (val parent = element.parent) {
is KtNamedFunction -> {
val expectedType = if (element == parent.bodyExpression && !parent.hasBlockBody() && parent.hasDeclaredReturnType())
(bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? FunctionDescriptor)?.returnType
else
null
return element to expectedType
}
is KtVariableDeclaration -> {
val expectedType = if (element == parent.initializer && parent.typeReference != null)
(bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? ValueDescriptor)?.type
else
null
return element to expectedType
}
is KtParameter -> {
val expectedType = if (element == parent.defaultValue)
(bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? ValueDescriptor)?.type
else
null
return element to expectedType
}
is KtPropertyAccessor -> {
val property = parent.parent as KtProperty
val expectedType = when {
element != parent.bodyExpression || parent.hasBlockBody() -> null
parent.isSetter -> parent.builtIns.unitType
property.typeReference == null -> null
else -> (bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? FunctionDescriptor)?.returnType
}
return element to expectedType
}
}
}
return expression to null
}
}
override fun isApplicableTo(element: KtTypeArgumentList): Boolean = isApplicableTo(element, approximateFlexible = false)
override fun applyTo(element: KtTypeArgumentList, editor: Editor?) = element.delete()
} | apache-2.0 | e7b521d32ab7e578e9bba5c74a7dd6c8 | 51.335366 | 158 | 0.685038 | 6.13877 | false | false | false | false |
Homes-MinecraftServerMod/Homes | src/main/kotlin/com/masahirosaito/spigot/homes/datas/ConfigData.kt | 1 | 1470 | package com.masahirosaito.spigot.homes.datas
import com.google.gson.annotations.SerializedName
import com.masahirosaito.spigot.homes.Configs
data class ConfigData(
@SerializedName("Language folder name")
var language: String = "en",
@SerializedName("Allow showing debug messages")
var onDebug: Boolean = false,
@SerializedName("Allow using named home")
var onNamedHome: Boolean = true,
@SerializedName("Allow using player home")
var onFriendHome: Boolean = true,
@SerializedName("Allow respawning default home")
var onDefaultHomeRespawn: Boolean = true,
@SerializedName("Allow checking update")
var onUpdateCheck: Boolean = true,
@SerializedName("Allow setting home private")
var onPrivate: Boolean = true,
@SerializedName("Allow invitation")
var onInvite: Boolean = true,
@SerializedName("The limit number of named home")
var homeLimit: Int = -1,
@SerializedName("Allow home display")
var onHomeDisplay: Boolean = true,
@SerializedName("Teleport delay seconds")
var teleportDelay: Int = 3,
@SerializedName("Cancel teleport when moved")
var onMoveCancel: Boolean = true,
@SerializedName("Cancel teleport when damaged")
var onDamageCancel: Boolean = true
) {
init {
require(homeLimit >= -1)
require(teleportDelay >= 0)
}
}
| apache-2.0 | 91aa30190f6a98b0b9fe98f9722f556a | 27.269231 | 57 | 0.64966 | 4.726688 | false | false | false | false |
mstream/BoardGameEngine | src/main/kotlin/io.mstream.boardgameengine/Position.kt | 1 | 846 | package io.mstream.boardgameengine
data class Position private constructor(val x: Int, val y: Int) {
companion object {
var positions = arrayOfNulls<Position>(100)
fun fromCords(x: Int, y: Int): Position {
if (x < 0 || y < 0) {
throw IllegalArgumentException("cords can't be negative")
}
if (x > 9 || y > 9) {
throw IllegalArgumentException("cords can't be bigger than 9")
}
val index = x * 10 + y
val position = positions[index]
when (position) {
null -> {
val newPosition = Position(x, y)
positions[index] = newPosition
return newPosition
}
else -> return position
}
}
}
}
| mit | 92a6dbecfe6edd40b29b33c463e48ffa | 30.333333 | 78 | 0.479905 | 5.005917 | false | false | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/merge/MergeConflictsTreeTable.kt | 13 | 1769 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.merge
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.treeStructure.treetable.ListTreeTableModelOnColumns
import com.intellij.ui.treeStructure.treetable.TreeTable
import com.intellij.util.ui.ColumnInfo
import com.intellij.util.ui.JBUI
class MergeConflictsTreeTable(private val tableModel: ListTreeTableModelOnColumns) : TreeTable(tableModel) {
init {
getTableHeader().reorderingAllowed = false
tree.isRootVisible = false
if (tableModel.columnCount > 1) setShowColumns(true)
}
override fun doLayout() {
if (getTableHeader().resizingColumn == null) {
updateColumnSizes()
}
super.doLayout()
}
private fun updateColumnSizes() {
for ((index, columnInfo) in tableModel.columns.withIndex()) {
val column = columnModel.getColumn(index)
columnInfo.maxStringValue?.let {
val width = calcColumnWidth(it, columnInfo)
column.preferredWidth = width
}
}
var size = width
val fileColumn = 0
for (i in 0 until tableModel.columns.size) {
if (i == fileColumn) continue
size -= columnModel.getColumn(i).preferredWidth
}
columnModel.getColumn(fileColumn).preferredWidth = Math.max(size, JBUI.scale(200))
}
private fun calcColumnWidth(maxStringValue: String, columnInfo: ColumnInfo<Any, Any>): Int {
val columnName = StringUtil.shortenTextWithEllipsis(columnInfo.name, 15, 7, true)
return Math.max(getFontMetrics(font).stringWidth(maxStringValue),
getFontMetrics(tableHeader.font).stringWidth(columnName)) + columnInfo.additionalWidth
}
} | apache-2.0 | 90712593243f97ef2c28299a01054497 | 35.875 | 140 | 0.731487 | 4.232057 | false | false | false | false |
siosio/intellij-community | plugins/git4idea/src/git4idea/index/ui/GitStagePanel.kt | 1 | 18179 | // 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 git4idea.index.ui
import com.intellij.dvcs.ui.RepositoryChangesBrowserNode
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAwareWithCallbacks
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Splitter
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.AbstractVcsHelper
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.ChangesViewManager.createTextStatusFactory
import com.intellij.openapi.vcs.changes.ui.*
import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.Companion.REPOSITORY_GROUPING
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.OnePixelSplitter
import com.intellij.ui.PopupHandler
import com.intellij.ui.ScrollPaneFactory.createScrollPane
import com.intellij.ui.SideBorder
import com.intellij.ui.components.panels.Wrapper
import com.intellij.ui.switcher.QuickActionProvider
import com.intellij.util.EditSourceOnDoubleClickHandler
import com.intellij.util.EventDispatcher
import com.intellij.util.OpenSourceUtil
import com.intellij.util.Processor
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JBUI.Borders.empty
import com.intellij.util.ui.JBUI.Panels.simplePanel
import com.intellij.util.ui.ThreeStateCheckBox
import com.intellij.util.ui.tree.TreeUtil
import com.intellij.vcs.commit.CommitStatusPanel
import com.intellij.vcs.commit.CommitWorkflowListener
import com.intellij.vcs.commit.EditedCommitNode
import com.intellij.vcs.log.runInEdt
import com.intellij.vcs.log.runInEdtAsync
import com.intellij.vcs.log.ui.frame.ProgressStripe
import git4idea.GitVcs
import git4idea.conflicts.GitConflictsUtil.canShowMergeWindow
import git4idea.conflicts.GitConflictsUtil.showMergeWindow
import git4idea.conflicts.GitMergeHandler
import git4idea.i18n.GitBundle.message
import git4idea.index.GitStageCommitWorkflow
import git4idea.index.GitStageCommitWorkflowHandler
import git4idea.index.GitStageTracker
import git4idea.index.GitStageTrackerListener
import git4idea.index.actions.GitAddOperation
import git4idea.index.actions.GitResetOperation
import git4idea.index.actions.StagingAreaOperation
import git4idea.index.actions.performStageOperation
import git4idea.merge.GitDefaultMergeDialogCustomizer
import git4idea.repo.GitConflict
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import git4idea.status.GitRefreshListener
import org.jetbrains.annotations.NonNls
import java.awt.BorderLayout
import java.beans.PropertyChangeListener
import java.util.*
import java.util.stream.Collectors
import javax.swing.JPanel
internal class GitStagePanel(private val tracker: GitStageTracker,
isVertical: Boolean,
isEditorDiffPreview: Boolean,
disposableParent: Disposable,
private val activate: () -> Unit) :
JPanel(BorderLayout()), DataProvider, Disposable {
private val project = tracker.project
private val _tree: MyChangesTree
val tree: ChangesTree get() = _tree
private val treeMessageSplitter: Splitter
private val commitPanel: GitStageCommitPanel
private val commitWorkflowHandler: GitStageCommitWorkflowHandler
private val progressStripe: ProgressStripe
private val commitDiffSplitter: OnePixelSplitter
private val toolbar: ActionToolbar
private val changesStatusPanel: Wrapper
private var diffPreviewProcessor: GitStageDiffPreview? = null
private var editorTabPreview: EditorTabPreview? = null
private val state: GitStageTracker.State
get() = tracker.state
private var hasPendingUpdates = false
internal val commitMessage get() = commitPanel.commitMessage
init {
_tree = MyChangesTree(project)
commitPanel = GitStageCommitPanel(project)
commitPanel.commitActionsPanel.isCommitButtonDefault = {
!commitPanel.commitProgressUi.isDumbMode &&
IdeFocusManager.getInstance(project).getFocusedDescendantFor(this) != null
}
commitPanel.commitActionsPanel.setupShortcuts(this, this)
commitPanel.addEditedCommitListener(_tree::editedCommitChanged, this)
commitPanel.setIncludedRoots(_tree.getIncludedRoots())
_tree.addIncludedRootsListener(object : IncludedRootsListener {
override fun includedRootsChanged() {
commitPanel.setIncludedRoots(_tree.getIncludedRoots())
}
}, this)
commitWorkflowHandler = GitStageCommitWorkflowHandler(GitStageCommitWorkflow(project), commitPanel)
Disposer.register(this, commitPanel)
val toolbarGroup = DefaultActionGroup()
toolbarGroup.add(ActionManager.getInstance().getAction("Git.Stage.Toolbar"))
toolbarGroup.addSeparator()
toolbarGroup.add(ActionManager.getInstance().getAction(ChangesTree.GROUP_BY_ACTION_GROUP))
toolbarGroup.addSeparator()
toolbarGroup.addAll(TreeActionsToolbarPanel.createTreeActions(tree))
toolbar = ActionManager.getInstance().createActionToolbar(GIT_STAGE_PANEL_PLACE, toolbarGroup, true)
toolbar.setTargetComponent(tree)
PopupHandler.installPopupMenu(tree, "Git.Stage.Tree.Menu", "Git.Stage.Tree.Menu")
val statusPanel = CommitStatusPanel(commitPanel).apply {
border = empty(0, 1, 0, 6)
background = tree.background
addToLeft(commitPanel.toolbar.component)
}
val treePanel = simplePanel(createScrollPane(tree, SideBorder.TOP)).addToBottom(statusPanel)
progressStripe = ProgressStripe(treePanel, this, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS)
val treePanelWithToolbar = JPanel(BorderLayout())
treePanelWithToolbar.add(toolbar.component, BorderLayout.NORTH)
treePanelWithToolbar.add(progressStripe, BorderLayout.CENTER)
treeMessageSplitter = TwoKeySplitter(true, ProportionKey("git.stage.tree.message.splitter", 0.7f,
"git.stage.tree.message.splitter.horizontal", 0.5f))
treeMessageSplitter.firstComponent = treePanelWithToolbar
treeMessageSplitter.secondComponent = commitPanel
changesStatusPanel = Wrapper()
changesStatusPanel.minimumSize = JBUI.emptySize()
commitDiffSplitter = OnePixelSplitter("git.stage.commit.diff.splitter", 0.5f)
commitDiffSplitter.firstComponent = treeMessageSplitter
add(commitDiffSplitter, BorderLayout.CENTER)
add(changesStatusPanel, BorderLayout.SOUTH)
updateLayout(isVertical, isEditorDiffPreview, forceDiffPreview = true)
tracker.addListener(MyGitStageTrackerListener(), this)
val busConnection = project.messageBus.connect(this)
busConnection.subscribe(GitRefreshListener.TOPIC, MyGitChangeProviderListener())
busConnection.subscribe(ChangeListListener.TOPIC, MyChangeListListener())
commitWorkflowHandler.workflow.addListener(MyCommitWorkflowListener(), this)
if (isRefreshInProgress()) {
tree.setEmptyText(message("stage.loading.status"))
progressStripe.startLoadingImmediately()
}
updateChangesStatusPanel()
Disposer.register(disposableParent, this)
runInEdtAsync(this) { update() }
}
private fun isRefreshInProgress(): Boolean {
if (GitVcs.getInstance(project).changeProvider!!.isRefreshInProgress) return true
return GitRepositoryManager.getInstance(project).repositories.any {
it.untrackedFilesHolder.isInUpdateMode ||
it.ignoredFilesHolder.isInUpdateMode()
}
}
private fun updateChangesStatusPanel() {
val manager = ChangeListManagerImpl.getInstanceImpl(project)
val factory = manager.updateException?.let { createTextStatusFactory(VcsBundle.message("error.updating.changes", it.message), true) }
?: manager.additionalUpdateInfo
changesStatusPanel.setContent(factory?.create())
}
@RequiresEdt
fun update() {
if (commitWorkflowHandler.workflow.isExecuting) {
hasPendingUpdates = true
return
}
tree.rebuildTree()
commitPanel.setTrackerState(state)
commitWorkflowHandler.state = state
}
override fun getData(dataId: String): Any? {
if (QuickActionProvider.KEY.`is`(dataId)) return toolbar
if (EditorTabDiffPreviewManager.EDITOR_TAB_DIFF_PREVIEW.`is`(dataId)) return editorTabPreview
return null
}
fun updateLayout(isVertical: Boolean, canUseEditorDiffPreview: Boolean, forceDiffPreview: Boolean = false) {
val isEditorDiffPreview = canUseEditorDiffPreview || isVertical
val isMessageSplitterVertical = isVertical || !isEditorDiffPreview
if (treeMessageSplitter.orientation != isMessageSplitterVertical) {
treeMessageSplitter.orientation = isMessageSplitterVertical
}
setDiffPreviewInEditor(isEditorDiffPreview, forceDiffPreview)
}
private fun setDiffPreviewInEditor(isInEditor: Boolean, force: Boolean = false) {
if (Disposer.isDisposed(this)) return
if (!force && (isInEditor == (editorTabPreview != null))) return
if (diffPreviewProcessor != null) Disposer.dispose(diffPreviewProcessor!!)
diffPreviewProcessor = GitStageDiffPreview(project, _tree, tracker, isInEditor, this)
diffPreviewProcessor!!.getToolbarWrapper().setVerticalSizeReferent(toolbar.component)
if (isInEditor) {
editorTabPreview = GitStageEditorDiffPreview(diffPreviewProcessor!!, tree, this, activate)
commitDiffSplitter.secondComponent = null
}
else {
editorTabPreview = null
commitDiffSplitter.secondComponent = diffPreviewProcessor!!.component
}
}
override fun dispose() {
}
private inner class MyChangesTree(project: Project) : GitStageTree(project, project.service<GitStageUiSettingsImpl>(), this@GitStagePanel) {
override val state
get() = [email protected]
override val ignoredFilePaths
get() = [email protected]
override val operations: List<StagingAreaOperation> = listOf(GitAddOperation, GitResetOperation)
private val includedRootsListeners = EventDispatcher.create(IncludedRootsListener::class.java)
init {
isShowCheckboxes = true
setInclusionModel(GitStageRootInclusionModel(project, tracker, this@GitStagePanel))
groupingSupport.addPropertyChangeListener(PropertyChangeListener {
includedRootsListeners.multicaster.includedRootsChanged()
})
inclusionModel.addInclusionListener(object : InclusionListener {
override fun inclusionChanged() {
includedRootsListeners.multicaster.includedRootsChanged()
}
})
tracker.addListener(object : GitStageTrackerListener {
override fun update() {
includedRootsListeners.multicaster.includedRootsChanged()
}
}, this@GitStagePanel)
doubleClickHandler = Processor { e ->
if (EditSourceOnDoubleClickHandler.isToggleEvent(this, e)) return@Processor false
val dataContext = DataManager.getInstance().getDataContext(this)
val mergeAction = ActionManager.getInstance().getAction("Git.Stage.Merge")
val event = AnActionEvent.createFromAnAction(mergeAction, e, ActionPlaces.UNKNOWN, dataContext)
if (ActionUtil.lastUpdateAndCheckDumb(mergeAction, event, true)) {
performActionDumbAwareWithCallbacks(mergeAction, event)
}
else {
OpenSourceUtil.openSourcesFrom(dataContext, true)
}
true
}
}
fun editedCommitChanged() {
rebuildTree()
commitPanel.editedCommit?.let {
val node = TreeUtil.findNodeWithObject(root, it)
node?.let { expandPath(TreeUtil.getPathFromRoot(node)) }
}
}
override fun customizeTreeModel(builder: TreeModelBuilder) {
super.customizeTreeModel(builder)
commitPanel.editedCommit?.let {
val commitNode = EditedCommitNode(it)
builder.insertSubtreeRoot(commitNode)
builder.insertChanges(it.commit.changes, commitNode)
}
}
override fun performStageOperation(nodes: List<GitFileStatusNode>, operation: StagingAreaOperation) {
performStageOperation(project, nodes, operation)
}
override fun getDndOperation(targetKind: NodeKind): StagingAreaOperation? {
return when (targetKind) {
NodeKind.STAGED -> GitAddOperation
NodeKind.UNSTAGED -> GitResetOperation
else -> null
}
}
override fun showMergeDialog(conflictedFiles: List<VirtualFile>) {
AbstractVcsHelper.getInstance(project).showMergeDialog(conflictedFiles)
}
override fun createHoverIcon(node: ChangesBrowserGitFileStatusNode): HoverIcon? {
val conflict = node.conflict ?: return null
val mergeHandler = createMergeHandler(project)
if (!canShowMergeWindow(project, mergeHandler, conflict)) return null
return GitStageMergeHoverIcon(mergeHandler, conflict)
}
fun getIncludedRoots(): Collection<VirtualFile> {
if (!isInclusionEnabled()) return state.allRoots
return inclusionModel.getInclusion().mapNotNull { (it as? GitRepository)?.root }
}
fun addIncludedRootsListener(listener: IncludedRootsListener, disposable: Disposable) {
includedRootsListeners.addListener(listener, disposable)
}
private fun isInclusionEnabled(): Boolean {
return state.rootStates.size > 1 && state.stagedRoots.size > 1 &&
groupingSupport.isAvailable(REPOSITORY_GROUPING) &&
groupingSupport[REPOSITORY_GROUPING]
}
override fun isInclusionEnabled(node: ChangesBrowserNode<*>): Boolean {
return isInclusionEnabled() && node is RepositoryChangesBrowserNode && isUnderKind(node, NodeKind.STAGED)
}
override fun isInclusionVisible(node: ChangesBrowserNode<*>): Boolean = isInclusionEnabled(node)
override fun getIncludableUserObjects(treeModelData: VcsTreeModelData): List<Any> {
return treeModelData
.rawNodesStream()
.filter { node -> isIncludable(node) }
.map { node -> node.userObject }
.collect(Collectors.toList())
}
override fun getNodeStatus(node: ChangesBrowserNode<*>): ThreeStateCheckBox.State {
return inclusionModel.getInclusionState(node.userObject)
}
private fun isUnderKind(node: ChangesBrowserNode<*>, nodeKind: NodeKind): Boolean {
val nodePath = node.path ?: return false
return (nodePath.find { it is MyKindNode } as? MyKindNode)?.kind == nodeKind
}
override fun installGroupingSupport(): ChangesGroupingSupport {
val result = ChangesGroupingSupport(project, this, false)
if (PropertiesComponent.getInstance(project).getValues(GROUPING_PROPERTY_NAME) == null) {
val oldGroupingKeys = (PropertiesComponent.getInstance(project).getValues(GROUPING_KEYS) ?: DEFAULT_GROUPING_KEYS).toMutableSet()
oldGroupingKeys.add(REPOSITORY_GROUPING)
PropertiesComponent.getInstance(project).setValues(GROUPING_PROPERTY_NAME, *oldGroupingKeys.toTypedArray())
}
installGroupingSupport(this, result, GROUPING_PROPERTY_NAME, *DEFAULT_GROUPING_KEYS + REPOSITORY_GROUPING)
return result
}
private inner class GitStageMergeHoverIcon(private val handler: GitMergeHandler, private val conflict: GitConflict) :
HoverIcon(AllIcons.Vcs.Merge, message("changes.view.merge.action.text")) {
override fun invokeAction(node: ChangesBrowserNode<*>) {
showMergeWindow(project, handler, listOf(conflict))
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as GitStageMergeHoverIcon
if (conflict != other.conflict) return false
return true
}
override fun hashCode(): Int {
return conflict.hashCode()
}
}
}
interface IncludedRootsListener : EventListener {
fun includedRootsChanged()
}
private inner class MyGitStageTrackerListener : GitStageTrackerListener {
override fun update() {
[email protected]()
}
}
private inner class MyGitChangeProviderListener : GitRefreshListener {
override fun progressStarted() {
runInEdt(this@GitStagePanel) {
updateProgressState()
}
}
override fun progressStopped() {
runInEdt(this@GitStagePanel) {
updateProgressState()
}
}
private fun updateProgressState() {
if (isRefreshInProgress()) {
tree.setEmptyText(message("stage.loading.status"))
progressStripe.startLoading()
}
else {
progressStripe.stopLoading()
tree.setEmptyText("")
}
}
}
private inner class MyChangeListListener : ChangeListListener {
override fun changeListUpdateDone() {
runInEdt(this@GitStagePanel) {
updateChangesStatusPanel()
}
}
}
private inner class MyCommitWorkflowListener: CommitWorkflowListener {
override fun executionEnded() {
if (hasPendingUpdates) {
hasPendingUpdates = false
update()
}
}
override fun vcsesChanged() = Unit
override fun executionStarted() = Unit
override fun beforeCommitChecksStarted() = Unit
override fun beforeCommitChecksEnded(isDefaultCommit: Boolean, result: CheckinHandler.ReturnResult) = Unit
}
companion object {
@NonNls
private const val GROUPING_PROPERTY_NAME = "GitStage.ChangesTree.GroupingKeys"
private const val GIT_STAGE_PANEL_PLACE = "GitStagePanelPlace"
}
}
internal fun createMergeHandler(project: Project) = GitMergeHandler(project, GitDefaultMergeDialogCustomizer(project))
| apache-2.0 | ba8e64114d1002e1f9a99b4b7aae3c0b | 38.263499 | 158 | 0.751086 | 5.063788 | false | false | false | false |
JetBrains/kotlin-native | shared/src/main/kotlin/org/jetbrains/kotlin/konan/target/KonanTargetExtenstions.kt | 1 | 1715 | package org.jetbrains.kotlin.konan.target
// TODO: This all needs to go to konan.properties
fun KonanTarget.supportsCodeCoverage(): Boolean =
this == KonanTarget.MINGW_X64 ||
this == KonanTarget.LINUX_X64 ||
this == KonanTarget.MACOS_X64 ||
this == KonanTarget.IOS_X64
fun KonanTarget.supportsMimallocAllocator(): Boolean =
when(this) {
is KonanTarget.LINUX_X64 -> true
is KonanTarget.MINGW_X86 -> true
is KonanTarget.MINGW_X64 -> true
is KonanTarget.MACOS_X64 -> true
is KonanTarget.LINUX_ARM64 -> true
is KonanTarget.LINUX_ARM32_HFP -> true
is KonanTarget.ANDROID_X64 -> true
is KonanTarget.ANDROID_ARM64 -> true
is KonanTarget.IOS_ARM32 -> true
is KonanTarget.IOS_ARM64 -> true
is KonanTarget.IOS_X64 -> true
else -> false // watchOS/tvOS/android_x86/android_arm32 aren't tested; linux_mips32/linux_mipsel32 need linking with libatomic.
}
fun KonanTarget.supportsThreads(): Boolean =
when(this) {
is KonanTarget.WASM32 -> false
is KonanTarget.ZEPHYR -> false
else -> true
}
fun KonanTarget.supportedSanitizers(): List<SanitizerKind> =
when(this) {
is KonanTarget.LINUX_X64 -> listOf(SanitizerKind.ADDRESS)
is KonanTarget.MACOS_X64 -> listOf(SanitizerKind.THREAD)
// TODO: Enable ASAN on macOS. Currently there's an incompatibility between clang frontend version and clang_rt.asan version.
// TODO: Enable TSAN on linux. Currently there's a link error between clang_rt.tsan and libstdc++.
// TODO: Consider supporting mingw.
// TODO: Support macOS arm64
else -> listOf()
}
| apache-2.0 | 570ada1ed68aba7a07b8bf9fcbde65cb | 38.883721 | 135 | 0.658309 | 4.063981 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/shortenRefs/removeCompanionRefWithQualifiedReceiverInCalleeExpression.kt | 13 | 401 | class T {
interface Factory {
operator fun invoke(i: Int): IntPredicate
companion object {
inline operator fun invoke(crossinline f: (Int) -> IntPredicate) = object : Factory {
override fun invoke(i: Int) = f(i)
}
}
}
}
<selection>fun foo(): T.Factory = T.Factory.Companion { k -> IntPredicate { n -> n % k == 0 } }</selection> | apache-2.0 | ce453b7ca3f3c158122a8737689b51e2 | 29.923077 | 107 | 0.553616 | 4.177083 | false | false | false | false |
smmribeiro/intellij-community | python/src/com/jetbrains/python/codeInsight/mlcompletion/PyClassCompletionFeatures.kt | 13 | 1244 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.codeInsight.mlcompletion
import com.intellij.codeInsight.completion.ml.CompletionEnvironment
import com.intellij.psi.util.PsiTreeUtil
import com.jetbrains.python.psi.PyClass
import com.jetbrains.python.psi.PyUtil
object PyClassCompletionFeatures {
data class ClassFeatures(val diffLinesWithClassDef: Int, val classHaveConstructor: Boolean)
fun getClassCompletionFeatures(environment: CompletionEnvironment): ClassFeatures? {
val parentClass = PsiTreeUtil.getParentOfType(environment.parameters.position, PyClass::class.java) ?: return null
val lookup = environment.lookup
val editor = lookup.topLevelEditor
val caretOffset = lookup.lookupStart
val logicalPosition = editor.offsetToLogicalPosition(caretOffset)
val lineno = logicalPosition.line
val classLogicalPosition = editor.offsetToLogicalPosition(parentClass.textOffset)
val classLineno = classLogicalPosition.line
val classHaveConstructor = parentClass.methods.any { PyUtil.isInitOrNewMethod(it) }
return ClassFeatures(lineno - classLineno, classHaveConstructor)
}
} | apache-2.0 | 6925b33c267fda126134fb8868d53c26 | 45.111111 | 140 | 0.808682 | 4.766284 | false | false | false | false |
ifabijanovic/swtor-holonet | android/app/src/test/java/com/ifabijanovic/holonet/helper/URLComponentsTests.kt | 1 | 1394 | package com.ifabijanovic.holonet.helper
import org.junit.Assert.*
import org.junit.Test
/**
* Created by feb on 19/03/2017.
*/
class URLComponentsTests {
@Test
fun queryValue_Success() {
val url = "http://www.holonet.test?param=value"
val value = URLComponents(url).queryValue("param")
assertNotNull(value)
assertEquals("value", value)
}
@Test
fun queryValue_NoParameters() {
val url = "http://www.holonet.test"
val value = URLComponents(url).queryValue("param")
assertNull(value)
}
@Test
fun queryValue_MissingParameter() {
val url = "http://www.holonet.test?param=value"
val value = URLComponents(url).queryValue("otherParam")
assertNull(value)
}
@Test
fun queryValue_MultipleParameters() {
val url = "http://www.holonet.test?param1=value1¶m2=value2"
val value1 = URLComponents(url).queryValue("param1")
val value2 = URLComponents(url).queryValue("param2")
assertNotNull(value1)
assertEquals("value1", value1)
assertNotNull(value2)
assertEquals("value2", value2)
}
@Test
fun queryValue_MalformedUrl() {
val url = "somewhere/test?param=value"
val value = URLComponents(url).queryValue("param")
assertNotNull(value)
assertEquals("value", value)
}
}
| gpl-3.0 | 1e8036e5f6a0ccae7422740b32ad4712 | 24.345455 | 71 | 0.628407 | 3.893855 | false | true | false | false |
adriangl/Dev-QuickSettings | app/src/main/kotlin/com/adriangl/devquicktiles/tiles/finishactivities/FinishActivitiesTileService.kt | 1 | 1907 | /*
* Copyright (C) 2017 Adrián García
*
* 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.adriangl.devquicktiles.tiles.finishactivities
import android.graphics.drawable.Icon
import android.provider.Settings
import com.adriangl.devquicktiles.R
import com.adriangl.devquicktiles.tiles.DevelopmentTileService
import com.adriangl.devquicktiles.utils.SettingsUtils
class FinishActivitiesTileService : DevelopmentTileService<Int>() {
companion object {
val SETTING = Settings.Global.ALWAYS_FINISH_ACTIVITIES
}
override fun isActive(value: Int): Boolean {
return value != 0
}
override fun queryValue(): Int {
var value = SettingsUtils.getIntFromGlobalSettings(contentResolver, SETTING)
if (value > 1) value = 1
return value
}
override fun saveValue(value: Int) : Boolean {
return SettingsUtils.setIntToGlobalSettings(contentResolver, SETTING, value)
}
override fun getValueList(): List<Int> {
return listOf(0, 1)
}
override fun getIcon(value: Int): Icon? {
return Icon.createWithResource(applicationContext,
if (value != 0) R.drawable.ic_qs_finish_activities_enabled
else R.drawable.ic_qs_finish_activities_disabled)
}
override fun getLabel(value: Int): CharSequence? {
return getString(R.string.qs_finish_activities)
}
} | apache-2.0 | 5ecd2eb25f35434e4dd0a7db25c946e8 | 32.438596 | 84 | 0.713386 | 4.2713 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/utils/GsonUtil.kt | 1 | 2307 | package ch.rmy.android.http_shortcuts.utils
import android.net.Uri
import androidx.core.net.toUri
import ch.rmy.android.http_shortcuts.data.models.BaseModel
import com.google.gson.ExclusionStrategy
import com.google.gson.FieldAttributes
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonParseException
import com.google.gson.JsonParser
import com.google.gson.JsonPrimitive
import com.google.gson.JsonSerializationContext
import com.google.gson.JsonSerializer
import com.google.gson.reflect.TypeToken
import io.realm.RealmObject
import java.lang.reflect.Type
object GsonUtil {
fun prettyPrint(jsonString: String): String =
try {
val json = JsonParser.parseString(jsonString)
val gson = GsonBuilder().setPrettyPrinting().create()
gson.toJson(json)
} catch (e: JsonParseException) {
jsonString
}
fun importData(data: JsonElement): BaseModel = gson.fromJson(data, BaseModel::class.java)
fun <T> fromJsonObject(jsonObject: String?): Map<String, T> {
if (jsonObject == null) {
return emptyMap()
}
val type = object : TypeToken<Map<String, T>>() {
}.type
return gson.fromJson(jsonObject, type)
}
fun toJson(item: Map<String, Any>): String = gson.toJson(item)
val gson: Gson by lazy {
GsonBuilder()
.addSerializationExclusionStrategy(RealmExclusionStrategy())
.registerTypeAdapter(Uri::class.java, UriSerializer)
.create()
}
object UriSerializer : JsonSerializer<Uri>, JsonDeserializer<Uri> {
override fun serialize(src: Uri, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement =
JsonPrimitive(src.toString())
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): Uri? =
json?.asString?.toUri()
}
private class RealmExclusionStrategy : ExclusionStrategy {
override fun shouldSkipField(f: FieldAttributes) = f.declaringClass == RealmObject::class.java
override fun shouldSkipClass(clazz: Class<*>) = false
}
}
| mit | b4aca719f269c509b1b0b26e1e715921 | 33.432836 | 114 | 0.703945 | 4.660606 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/usecases/GetBuiltInIconPickerDialogUseCase.kt | 1 | 2330 | package ch.rmy.android.http_shortcuts.usecases
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import ch.rmy.android.framework.viewmodel.viewstate.DialogState
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.extensions.createDialogState
import ch.rmy.android.http_shortcuts.icons.BuiltInIconAdapter
import ch.rmy.android.http_shortcuts.icons.Icons
import ch.rmy.android.http_shortcuts.icons.ShortcutIcon
import ch.rmy.android.http_shortcuts.utils.GridLayoutManager
import javax.inject.Inject
class GetBuiltInIconPickerDialogUseCase
@Inject
constructor() {
operator fun invoke(onIconSelected: (ShortcutIcon.BuiltInIcon) -> Unit): DialogState =
createDialogState(DIALOG_ID) {
title(R.string.title_choose_icon)
.view(R.layout.dialog_icon_selector)
.build()
.show {
val grid = findViewById<RecyclerView>(R.id.icon_selector_grid)
grid.setHasFixedSize(true)
val layoutManager = GridLayoutManager(context, R.dimen.grid_layout_builtin_icon_width)
grid.layoutManager = layoutManager
view.addOnLayoutChangeListener { view, _, _, _, _, _, _, _, _ ->
layoutManager.setTotalWidth(view.width)
}
val adapter = BuiltInIconAdapter(getIcons(context)) { icon ->
dismiss()
onIconSelected(icon)
}
grid.adapter = adapter
}
}
private fun getIcons(context: Context): List<ShortcutIcon.BuiltInIcon> =
getColoredIcons(context).plus(getTintableIcons(context))
private fun getColoredIcons(context: Context): List<ShortcutIcon.BuiltInIcon> =
Icons.getColoredIcons()
.map {
ShortcutIcon.BuiltInIcon.fromDrawableResource(context, it)
}
private fun getTintableIcons(context: Context): List<ShortcutIcon.BuiltInIcon> =
Icons.getTintableIcons().map { iconResource ->
ShortcutIcon.BuiltInIcon.fromDrawableResource(context, iconResource, Icons.TintColors.BLACK)
}
companion object {
private const val DIALOG_ID = "built-in-icon-picker"
}
}
| mit | 3e29075572ef20f39664d1ee63dfb433 | 40.607143 | 106 | 0.648927 | 4.586614 | false | false | false | false |
marktony/ZhiHuDaily | app/src/main/java/com/marktony/zhihudaily/data/source/repository/GuokrHandpickNewsRepository.kt | 1 | 4300 | /*
* Copyright 2016 lizhaotailang
*
* 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.marktony.zhihudaily.data.source.repository
import com.marktony.zhihudaily.data.GuokrHandpickNewsResult
import com.marktony.zhihudaily.data.source.Result
import com.marktony.zhihudaily.data.source.datasource.GuokrHandpickDataSource
import com.marktony.zhihudaily.util.formatGuokrHandpickTimeStringToLong
import java.util.*
/**
* Created by lizhaotailang on 2017/5/24.
*
* Concrete implementation to load [GuokrHandpickNewsResult] from the data sources into a cache.
*
* Use the remote data source firstly, which is obtained from the server.
* If the remote data was not available, then use the local data source,
* which was from the locally persisted in database.
*/
class GuokrHandpickNewsRepository private constructor(
private val mRemoteDataSource: GuokrHandpickDataSource,
private val mLocalDataSource: GuokrHandpickDataSource
) : GuokrHandpickDataSource {
private var mCachedItems: MutableMap<Int, GuokrHandpickNewsResult> = LinkedHashMap()
companion object {
private var INSTANCE: GuokrHandpickNewsRepository? = null
fun getInstance(remoteDataSource: GuokrHandpickDataSource, localDataSource: GuokrHandpickDataSource): GuokrHandpickNewsRepository {
if (INSTANCE == null) {
INSTANCE = GuokrHandpickNewsRepository(remoteDataSource, localDataSource)
}
return INSTANCE!!
}
fun destroyInstance() {
INSTANCE = null
}
}
override suspend fun getGuokrHandpickNews(forceUpdate: Boolean, clearCache: Boolean, offset: Int, limit: Int): Result<List<GuokrHandpickNewsResult>> {
if (!forceUpdate) {
return Result.Success(mCachedItems.values.toList())
}
val remoteResult = mRemoteDataSource.getGuokrHandpickNews(false, clearCache, offset, limit)
return if (remoteResult is Result.Success) {
refreshCache(clearCache, remoteResult.data)
saveAll(remoteResult.data)
remoteResult
} else {
mLocalDataSource.getGuokrHandpickNews(false, clearCache, offset, limit).also {
if (it is Result.Success) {
refreshCache(clearCache, it.data)
}
}
}
}
override suspend fun getFavorites(): Result<List<GuokrHandpickNewsResult>> = mLocalDataSource.getFavorites()
override suspend fun getItem(itemId: Int): Result<GuokrHandpickNewsResult> {
val item = getItemWithId(itemId)
if (item != null) {
return Result.Success(item)
}
return mLocalDataSource.getItem(itemId).apply {
if (this is Result.Success) {
mCachedItems[this.data.id] = this.data
}
}
}
override suspend fun favoriteItem(itemId: Int, favorite: Boolean) {
mLocalDataSource.favoriteItem(itemId, favorite)
val cachedItem = getItemWithId(itemId)
if (cachedItem != null) {
cachedItem.isFavorite = favorite
}
}
override suspend fun saveAll(list: List<GuokrHandpickNewsResult>) {
for (item in list) {
item.timestamp = formatGuokrHandpickTimeStringToLong(item.datePublished)
mCachedItems[item.id] = item
}
mLocalDataSource.saveAll(list)
}
private fun refreshCache(clearCache: Boolean, list: List<GuokrHandpickNewsResult>) {
if (clearCache) {
mCachedItems.clear()
}
for (item in list) {
mCachedItems[item.id] = item
}
}
private fun getItemWithId(itemId: Int): GuokrHandpickNewsResult? = if (mCachedItems.isEmpty()) null else mCachedItems[itemId]
}
| apache-2.0 | 6759cc28cdcd05efd023c99891af7888 | 33.95935 | 154 | 0.680465 | 4.931193 | false | false | false | false |
MaTriXy/gradle-play-publisher-1 | play/android-publisher/src/main/kotlin/com/github/triplet/gradle/androidpublisher/EditManager.kt | 1 | 4229 | package com.github.triplet.gradle.androidpublisher
import java.io.File
import java.util.ServiceLoader
/**
* Orchestrates all edit based operations.
*
* For more information on edits, see [here](https://developers.google.com/android-publisher/edits).
*/
interface EditManager {
/** Retrieves the current app details. */
fun getAppDetails(): GppAppDetails
/** Retrieves the current app listings for all languages. */
fun getListings(): List<GppListing>
/** Retrieves the app's graphics for the given [locale] and [type]. */
fun getImages(locale: String, type: String): List<GppImage>
/** Retrieves the highest version code available for this app. */
fun findMaxAppVersionCode(): Long
/** Retrieves the track with the highest version code available for this app. */
fun findLeastStableTrackName(): String?
/** Retrieves the release notes across all tracks for this app. */
fun getReleaseNotes(): List<ReleaseNote>
/** Publish app details, overwriting any existing values. */
fun publishAppDetails(
defaultLocale: String?,
contactEmail: String?,
contactPhone: String?,
contactWebsite: String?
)
/**
* Publish an app listing for the given [locale], overwriting any existing values.
*
* Note: valid locales may be found
* [here](https://support.google.com/googleplay/android-developer/table/4419860?hl=en).
*/
fun publishListing(
locale: String,
title: String?,
shortDescription: String?,
fullDescription: String?,
video: String?
)
/** Publish images for a given [locale] and [type], overwriting any existing values. */
fun publishImages(locale: String, type: String, images: List<File>)
/**
* Promote a release from [fromTrackName] to [promoteTrackName] with the specified update
* params.
*/
fun promoteRelease(
promoteTrackName: String,
fromTrackName: String,
releaseStatus: ReleaseStatus?,
releaseName: String?,
releaseNotes: Map</* locale= */String, /* text= */String?>?,
userFraction: Double?,
updatePriority: Int?,
retainableArtifacts: List<Long>?
)
/** Uploads and publishes the given [bundleFile]. */
fun uploadBundle(
bundleFile: File,
mappingFile: File?,
strategy: ResolutionStrategy,
didPreviousBuildSkipCommit: Boolean,
trackName: String,
releaseStatus: ReleaseStatus?,
releaseName: String?,
releaseNotes: Map</* locale= */String, /* text= */String?>?,
userFraction: Double?,
updatePriority: Int?,
retainableArtifacts: List<Long>?
)
/**
* Uploads the given [apkFile].
*
* Note: since APKs have splits, APK management is a two step process. The APKs must first be
* uploaded and then published using [publishApk].
*/
fun uploadApk(
apkFile: File,
mappingFile: File?,
strategy: ResolutionStrategy,
mainObbRetainable: Int?,
patchObbRetainable: Int?
): Long?
/** Publishes a set of APKs uploaded with [uploadApk]. */
fun publishApk(
versionCodes: List<Long>,
didPreviousBuildSkipCommit: Boolean,
trackName: String,
releaseStatus: ReleaseStatus?,
releaseName: String?,
releaseNotes: Map</* locale= */String, /* text= */String?>?,
userFraction: Double?,
updatePriority: Int?,
retainableArtifacts: List<Long>?
)
/** Basic factory to create [EditManager] instances. */
interface Factory {
/** Creates a new [EditManager]. */
fun create(publisher: PlayPublisher, editId: String): EditManager
}
companion object {
/** Creates a new [EditManager]. */
operator fun invoke(
publisher: PlayPublisher,
editId: String
): EditManager = ServiceLoader.load(Factory::class.java).last()
.create(publisher, editId)
}
}
| mit | a3983eb9fa1b675a025352c933ae8b0f | 32.563492 | 100 | 0.607945 | 4.855339 | false | false | false | false |
justin-hayes/kotlin-boot-react | backend/src/main/kotlin/me/justinhayes/bookclub/service/BookService.kt | 1 | 1094 | package me.justinhayes.bookclub.service
import me.justinhayes.bookclub.client.BookClient
import me.justinhayes.bookclub.domain.Book
import me.justinhayes.bookclub.repository.BookRepository
import me.justinhayes.bookclub.util.toIsbn13
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
interface BookService {
fun getAllBooks(): List<Book>
fun getBookByIsbn(isbn: String): Book
}
@Service
class BookServiceImpl @Autowired constructor(val repository: BookRepository,
val client: BookClient) : BookService {
override fun getAllBooks(): List<Book> = repository.findAll().toList()
override fun getBookByIsbn(isbn: String): Book {
val isbn13 = isbn.toIsbn13()
return repository.findOne(isbn13) ?: repository.save(addCoverToBook(client.getBookByIsbn(isbn13)))
}
private fun addCoverToBook(book: Book): Book {
val coverUrl = client.findCoverForBook(book.isbn);
return if (coverUrl != null) book.copy(coverUrl = coverUrl) else book
}
} | mit | 7079e0643e6bc9e01db1f726a41d018b | 35.5 | 106 | 0.731261 | 3.772414 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/external/service/httpws/HarvestActualHttpWsResponseHandler.kt | 1 | 17042 | package org.evomaster.core.problem.external.service.httpws
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.inject.Inject
import org.evomaster.client.java.instrumentation.shared.PreDefinedSSLInfo
import org.evomaster.core.EMConfig
import org.evomaster.core.Lazy
import org.evomaster.core.logging.LoggingUtil
import org.evomaster.core.problem.external.service.ApiExternalServiceAction
import org.evomaster.core.problem.external.service.httpws.param.HttpWsResponseParam
import org.evomaster.core.problem.external.service.param.ResponseParam
import org.evomaster.core.problem.util.ParamUtil
import org.evomaster.core.problem.util.ParserDtoUtil
import org.evomaster.core.problem.util.ParserDtoUtil.getJsonNodeFromText
import org.evomaster.core.problem.util.ParserDtoUtil.parseJsonNodeAsGene
import org.evomaster.core.problem.util.ParserDtoUtil.setGeneBasedOnString
import org.evomaster.core.problem.util.ParserDtoUtil.wrapWithOptionalGene
import org.evomaster.core.remote.TcpUtils
import org.evomaster.core.remote.service.RemoteController
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.collection.EnumGene
import org.evomaster.core.search.gene.optional.OptionalGene
import org.evomaster.core.search.gene.string.StringGene
import org.evomaster.core.search.service.Randomness
import org.glassfish.jersey.client.ClientConfig
import org.glassfish.jersey.client.ClientProperties
import org.glassfish.jersey.client.HttpUrlConnectorProvider
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.concurrent.ConcurrentLinkedQueue
import javax.annotation.PostConstruct
import javax.annotation.PreDestroy
import javax.ws.rs.ProcessingException
import javax.ws.rs.client.Client
import javax.ws.rs.client.ClientBuilder
import javax.ws.rs.client.Entity
import javax.ws.rs.client.Invocation
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
import kotlin.math.max
/**
* based on collected requests to external services from WireMock
* harvest actual responses by making the requests to real external services
*
* harvested actual responses could be applied as seeded in optimizing
* test generation with search
*/
class HarvestActualHttpWsResponseHandler {
// note rc should never be used in the thread of sending requests to external services
@Inject(optional = true)
private lateinit var rc: RemoteController
@Inject
private lateinit var config: EMConfig
@Inject
private lateinit var randomness: Randomness
private lateinit var httpWsClient : Client
/**
* TODO
* to further improve the efficiency of collecting actual responses,
* might have a pool of threads to send requests
*/
private lateinit var threadToHandleRequest: Thread
companion object {
private val log: Logger = LoggerFactory.getLogger(HarvestActualHttpWsResponseHandler::class.java)
private const val ACTUAL_RESPONSE_GENE_NAME = "ActualResponse"
init{
/**
* this default setting in jersey-client is false
* to allow collected requests which might have restricted headers, then
* set the property
*/
System.setProperty("sun.net.http.allowRestrictedHeaders", "true")
}
}
/**
* save the harvested actual responses
*
* key is actual request based on [HttpExternalServiceRequest.getDescription]
* ie, "method:absoluteURL[headers]{body payload}",
* value is an actual response info
*/
private val actualResponses = mutableMapOf<String, ActualResponseInfo>()
/**
* cache collected requests
*
* key is description of request with [HttpExternalServiceRequest.getDescription]
* ie, "method:absoluteURL[headers]{body payload}",
* value is an example of HttpExternalServiceRequest
*/
private val cachedRequests = mutableMapOf<String, HttpExternalServiceRequest>()
/**
* track a list of actual responses which have been seeded in the search based on
* its corresponding request using its description, ie, ie, "method:absoluteURL[headers]{body payload}",
*/
private val seededResponses = mutableSetOf<String>()
/**
* need it for wait and notify in kotlin
*/
private val lock = Object()
/**
* an queue for handling urls for
*/
private val queue = ConcurrentLinkedQueue<String>()
/**
* key is dto class name
* value is parsed gene based on schema
*/
private val extractedObjectDto = mutableMapOf<String, Gene>()
/*
skip headers if they depend on the client
shall we skip Connection?
*/
private val skipHeaders = listOf("user-agent","host","accept-encoding")
@PostConstruct
fun initialize() {
if (config.doHarvestActualResponse()){
val clientConfiguration = ClientConfig()
.property(ClientProperties.CONNECT_TIMEOUT, 10_000)
.property(ClientProperties.READ_TIMEOUT, config.tcpTimeoutMs)
//workaround bug in Jersey client
.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true)
.property(ClientProperties.FOLLOW_REDIRECTS, false)
httpWsClient = ClientBuilder.newBuilder()
.sslContext(PreDefinedSSLInfo.getSSLContext()) // configure ssl certificate
.hostnameVerifier(PreDefinedSSLInfo.allowAllHostNames()) // configure all hostnames
.withConfig(clientConfiguration).build()
threadToHandleRequest = object :Thread() {
override fun run() {
while (!this.isInterrupted) {
sendRequestToRealExternalService()
}
}
}
threadToHandleRequest.start()
}
}
@PreDestroy
private fun preDestroy() {
if (config.doHarvestActualResponse()){
shutdown()
}
}
fun shutdown(){
Lazy.assert { config.doHarvestActualResponse() }
synchronized(lock){
if (threadToHandleRequest.isAlive)
threadToHandleRequest.interrupt()
httpWsClient.close()
}
}
@Synchronized
private fun sendRequestToRealExternalService() {
synchronized(lock){
while (queue.size == 0) {
lock.wait()
}
val first = queue.remove()
val info = handleActualResponse(createInvocationToRealExternalService(cachedRequests[first]?:throw IllegalStateException("Fail to get Http request with description $first")))
if (info != null){
info.param.responseBody.markAllAsInitialized()
actualResponses[first] = info
}else
LoggingUtil.uniqueWarn(log, "Fail to harvest actual responses from GET $first")
}
}
/**
* @return a copy of gene of actual responses based on the given [gene] and probability
*
* note that this method is used in mutation phase to mutate the given [gene] based on actual response if it exists
* and based on the given [probability]
*
* the given [gene] should be the response body gene of ResponseParam
*/
fun getACopyOfItsActualResponseIfExist(gene: Gene, probability : Double) : ResponseParam?{
if (probability == 0.0) return null
val exAction = gene.getFirstParent { it is ApiExternalServiceAction }?:return null
// only support HttpExternalServiceAction, TODO for others
if (exAction is HttpExternalServiceAction ){
Lazy.assert { gene.parent == exAction.response}
if (exAction.response.responseBody == gene){
val p = if (!seededResponses.contains(exAction.request.getDescription()) && actualResponses.containsKey(exAction.request.getDescription())){
// if the actual response is never seeded, give a higher probably to employ it
max(config.probOfHarvestingResponsesFromActualExternalServices, probability)
} else probability
if (randomness.nextBoolean(p))
return getACopyOfActualResponse(exAction.request)
}
}
return null
}
/**
* @return a copy of actual responses based on the given [httpRequest] and probability
*/
fun getACopyOfActualResponse(httpRequest: HttpExternalServiceRequest, probability: Double?=null) : ResponseParam?{
val harvest = probability == null || (randomness.nextBoolean(probability))
if (!harvest) return null
synchronized(actualResponses){
val found= (actualResponses[httpRequest.getDescription()]?.param?.copy() as? ResponseParam)
if (found!=null) seededResponses.add(httpRequest.getDescription())
return found
}
}
/**
* add http request to queue for sending them to real external services
*/
fun addHttpRequests(requests: List<HttpExternalServiceRequest>){
if (requests.isEmpty()) return
if (!config.doHarvestActualResponse())
return
// only harvest responses with GET method
//val filter = requests.filter { it.method.equals("GET", ignoreCase = true) }
synchronized(cachedRequests){
requests.forEach { cachedRequests.putIfAbsent(it.getDescription(), it) }
}
addRequests(requests.map { it.getDescription() })
}
private fun addRequests(requests : List<String>) {
if (requests.isEmpty()) return
val notInCollected = requests.filterNot { actualResponses.containsKey(it) }.distinct()
if (notInCollected.isEmpty()) return
synchronized(lock){
val newRequests = notInCollected.filterNot { queue.contains(it) }
if (newRequests.isEmpty())
return
updateExtractedObjectDto()
lock.notify()
queue.addAll(newRequests)
}
}
private fun buildInvocation(httpRequest : HttpExternalServiceRequest) : Invocation{
val build = httpWsClient.target(httpRequest.actualAbsoluteURL).request("*/*").apply {
val handledHeaders = httpRequest.headers.filterNot { skipHeaders.contains(it.key.lowercase()) }
if (handledHeaders.isNotEmpty())
handledHeaders.forEach { (t, u) -> this.header(t, u) }
}
val bodyEntity = if (httpRequest.body != null) {
val contentType = httpRequest.getContentType()
if (contentType !=null )
Entity.entity(httpRequest.body, contentType)
else
Entity.entity(httpRequest.body, MediaType.APPLICATION_FORM_URLENCODED_TYPE)
} else {
null
}
return when{
httpRequest.method.equals("GET", ignoreCase = true) -> build.buildGet()
httpRequest.method.equals("POST", ignoreCase = true) -> build.buildPost(bodyEntity)
httpRequest.method.equals("PUT", ignoreCase = true) -> build.buildPut(bodyEntity)
httpRequest.method.equals("DELETE", ignoreCase = true) -> build.buildDelete()
httpRequest.method.equals("PATCH", ignoreCase = true) -> build.build("PATCH", bodyEntity)
httpRequest.method.equals("OPTIONS", ignoreCase = true) -> build.build("OPTIONS")
httpRequest.method.equals("HEAD", ignoreCase = true) -> build.build("HEAD")
httpRequest.method.equals("TRACE", ignoreCase = true) -> build.build("TRACE")
else -> {
throw IllegalStateException("NOT SUPPORT to create invocation for method ${httpRequest.method}")
}
}
}
private fun createInvocationToRealExternalService(httpRequest : HttpExternalServiceRequest) : Response?{
return try {
buildInvocation(httpRequest).invoke()
} catch (e: ProcessingException) {
log.debug("There has been an issue in accessing external service with url (${httpRequest.getDescription()}): {}", e)
when {
TcpUtils.isTooManyRedirections(e) -> {
return null
}
TcpUtils.isTimeout(e) -> {
return null
}
TcpUtils.isOutOfEphemeralPorts(e) -> {
httpWsClient.close() //make sure to release any resource
httpWsClient = ClientBuilder.newClient()
TcpUtils.handleEphemeralPortIssue()
createInvocationToRealExternalService(httpRequest)
}
TcpUtils.isStreamClosed(e) || TcpUtils.isEndOfFile(e) -> {
log.warn("TCP connection to Real External Service: ${e.cause!!.message}")
return null
}
TcpUtils.isRefusedConnection(e) -> {
log.warn("Failed to connect Real External Service with TCP with url ($httpRequest).")
return null
}
else -> throw e
}
}
}
private fun handleActualResponse(response: Response?) : ActualResponseInfo? {
response?:return null
val status = response.status
var statusGene = HttpWsResponseParam.getDefaultStatusEnumGene()
if (!statusGene.values.contains(status))
statusGene = EnumGene(name = statusGene.name, statusGene.values.plus(status))
val body = response.readEntity(String::class.java)
val node = getJsonNodeFromText(body)
val responseParam = if(node != null){
getHttpResponse(node, statusGene).apply {
setGeneBasedOnString(responseBody, body)
}
}else{
HttpWsResponseParam(status = statusGene, responseBody = OptionalGene(ACTUAL_RESPONSE_GENE_NAME, StringGene(ACTUAL_RESPONSE_GENE_NAME, value = body)))
}
(responseParam as HttpWsResponseParam).setStatus(status)
return ActualResponseInfo(body, responseParam)
}
private fun getHttpResponse(node: JsonNode, statusGene: EnumGene<Int>) : ResponseParam{
synchronized(extractedObjectDto){
val found = if (extractedObjectDto.isEmpty()) null else parseJsonNodeAsGene(ACTUAL_RESPONSE_GENE_NAME, node, extractedObjectDto)
return if (found != null)
HttpWsResponseParam(status= statusGene, responseBody = OptionalGene(ACTUAL_RESPONSE_GENE_NAME, found))
else {
val parsed = parseJsonNodeAsGene(ACTUAL_RESPONSE_GENE_NAME, node)
HttpWsResponseParam(status= statusGene, responseBody = wrapWithOptionalGene(parsed, true) as OptionalGene)
}
}
}
private fun updateExtractedObjectDto(){
synchronized(extractedObjectDto){
val infoDto = rc.getSutInfo()!!
val map = ParserDtoUtil.getOrParseDtoWithSutInfo(infoDto)
if (map.isNotEmpty()){
map.forEach { (t, u) ->
extractedObjectDto.putIfAbsent(t, u)
}
}
}
}
/**
* harvest the existing action [externalServiceAction] with collected actual responses only if the actual response for the action exists, and it is never seeded
*/
fun harvestExistingExternalActionIfNeverSeeded(externalServiceAction: HttpExternalServiceAction, probability: Double) : Boolean{
if (!seededResponses.contains(externalServiceAction.request.getDescription())
&& actualResponses.containsKey(externalServiceAction.request.getDescription())){
return harvestExistingGeneBasedOn(externalServiceAction.response.responseBody, probability)
}
return false
}
/**
* harvest the existing mocked response with collected actual responses
*/
fun harvestExistingGeneBasedOn(geneToMutate: Gene, probability: Double) : Boolean{
try {
val template = getACopyOfItsActualResponseIfExist(geneToMutate, probability)?.responseBody?:return false
val v = ParamUtil.getValueGene(geneToMutate)
val t = ParamUtil.getValueGene(template)
if (v::class.java == t::class.java){
v.copyValueFrom(t)
return true
}else if (v is StringGene){
// add template as part of specialization
v.addChild(t)
v.selectedSpecialization = v.specializationGenes.indexOf(t)
return true
}
LoggingUtil.uniqueWarn(log, "Fail to mutate gene (${geneToMutate::class.java.name}) based on a given gene (${template::class.java.name})")
return false
}catch (e: Exception){
LoggingUtil.uniqueWarn(log, "Fail to mutate gene based on a given gene and an exception (${e.message}) is thrown")
return false
}
}
} | lgpl-3.0 | 03843a530b36843aa37a7c6008aaa220 | 39.29078 | 186 | 0.653327 | 4.877504 | false | false | false | false |
DR-YangLong/spring-boot-kotlin-demo | src/main/kotlin/site/yanglong/promotion/model/Resources.kt | 1 | 1146 | package site.yanglong.promotion.model
import java.io.Serializable
import com.baomidou.mybatisplus.enums.IdType
import com.baomidou.mybatisplus.annotations.TableId
import com.baomidou.mybatisplus.activerecord.Model
import com.baomidou.mybatisplus.annotations.TableField
import com.baomidou.mybatisplus.annotations.TableLogic
/**
*
*
*
*
*
* @author Dr.YangLong
* @since 2017-11-01
*/
class Resources : Model<Resources>() {
/**
* 资源id
*/
@TableId(value = "id", type = IdType.AUTO)
var id: Long? = null
/**
* 资源标识
*/
var uri: String? = null
/**
* 资源名称
*/
var name: String? = null
/**
* 是否启用
*/
@TableField
@TableLogic
var enable: String? = null
override fun pkVal(): Serializable? {
return this.id
}
override fun toString(): String {
return "Resources{" +
", id=" + id +
", uri=" + uri +
", name=" + name +
", enable=" + enable +
"}"
}
companion object {
private val serialVersionUID = 1L
}
}
| apache-2.0 | 940c83ab356feec828be2f11c9521545 | 17.949153 | 54 | 0.55814 | 3.868512 | false | false | false | false |
kangsLee/sh8email-kotlin | app/src/main/kotlin/org/triplepy/sh8email/sh8/utils/LogAppEventUtil.kt | 1 | 653 | package org.triplepy.sh8email.sh8.utils
import com.crashlytics.android.answers.Answers
import com.crashlytics.android.answers.LoginEvent
/**
* The sh8email-android Project.
* ==============================
* org.triplepy.sh8email.sh8.utils
* ==============================
* Created by igangsan on 2016. 9. 1..
*/
object LogAppEventUtil {
fun eventLogin(method: String, isLoginSucceeded: Boolean, responseCode: Int = 200) {
Answers.getInstance().logLogin(LoginEvent()
.putMethod(method)
.putSuccess(isLoginSucceeded)
.putCustomAttribute("responseCode", responseCode)
)
}
} | apache-2.0 | 041463b6cc2bcaf559958a6d963362ce | 28.727273 | 88 | 0.61562 | 4.030864 | false | false | false | false |
matthieucoisne/LeagueChampions | features/champions/src/main/java/com/leaguechampions/features/champions/presentation/championdetails/ChampionDetailsFragment.kt | 1 | 2535 | package com.leaguechampions.features.champions.presentation.championdetails
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.leaguechampions.features.champions.databinding.FragmentChampionDetailsBinding
import com.leaguechampions.libraries.core.data.local.Const
import com.leaguechampions.libraries.core.injection.ViewModelFactory
import com.leaguechampions.libraries.core.utils.loadChampionImage
import dagger.android.support.DaggerFragment
import javax.inject.Inject
class ChampionDetailsFragment : DaggerFragment() {
private lateinit var binding: FragmentChampionDetailsBinding
private lateinit var viewModel: ChampionDetailsViewModel
@Inject
lateinit var viewModelFactory: ViewModelFactory
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentChampionDetailsBinding.inflate(inflater, container, false)
viewModel = ViewModelProvider(this, viewModelFactory).get(ChampionDetailsViewModel::class.java)
viewModel.viewState.observe(viewLifecycleOwner, Observer {
render(it)
})
val championId = requireArguments().getString(Const.KEY_CHAMPION_ID)
viewModel.setChampionId(championId)
return binding.root
}
private fun render(viewState: ChampionDetailsViewModel.ViewState) {
when (viewState) {
is ChampionDetailsViewModel.ViewState.ShowLoading -> {
showToast("Loading")
viewState.championDetails?.let { showChampionDetails(it) }
}
is ChampionDetailsViewModel.ViewState.ShowChampionDetails -> showChampionDetails(viewState.championDetails)
is ChampionDetailsViewModel.ViewState.ShowError -> showError(getString(viewState.errorStringId))
}
}
private fun showChampionDetails(championDetails: ChampionDetailsUiModel) {
binding.tvName.text = championDetails.name
binding.tvLore.text = championDetails.lore
loadChampionImage(binding.ivChampion, championDetails.id, championDetails.version)
}
private fun showError(message: String) {
showToast(message, Toast.LENGTH_LONG)
}
private fun showToast(message: String, length: Int = Toast.LENGTH_SHORT) {
Toast.makeText(requireActivity(), message, length).show()
}
}
| apache-2.0 | 4eda674ebe9727009ad8cb4c6bed9993 | 38 | 119 | 0.756607 | 5.07 | false | false | false | false |
manami-project/manami | manami-gui/src/main/kotlin/io/github/manamiproject/manami/gui/relatedanime/RelatedAnimeView.kt | 1 | 3184 | package io.github.manamiproject.manami.gui.relatedanime
import io.github.manamiproject.manami.app.lists.Link
import io.github.manamiproject.manami.gui.*
import io.github.manamiproject.manami.gui.components.animeTable
import io.github.manamiproject.manami.gui.components.simpleServiceStart
import io.github.manamiproject.manami.gui.events.*
import javafx.beans.property.ObjectProperty
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleIntegerProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.scene.layout.Priority.ALWAYS
import tornadofx.*
class RelatedAnimeView : View() {
private val manamiAccess: ManamiAccess by inject()
private val finishedTasks: SimpleIntegerProperty = SimpleIntegerProperty(0)
private val tasks: SimpleIntegerProperty = SimpleIntegerProperty(0)
private val isRelatedAnimeProgressIndicatorVisible = SimpleBooleanProperty(false)
private val entries: ObjectProperty<ObservableList<BigPicturedAnimeEntry>> = SimpleObjectProperty(
FXCollections.observableArrayList()
)
init {
subscribe<AnimeListRelatedAnimeFoundGuiEvent> { event ->
entries.value.add(BigPicturedAnimeEntry(event.anime))
}
subscribe<AnimeListRelatedAnimeStatusGuiEvent> { event ->
finishedTasks.set(event.finishedChecking)
tasks.set(event.toBeChecked)
if (event.finishedChecking == 1) {
entries.get().clear()
}
}
subscribe<AnimeListRelatedAnimeFinishedGuiEvent> {
isRelatedAnimeProgressIndicatorVisible.set(false)
}
subscribe<AddAnimeListEntryGuiEvent> { event ->
val uris = event.entries.map { it.link }.filterIsInstance<Link>().map { it.uri }.toSet()
entries.get().removeIf { uris.contains(it.link.uri) }
}
subscribe<AddWatchListEntryGuiEvent> { event ->
val uris = event.entries.map { it.link }.map { it.uri }.toSet()
entries.get().removeIf { uris.contains(it.link.uri) }
}
subscribe<AddIgnoreListEntryGuiEvent> { event ->
val uris = event.entries.map { it.link }.map { it.uri }.toSet()
entries.get().removeIf { uris.contains(it.link.uri) }
}
subscribe<FileOpenedGuiEvent> {
entries.get().clear()
}
}
override val root = pane {
vbox {
vgrow = ALWAYS
hgrow = ALWAYS
fitToParentSize()
simpleServiceStart {
finishedTasksProperty.bindBidirectional(finishedTasks)
numberOfTasksProperty.bindBidirectional(tasks)
progressIndicatorVisibleProperty.bindBidirectional(isRelatedAnimeProgressIndicatorVisible)
onStart = {
entries.get().clear()
manamiAccess.findRelatedAnimeForAnimeList()
}
}
animeTable<BigPicturedAnimeEntry> {
manamiApp = manamiAccess
items = entries
}
}
}
} | agpl-3.0 | d4367336bd8e07dc5c129e63de3e9847 | 37.373494 | 106 | 0.665829 | 4.91358 | false | false | false | false |
pardom/navigator | navigator/src/main/kotlin/navigator/route/AbsRoute.kt | 1 | 508 | package navigator.route
import kotlinx.coroutines.experimental.CompletableDeferred
import navigator.Navigator
import navigator.Overlay
import navigator.Route
abstract class AbsRoute<T> : Route<T> {
override var navigator: Navigator? = null
override val overlayEntries: MutableList<Overlay.Entry> = mutableListOf()
override val popped: CompletableDeferred<Any?> = CompletableDeferred()
override val currentResult: T? = null
override val willHandlePopInternally: Boolean = false
}
| apache-2.0 | d04599f6443fc9cd6c727db3d4717f0f | 23.190476 | 77 | 0.779528 | 4.838095 | false | false | false | false |
weisterjie/FamilyLedger | app/src/main/java/ycj/com/familyledger/ui/KHomeActivity.kt | 1 | 9225 | package ycj.com.familyledger.ui
import android.content.Intent
import android.os.SystemClock
import android.support.design.widget.FloatingActionButton
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.Gravity
import android.view.View
import android.widget.TextView
import org.jetbrains.anko.*
import org.jetbrains.anko.design.floatingActionButton
import org.jetbrains.anko.recyclerview.v7.recyclerView
import ycj.com.familyledger.Consts
import ycj.com.familyledger.R
import ycj.com.familyledger.adapter.KHomeAdapter
import ycj.com.familyledger.bean.BaseResponse
import ycj.com.familyledger.bean.LedgerBean
import ycj.com.familyledger.bean.PageResult
import ycj.com.familyledger.http.HttpUtils
import ycj.com.familyledger.impl.BaseCallBack
import ycj.com.familyledger.impl.IGetLedgerList
import ycj.com.familyledger.utils.RecyclerViewItemDiv
import ycj.com.familyledger.utils.SPUtils
import ycj.com.familyledger.view.EdxDialog
import java.util.*
class KHomeActivity : KBaseActivity(),
KHomeAdapter.ItemClickListener,
EdxDialog.DataCallBack,
View.OnClickListener, IGetLedgerList {
private var trigleCancel: Long = 0
private var selfData: Boolean = true
private var lView: RecyclerView? = null
private var data: ArrayList<LedgerBean> = ArrayList()
private var fBtn: FloatingActionButton? = null
private var mAdapter: KHomeAdapter? = null
override fun initialize() {
showLoading()
HttpUtils.getInstance().getLedgerList(0, 1, 1000, this)
}
override fun initListener() {
leftLayout?.setOnClickListener(this)
splitLayout?.setOnClickListener(this)
mAdapter?.setOnItemClickListener(this)
fBtn?.setOnClickListener(this)
lView?.setOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (lView?.scrollState == RecyclerView.SCROLL_STATE_DRAGGING) {
if (dy > 0) {
fBtn?.hide()
} else {
fBtn?.show()
}
}
}
override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
android.util.Log.i("ycj ScrollChanged", "" + newState)
//==1,显示
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
fBtn?.show()
}
}
})
}
//输入框返回
override fun callBack(dates: String, cashs: String) {
val userId = SPUtils.getInstance().getLong(Consts.SP_USER_ID)
HttpUtils.getInstance().addLedger(userId, dates, cashs, object : BaseCallBack<String> {
override fun onSuccess(data: BaseResponse<String>) {
hideLoading()
if (data.result == 1) {
toast(data.data)
initialize()
} else {
toast(data.error.message)
}
}
override fun onFail(msg: String) {
toast(msg)
}
})
}
override fun onItemClickListener(position: Int) {
go2Detail(position)
}
override fun onItemLongClickListener(position: Int) {
showTips(getString(R.string.sure_delete), object : OnTipsCallBack {
override fun positiveClick() {
HttpUtils.getInstance().deleteLedger(data[position].id!!, object : BaseCallBack<String> {
override fun onSuccess(data: BaseResponse<String>) {
if (data.result == 1) {
toast(getString(R.string.success_delete))
[email protected](position)
mAdapter?.notifyDataSetChanged()
} else {
toast(data.error.message)
}
}
override fun onFail(msg: String) {
toast(getString(R.string.fail_delete))
}
})
}
})
}
override fun onClick(v: android.view.View?) {
when (v?.id) {
R.id.layout_left_title_home -> {
go2Calculate()
}
R.id.layout_split -> {
showLoading()
val userId = SPUtils.getInstance().getLong(Consts.SP_USER_ID)
HttpUtils.getInstance().getLedgerList(if (selfData) userId else 0,
1, 1000, this)
selfData = !selfData
}
R.id.btn_home_add -> EdxDialog.Companion.create()
.showEdxDialog("请输入信息", this@KHomeActivity,
this@KHomeActivity)
}
}
override fun onSuccess(pages: PageResult<LedgerBean>) {
hideLoading()
mAdapter?.setDatas(pages.list)
}
override fun onFail(msg: String) {
hideLoading()
mAdapter?.clearData()
toast("获取失败")
}
private fun go2Detail(position: Int) {
val intent = android.content.Intent(KHomeActivity@ this, KLedgerDetailActivity::class.java)
intent.putExtra(Consts.DATA_ID, position)
intent.putExtra(Consts.DATA_BEAN, data[position])
startActivityForResult(intent, 100)
}
private fun go2Calculate() {
val intent = android.content.Intent(KHomeActivity@ this, KCalculateActivity::class.java)
intent.putExtra(Consts.LIST_DATA, data)
startActivity(intent)
}
private var splitLayout: TextView? = null
private var leftLayout: TextView? = null
override fun initView() {
relativeLayout {
lparams(height = matchParent, width = matchParent)
relativeLayout {
id = R.id.layout_title
backgroundResource = R.color.color_title_bar
textView("Ledger") {
textSize = resources.getDimension(R.dimen.title_size)
textColor = resources.getColor(R.color.white)
}.lparams(height = wrapContent, width = wrapContent) {
centerInParent()
}
splitLayout = textView("筛选") {
id = R.id.layout_split
gravity = Gravity.CENTER
textColor = resources.getColor(R.color.white)
backgroundResource = R.drawable.bg_btn
}.lparams(width = dip(48), height = matchParent) {
centerInParent()
alignParentRight()
}
leftLayout = textView("结账") {
id = R.id.layout_left_title_home
gravity = Gravity.CENTER
textColor = resources.getColor(R.color.white)
backgroundResource = R.drawable.bg_btn
}.lparams(width = dip(48), height = matchParent)
}.lparams(height = dip(48), width = matchParent)
lView = recyclerView {
id = R.id.list_view_home
}.lparams(width = matchParent, height = matchParent) { below(R.id.layout_title) }
fBtn = floatingActionButton {
id = R.id.btn_home_add
imageResource = android.R.drawable.ic_menu_add
}.lparams(width = wrapContent, height = wrapContent) {
alignParentRight()
alignParentBottom()
bottomMargin = dip(20)
rightMargin = dip(20)
}
}
mAdapter = KHomeAdapter(data, this)
//分割线
lView?.addItemDecoration(RecyclerViewItemDiv(this@KHomeActivity, LinearLayoutManager.VERTICAL))
lView?.adapter = mAdapter
lView?.layoutManager = LinearLayoutManager(this@KHomeActivity)
//滑动监听
lView?.overScrollMode = android.view.View.OVER_SCROLL_NEVER
lView?.itemAnimator = DefaultItemAnimator() as RecyclerView.ItemAnimator?//设置Item增加、移除动画
// val callBack = RItemTouchHelper(mAdapter!!)
// val helpers = ItemTouchHelper(callBack)
// helpers.attachToRecyclerView(lView)
}
//按后退键时
override fun onBackPressed() {
toastExtrance() // “提示再按一次可退出..”
}
//双击退出提醒
fun toastExtrance() {
val uptimeMillis = SystemClock.uptimeMillis()
if (uptimeMillis - trigleCancel > 2000) {
trigleCancel = uptimeMillis
toast(getString(R.string.note_exit))
} else {
finish()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Consts.ACTIVITY_RESULT_REFRESH) {
initialize()
}
}
} | apache-2.0 | d556f319bdfcdb314d8831984858bee3 | 34.447471 | 105 | 0.581074 | 4.764121 | false | false | false | false |
kotlintest/kotlintest | kotest-extensions/src/jvmTest/kotlin/com/sksamuel/kt/extensions/system/SystemEnvironmentExtensionTest.kt | 1 | 2875 | package com.sksamuel.kt.extensions.system
import io.kotest.core.listeners.TestListener
import io.kotest.core.test.TestCase
import io.kotest.core.test.TestResult
import io.kotest.core.spec.Spec
import io.kotest.core.spec.style.FreeSpec
import io.kotest.core.spec.style.FreeSpecScope
import io.kotest.core.spec.style.WordSpec
import io.kotest.extensions.system.OverrideMode
import io.kotest.extensions.system.SystemEnvironmentTestListener
import io.kotest.extensions.system.withEnvironment
import io.kotest.inspectors.forAll
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import io.mockk.every
import io.mockk.mockk
import kotlin.reflect.KClass
class SystemEnvironmentExtensionTest : FreeSpec() {
private val key = "SystemEnvironmentExtensionTestFoo"
private val value = "SystemEnvironmentExtensionTestBar"
private val mode: OverrideMode = mockk {
every { override(any(), any()) } answers {
firstArg<Map<String, String>>().plus(secondArg<Map<String, String>>()).toMutableMap()
}
}
init {
"Should set environment to specific map" - {
executeOnAllEnvironmentOverloads {
System.getenv(key) shouldBe value
}
}
"Should return original environment to its place after execution" - {
val before = System.getenv().toMap()
executeOnAllEnvironmentOverloads {
System.getenv() shouldNotBe before
}
System.getenv() shouldBe before
}
"Should return the computed value" - {
val results = executeOnAllEnvironmentOverloads { "RETURNED" }
results.forAll {
it shouldBe "RETURNED"
}
}
}
private suspend fun <T> FreeSpecScope.executeOnAllEnvironmentOverloads(block: suspend () -> T): List<T> {
val results = mutableListOf<T>()
"String String overload" {
results += withEnvironment(key, value, mode) { block() }
}
"Pair overload" {
results += withEnvironment(key to value, mode) { block() }
}
"Map overload" {
results += withEnvironment(mapOf(key to value), mode) { block() }
}
return results
}
}
class SystemEnvironmentTestListenerTest : WordSpec() {
override fun listeners() =
listOf(SystemEnvironmentTestListener("mop", "dop", mode = OverrideMode.SetOrOverride), listener)
private val listener = object : TestListener {
override suspend fun prepareSpec(kclass: KClass<out Spec>) {
System.getenv("mop") shouldBe null
}
override suspend fun finalizeSpec(kclass: KClass<out Spec>, results: Map<TestCase, TestResult>) {
System.getenv("mop") shouldBe null
}
}
init {
"sys environment extension" should {
"set environment variable" {
System.getenv("mop") shouldBe "dop"
}
}
}
}
| apache-2.0 | 346704ae4f0e0d6ec8958e206f1ca322 | 28.040404 | 108 | 0.671652 | 4.389313 | false | true | false | false |
cliffano/swaggy-jenkins | clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/BranchImplpermissions.kt | 1 | 1272 | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
*
* @param create
* @param read
* @param start
* @param stop
* @param propertyClass
*/
data class BranchImplpermissions(
@Schema(example = "null", description = "")
@field:JsonProperty("create") val create: kotlin.Boolean? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("read") val read: kotlin.Boolean? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("start") val start: kotlin.Boolean? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("stop") val stop: kotlin.Boolean? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("_class") val propertyClass: kotlin.String? = null
) {
}
| mit | f053028cc7a92768cf768c6b4d3ddcea | 28.581395 | 74 | 0.735063 | 4.038095 | false | false | false | false |
Bombe/Sone | src/main/kotlin/net/pterodactylus/sone/text/SoneTextParser.kt | 1 | 7803 | package net.pterodactylus.sone.text
import freenet.keys.*
import net.pterodactylus.sone.data.*
import net.pterodactylus.sone.data.impl.*
import net.pterodactylus.sone.database.*
import net.pterodactylus.sone.text.LinkType.*
import net.pterodactylus.sone.text.LinkType.USK
import net.pterodactylus.sone.utils.*
import org.bitpedia.util.*
import java.net.*
import javax.inject.*
/**
* [Parser] implementation that can recognize Freenet URIs.
*/
class SoneTextParser @Inject constructor(private val soneProvider: SoneProvider?, private val postProvider: PostProvider?) {
fun parse(source: String, context: SoneTextParserContext?) =
source.split("\n")
.dropWhile { it.trim() == "" }
.dropLastWhile { it.trim() == "" }
.mergeMultipleEmptyLines()
.flatMap { splitLineIntoParts(it, context) }
.removeEmptyPlainTextParts()
.mergeAdjacentPlainTextParts()
private fun splitLineIntoParts(line: String, context: SoneTextParserContext?) =
generateSequence(PlainTextPart("") as Part to line) { remainder ->
if (remainder.second == "")
null
else
LinkType.values()
.mapNotNull { it.findNext(remainder.second) }
.minBy { it.position }
.let {
when {
it == null -> PlainTextPart(remainder.second) to ""
it.position == 0 -> it.toPart(context) to it.remainder
else -> PlainTextPart(remainder.second.substring(0, it.position)) to (it.link + it.remainder)
}
}
}.map { it.first }.toList()
private val NextLink.linkWithoutBacklink: String
get() {
val backlink = link.indexOf("/../")
val query = link.indexOf("?")
return if ((backlink > -1) && ((query == -1) || (query > -1) && (backlink < query)))
link.substring(0, backlink)
else
link
}
private fun NextLink.toPart(context: SoneTextParserContext?) = when (linkType) {
KSK, CHK -> try {
FreenetURI(linkWithoutBacklink).let { freenetUri ->
FreenetLinkPart(
linkWithoutBacklink,
freenetUri.allMetaStrings?.lastOrNull { it != "" } ?: freenetUri.docName ?: linkWithoutBacklink.substring(0, 9),
linkWithoutBacklink.split('?').first()
)
}
} catch (e: MalformedURLException) {
PlainTextPart(linkWithoutBacklink)
}
SSK, USK ->
try {
FreenetURI(linkWithoutBacklink).let { uri ->
uri.allMetaStrings
?.takeIf { (it.size > 1) || ((it.size == 1) && (it.single() != "")) }
?.lastOrNull()
?: uri.docName
?: "${uri.keyType}@${uri.routingKey.asFreenetBase64}"
}.let { FreenetLinkPart(linkWithoutBacklink.removeSuffix("/"), it, trusted = context?.routingKey?.contentEquals(FreenetURI(linkWithoutBacklink).routingKey) == true) }
} catch (e: MalformedURLException) {
PlainTextPart(linkWithoutBacklink)
}
SONE -> link.substring(7).let { SonePart(soneProvider?.getSone(it) ?: IdOnlySone(it)) }
POST -> postProvider?.getPost(link.substring(7))?.let { PostPart(it) } ?: PlainTextPart(link)
FREEMAIL -> link.indexOf('@').let { atSign ->
link.substring(atSign + 1, link.length - 9).let { freemailId ->
FreemailPart(link.substring(0, atSign), freemailId, freemailId.decodedId)
}
}
HTTP, HTTPS -> LinkPart(link, link
.withoutProtocol
.withoutWwwPrefix
.withoutUrlParameters
.withoutMiddlePathComponents
.withoutTrailingSlash)
}
}
private fun List<String>.mergeMultipleEmptyLines() = fold(emptyList<String>()) { previous, current ->
if (previous.isEmpty()) {
previous + current
} else {
if ((previous.last() == "\n") && (current == "")) {
previous
} else {
previous + ("\n" + current)
}
}
}
private fun List<Part>.mergeAdjacentPlainTextParts() = fold(emptyList<Part>()) { parts, part ->
if ((parts.lastOrNull() is PlainTextPart) && (part is PlainTextPart)) {
parts.dropLast(1) + PlainTextPart(parts.last().text + part.text)
} else {
parts + part
}
}
private fun List<Part>.removeEmptyPlainTextParts() = filterNot { it == PlainTextPart("") }
private val String.decodedId: String get() = Base32.decode(this).asFreenetBase64
private val String.withoutProtocol get() = substring(indexOf("//") + 2)
private val String.withoutUrlParameters get() = split('?').first()
private val String.withoutWwwPrefix
get() = split("/")
.replaceFirst { it.split(".").dropWhile { it == "www" }.joinToString(".") }
.joinToString("/")
private fun <T> List<T>.replaceFirst(replacement: (T) -> T) = mapIndexed { index, element ->
if (index == 0) replacement(element) else element
}
private val String.withoutMiddlePathComponents
get() = split("/").let {
if (it.size > 2) {
"${it.first()}/…/${it.last()}"
} else {
it.joinToString("/")
}
}
private val String.withoutTrailingSlash get() = if (endsWith("/")) substring(0, length - 1) else this
private val SoneTextParserContext.routingKey: ByteArray? get() = postingSone?.routingKey
private val Sone.routingKey: ByteArray get() = id.fromFreenetBase64
private enum class LinkType(private val scheme: String, private val freenetLink: Boolean) {
KSK("KSK@", true),
CHK("CHK@", true),
SSK("SSK@", true),
USK("USK@", true),
HTTP("http://", false),
HTTPS("https://", false),
SONE("sone://", false) {
override fun validateLinkLength(length: Int) = length.takeIf { it == 50 }
},
POST("post://", false),
FREEMAIL("", true) {
override fun findNext(line: String): NextLink? {
val nextFreemailSuffix = line.indexOf(".freemail").takeIf { it >= 54 } ?: return null
if (line[nextFreemailSuffix - 53] != '@') return null
if (!line.substring(nextFreemailSuffix - 52, nextFreemailSuffix).matches(Regex("^[a-z2-7]*\$"))) return null
val firstCharacterIndex = generateSequence(nextFreemailSuffix - 53) {
it.minus(1).takeIf { (it >= 0) && line[it].validLocalPart }
}.lastOrNull() ?: return null
return NextLink(firstCharacterIndex, this, line.substring(firstCharacterIndex, nextFreemailSuffix + 9), line.substring(nextFreemailSuffix + 9))
}
private val Char.validLocalPart get() = (this in ('A'..'Z')) || (this in ('a'..'z')) || (this in ('0'..'9')) || (this == '-') || (this == '_') || (this == '.')
};
open fun findNext(line: String): NextLink? {
val nextLinkPosition = line.indexOf(scheme).takeIf { it != -1 } ?: return null
val endOfLink = line.substring(nextLinkPosition).findEndOfLink().validate() ?: return null
val link = line.substring(nextLinkPosition, nextLinkPosition + endOfLink)
val realNextLinkPosition = if (freenetLink && line.substring(0, nextLinkPosition).endsWith("freenet:")) nextLinkPosition - 8 else nextLinkPosition
return NextLink(realNextLinkPosition, this, link, line.substring(nextLinkPosition + endOfLink))
}
private fun String.findEndOfLink() =
substring(0, whitespace.find(this)?.range?.start ?: length)
.dropLastWhile(::isPunctuation)
.upToFirstUnmatchedParen()
private fun Int.validate() = validateLinkLength(this)
protected open fun validateLinkLength(length: Int) = length.takeIf { it > scheme.length }
private fun String.upToFirstUnmatchedParen() =
foldIndexed(Pair<Int, Int?>(0, null)) { index, (openParens, firstUnmatchedParen), currentChar ->
when (currentChar) {
'(' -> (openParens + 1) to firstUnmatchedParen
')' -> ((openParens - 1) to (if (openParens == 0) (firstUnmatchedParen ?: index) else firstUnmatchedParen))
else -> openParens to firstUnmatchedParen
}
}.second ?: length
}
private val punctuationChars = listOf('.', ',', '?', '!')
private fun isPunctuation(char: Char) = char in punctuationChars
private val whitespace = Regex("[\\u000a\u0020\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u200c\u200d\u202f\u205f\u2060\u2800\u3000]")
private data class NextLink(val position: Int, val linkType: LinkType, val link: String, val remainder: String)
| gpl-3.0 | c06ef20c44e6aaaac28c17d1c083fe26 | 37.810945 | 181 | 0.679913 | 3.467111 | false | false | false | false |
ruuvi/Android_RuuvitagScanner | app/src/main/java/com/ruuvi/station/tagdetails/ui/TagFragment.kt | 1 | 8662 | package com.ruuvi.station.tagdetails.ui
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.text.SpannableString
import android.text.style.SuperscriptSpan
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.ruuvi.station.R
import com.ruuvi.station.graph.GraphView
import com.ruuvi.station.network.ui.SignInActivity
import com.ruuvi.station.tag.domain.RuuviTag
import com.ruuvi.station.tagdetails.domain.TagViewModelArgs
import com.ruuvi.station.util.extensions.describingTimeSince
import com.ruuvi.station.util.extensions.sharedViewModel
import com.ruuvi.station.util.extensions.viewModel
import kotlinx.android.synthetic.main.view_graphs.*
import kotlinx.android.synthetic.main.view_tag_detail.*
import org.kodein.di.Kodein
import org.kodein.di.KodeinAware
import org.kodein.di.android.support.closestKodein
import org.kodein.di.generic.instance
import timber.log.Timber
import java.util.*
import kotlin.concurrent.scheduleAtFixedRate
class TagFragment : Fragment(R.layout.view_tag_detail), KodeinAware {
override val kodein: Kodein by closestKodein()
private var timer: Timer? = null
private val viewModel: TagViewModel by viewModel {
arguments?.let {
TagViewModelArgs(it.getString(TAG_ID, ""))
}
}
private val activityViewModel: TagDetailsViewModel by sharedViewModel()
private val graphView: GraphView by instance()
init {
Timber.d("new TagFragment")
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
observeShowGraph()
observeTagEntry()
observeTagReadings()
observeSelectedTag()
observeSync()
gattSyncButton.setOnClickListener {
viewModel.syncGatt()
}
clearDataButton.setOnClickListener {
confirm(getString(R.string.clear_confirm), DialogInterface.OnClickListener { _, _ ->
viewModel.removeTagData()
})
}
gattSyncCancel.setOnClickListener {
viewModel.disconnectGatt()
}
}
override fun onResume() {
super.onResume()
timer = Timer("TagFragmentTimer", true)
timer?.scheduleAtFixedRate(0, 1000) {
viewModel.getTagInfo()
}
}
override fun onPause() {
super.onPause()
timer?.cancel()
}
private fun observeSelectedTag() {
activityViewModel.selectedTagObserve.observe(viewLifecycleOwner, Observer {
viewModel.tagSelected(it)
})
}
private fun confirm(message: String, positiveButtonClick: DialogInterface.OnClickListener) {
val builder = AlertDialog.Builder(requireContext())
with(builder)
{
setMessage(message)
setPositiveButton(getString(R.string.yes), positiveButtonClick)
setNegativeButton(getString(R.string.no), DialogInterface.OnClickListener { dialogInterface, i ->
dialogInterface.dismiss()
})
show()
}
}
private fun gattAlertDialog(message: String) {
val alertDialog = AlertDialog.Builder(requireContext(), R.style.CustomAlertDialog).create()
alertDialog.setMessage(message)
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, getString(R.string.ok)
) { dialog, _ -> dialog.dismiss() }
alertDialog.setOnDismissListener {
gattSyncViewButtons.visibility = View.VISIBLE
gattSyncViewProgress.visibility = View.GONE
}
alertDialog.show()
}
private fun observeShowGraph() {
activityViewModel.isShowGraphObserve.observe(viewLifecycleOwner, Observer { isShowGraph ->
view?.let {
setupViewVisibility(it, isShowGraph)
viewModel.isShowGraph(isShowGraph)
}
})
}
private fun observeTagEntry() {
viewModel.tagEntryObserve.observe(viewLifecycleOwner, Observer {
it?.let { updateTagData(it) }
})
}
private fun observeSync() {
viewModel.syncStatusObserve.observe(viewLifecycleOwner, Observer {
when (it.syncProgress) {
TagViewModel.SyncProgress.STILL -> {
// nothing is happening
}
TagViewModel.SyncProgress.CONNECTING -> {
gattSyncStatusTextView.text = "${context?.getString(R.string.connecting)}"
gattSyncViewButtons.visibility = View.GONE
gattSyncViewProgress.visibility = View.VISIBLE
gattSyncCancel.visibility = View.GONE
}
TagViewModel.SyncProgress.CONNECTED -> {
gattSyncStatusTextView.text = "${context?.getString(R.string.connected_reading_info)}"
}
TagViewModel.SyncProgress.DISCONNECTED -> {
gattAlertDialog(requireContext().getString(R.string.disconnected))
}
TagViewModel.SyncProgress.READING_INFO -> {
gattSyncStatusTextView.text = "${context?.getString(R.string.connected_reading_info)}"
}
TagViewModel.SyncProgress.NOT_SUPPORTED -> {
gattAlertDialog("${it.deviceInfoModel}, ${it.deviceInfoFw}\n${context?.getString(R.string.reading_history_not_supported)}")
}
TagViewModel.SyncProgress.READING_DATA -> {
gattSyncStatusTextView.text = "${context?.getString(R.string.reading_history)}"+"..."
gattSyncCancel.visibility = View.VISIBLE
}
TagViewModel.SyncProgress.SAVING_DATA -> {
gattSyncStatusTextView.text = if (it.readDataSize > 0) {
"${context?.getString(R.string.data_points_read, it.readDataSize)}"
} else {
"${context?.getString(R.string.no_new_data_points)}"
}
}
TagViewModel.SyncProgress.NOT_FOUND -> {
gattAlertDialog(requireContext().getString(R.string.tag_not_in_range))
}
TagViewModel.SyncProgress.ERROR -> {
gattAlertDialog(requireContext().getString(R.string.something_went_wrong))
}
TagViewModel.SyncProgress.DONE -> {
//gattAlertDialog(requireContext().getString(R.string.sync_complete))
gattSyncViewButtons.visibility = View.VISIBLE
gattSyncViewProgress.visibility = View.GONE
}
}
})
}
private fun observeTagReadings() {
viewModel.tagReadingsObserve.observe(viewLifecycleOwner, Observer { readings ->
readings?.let {
view?.let { view ->
graphView.drawChart(readings, view)
}
}
})
}
private fun updateTagData(tag: RuuviTag) {
Timber.d("updateTagData for ${tag.id}")
tagTemperatureTextView.text = viewModel.getTemperatureStringWithoutUnit(tag)
tagHumidityTextView.text = viewModel.getHumidityString(tag)
tagPressureTextView.text = viewModel.getPressureString(tag)
tagSignalTextView.text = viewModel.getSignalString(tag)
tagUpdatedTextView.text = getString(R.string.updated, tag.updatedAt?.describingTimeSince(requireContext()))
val unit = viewModel.getTemperatureUnitString()
val unitSpan = SpannableString(unit)
unitSpan.setSpan(SuperscriptSpan(), 0, unit.length, 0)
tagTempUnitTextView.text = unitSpan
tag.connectable?.let {
if (it) {
gattSyncView.visibility = View.VISIBLE
} else {
gattSyncView.visibility = View.GONE
}
}
}
private fun setupViewVisibility(view: View, showGraph: Boolean) {
val graph = view.findViewById<View>(R.id.tag_graphs)
graph.isVisible = showGraph
tagContainer.isVisible = !showGraph
}
companion object {
private const val TAG_ID = "TAG_ID"
fun newInstance(tagEntity: RuuviTag): TagFragment {
val tagFragment = TagFragment()
val arguments = Bundle()
arguments.putString(TAG_ID, tagEntity.id)
tagFragment.arguments = arguments
return tagFragment
}
}
} | mit | bbe0f6417e26d830546a52bc0ad041b2 | 36.665217 | 143 | 0.626414 | 4.978161 | false | false | false | false |
lttng/lttng-scope | jabberwocky-lttng/src/main/kotlin/com/efficios/jabberwocky/lttng/kernel/analysis/os/Attributes.kt | 2 | 3322 | /*
* Copyright (C) 2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
* Copyright (C) 2012-2015 Ericsson
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.efficios.jabberwocky.lttng.kernel.analysis.os
/**
* This file defines all the attribute names used in the handler. Both the
* construction and query steps should use them.
*
* These should not be externalized! The values here are used as-is in the
* history file on disk, so they should be kept the same to keep the file format
* compatible. If a view shows attribute names directly, the localization should
* be done on the viewer side.
*/
object Attributes {
/* First-level attributes */
const val CPUS = "CPUs"
const val THREADS = "Threads"
/* Sub-attributes of the CPU nodes */
const val CURRENT_THREAD = "Current_thread"
const val SOFT_IRQS = "Soft_IRQs"
const val IRQS = "IRQs"
/* Sub-attributes of the Thread nodes */
const val CURRENT_CPU_RQ = "Current_cpu_rq"
const val PPID = "PPID"
const val EXEC_NAME = "Exec_name"
const val PRIO = "Prio"
const val SYSTEM_CALL = "System_call"
/* Misc stuff */
const val UNKNOWN = "Unknown"
const val THREAD_0_PREFIX = "0_"
const val THREAD_0_SEPARATOR = "_"
/**
* Build the thread attribute name.
*
* For all threads except "0" this is the string representation of the
* threadId. For thread "0" which is the idle thread and can be running
* concurrently on multiple CPUs, append "_cpuId".
*
* @param threadId
* the thread id
* @param cpuId
* the cpu id
* @return the thread attribute name null if the threadId is zero and the
* cpuId is null
*/
@JvmStatic
fun buildThreadAttributeName(threadId: Int, cpuId: Int?): String? {
if (threadId == 0) {
cpuId ?: return null
return "${Attributes.THREAD_0_PREFIX}$cpuId"
}
return threadId.toString()
}
/**
* Parse the thread id and CPU id from the thread attribute name string
*
* For thread "0" the attribute name is in the form "threadId_cpuId",
* extract both values from the string.
*
* For all other threads, the attribute name is the string representation of
* the threadId and there is no cpuId.
*
* @param threadAttributeName
* the thread attribute name
* @return the thread id and cpu id
*/
@JvmStatic
fun parseThreadAttributeName(threadAttributeName: String): Pair<Int, Int> {
var threadId = -1
var cpuId = -1
try {
if (threadAttributeName.startsWith(Attributes.THREAD_0_PREFIX)) {
threadId = 0
val tokens = threadAttributeName.split(Attributes.THREAD_0_SEPARATOR)
cpuId = Integer.parseInt(tokens[1])
} else {
threadId = Integer.parseInt(threadAttributeName)
}
} catch (e: NumberFormatException) {
// ignore
}
return (threadId to cpuId)
}
}
| epl-1.0 | 5d16ee6b68f8bbc81ac47d62e0dccb20 | 31.252427 | 85 | 0.630343 | 4.221093 | false | false | false | false |
facebook/litho | sample/src/main/java/com/facebook/samples/litho/kotlin/bordereffects/VaryingRadiiBorder.kt | 1 | 2024 | /*
* 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.samples.litho.kotlin.bordereffects
import android.graphics.Color
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.Row
import com.facebook.litho.Style
import com.facebook.litho.dp
import com.facebook.litho.flexbox.border
import com.facebook.litho.kotlin.widget.Border
import com.facebook.litho.kotlin.widget.BorderEdge
import com.facebook.litho.kotlin.widget.BorderRadius
import com.facebook.litho.kotlin.widget.Text
class VaryingRadiiBorder : KComponent() {
override fun ComponentScope.render(): Component {
return Row(
style =
Style.border(
Border(
edgeAll = BorderEdge(width = 3f.dp),
edgeTop = BorderEdge(color = NiceColor.GREEN),
edgeBottom = BorderEdge(color = NiceColor.BLUE),
edgeLeft = BorderEdge(color = Color.BLACK),
edgeRight = BorderEdge(NiceColor.RED),
radius =
BorderRadius(
topLeft = 10f.dp,
topRight = 5f.dp,
bottomLeft = 30f.dp,
bottomRight = 20f.dp),
))) {
child(Text("This component has varying corner radii", textSize = 20f.dp))
}
}
}
| apache-2.0 | 58a9ae5f20e8912c1e6359a4c539f658 | 36.481481 | 83 | 0.644763 | 4.380952 | false | false | false | false |
toastkidjp/Jitte | app/src/main/java/jp/toastkid/yobidashi/browser/webview/factory/WebChromeClientFactory.kt | 1 | 3011 | /*
* Copyright (c) 2020 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.browser.webview.factory
import android.graphics.Bitmap
import android.os.Message
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebView
import androidx.core.net.toUri
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModelProvider
import jp.toastkid.lib.BrowserViewModel
import jp.toastkid.lib.image.BitmapCompressor
import jp.toastkid.yobidashi.browser.BrowserHeaderViewModel
import jp.toastkid.yobidashi.browser.FaviconApplier
import jp.toastkid.yobidashi.browser.webview.CustomViewSwitcher
class WebChromeClientFactory(
private val browserHeaderViewModel: BrowserHeaderViewModel? = null,
private val faviconApplier: FaviconApplier? = null,
private val customViewSwitcher: CustomViewSwitcher? = null
) {
operator fun invoke(): WebChromeClient = object : WebChromeClient() {
private val bitmapCompressor = BitmapCompressor()
override fun onProgressChanged(view: WebView, newProgress: Int) {
super.onProgressChanged(view, newProgress)
browserHeaderViewModel?.updateProgress(newProgress)
browserHeaderViewModel?.stopProgress(newProgress < 65)
}
override fun onReceivedIcon(view: WebView?, favicon: Bitmap?) {
super.onReceivedIcon(view, favicon)
val urlStr = view?.url
if (urlStr != null && favicon != null) {
val file = faviconApplier?.assignFile(urlStr) ?: return
bitmapCompressor(favicon, file)
}
}
override fun onShowCustomView(view: View?, callback: CustomViewCallback?) {
super.onShowCustomView(view, callback)
customViewSwitcher?.onShowCustomView(view, callback)
}
override fun onHideCustomView() {
super.onHideCustomView()
customViewSwitcher?.onHideCustomView()
}
override fun onCreateWindow(
view: WebView?,
isDialog: Boolean,
isUserGesture: Boolean,
resultMsg: Message?
): Boolean {
val href = view?.handler?.obtainMessage()
view?.requestFocusNodeHref(href)
val url = href?.data?.getString("url")?.toUri()
?: return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg)
view.stopLoading()
(view.context as? FragmentActivity)?.also { fragmentActivity ->
ViewModelProvider(fragmentActivity)
.get(BrowserViewModel::class.java)
.open(url)
}
return true
}
}
} | epl-1.0 | 3790e3e81361f2e2a81d62e28a95f3e5 | 35.731707 | 92 | 0.664563 | 5.10339 | false | false | false | false |
tmarsteel/compiler-fiddle | test/matchers.kt | 1 | 966 | /*
* Copyright 2018 Tobias Marstaller
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package matchers
var isNotNull = com.natpryce.hamkrest.Matcher("isNotNull", { it: Any? -> it != null })
var isNull = com.natpryce.hamkrest.Matcher("isNull", { it: Any? -> it == null }) | lgpl-3.0 | bc96c3d7f00a1354953ee5186c516ac2 | 42.954545 | 86 | 0.73499 | 4.218341 | false | false | false | false |
xfournet/intellij-community | platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/configurationStore/ExternalSystemStorageTest.kt | 8 | 4015 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.configurationStore
import com.intellij.configurationStore.ESCAPED_MODULE_DIR
import com.intellij.configurationStore.useAndDispose
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.externalSystem.ExternalSystemModulePropertyManager
import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsDataStorage
import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManagerImpl
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleTypeId
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.roots.impl.ModuleRootManagerImpl
import com.intellij.project.stateStore
import com.intellij.testFramework.*
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.util.io.delete
import com.intellij.util.io.parentSystemIndependentPath
import com.intellij.util.io.systemIndependentPath
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.nio.file.Paths
@RunsInEdt
@RunsInActiveStoreMode
class ExternalSystemStorageTest {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule()
}
private val tempDirManager = TemporaryDirectory()
@Suppress("unused")
@JvmField
@Rule
val ruleChain = RuleChain(tempDirManager, EdtRule())
@Test
fun `must be empty if external system storage`() {
createProjectAndUseInLoadComponentStateMode(tempDirManager, directoryBased = true) { project ->
ExternalProjectsManagerImpl.getInstance(project).setStoreExternally(true)
val dotIdeaDir = Paths.get(project.stateStore.directoryStorePath)
val cacheDir = ExternalProjectsDataStorage.getProjectConfigurationDir(project).resolve("modules")
cacheDir.delete()
// we must not use VFS here, file must not be created
val moduleFile = dotIdeaDir.parent.resolve("test.iml")
runWriteAction { ModuleManager.getInstance(project).newModule(moduleFile.systemIndependentPath, ModuleTypeId.JAVA_MODULE) }.useAndDispose {
assertThat(cacheDir).doesNotExist()
ModuleRootModificationUtil.addContentRoot(this, moduleFile.parentSystemIndependentPath)
saveStore()
assertThat(cacheDir).doesNotExist()
assertThat(moduleFile).isEqualTo("""
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$ESCAPED_MODULE_DIR" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>""")
ExternalSystemModulePropertyManager.getInstance(this).setMavenized(true)
// force re-save: this call not in the setMavenized because ExternalSystemModulePropertyManager in the API (since in production we have the only usage, it is ok for now)
(ModuleRootManager.getInstance(this) as ModuleRootManagerImpl).stateChanged()
assertThat(cacheDir).doesNotExist()
saveStore()
assertThat(cacheDir).isDirectory
assertThat(moduleFile).isEqualTo("""
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4" />""")
assertThat(cacheDir.resolve("test.xml")).isEqualTo("""
<module>
<component name="ExternalSystem" externalSystem="Maven" />
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$ESCAPED_MODULE_DIR" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>""")
assertThat(dotIdeaDir.resolve("modules.xml")).doesNotExist()
}
}
}
} | apache-2.0 | 2f24b164e7b60a4a5e2da57547371445 | 40.833333 | 177 | 0.746949 | 4.884428 | false | true | false | false |
lskycity/AndroidTools | app/src/main/java/com/lskycity/androidtools/DeviceFragment.kt | 1 | 7211 | package com.lskycity.androidtools
import android.Manifest
import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.loader.app.LoaderManager
import androidx.loader.content.Loader
import com.lskycity.androidtools.utils.ClassUtils
import com.lskycity.androidtools.utils.PermissionUtils
import com.lskycity.support.utils.DeviceUtils
import java.util.*
/**
* Created by zhaofliu on 10/1/16.
*
*/
class DeviceFragment : Fragment(), LoaderManager.LoaderCallbacks<ArrayList<String>> {
private lateinit var deviceName: TextView
private lateinit var androidVersion: TextView
private lateinit var imei: TextView
private lateinit var support32: TextView
private lateinit var support64: TextView
private lateinit var cpuFeature: TextView
private lateinit var backend: TextView
private lateinit var front: TextView
private lateinit var grantCameraPermission: Button
private lateinit var more: TextView
private lateinit var glVersion: TextView
private val systemInfo: CharSequence
get() {
val sb = StringBuilder()
sb.append("-------build info -------\n\n")
ClassUtils.fetchClassInfo(sb, Build::class.java)
sb.append('\n')
sb.append("Radio version is ")
sb.append(Build.getRadioVersion())
sb.append('\n')
sb.append('\n')
sb.append("-------version info -------\n\n")
ClassUtils.fetchClassInfo(sb, Build.VERSION::class.java)
return sb
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_devices, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
deviceName = view.findViewById(R.id.device_name) as TextView
androidVersion = view.findViewById(R.id.android_version) as TextView
imei = view.findViewById(R.id.imei) as TextView
support32 = view.findViewById(R.id.support_32) as TextView
support64 = view.findViewById(R.id.support_64) as TextView
cpuFeature = view.findViewById(R.id.cpu_feature) as TextView
backend = view.findViewById(R.id.backend) as TextView
front = view.findViewById(R.id.front) as TextView
grantCameraPermission = view.findViewById(R.id.grant_camera_permission) as Button
grantCameraPermission.setOnClickListener { requestPermissions(arrayOf(Manifest.permission.CAMERA), permissionId)}
more = view.findViewById(R.id.more) as TextView
more.setOnClickListener {
clickMore()
}
glVersion = view.findViewById(R.id.gl_version) as TextView
updateInfo()
}
@SuppressLint("SetTextI18n")
private fun updateInfo() {
deviceName.text = Build.BRAND + " " + Build.MODEL
androidVersion.text = getString(R.string.android_version) + ": " + Build.VERSION.RELEASE + " / " + Build.VERSION.SDK_INT
if (PermissionUtils.checkPermission(activity!!, Manifest.permission.READ_PHONE_STATE)) {
imei.text = "IMEI: " + DeviceUtils.getIMEI(activity!!)
} else {
imei.text = getString(R.string.serial) + ": " + Build.SERIAL
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
support32.text = "64 ABI: " + Arrays.toString(Build.SUPPORTED_64_BIT_ABIS)
} else {
support32.text = "ABI: " + Build.CPU_ABI
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
support64.text = "32 ABI: " + Arrays.toString(Build.SUPPORTED_32_BIT_ABIS)
} else {
//noinspection deprecated
if (!TextUtils.isEmpty(Build.CPU_ABI2)) {
support64.text = "ABI2: " + Build.CPU_ABI2
} else {
support64.visibility = View.GONE
}
}
cpuFeature.text = getCpuFeature()
glVersion.text = getGlVersion()
try {
updateCameraInfo()
} catch (e: Exception) {
backend.text = "No Camera found."
front.visibility = View.GONE
grantCameraPermission.visibility = View.GONE
}
}
private fun getGlVersion(): String {
val am = context!!.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val info = am.deviceConfigurationInfo
val glversion = info.reqGlEsVersion
return (glversion shr 16).toString() + "." + (glversion and 0xffff).toString()
}
fun clickMore() {
val builder = AlertDialog.Builder(activity!!)
builder.setMessage(systemInfo)
builder.setNegativeButton(android.R.string.cancel, null)
builder.show()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (PermissionUtils.verifyPermissions(grantResults)) {
updateInfo()
} else {
Toast.makeText(activity, "No grant Permission", Toast.LENGTH_LONG).show()
}
}
private fun updateCameraInfo() {
if (PermissionUtils.checkPermission(activity!!, Manifest.permission.CAMERA)) {
loaderManager.initLoader(0, null, this)
grantCameraPermission.visibility = View.GONE
backend.setText(R.string.loading)
front.setText(R.string.loading)
} else {
backend.setText(R.string.grant_camera_permission_msg)
front.visibility = View.GONE
grantCameraPermission.visibility = View.VISIBLE
}
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader<ArrayList<String>> {
return CameraParameterLoader(context!!)
}
override fun onLoadFinished(loader: Loader<ArrayList<String>>, data: ArrayList<String>) {
if (data.size > 0) {
backend.text = data[0]
if (data.size > 1) {
front.text = data[1]
front.visibility = View.VISIBLE
} else {
front.visibility = View.GONE
}
} else {
backend.setText(R.string.no_camera_found)
front.visibility = View.GONE
}
}
override fun onLoaderReset(loader: Loader<ArrayList<String>>) {
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
private external fun getCpuFeature(): String
companion object {
private val permissionId = 11
init {
System.loadLibrary("native-lib")
}
}
}
| apache-2.0 | b7e4d1d16547fa2478f0c991c330631b | 32.696262 | 128 | 0.647206 | 4.484453 | false | false | false | false |
sepatel/tekniq | tekniq-jdbc/src/main/kotlin/io/tekniq/jdbc/TqResultSetExt.kt | 1 | 1181 | package io.tekniq.jdbc
import java.sql.ResultSet
fun ResultSet.getBooleanNull(x: Int) = returnNullable(getBoolean(x))
fun ResultSet.getBooleanNull(x: String) = returnNullable(getBoolean(x))
fun ResultSet.getByteNull(x: Int) = returnNullable(getByte(x))
fun ResultSet.getByteNull(x: String) = returnNullable(getByte(x))
fun ResultSet.getShortNull(x: Int) = returnNullable(getShort(x))
fun ResultSet.getShortNull(x: String) = returnNullable(getShort(x))
fun ResultSet.getIntNull(x: Int) = returnNullable(getInt(x))
fun ResultSet.getIntNull(x: String) = returnNullable(getInt(x))
fun ResultSet.getLongNull(x: Int) = returnNullable(getLong(x))
fun ResultSet.getLongNull(x: String) = returnNullable(getLong(x))
fun ResultSet.getFloatNull(x: Int) = returnNullable(getFloat(x))
fun ResultSet.getFloatNull(x: String) = returnNullable(getFloat(x))
fun ResultSet.getDoubleNull(x: Int) = returnNullable(getDouble(x))
fun ResultSet.getDoubleNull(x: String) = returnNullable(getDouble(x))
private fun <T> ResultSet.returnNullable(x: T): T? = when (wasNull()) {
true -> null
false -> x
}
inline fun ResultSet.forEach(action: ResultSet.() -> Unit) {
while (next()) action(this)
}
| mit | 4bbe122aafb7ddcb8bd062ac6520e515 | 42.740741 | 71 | 0.759526 | 3.423188 | false | false | false | false |
JimSeker/ui | ListViews/ListviewFragmentDemo_kt/app/src/main/java/edu/cs4730/listviewfragmentdemo_kt/MainActivity.kt | 1 | 2181 | package edu.cs4730.listviewfragmentdemo_kt
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
/**
* This is an example using the listview in a fragment. There is very little code here that is not default
* except the callbacks for the fragment named titlefrag. There is a layout and layout-land for this
* so the code also decides if it needs to display a fragment or if it is already showing.
*
* see the two fragments textFrag and titlefrag for the bulk of the code.
*/
class MainActivity : AppCompatActivity(), titlefrag.OnFragmentInteractionListener {
var TwoPane = false
lateinit var myTextFrag: textFrag
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (findViewById<View?>(R.id.container) == null) {
//landscape or large mode. both fragments will be displayed on the screen.
// nothing to do, since it already showing.
TwoPane = true
myTextFrag = supportFragmentManager.findFragmentById(R.id.frag_text) as textFrag
} else {
//portrait or small screen. the container exists.
TwoPane = false
//add the title fragment.
supportFragmentManager.beginTransaction()
.add(R.id.container, titlefrag())
.commit()
}
}
override fun onItemSelected(id: Int) {
if (TwoPane) {
//already showing, so just update it.
myTextFrag.setText(id)
} else {
//get an new instance of the fragment with the correct data.
myTextFrag = textFrag.newInstance(id)
val transaction = supportFragmentManager.beginTransaction()
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.container, myTextFrag, "second")
transaction.addToBackStack(null)
// Commit the transaction
transaction.commit()
}
}
}
| apache-2.0 | 12d7c2652cd778db8425e5d3828d3d80 | 38.654545 | 107 | 0.656121 | 4.923251 | false | false | false | false |
alashow/music-android | app/src/main/kotlin/tm/alashow/datmusic/ui/AppNavigation.kt | 1 | 4668 | /*
* Copyright (C) 2021, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.datmusic.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.navigation.NavController
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.navigation
import kotlinx.coroutines.InternalCoroutinesApi
import timber.log.Timber
import tm.alashow.common.compose.collectEvent
import tm.alashow.datmusic.ui.album.AlbumDetail
import tm.alashow.datmusic.ui.artist.ArtistDetail
import tm.alashow.datmusic.ui.downloads.Downloads
import tm.alashow.datmusic.ui.search.Search
import tm.alashow.datmusic.ui.settings.Settings
import tm.alashow.navigation.LeafScreen
import tm.alashow.navigation.LocalNavigator
import tm.alashow.navigation.NavigationEvent
import tm.alashow.navigation.Navigator
import tm.alashow.navigation.RootScreen
import tm.alashow.navigation.composableScreen
@OptIn(InternalCoroutinesApi::class)
@Composable
internal fun AppNavigation(
navController: NavHostController,
navigator: Navigator = LocalNavigator.current,
) {
collectEvent(navigator.queue) { event ->
Timber.i("Navigation event: $event")
when (event) {
is NavigationEvent.Destination -> navController.navigate(event.route)
is NavigationEvent.Back -> navController.navigateUp()
else -> Unit
}
}
NavHost(
navController = navController,
startDestination = RootScreen.Search.route
) {
addSearchRoot(navController)
addDownloadsRoot(navController)
addSettingsRoot(navController)
}
}
private fun NavGraphBuilder.addSearchRoot(navController: NavController) {
navigation(
route = RootScreen.Search.route,
startDestination = LeafScreen.Search.route
) {
addSearch(navController)
addArtistDetails(navController)
addAlbumDetails(navController)
}
}
private fun NavGraphBuilder.addDownloadsRoot(navController: NavController) {
navigation(
route = RootScreen.Downloads.route,
startDestination = LeafScreen.Downloads.route
) {
addDownloads(navController)
}
}
private fun NavGraphBuilder.addSettingsRoot(navController: NavController) {
navigation(
route = RootScreen.Settings.route,
startDestination = LeafScreen.Settings.route
) {
addSettings(navController)
}
}
private fun NavGraphBuilder.addSearch(navController: NavController) {
composableScreen(LeafScreen.Search) {
Search()
}
}
private fun NavGraphBuilder.addSettings(navController: NavController) {
composableScreen(LeafScreen.Settings) {
Settings()
}
}
private fun NavGraphBuilder.addDownloads(navController: NavController) {
composableScreen(LeafScreen.Downloads) {
Downloads()
}
}
private fun NavGraphBuilder.addArtistDetails(navController: NavController) {
composableScreen(LeafScreen.ArtistDetails) {
ArtistDetail()
}
}
private fun NavGraphBuilder.addAlbumDetails(navController: NavController) {
composableScreen(LeafScreen.AlbumDetails) {
AlbumDetail()
}
}
/**
* Adds an [NavController.OnDestinationChangedListener] to this [NavController] and updates the
* returned [State] which is updated as the destination changes.
*/
@Stable
@Composable
internal fun NavController.currentScreenAsState(): State<RootScreen> {
val selectedItem = remember { mutableStateOf<RootScreen>(RootScreen.Search) }
DisposableEffect(this) {
val listener = NavController.OnDestinationChangedListener { _, destination, _ ->
when {
destination.hierarchy.any { it.route == RootScreen.Search.route } -> {
selectedItem.value = RootScreen.Search
}
destination.hierarchy.any { it.route == RootScreen.Downloads.route } -> {
selectedItem.value = RootScreen.Downloads
}
destination.hierarchy.any { it.route == RootScreen.Settings.route } -> {
selectedItem.value = RootScreen.Settings
}
}
}
addOnDestinationChangedListener(listener)
onDispose {
removeOnDestinationChangedListener(listener)
}
}
return selectedItem
}
| apache-2.0 | 4122fe2011523da704a257c3ea19de1e | 30.328859 | 95 | 0.720223 | 4.837306 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/wildplot/android/rendering/PieChart.kt | 1 | 6361 | /****************************************************************************************
* Copyright (c) 2014 Michael Goldbach <[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.wildplot.android.rendering
import com.wildplot.android.rendering.graphics.wrapper.ColorWrap
import com.wildplot.android.rendering.graphics.wrapper.GraphicsWrap
import com.wildplot.android.rendering.interfaces.Drawable
import com.wildplot.android.rendering.interfaces.Legendable
class PieChart(plotSheet: PlotSheet, values: DoubleArray, colors: Array<ColorWrap>) : Drawable, Legendable {
private val mPlotSheet: PlotSheet
private val mValues: DoubleArray
private val mColors: Array<ColorWrap>
override var name: String = ""
set(value) {
field = value
mNameIsSet = true
}
private var mNameIsSet = false
private val mPercent: DoubleArray
private var mSum = 0.0
private fun checkArguments(values: DoubleArray, colors: Array<ColorWrap>) {
require(values.size == colors.size) { "The number of colors must match the number of values" }
}
override fun isOnFrame(): Boolean {
return false
}
override fun paint(g: GraphicsWrap) {
// Do not show chart if segments are all zero
if (mSum == 0.0) {
return
}
val maxSideBorders = Math.max(
mPlotSheet.frameThickness[PlotSheet.LEFT_FRAME_THICKNESS_INDEX],
mPlotSheet.frameThickness[PlotSheet.RIGHT_FRAME_THICKNESS_INDEX]
)
val maxUpperBottomBorders = Math.max(
mPlotSheet.frameThickness[PlotSheet.UPPER_FRAME_THICKNESS_INDEX],
mPlotSheet.frameThickness[PlotSheet.BOTTOM_FRAME_THICKNESS_INDEX]
)
val realBorder = Math.max(maxSideBorders, maxUpperBottomBorders) + 3
val field = g.clipBounds
val diameter = Math.min(field.width, field.height) - 2 * realBorder
val xCenter = field.width / 2.0f
val yCenter = field.height / 2.0f
val oldColor = g.color
drawSectors(g, diameter, xCenter, yCenter)
drawSectorLabels(g, diameter, xCenter, yCenter)
g.color = oldColor
}
private fun drawSectors(g: GraphicsWrap, diameter: Float, xCenter: Float, yCenter: Float) {
val left = xCenter - diameter / 2f
val top = yCenter - diameter / 2f
var currentAngle = FIRST_SECTOR_OFFSET
for (i in 0 until mPercent.size - 1) {
g.color = mColors[i]
val arcLength = (360 * mValues[i] / mSum).toFloat()
g.fillArc(left, top, diameter, diameter, currentAngle, arcLength)
currentAngle += arcLength
}
// last one does need some corrections to fill a full circle:
g.color = lastSectorColor
g.fillArc(
left, top, diameter, diameter, currentAngle,
360f + FIRST_SECTOR_OFFSET - currentAngle
)
g.color = ColorWrap.black
g.drawArc(left, top, diameter, diameter, 0f, 360f)
}
private val lastSectorColor: ColorWrap
get() = mColors[mColors.size - 1]
private fun drawSectorLabels(g: GraphicsWrap, diameter: Float, xCenter: Float, yCenter: Float) {
val labelBackground = ColorWrap(0.0f, 0.0f, 0.0f, 0.5f)
for (j in mPercent.indices) {
if (mValues[j] == 0.0) {
continue
}
var oldPercent = 0.0
if (j != 0) {
oldPercent = mPercent[j - 1]
}
val text = "" + Math.round((mPercent[j] - oldPercent) * 100 * 100) / 100.0 + "%"
val x = (xCenter + Math.cos(-1 * ((oldPercent + (mPercent[j] - oldPercent) * 0.5) * 360 + FIRST_SECTOR_OFFSET) * Math.PI / 180.0) * 0.375 * diameter).toFloat() - 20
val y = (yCenter - Math.sin(-1 * ((oldPercent + (mPercent[j] - oldPercent) * 0.5) * 360 + FIRST_SECTOR_OFFSET) * Math.PI / 180.0) * 0.375 * diameter).toFloat()
val fm = g.fontMetrics
val width = fm.stringWidth(text)
val height = fm.height
g.color = labelBackground
g.fillRect(x - 1, y - height + 3, width + 2, height)
g.color = ColorWrap.white
g.drawString(text, x, y)
}
}
override fun isClusterable(): Boolean {
return true
}
override fun isCritical(): Boolean {
return false
}
override val color: ColorWrap
get() = if (mColors.size > 0) mColors[0] else ColorWrap.WHITE
override fun nameIsSet(): Boolean {
return mNameIsSet
}
companion object {
// First sector starts at 12 o'clock.
private const val FIRST_SECTOR_OFFSET = -90f
}
init {
checkArguments(values, colors)
mPlotSheet = plotSheet
mValues = values
mColors = colors
mPercent = DoubleArray(mValues.size)
for (v in mValues) {
mSum += v
}
val denominator: Double = if (mSum == 0.0) 1.0 else mSum
mPercent[0] = mValues[0] / denominator
for (i in 1 until mValues.size) {
mPercent[i] = mPercent[i - 1] + mValues[i] / denominator
}
}
}
| gpl-3.0 | 70e4f65199d81b78fdc317c294753c4e | 41.406667 | 176 | 0.557931 | 4.300879 | false | false | false | false |
mixitconf/mixit | src/main/kotlin/mixit/security/model/AuthenticationService.kt | 1 | 6999 | package mixit.security.model
import mixit.MixitProperties
import mixit.security.MixitWebFilter.Companion.AUTHENT_COOKIE
import mixit.ticket.repository.LotteryRepository
import mixit.user.model.Role
import mixit.user.model.User
import mixit.user.model.UserService
import mixit.user.model.generateNewToken
import mixit.user.model.hasValidToken
import mixit.user.model.hasValidTokens
import mixit.user.model.jsonToken
import mixit.user.repository.UserRepository
import mixit.util.camelCase
import mixit.util.email.EmailService
import mixit.util.errors.CredentialValidatorException
import mixit.util.errors.DuplicateException
import mixit.util.errors.EmailSenderException
import mixit.util.errors.NotFoundException
import mixit.util.errors.TokenException
import mixit.util.toSlug
import mixit.util.validator.EmailValidator
import org.slf4j.LoggerFactory
import org.springframework.http.ResponseCookie
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import java.util.Locale
@Service
class AuthenticationService(
private val userRepository: UserRepository,
private val userService: UserService,
private val lotteryRepository: LotteryRepository,
private val emailService: EmailService,
private val emailValidator: EmailValidator,
private val cryptographer: Cryptographer,
private val properties: MixitProperties
) {
private val logger = LoggerFactory.getLogger(this.javaClass)
/**
* Create user from HTTP form or from a ticket
*/
fun createUser(nonEncryptedMail: String?, firstname: String?, lastname: String?): Pair<String, User> =
emailValidator.check(nonEncryptedMail).let { email ->
if (firstname == null || lastname == null) {
throw CredentialValidatorException()
}
Pair(
email,
User(
login = email.split("@")[0].toSlug(),
firstname = firstname.camelCase(),
lastname = lastname.camelCase(),
email = cryptographer.encrypt(email),
role = Role.USER
)
)
}
/**
* Create user if he does not exist
*/
fun createUserIfEmailDoesNotExist(nonEncryptedMail: String, user: User): Mono<User> =
userRepository.findOne(user.login)
.flatMap { Mono.error<User> { DuplicateException("Login already exist") } }
.switchIfEmpty(
Mono.defer {
userRepository.findByNonEncryptedEmail(nonEncryptedMail)
// Email is unique and if an email is found we return an error
.flatMap { Mono.error<User> { DuplicateException("Email already exist") } }
.switchIfEmpty(Mono.defer { userRepository.save(user) })
}
)
/**
* This function try to find a user in the user table and if not try to read his information in
* ticketing table to create a new one.
*/
fun searchUserByEmailOrCreateHimFromTicket(nonEncryptedMail: String): Mono<User> =
userRepository.findByNonEncryptedEmail(nonEncryptedMail)
.switchIfEmpty(
Mono.defer {
lotteryRepository.findByEncryptedEmail(cryptographer.encrypt(nonEncryptedMail)!!)
.flatMap {
createUserIfEmailDoesNotExist(
nonEncryptedMail,
createUser(nonEncryptedMail, it.firstname, it.lastname).second
)
}
.switchIfEmpty(Mono.empty())
}
)
fun createCookie(user: User) = ResponseCookie
.from(AUTHENT_COOKIE, user.jsonToken(cryptographer))
.secure(properties.baseUri.startsWith("https"))
.httpOnly(true)
.maxAge(user.tokenLifeTime)
.build()
/**
* Function used on login to check if user email and token are valids
*/
fun checkUserEmailAndToken(nonEncryptedMail: String, token: String): Mono<User> =
userRepository.findByNonEncryptedEmail(nonEncryptedMail)
.flatMap {
if (it.hasValidToken(token.trim())) {
return@flatMap Mono.just(it)
}
return@flatMap Mono.error<User> { TokenException("Token is invalid or is expired") }
}
.switchIfEmpty(Mono.defer { throw NotFoundException() })
/**
* Function used on login to check if user email and token are valids
*/
fun checkUserEmailAndTokenOrAppToken(nonEncryptedMail: String, token: String?, appToken: String?): Mono<User> =
userRepository.findByNonEncryptedEmail(nonEncryptedMail)
.flatMap {
if (it.hasValidTokens(token, appToken)) {
return@flatMap Mono.just(it)
}
return@flatMap Mono.error<User> { TokenException("Token is invalid or is expired") }
}
.switchIfEmpty(Mono.defer { throw NotFoundException() })
/**
* Sends an email with a token to the user. We don't need validation of the email adress. If he receives
* the email it's OK. If he retries a login a new token is sent. Be careful email service can throw
* an EmailSenderException
*/
fun generateAndSendToken(
user: User,
locale: Locale,
nonEncryptedMail: String,
tokenForNewsletter: Boolean,
generateExternalToken: Boolean = false
): Mono<User> =
user.generateNewToken(generateExternalToken).let { newUser ->
try {
if (!properties.feature.email) {
logger.info("A token ${newUser.token} was sent by email")
}
emailService.send(if (tokenForNewsletter) "email-newsletter-subscribe" else "email-token", newUser, locale)
userRepository.save(newUser)
} catch (e: EmailSenderException) {
Mono.error<User> { e }
}
}
/**
* Sends an email with a token to the user. We don't need validation of the email adress.
*/
fun clearToken(nonEncryptedMail: String): Mono<User> =
userRepository
.findByNonEncryptedEmail(nonEncryptedMail)
.flatMap { user -> user.generateNewToken().let { userRepository.save(it) } }
fun updateNewsletterSubscription(user: User, tokenForNewsletter: Boolean): Mono<User> =
if (tokenForNewsletter) {
userRepository.save(user.copy(newsletterSubscriber = true))
} else if (user.email == null) {
// Sometimes we can have a email hash in the DB but not the email (for legacy users). So in this case
// we store the email
userService.updateReference(user).flatMap { userRepository.save(it) }
} else {
Mono.just(user)
}
}
| apache-2.0 | 19951081b69e99405c0022d7b7409372 | 39.69186 | 123 | 0.627947 | 4.82357 | false | false | false | false |
EvidentSolutions/apina | apina-core/src/main/kotlin/fi/evident/apina/spring/SpringUriTemplateParser.kt | 1 | 1778 | package fi.evident.apina.spring
import fi.evident.apina.model.URITemplate
/**
* Converts URI-template in Spring format to plain URI-template, removing
* the specified regex constraints from variables.
*/
fun parseSpringUriTemplate(template: String): URITemplate {
val parser = SpringUriTemplateParser(template)
parser.parse()
return URITemplate(parser.result.toString())
}
private class SpringUriTemplateParser(private val template: String) {
private var pos = 0
val result = StringBuilder()
fun parse() {
while (hasMore()) {
readPlainText()
if (hasMore())
readVariable()
}
}
private fun readChar(): Char {
check(hasMore()) { "unexpected end of input" }
return template[pos++]
}
private fun readVariable() {
check(readChar() == '{') { "expected '{'" }
var braceLevel = 0
val start = pos
while (hasMore()) {
when (template[pos++]) {
'\\' -> readChar() // skip next
'{' -> braceLevel++
'}' -> if (braceLevel == 0) {
val variable = template.substring(start, pos - 1)
val colonIndex = variable.indexOf(':')
result.append('{').append(if (colonIndex == -1) variable else variable.substring(0, colonIndex)).append('}')
return
} else {
braceLevel--
}
}
}
error("unexpected end of input for template '$template'")
}
private fun readPlainText() {
while (hasMore() && template[pos] != '{')
result.append(template[pos++])
}
private fun hasMore() = pos < template.length
}
| mit | 4f339c009ad3b0649d51009a2aa52447 | 25.939394 | 128 | 0.542182 | 4.754011 | false | false | false | false |
nosix/vue-kotlin | single-file/greeting/main/greeting.kt | 1 | 484 | import org.musyozoku.vuekt.*
@JsModule("greeting-component.vue")
external val GreetingComponent: Component = definedExternally
@JsModule("vue")
@JsName("Vue")
external class AppVue(options: ComponentOptions<AppVue>) : Vue {
var message: String
}
val vm = AppVue(ComponentOptions {
el = ElementConfig("#app")
data = Data(json<AppVue> {
message = "Vue & Kotlin"
})
components = json {
this["greeting"] = ComponentConfig(GreetingComponent)
}
}) | apache-2.0 | 9952e9db3200cf9f033064aa8467cbdf | 23.25 | 64 | 0.679752 | 3.751938 | false | true | false | false |
pdvrieze/ProcessManager | PE-common/src/commonMain/kotlin/nl/adaptivity/process/engine/ProcessData.kt | 1 | 5055 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.nullable
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.buildClassSerialDescriptor
import kotlinx.serialization.descriptors.element
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.encoding.decodeStructure
import net.devrieze.util.Named
import nl.adaptivity.process.ProcessConsts
import nl.adaptivity.serialutil.decodeElements
import nl.adaptivity.xmlutil.*
import nl.adaptivity.xmlutil.serialization.ICompactFragmentSerializer
import nl.adaptivity.xmlutil.serialization.XML
import nl.adaptivity.xmlutil.serialization.XmlSerialName
import nl.adaptivity.xmlutil.util.CompactFragment
import nl.adaptivity.xmlutil.util.ICompactFragment
/** Class to represent data attached to process instances. */
@Serializable(with = ProcessData.Companion::class)
@XmlSerialName(ProcessData.ELEMENTLOCALNAME, ProcessConsts.Engine.NAMESPACE, ProcessConsts.Engine.NSPREFIX)
class ProcessData
constructor(
override val name: String?,
val content: ICompactFragment
) : Named {
val contentStream: XmlReader get() = content.getXmlReader()
override fun copy(name: String?): ProcessData = copy(name, content)
fun copy(name: String?, value: ICompactFragment): ProcessData = ProcessData(name, value)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as ProcessData
if (name != other.name) return false
if (content != other.content) return false
return true
}
override fun hashCode(): Int {
var result = name?.hashCode() ?: 0
result = 31 * result + content.hashCode()
return result
}
override fun toString(): String {
return "ProcessData($name=$content)"
}
@Serializable
@XmlSerialName(ELEMENTLOCALNAME, ProcessConsts.Engine.NAMESPACE, ProcessConsts.Engine.NSPREFIX)
private class SerialAnnotationHelper
companion object: KSerializer<ProcessData> {
const val ELEMENTLOCALNAME = "value"
val ELEMENTNAME = QName(ProcessConsts.Engine.NAMESPACE, ELEMENTLOCALNAME, ProcessConsts.Engine.NSPREFIX)
fun missingData(name: String): ProcessData {
return ProcessData(name, CompactFragment(""))
}
@OptIn(XmlUtilInternal::class, ExperimentalSerializationApi::class)
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ProcessData") {
annotations = SerialAnnotationHelper.serializer().descriptor.annotations
element<String>("name")
element<ICompactFragment>("content")
}
override fun deserialize(decoder: Decoder): ProcessData {
var name: String? = null
lateinit var content: ICompactFragment
decoder.decodeStructure(descriptor) {
decodeElements(this) { i ->
when (i) {
0 -> name = decodeSerializableElement(descriptor, 0, String.serializer().nullable)
1 -> content = when (this) {
is XML.XmlInput -> this.input.siblingsToFragment()
else -> decodeSerializableElement(descriptor, 1, ICompactFragmentSerializer)
}
}
}
}
return ProcessData(name, content)
}
@OptIn(ExperimentalSerializationApi::class)
override fun serialize(encoder: Encoder, value: ProcessData) {
val newOutput = encoder.beginStructure(descriptor)
newOutput.encodeNullableSerializableElement(descriptor, 0, String.serializer(), value.name)
if (newOutput is XML.XmlOutput) {
value.content.serialize(newOutput.target)
} else {
newOutput.encodeSerializableElement(descriptor, 1, ICompactFragmentSerializer, value.content)
}
newOutput.endStructure(descriptor)
}
}
}
| lgpl-3.0 | dd844737f6fe46673bed41b4b5d324a8 | 37.587786 | 115 | 0.698121 | 5.137195 | false | false | false | false |
magnusja/libaums | app/src/main/java/me/jahnen/libaums/core/usbfileman/MainActivity.kt | 2 | 37623 | /*
* (C) Copyright 2014-2016 mjahnen <[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 me.jahnen.libaums.core.usbfileman
import android.Manifest
import android.app.*
import android.content.*
import android.content.pm.PackageManager
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.net.Uri
import android.os.*
import android.provider.OpenableColumns
import android.util.Log
import android.view.ContextMenu
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.webkit.MimeTypeMap
import android.widget.*
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.documentfile.provider.DocumentFile
import androidx.drawerlayout.widget.DrawerLayout
import me.jahnen.libaums.javafs.JavaFsFileSystemCreator
import me.jahnen.libaums.core.UsbMassStorageDevice
import me.jahnen.libaums.core.UsbMassStorageDevice.Companion.getMassStorageDevices
import me.jahnen.libaums.core.fs.FileSystem
import me.jahnen.libaums.core.fs.FileSystemFactory.registerFileSystem
import me.jahnen.libaums.core.fs.UsbFile
import me.jahnen.libaums.core.fs.UsbFileInputStream
import me.jahnen.libaums.core.fs.UsbFileStreamFactory.createBufferedOutputStream
import me.jahnen.libaums.server.http.UsbFileHttpServerService
import me.jahnen.libaums.server.http.UsbFileHttpServerService.ServiceBinder
import me.jahnen.libaums.server.http.server.AsyncHttpServer
import me.jahnen.libaums.core.usb.UsbCommunicationFactory
import me.jahnen.libaums.core.usb.UsbCommunicationFactory.registerCommunication
import me.jahnen.libaums.core.usb.UsbCommunicationFactory.underlyingUsbCommunication
import me.jahnen.libaums.libusbcommunication.LibusbCommunicationCreator
import java.io.*
import java.nio.ByteBuffer
import java.util.*
/**
* MainActivity of the demo application which shows the contents of the first
* partition.
*
* @author mjahnen
*/
class MainActivity : AppCompatActivity(), AdapterView.OnItemClickListener {
companion object {
/**
* Action string to request the permission to communicate with an UsbDevice.
*/
private const val ACTION_USB_PERMISSION = "me.jahnen.libaums.USB_PERMISSION"
private val TAG = MainActivity::class.java.simpleName
private const val COPY_STORAGE_PROVIDER_RESULT = 0
private const val OPEN_STORAGE_PROVIDER_RESULT = 1
private const val OPEN_DOCUMENT_TREE_RESULT = 2
private const val REQUEST_EXT_STORAGE_WRITE_PERM = 0
init {
registerFileSystem(JavaFsFileSystemCreator())
registerCommunication(LibusbCommunicationCreator())
underlyingUsbCommunication = UsbCommunicationFactory.UnderlyingUsbCommunication.OTHER
}
}
private val usbReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (ACTION_USB_PERMISSION == action) {
val device = intent.getParcelableExtra<Parcelable>(UsbManager.EXTRA_DEVICE) as UsbDevice?
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
setupDevice()
}
}
} else if (UsbManager.ACTION_USB_DEVICE_ATTACHED == action) {
val device = intent.getParcelableExtra<Parcelable>(UsbManager.EXTRA_DEVICE) as UsbDevice?
Log.d(TAG, "USB device attached")
// determine if connected device is a mass storage devuce
if (device != null) {
discoverDevice()
}
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED == action) {
val device = intent.getParcelableExtra<Parcelable>(UsbManager.EXTRA_DEVICE) as UsbDevice?
Log.d(TAG, "USB device detached")
// determine if connected device is a mass storage devuce
if (device != null) {
if (currentDevice != -1) {
massStorageDevices[currentDevice].close()
}
// check if there are other devices or set action bar title
// to no device if not
discoverDevice()
}
}
}
}
/**
* Dialog to create new directories.
*
* @author mjahnen
*/
class NewDirDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val activity = activity as MainActivity
return AlertDialog.Builder(activity).apply {
setTitle("New Directory")
setMessage("Please enter a name for the new directory")
val input = EditText(activity)
setView(input)
setPositiveButton("Ok") { _, _ ->
val dir = activity.adapter.currentDir
try {
dir.createDirectory(input.text.toString())
activity.adapter.refresh()
} catch (e: Exception) {
Log.e(TAG, "error creating dir!", e)
}
}
setNegativeButton("Cancel") { dialog, _ -> dialog.dismiss() }
setCancelable(false)
}.create()
}
}
/**
* Dialog to create new files.
*
* @author mjahnen
*/
class NewFileDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val activity = activity as MainActivity
return AlertDialog.Builder(activity).apply {
setTitle("New File")
setMessage("Please enter a name for the new file and some input")
val input = EditText(activity)
val content = EditText(activity)
setView(
LinearLayout(activity).apply {
orientation = LinearLayout.VERTICAL
addView(TextView(activity).apply { setText(R.string.name) })
addView(input)
addView(TextView(activity).apply { setText(R.string.content) })
addView(content)
}
)
setPositiveButton("Ok") { _, _ ->
val dir = activity.adapter.currentDir
try {
val file = dir.createFile(input.text.toString())
file.write(0, ByteBuffer.wrap(content.text.toString().toByteArray()))
file.close()
activity.adapter.refresh()
} catch (e: Exception) {
Log.e(TAG, "error creating file!", e)
}
}
setNegativeButton("Cancel") { dialog, _ -> dialog.dismiss() }
setCancelable(false)
}.create()
}
}
/**
* Class to hold the files for a copy task. Holds the source and the
* destination file.
*
* @author mjahnen
*/
private class CopyTaskParam {
/* package */
var from: UsbFile? = null
/* package */
var to: File? = null
}
/**
* Asynchronous task to copy a file from the mass storage device connected
* via USB to the internal storage.
*
* @author mjahnen
*/
private inner class CopyTask : AsyncTask<CopyTaskParam?, Int?, Void?>() {
private val dialog: ProgressDialog = ProgressDialog(this@MainActivity).apply {
setTitle("Copying file")
setMessage("Copying a file to the internal storage, this can take some time!")
isIndeterminate = false
setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
setCancelable(false)
}
private var param: CopyTaskParam? = null
override fun onPreExecute() {
dialog.show()
}
protected override fun doInBackground(vararg params: CopyTaskParam?): Void? {
val time = System.currentTimeMillis()
param = params[0]
try {
val out: OutputStream = BufferedOutputStream(FileOutputStream(param!!.to))
val inputStream: InputStream = UsbFileInputStream(param!!.from!!)
val bytes = ByteArray(currentFs.chunkSize)
var count: Int
var total: Long = 0
Log.d(TAG, "Copy file with length: " + param!!.from!!.length)
while (inputStream.read(bytes).also { count = it } != -1) {
out.write(bytes, 0, count)
total += count.toLong()
var progress = total.toInt()
if (param!!.from!!.length > Int.MAX_VALUE) {
progress = (total / 1024).toInt()
}
publishProgress(progress)
}
out.close()
inputStream.close()
} catch (e: IOException) {
Log.e(TAG, "error copying!", e)
}
Log.d(TAG, "copy time: " + (System.currentTimeMillis() - time))
return null
}
override fun onPostExecute(result: Void?) {
dialog.dismiss()
val myIntent = Intent(Intent.ACTION_VIEW)
val file = File(param!!.to!!.absolutePath)
val extension = MimeTypeMap.getFileExtensionFromUrl(Uri
.fromFile(file).toString())
val mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
extension)
val uri: Uri
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
myIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
uri = FileProvider.getUriForFile(this@MainActivity,
[email protected] + ".provider",
file)
} else {
uri = Uri.fromFile(file)
}
myIntent.setDataAndType(uri, mimetype)
try {
startActivity(myIntent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this@MainActivity, "Could no find an app for that file!",
Toast.LENGTH_LONG).show()
}
}
protected override fun onProgressUpdate(vararg values: Int?) {
var max = param!!.from!!.length.toInt()
if (param!!.from!!.length > Int.MAX_VALUE) {
max = (param!!.from!!.length / 1024).toInt()
}
dialog.max = max
dialog.progress = values[0]!!
}
}
/**
* Class to hold the files for a copy task. Holds the source and the
* destination file.
*
* @author mjahnen
*/
private class CopyToUsbTaskParam {
/* package */
var from: Uri? = null
}
/**
* Asynchronous task to copy a file from the mass storage device connected
* via USB to the internal storage.
*
* @author mjahnen
*/
private inner class CopyToUsbTask : AsyncTask<CopyToUsbTaskParam?, Int?, Void?>() {
private val dialog: ProgressDialog = ProgressDialog(this@MainActivity).apply {
setTitle("Copying file")
setMessage("Copying a file to the USB drive, this can take some time!")
isIndeterminate = true
setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
setCancelable(false)
}
private var param: CopyToUsbTaskParam? = null
private var name: String? = null
private var size: Long = -1
private fun queryUriMetaData(uri: Uri?) {
contentResolver
.query(uri!!, null, null, null, null, null)
?.apply {
if (moveToFirst()) {
// TODO: query created and modified times to write it USB
name = getString(
getColumnIndex(OpenableColumns.DISPLAY_NAME))
Log.i(TAG, "Display Name: $name")
val sizeIndex = getColumnIndex(OpenableColumns.SIZE)
if (!isNull(sizeIndex)) {
size = getLong(sizeIndex)
}
Log.i(TAG, "Size: $size")
}
}
?.close()
}
override fun onPreExecute() = dialog.show()
protected override fun doInBackground(vararg params: CopyToUsbTaskParam?): Void? {
val time = System.currentTimeMillis()
param = params[0]
queryUriMetaData(param!!.from)
if (name == null) {
val segments = param!!.from!!.path!!.split("/".toRegex()).toTypedArray()
name = segments[segments.size - 1]
}
try {
val file = adapter.currentDir.createFile(name!!)
if (size > 0) {
file.length = size
}
val inputStream = contentResolver.openInputStream(param!!.from!!)
val outputStream: OutputStream = createBufferedOutputStream(file, currentFs)
val bytes = ByteArray(1337)
var count: Int
var total: Long = 0
while (inputStream!!.read(bytes).also { count = it } != -1) {
outputStream.write(bytes, 0, count)
if (size > 0) {
total += count.toLong()
var progress = total.toInt()
if (size > Int.MAX_VALUE) {
progress = (total / 1024).toInt()
}
publishProgress(progress)
}
}
outputStream.close()
inputStream.close()
} catch (e: IOException) {
Log.e(TAG, "error copying!", e)
}
Log.d(TAG, "copy time: " + (System.currentTimeMillis() - time))
return null
}
override fun onPostExecute(result: Void?) {
dialog.dismiss()
try {
adapter.refresh()
} catch (e: IOException) {
Log.e(TAG, "Error refreshing adapter", e)
}
}
protected override fun onProgressUpdate(vararg values: Int?) {
dialog.isIndeterminate = false
var max = size.toInt()
if (size > Int.MAX_VALUE) {
max = (size / 1024).toInt()
}
dialog.max = max
dialog.progress = values[0]!!
}
}
/**
* Asynchronous task to copy a file from the mass storage device connected
* via USB to the internal storage.
*
* @author mjahnen
*/
private inner class CopyFolderToUsbTask : AsyncTask<CopyToUsbTaskParam?, Int?, Void?>() {
private val dialog: ProgressDialog = ProgressDialog(this@MainActivity).apply {
setTitle("Copying a folder")
setMessage("Copying a folder to the USB drive, this can take some time!")
isIndeterminate = true
setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
setCancelable(false)
}
private var param: CopyToUsbTaskParam? = null
private var size: Long = -1
private var pickedDir: DocumentFile? = null
override fun onPreExecute() {
dialog.show()
}
@Throws(IOException::class)
private fun copyDir(dir: DocumentFile?, currentUsbDir: UsbFile) {
for (file in dir!!.listFiles()) {
Log.d(TAG, "Found file " + file.name + " with size " + file.length())
if (file.isDirectory) {
copyDir(file, currentUsbDir.createDirectory(file.name!!))
} else {
copyFile(file, currentUsbDir)
}
}
}
private fun copyFile(file: DocumentFile, currentUsbDir: UsbFile) {
try {
val usbFile = currentUsbDir.createFile(file.name!!)
size = file.length()
usbFile.length = file.length()
val inputStream = contentResolver.openInputStream(file.uri)
val outputStream: OutputStream = createBufferedOutputStream(usbFile, currentFs!!)
val bytes = ByteArray(1337)
var count: Int
var total: Long = 0
while (inputStream!!.read(bytes).also { count = it } != -1) {
outputStream.write(bytes, 0, count)
if (size > 0) {
total += count.toLong()
var progress = total.toInt()
if (file.length() > Int.MAX_VALUE) {
progress = (total / 1024).toInt()
}
publishProgress(progress)
}
}
outputStream.close()
inputStream.close()
} catch (e: IOException) {
Log.e(TAG, "error copying!", e)
}
}
protected override fun doInBackground(vararg params: CopyToUsbTaskParam?): Void? {
val time = System.currentTimeMillis()
param = params[0]
pickedDir = DocumentFile.fromTreeUri(this@MainActivity, param!!.from!!)
try {
copyDir(pickedDir, adapter.currentDir.createDirectory(pickedDir!!.name!!))
} catch (e: IOException) {
Log.e(TAG, "could not copy directory", e)
}
Log.d(TAG, "copy time: " + (System.currentTimeMillis() - time))
return null
}
override fun onPostExecute(result: Void?) {
dialog.dismiss()
try {
adapter.refresh()
} catch (e: IOException) {
Log.e(TAG, "Error refreshing adapter", e)
}
}
protected override fun onProgressUpdate(vararg values: Int?) {
dialog.apply {
isIndeterminate = false
max = size.toInt()
if (size > Int.MAX_VALUE) {
max = (size / 1024).toInt()
}
progress = values[0]!!
}
}
}
private var serviceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
Log.d(TAG, "on service connected $name")
val binder = service as ServiceBinder
serverService = binder.service
}
override fun onServiceDisconnected(name: ComponentName) {
Log.d(TAG, "on service disconnected $name")
serverService = null
}
}
lateinit var listView: ListView
lateinit var drawerListView: ListView
lateinit var drawerLayout: DrawerLayout
lateinit var drawerToggle: ActionBarDrawerToggle
/* package */
lateinit var adapter: UsbFileListAdapter
private val dirs: Deque<UsbFile> = ArrayDeque()
lateinit var currentFs: FileSystem
lateinit var serviceIntent: Intent
var serverService: UsbFileHttpServerService? = null
lateinit var massStorageDevices: Array<UsbMassStorageDevice>
private var currentDevice = -1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
serviceIntent = Intent(this, UsbFileHttpServerService::class.java)
setContentView(R.layout.activity_main)
listView = findViewById<View>(R.id.listview) as ListView
drawerListView = findViewById<View>(R.id.left_drawer) as ListView
drawerLayout = findViewById<View>(R.id.drawer_layout) as DrawerLayout
drawerToggle = object : ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
override fun onDrawerClosed(view: View) {
super.onDrawerClosed(view)
supportActionBar!!.setTitle(massStorageDevices[currentDevice].partitions[0].volumeLabel)
}
/** Called when a drawer has settled in a completely open state. */
override fun onDrawerOpened(drawerView: View) {
super.onDrawerOpened(drawerView)
supportActionBar!!.setTitle("Devices")
}
}
// Set the drawer toggle as the DrawerListener
drawerLayout.addDrawerListener(drawerToggle)
drawerListView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
selectDevice(position)
drawerLayout.closeDrawer(drawerListView)
drawerListView.setItemChecked(position, true)
}
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setHomeButtonEnabled(true)
listView.onItemClickListener = this
registerForContextMenu(listView)
val filter = IntentFilter(ACTION_USB_PERMISSION)
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
registerReceiver(usbReceiver, filter)
discoverDevice()
}
override fun onStart() {
super.onStart()
startService(serviceIntent)
bindService(serviceIntent, serviceConnection, BIND_AUTO_CREATE)
}
override fun onStop() {
super.onStop()
unbindService(serviceConnection)
}
private fun selectDevice(position: Int) {
currentDevice = position
setupDevice()
}
/**
* Searches for connected mass storage devices, and initializes them if it
* could find some.
*/
private fun discoverDevice() {
val usbManager = getSystemService(USB_SERVICE) as UsbManager
massStorageDevices = getMassStorageDevices(this)
if (massStorageDevices.isEmpty()) {
Log.w(TAG, "no device found!")
val actionBar = supportActionBar
actionBar!!.title = "No device"
listView.adapter = null
return
}
drawerListView.adapter = DrawerListAdapter(this, R.layout.drawer_list_item, massStorageDevices)
drawerListView.setItemChecked(0, true)
currentDevice = 0
val usbDevice = intent.getParcelableExtra<Parcelable>(UsbManager.EXTRA_DEVICE) as UsbDevice?
if (usbDevice != null && usbManager.hasPermission(usbDevice)) {
Log.d(TAG, "received usb device via intent")
// requesting permission is not needed in this case
setupDevice()
} else {
// first request permission from user to communicate with the underlying UsbDevice
val permissionIntent = PendingIntent.getBroadcast(this, 0, Intent(
ACTION_USB_PERMISSION), 0)
usbManager.requestPermission(massStorageDevices[currentDevice].usbDevice, permissionIntent)
}
}
/**
* Sets the device up and shows the contents of the root directory.
*/
private fun setupDevice() {
try {
massStorageDevices[currentDevice].init()
// we always use the first partition of the device
currentFs = massStorageDevices[currentDevice].partitions[0].fileSystem.also {
Log.d(TAG, "Capacity: " + it.capacity)
Log.d(TAG, "Occupied Space: " + it.occupiedSpace)
Log.d(TAG, "Free Space: " + it.freeSpace)
Log.d(TAG, "Chunk size: " + it.chunkSize)
}
val root = currentFs.rootDirectory
val actionBar = supportActionBar
actionBar!!.title = currentFs.volumeLabel
listView.adapter = UsbFileListAdapter(this, root).apply { adapter = this }
} catch (e: IOException) {
Log.e(TAG, "error setting up device", e)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
val cl = MoveClipboard
menu.findItem(R.id.paste).isEnabled = cl?.file != null
menu.findItem(R.id.stop_http_server).isEnabled = serverService != null && serverService!!.isServerRunning
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return if (drawerToggle.onOptionsItemSelected(item)) {
true
} else when (item.itemId) {
R.id.create_file -> {
NewFileDialog().show(fragmentManager, "NEW_FILE")
true
}
R.id.create_dir -> {
NewDirDialog().show(fragmentManager, "NEW_DIR")
true
}
R.id.create_big_file -> {
createBigFile()
true
}
R.id.paste -> {
move()
true
}
R.id.stop_http_server -> {
if (serverService != null) {
serverService!!.stopServer()
}
true
}
R.id.open_storage_provider -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (currentDevice != -1) {
Log.d(TAG, "Closing device first")
massStorageDevices[currentDevice].close()
}
val intent = Intent()
intent.action = Intent.ACTION_OPEN_DOCUMENT
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "*/*"
val extraMimeTypes = arrayOf("image/*", "video/*")
intent.putExtra(Intent.EXTRA_MIME_TYPES, extraMimeTypes)
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
startActivityForResult(intent, OPEN_STORAGE_PROVIDER_RESULT)
}
true
}
R.id.copy_from_storage_provider -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
val intent = Intent()
intent.action = Intent.ACTION_OPEN_DOCUMENT
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "*/*"
startActivityForResult(intent, COPY_STORAGE_PROVIDER_RESULT)
}
true
}
R.id.copy_folder_from_storage_provider -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val intent = Intent()
intent.action = Intent.ACTION_OPEN_DOCUMENT_TREE
startActivityForResult(intent, OPEN_DOCUMENT_TREE_RESULT)
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenu.ContextMenuInfo) {
super.onCreateContextMenu(menu, v, menuInfo)
val inflater = menuInflater
inflater.inflate(R.menu.context, menu)
}
override fun onContextItemSelected(item: MenuItem): Boolean {
val info = item.menuInfo as AdapterView.AdapterContextMenuInfo
val entry = adapter.getItem(info.id.toInt())
return when (item.itemId) {
R.id.delete_item -> {
try {
entry!!.delete()
adapter.refresh()
} catch (e: IOException) {
Log.e(TAG, "error deleting!", e)
}
true
}
R.id.rename_item -> {
AlertDialog.Builder(this).apply {
setTitle("Rename")
setMessage("Please enter a name for renaming")
val input = EditText(this@MainActivity)
input.setText(entry!!.name)
setView(input)
setPositiveButton("Ok") { _, _ ->
try {
entry.name = input.text.toString()
adapter.refresh()
} catch (e: IOException) {
Log.e(TAG, "error renaming!", e)
}
}
setNegativeButton("Cancel") { dialog, _ -> dialog.dismiss() }
setCancelable(false)
create()
show()
}
true
}
R.id.move_item -> {
val cl = MoveClipboard
cl.file = entry
true
}
R.id.start_http_server -> {
startHttpServer(entry)
true
}
else -> super.onContextItemSelected(item)
}
}
override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, rowId: Long) {
val entry = adapter.getItem(position)
try {
if (entry.isDirectory) {
dirs.push(adapter.currentDir)
listView.adapter = UsbFileListAdapter(this, entry).also { adapter = it }
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, R.string.request_write_storage_perm, Toast.LENGTH_LONG).show()
} else {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
REQUEST_EXT_STORAGE_WRITE_PERM)
}
return
}
val param = CopyTaskParam()
param.from = entry
val f = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
File(getExternalFilesDir(null)!!.absolutePath + "/usbfileman/cache")
} else {
File(Environment.getExternalStorageDirectory().absolutePath + "/usbfileman/cache")
}
f.mkdirs()
val index = if (entry.name.lastIndexOf(".") > 0) entry.name.lastIndexOf(".") else entry.name.length
var prefix = entry.name.substring(0, index)
val ext = entry.name.substring(index)
// prefix must be at least 3 characters
if (prefix.length < 3) {
prefix += "pad"
}
param.to = File.createTempFile(prefix, ext, f)
CopyTask().execute(param)
}
} catch (e: IOException) {
Log.e(TAG, "error starting to copy!", e)
}
}
private fun startHttpServer(file: UsbFile?) {
Log.d(TAG, "starting HTTP server")
if (serverService == null) {
Toast.makeText(this@MainActivity, "serverService == null!", Toast.LENGTH_LONG).show()
return
}
if (serverService!!.isServerRunning) {
Log.d(TAG, "Stopping existing server service")
serverService!!.stopServer()
}
// now start the server
try {
serverService!!.startServer(file!!, AsyncHttpServer(8000))
Toast.makeText(this@MainActivity, "HTTP server up and running", Toast.LENGTH_LONG).show()
} catch (e: IOException) {
Log.e(TAG, "Error starting HTTP server", e)
Toast.makeText(this@MainActivity, "Could not start HTTP server", Toast.LENGTH_LONG).show()
}
if (file!!.isDirectory) {
// only open activity when serving a file
return
}
val myIntent = Intent(Intent.ACTION_VIEW)
myIntent.data = Uri.parse(serverService!!.server!!.baseUrl + file.name)
try {
startActivity(myIntent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this@MainActivity, "Could no find an app for that file!",
Toast.LENGTH_LONG).show()
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
REQUEST_EXT_STORAGE_WRITE_PERM -> {
// If request is cancelled, the result arrays are empty.
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, R.string.permission_granted, Toast.LENGTH_LONG).show()
} else {
Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_LONG).show()
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
super.onActivityResult(requestCode, resultCode, intent)
if (requestCode == RESULT_OK) {
Log.w(TAG, "Activity result is not ok")
return
}
if (intent == null) {
return
}
Log.i(TAG, "Uri: " + intent.data.toString())
val newIntent = Intent(Intent.ACTION_VIEW).apply { data = intent.data }
val params = CopyToUsbTaskParam().apply { from = intent.data }
when (requestCode) {
OPEN_STORAGE_PROVIDER_RESULT -> startActivity(newIntent)
COPY_STORAGE_PROVIDER_RESULT -> CopyToUsbTask().execute(params)
OPEN_DOCUMENT_TREE_RESULT -> CopyFolderToUsbTask().execute(params)
}
}
/**
* This methods creates a very big file for testing purposes. It writes only
* a small chunk of bytes in every loop iteration, so the offset where the
* write starts will not always be a multiple of the cluster or block size
* of the file system or block device. As a plus the file has to be grown
* after every loop iteration which tests for example on FAT32 the dynamic
* growth of a cluster chain.
*/
private fun createBigFile() {
val dir = adapter.currentDir
val file: UsbFile
try {
file = dir.createFile("big_file_test.txt")
val outputStream: OutputStream = createBufferedOutputStream(file, currentFs)
outputStream.write("START\n".toByteArray())
var i: Int
i = 6
while (i < 9000) {
outputStream.write("TEST\n".toByteArray())
i += 5
}
outputStream.write("END\n".toByteArray())
outputStream.close()
adapter.refresh()
} catch (e: IOException) {
Log.e(TAG, "error creating big file!", e)
}
}
/**
* This method moves the file located in the [MoveClipboard] into the
* current shown directory.
*/
private fun move() {
val cl = MoveClipboard
val file = cl.file
try {
file?.moveTo(adapter.currentDir)
adapter.refresh()
} catch (e: IOException) {
Log.e(TAG, "error moving!", e)
}
cl.file = null
}
override fun onBackPressed() {
try {
val dir = dirs.pop()
listView.adapter = UsbFileListAdapter(this, dir).also { adapter = it }
} catch (e: NoSuchElementException) {
super.onBackPressed()
} catch (e: IOException) {
Log.e(TAG, "error initializing adapter!", e)
}
}
public override fun onDestroy() {
super.onDestroy()
unregisterReceiver(usbReceiver)
if (!serverService!!.isServerRunning) {
Log.d(TAG, "Stopping service")
stopService(serviceIntent)
if (currentDevice != -1) {
Log.d(TAG, "Closing device")
massStorageDevices[currentDevice].close()
}
}
}
} | apache-2.0 | 0afd54ae35d527e39577a7639ccd46e6 | 39.110874 | 116 | 0.553598 | 5.083502 | false | false | false | false |
crunchersaspire/worshipsongs-android | app/src/main/java/org/worshipsongs/service/ExternalImportDatabaseService.kt | 3 | 1200 | package org.worshipsongs.service
import android.content.Intent
import android.net.Uri
import android.os.Environment
import androidx.appcompat.app.AppCompatActivity
import org.worshipsongs.service.ImportDatabaseService
/**
* Author : Madasamy
* Version : 3.x
*/
class ExternalImportDatabaseService : ImportDatabaseService
{
private var objects: Map<String, Any>? = null
private var appCompatActivity: AppCompatActivity? = null
override fun loadDb(appCompatActivity: AppCompatActivity, objects: Map<String, Any>)
{
this.appCompatActivity = appCompatActivity
this.objects = objects
showFileChooser()
}
private fun showFileChooser()
{
val intent = Intent(Intent.ACTION_GET_CONTENT)
val uri = Uri.parse(Environment.getExternalStorageDirectory().path)
intent.setDataAndType(uri, "*/*")
try
{
appCompatActivity!!.startActivityForResult(Intent.createChooser(intent, "Select a File to Import"), 1)
} catch (ex: android.content.ActivityNotFoundException)
{
}
}
override val name: String get() = this.javaClass.simpleName
override val order: Int get() = 1
}
| gpl-3.0 | 2f41070e9efcf8a21767e17562741838 | 25.666667 | 114 | 0.696667 | 4.761905 | false | false | false | false |
FHannes/intellij-community | platform/lang-impl/src/com/intellij/openapi/module/impl/moduleFileListener.kt | 1 | 4713 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.module.impl
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.impl.ModuleRootManagerImpl
import com.intellij.openapi.roots.impl.storage.ClasspathStorage
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent
import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent
import com.intellij.util.PathUtilRt
import gnu.trove.THashSet
/**
* Why this class is required if we have StorageVirtualFileTracker?
* Because StorageVirtualFileTracker doesn't detect (intentionally) parent file changes -
*
* If module file is foo/bar/hello.iml and directory foo is renamed to oof then we must update module path.
* And StorageVirtualFileTracker doesn't help us here (and is not going to help by intention).
*/
internal class ModuleFileListener(private val moduleManager: ModuleManagerComponent) : BulkFileListener {
override fun after(events: List<VFileEvent>) {
for (event in events) {
when (event) {
is VFilePropertyChangeEvent -> propertyChanged(event)
is VFileMoveEvent -> fileMoved(event)
}
}
}
private fun propertyChanged(event: VFilePropertyChangeEvent) {
if (!event.file.isDirectory || event.requestor is StateStorage || event.propertyName != VirtualFile.PROP_NAME) {
return
}
val parentPath = event.file.parent?.path ?: return
var someModulePathIsChanged = false
val newAncestorPath = "${parentPath}/${event.newValue}"
for (module in moduleManager.modules) {
if (!module.isLoaded || module.isDisposed) {
continue
}
val ancestorPath = "$parentPath/${event.oldValue}"
val moduleFilePath = module.moduleFilePath
if (FileUtil.isAncestor(ancestorPath, moduleFilePath, true)) {
setModuleFilePath(module, "$newAncestorPath/${FileUtil.getRelativePath(ancestorPath, moduleFilePath, '/')}")
someModulePathIsChanged = true
}
// if ancestor path is a direct parent of module file - root will be serialized as $MODULE_DIR$ and, so, we don't need to mark it as changed to save
if (PathUtilRt.getParentPath(moduleFilePath) != ancestorPath) {
checkRootModification(module, newAncestorPath)
}
}
if (someModulePathIsChanged) {
moduleManager.incModificationCount()
}
}
private fun fileMoved(event: VFileMoveEvent) {
if (!event.file.isDirectory) {
return
}
val dirName = event.file.nameSequence
val ancestorPath = "${event.oldParent.path}/$dirName"
val newAncestorPath = "${event.newParent.path}/$dirName"
for (module in moduleManager.modules) {
if (!module.isLoaded || module.isDisposed) {
continue
}
val moduleFilePath = module.moduleFilePath
if (FileUtil.isAncestor(ancestorPath, moduleFilePath, true)) {
setModuleFilePath(module, "${event.newParent.path}/$dirName/${FileUtil.getRelativePath(ancestorPath, moduleFilePath, '/')}")
}
checkRootModification(module, newAncestorPath)
}
}
// https://youtrack.jetbrains.com/issue/IDEA-168933
private fun checkRootModification(module: Module, newAncestorPath: String) {
val moduleRootManager = module.rootManager as? ModuleRootManagerImpl ?: return
val roots = THashSet<String>()
moduleRootManager.contentRootUrls.forEach { roots.add(VfsUtilCore.urlToPath(it)) }
moduleRootManager.sourceRootUrls.forEach { roots.add(VfsUtilCore.urlToPath(it)) }
if (roots.contains(newAncestorPath)) {
moduleRootManager.stateChanged()
}
}
private fun setModuleFilePath(module: Module, newFilePath: String) {
ClasspathStorage.modulePathChanged(module, newFilePath)
module.stateStore.setPath(newFilePath)
}
} | apache-2.0 | 1caad2adc0fd6d6bc4432672034e0c9c | 38.283333 | 154 | 0.739656 | 4.471537 | false | false | false | false |
DSolyom/ViolinDS | ViolinDS/app/src/main/java/ds/violin/v1/app/violin/GoogleApiViolin.kt | 1 | 2225 | /*
Copyright 2016 Dániel Sólyom
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 ds.violin.v1.app.violin
import android.content.Context
import android.os.Bundle
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.Api
import com.google.android.gms.common.api.GoogleApiClient
/**
* Basic interface to use [GoogleApiClient] in Violins
*/
interface GoogleApiViolin {
/** = ArrayList(), required Apis */
val requiredApis: MutableList<Api<*>>
/** = null, #Private */
var googleApiClient: GoogleApiClient?
fun onCreate(savedInstanceState: Bundle?) {
if (!requiredApis.isEmpty() && googleApiClient == null) {
val builder = GoogleApiClient.Builder((this as PlayingViolin).violinActivity as Context)
.addConnectionCallbacks(object : GoogleApiClient.ConnectionCallbacks {
override fun onConnectionSuspended(p0: Int) {
}
override fun onConnected(connectionHint: Bundle?) {
onGoogleApiConnected(connectionHint)
}
})
.addOnConnectionFailedListener { result -> onGoogleApiConnectionFailed(result) }
for(api in requiredApis) {
builder.addApi(api as Api<Api.ApiOptions.NotRequiredOptions>)
}
googleApiClient = builder.build()
}
}
fun onStart() {
googleApiClient?.connect()
}
fun onStop() {
googleApiClient?.disconnect()
}
fun onGoogleApiConnected(connectionHint: Bundle?)
fun onGoogleApiConnectionFailed(result: ConnectionResult)
} | apache-2.0 | ffd8734ec82041f74b540e7f6a6960d3 | 31.231884 | 100 | 0.65722 | 4.984305 | false | false | false | false |
TeamAmaze/AmazeFileManager | app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractCompressedFileExtractorTest.kt | 1 | 3053 | /*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.filesystem.compressed.extractcontents
import android.content.Context
import android.os.Environment
import androidx.test.core.app.ApplicationProvider
import com.amaze.filemanager.asynchronous.management.ServiceWatcherUtil
import com.amaze.filemanager.fileoperations.utils.UpdatePosition
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import java.io.File
import java.util.concurrent.CountDownLatch
abstract class AbstractCompressedFileExtractorTest : AbstractExtractorTest() {
@Throws(Exception::class)
override fun doTestExtractFiles() {
val latch = CountDownLatch(1)
val extractor = extractorClass()
.getConstructor(
Context::class.java,
String::class.java,
String::class.java,
Extractor.OnUpdate::class.java,
UpdatePosition::class.java
)
.newInstance(
ApplicationProvider.getApplicationContext(),
archiveFile.absolutePath,
Environment.getExternalStorageDirectory().absolutePath,
object : Extractor.OnUpdate {
override fun onStart(totalBytes: Long, firstEntryName: String) = Unit
override fun onUpdate(entryPath: String) = Unit
override fun isCancelled(): Boolean = false
override fun onFinish() {
latch.countDown()
}
},
ServiceWatcherUtil.UPDATE_POSITION
)
extractor.extractEverything()
latch.await()
verifyExtractedArchiveContents()
}
private fun verifyExtractedArchiveContents() {
Environment.getExternalStorageDirectory().run {
File(this, "test.txt").let {
assertTrue(it.exists())
assertEquals("abcdefghijklmnopqrstuvwxyz1234567890", it.readText().trim())
}
}
}
override val archiveFile: File
get() = File(Environment.getExternalStorageDirectory(), "test.txt.$archiveType")
}
| gpl-3.0 | 90959245f155c554b81583addf860da5 | 39.171053 | 107 | 0.666557 | 5.122483 | false | true | false | false |
googlearchive/android-constraint-layout-performance | app/src/main/java/com/example/android/perf/MainActivity.kt | 1 | 6406 | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.example.android.perf
import android.annotation.SuppressLint
import android.os.AsyncTask
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.FrameMetrics
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.Button
import android.widget.TextView
import java.lang.ref.WeakReference
class MainActivity : AppCompatActivity() {
private val frameMetricsHandler = Handler()
private val frameMetricsAvailableListener = Window.OnFrameMetricsAvailableListener {
_, frameMetrics, _ ->
val frameMetricsCopy = FrameMetrics(frameMetrics)
// Layout measure duration in Nano seconds
val layoutMeasureDurationNs = frameMetricsCopy.getMetric(FrameMetrics.LAYOUT_MEASURE_DURATION)
Log.d(TAG, "layoutMeasureDurationNs: " + layoutMeasureDurationNs)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_for_test)
val traditionalCalcButton = findViewById<Button>(R.id.button_start_calc_traditional)
val constraintCalcButton = findViewById<Button>(R.id.button_start_calc_constraint)
val textViewFinish = findViewById<TextView>(R.id.textview_finish)
traditionalCalcButton.setOnClickListener {
@SuppressLint("InflateParams")
constraintCalcButton.visibility = View.INVISIBLE
val container = layoutInflater
.inflate(R.layout.activity_traditional, null) as ViewGroup
val asyncTask = MeasureLayoutAsyncTask(
getString(R.string.executing_nth_iteration),
WeakReference(traditionalCalcButton),
WeakReference(textViewFinish),
WeakReference(container))
asyncTask.execute()
}
constraintCalcButton.setOnClickListener {
@SuppressLint("InflateParams")
traditionalCalcButton.visibility = View.INVISIBLE
val container = layoutInflater
.inflate(R.layout.activity_constraintlayout, null) as ViewGroup
val asyncTask = MeasureLayoutAsyncTask(
getString(R.string.executing_nth_iteration),
WeakReference(constraintCalcButton),
WeakReference(textViewFinish),
WeakReference(container))
asyncTask.execute()
}
}
override fun onResume() {
super.onResume()
window.addOnFrameMetricsAvailableListener(frameMetricsAvailableListener, frameMetricsHandler)
}
override fun onPause() {
super.onPause()
window.removeOnFrameMetricsAvailableListener(frameMetricsAvailableListener)
}
/**
* AsyncTask that triggers measure/layout in the background. Not to leak the Context of the
* Views, take the View instances as WeakReferences.
*/
private class MeasureLayoutAsyncTask(val executingNthIteration: String,
val startButtonRef: WeakReference<Button>,
val finishTextViewRef: WeakReference<TextView>,
val containerRef: WeakReference<ViewGroup>) : AsyncTask<Void?, Int, Void?>() {
override fun doInBackground(vararg voids: Void?): Void? {
for (i in 0 until TOTAL) {
publishProgress(i)
try {
Thread.sleep(100)
} catch (ignore: InterruptedException) {
// No op
}
}
return null
}
override fun onProgressUpdate(vararg values: Int?) {
val startButton = startButtonRef.get() ?: return
startButton.text = String.format(executingNthIteration, values[0], TOTAL)
val container = containerRef.get() ?: return
// Not to use the view cache in the View class, use the different measureSpecs
// for each calculation. (Switching the
// View.MeasureSpec.EXACT and View.MeasureSpec.AT_MOST alternately)
measureAndLayoutExactLength(container)
measureAndLayoutWrapLength(container)
}
override fun onPostExecute(aVoid: Void?) {
val finishTextView = finishTextViewRef.get() ?: return
finishTextView.visibility = View.VISIBLE
val startButton = startButtonRef.get() ?: return
startButton.visibility = View.GONE
}
private fun measureAndLayoutWrapLength(container: ViewGroup) {
val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(WIDTH,
View.MeasureSpec.AT_MOST)
val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(HEIGHT,
View.MeasureSpec.AT_MOST)
container.measure(widthMeasureSpec, heightMeasureSpec)
container.layout(0, 0, container.measuredWidth,
container.measuredHeight)
}
private fun measureAndLayoutExactLength(container: ViewGroup) {
val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(WIDTH,
View.MeasureSpec.EXACTLY)
val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(HEIGHT,
View.MeasureSpec.EXACTLY)
container.measure(widthMeasureSpec, heightMeasureSpec)
container.layout(0, 0, container.measuredWidth,
container.measuredHeight)
}
}
companion object {
private val TAG = "MainActivity"
private val TOTAL = 100
private val WIDTH = 1920
private val HEIGHT = 1080
}
}
| apache-2.0 | d7f02afeb06d379f70be10866745ce97 | 39.289308 | 119 | 0.650328 | 5.401349 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/data/ContentProviderDao.kt | 1 | 1499 | package org.tasks.data
import android.database.Cursor
import androidx.room.Dao
import androidx.room.Query
import androidx.room.RawQuery
import androidx.sqlite.db.SupportSQLiteQuery
import com.todoroo.astrid.data.Task
@Dao
interface ContentProviderDao {
@Query("SELECT name FROM tags WHERE task = :taskId ORDER BY UPPER(name) ASC")
suspend fun getTagNames(taskId: Long): List<String>
@Query("""
SELECT *
FROM tasks
WHERE completed = 0
AND deleted = 0
AND hideUntil < (strftime('%s', 'now') * 1000)
ORDER BY (CASE
WHEN (dueDate = 0) THEN
(strftime('%s', 'now') * 1000) * 2
ELSE ((CASE WHEN (dueDate / 1000) % 60 > 0 THEN dueDate ELSE (dueDate + 43140000) END)) END) +
172800000 * importance
ASC
LIMIT 100""")
suspend fun getAstrid2TaskProviderTasks(): List<Task>
@Query("SELECT * FROM tagdata WHERE name IS NOT NULL AND name != '' ORDER BY UPPER(name) ASC")
suspend fun tagDataOrderedByName(): List<TagData>
@Query("SELECT * FROM tasks")
fun getTasks(): Cursor
@Query("""
SELECT caldav_lists.*, caldav_accounts.cda_name
FROM caldav_lists
INNER JOIN caldav_accounts ON cdl_account = cda_uuid""")
fun getLists(): Cursor
@Query("SELECT * FROM google_task_lists")
fun getGoogleTaskLists(): Cursor
@RawQuery
fun rawQuery(query: SupportSQLiteQuery): Cursor
} | gpl-3.0 | c86dfe3cd8479f59e88356abaac3d0be | 30.914894 | 116 | 0.623749 | 4.175487 | false | false | false | false |
dafi/photoshelf | tumblr-ui-core/src/main/java/com/ternaryop/photoshelf/tumblr/ui/core/adapter/photo/PhotoGridAdapter.kt | 1 | 1738 | package com.ternaryop.photoshelf.tumblr.ui.core.adapter.photo
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.ternaryop.photoshelf.adapter.OnPhotoBrowseClickMultiChoice
import com.ternaryop.photoshelf.tumblr.ui.core.R
class PhotoGridAdapter(
context: Context,
private val colorCellByScheduleTimeType: Boolean
) : PhotoAdapter<PhotoGridViewHolder>(context) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotoGridViewHolder {
return PhotoGridViewHolder(LayoutInflater.from(context).inflate(R.layout.grid_photo_item, parent, false))
}
override fun onBindViewHolder(holder: PhotoGridViewHolder, position: Int) {
val item = getItem(position)
holder.bindModel(item, selection.isSelected(position), colorCellByScheduleTimeType)
if (onPhotoBrowseClick == null) {
return
}
holder.setOnClickTags(this)
holder.setOnClickMenu(this)
holder.setOnClickThumbnail(this, this)
}
override fun onClick(v: View) {
val onPhotoBrowseClick = onPhotoBrowseClick ?: return
when (v.id) {
R.id.menu -> onPhotoBrowseClick.onOverflowClick(v.tag as Int, v)
R.id.thumbnail_image -> if (isActionModeOn) {
(onPhotoBrowseClick as OnPhotoBrowseClickMultiChoice).onItemClick(v.tag as Int)
} else {
onPhotoBrowseClick.onThumbnailImageClick(v.tag as Int)
}
R.id.tag_text_view -> {
val position = (v.parent as ViewGroup).tag as Int
onPhotoBrowseClick.onTagClick(position, v.tag as String)
}
}
}
}
| mit | baed17a18629e5fe73c02e823eb8b6c0 | 36.782609 | 113 | 0.68412 | 4.239024 | false | false | false | false |
SpineEventEngine/core-java | buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/JsEnvironment.kt | 2 | 7788 | /*
* Copyright 2022, TeamDev. 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
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.internal.gradle.javascript
import java.io.File
import org.apache.tools.ant.taskdefs.condition.Os
/**
* Describes the environment in which JavaScript code is assembled and processed during the build.
*
* Consists of three parts describing:
*
* 1. A module itself.
* 2. Tools and their input/output files.
* 3. Code generation.
*/
interface JsEnvironment {
/*
* A module itself
******************/
/**
* Module's root catalog.
*/
val projectDir: File
/**
* Module's version.
*/
val moduleVersion: String
/**
* Module's production sources directory.
*
* Default value: "$projectDir/main".
*/
val srcDir: File
get() = projectDir.resolve("main")
/**
* Module's test sources directory.
*
* Default value: "$projectDir/test".
*/
val testSrcDir: File
get() = projectDir.resolve("test")
/**
* A directory which all artifacts are generated into.
*
* Default value: "$projectDir/build".
*/
val buildDir: File
get() = projectDir.resolve("build")
/**
* A directory where artifacts for further publishing would be prepared.
*
* Default value: "$buildDir/npm-publication".
*/
val publicationDir: File
get() = buildDir.resolve("npm-publication")
/*
* Tools and their input/output files
*************************************/
/**
* Name of an executable for running `npm`.
*
* Default value:
*
* 1. "nmp.cmd" for Windows.
* 2. "npm" for other OSs.
*/
val npmExecutable: String
get() = if (isWindows()) "npm.cmd" else "npm"
/**
* An access token that allows installation and/or publishing modules.
*
* During installation a token is required only if dependencies from private
* repositories are used.
*
* Default value is read from the environmental variable - `NPM_TOKEN`.
* "PUBLISHING_FORBIDDEN" stub value would be assigned in case `NPM_TOKEN` variable is not set.
*
* See [Creating and viewing access tokens | npm Docs](https://docs.npmjs.com/creating-and-viewing-access-tokens).
*/
val npmAuthToken: String
get() = System.getenv("NPM_TOKEN") ?: "PUBLISHING_FORBIDDEN"
/**
* A directory where `npm` puts downloaded module's dependencies.
*
* Default value: "$projectDir/node_modules".
*/
val nodeModules: File
get() = projectDir.resolve("node_modules")
/**
* Module's descriptor used by `npm`.
*
* Default value: "$projectDir/package.json".
*/
val packageJson: File
get() = projectDir.resolve("package.json")
/**
* `npm` gets its configuration settings from the command line, environment variables,
* and `npmrc` file.
*
* Default value: "$projectDir/.npmrc".
*
* See [npmrc | npm Docs](https://docs.npmjs.com/cli/v8/configuring-npm/npmrc).
*/
val npmrc: File
get() = projectDir.resolve(".npmrc")
/**
* A cache directory in which `nyc` tool outputs raw coverage report.
*
* Default value: "$projectDir/.nyc_output".
*
* See [istanbuljs/nyc](https://github.com/istanbuljs/nyc).
*/
val nycOutput: File
get() = projectDir.resolve(".nyc_output")
/**
* A directory in which `webpack` would put a ready-to-use bundle.
*
* Default value: "$projectDir/dist"
*
* See [webpack - npm](https://www.npmjs.com/package/webpack).
*/
val webpackOutput: File
get() = projectDir.resolve("dist")
/**
* A directory where bundled artifacts for further publishing would be prepared.
*
* Default value: "$publicationDir/dist".
*/
val webpackPublicationDir: File
get() = publicationDir.resolve("dist")
/*
* Code generation
******************/
/**
* Name of a directory that contains generated code.
*
* Default value: "proto".
*/
val genProtoDirName: String
get() = "proto"
/**
* Directory with production Protobuf messages compiled into JavaScript.
*
* Default value: "$srcDir/$genProtoDirName".
*/
val genProtoMain: File
get() = srcDir.resolve(genProtoDirName)
/**
* Directory with test Protobuf messages compiled into JavaScript.
*
* Default value: "$testSrcDir/$genProtoDirName".
*/
val genProtoTest: File
get() = testSrcDir.resolve(genProtoDirName)
}
/**
* Allows overriding [JsEnvironment]'s defaults.
*
* All of declared properties can be split into two groups:
*
* 1. The ones that *define* something - can be overridden.
* 2. The ones that *describe* something - can NOT be overridden.
*
* Overriding a "defining" property affects the way `npm` tool works.
* In contrary, overriding a "describing" property does not affect the tool.
* Such properties just describe how the used tool works.
*
* Therefore, overriding of "describing" properties leads to inconsistency with expectations.
*
* The next properties could not be overridden:
*
* 1. [JsEnvironment.nodeModules].
* 2. [JsEnvironment.packageJson].
* 3. [JsEnvironment.npmrc].
* 4. [JsEnvironment.nycOutput].
*/
class ConfigurableJsEnvironment(initialEnvironment: JsEnvironment)
: JsEnvironment by initialEnvironment
{
/*
* A module itself
******************/
override var projectDir = initialEnvironment.projectDir
override var moduleVersion = initialEnvironment.moduleVersion
override var srcDir = initialEnvironment.srcDir
override var testSrcDir = initialEnvironment.testSrcDir
override var buildDir = initialEnvironment.buildDir
override var publicationDir = initialEnvironment.publicationDir
/*
* Tools and their input/output files
*************************************/
override var npmExecutable = initialEnvironment.npmExecutable
override var npmAuthToken = initialEnvironment.npmAuthToken
override var webpackOutput = initialEnvironment.webpackOutput
override var webpackPublicationDir = initialEnvironment.webpackPublicationDir
/*
* Code generation
******************/
override var genProtoDirName = initialEnvironment.genProtoDirName
override var genProtoMain = initialEnvironment.genProtoMain
override var genProtoTest = initialEnvironment.genProtoTest
}
internal fun isWindows(): Boolean = Os.isFamily(Os.FAMILY_WINDOWS)
| apache-2.0 | 9f3f74b35a02522f1ce629681a682931 | 29.541176 | 118 | 0.652542 | 4.331479 | false | false | false | false |
adrcotfas/Goodtime | app/src/main/java/com/apps/adrcotfas/goodtime/database/Label.kt | 1 | 1094 | /*
* Copyright 2016-2021 Adrian Cotfas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
package com.apps.adrcotfas.goodtime.database
import androidx.annotation.NonNull
import androidx.room.ColumnInfo
import androidx.room.Entity
@Entity(primaryKeys = ["title", "archived"])
class Label(
@ColumnInfo(defaultValue = "")
@NonNull
var title: String,
@ColumnInfo(defaultValue = "0")
@NonNull
var colorId: Int) {
@ColumnInfo(defaultValue = "0")
@NonNull
var order: Int= 0
@ColumnInfo(defaultValue = "0")
@NonNull
var archived: Boolean = false
} | apache-2.0 | eafed0a6105195fcabaffdabe1c7911c | 29.416667 | 128 | 0.720293 | 4.191571 | false | false | false | false |
nemerosa/ontrack | ontrack-service/src/test/java/net/nemerosa/ontrack/service/ValidationRunIT.kt | 1 | 16048 | package net.nemerosa.ontrack.service
import net.nemerosa.ontrack.extension.api.support.TestNumberValidationDataType
import net.nemerosa.ontrack.extension.api.support.TestValidationData
import net.nemerosa.ontrack.extension.api.support.TestValidationDataType
import net.nemerosa.ontrack.it.AbstractDSLTestJUnit4Support
import net.nemerosa.ontrack.model.exceptions.ValidationRunDataInputException
import net.nemerosa.ontrack.model.exceptions.ValidationRunDataStatusRequiredBecauseNoDataException
import net.nemerosa.ontrack.model.exceptions.ValidationRunDataTypeNotFoundException
import net.nemerosa.ontrack.model.security.ValidationRunStatusChange
import net.nemerosa.ontrack.model.structure.*
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotNull
import kotlin.test.assertNull
class ValidationRunIT : AbstractDSLTestJUnit4Support() {
@Autowired
private lateinit var testValidationDataType: TestValidationDataType
@Autowired
private lateinit var testNumberValidationDataType: TestNumberValidationDataType
@Test
fun validationRunWithData() {
project {
branch {
val vs = validationStamp(
"VS",
testValidationDataType.config(null)
)
// Build
build("1.0.0") {
// Creates a validation run with data
val run = validateWithData(
validationStamp = vs,
validationDataTypeId = testValidationDataType.descriptor.id,
validationRunData = TestValidationData(2, 4, 8)
)
// Loads the validation run
val loadedRun = asUserWithView(branch).call { structureService.getValidationRun(run.id) }
// Checks the data is still there
@Suppress("UNCHECKED_CAST")
val data: ValidationRunData<TestValidationData> = loadedRun.data as ValidationRunData<TestValidationData>
assertNotNull(data, "Data type is loaded")
assertEquals(TestValidationDataType::class.java.name, data.descriptor.id)
assertEquals(2, data.data.critical)
assertEquals(4, data.data.high)
assertEquals(8, data.data.medium)
// Checks the status
val status = loadedRun.lastStatus
assertNotNull(status)
assertEquals(ValidationRunStatusID.STATUS_FAILED.id, status.statusID.id)
}
}
}
}
@Test
fun validationRunWithDataAndForcedStatus() {
project {
branch {
val vs = validationStamp(
"VS",
testValidationDataType.config(null)
)
// Build
build("1.0.0") {
// Creates a validation run with data
val run = validateWithData(
validationStamp = vs,
validationRunStatusID = ValidationRunStatusID.STATUS_FAILED,
validationRunData = TestValidationData(0, 0, 8)
)
// Checks the status
assertEquals(ValidationRunStatusID.STATUS_FAILED.id, run.lastStatus.statusID.id)
}
}
}
}
@Test
fun validationRunWithDataAndStatusUpdate() {
project {
branch {
val vs = validationStamp("VS", testValidationDataType.config(null))
build("1.0.0") {
// Creates a validation run with data
val run = validateWithData(
validationStamp = vs,
validationDataTypeId = testValidationDataType.descriptor.id,
validationRunStatusID = ValidationRunStatusID.STATUS_FAILED,
validationRunData = TestValidationData(0, 0, 10)
)
// Checks the initial status
assertEquals(ValidationRunStatusID.STATUS_FAILED.id, run.lastStatus.statusID.id)
// Updates the status
asUser().with(branch, ValidationRunStatusChange::class.java).execute {
structureService.newValidationRunStatus(
run,
ValidationRunStatus(
ID.NONE,
Signature.of("test"),
ValidationRunStatusID.STATUS_DEFECTIVE,
"This is a defect"
)
)
}
// Reloads
val newRun = asUser().withView(branch).call {
structureService.getValidationRun(run.id)
}
// Checks the new status
assertEquals(ValidationRunStatusID.STATUS_DEFECTIVE.id, newRun.lastStatus.statusID.id)
}
}
}
}
@Test
fun validationRunWithoutData() {
project {
branch {
// Creates a validation stamp with no required data
val vs = validationStamp("VS")
// Creates a validation run without data
build("1.0.0") {
val run = validate(vs)
// Loads the validation run
val loadedRun = asUserWithView(branch).call { structureService.getValidationRun(run.id) }
// Checks the data
val data = loadedRun.data
assertNull(data, "No data is loaded")
// Checks the status
val status = loadedRun.lastStatus
assertNotNull(status)
assertEquals(ValidationRunStatusID.STATUS_PASSED.id, status.statusID.id)
}
}
}
}
@Test
fun validationRunWithDataAndNoDataTypeOnValidationStamp() {
project {
branch {
// Validation data without data
val vs = validationStamp("VS")
// Build
build("1.0.0") {
val run = validateWithData(
vs,
ValidationRunStatusID.STATUS_PASSED,
testValidationDataType.descriptor.id,
TestValidationData(0, 10, 100)
)
assertEquals(
ValidationRunStatusID.PASSED,
run.lastStatus.statusID.id
)
}
}
}
}
@Test(expected = ValidationRunDataInputException::class)
fun validationRunWithInvalidData() {
project {
branch {
val vs = validationStamp(
"VS",
testValidationDataType.config(null)
)
build("1.0.0") {
validateWithData(
validationStamp = vs,
validationDataTypeId = testValidationDataType.descriptor.id,
validationRunData = TestValidationData(-1, 0, 0)
)
}
}
}
}
@Test
fun validationRunWithUnrequestedData() {
project {
branch {
// Creates a "normal" validation stamp
val vs = validationStamp("VS")
// Build
build("1.0.0") {
// Creates a validation run with data
validateWithData(
validationStamp = vs,
validationRunStatusID = ValidationRunStatusID.STATUS_PASSED,
validationDataTypeId = testNumberValidationDataType.descriptor.id,
validationRunData = 80
)
}
}
}
}
@Test
fun validationRunWithMissingDataOKWithStatus() {
project {
branch {
val vs = validationStamp("VS", testNumberValidationDataType.config(50))
build("1.0.0") {
val run = validateWithData<Any>(
validationStamp = vs,
validationRunStatusID = ValidationRunStatusID.STATUS_PASSED
)
assertEquals(
ValidationRunStatusID.STATUS_PASSED.id,
run.lastStatus.statusID.id
)
}
}
}
}
@Test(expected = ValidationRunDataStatusRequiredBecauseNoDataException::class)
fun validationRunWithMissingDataNotOKWithoutStatus() {
project {
branch {
val vs = validationStamp("VS", testNumberValidationDataType.config(50))
build("1.0.0") {
validateWithData<Any>(vs)
}
}
}
}
@Test
fun `Introducing a data type on existing validation runs`() {
// Creates a basic stamp, with no data type
val vs = doCreateValidationStamp()
// Creates a build
val build = doCreateBuild(vs.branch, NameDescription.nd("1", ""))
// ... and validates it
val runId = doValidateBuild(build, vs, ValidationRunStatusID.STATUS_PASSED).id
// Now, changes the data type for the validation stamp
asAdmin().execute {
structureService.saveValidationStamp(
vs.withDataType(
testNumberValidationDataType.config(50)
)
)
}
// Gets the validation run back
val run = asUser().withView(vs).call { structureService.getValidationRun(runId) }
// Checks it has still no data
assertNull(run.data, "No data associated with validation run after migration")
}
@Test
fun `Removing a data type from existing validation runs`() {
project {
branch {
// Creates a basic stamp, with some data type
val vs = validationStamp(
"VS",
testNumberValidationDataType.config(50)
)
// Creates a build
build("1.0.0") {
// ... and validates it with some data
val runId: ID = validateWithData(
validationStamp = vs,
validationRunStatusID = ValidationRunStatusID.STATUS_PASSED,
validationDataTypeId = testNumberValidationDataType.descriptor.id,
validationRunData = 40
).id
// Now, changes the data type for the validation stamp
asAdmin().execute {
structureService.saveValidationStamp(
vs.withDataType(null)
)
}
// Gets the validation run back
val run = asUser().withView(vs).call { structureService.getValidationRun(runId) }
// Checks it has still some data
assertNotNull(run.data, "Data still associated with validation run after migration") {
assertEquals(TestNumberValidationDataType::class.qualifiedName, it.descriptor.id)
assertEquals(40, it.data as Int)
}
}
}
}
}
@Test
fun `Changing a data type for existing validation runs`() {
project {
branch {
// Creates a basic stamp, with some data type
val vs = validationStamp("VS", testNumberValidationDataType.config(50))
// Creates a build
build("1.0.0") {
// ... and validates it with some data
val runId = validateWithData(
validationStamp = vs,
validationRunStatusID = ValidationRunStatusID.STATUS_PASSED,
validationRunData = 40
).id
// Now, changes the data type for the validation stamp
asAdmin().execute {
structureService.saveValidationStamp(
vs.withDataType(
testValidationDataType.config(null)
)
)
}
// Gets the validation run back
val run = asUser().withView(vs).call { structureService.getValidationRun(runId) }
// Checks it has still some data
assertNotNull(run.data, "Data still associated with validation run after migration") {
assertEquals(TestNumberValidationDataType::class.qualifiedName, it.descriptor.id)
assertEquals(40, it.data as Int)
}
}
}
}
}
@Test
fun `Validation data still present when validation stamp has no longer a validation data type`() {
project {
branch {
// Creates a basic stamp, with some data type
val vs = validationStamp("VS", testNumberValidationDataType.config(50))
// Creates a build
build("1.0.0") {
// ... and validates it with some data
val runId = validateWithData(
validationStamp = vs,
validationRunStatusID = ValidationRunStatusID.STATUS_PASSED,
validationDataTypeId = testNumberValidationDataType.descriptor.id,
validationRunData = 40
).id
// Now, changes the data type for the validation stamp to null
asAdmin().execute {
structureService.saveValidationStamp(
vs.withDataType(null)
)
}
// Gets the validation run back
val run = asUser().withView(vs).call { structureService.getValidationRun(runId) }
// Checks it has still some data
assertNotNull(run.data, "Data still associated with validation run after migration") {
assertEquals(TestNumberValidationDataType::class.qualifiedName, it.descriptor.id)
assertEquals(40, it.data as Int)
}
}
}
}
}
@Test
fun `Validation run data with unknown type`() {
project {
branch {
val vs = validationStamp("VS")
// Build
build("1.0.0") {
// Creates a validation run with data, and an unknown data type
assertFailsWith<ValidationRunDataTypeNotFoundException> {
validateWithData(
validationStamp = vs,
validationDataTypeId = "unknown",
validationRunData = TestValidationData(2, 4, 8)
)
}
}
}
}
}
} | mit | a3d659fa5203a6445e431a729b2daf4b | 39.527778 | 125 | 0.49757 | 6.25897 | false | true | false | false |
jraska/github-client | feature/push/src/main/java/com/jraska/github/client/push/PushTokenSynchronizer.kt | 1 | 1179 | package com.jraska.github.client.push
import android.os.Build
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.installations.FirebaseInstallations
import com.jraska.github.client.time.DateTimeProvider
import timber.log.Timber
import java.util.HashMap
import javax.inject.Inject
internal class PushTokenSynchronizer @Inject constructor(
private val database: FirebaseDatabase,
private val dateTimeProvider: DateTimeProvider
) {
fun synchronizeToken(token: String) {
val installationIdTask = FirebaseInstallations.getInstance().id
installationIdTask.addOnSuccessListener { saveToken(it, token) }
.addOnFailureListener { Timber.e(it, "installation Id couldn't be found.") }
}
private fun saveToken(id: String, pushToken: String) {
Timber.d("Id: %s, Token: %s", id, pushToken)
val map = HashMap<String, Any>()
map["date"] = dateTimeProvider.now().toString()
map["push_token"] = pushToken
map["android_os"] = Build.VERSION.RELEASE
map["manufacturer"] = Build.BRAND
map["model"] = Build.MODEL
val tokenReference = database.getReference("devices/$id")
tokenReference.setValue(map)
}
}
| apache-2.0 | bb717ec06a03c0bc02c7e16cc6e1f059 | 30.864865 | 82 | 0.748092 | 4.122378 | false | false | false | false |
nextcloud/android | app/src/main/java/com/nextcloud/client/media/ErrorFormat.kt | 1 | 5355 | /**
* Nextcloud Android client application
*
* @author David A. Velasco
* @author masensio
* @author Chris Narkiewicz
* Copyright (C) 2013 David A. Velasco
* Copyright (C) 2016 masensio
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
*
* 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 com.nextcloud.client.media
import android.content.Context
import android.media.MediaPlayer
import com.google.android.exoplayer2.PlaybackException
import com.owncloud.android.R
/**
* This code has been moved from legacy media player service.
*/
@Deprecated("This legacy helper should be refactored")
@Suppress("ComplexMethod") // it's legacy code
object ErrorFormat {
/** Error code for specific messages - see regular error codes at [MediaPlayer] */
const val OC_MEDIA_ERROR = 0
@JvmStatic
fun toString(context: Context?, what: Int, extra: Int): String {
val messageId: Int
if (what == OC_MEDIA_ERROR) {
messageId = extra
} else if (extra == MediaPlayer.MEDIA_ERROR_UNSUPPORTED) {
/* Added in API level 17
Bitstream is conforming to the related coding standard or file spec,
but the media framework does not support the feature.
Constant Value: -1010 (0xfffffc0e)
*/
messageId = R.string.media_err_unsupported
} else if (extra == MediaPlayer.MEDIA_ERROR_IO) {
/* Added in API level 17
File or network related operation errors.
Constant Value: -1004 (0xfffffc14)
*/
messageId = R.string.media_err_io
} else if (extra == MediaPlayer.MEDIA_ERROR_MALFORMED) {
/* Added in API level 17
Bitstream is not conforming to the related coding standard or file spec.
Constant Value: -1007 (0xfffffc11)
*/
messageId = R.string.media_err_malformed
} else if (extra == MediaPlayer.MEDIA_ERROR_TIMED_OUT) {
/* Added in API level 17
Some operation takes too long to complete, usually more than 3-5 seconds.
Constant Value: -110 (0xffffff92)
*/
messageId = R.string.media_err_timeout
} else if (what == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) {
/* Added in API level 3
The video is streamed and its container is not valid for progressive playback i.e the video's index
(e.g moov atom) is not at the start of the file.
Constant Value: 200 (0x000000c8)
*/
messageId = R.string.media_err_invalid_progressive_playback
} else {
/* MediaPlayer.MEDIA_ERROR_UNKNOWN
Added in API level 1
Unspecified media player error.
Constant Value: 1 (0x00000001)
*/
/* MediaPlayer.MEDIA_ERROR_SERVER_DIED)
Added in API level 1
Media server died. In this case, the application must release the MediaPlayer
object and instantiate a new one.
Constant Value: 100 (0x00000064)
*/
messageId = R.string.media_err_unknown
}
return context?.getString(messageId) ?: "Media error"
}
fun toString(context: Context, exception: PlaybackException): String {
val messageId = when (exception.errorCode) {
PlaybackException.ERROR_CODE_DECODING_FORMAT_UNSUPPORTED,
PlaybackException.ERROR_CODE_DECODING_FORMAT_EXCEEDS_CAPABILITIES -> {
R.string.media_err_unsupported
}
PlaybackException.ERROR_CODE_IO_UNSPECIFIED,
PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED,
PlaybackException.ERROR_CODE_IO_INVALID_HTTP_CONTENT_TYPE,
PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS,
PlaybackException.ERROR_CODE_IO_FILE_NOT_FOUND,
PlaybackException.ERROR_CODE_IO_NO_PERMISSION,
PlaybackException.ERROR_CODE_IO_CLEARTEXT_NOT_PERMITTED,
PlaybackException.ERROR_CODE_IO_READ_POSITION_OUT_OF_RANGE -> {
R.string.media_err_io
}
PlaybackException.ERROR_CODE_TIMEOUT -> {
R.string.media_err_timeout
}
PlaybackException.ERROR_CODE_PARSING_CONTAINER_MALFORMED,
PlaybackException.ERROR_CODE_PARSING_MANIFEST_MALFORMED -> {
R.string.media_err_malformed
}
else -> {
R.string.media_err_invalid_progressive_playback
}
}
return context.getString(messageId)
}
}
| gpl-2.0 | 0388562237fbb4436e8e953ad67b6071 | 41.84 | 115 | 0.625397 | 4.443983 | false | false | false | false |
olonho/carkot | server/src/main/java/net/web/server/handlers/DirectionOrder.kt | 1 | 1299 | package net.web.server.handlers
import CodedInputStream
import CodedOutputStream
import DirectionRequest
import GenericResponse
import Result
import net.Handler
import net.web.server.Server
class DirectionOrder : Handler {
override fun execute(bytesFromClient: ByteArray): ByteArray {
if (Server.serverMode != Server.ServerMode.MANUAL_MODE) {
println("Can't execute move order when not in manual mode")
val protoResponse = GenericResponse.BuilderGenericResponse(Result.BuilderResult(1).build()).build()
return protoBufToBytes(protoResponse)
}
val ins = CodedInputStream(bytesFromClient)
val order = DirectionRequest.BuilderDirectionRequest(DirectionRequest.Command.FORWARD, 0, false).parseFrom(ins)
if (order.stop) {
net.web.server.Server.changeMode(Server.ServerMode.IDLE)
val protoResponse = GenericResponse.BuilderGenericResponse(Result.BuilderResult(1).build()).build()
return protoBufToBytes(protoResponse)
}
return ByteArray(0)
}
private fun protoBufToBytes(protoMessage: GenericResponse): ByteArray {
val result = ByteArray(protoMessage.getSizeNoTag())
protoMessage.writeTo(CodedOutputStream(result))
return result
}
} | mit | 561cc94f56ad5b53ed203373f7020db8 | 35.111111 | 119 | 0.717475 | 4.775735 | false | false | false | false |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/adapter/SelectionRecyclerViewAdapter.kt | 2 | 2832 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2021 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import edu.berkeley.boinc.attach.ProjectInfoFragment.Companion.newInstance
import edu.berkeley.boinc.attach.SelectionListActivity
import edu.berkeley.boinc.databinding.AttachProjectListLayoutListItemBinding
import edu.berkeley.boinc.utils.Logging
class SelectionRecyclerViewAdapter(
private val activity: SelectionListActivity,
private val entries: List<ProjectListEntry>
) : RecyclerView.Adapter<SelectionRecyclerViewAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = AttachProjectListLayoutListItemBinding.inflate(LayoutInflater.from(parent.context))
return ViewHolder(binding)
}
override fun getItemCount() = entries.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val listItem = entries[position]
// element is project option
holder.name.text = listItem.info?.name
holder.description.text = listItem.info?.generalArea
holder.summary.text = listItem.info?.summary
holder.checkBox.isChecked = listItem.isChecked
holder.checkBox.setOnClickListener { listItem.isChecked = !listItem.isChecked }
holder.textWrapper.setOnClickListener {
Logging.logDebug(Logging.Category.USER_ACTION, "SelectionListAdapter: onProjectClick open info for: " +
listItem.info?.name)
val dialog = newInstance(listItem.info)
dialog.show(activity.supportFragmentManager, "ProjectInfoFragment")
}
}
inner class ViewHolder(binding: AttachProjectListLayoutListItemBinding) :
RecyclerView.ViewHolder(binding.root) {
val root = binding.root
val name = binding.name
val description = binding.description
val summary = binding.summary
val checkBox = binding.checkBox
val textWrapper = binding.textWrapper
}
}
| lgpl-3.0 | 63177c176b2dc4b31aa1e1e96d3ebf11 | 41.268657 | 115 | 0.735169 | 4.841026 | false | false | false | false |
adgvcxz/ViewModel | recyclerviewmodel/src/main/kotlin/com/adgvcxz/recyclerviewmodel/ItemClickObservable.kt | 1 | 1332 | package com.adgvcxz.recyclerviewmodel
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import io.reactivex.rxjava3.android.MainThreadDisposable
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Observer
/**
* zhaowei
* Created by zhaowei on 2017/5/15.
*/
class ItemClickObservable(private val adapter: RecyclerAdapter) : Observable<Int>() {
override fun subscribeActual(observer: Observer<in Int>) {
adapter.notifyDataSetChanged()
adapter.itemClickListener = Listener(observer)
}
class Listener(private val observer: Observer<in Int>) : MainThreadDisposable(), View.OnClickListener {
var recyclerView: RecyclerView? = null
override fun onDispose() {
if (recyclerView != null) {
(0 until recyclerView!!.childCount)
.map { recyclerView!!.getChildAt(it) }
.forEach { it.setOnClickListener(null) }
}
}
override fun onClick(v: View) {
val parent = v.parent
if (parent is RecyclerView && recyclerView == null) {
recyclerView = parent
}
val holder = recyclerView?.getChildViewHolder(v)
observer.onNext(holder?.adapterPosition ?: -1)
}
}
} | apache-2.0 | a97c1b270583124f7a6b4e9dcd59bb27 | 29.295455 | 107 | 0.636637 | 4.970149 | false | false | false | false |
equeim/tremotesf-android | app/src/main/kotlin/org/equeim/tremotesf/ui/utils/StateRestoringListAdapter.kt | 1 | 1942 | /*
* Copyright (C) 2017-2022 Alexey Rochev <[email protected]>
*
* This file is part of Tremotesf.
*
* Tremotesf 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.
*
* Tremotesf 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 org.equeim.tremotesf.ui.utils
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import timber.log.Timber
abstract class StateRestoringListAdapter<T : Any?, VH : RecyclerView.ViewHolder>(diffCallback: DiffUtil.ItemCallback<T>) :
ListAdapter<T, VH>(diffCallback) {
init {
stateRestorationPolicy = StateRestorationPolicy.PREVENT
}
abstract fun allowStateRestoring(): Boolean
override fun submitList(list: List<T>?) = submitList(list, null)
override fun submitList(list: List<T>?, commitCallback: Runnable?) {
val restore = allowStateRestoring()
super.submitList(list?.nullIfEmpty()) {
commitCallback?.run()
if (restore && stateRestorationPolicy == StateRestorationPolicy.PREVENT) {
Timber.i("commitCallback: restoring state")
stateRestorationPolicy = StateRestorationPolicy.ALLOW
onStateRestored()
}
}
}
protected open fun onStateRestored() {}
private companion object {
fun <T> List<T>.nullIfEmpty() = ifEmpty { null }
}
}
| gpl-3.0 | bd9261b143505f22c097dbb45eb6f058 | 34.309091 | 122 | 0.703913 | 4.569412 | false | false | false | false |
gameofbombs/kt-postgresql-async | db-async-common/src/main/kotlin/com/github/elizarov/async/CancellableDispatcher.kt | 2 | 1097 | package com.github.elizarov.async
import kotlin.coroutines.Continuation
import kotlin.coroutines.ContinuationDispatcher
class CancellableDispatcher(
cancellable: Cancellable,
dispatcher: ContinuationDispatcher? = null
) : Cancellable by cancellable, ContinuationDispatcher {
private val delegate: ContinuationDispatcher? =
if (dispatcher is CancellableDispatcher) dispatcher.delegate else dispatcher
override fun <T> dispatchResume(value: T, continuation: Continuation<T>): Boolean {
if (isCancelled) {
val exception = CancellationException()
if (dispatchResumeWithException(exception, continuation)) return true
continuation.resumeWithException(exception) // todo: stack overflow?
return true
}
return delegate != null && delegate.dispatchResume(value, continuation)
}
override fun dispatchResumeWithException(exception: Throwable, continuation: Continuation<*>): Boolean {
return delegate != null && delegate.dispatchResumeWithException(exception, continuation)
}
}
| apache-2.0 | 27e55c357e54f5f6af0f2c08193367b4 | 39.62963 | 108 | 0.72835 | 5.596939 | false | false | false | false |
HedvigInsurance/bot-service | src/main/java/com/hedvig/botService/serviceIntegration/underwriter/QuoteRequestDto.kt | 1 | 2789 | package com.hedvig.botService.serviceIntegration.underwriter
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import java.math.BigDecimal
import java.time.Instant
import java.time.LocalDate
import java.util.UUID
data class QuoteRequestDto(
val firstName: String?,
val lastName: String?,
val email: String?,
val currentInsurer: String?,
val birthDate: LocalDate?,
val ssn: String?,
val quotingPartner: Partner?,
val productType: ProductType?,
@field:JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@field:JsonSubTypes(
JsonSubTypes.Type(value = IncompleteApartmentQuoteDataDto::class, name = "apartment"),
JsonSubTypes.Type(value = IncompleteHouseQuoteDataDto::class, name = "house")
) val incompleteQuoteData: IncompleteQuoteRequestData?,
val memberId: String? = null,
val originatingProductId: UUID? = null,
val startDate: Instant? = null,
val dataCollectionId: UUID? = null,
val shouldComplete: Boolean,
val underwritingGuidelinesBypassedBy: String?
)
sealed class IncompleteQuoteRequestData
data class IncompleteHouseQuoteDataDto(
val street: String?,
val zipCode: String?,
val city: String?,
val livingSpace: Int?,
val householdSize: Int?,
val ancillaryArea: Int?,
val yearOfConstruction: Int?,
val numberOfBathrooms: Int?,
val extraBuildings: List<ExtraBuildingRequestDto>?,
@field:JsonProperty("subleted")
val isSubleted: Boolean?,
val floor: Int? = 0
) : IncompleteQuoteRequestData()
data class IncompleteApartmentQuoteDataDto(
val street: String?,
val zipCode: String?,
val city: String?,
val livingSpace: Int?,
val householdSize: Int?,
val floor: Int?,
val subType: ApartmentProductSubType?
) : IncompleteQuoteRequestData()
data class ExtraBuildingRequestDto(
val id: UUID?,
val type: ExtraBuildingType,
val area: Int,
val hasWaterConnected: Boolean
)
enum class Partner(val campaignCode: String? = null) {
HEDVIG,
INSPLANET,
COMPRICER,
INSURLEY
}
enum class ProductType {
APARTMENT,
HOUSE,
OBJECT,
UNKNOWN
}
enum class ExtraBuildingType {
GARAGE,
CARPORT,
SHED,
STOREHOUSE,
FRIGGEBOD,
ATTEFALL,
OUTHOUSE,
GUESTHOUSE,
GAZEBO,
GREENHOUSE,
SAUNA,
BARN,
BOATHOUSE,
OTHER
}
enum class ApartmentProductSubType {
BRF,
RENT,
RENT_BRF,
SUBLET_RENTAL,
SUBLET_BRF,
STUDENT_BRF,
STUDENT_RENT,
LODGER,
UNKNOWN
}
data class CompleteQuoteResponseDto(
val id: UUID,
val price: BigDecimal,
val validTo: Instant
)
| agpl-3.0 | 3d7c6a138e74c9aa28bd0c81d8903155 | 23.043103 | 106 | 0.704912 | 3.846897 | false | false | false | false |
alfadur/antiques | src/Pixi.kt | 1 | 4063 | import org.w3c.dom.HTMLCanvasElement
//@suppress("UNUSED_PARAMETER")
@native object PIXI
{
@native class Point(val x: Number, val y: Number)
@native class Rectangle(val x: Number, val y: Number, val width: Number, val height: Number)
@native class Matrix
{
@native val a: Double = noImpl
@native val b: Double = noImpl
@native val c: Double = noImpl
@native val d: Double = noImpl
@native val tx: Double = noImpl
@native val ty: Double = noImpl
companion object
{
@native fun fromArray(array: Array<Double>): Matrix = noImpl
}
}
@native open class DisplayObject
{
@native var position: Point get() = noImpl; set(v) = noImpl
@native var rotation: Double get() = noImpl; set(v) = noImpl
@native var pivot: Point get() = noImpl; set(v) = noImpl
@native var scale: Point get() = noImpl; set(v) = noImpl
@native var worldTransform: Matrix get() = noImpl; set(v) = noImpl
@native var width: Number = noImpl
@native var height: Number = noImpl
@native var visible: Boolean get() = noImpl; set(v) = noImpl
}
@native open class DisplayObjectContainer: DisplayObject()
{
@native fun addChild(child: DisplayObject): DisplayObject = noImpl
@native fun removeChild(child: DisplayObject): DisplayObject = noImpl
@native fun removeChildren(): Unit = noImpl
}
@native class Stage(color: Number = 0): DisplayObjectContainer()
@native class CanvasRenderer(width: Number = 800, height: Number = 600)
{
@native val view: HTMLCanvasElement = noImpl
@native fun render(stage: Stage): Unit = noImpl
}
@native class Graphics: DisplayObject()
{
@native fun beginFill(color: Number = 0, alpha: Number = 1): Graphics = noImpl
@native fun endFill(): Graphics = noImpl
@native fun lineStyle(lineWidth: Number = 0, color: Number = 0, alpha: Number = 1): Graphics = noImpl
@native fun moveTo(x: Number, y: Number): Graphics = noImpl
@native fun lineTo(x: Number, y: Number): Graphics = noImpl
@native fun drawRect(x: Number, y: Number, width: Number, height: Number): Graphics = noImpl
@native fun drawCircle(x: Number, y: Number, radius: Number): Graphics = noImpl
@native fun clear(): Graphics = noImpl
}
@native class AssetLoader(assetUrls: Array<String>, crossorigin: Boolean)
{
@native fun load(): Unit = noImpl
@native var onComplete: () -> Unit = noImpl
}
@native class BaseTexture private constructor()
{
@native val width: Int = noImpl
@native val height: Int = noImpl
companion object
{
@native fun fromImage(imageUrl: String, crossorigin: Boolean): BaseTexture = noImpl
}
}
@native class Texture(baseTexture: BaseTexture, val frame: Rectangle)
{
companion object
{
@native fun fromFrame(frameId: String): Texture = noImpl
}
}
@native class Sprite(texture: Texture): DisplayObject()
@native class Text(var text: String, val style: TextStyle? = null): DisplayObject()
{
fun setStyle(style: TextStyle): Unit = noImpl
}
@native class SpriteBatch(): DisplayObjectContainer()
}
data class TextStyle(
val fill: String = "black",
val wordWrap: Boolean = false,
val wordWrapWidth: Number = 100,
val font: String? = null)
fun PIXI.BaseTexture.slice(vararg sizes: Int): Array<PIXI.Texture>
{
val result = arrayListOf<PIXI.Texture>()
var x = 0
var y = 0
for (height in sizes)
{
for (width in sizes)
{
result.add(PIXI.Texture(this, PIXI.Rectangle(x, y, width, height)))
x += width
}
y += height
x = 0
}
return result.toTypedArray()
}
operator fun PIXI.Point.plus(p: PIXI.Point) =
PIXI.Point(x.toDouble() + p.x.toDouble(),
y.toDouble() + p.y.toDouble()) | mit | 9177bccc850bd8e04967e77328f44d9c | 30.022901 | 109 | 0.614324 | 4.18866 | false | false | false | false |
cashapp/sqldelight | sqldelight-compiler/src/test/kotlin/app/cash/sqldelight/core/tables/InterfaceGeneration.kt | 1 | 15389 | package app.cash.sqldelight.core.tables
import app.cash.sqldelight.core.compiler.SqlDelightCompiler
import app.cash.sqldelight.core.compiler.TableInterfaceGenerator
import app.cash.sqldelight.dialects.hsql.HsqlDialect
import app.cash.sqldelight.dialects.mysql.MySqlDialect
import app.cash.sqldelight.dialects.postgresql.PostgreSqlDialect
import app.cash.sqldelight.test.util.FixtureCompiler
import app.cash.sqldelight.test.util.withInvariantLineSeparators
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
class InterfaceGeneration {
@get:Rule val tempFolder = TemporaryFolder()
@Test fun requiresAdapter() {
checkFixtureCompiles("requires-adapter")
}
@Test fun `annotation with values is preserved`() {
val result = FixtureCompiler.compileSql(
"""
|import com.sample.SomeAnnotation;
|import com.sample.SomeOtherAnnotation;
|import java.util.List;
|import kotlin.Int;
|
|CREATE TABLE test (
| annotated INTEGER AS @SomeAnnotation(
| cheese = ["havarti", "provalone"],
| age = 10,
| type = List::class,
| otherAnnotation = SomeOtherAnnotation("value")
| ) Int
|);
|
""".trimMargin(),
tempFolder,
)
assertThat(result.errors).isEmpty()
val generatedInterface = result.compilerOutput.get(File(result.outputDirectory, "com/example/Test.kt"))
assertThat(generatedInterface).isNotNull()
assertThat(generatedInterface.toString()).isEqualTo(
"""
|package com.example
|
|import app.cash.sqldelight.ColumnAdapter
|import com.sample.SomeAnnotation
|import com.sample.SomeOtherAnnotation
|import java.util.List
|import kotlin.Int
|import kotlin.Long
|
|public data class Test(
| @SomeAnnotation(
| cheese = ["havarti","provalone"],
| age = 10,
| type = List::class,
| otherAnnotation = SomeOtherAnnotation("value"),
| )
| public val annotated: Int?,
|) {
| public class Adapter(
| public val annotatedAdapter: ColumnAdapter<Int, Long>,
| )
|}
|
""".trimMargin(),
)
}
@Test fun `abstract class doesnt override kotlin functions unprepended by get`() {
val result = FixtureCompiler.compileSql(
"""
|CREATE TABLE test (
| is_cool TEXT NOT NULL,
| get_cheese TEXT,
| isle TEXT,
| stuff TEXT
|);
|
""".trimMargin(),
tempFolder,
)
assertThat(result.errors).isEmpty()
val generatedInterface = result.compilerOutput.get(File(result.outputDirectory, "com/example/Test.kt"))
assertThat(generatedInterface).isNotNull()
assertThat(generatedInterface.toString()).isEqualTo(
"""
|package com.example
|
|import kotlin.String
|
|public data class Test(
| public val is_cool: String,
| public val get_cheese: String?,
| public val isle: String?,
| public val stuff: String?,
|)
|
""".trimMargin(),
)
}
@Test fun `complex generic type is inferred properly`() {
val result = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| mapValue INTEGER AS kotlin.collections.Map<kotlin.collections.List<kotlin.collections.List<String>>, kotlin.collections.List<kotlin.collections.List<String>>>
|);
|
""".trimMargin(),
tempFolder,
)
val generator = TableInterfaceGenerator(result.sqlStatements().first().statement.createTableStmt!!.tableExposed())
assertThat(generator.kotlinImplementationSpec().toString()).isEqualTo(
"""
|public data class Test(
| public val mapValue: kotlin.collections.Map<kotlin.collections.List<kotlin.collections.List<String>>, kotlin.collections.List<kotlin.collections.List<String>>>?,
|) {
| public class Adapter(
| public val mapValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.collections.Map<kotlin.collections.List<kotlin.collections.List<String>>, kotlin.collections.List<kotlin.collections.List<String>>>, kotlin.Long>,
| )
|}
|
""".trimMargin(),
)
}
@Test fun `type doesnt just use suffix to resolve`() {
val result = FixtureCompiler.parseSql(
"""
|import java.time.DayOfWeek;
|import com.gabrielittner.timetable.core.db.Week;
|import kotlin.collections.Set;
|
|CREATE TABLE test (
| _id INTEGER PRIMARY KEY AUTOINCREMENT,
| enabledDays TEXT AS Set<DayOfWeek>,
| enabledWeeks TEXT AS Set<Week>
|);
|
""".trimMargin(),
tempFolder,
)
val generator = TableInterfaceGenerator(result.sqlStatements().first().statement.createTableStmt!!.tableExposed())
assertThat(generator.kotlinImplementationSpec().toString()).isEqualTo(
"""
|public data class Test(
| public val _id: kotlin.Long,
| public val enabledDays: kotlin.collections.Set<java.time.DayOfWeek>?,
| public val enabledWeeks: kotlin.collections.Set<com.gabrielittner.timetable.core.db.Week>?,
|) {
| public class Adapter(
| public val enabledDaysAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.collections.Set<java.time.DayOfWeek>, kotlin.String>,
| public val enabledWeeksAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.collections.Set<com.gabrielittner.timetable.core.db.Week>, kotlin.String>,
| )
|}
|
""".trimMargin(),
)
}
@Test fun `escaped names is handled correctly`() {
val result = FixtureCompiler.parseSql(
"""
|CREATE TABLE [group] (
| `index1` TEXT,
| 'index2' TEXT,
| "index3" TEXT,
| [index4] TEXT
|);
|
""".trimMargin(),
tempFolder,
)
val generator = TableInterfaceGenerator(result.sqlStatements().first().statement.createTableStmt!!.tableExposed())
assertThat(generator.kotlinImplementationSpec().toString()).isEqualTo(
"""
|public data class Group(
| public val index1: kotlin.String?,
| public val index2: kotlin.String?,
| public val index3: kotlin.String?,
| public val index4: kotlin.String?,
|)
|
""".trimMargin(),
)
}
@Test fun `underlying type is inferred properly in MySQL`() {
val result = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| tinyIntValue TINYINT AS kotlin.Any NOT NULL,
| tinyIntBoolValue BOOLEAN AS kotlin.Any NOT NULL,
| smallIntValue SMALLINT AS kotlin.Any NOT NULL,
| mediumIntValue MEDIUMINT AS kotlin.Any NOT NULL,
| intValue INT AS kotlin.Any NOT NULL,
| bigIntValue BIGINT AS kotlin.Any NOT NULL,
| bitValue BIT AS kotlin.Any NOT NULL
|);
|
""".trimMargin(),
tempFolder,
dialect = MySqlDialect(),
)
val generator = TableInterfaceGenerator(result.sqlStatements().first().statement.createTableStmt!!.tableExposed())
assertThat(generator.kotlinImplementationSpec().toString()).isEqualTo(
"""
|public data class Test(
| public val tinyIntValue: kotlin.Any,
| public val tinyIntBoolValue: kotlin.Any,
| public val smallIntValue: kotlin.Any,
| public val mediumIntValue: kotlin.Any,
| public val intValue: kotlin.Any,
| public val bigIntValue: kotlin.Any,
| public val bitValue: kotlin.Any,
|) {
| public class Adapter(
| public val tinyIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Byte>,
| public val tinyIntBoolValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Boolean>,
| public val smallIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Short>,
| public val mediumIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Int>,
| public val intValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Int>,
| public val bigIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Long>,
| public val bitValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Boolean>,
| )
|}
|
""".trimMargin(),
)
}
@Test fun `underlying type is inferred properly in PostgreSQL`() {
val result = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| smallIntValue SMALLINT AS kotlin.Any NOT NULL,
| intValue INT AS kotlin.Any NOT NULL,
| bigIntValue BIGINT AS kotlin.Any NOT NULL,
| smallSerialValue SMALLSERIAL AS kotlin.Any,
| serialValue SERIAL AS kotlin.Any NOT NULL,
| bigSerialValue BIGSERIAL AS kotlin.Any NOT NULL
|);
|
""".trimMargin(),
tempFolder,
dialect = PostgreSqlDialect(),
)
val generator = TableInterfaceGenerator(result.sqlStatements().first().statement.createTableStmt!!.tableExposed())
assertThat(generator.kotlinImplementationSpec().toString()).isEqualTo(
"""
|public data class Test(
| public val smallIntValue: kotlin.Any,
| public val intValue: kotlin.Any,
| public val bigIntValue: kotlin.Any,
| public val smallSerialValue: kotlin.Any?,
| public val serialValue: kotlin.Any,
| public val bigSerialValue: kotlin.Any,
|) {
| public class Adapter(
| public val smallIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Short>,
| public val intValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Int>,
| public val bigIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Long>,
| public val smallSerialValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Short>,
| public val serialValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Int>,
| public val bigSerialValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Long>,
| )
|}
|
""".trimMargin(),
)
}
@Test fun `underlying type is inferred properly in HSQL`() {
val result = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| tinyIntValue TINYINT AS kotlin.Any NOT NULL,
| smallIntValue SMALLINT AS kotlin.Any NOT NULL,
| intValue INT AS kotlin.Any NOT NULL,
| bigIntValue BIGINT AS kotlin.Any NOT NULL,
| booleanValue BOOLEAN AS kotlin.Any NOT NULL
|);
|
""".trimMargin(),
tempFolder,
dialect = HsqlDialect(),
)
val generator = TableInterfaceGenerator(result.sqlStatements().first().statement.createTableStmt!!.tableExposed())
assertThat(generator.kotlinImplementationSpec().toString()).isEqualTo(
"""
|public data class Test(
| public val tinyIntValue: kotlin.Any,
| public val smallIntValue: kotlin.Any,
| public val intValue: kotlin.Any,
| public val bigIntValue: kotlin.Any,
| public val booleanValue: kotlin.Any,
|) {
| public class Adapter(
| public val tinyIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Byte>,
| public val smallIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Short>,
| public val intValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Int>,
| public val bigIntValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Long>,
| public val booleanValueAdapter: app.cash.sqldelight.ColumnAdapter<kotlin.Any, kotlin.Boolean>,
| )
|}
|
""".trimMargin(),
)
}
@Test fun `move annotations to the front of the property`() {
val result = FixtureCompiler.parseSql(
"""
|import java.lang.Deprecated;
|import java.util.Date;
|
|CREATE TABLE something (
| startDate INTEGER AS @Deprecated Date NOT NULL,
| endDate INTEGER AS @Deprecated Date NOT NULL
|);
""".trimMargin(),
tempFolder,
)
val generator = TableInterfaceGenerator(result.sqlStatements().first().statement.createTableStmt!!.tableExposed())
assertThat(generator.kotlinImplementationSpec().toString()).isEqualTo(
"""
|public data class Something(
| @java.lang.Deprecated
| public val startDate: java.util.Date,
| @java.lang.Deprecated
| public val endDate: java.util.Date,
|) {
| public class Adapter(
| public val startDateAdapter: app.cash.sqldelight.ColumnAdapter<java.util.Date, kotlin.Long>,
| public val endDateAdapter: app.cash.sqldelight.ColumnAdapter<java.util.Date, kotlin.Long>,
| )
|}
|
""".trimMargin(),
)
}
@Test fun `value types correctly generated`() {
val result = FixtureCompiler.compileSql(
"""
|CREATE TABLE test (
| id INTEGER AS VALUE NOT NULL
|);
|
""".trimMargin(),
tempFolder,
)
assertThat(result.errors).isEmpty()
val generatedInterface = result.compilerOutput.get(File(result.outputDirectory, "com/example/Test.kt"))
assertThat(generatedInterface).isNotNull()
assertThat(generatedInterface.toString()).isEqualTo(
"""
|package com.example
|
|import kotlin.Long
|import kotlin.jvm.JvmInline
|
|public data class Test(
| public val id: Id,
|) {
| @JvmInline
| public value class Id(
| public val id: Long,
| )
|}
|
""".trimMargin(),
)
}
@Test fun `postgres primary keys are non null`() {
val result = FixtureCompiler.compileSql(
"""
|CREATE TABLE test(
| bioguide_id VARCHAR,
| score_year INTEGER,
| score INTEGER NOT NULL,
| PRIMARY KEY(bioguide_id, score_year)
|);
|
""".trimMargin(),
tempFolder,
overrideDialect = PostgreSqlDialect(),
)
assertThat(result.errors).isEmpty()
val generatedInterface = result.compilerOutput.get(File(result.outputDirectory, "com/example/Test.kt"))
assertThat(generatedInterface).isNotNull()
assertThat(generatedInterface.toString()).isEqualTo(
"""
|package com.example
|
|import kotlin.Int
|import kotlin.String
|
|public data class Test(
| public val bioguide_id: String,
| public val score_year: Int,
| public val score: Int,
|)
|
""".trimMargin(),
)
}
private fun checkFixtureCompiles(fixtureRoot: String) {
val result = FixtureCompiler.compileFixture(
fixtureRoot = "src/test/table-interface-fixtures/$fixtureRoot",
compilationMethod = { _, _, sqlDelightQueriesFile, writer ->
SqlDelightCompiler.writeTableInterfaces(sqlDelightQueriesFile, writer)
},
generateDb = false,
)
for ((expectedFile, actualOutput) in result.compilerOutput) {
assertWithMessage("No file with name $expectedFile").that(expectedFile.exists()).isTrue()
assertWithMessage(expectedFile.name)
.that(expectedFile.readText().withInvariantLineSeparators())
.isEqualTo(actualOutput.toString())
}
}
}
| apache-2.0 | 5075701701d035fe4293d82b5e9aece6 | 33.738149 | 226 | 0.646306 | 4.301006 | false | true | false | false |
vondear/RxTools | RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityTabLayout.kt | 1 | 2198 | package com.tamsiree.rxdemo.activity
import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.tamsiree.rxdemo.R
import com.tamsiree.rxdemo.adapter.AdapterRecyclerViewMain
import com.tamsiree.rxdemo.adapter.AdapterRecyclerViewMain.ContentListener
import com.tamsiree.rxdemo.model.ModelDemo
import com.tamsiree.rxkit.RxActivityTool
import com.tamsiree.rxkit.RxImageTool
import com.tamsiree.rxkit.RxRecyclerViewDividerTool
import com.tamsiree.rxui.activity.ActivityBase
import kotlinx.android.synthetic.main.activity_tablayout.*
import java.util.*
class ActivityTabLayout : ActivityBase() {
private val mItems = arrayOf("TGlideTabLayout", "CommonTabLayout", "TSectionTabLayout")
private val mColumnCount = 2
private lateinit var mData: MutableList<ModelDemo>
private lateinit var madapter: AdapterRecyclerViewMain
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tablayout)
}
override fun initView() {
rx_title.setLeftFinish(this)
if (mColumnCount <= 1) {
recyclerview.layoutManager = LinearLayoutManager(mContext)
} else {
recyclerview.layoutManager = GridLayoutManager(mContext, mColumnCount)
}
recyclerview.addItemDecoration(RxRecyclerViewDividerTool(RxImageTool.dp2px(5f)))
mData = ArrayList()
madapter = AdapterRecyclerViewMain(mData, object : ContentListener {
override fun setListener(position: Int) {
RxActivityTool.skipActivity(mContext, mData[position].activity)
}
})
recyclerview.adapter = madapter
}
override fun initData() {
mData.clear()
mData.add(ModelDemo("TTabLayout", R.drawable.circle_elves_ball, ActivityTTabLayout::class.java))
mData.add(ModelDemo("TGlideTabLayout", R.drawable.circle_elves_ball, ActivityTGlideTabLayout::class.java))
mData.add(ModelDemo("TSectionTabLayout", R.drawable.circle_elves_ball, ActivityTSectionTabLayout::class.java))
madapter.notifyDataSetChanged()
}
} | apache-2.0 | 3dc0c8d755954462f251d17a319bc6ae | 40.490566 | 118 | 0.744313 | 4.541322 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/settings/SettingsPreferenceLoader.kt | 1 | 6471 | package org.wikipedia.settings
import android.content.DialogInterface
import android.content.Intent
import androidx.appcompat.app.AlertDialog
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreferenceCompat
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.analytics.LoginFunnel
import org.wikipedia.auth.AccountUtil
import org.wikipedia.feed.configure.ConfigureActivity
import org.wikipedia.login.LoginActivity
import org.wikipedia.readinglist.sync.ReadingListSyncAdapter
import org.wikipedia.settings.languages.WikipediaLanguagesActivity
import org.wikipedia.theme.ThemeFittingRoomActivity
/** UI code for app settings used by PreferenceFragment. */
internal class SettingsPreferenceLoader(fragment: PreferenceFragmentCompat) : BasePreferenceLoader(fragment) {
override fun loadPreferences() {
loadPreferences(R.xml.preferences)
if (RemoteConfig.config.disableReadingListSync) {
findPreference(R.string.preference_category_sync).isVisible = false
findPreference(R.string.preference_key_sync_reading_lists).isVisible = false
}
findPreference(R.string.preference_key_sync_reading_lists).onPreferenceChangeListener = SyncReadingListsListener()
findPreference(R.string.preference_key_eventlogging_opt_in).onPreferenceChangeListener = Preference.OnPreferenceChangeListener { preference: Preference, newValue: Any ->
if (!(newValue as Boolean)) {
Prefs.appInstallId = null
}
true
}
loadPreferences(R.xml.preferences_about)
updateLanguagePrefSummary()
findPreference(R.string.preference_key_language).onPreferenceClickListener = Preference.OnPreferenceClickListener {
activity.startActivityForResult(WikipediaLanguagesActivity.newIntent(activity, Constants.InvokeSource.SETTINGS),
Constants.ACTIVITY_REQUEST_ADD_A_LANGUAGE)
true
}
findPreference(R.string.preference_key_customize_explore_feed).onPreferenceClickListener = Preference.OnPreferenceClickListener {
activity.startActivityForResult(ConfigureActivity.newIntent(activity, Constants.InvokeSource.NAV_MENU.ordinal),
Constants.ACTIVITY_REQUEST_FEED_CONFIGURE)
true
}
findPreference(R.string.preference_key_color_theme).let {
it.setSummary(WikipediaApp.instance.currentTheme.nameId)
it.onPreferenceClickListener = Preference.OnPreferenceClickListener {
activity.startActivity(ThemeFittingRoomActivity.newIntent(activity))
true
}
}
findPreference(R.string.preference_key_about_wikipedia_app).onPreferenceClickListener = Preference.OnPreferenceClickListener {
activity.startActivity(Intent(activity, AboutActivity::class.java))
true
}
if (AccountUtil.isLoggedIn) {
loadPreferences(R.xml.preferences_account)
(findPreference(R.string.preference_key_logout) as LogoutPreference).activity = activity
}
}
fun updateLanguagePrefSummary() {
// TODO: resolve RTL vs LTR with multiple languages (e.g. list contains English and Hebrew)
findPreference(R.string.preference_key_language).summary = WikipediaApp.instance.languageState.appLanguageLocalizedNames
}
private inner class SyncReadingListsListener : Preference.OnPreferenceChangeListener {
override fun onPreferenceChange(preference: Preference, newValue: Any): Boolean {
if (AccountUtil.isLoggedIn) {
if (newValue as Boolean) {
(preference as SwitchPreferenceCompat).isChecked = true
ReadingListSyncAdapter.setSyncEnabledWithSetup()
} else {
AlertDialog.Builder(activity)
.setTitle(activity.getString(R.string.preference_dialog_of_turning_off_reading_list_sync_title, AccountUtil.userName))
.setMessage(activity.getString(R.string.preference_dialog_of_turning_off_reading_list_sync_text, AccountUtil.userName))
.setPositiveButton(R.string.reading_lists_confirm_remote_delete_yes, DeleteRemoteListsYesListener(preference))
.setNegativeButton(R.string.reading_lists_confirm_remote_delete_no, null)
.show()
}
} else {
AlertDialog.Builder(activity)
.setTitle(R.string.reading_list_preference_login_to_enable_sync_dialog_title)
.setMessage(R.string.reading_list_preference_login_to_enable_sync_dialog_text)
.setPositiveButton(R.string.reading_list_preference_login_to_enable_sync_dialog_login
) { _: DialogInterface, _: Int ->
val loginIntent = LoginActivity.newIntent(activity,
LoginFunnel.SOURCE_SETTINGS)
activity.startActivity(loginIntent)
}
.setNegativeButton(R.string.reading_list_preference_login_to_enable_sync_dialog_cancel, null)
.show()
}
// clicks are handled and preferences updated accordingly; don't pass the result through
return false
}
}
fun updateSyncReadingListsPrefSummary() {
findPreference(R.string.preference_key_sync_reading_lists).let {
if (AccountUtil.isLoggedIn) {
it.summary = activity.getString(R.string.preference_summary_sync_reading_lists_from_account, AccountUtil.userName)
} else {
it.setSummary(R.string.preference_summary_sync_reading_lists)
}
}
}
private inner class DeleteRemoteListsYesListener(private val preference: Preference) : DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface, which: Int) {
(preference as SwitchPreferenceCompat).isChecked = false
Prefs.isReadingListSyncEnabled = false
Prefs.isReadingListsRemoteSetupPending = false
Prefs.isReadingListsRemoteDeletePending = true
ReadingListSyncAdapter.manualSync()
}
}
}
| apache-2.0 | 51c3cba6b0cd186b6441d019bbf293d3 | 52.479339 | 177 | 0.677948 | 5.273839 | false | false | false | false |
stripe/stripe-android | payments-core/src/test/java/com/stripe/android/FakeFraudDetectionDataRepository.kt | 1 | 779 | package com.stripe.android
import com.stripe.android.networking.FraudDetectionData
import java.util.UUID
internal class FakeFraudDetectionDataRepository(
private val fraudDetectionData: FraudDetectionData?
) : FraudDetectionDataRepository {
@JvmOverloads constructor(
guid: UUID = UUID.randomUUID(),
muid: UUID = UUID.randomUUID(),
sid: UUID = UUID.randomUUID()
) : this(
FraudDetectionData(
guid = guid.toString(),
muid = muid.toString(),
sid = sid.toString()
)
)
override fun refresh() {
}
override fun getCached() = fraudDetectionData
override suspend fun getLatest() = fraudDetectionData
override fun save(fraudDetectionData: FraudDetectionData) {
}
}
| mit | 5c3e8b7b3e705f8cc3886006afe87f99 | 24.129032 | 63 | 0.664955 | 4.327778 | false | false | false | false |
exponent/exponent | packages/expo-dev-menu-interface/android/src/main/java/expo/interfaces/devmenu/items/DevMenuItemsContainer.kt | 2 | 1477 | package expo.interfaces.devmenu.items
import java.util.*
open class DevMenuItemsContainer : DevMenuDSLItemsContainerInterface {
private val items = mutableListOf<DevMenuScreenItem>()
override fun getRootItems(): List<DevMenuScreenItem> {
items.sortedWith(compareBy { it.importance })
return items
}
override fun getAllItems(): List<DevMenuScreenItem> {
val result = LinkedList<DevMenuScreenItem>()
items.forEach {
result.add(it)
if (it is DevMenuItemsContainerInterface) {
result.addAll(it.getAllItems())
}
}
return result
}
private fun addItem(item: DevMenuScreenItem) {
items.add(item)
}
override fun group(init: DevMenuGroup.() -> Unit) = addItem(DevMenuGroup(), init)
override fun action(actionId: String, action: () -> Unit, init: DevMenuAction.() -> Unit) =
addItem(DevMenuAction(actionId, action), init)
override fun link(target: String, init: DevMenuLink.() -> Unit) = addItem(DevMenuLink(target), init)
override fun selectionList(init: DevMenuSelectionList.() -> Unit) = addItem(DevMenuSelectionList(), init)
private fun <T : DevMenuScreenItem> addItem(item: T, init: T.() -> Unit): T {
item.init()
addItem(item)
return item
}
companion object {
@JvmStatic
fun export(init: DevMenuDSLItemsContainerInterface.() -> Unit): DevMenuItemsContainer {
val container = DevMenuItemsContainer()
container.init()
return container
}
}
}
| bsd-3-clause | 955b09179d75ce5b363a44575260b750 | 26.867925 | 107 | 0.691943 | 4.196023 | false | false | false | false |
thanksmister/androidthings-mqtt-alarm-panel | app/src/main/java/com/thanksmister/iot/mqtt/alarmpanel/network/TelegramApi.kt | 1 | 2704 | /*
* <!--
* ~ Copyright (c) 2017. ThanksMister LLC
* ~
* ~ Licensed under the Apache License, Version 2.0 (the "License");
* ~ you may not use this file except in compliance with the License.
* ~ You may obtain a copy of the License at
* ~
* ~ http://www.apache.org/licenses/LICENSE-2.0
* ~
* ~ Unless required by applicable law or agreed to in writing, software distributed
* ~ under the License is distributed on an "AS IS" BASIS,
* ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* ~ See the License for the specific language governing permissions and
* ~ limitations under the License.
* -->
*/
package com.thanksmister.iot.mqtt.alarmpanel.network
import android.graphics.Bitmap
import android.util.Base64
import com.facebook.stetho.okhttp3.StethoInterceptor
import com.google.gson.GsonBuilder
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import timber.log.Timber
import java.util.concurrent.TimeUnit
import okhttp3.MultipartBody
import java.io.ByteArrayOutputStream
class TelegramApi(private val token: String, private val chat_id:String) {
private val service: TelegramRequest
init {
val base_url = "https://api.telegram.org/bot$token/"
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.HEADERS
val httpClient = OkHttpClient.Builder()
.addInterceptor(logging)
.connectTimeout(10000, TimeUnit.SECONDS)
.readTimeout(10000, TimeUnit.SECONDS)
.addNetworkInterceptor(StethoInterceptor())
.build()
val gson = GsonBuilder()
.create()
val retrofit = Retrofit.Builder()
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(base_url)
.build()
service = retrofit.create(TelegramRequest::class.java)
}
fun sendMessage(text: String, bitmap:Bitmap): Call<JSONObject> {
val stream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 75, stream)
val byteArray = stream.toByteArray()
return service.sendPhoto(
RequestBody.create(MediaType.parse("multipart/form-data"), chat_id),
RequestBody.create(MediaType.parse("multipart/form-data"), text),
RequestBody.create(MediaType.parse("multipart/form-data"), byteArray))
}
} | apache-2.0 | c8f6fe9052f8984031a3ffa2581127e0 | 34.12987 | 87 | 0.682322 | 4.506667 | false | false | false | false |
AndroidX/androidx | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/RadioButton.kt | 3 | 9202 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material3
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.interaction.Interaction
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.selection.selectable
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.tokens.RadioButtonTokens
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.State
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
/**
* <a href="https://m3.material.io/components/radio-button/overview" class="external" target="_blank">Material Design radio button</a>.
*
* Radio buttons allow users to select one option from a set.
*
* 
*
* @sample androidx.compose.material3.samples.RadioButtonSample
*
* [RadioButton]s can be combined together with [Text] in the desired layout (e.g. [Column] or
* [Row]) to achieve radio group-like behaviour, where the entire layout is selectable:
* @sample androidx.compose.material3.samples.RadioGroupSample
*
* @param selected whether this radio button is selected or not
* @param onClick called when this radio button is clicked. If `null`, then this radio button will
* not be interactable, unless something else handles its input events and updates its state.
* @param modifier the [Modifier] to be applied to this radio button
* @param enabled controls the enabled state of this radio button. When `false`, this component will
* not respond to user input, and it will appear visually disabled and disabled to accessibility
* services.
* @param colors [RadioButtonColors] that will be used to resolve the color used for this radio
* button in different states. See [RadioButtonDefaults.colors].
* @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s
* for this radio button. You can create and pass in your own `remember`ed instance to observe
* [Interaction]s and customize the appearance / behavior of this radio button in different states.
*/
@Composable
fun RadioButton(
selected: Boolean,
onClick: (() -> Unit)?,
modifier: Modifier = Modifier,
enabled: Boolean = true,
colors: RadioButtonColors = RadioButtonDefaults.colors(),
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }
) {
val dotRadius = animateDpAsState(
targetValue = if (selected) RadioButtonDotSize / 2 else 0.dp,
animationSpec = tween(durationMillis = RadioAnimationDuration)
)
val radioColor = colors.radioColor(enabled, selected)
val selectableModifier =
if (onClick != null) {
Modifier.selectable(
selected = selected,
onClick = onClick,
enabled = enabled,
role = Role.RadioButton,
interactionSource = interactionSource,
indication = rememberRipple(
bounded = false,
radius = RadioButtonTokens.StateLayerSize / 2
)
)
} else {
Modifier
}
Canvas(
modifier
.then(
if (onClick != null) {
Modifier.minimumTouchTargetSize()
} else {
Modifier
}
)
.then(selectableModifier)
.wrapContentSize(Alignment.Center)
.padding(RadioButtonPadding)
.requiredSize(RadioButtonTokens.IconSize)
) {
// Draw the radio button
val strokeWidth = RadioStrokeWidth.toPx()
drawCircle(
radioColor.value,
radius = (RadioButtonTokens.IconSize / 2).toPx() - strokeWidth / 2,
style = Stroke(strokeWidth)
)
if (dotRadius.value > 0.dp) {
drawCircle(radioColor.value, dotRadius.value.toPx() - strokeWidth / 2, style = Fill)
}
}
}
/**
* Defaults used in [RadioButton].
*/
object RadioButtonDefaults {
/**
* Creates a [RadioButtonColors] that will animate between the provided colors according to
* the Material specification.
*
* @param selectedColor the color to use for the RadioButton when selected and enabled.
* @param unselectedColor the color to use for the RadioButton when unselected and enabled.
* @param disabledSelectedColor the color to use for the RadioButton when disabled and selected.
* @param disabledUnselectedColor the color to use for the RadioButton when disabled and not
* selected.
* @return the resulting [RadioButtonColors] used for the RadioButton
*/
@Composable
fun colors(
selectedColor: Color = RadioButtonTokens.SelectedIconColor.toColor(),
unselectedColor: Color = RadioButtonTokens.UnselectedIconColor.toColor(),
disabledSelectedColor: Color = RadioButtonTokens.DisabledSelectedIconColor
.toColor()
.copy(alpha = RadioButtonTokens.DisabledSelectedIconOpacity),
disabledUnselectedColor: Color = RadioButtonTokens.DisabledUnselectedIconColor
.toColor()
.copy(alpha = RadioButtonTokens.DisabledUnselectedIconOpacity)
): RadioButtonColors = RadioButtonColors(
selectedColor,
unselectedColor,
disabledSelectedColor,
disabledUnselectedColor
)
}
/**
* Represents the color used by a [RadioButton] in different states.
*
* See [RadioButtonDefaults.colors] for the default implementation that follows Material
* specifications.
*/
@Immutable
class RadioButtonColors internal constructor(
private val selectedColor: Color,
private val unselectedColor: Color,
private val disabledSelectedColor: Color,
private val disabledUnselectedColor: Color
) {
/**
* Represents the main color used to draw the outer and inner circles, depending on whether
* the [RadioButton] is [enabled] / [selected].
*
* @param enabled whether the [RadioButton] is enabled
* @param selected whether the [RadioButton] is selected
*/
@Composable
internal fun radioColor(enabled: Boolean, selected: Boolean): State<Color> {
val target = when {
enabled && selected -> selectedColor
enabled && !selected -> unselectedColor
!enabled && selected -> disabledSelectedColor
else -> disabledUnselectedColor
}
// If not enabled 'snap' to the disabled state, as there should be no animations between
// enabled / disabled.
return if (enabled) {
animateColorAsState(target, tween(durationMillis = RadioAnimationDuration))
} else {
rememberUpdatedState(target)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || other !is RadioButtonColors) return false
if (selectedColor != other.selectedColor) return false
if (unselectedColor != other.unselectedColor) return false
if (disabledSelectedColor != other.disabledSelectedColor) return false
if (disabledUnselectedColor != other.disabledUnselectedColor) return false
return true
}
override fun hashCode(): Int {
var result = selectedColor.hashCode()
result = 31 * result + unselectedColor.hashCode()
result = 31 * result + disabledSelectedColor.hashCode()
result = 31 * result + disabledUnselectedColor.hashCode()
return result
}
}
private const val RadioAnimationDuration = 100
private val RadioButtonPadding = 2.dp
private val RadioButtonDotSize = 12.dp
private val RadioStrokeWidth = 2.dp
| apache-2.0 | 236ed116ec25ea5d8d65b1730c79b2f9 | 39.897778 | 135 | 0.704738 | 4.947312 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/PrefsActivity.kt | 2 | 2723 | package com.habitrpg.android.habitica.ui.activities
import android.os.Bundle
import android.view.ViewGroup
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceScreen
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.ui.fragments.preferences.AccountPreferenceFragment
import com.habitrpg.android.habitica.ui.fragments.preferences.EmailNotificationsPreferencesFragment
import com.habitrpg.android.habitica.ui.fragments.preferences.PreferencesFragment
import com.habitrpg.android.habitica.ui.fragments.preferences.PushNotificationsPreferencesFragment
import com.habitrpg.android.habitica.ui.views.SnackbarActivity
class PrefsActivity : BaseActivity(), PreferenceFragmentCompat.OnPreferenceStartScreenCallback, SnackbarActivity {
override fun getLayoutResId(): Int = R.layout.activity_prefs
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupToolbar(findViewById(R.id.toolbar))
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, PreferencesFragment())
.commit()
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
override fun onSupportNavigateUp(): Boolean {
if (supportFragmentManager.backStackEntryCount > 0) {
onBackPressed()
return true
}
return super.onSupportNavigateUp()
}
override fun onPreferenceStartScreen(
preferenceFragment: PreferenceFragmentCompat,
preferenceScreen: PreferenceScreen
): Boolean {
val fragment = createNextPage(preferenceScreen)
if (fragment != null) {
val arguments = Bundle()
arguments.putString(PreferenceFragmentCompat.ARG_PREFERENCE_ROOT, preferenceScreen.key)
fragment.arguments = arguments
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit()
return true
}
return false
}
private fun createNextPage(preferenceScreen: PreferenceScreen): PreferenceFragmentCompat? =
when (preferenceScreen.key) {
"my_account" -> AccountPreferenceFragment()
"pushNotifications" -> PushNotificationsPreferencesFragment()
"emailNotifications" -> EmailNotificationsPreferencesFragment()
else -> null
}
override fun snackbarContainer(): ViewGroup {
val v = findViewById<ViewGroup>(R.id.snackbar_container)
return v
}
}
| gpl-3.0 | 7cef50a347dfe00ccb50dbc43c635122 | 37.352113 | 114 | 0.717958 | 5.68476 | false | false | false | false |
RSDT/Japp16 | app/src/main/java/nl/rsdt/japp/jotial/maps/management/controllers/EchoVosController.kt | 2 | 706 | package nl.rsdt.japp.jotial.maps.management.controllers
import nl.rsdt.japp.jotial.maps.wrapper.IJotiMap
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 31-7-2016
* Description...
*/
class EchoVosController(jotiMap: IJotiMap) : VosController(jotiMap) {
override val team: String
get() = "e"
override val id: String
get() = CONTROLLER_ID
override val storageId: String
get() = STORAGE_ID
override val bundleId: String
get() = BUNDLE_ID
companion object {
val CONTROLLER_ID = "EchoVosController"
val STORAGE_ID = "STORAGE_VOS_E"
val BUNDLE_ID = "VOS_E"
val REQUEST_ID = "REQUEST_VOS_E"
}
}
| apache-2.0 | 969d489ebd07261adcb8131ac175cf0b | 18.081081 | 69 | 0.628895 | 3.565657 | false | false | false | false |
DemonWav/StatCraft | src/main/kotlin/com/demonwav/statcraft/listeners/BucketEmptyListener.kt | 1 | 2382 | /*
* StatCraft Bukkit Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.listeners
import com.demonwav.statcraft.StatCraft
import com.demonwav.statcraft.magic.BucketCode
import com.demonwav.statcraft.querydsl.QBucketEmpty
import org.bukkit.Material
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerBucketEmptyEvent
import org.bukkit.event.player.PlayerItemConsumeEvent
class BucketEmptyListener(private val plugin: StatCraft) : Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
fun onBucketEmpty(event: PlayerBucketEmptyEvent) {
val uuid = event.player.uniqueId
val worldName = event.player.world.name
val code: BucketCode
if (event.bucket == Material.LAVA_BUCKET) {
code = BucketCode.LAVA
} else {
// default to water
code = BucketCode.WATER
}
plugin.threadManager.schedule<QBucketEmpty>(
uuid, worldName,
{ e, clause, id, worldId ->
clause.columns(e.id, e.worldId, e.type, e.amount)
.values(id, worldId, code.code, 1).execute()
}, { e, clause, id, worldId ->
clause.where(e.id.eq(id), e.worldId.eq(worldId), e.type.eq(code.code))
.set(e.amount, e.amount.add(1)).execute()
}
)
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
fun onPlayerConsume(event: PlayerItemConsumeEvent) {
if (event.item.type == Material.MILK_BUCKET) {
val uuid = event.player.uniqueId
val worldName = event.player.world.name
val code = BucketCode.MILK
plugin.threadManager.schedule<QBucketEmpty>(
uuid, worldName,
{ e, clause, id, worldId ->
clause.columns(e.id, e.worldId, e.type, e.amount)
.values(id, worldId, code.code, 1).execute()
}, { e, clause, id, worldId ->
clause.where(e.id.eq(id), e.worldId.eq(worldId), e.type.eq(code.code))
.set(e.amount, e.amount.add(1)).execute()
}
)
}
}
}
| mit | 12493f51b497f30ed2174d7bfc2b6aba | 35.090909 | 90 | 0.606213 | 4.044143 | false | false | false | false |
hidroh/tldroid | app/src/main/kotlin/io/github/hidroh/tldroid/MarkdownProcessor.kt | 1 | 3235 | package io.github.hidroh.tldroid
import android.content.ContentProviderOperation
import android.content.Context
import android.content.OperationApplicationException
import android.os.RemoteException
import android.support.annotation.WorkerThread
import android.text.TextUtils
import com.github.rjeschke.txtmark.Processor
import java.io.File
import java.io.IOException
import java.util.zip.ZipFile
class MarkdownProcessor(private val platform: String?) {
@WorkerThread
fun process(context: Context, commandName: String, lastModified: Long): String? {
val selection = "${TldrProvider.CommandEntry.COLUMN_NAME}=? AND " +
"${TldrProvider.CommandEntry.COLUMN_PLATFORM}=? AND " +
"${TldrProvider.CommandEntry.COLUMN_MODIFIED}>=?"
val selectionArgs = arrayOf(commandName, platform?: "", lastModified.toString())
val cursor = context.contentResolver.query(
TldrProvider.URI_COMMAND, null, selection, selectionArgs, null)
val markdown = if (cursor != null && cursor.moveToFirst()) {
cursor.getString(cursor.getColumnIndex(TldrProvider.CommandEntry.COLUMN_TEXT))
} else {
loadFromZip(context, commandName, platform ?: findPlatform(context, commandName), lastModified)
}
cursor?.close()
return if (TextUtils.isEmpty(markdown)) null else Processor.process(markdown)
.replace("{{", """<span class="literal">""")
.replace("}}", """</span>""")
}
private fun loadFromZip(context: Context, name: String, platform: String?, lastModified: Long): String? {
platform ?: return null
val markdown: String
try {
val zip = ZipFile(File(context.cacheDir, Constants.ZIP_FILENAME), ZipFile.OPEN_READ)
markdown = Utils.readUtf8(zip.getInputStream(zip.getEntry(
Constants.COMMAND_PATH.format(platform, name))))
zip.close()
} catch (e: IOException) {
return null
} catch (e: NullPointerException) {
return null
}
persist(context, name, platform, markdown, lastModified)
return markdown
}
private fun findPlatform(context: Context, name: String): String? {
val cursor = context.contentResolver.query(TldrProvider.URI_COMMAND, null,
"${TldrProvider.CommandEntry.COLUMN_NAME}=?", arrayOf(name), null)
val platform = if (cursor != null && cursor.moveToFirst()) {
cursor.getString(cursor.getColumnIndex(TldrProvider.CommandEntry.COLUMN_PLATFORM))
} else {
null
}
cursor?.close()
return platform
}
private fun persist(context: Context, name: String, platform: String, markdown: String, lastModified: Long) {
val operations = arrayListOf(ContentProviderOperation.newUpdate(TldrProvider.URI_COMMAND)
.withValue(TldrProvider.CommandEntry.COLUMN_TEXT, markdown)
.withValue(TldrProvider.CommandEntry.COLUMN_MODIFIED, lastModified)
.withSelection("${TldrProvider.CommandEntry.COLUMN_PLATFORM}=? AND " +
"${TldrProvider.CommandEntry.COLUMN_NAME}=?",
arrayOf(platform, name))
.build())
try {
context.contentResolver.applyBatch(TldrProvider.AUTHORITY, operations)
} catch (e: RemoteException) {
// no op
} catch (e: OperationApplicationException) {
// no op
}
}
} | apache-2.0 | ab075fb4769a37df145c99d8c11a3cd8 | 39.45 | 111 | 0.703864 | 4.319092 | false | false | false | false |
collaction/freehkkai-android | app/src/main/java/hk/collaction/freehkkai/util/ext/NumberExt.kt | 1 | 1115 | package hk.collaction.freehkkai.util.ext
import android.content.res.Resources
import android.util.TypedValue
import java.math.BigDecimal
import java.math.RoundingMode
import kotlin.math.roundToInt
fun Float.dp2px(): Int =
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
this,
Resources.getSystem().displayMetrics
).toInt()
fun Float.px2dp(): Float {
val scale = Resources.getSystem().displayMetrics.density
return (this / scale + 0.5F)
}
fun Int.px2dp() = this.toFloat().px2dp().toInt()
fun Float.px2sp(): Float {
val fontScale = Resources.getSystem().displayMetrics.density
return (this / fontScale + 0.5F)
}
fun Int.px2sp() = this.toFloat().px2sp().toInt()
fun Float.roundTo(n: Int): Float {
return this.toDouble().roundTo(n).toFloat()
}
fun Double.roundTo(n: Int): Double {
if (this.isNaN()) return 0.0
return try {
BigDecimal(this).setScale(n, RoundingMode.HALF_EVEN).toDouble()
} catch (e: NumberFormatException) {
this.roundToInt().toDouble()
}
}
fun Double.format(digits: Int) = "%.${digits}f".format(this) | gpl-3.0 | e239557a1cc44524916a6d7d5527cffa | 24.363636 | 71 | 0.686099 | 3.528481 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/bike_parking_cover/AddBikeParkingCover.kt | 1 | 1199 | package de.westnordost.streetcomplete.quests.bike_parking_cover
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.ktx.toYesNo
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddBikeParkingCover : OsmFilterQuestType<Boolean>() {
override val elementFilter = """
nodes, ways with
amenity = bicycle_parking
and access !~ private|no
and !covered
and bicycle_parking !~ shed|lockers|building
"""
override val commitMessage = "Add bicycle parkings cover"
override val wikiLink = "Tag:amenity=bicycle_parking"
override val icon = R.drawable.ic_quest_bicycle_parking_cover
override val isDeleteElementEnabled = true
override fun getTitle(tags: Map<String, String>) =
R.string.quest_bicycleParkingCoveredStatus_title
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("covered", answer.toYesNo())
}
}
| gpl-3.0 | 4f3264228d655675576cfae0ee7f898a | 37.677419 | 83 | 0.753962 | 4.720472 | false | false | false | false |
wix/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/options/ShadowOptions.kt | 1 | 1822 | package com.reactnativenavigation.options
import android.content.Context
import com.reactnativenavigation.options.params.Fraction
import com.reactnativenavigation.options.params.NullFraction
import com.reactnativenavigation.options.params.NullThemeColour
import com.reactnativenavigation.options.params.ThemeColour
import com.reactnativenavigation.options.parsers.FractionParser
import org.json.JSONObject
fun parseShadowOptions(context: Context, shadowJson: JSONObject?): ShadowOptions = shadowJson?.let { json ->
ShadowOptions(
ThemeColour.parse(context, json.optJSONObject("color")), FractionParser.parse(json, "radius"),
FractionParser
.parse(
json,
"opacity"
)
)
} ?: NullShadowOptions
object NullShadowOptions : ShadowOptions() {
override fun hasValue(): Boolean = false
}
open class ShadowOptions(
var color: ThemeColour = NullThemeColour(), var radius: Fraction = NullFraction(), var opacity: Fraction =
NullFraction()
) {
fun copy(): ShadowOptions = ShadowOptions(this.color, this.radius, this.opacity)
fun mergeWith(other: ShadowOptions): ShadowOptions {
if(other.color.hasValue()) this.color = other.color;
if (other.opacity.hasValue()) this.opacity = other.opacity
if (other.radius.hasValue()) this.radius = other.radius
return this
}
fun mergeWithDefaults(defaultOptions: ShadowOptions = NullShadowOptions): ShadowOptions {
if(!this.color.hasValue()) this.color = defaultOptions.color;
if (!this.opacity.hasValue()) this.opacity = defaultOptions.opacity
if (!this.radius.hasValue()) this.radius = defaultOptions.radius
return this
}
open fun hasValue() = color.hasValue() || radius.hasValue() || opacity.hasValue()
} | mit | bc67f4aeecdca62cf266e54d0e83252b | 36.204082 | 110 | 0.71405 | 4.566416 | false | false | false | false |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/quests/note_discussion/AttachPhotoFragment.kt | 1 | 5890 | package de.westnordost.streetcomplete.quests.note_discussion
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import androidx.fragment.app.Fragment
import androidx.core.content.FileProvider
import androidx.recyclerview.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.ArrayList
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osmnotes.AttachPhotoUtils
import android.app.Activity.RESULT_OK
import de.westnordost.streetcomplete.ApplicationConstants.ATTACH_PHOTO_MAXWIDTH
import de.westnordost.streetcomplete.ApplicationConstants.ATTACH_PHOTO_QUALITY
import de.westnordost.streetcomplete.ktx.toast
import kotlinx.android.synthetic.main.fragment_attach_photo.*
class AttachPhotoFragment : Fragment() {
val imagePaths: List<String> get() = noteImageAdapter.list
private var currentImagePath: String? = null
private lateinit var noteImageAdapter: NoteImageAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_attach_photo, container, false)
if (!activity!!.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
view.visibility = View.GONE
}
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
takePhotoButton.setOnClickListener { takePhoto() }
val paths: ArrayList<String>
if (savedInstanceState != null) {
paths = savedInstanceState.getStringArrayList(PHOTO_PATHS)!!
currentImagePath = savedInstanceState.getString(CURRENT_PHOTO_PATH)
} else {
paths = ArrayList()
currentImagePath = null
}
noteImageAdapter = NoteImageAdapter(paths, context!!)
gridView.layoutManager = LinearLayoutManager(
context,
LinearLayoutManager.HORIZONTAL,
false
)
gridView.adapter = noteImageAdapter
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putStringArrayList(PHOTO_PATHS, ArrayList(imagePaths))
outState.putString(CURRENT_PHOTO_PATH, currentImagePath)
}
private fun takePhoto() {
val takePhotoIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
activity?.packageManager?.let { packageManager ->
if (takePhotoIntent.resolveActivity(packageManager) != null) {
try {
val photoFile = createImageFile()
val photoUri = if (Build.VERSION.SDK_INT > 21) {
//Use FileProvider for getting the content:// URI, see: https://developer.android.com/training/camera/photobasics.html#TaskPath
FileProvider.getUriForFile(activity!!,getString(R.string.fileprovider_authority),photoFile)
} else {
Uri.fromFile(photoFile)
}
currentImagePath = photoFile.path
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
startActivityForResult(takePhotoIntent, REQUEST_TAKE_PHOTO)
} catch (e: IOException) {
Log.e(TAG, "Unable to create file for photo", e)
context?.toast(R.string.quest_leave_new_note_create_image_error)
} catch (e: IllegalArgumentException) {
Log.e(TAG, "Unable to create file for photo", e)
context?.toast(R.string.quest_leave_new_note_create_image_error)
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_TAKE_PHOTO) {
if (resultCode == RESULT_OK) {
try {
val path = currentImagePath!!
val bitmap = AttachPhotoUtils.resize(path, ATTACH_PHOTO_MAXWIDTH) ?: throw IOException()
val out = FileOutputStream(path)
bitmap.compress(Bitmap.CompressFormat.JPEG, ATTACH_PHOTO_QUALITY, out)
noteImageAdapter.list.add(path)
noteImageAdapter.notifyItemInserted(imagePaths.size - 1)
} catch (e: IOException) {
Log.e(TAG, "Unable to rescale the photo", e)
context?.toast(R.string.quest_leave_new_note_create_image_error)
removeCurrentImage()
}
} else {
removeCurrentImage()
}
currentImagePath = null
}
}
private fun removeCurrentImage() {
currentImagePath?.let {
val photoFile = File(it)
if (photoFile.exists()) {
photoFile.delete()
}
}
}
private fun createImageFile(): File {
val directory = activity!!.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile("photo", ".jpg", directory)
}
fun deleteImages() {
AttachPhotoUtils.deleteImages(imagePaths)
}
companion object {
private const val TAG = "AttachPhotoFragment"
private const val REQUEST_TAKE_PHOTO = 1
private const val PHOTO_PATHS = "photo_paths"
private const val CURRENT_PHOTO_PATH = "current_photo_path"
}
}
| gpl-3.0 | eb52cb4c37f1d75b843ef9385b1658e3 | 36.515924 | 151 | 0.64601 | 4.953743 | false | false | false | false |
huy-vuong/streamr | app/src/main/java/com/huyvuong/streamr/model/transport/photos/exif/GetExifResponse.kt | 1 | 1109 | package com.huyvuong.streamr.model.transport.photos.exif
import com.google.gson.annotations.SerializedName
/**
* Response from flickr.photos.getExif.
*/
data class GetExifResponse(
@SerializedName("photo") val exifSummary: ExifSummary,
@SerializedName("stat") val status: String,
@SerializedName("code") val code: Int)
data class ExifSummary(
@SerializedName("id") val photoId: String,
@SerializedName("camera") val camera: String,
@SerializedName("exif") val exifEntries: List<ExifEntry>) {
operator fun contains(tag: String): Boolean {
return exifEntries.any { it.tag == tag }
}
operator fun get(tag: String): String? {
return exifEntries.firstOrNull { it.tag == tag }?.rawContent?.content
}
}
data class ExifEntry(
@SerializedName("tag") val tag: String,
@SerializedName("label") val label: String,
@SerializedName("raw") val rawContent: ExifContent,
@SerializedName("clean") val cleanContent: ExifContent? = null)
data class ExifContent(@SerializedName("_content") val content: String) | gpl-3.0 | f9c5979834909a1c74c2e3f33c1b2235 | 33.6875 | 77 | 0.682597 | 4.281853 | false | false | false | false |
marius-m/racer_test | core/src/main/java/lt/markmerkk/app/box2d/temp_components/wheel/BaseWheelImpl.kt | 1 | 2320 | package lt.markmerkk.app.box2d.temp_components.wheel
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.*
import lt.markmerkk.app.box2d.CarBox2D
/**
* @author mariusmerkevicius
* @since 2016-08-28
*/
abstract class BaseWheelImpl(
override val world: World,
override val carBox2D: CarBox2D,
override var posX: Float,
override var posY: Float,
override val width: Float,
override val height: Float,
override val powered: Boolean
) : Wheel {
override val body: Body
init {
//init body
val bodyDef = BodyDef()
bodyDef.type = BodyDef.BodyType.DynamicBody
bodyDef.position.set(carBox2D.body.getWorldPoint(Vector2(posX, posY)))
bodyDef.angle = carBox2D.body.angle
this.body = world.createBody(bodyDef)
//init shape
val fixtureDef = FixtureDef()
fixtureDef.density = 1.0f
fixtureDef.isSensor = true
val wheelShape = PolygonShape()
wheelShape.setAsBox(width / 2, height / 2)
fixtureDef.shape = wheelShape
this.body.createFixture(fixtureDef)
wheelShape.dispose()
initJoint(world, carBox2D)
}
abstract fun initJoint(world: World, carBox2D: CarBox2D)
override fun localVelocity(): Vector2 {
return carBox2D.body.getLocalVector(carBox2D.body.getLinearVelocityFromLocalPoint(body.position))
}
override fun directionVector(): Vector2 {
val directionVector: Vector2
if (localVelocity().y > 0)
directionVector = Vector2(0f, 1f)
else
directionVector = Vector2(0f, -1f)
return directionVector.rotate(Math.toDegrees(body.angle.toDouble()).toFloat())
}
override fun changeAngle(angle: Float) {
body.setTransform(body.position, carBox2D.body.angle + Math.toRadians(angle.toDouble()).toFloat())
}
override fun killSidewayVector() {
body.linearVelocity = killedLocalVelocity()
}
//region Convenience
private fun killedLocalVelocity(): Vector2 {
val velocity = body.linearVelocity
val sidewaysAxis = directionVector()
val dotprod = velocity.dot(sidewaysAxis)
return Vector2(sidewaysAxis.x * dotprod, sidewaysAxis.y * dotprod)
}
//endregion
} | apache-2.0 | 7a7c66d1a1948fb72a36fd985122eedf | 28.0125 | 106 | 0.660345 | 3.938879 | false | false | false | false |
tommybuonomo/dotsindicator | viewpagerdotsindicator/src/main/kotlin/com/tbuonomo/viewpagerdotsindicator/BaseDotsIndicator.kt | 1 | 7025 | package com.tbuonomo.viewpagerdotsindicator
import android.content.Context
import android.graphics.Color
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.os.Parcelable
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.annotation.StyleableRes
import androidx.viewpager.widget.ViewPager
import androidx.viewpager2.widget.ViewPager2
import com.tbuonomo.viewpagerdotsindicator.attacher.ViewPager2Attacher
import com.tbuonomo.viewpagerdotsindicator.attacher.ViewPagerAttacher
abstract class BaseDotsIndicator @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
companion object {
const val DEFAULT_POINT_COLOR = Color.CYAN
}
enum class Type(
val defaultSize: Float,
val defaultSpacing: Float,
@StyleableRes val styleableId: IntArray,
@StyleableRes val dotsColorId: Int,
@StyleableRes val dotsSizeId: Int,
@StyleableRes val dotsSpacingId: Int,
@StyleableRes val dotsCornerRadiusId: Int,
@StyleableRes val dotsClickableId: Int
) {
DEFAULT(
16f,
8f,
R.styleable.SpringDotsIndicator,
R.styleable.SpringDotsIndicator_dotsColor,
R.styleable.SpringDotsIndicator_dotsSize,
R.styleable.SpringDotsIndicator_dotsSpacing,
R.styleable.SpringDotsIndicator_dotsCornerRadius,
R.styleable.SpringDotsIndicator_dotsClickable
),
SPRING(
16f,
4f,
R.styleable.DotsIndicator,
R.styleable.DotsIndicator_dotsColor,
R.styleable.DotsIndicator_dotsSize,
R.styleable.DotsIndicator_dotsSpacing,
R.styleable.DotsIndicator_dotsCornerRadius,
R.styleable.SpringDotsIndicator_dotsClickable
),
WORM(
16f,
4f,
R.styleable.WormDotsIndicator,
R.styleable.WormDotsIndicator_dotsColor,
R.styleable.WormDotsIndicator_dotsSize,
R.styleable.WormDotsIndicator_dotsSpacing,
R.styleable.WormDotsIndicator_dotsCornerRadius,
R.styleable.SpringDotsIndicator_dotsClickable
)
}
@JvmField
protected val dots = ArrayList<ImageView>()
var dotsClickable: Boolean = true
var dotsColor: Int = DEFAULT_POINT_COLOR
set(value) {
field = value
refreshDotsColors()
}
protected var dotsSize = dpToPxF(type.defaultSize)
protected var dotsCornerRadius = dotsSize / 2f
protected var dotsSpacing = dpToPxF(type.defaultSpacing)
init {
if (attrs != null) {
val a = context.obtainStyledAttributes(attrs, type.styleableId)
dotsColor = a.getColor(type.dotsColorId, DEFAULT_POINT_COLOR)
dotsSize = a.getDimension(type.dotsSizeId, dotsSize)
dotsCornerRadius = a.getDimension(type.dotsCornerRadiusId, dotsCornerRadius)
dotsSpacing = a.getDimension(type.dotsSpacingId, dotsSpacing)
dotsClickable = a.getBoolean(type.dotsClickableId, true)
a.recycle()
}
}
var pager: Pager? = null
interface Pager {
val isNotEmpty: Boolean
val currentItem: Int
val isEmpty: Boolean
val count: Int
fun setCurrentItem(item: Int, smoothScroll: Boolean)
fun removeOnPageChangeListener()
fun addOnPageChangeListener(onPageChangeListenerHelper: OnPageChangeListenerHelper)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
post { refreshDots() }
}
private fun refreshDotsCount() {
if (dots.size < pager!!.count) {
addDots(pager!!.count - dots.size)
} else if (dots.size > pager!!.count) {
removeDots(dots.size - pager!!.count)
}
}
protected fun refreshDotsColors() {
for (i in dots.indices) {
refreshDotColor(i)
}
}
protected fun dpToPx(dp: Int): Int {
return (context.resources.displayMetrics.density * dp).toInt()
}
protected fun dpToPxF(dp: Float): Float {
return context.resources.displayMetrics.density * dp
}
protected fun addDots(count: Int) {
for (i in 0 until count) {
addDot(i)
}
}
private fun removeDots(count: Int) {
for (i in 0 until count) {
removeDot()
}
}
fun refreshDots() {
if (pager == null) {
return
}
post {
// Check if we need to refresh the dots count
refreshDotsCount()
refreshDotsColors()
refreshDotsSize()
refreshOnPageChangedListener()
}
}
private fun refreshOnPageChangedListener() {
if (pager!!.isNotEmpty) {
pager!!.removeOnPageChangeListener()
val onPageChangeListenerHelper = buildOnPageChangedListener()
pager!!.addOnPageChangeListener(onPageChangeListenerHelper)
onPageChangeListenerHelper.onPageScrolled(pager!!.currentItem, 0f)
}
}
private fun refreshDotsSize() {
dots.forEach { it.setWidth(dotsSize.toInt()) }
}
// ABSTRACT METHODS AND FIELDS
abstract fun refreshDotColor(index: Int)
abstract fun addDot(index: Int)
abstract fun removeDot()
abstract fun buildOnPageChangedListener(): OnPageChangeListenerHelper
abstract val type: Type
// PUBLIC METHODS
@Deprecated(
"Use setDotsColors(color) instead", ReplaceWith("setDotsColors(color)")
)
fun setPointsColor(color: Int) {
dotsColor = color
refreshDotsColors()
}
@Deprecated(
"Use attachTo(viewPager) instead", ReplaceWith("attachTo(viewPager)")
)
fun setViewPager(viewPager: ViewPager) {
ViewPagerAttacher().setup(this, viewPager)
}
@Deprecated(
"Use attachTo(viewPager) instead", ReplaceWith("attachTo(viewPager)")
)
fun setViewPager2(viewPager2: ViewPager2) {
ViewPager2Attacher().setup(this, viewPager2)
}
fun attachTo(viewPager: ViewPager) {
ViewPagerAttacher().setup(this, viewPager)
}
fun attachTo(viewPager2: ViewPager2) {
ViewPager2Attacher().setup(this, viewPager2)
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1 && layoutDirection == View.LAYOUT_DIRECTION_RTL) {
layoutDirection = View.LAYOUT_DIRECTION_LTR
rotation = 180f
requestLayout()
}
}
override fun onRestoreInstanceState(state: Parcelable?) {
super.onRestoreInstanceState(state)
post { refreshDots() }
}
} | apache-2.0 | f5542c7597322c0593614b1196c7f667 | 29.815789 | 110 | 0.642705 | 4.603539 | false | false | false | false |
ncruz8991/kotlin-koans | src/ii_collections/_14_FilterMap.kt | 1 | 537 | package ii_collections
fun example1(list: List<Int>) {
// If a lambda has exactly one parameter, that parameter can be accessed as 'it'
val positiveNumbers = list.filter { it > 0 }
val squares = list.map { it * it }
}
// Return the set of cities the customers are from
fun Shop.getCitiesCustomersAreFrom(): Set<City> = this.customers.map { it.city } .toSet()
// Return a list of the customers who live in the given city
fun Shop.getCustomersFrom(city: City): List<Customer> = this.customers.filter { it.city == city }
| mit | aafe11c88766b680f1faeff5f1fac27c | 30.588235 | 97 | 0.703911 | 3.755245 | false | false | false | false |
ShadwLink/Shadow-Mapper | src/main/java/nl/shadowlink/tools/shadowmapper/gui/preview/GlListener.kt | 1 | 6335 | package nl.shadowlink.tools.shadowmapper.gui.preview
import com.jogamp.opengl.*
import com.jogamp.opengl.fixedfunc.GLMatrixFunc
import com.jogamp.opengl.glu.GLU
import nl.shadowlink.tools.io.ByteReader
import nl.shadowlink.tools.shadowlib.model.model.Model
import nl.shadowlink.tools.shadowlib.texturedic.TextureDic
import nl.shadowlink.tools.shadowmapper.FileManager
import nl.shadowlink.tools.shadowmapper.render.Camera
import nl.shadowlink.tools.shadowmapper.utils.toGl
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import java.awt.event.MouseWheelEvent
/**
* @author Shadow-Link
*/
class GlListener : GLEventListener {
var fm: FileManager? = null
var camera: Camera? = null
private var modelZoom = -20.0f
private var rotationX = 0.0f
private var rotationY = 0.0f
private var dragX = -1
private var dragY = -1
var mdl: Model? = Model()
var txd: TextureDic? = null
// public WBDFile wbd;
// public WBNFile wbn;
var type = -1
var size = -1
var br: ByteReader? = null
var load = false
private var selected = 0
private var selPoly = 0
fun mouseWheelMoved(evt: MouseWheelEvent) {
if (evt.scrollType == MouseWheelEvent.WHEEL_UNIT_SCROLL) {
modelZoom -= (evt.wheelRotation / 1.5).toFloat()
}
}
fun mousePressed(evt: MouseEvent) {
dragX = evt.x
dragY = evt.y
}
fun keyPressed(evt: KeyEvent) {
if (evt.keyCode == KeyEvent.VK_UP) {
selPoly += 1
}
if (evt.keyCode == KeyEvent.VK_DOWN) {
selPoly -= 1
}
if (evt.keyCode == KeyEvent.VK_P) {
println("Sel poly: $selPoly")
}
}
fun mouseMoved(evt: MouseEvent) {
if (evt.modifiers == 4) {
val newX = dragX - evt.x
val newY = dragY - evt.y
dragX = evt.x
dragY = evt.y
rotationX += newX.toFloat()
rotationY += newY.toFloat()
}
}
private var txdArray: IntArray? = null
private fun loadModel(gl: GL2) {
mdl = null
mdl = Model()
when (type) {
0 -> mdl!!.loadWDR(br, size)
1 -> mdl!!.loadWFT(br, size)
2 -> mdl!!.loadWDD(br, size, null)
3 -> txdArray = txd!!.toGl(gl)
4 -> {}
5 -> {}
}
load = false
}
fun loadTxdIntoGl(txd: TextureDic?) {
this.txd = txd
type = 3
load = true
}
override fun display(drawable: GLAutoDrawable) {
val gl = drawable.gl.gL2
val glu = GLU()
if (load) {
loadModel(gl)
}
gl.glClear(GL.GL_COLOR_BUFFER_BIT or GL.GL_DEPTH_BUFFER_BIT)
gl.glLoadIdentity()
glu.gluLookAt(
camera!!.posX, camera!!.posY, camera!!.posZ, camera!!.viewX, camera!!.viewY,
camera!!.viewZ, camera!!.upX, camera!!.upY, camera!!.upZ
)
gl.glPolygonMode(GL2.GL_FRONT, GL2.GL_FILL)
if (type == 3 && txdArray != null) {
val height = 512
val width = 512
gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION)
gl.glPushMatrix()
gl.glLoadIdentity()
gl.glOrtho(0.0, height.toDouble(), 0.0, width.toDouble(), -1.0, 1.0)
gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW)
gl.glPushMatrix()
gl.glLoadIdentity()
gl.glTranslatef(0f, 512f, 0f)
gl.glRotatef(-90f, 0.0f, 0.0f, 1.0f)
// TODO: Fix this
gl.glBindTexture(GL.GL_TEXTURE_2D, txdArray!![selected])
gl.glBegin(GL2ES3.GL_QUADS)
gl.glTexCoord2d(0.0, 0.0)
gl.glVertex2f(0f, 0f)
gl.glTexCoord2d(0.0, 1.0)
gl.glVertex2f(txd!!.textures[selected].height.toFloat(), 0f)
gl.glTexCoord2d(1.0, 1.0)
gl.glVertex2f(txd!!.textures[selected].height.toFloat(), txd!!.textures[selected].width.toFloat())
gl.glTexCoord2d(1.0, 0.0)
gl.glVertex2f(0f, txd!!.textures[selected].width.toFloat())
gl.glEnd()
gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION)
gl.glPopMatrix()
gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW)
gl.glPopMatrix()
} else if (type == 4 || type == 5) {
// Do nothing yet
} else {
gl.glPushMatrix()
gl.glTranslatef(0f, 2f, modelZoom)
gl.glRotatef(270f, 1.0f, 0.0f, 0.0f)
gl.glRotatef(rotationX, 0.0f, 0.0f, 1.0f)
gl.glRotatef(rotationY, 0.0f, 1.0f, 0.0f)
gl.glColor3f(1.0f, 1.0f, 1.0f)
if (mdl!!.isLoaded) {
mdl!!.render(gl)
}
gl.glPopMatrix()
}
gl.glFlush()
}
override fun reshape(drawable: GLAutoDrawable, x: Int, y: Int, width: Int, height: Int) {
var height = height
val gl = drawable.gl.gL2
val glu = GLU()
if (height <= 0) { // avoid a divide by zero error!
height = 1
}
val h = width.toFloat() / height.toFloat()
gl.glViewport(0, 0, width, height)
gl.glMatrixMode(GL2.GL_PROJECTION)
gl.glLoadIdentity()
glu.gluPerspective(45.0, h.toDouble(), 0.1, 1000.0)
gl.glMatrixMode(GL2.GL_MODELVIEW)
gl.glLoadIdentity()
}
override fun init(drawable: GLAutoDrawable) {
val glProfile = GLProfile.getDefault()
val caps = GLCapabilities(glProfile)
caps.hardwareAccelerated = true
caps.doubleBuffered = true
val gl = drawable.gl.gL2
System.err.println("INIT GL IS: " + gl.javaClass.name)
gl.glClearColor(0.250f, 0.250f, 0.250f, 0.0f)
gl.glEnable(GL.GL_TEXTURE_2D)
gl.glEnable(GL2.GL_DEPTH_TEST)
gl.glEnable(GL2.GL_CULL_FACE)
gl.glCullFace(GL2.GL_BACK)
gl.glPolygonMode(GL2.GL_FRONT, GL2.GL_FILL)
gl.glBlendFunc(GL2.GL_SRC_ALPHA, GL2.GL_ONE_MINUS_SRC_ALPHA)
gl.glEnable(GL2.GL_BLEND)
// gl.glDisable(gl.GL_COLOR_MATERIAL);
camera = Camera(0f, 2f, 5f, 0f, 2.5f, 0f, 0f, 1f, 0f)
}
fun setSelected(sel: Int) {
selected = sel
}
override fun dispose(arg0: GLAutoDrawable) {
// TODO Auto-generated method stub
}
} | gpl-2.0 | be9a4b1679d2b11c2e1eb028465d9d07 | 31.829016 | 110 | 0.565746 | 3.360743 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/browse/components/BrowseSourceDialogs.kt | 1 | 1273 | package eu.kanade.presentation.browse.components
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.ui.res.stringResource
import eu.kanade.domain.manga.model.Manga
import eu.kanade.tachiyomi.R
@Composable
fun RemoveMangaDialog(
onDismissRequest: () -> Unit,
onConfirm: () -> Unit,
mangaToRemove: Manga,
) {
AlertDialog(
onDismissRequest = onDismissRequest,
dismissButton = {
TextButton(onClick = onDismissRequest) {
Text(text = stringResource(android.R.string.cancel))
}
},
confirmButton = {
TextButton(
onClick = {
onDismissRequest()
onConfirm()
},
) {
Text(text = stringResource(R.string.action_remove))
}
},
title = {
Text(text = stringResource(R.string.are_you_sure))
},
text = {
Text(text = stringResource(R.string.remove_manga, mangaToRemove.title))
},
)
}
| apache-2.0 | 14b9463c7fa66e3618b289feac2dd214 | 28.604651 | 83 | 0.613511 | 4.75 | false | false | false | false |
sjnyag/stamp | app/src/main/java/com/sjn/stamp/ui/DrawerMenu.kt | 1 | 1287 | package com.sjn.stamp.ui
import android.support.v4.app.Fragment
import com.sjn.stamp.R
import com.sjn.stamp.ui.fragment.SettingFragment
import com.sjn.stamp.ui.fragment.media.*
enum class DrawerMenu(val menuId: Int) {
HOME(R.id.navigation_home) {
override val fragment: Fragment
get() = AllSongPagerFragment()
},
TIMELINE(R.id.navigation_timeline) {
override val fragment: Fragment
get() = TimelineFragment()
},
QUEUE(R.id.navigation_queue) {
override val fragment: Fragment
get() = QueueListFragment()
},
STAMP(R.id.navigation_stamp) {
override val fragment: Fragment
get() = StampPagerFragment()
},
RANKING(R.id.navigation_ranking) {
override val fragment: Fragment
get() = RankingPagerFragment()
},
SETTING(R.id.navigation_setting) {
override val fragment: Fragment
get() = SettingFragment()
};
abstract val fragment: Fragment
companion object {
fun of(menuId: Int): DrawerMenu? = DrawerMenu.values().firstOrNull { it.menuId == menuId }
fun of(menuId: Long): DrawerMenu? = DrawerMenu.values().firstOrNull { it.menuId.toLong() == menuId }
fun first(): DrawerMenu = HOME
}
}
| apache-2.0 | 2a936b7a3f840329520ba08c3b309ee8 | 28.25 | 108 | 0.631702 | 4.219672 | false | false | false | false |
Maccimo/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildSubEntityImpl.kt | 3 | 10332 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.extractOneToOneParent
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ChildSubEntityImpl: ChildSubEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentSubEntity::class.java, ChildSubEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false)
internal val CHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(ChildSubEntity::class.java, ChildSubSubEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
CHILD_CONNECTION_ID,
)
}
override val parentEntity: ParentSubEntity
get() = snapshot.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this)!!
override val child: ChildSubSubEntity
get() = snapshot.extractOneToOneChild(CHILD_CONNECTION_ID, this)!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ChildSubEntityData?): ModifiableWorkspaceEntityBase<ChildSubEntity>(), ChildSubEntity.Builder {
constructor(): this(ChildSubEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ChildSubEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (_diff != null) {
if (_diff.extractOneToOneParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) {
error("Field ChildSubEntity#parentEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) {
error("Field ChildSubEntity#parentEntity should be initialized")
}
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field ChildSubEntity#entitySource should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToOneChild<WorkspaceEntityBase>(CHILD_CONNECTION_ID, this) == null) {
error("Field ChildSubEntity#child should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] == null) {
error("Field ChildSubEntity#child should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var parentEntity: ParentSubEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentSubEntity
} else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentSubEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var child: ChildSubSubEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(CHILD_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)]!! as ChildSubSubEntity
} else {
this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)]!! as ChildSubSubEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(CHILD_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] = value
}
changedProperty.add("child")
}
override fun getEntityData(): ChildSubEntityData = result ?: super.getEntityData() as ChildSubEntityData
override fun getEntityClass(): Class<ChildSubEntity> = ChildSubEntity::class.java
}
}
class ChildSubEntityData : WorkspaceEntityData<ChildSubEntity>() {
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildSubEntity> {
val modifiable = ChildSubEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ChildSubEntity {
val entity = ChildSubEntityImpl()
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ChildSubEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildSubEntityData
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildSubEntityData
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
return result
}
} | apache-2.0 | 971500280b0449729443a2963c0637ed | 41.875519 | 187 | 0.609369 | 5.778523 | false | false | false | false |
k9mail/k-9 | app/storage/src/main/java/com/fsck/k9/preferences/migrations/StorageMigrationTo14.kt | 2 | 1237 | package com.fsck.k9.preferences.migrations
import android.database.sqlite.SQLiteDatabase
import com.fsck.k9.ServerSettingsSerializer
import com.fsck.k9.preferences.Protocols
/**
* Rewrite 'folderPushMode' value of non-IMAP accounts to 'NONE'.
*/
class StorageMigrationTo14(
private val db: SQLiteDatabase,
private val migrationsHelper: StorageMigrationsHelper
) {
private val serverSettingsSerializer = ServerSettingsSerializer()
fun disablePushFoldersForNonImapAccounts() {
val accountUuidsListValue = migrationsHelper.readValue(db, "accountUuids")
if (accountUuidsListValue == null || accountUuidsListValue.isEmpty()) {
return
}
val accountUuids = accountUuidsListValue.split(",")
for (accountUuid in accountUuids) {
disablePushFolders(accountUuid)
}
}
private fun disablePushFolders(accountUuid: String) {
val json = migrationsHelper.readValue(db, "$accountUuid.incomingServerSettings") ?: return
val serverSettings = serverSettingsSerializer.deserialize(json)
if (serverSettings.type != Protocols.IMAP) {
migrationsHelper.writeValue(db, "$accountUuid.folderPushMode", "NONE")
}
}
}
| apache-2.0 | ff9f03035b50205cb04473d58309331a | 34.342857 | 98 | 0.714632 | 5.028455 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/engagement/LikerViewHolder.kt | 1 | 2594 | package org.wordpress.android.ui.engagement
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import org.wordpress.android.R
import org.wordpress.android.ui.engagement.EngageItem.Liker
import org.wordpress.android.ui.engagement.EngagedListNavigationEvent.OpenUserProfileBottomSheet.UserProfile
import org.wordpress.android.util.GravatarUtils
import org.wordpress.android.util.image.ImageManager
import org.wordpress.android.util.image.ImageType
import org.wordpress.android.viewmodel.ResourceProvider
class LikerViewHolder(
parent: ViewGroup,
private val imageManager: ImageManager,
private val resourceProvider: ResourceProvider
) : EngagedPeopleViewHolder(parent, R.layout.liker_user) {
private val likerName = itemView.findViewById<TextView>(R.id.user_name)
private val likerLogin = itemView.findViewById<TextView>(R.id.user_login)
private val likerAvatar = itemView.findViewById<ImageView>(R.id.user_avatar)
private val likerRootView = itemView.findViewById<View>(R.id.liker_root_view)
fun bind(liker: Liker) {
this.likerName.text = liker.name
this.likerLogin.text = if (liker.login.isNotBlank()) {
resourceProvider.getString(R.string.at_username, liker.login)
} else {
liker.login
}
val likerAvatarUrl = GravatarUtils.fixGravatarUrl(
liker.userAvatarUrl,
likerRootView.context.resources.getDimensionPixelSize(R.dimen.avatar_sz_medium)
)
imageManager.loadIntoCircle(this.likerAvatar, ImageType.AVATAR_WITH_BACKGROUND, likerAvatarUrl)
if (liker.onClick != null) {
likerRootView.isEnabled = true
likerRootView.setOnClickListener {
liker.onClick.invoke(
UserProfile(
userAvatarUrl = liker.userAvatarUrl,
blavatarUrl = liker.preferredBlogBlavatar,
userName = liker.name,
userLogin = liker.login,
userBio = liker.userBio,
siteTitle = liker.preferredBlogName,
siteUrl = liker.preferredBlogUrl,
siteId = liker.preferredBlogId
),
liker.source
)
}
} else {
likerRootView.isEnabled = true
likerRootView.setOnClickListener(null)
}
}
}
| gpl-2.0 | ec11003003b6f1d8c2580b1f8de22bc8 | 40.83871 | 108 | 0.636854 | 4.623886 | false | false | false | false |
y20k/transistor | app/src/main/java/org/y20k/transistor/helpers/NotificationHelper.kt | 1 | 6712 | /*
* NotificationHelper.kt
* Implements the NotificationHelper class
* A NotificationHelper creates and configures a notification
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package org.y20k.transistor.helpers
import android.app.PendingIntent
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.MediaSessionCompat
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.ui.PlayerNotificationManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.y20k.transistor.Keys
import org.y20k.transistor.R
/*
* NotificationHelper class
* Credit: https://github.com/android/uamp/blob/5bae9316b60ba298b6080de1fcad53f6f74eb0bf/common/src/main/java/com/example/android/uamp/media/UampNotificationManager.kt
*/
class NotificationHelper(private val context: Context, sessionToken: MediaSessionCompat.Token, notificationListener: PlayerNotificationManager.NotificationListener) {
/* Define log tag */
private val TAG: String = LogHelper.makeLogTag(NotificationHelper::class.java)
/* Main class variables */
private val serviceJob = SupervisorJob()
private val serviceScope = CoroutineScope(Main + serviceJob)
private val notificationManager: PlayerNotificationManager
private val mediaController: MediaControllerCompat = MediaControllerCompat(context, sessionToken)
/* Constructor */
init {
// create a notification builder
val notificationBuilder = PlayerNotificationManager.Builder(context, Keys.NOW_PLAYING_NOTIFICATION_ID, Keys.NOW_PLAYING_NOTIFICATION_CHANNEL_ID)
notificationBuilder.apply {
setChannelNameResourceId(R.string.notification_now_playing_channel_name)
setChannelDescriptionResourceId(R.string.notification_now_playing_channel_description)
setMediaDescriptionAdapter(DescriptionAdapter(mediaController))
setNotificationListener(notificationListener)
}
// create and configure the notification manager
notificationManager = notificationBuilder.build()
notificationManager.apply {
// note: notification icons are customized in values.xml
setMediaSessionToken(sessionToken)
setSmallIcon(R.drawable.ic_notification_app_icon_white_24dp)
setUsePlayPauseActions(true)
setUseStopAction(true) // set true to display the dismiss button
setUsePreviousAction(true)
setUsePreviousActionInCompactView(false)
setUseNextAction(true) // only visible, if player is set to Player.REPEAT_MODE_ALL
setUseNextActionInCompactView(false)
setUseChronometer(true)
}
}
/* Hides notification via notification manager */
fun hideNotification() {
notificationManager.setPlayer(null)
}
/* Displays notification via notification manager */
fun showNotificationForPlayer(player: Player) {
notificationManager.setPlayer(player)
}
/* Triggers notification */
fun updateNotification() {
notificationManager.invalidate()
}
// /*
// * Inner class: Intercept stop button tap
// */
// private inner class Dispatcher: DefaultControlDispatcher(0L, 0L /* hide fast forward and rewind */) {
// override fun dispatchStop(player: Player, reset: Boolean): Boolean {
// // Default implementation see: https://github.com/google/ExoPlayer/blob/b1000940eaec9e1202d9abf341a48a58b728053f/library/core/src/main/java/com/google/android/exoplayer2/DefaultControlDispatcher.java#L137
// mediaController.sendCommand(Keys.CMD_DISMISS_NOTIFICATION, null, null)
// return true
// }
//
// override fun dispatchSetPlayWhenReady(player: Player, playWhenReady: Boolean): Boolean {
// // changes the default behavior of !playWhenReady from player.pause() to player.stop()
// when (playWhenReady) {
// true -> player.play()
// false -> player.stop()
// }
// return true
// }
//
// override fun dispatchPrevious(player: Player): Boolean {
// mediaController.sendCommand(Keys.CMD_PREVIOUS_STATION, null, null)
// return true
// }
//
// override fun dispatchNext(player: Player): Boolean {
// mediaController.sendCommand(Keys.CMD_NEXT_STATION, null, null)
// return true
// }
// }
// /*
// * End of inner class
// */
/*
* Inner class: Create content of notification from metaddata
*/
private inner class DescriptionAdapter(private val controller: MediaControllerCompat) : PlayerNotificationManager.MediaDescriptionAdapter {
var currentIconUri: Uri? = null
var currentBitmap: Bitmap? = null
override fun createCurrentContentIntent(player: Player): PendingIntent? = controller.sessionActivity
override fun getCurrentContentText(player: Player) = controller.metadata.description.subtitle.toString()
override fun getCurrentContentTitle(player: Player) = controller.metadata.description.title.toString()
override fun getCurrentLargeIcon(player: Player, callback: PlayerNotificationManager.BitmapCallback): Bitmap? {
val iconUri: Uri? = controller.metadata.description.iconUri
return if (currentIconUri != iconUri || currentBitmap == null) {
// Cache the bitmap for the current song so that successive calls to
// `getCurrentLargeIcon` don't cause the bitmap to be recreated.
currentIconUri = iconUri
serviceScope.launch {
currentBitmap = iconUri?.let {
resolveUriAsBitmap(it)
}
currentBitmap?.let { callback.onBitmap(it) }
}
null
} else {
currentBitmap
}
}
private suspend fun resolveUriAsBitmap(currentIconUri: Uri): Bitmap {
return withContext(IO) {
// Block on downloading artwork.
ImageHelper.getStationImage(context, currentIconUri.toString())
}
}
}
/*
* End of inner class
*/
}
| mit | d168837231471cf082018a54445bc2ce | 37.797688 | 218 | 0.684148 | 4.828777 | false | false | false | false |
fengzhizi715/SAF-Kotlin-Utils | saf-kotlin-utils/src/main/java/com/safframework/utils/NetUtils.kt | 1 | 1616 | package com.safframework.utils
import android.content.Context
import android.net.wifi.WifiManager
import java.net.Inet4Address
import java.net.InetAddress
import java.net.NetworkInterface
import java.util.*
/**
*
* @FileName:
* com.safframework.utils.NetUtils
* @author: Tony Shen
* @date: 2020-11-19 15:02
* @version: V1.0 <描述当前版本功能>
*/
/**
* 获取内网IP地址
*/
val localIPAddress: String by lazy {
val en: Enumeration<NetworkInterface> = NetworkInterface.getNetworkInterfaces()
while (en.hasMoreElements()) {
val intf: NetworkInterface = en.nextElement()
val enumIpAddr: Enumeration<InetAddress> = intf.inetAddresses
while (enumIpAddr.hasMoreElements()) {
val inetAddress: InetAddress = enumIpAddr.nextElement()
if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
return@lazy inetAddress.hostAddress.toString()
}
}
}
"null"
}
/**
* 获取局域网的网关地址
*/
fun getGatewayIP(context: Context):String {
val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
val info = wifiManager.dhcpInfo
val gateway = info.gateway
return intToIp(gateway)
}
/**
* int值转换为ip
* @param addr
* @return
*/
private fun intToIp(addr: Int): String {
var addr = addr
return (addr and 0xFF).toString() + "." +
(8.let { addr = addr ushr it; addr } and 0xFF) + "." +
(8.let { addr = addr ushr it; addr } and 0xFF) + "." +
(8.let { addr = addr ushr it; addr } and 0xFF)
} | apache-2.0 | e3d53288ca5627341152fa258e65eeb5 | 24.177419 | 83 | 0.646154 | 3.741007 | false | false | false | false |
mbrlabs/Mundus | editor/src/main/com/mbrlabs/mundus/editor/ui/modules/inspector/BaseInspectorWidget.kt | 1 | 4043 | /*
* Copyright (c) 2016. See AUTHORS file.
*
* 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.mbrlabs.mundus.editor.ui.modules.inspector
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.ui.Cell
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.kotcrab.vis.ui.widget.Separator
import com.kotcrab.vis.ui.widget.VisLabel
import com.kotcrab.vis.ui.widget.VisTable
import com.mbrlabs.mundus.commons.scene3d.GameObject
import com.mbrlabs.mundus.editor.ui.UI
import com.mbrlabs.mundus.editor.ui.widgets.CollapseWidget
import com.mbrlabs.mundus.editor.ui.widgets.FaTextButton
import com.mbrlabs.mundus.editor.utils.Fa
/**
* @author Marcus Brummer
* @version 19-01-2016
*/
abstract class BaseInspectorWidget(title: String) : VisTable() {
companion object {
private val COLLAPSE_BTN_DOWN = Fa.CARET_UP
private val COLLAPSE_BTN_UP = Fa.CARET_DOWN
}
var title: String? = null
set(title) {
field = title
titleLabel.setText(title)
}
private val collapseBtn = FaTextButton(COLLAPSE_BTN_UP)
private val deleteBtn = FaTextButton(Fa.TIMES)
private var deletableBtnCell: Cell<*>? = null
protected val collapsibleContent = VisTable()
private val collapsibleWidget = CollapseWidget(collapsibleContent)
private val titleLabel = VisLabel()
private var deletable: Boolean = false
init {
collapseBtn.label.setFontScale(0.7f)
deleteBtn.label.setFontScale(0.7f)
deleteBtn.style.up = null
deletable = false
setupUI()
setupListeners()
this.title = title
}
private fun setupListeners() {
// collapse
collapseBtn.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
collapse(!isCollapsed)
}
})
// delete
deleteBtn.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
onDelete()
}
})
}
private fun setupUI() {
// header
val header = VisTable()
deletableBtnCell = header.add(deleteBtn).top().left().padBottom(4f)
header.add(titleLabel)
header.add(collapseBtn).right().top().width(20f).height(20f).expand().row()
// add seperator
header.add(Separator(UI.greenSeperatorStyle)).fillX().expandX().colspan(3).row()
// add everything to root
add(header).expand().fill().padBottom(10f).row()
add(collapsibleWidget).expand().fill().row()
isDeletable = deletable
}
var isDeletable: Boolean
get() = deletable
set(deletable) {
this.deletable = deletable
if (deletable) {
deleteBtn.isVisible = true
deletableBtnCell!!.width(20f).height(20f).padRight(5f)
} else {
deleteBtn.isVisible = false
deletableBtnCell!!.width(0f).height(0f).padRight(0f)
}
}
val isCollapsed: Boolean
get() = collapsibleWidget.isCollapsed
fun collapse(collapse: Boolean) {
collapsibleWidget.setCollapsed(collapse, false)
if (collapse) {
collapseBtn.setText(COLLAPSE_BTN_DOWN)
} else {
collapseBtn.setText(COLLAPSE_BTN_UP)
}
}
abstract fun onDelete()
abstract fun setValues(go: GameObject)
}
| apache-2.0 | 81e8b93ad439fa5937b744c83b2d13cc | 29.628788 | 88 | 0.647044 | 4.067404 | false | false | false | false |
ingokegel/intellij-community | platform/statistics/src/com/intellij/internal/statistic/eventLog/StatisticsEventLogProvidersHolder.kt | 5 | 2880 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.statistic.eventLog
import com.intellij.internal.statistic.eventLog.StatisticsEventLoggerProvider.Companion.EP_NAME
import com.intellij.internal.statistic.utils.PluginType
import com.intellij.internal.statistic.utils.StatisticsRecorderUtil
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.util.PlatformUtils
import java.util.concurrent.atomic.AtomicReference
@Service(Service.Level.APP)
internal class StatisticsEventLogProvidersHolder {
private val eventLoggerProviders: AtomicReference<Map<String, StatisticsEventLoggerProvider>> =
AtomicReference(calculateEventLogProvider())
init {
if (ApplicationManager.getApplication().extensionArea.hasExtensionPoint(EP_NAME)) {
EP_NAME.addChangeListener(Runnable { eventLoggerProviders.set(calculateEventLogProvider()) }, null)
}
}
fun getEventLogProvider(recorderId: String): StatisticsEventLoggerProvider {
return eventLoggerProviders.get()[recorderId] ?: EmptyStatisticsEventLoggerProvider(recorderId)
}
fun getEventLogProviders(): Collection<StatisticsEventLoggerProvider> {
return eventLoggerProviders.get().values
}
private fun calculateEventLogProvider(): Map<String, StatisticsEventLoggerProvider> {
return getAllEventLogProviders().associateBy { it.recorderId }
}
private fun getAllEventLogProviders(): Sequence<StatisticsEventLoggerProvider> {
val providers = EP_NAME.extensionsIfPointIsRegistered
if (providers.isEmpty()) {
return emptySequence()
}
val isJetBrainsProduct = isJetBrainsProduct()
return providers.asSequence()
.filter { isProviderApplicable(isJetBrainsProduct, it.recorderId, it) }
.distinctBy { it.recorderId }
}
private fun isJetBrainsProduct(): Boolean {
val appInfo = ApplicationInfo.getInstance()
return if (appInfo == null || appInfo.shortCompanyName.isNullOrEmpty()) true else PlatformUtils.isJetBrainsProduct()
}
private fun isProviderApplicable(isJetBrainsProduct: Boolean, recorderId: String, extension: StatisticsEventLoggerProvider): Boolean {
if (recorderId == extension.recorderId) {
if (!isJetBrainsProduct || !StatisticsRecorderUtil.isBuildInRecorder(recorderId)) {
return true
}
val pluginInfo = getPluginInfo(extension::class.java)
return if (recorderId == "MLSE") {
pluginInfo.isDevelopedByJetBrains()
}
else {
pluginInfo.type == PluginType.PLATFORM || pluginInfo.type == PluginType.FROM_SOURCES || pluginInfo.isAllowedToInjectIntoFUS()
}
}
return false
}
} | apache-2.0 | 04e2f13c432a384447023ead3adf6688 | 40.753623 | 136 | 0.774306 | 5.245902 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/nextfare/record/NextfareRecord.kt | 1 | 4150 | /*
* NextfareRecord.kt
*
* Copyright 2015-2019 Michael Farrell <[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 au.id.micolous.metrodroid.transit.nextfare.record
import au.id.micolous.metrodroid.multi.Log
import au.id.micolous.metrodroid.time.MetroTimeZone
import au.id.micolous.metrodroid.time.TimestampFull
import au.id.micolous.metrodroid.util.ImmutableByteArray
import au.id.micolous.metrodroid.util.NumberUtils
/**
* Represents a record on a Nextfare card
* This fans out parsing to subclasses.
* https://github.com/micolous/metrodroid/wiki/Cubic-Nextfare-MFC
*/
interface NextfareRecord {
companion object {
private const val TAG = "NextfareRecord"
fun recordFromBytes(input: ImmutableByteArray, sectorIndex: Int, blockIndex: Int, timeZone: MetroTimeZone): NextfareRecord? {
Log.d(TAG, "Record: $input")
when {
sectorIndex == 1 && blockIndex <= 1 -> {
Log.d(TAG, "Balance record")
return NextfareBalanceRecord.recordFromBytes(input)
}
sectorIndex == 1 && blockIndex == 2 -> {
Log.d(TAG, "Configuration record")
return NextfareConfigRecord.recordFromBytes(input, timeZone)
}
sectorIndex == 2 -> {
Log.d(TAG, "Top-up record")
return NextfareTopupRecord.recordFromBytes(input, timeZone)
}
sectorIndex == 3 -> {
Log.d(TAG, "Travel pass record")
return NextfareTravelPassRecord.recordFromBytes(input, timeZone)
}
sectorIndex in 5..8 -> {
Log.d(TAG, "Transaction record")
return NextfareTransactionRecord.recordFromBytes(input, timeZone)
}
else -> return null
}
}
/**
* Date format:
*
*
* Top two bytes:
* 0001111 1100 00100 = 2015-12-04
* yyyyyyy mmmm ddddd
*
*
* Bottom 11 bits = minutes since 00:00
* Time is represented in localtime
*
*
* Assumes that data has not been byte-reversed.
*
* @param input Bytes of input representing the timestamp to parse
* @param offset Offset in byte to timestamp
* @return Date and time represented by that value
*/
fun unpackDate(input: ImmutableByteArray, offset: Int, timeZone: MetroTimeZone): TimestampFull {
val timestamp = input.byteArrayToIntReversed(offset, 4)
val minute = NumberUtils.getBitsFromInteger(timestamp, 16, 11)
val year = NumberUtils.getBitsFromInteger(timestamp, 9, 7) + 2000
val month = NumberUtils.getBitsFromInteger(timestamp, 5, 4)
val day = NumberUtils.getBitsFromInteger(timestamp, 0, 5)
//noinspection MagicCharacter
Log.d(TAG, "unpackDate: $minute minutes, $year-$month-$day")
if (minute > 1440)
throw AssertionError("Minute > 1440 ($minute)")
if (minute < 0)
throw AssertionError("Minute < 0 ($minute)")
if (day > 31) throw AssertionError("Day > 31 ($day)")
if (month > 12)
throw AssertionError("Month > 12 ($month)")
return TimestampFull(timeZone, year, month - 1, day, minute / 60, minute % 60, 0)
}
}
}
| gpl-3.0 | bee1caa190a819ea40874b4e74c24fb0 | 38.52381 | 133 | 0.602169 | 4.626533 | false | false | false | false |
squanchy-dev/squanchy-android | app/src/test/java/net/squanchy/favorites/ListItemFixtures.kt | 1 | 457 | package net.squanchy.favorites
import net.squanchy.favorites.view.FavoritesItem
import net.squanchy.schedule.domain.view.Event
import net.squanchy.schedule.domain.view.aDay
import net.squanchy.schedule.domain.view.anEvent
import org.threeten.bp.LocalDate
fun aFavoriteHeaderListItem(
date: LocalDate = aDay().date
) = FavoritesItem.Header(date = date)
fun aFavoriteItemListItem(
event: Event = anEvent()
) = FavoritesItem.Favorite(event = event)
| apache-2.0 | 506affeab5cf0348633916c999e92fcb | 29.466667 | 48 | 0.798687 | 3.598425 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/troika/TroikaTransitData.kt | 1 | 3214 | /*
* TroikaTransitData.kt
*
* Copyright 2015-2016 Michael Farrell <[email protected]>
* Copyright 2018 Google
*
* 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 au.id.micolous.metrodroid.transit.troika
import au.id.micolous.metrodroid.card.CardType
import au.id.micolous.metrodroid.card.classic.ClassicCard
import au.id.micolous.metrodroid.card.classic.UnauthorizedClassicSector
import au.id.micolous.metrodroid.multi.*
import au.id.micolous.metrodroid.transit.*
import au.id.micolous.metrodroid.ui.ListItem
/**
* Troika cards.
*/
@Parcelize
class TroikaTransitData(private val mBlocks: List<TroikaBlock>) : Parcelable {
val serialNumber: String?
get() = mBlocks[0].serialNumber
val info: List<ListItem>?
get() = mBlocks.flatMap { it.info.orEmpty() }.ifEmpty { null }
val balance: TransitBalance
get() = mBlocks[0].balance ?: TransitCurrency.RUB(0)
val warning: String?
get() = if (mBlocks[0].balance == null && subscriptions.isEmpty())
Localizer.localizeString(R.string.troika_unformatted)
else
null
val trips: List<Trip>
get() = mBlocks.flatMap { it.trips.orEmpty() }
val subscriptions: List<Subscription>
get() = mBlocks.mapNotNull { it.subscription }
constructor(card: ClassicCard) : this(listOfNotNull(
decodeSector(card, 8),
decodeSector(card, 7),
decodeSector(card, 4),
decodeSector(card, 1)
)
)
companion object {
internal val CARD_INFO = CardInfo(
imageId = R.drawable.troika_card,
imageAlphaId = R.drawable.iso7810_id1_alpha,
name = R.string.card_name_troika,
locationId = R.string.location_moscow,
cardType = CardType.MifareClassic,
resourceExtraNote = R.string.card_note_russia,
region = TransitRegion.RUSSIA,
keysRequired = true, preview = true, keyBundle = "troika")
private const val TAG = "TroikaTransitData"
private fun decodeSector(card: ClassicCard, idx: Int): TroikaBlock? {
try {
val sector = card.getSector(idx)
if (sector is UnauthorizedClassicSector)
return null
val block = sector.readBlocks(0, 3)
return if (!TroikaBlock.check(block)) null else TroikaBlock.parseBlock(block)
} catch (e: Exception) {
Log.w(TAG, "Error decoding troika sector", e)
return null
}
}
}
}
| gpl-3.0 | 7d7a5a8d267dcd7a6108189c1313e00f | 34.318681 | 93 | 0.643124 | 4.206806 | false | false | false | false |
Subsets and Splits