repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Budincsevity/opensubtitles-api | src/main/kotlin/io/github/budincsevity/OpenSubtitlesAPI/mapper/SearchResultMapper.kt | 1 | 5051 | package io.github.budincsevity.OpenSubtitlesAPI.mapper
import io.github.budincsevity.OpenSubtitlesAPI.model.SearchResult
import io.github.budincsevity.OpenSubtitlesAPI.model.SearchResultData
import io.github.budincsevity.OpenSubtitlesAPI.model.builder.SearchResultDataBuilder
import io.github.budincsevity.OpenSubtitlesAPI.model.status.OpenSubtitlesStatus
import io.github.budincsevity.OpenSubtitlesAPI.util.ResponseParam.DATA
import io.github.budincsevity.OpenSubtitlesAPI.util.ResponseParam.STATUS
class SearchResultMapper {
fun mapSearchResult(searchResultMap: Map<*, *>): SearchResult {
val status: String = searchResultMap[STATUS.paramName] as String
val data = searchResultMap[DATA.paramName] as Array<*>
if (status != OpenSubtitlesStatus.OK.status) {
return SearchResult(status, arrayListOf<SearchResultData>())
}
val searchResultData = mapSearchResultData(data)
return SearchResult(status, searchResultData)
}
private fun mapSearchResultData(data: Array<*>): ArrayList<SearchResultData> {
val searchResultData = arrayListOf<SearchResultData>()
data.map { it as HashMap<*, *> }.mapTo(searchResultData) {
buildSearchResultData(it)
}
return searchResultData
}
private fun buildSearchResultData(data: HashMap<*, *>): SearchResultData {
return SearchResultDataBuilder()
.withSubActualCD(data["SubActualCD"].toString())
.withMovieName(data["MovieName"].toString())
.withSubBad(data["SubBad"].toString())
.withMovieHash(data["MovieHash"].toString())
.withSubFileName(data["SubFileName"].toString())
.withSubSumCD(data["SubSumCD"].toString())
.withZipDownloadLink(data["ZipDownloadLink"].toString())
.withMovieNameEng(data["MovieNameEng"].toString())
.withSubSize(data["SubSize"].toString())
.withIDSubtitleFile(data["IDSubtitleFile"].toString())
.withSubHash(data["SubHash"].toString())
.withSubFeatured(data["SubFeatured"].toString())
.withSubAuthorComment(data["SubAuthorComment"].toString())
.withSubDownloadsCnt(data["SubDownloadsCnt"].toString())
.withSubAddDate(data["SubAddDate"].toString())
.withSubLastTS(data["SubLastTS"].toString())
.withSubAutoTranslation(data["SubAutoTranslation"].toString())
.withMovieReleaseName(data["MovieReleaseName"].toString())
.withSeriesIMDBParent(data["SeriesIMDBParent"].toString())
.withScore(data["Score"].toString())
.withUserNickName(data["UserNickName"].toString())
.withSubHearingImpaired(data["SubHearingImpaired"].toString())
.withSubTSGroup(data["SubTSGroup"].toString())
.withQueryCached(data["QueryCached"].toString())
.withSubLanguageID(data["SubLanguageID"].toString())
.withSubFormat(data["SubFormat"].toString())
.withLanguageName(data["LanguageName"].toString())
.withSubTranslator(data["SubTranslator"].toString())
.withSeriesEpisode(data["SeriesEpisode"].toString())
.withUserRank(data["UserRank"].toString())
.withMovieImdbRating(data["MovieImdbRating"].toString())
.withMovieTimeMS(data["MovieTimeMS"].toString())
.withMovieYear(data["MovieYear"].toString())
.withSubEncoding(data["SubEncoding"].toString())
.withQueryNumber(data["QueryNumber"].toString())
.withSubHD(data["SubHD"].toString())
.withUserID(data["UserID"].toString())
.withMovieByteSize(data["MovieByteSize"].toString())
.withMovieFPS(data["MovieFPS"].toString())
.withSubtitlesLink(data["SubtitlesLink"].toString())
.withIDSubMovieFile(data["IDSubMovieFile"].toString())
.withISO639(data["ISO639"].toString())
.withSeriesSeason(data["SeriesSeason"].toString())
.withSubFromTrusted(data["SubFromTrusted"].toString())
.withSubTSGroupHash(data["SubTSGroupHash"].toString())
.withMatchedBy(data["MatchedBy"].toString())
.withSubDownloadLink(data["SubDownloadLink"].toString())
.withSubRating(data["SubRating"].toString())
.withQueryParameters(data["QueryParameters"].toString())
.withSubComments(data["SubComments"].toString())
.withMovieKind(data["MovieKind"].toString())
.withIDMovie(data["IDMovie"].toString())
.withIDMovieImdb(data["IDMovieImdb"].toString())
.withSubForeignPartsOnly(data["SubForeignPartsOnly"].toString())
.withIDSubtitle(data["IDSubtitle"].toString())
.build()
}
}
| mit | 623ccdcbecfc1d60e30d8e7f04c55e6a | 55.122222 | 84 | 0.63136 | 4.685529 | false | false | false | false |
GymDon-P-Q11Info-13-15/game | Game Commons/src/de/gymdon/inf1315/game/tile/TileMap.kt | 1 | 594 | package de.gymdon.inf1315.game.tile
data class TileMap(val width: Int, val height: Int) {
val tiles: Array<Array<Tile>> = Array(width) { _ -> Array(height) { _ -> Tile.grass} }
operator fun get(pos: TilePosition): Tile = tiles[pos.x][pos.y]
operator fun get(x: Int, y: Int): Tile = tiles[x][y]
operator fun set(pos: TilePosition, tile: Tile) {
set(pos.x, pos.y, tile)
}
operator fun set(x: Int, y: Int, tile: Tile) {
tiles[x][y] = tile
}
fun isValid(pos: TilePosition): Boolean = pos.x >= 0 && pos.y >= 0 && pos.x < width && pos.y < height
} | gpl-3.0 | c65934df663e7596b91781e30d6d33d1 | 32.055556 | 105 | 0.59596 | 2.97 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osm/mapdata/MapDataApi.kt | 1 | 7413 | package de.westnordost.streetcomplete.data.osm.mapdata
import de.westnordost.streetcomplete.data.download.ConnectionException
import de.westnordost.streetcomplete.data.download.QueryTooBigException
import de.westnordost.streetcomplete.data.upload.ConflictException
import de.westnordost.streetcomplete.data.user.AuthorizationException
/** Get and upload changes to map data */
interface MapDataApi : MapDataRepository {
/**
* Upload changes into an opened changeset.
*
* @param changesetId id of the changeset to upload changes into
* @param changes changes to upload.
*
* @throws ConflictException if the changeset has already been closed, there is a conflict for
* the elements being uploaded or the user who created the changeset
* is not the same as the one uploading the change
* @throws AuthorizationException if the application does not have permission to edit the map
* (Permission.MODIFY_MAP)
* @throws ConnectionException if a temporary network connection problem occurs
*
* @return the updated elements
*/
fun uploadChanges(changesetId: Long, changes: MapDataChanges): MapDataUpdates
/**
* Open a new changeset with the given tags
*
* @param tags tags of this changeset. Usually it is comment and source.
*
* @throws AuthorizationException if the application does not have permission to edit the map
* (Permission.MODIFY_MAP)
* @throws ConnectionException if a temporary network connection problem occurs
*
* @return the id of the changeset
*/
fun openChangeset(tags: Map<String, String?>): Long
/**
* Closes the given changeset.
*
* @param changesetId id of the changeset to close
*
* @throws ConflictException if the changeset has already been closed
* @throws AuthorizationException if the application does not have permission to edit the map
* (Permission.MODIFY_MAP)
* @throws ConnectionException if a temporary network connection problem occurs
*/
fun closeChangeset(changesetId: Long)
/**
* Feeds map data to the given MapDataHandler.
* If not logged in, the Changeset for each returned element will be null
*
* @param bounds rectangle in which to query map data. May not cross the 180th meridian. This is
* usually limited at 0.25 square degrees. Check the server capabilities.
* @param mutableMapData mutable map data to add the add the data to
* @param ignoreRelationTypes don't put any relations of the given types in the given mutableMapData
*
* @throws QueryTooBigException if the bounds area is too large
* @throws IllegalArgumentException if the bounds cross the 180th meridian.
* @throws ConnectionException if a temporary network connection problem occurs
*
* @return the map data
*/
fun getMap(bounds: BoundingBox, mutableMapData: MutableMapData, ignoreRelationTypes: Set<String?> = emptySet())
/**
* Queries the way with the given id plus all nodes that are in referenced by it.
* If not logged in, the Changeset for each returned element will be null
*
* @param id the way's id
*
* @throws ConnectionException if a temporary network connection problem occurs
*
* @return the map data
*/
override fun getWayComplete(id: Long): MapData?
/**
* Queries the relation with the given id plus all it's members and all nodes of ways that are
* members of the relation.
* If not logged in, the Changeset for each returned element will be null
*
* @param id the relation's id
*
* @throws ConnectionException if a temporary network connection problem occurs
*
* @return the map data
*/
override fun getRelationComplete(id: Long): MapData?
/**
* Note that if not logged in, the Changeset for each returned element will be null
*
* @param id the node's id
*
* @throws ConnectionException if a temporary network connection problem occurs
*
* @return the node with the given id or null if it does not exist
*/
override fun getNode(id: Long): Node?
/**
* Note that if not logged in, the Changeset for each returned element will be null
*
* @param id the way's id
*
* @throws ConnectionException if a temporary network connection problem occurs
*
* @return the way with the given id or null if it does not exist
*/
override fun getWay(id: Long): Way?
/**
* Note that if not logged in, the Changeset for each returned element will be null
*
* @param id the relation's id
*
* @throws ConnectionException if a temporary network connection problem occurs
*
* @return the relation with the given id or null if it does not exist
*/
override fun getRelation(id: Long): Relation?
/**
* Note that if not logged in, the Changeset for each returned element will be null
*
* @param id the node's id
*
* @throws ConnectionException if a temporary network connection problem occurs
*
* @return all ways that reference the node with the given id. Empty if none.
*/
override fun getWaysForNode(id: Long): List<Way>
/**
* Note that if not logged in, the Changeset for each returned element will be null
*
* @param id the node's id
*
* @throws ConnectionException if a temporary network connection problem occurs
*
* @return all relations that reference the node with the given id. Empty if none.
*/
override fun getRelationsForNode(id: Long): List<Relation>
/**
* Note that if not logged in, the Changeset for each returned element will be null
*
* @param id the way's id
*
* @throws ConnectionException if a temporary network connection problem occurs
*
* @return all relations that reference the way with the given id. Empty if none.
*/
override fun getRelationsForWay(id: Long): List<Relation>
/**
* Note that if not logged in, the Changeset for each returned element will be null
*
* @param id the relation's id
*
* @throws ConnectionException if a temporary network connection problem occurs
*
* @return all relations that reference the relation with the given id. Empty if none.
*/
override fun getRelationsForRelation(id: Long): List<Relation>
}
/** Data class that contains the map data updates (updated elements, deleted elements, elements
* whose id have been updated) after the modifications have been uploaded */
data class MapDataUpdates(
val updated: Collection<Element> = emptyList(),
val deleted: Collection<ElementKey> = emptyList(),
val idUpdates: Collection<ElementIdUpdate> = emptyList()
)
data class ElementIdUpdate(
val elementType: ElementType,
val oldElementId: Long,
val newElementId: Long
)
/** Data class that contains a the request to create, modify elements and delete the given elements */
data class MapDataChanges(
val creations: Collection<Element> = emptyList(),
val modifications: Collection<Element> = emptyList(),
val deletions: Collection<Element> = emptyList()
)
| gpl-3.0 | d356682629ea045bd8cdc3baf30acb92 | 37.609375 | 115 | 0.679347 | 4.736741 | false | false | false | false |
WijayaPrinting/wp-javafx | openpss-client-javafx/src/com/hendraanggrian/openpss/FxComponent.kt | 1 | 4291 | package com.hendraanggrian.openpss
import com.hendraanggrian.openpss.api.OpenPSSApi
import com.hendraanggrian.openpss.schema.Employee
import com.hendraanggrian.openpss.schema.GlobalSetting
import com.hendraanggrian.openpss.ui.ResultableDialog
import com.hendraanggrian.prefy.jvm.PropertiesPreferences
import java.awt.Desktop
import javafx.scene.Node
import javafx.scene.control.ComboBox
import javafx.scene.control.PasswordField
import javafx.scene.layout.StackPane
import javafx.scene.paint.Color
import javafx.util.StringConverter
import javafx.util.converter.CurrencyStringConverter
import javafx.util.converter.NumberStringConverter
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.javafx.JavaFx
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import ktfx.collections.toObservableList
import ktfx.controls.gap
import ktfx.jfoenix.controls.jfxSnackbar
import ktfx.jfoenix.layouts.jfxComboBox
import ktfx.jfoenix.layouts.jfxPasswordField
import ktfx.layouts.gridPane
import ktfx.layouts.label
import ktfx.or
import ktfx.toBooleanBinding
/** StackPane is the root layout for [ktfx.jfoenix.jfxSnackbar]. */
interface FxComponent : Component<StackPane, PropertiesPreferences>, StringResources, ValueResources {
/** Number decimal string converter. */
val numberConverter: StringConverter<Number>
get() = NumberStringConverter()
/** Number decimal with currency prefix string converter. */
val currencyConverter: StringConverter<Number>
get() = CurrencyStringConverter(runBlocking(Dispatchers.IO) {
Language.ofFullCode(OpenPSSApi.getSetting(GlobalSetting.KEY_LANGUAGE).value).toLocale()
})
/** Returns [Desktop] instance, may be null if it is unsupported. */
val desktop: Desktop?
get() {
if (!Desktop.isDesktopSupported()) {
rootLayout.jfxSnackbar(
"java.awt.Desktop is not supported.",
getLong(R.value.duration_short)
)
return null
}
return Desktop.getDesktop()
}
suspend fun CoroutineScope.withPermission(
context: CoroutineContext = Dispatchers.JavaFx,
action: suspend CoroutineScope.() -> Unit
) {
when {
OpenPSSApi.isAdmin(login) -> action()
else -> PermissionDialog(this@FxComponent).show { admin ->
when (admin) {
null -> rootLayout.jfxSnackbar(
getString(R2.string.invalid_password),
getLong(R.value.duration_short)
)
else -> launch(context) { action() }
}
}
}
}
fun getColor(id: String): Color = Color.web(valueProperties.getProperty(id))
private class PermissionDialog(component: FxComponent) :
ResultableDialog<Employee>(component, R2.string.permission_required) {
private val adminCombo: ComboBox<Employee>
private val passwordField: PasswordField
override val focusedNode: Node? get() = adminCombo
init {
gridPane {
gap = getDouble(R.value.padding_medium)
label {
text = getString(R2.string._permission_required)
} col (0 to 2) row 0
label(getString(R2.string.admin)) col 0 row 1
adminCombo = jfxComboBox(runBlocking(Dispatchers.IO) { OpenPSSApi.getEmployees() }
.filter { it.isAdmin }
.toObservableList()
) { promptText = getString(R2.string.admin) } col 1 row 1
label(getString(R2.string.password)) col 0 row 2
passwordField = jfxPasswordField { promptText = getString(R2.string.password) } col 1 row 2
}
defaultButton.disableProperty().bind(
adminCombo.valueProperty().isNull or passwordField.textProperty().toBooleanBinding { it!!.isBlank() }
)
}
override val nullableResult: Employee?
get() = runBlocking(Dispatchers.IO) { OpenPSSApi.login(adminCombo.value.name, passwordField.text) }
}
}
| apache-2.0 | f19e636572917186b0ab877f7d1c2fb4 | 38.366972 | 117 | 0.663715 | 4.741436 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/api/util/VariableValueArray.kt | 1 | 6555 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.api.util
import org.lanternpowered.server.util.BitHelper
import kotlin.math.ceil
/**
* Represents an array for which can be specified how many bits
* should be occupied for each value. These bits will be spread
* out per long value. E.g. if you have 4 bits per value, there
* will be 64 / 4 values be stored on a single long value. If
* you use a number that's not the power of two, a few bits will
* be unused per long, e.g. for bits per value 3, 64 % 3 = 1
*
* The implementation was changed for minecraft 1.16 changes, prior
* to this version, values could be spread out over multiple long
* values if the bits per value wasn't a power of two. This was
* changed for performance reasons and was a breaking change.
*/
class VariableValueArray {
/**
* The size.
*/
val size: Int
/**
* The amount of bits that are used for a single value.
*/
val bitsPerValue: Int
/**
* The backing array that's used to store the values.
*/
val backing: LongArray
/**
* A bitmask for a value.
*/
private val valueMask: Long
/**
* How many values can be stored in a single long value.
*/
private val valuesPerLong: Int
/**
* How many bits per value there would be if bitsPerValue
* was the power of two, rounded up.
*/
private val powOfTwoBitsVerValue: Int
/**
* Constructs a new [VariableValueArray].
*/
constructor(bitsPerValue: Int, size: Int) : this(null, bitsPerValue, size)
/**
* Constructs a new [VariableValueArray].
*/
constructor(bitsPerValue: Int, size: Int, backing: LongArray) : this(backing, bitsPerValue, size)
private constructor(backing: LongArray?, bitsPerValue: Int, size: Int) {
check(size > 0) { "size ($size) may not be negative" }
check(bitsPerValue >= 1) { "bitsPerValue ($bitsPerValue) may not be smaller then 1" }
check(bitsPerValue <= Int.SIZE_BITS) { "bitsPerValue ($bitsPerValue) may not be greater then ${Int.SIZE_BITS}}" }
this.size = size
this.bitsPerValue = bitsPerValue
this.valueMask = (1L shl bitsPerValue) - 1L
this.valuesPerLong = Long.SIZE_BITS / this.bitsPerValue
this.powOfTwoBitsVerValue = BitHelper.nextPowOfTwo(bitsPerValue)
val backingSize = ceil(size.toDouble() / this.valuesPerLong.toDouble()).toInt()
if (backing == null) {
this.backing = LongArray(backingSize)
} else {
check(backingSize == backing.size) { "expected backing size of $backingSize, but got ${backing.size}" }
this.backing = backing
}
}
/**
* Creates a copy of this [VariableValueArray].
*/
fun copy(): VariableValueArray = VariableValueArray(this.bitsPerValue, this.size, this.backing.copyOf())
/**
* Creates a copy of this [VariableValueArray] with the new [bitsPerValue].
*
* An [IllegalArgumentException] can be expected if any of the values won't
* fit in the new [bitsPerValue].
*/
fun copyWithBitsPerValue(bitsPerValue: Int): VariableValueArray {
if (bitsPerValue == this.bitsPerValue)
return this.copy()
val copy = VariableValueArray(bitsPerValue, this.size)
for (index in 0 until this.size)
copy[index] = this[index]
return copy
}
/**
* Gets a value at the given [index].
*/
operator fun get(index: Int): Int {
return this.perform(index) { longIndex, indexInLong ->
((this.backing[longIndex] ushr indexInLong) and this.valueMask).toInt()
}
}
/**
* Sets a value at the given [index].
*/
operator fun set(index: Int, value: Int) {
require(value >= 0) { "value ($value) must not be negative" }
require(value <= this.valueMask) { "value ($value) must not be greater than $valueMask" }
this.perform(index) { longIndex, indexInLong ->
// Remove the old value
val cleaned = this.backing[longIndex] and (this.valueMask shl indexInLong).inv()
// Update the new value
this.backing[longIndex] = cleaned or (value.toLong() shl indexInLong)
}
}
/**
* Fills the value at all the possible indexes in this array.
*/
fun fill(value: Int) {
require(value >= 0) { "value ($value) must not be negative" }
require(value <= this.valueMask) { "value ($value) must not be greater than $valueMask" }
val valueLong = value.toLong()
// Compute a single long value which can put in every
// backing array element.
var long = valueLong
for (i in 1 until this.valuesPerLong)
long = long or (valueLong shl (i * this.bitsPerValue))
this.backing.fill(long)
}
/**
* Creates an iterator over the elements of the array.
*/
operator fun iterator(): IntIterator {
return object : IntIterator() {
var index = 0
override fun hasNext(): Boolean = this.index < size
override fun nextInt(): Int {
if (!this.hasNext())
throw NoSuchElementException()
return get(this.index++)
}
}
}
private inline fun <R> perform(index: Int, fn: (longIndex: Int, indexInLong: Int) -> R): R {
if (index < 0)
throw IndexOutOfBoundsException("index ($index) must not be negative")
if (index >= this.size)
throw IndexOutOfBoundsException("index ($index) must not be greater than the size ($size)")
// The long the value is located in
val longIndex: Int
// The value start index
val indexInLong: Int
// Is power of two
if (this.powOfTwoBitsVerValue == this.bitsPerValue) {
val bitPosition = index * this.bitsPerValue
longIndex = bitPosition shr 6
indexInLong = bitPosition and 0x3f
} else {
longIndex = (index * this.powOfTwoBitsVerValue) shr 6
indexInLong = (index - longIndex * this.valuesPerLong) * this.bitsPerValue
}
return fn(longIndex, indexInLong)
}
}
| mit | 2ac041bd3d8ceaa6e60a167b58a20172 | 33.140625 | 121 | 0.618002 | 4.089208 | false | false | false | false |
sabi0/intellij-community | platform/configuration-store-impl/src/DirectoryBasedStorage.kt | 1 | 8590 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.configurationStore.schemeManager.createDir
import com.intellij.configurationStore.schemeManager.getOrCreateChild
import com.intellij.openapi.application.runUndoTransparentWriteAction
import com.intellij.openapi.components.StateSplitter
import com.intellij.openapi.components.StateSplitterEx
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.TrackingPathMacroSubstitutor
import com.intellij.openapi.components.impl.stores.DirectoryStorageUtil
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.LineSeparator
import com.intellij.util.SmartList
import com.intellij.util.attribute
import com.intellij.util.containers.SmartHashSet
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.isEmpty
import gnu.trove.THashMap
import gnu.trove.THashSet
import org.jdom.Element
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.file.Path
abstract class DirectoryBasedStorageBase(@Suppress("DEPRECATION") protected val splitter: StateSplitter,
protected val pathMacroSubstitutor: TrackingPathMacroSubstitutor? = null) : StateStorageBase<StateMap>() {
protected var componentName: String? = null
protected abstract val virtualFile: VirtualFile?
override public fun loadData(): StateMap = StateMap.fromMap(DirectoryStorageUtil.loadFrom(virtualFile, pathMacroSubstitutor))
override fun startExternalization(): StateStorage.ExternalizationSession? = null
override fun analyzeExternalChangesAndUpdateIfNeed(componentNames: MutableSet<String>) {
// todo reload only changed file, compute diff
val newData = loadData()
storageDataRef.set(newData)
if (componentName != null) {
componentNames.add(componentName!!)
}
}
override fun getSerializedState(storageData: StateMap, component: Any?, componentName: String, archive: Boolean): Element? {
this.componentName = componentName
if (storageData.isEmpty()) {
return null
}
// FileStorageCoreUtil on load check both component and name attributes (critical important for external store case, where we have only in-project artifacts, but not external)
val state = Element(FileStorageCoreUtil.COMPONENT).attribute(FileStorageCoreUtil.NAME, componentName)
if (splitter is StateSplitterEx) {
for (fileName in storageData.keys()) {
val subState = storageData.getState(fileName, archive) ?: return null
splitter.mergeStateInto(state, subState.clone())
}
}
else {
val subElements = SmartList<Element>()
for (fileName in storageData.keys()) {
val subState = storageData.getState(fileName, archive) ?: return null
subElements.add(subState.clone())
}
if (!subElements.isEmpty()) {
splitter.mergeStatesInto(state, subElements.toTypedArray())
}
}
return state
}
override fun hasState(storageData: StateMap, componentName: String): Boolean = storageData.hasStates()
}
open class DirectoryBasedStorage(private val dir: Path,
@Suppress("DEPRECATION") splitter: StateSplitter,
pathMacroSubstitutor: TrackingPathMacroSubstitutor? = null) : DirectoryBasedStorageBase(splitter, pathMacroSubstitutor) {
private @Volatile var cachedVirtualFile: VirtualFile? = null
override val virtualFile: VirtualFile?
get() {
var result = cachedVirtualFile
if (result == null) {
result = LocalFileSystem.getInstance().findFileByPath(dir.systemIndependentPath)
cachedVirtualFile = result
}
return result
}
internal fun setVirtualDir(dir: VirtualFile?) {
cachedVirtualFile = dir
}
override fun startExternalization(): StateStorage.ExternalizationSession? = if (checkIsSavingDisabled()) null else MySaveSession(this, getStorageData())
private class MySaveSession(private val storage: DirectoryBasedStorage, private val originalStates: StateMap) : SaveSessionBase() {
private var copiedStorageData: MutableMap<String, Any>? = null
private val dirtyFileNames = SmartHashSet<String>()
private var someFileRemoved = false
override fun setSerializedState(componentName: String, element: Element?) {
storage.componentName = componentName
val stateAndFileNameList = if (element.isEmpty()) emptyList() else storage.splitter.splitState(element!!)
if (stateAndFileNameList.isEmpty()) {
if (copiedStorageData != null) {
copiedStorageData!!.clear()
}
else if (!originalStates.isEmpty()) {
copiedStorageData = THashMap()
}
return
}
val existingFiles = THashSet<String>(stateAndFileNameList.size)
for (pair in stateAndFileNameList) {
doSetState(pair.second, pair.first)
existingFiles.add(pair.second)
}
for (key in originalStates.keys()) {
if (existingFiles.contains(key)) {
continue
}
if (copiedStorageData == null) {
copiedStorageData = originalStates.toMutableMap()
}
someFileRemoved = true
copiedStorageData!!.remove(key)
}
}
private fun doSetState(fileName: String, subState: Element) {
if (copiedStorageData == null) {
copiedStorageData = setStateAndCloneIfNeed(fileName, subState, originalStates)
if (copiedStorageData != null) {
dirtyFileNames.add(fileName)
}
}
else if (updateState(copiedStorageData!!, fileName, subState)) {
dirtyFileNames.add(fileName)
}
}
override fun createSaveSession() = if (storage.checkIsSavingDisabled() || copiedStorageData == null) null else this
override fun save() {
val stateMap = StateMap.fromMap(copiedStorageData!!)
var dir = storage.virtualFile
if (copiedStorageData!!.isEmpty()) {
if (dir != null && dir.exists()) {
deleteFile(this, dir)
}
storage.setStorageData(stateMap)
return
}
if (dir == null || !dir.isValid) {
dir = createDir(storage.dir, this)
storage.cachedVirtualFile = dir
}
if (!dirtyFileNames.isEmpty) {
saveStates(dir, stateMap)
}
if (someFileRemoved && dir.exists()) {
deleteFiles(dir)
}
storage.setStorageData(stateMap)
}
private fun saveStates(dir: VirtualFile, states: StateMap) {
for (fileName in states.keys()) {
if (!dirtyFileNames.contains(fileName)) {
continue
}
try {
val element = states.getElement(fileName) ?: continue
val file = dir.getOrCreateChild(fileName, this)
// we don't write xml prolog due to historical reasons (and should not in any case)
val macroManager = if (storage.pathMacroSubstitutor == null) null else (storage.pathMacroSubstitutor as TrackingPathMacroSubstitutorImpl).macroManager
writeFile(null, this, file, XmlDataWriter(FileStorageCoreUtil.COMPONENT, listOf(element), mapOf(FileStorageCoreUtil.NAME to storage.componentName!!), macroManager), getOrDetectLineSeparator(file) ?: LineSeparator.getSystemLineSeparator(), false)
}
catch (e: IOException) {
LOG.error(e)
}
}
}
private fun deleteFiles(dir: VirtualFile) {
runUndoTransparentWriteAction {
for (file in dir.children) {
val fileName = file.name
if (fileName.endsWith(FileStorageCoreUtil.DEFAULT_EXT) && !copiedStorageData!!.containsKey(fileName)) {
if (file.isWritable) {
file.delete(this)
}
else {
throw ReadOnlyModificationException(file, null)
}
}
}
}
}
}
private fun setStorageData(newStates: StateMap) {
storageDataRef.set(newStates)
}
}
private fun getOrDetectLineSeparator(file: VirtualFile): LineSeparator? {
if (!file.exists()) {
return null
}
file.detectedLineSeparator?.let {
return LineSeparator.fromString(it)
}
val lineSeparator = detectLineSeparators(Charsets.UTF_8.decode(ByteBuffer.wrap(file.contentsToByteArray())))
file.detectedLineSeparator = lineSeparator.separatorString
return lineSeparator
} | apache-2.0 | ebadd48b5552acbd29bbcc9aee164a6e | 36.030172 | 255 | 0.698021 | 5.19347 | false | false | false | false |
faceofcat/Tesla-Powered-Thingies | src/main/kotlin/net/ndrei/teslapoweredthingies/machines/cropfarm/FarmlandFactory.kt | 1 | 1200 | package net.ndrei.teslapoweredthingies.machines.cropfarm
import net.minecraft.block.BlockFarmland
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
import net.minecraftforge.fluids.IFluidTank
object FarmlandFactory {
fun getFarmland(world: World, pos: BlockPos): IAmFarmland? {
val state = world.getBlockState(pos)
if (state.block is BlockFarmland) {
return object: IAmFarmland {
@Suppress("NAME_SHADOWING")
override fun moisturize(water: IFluidTank, world: World, pos: BlockPos): Boolean {
val state = world.getBlockState(pos)
val moisture = state.getValue(BlockFarmland.MOISTURE)
val fluidNeeded = Math.min(2, 7 - moisture) * 15
if ((fluidNeeded > 0) && (water.fluidAmount >= fluidNeeded)) {
world.setBlockState(pos, state.withProperty(BlockFarmland.MOISTURE, Math.min(7, moisture + 2)))
water.drain(fluidNeeded, true)
return true
}
return false
}
}
}
return null
}
} | mit | c51a31f093a47ffeacabc8468b98806a | 37.741935 | 119 | 0.5825 | 4.363636 | false | false | false | false |
crunchersaspire/worshipsongs-android | app/src/main/java/org/worshipsongs/fragment/SongsFragment.kt | 2 | 16112 | package org.worshipsongs.fragment
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.PorterDuff
import android.os.Bundle
import android.os.Parcelable
import android.preference.PreferenceManager
import android.util.TypedValue
import android.view.*
import android.widget.AdapterView
import android.widget.ImageView
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import org.worshipsongs.CommonConstants
import org.worshipsongs.R
import org.worshipsongs.WorshipSongApplication
import org.worshipsongs.activity.SongContentViewActivity
import org.worshipsongs.adapter.TitleAdapter
import org.worshipsongs.domain.Setting
import org.worshipsongs.domain.Song
import org.worshipsongs.domain.Type
import org.worshipsongs.listener.SongContentViewListener
import org.worshipsongs.registry.ITabFragment
import org.worshipsongs.service.*
import org.worshipsongs.utils.CommonUtils
import org.worshipsongs.utils.ImageUtils
import java.util.*
/**
* @author : Madasamy
* @version : 3.x
*/
class SongsFragment : Fragment(), TitleAdapter.TitleAdapterListener<Song>, ITabFragment
{
private var state: Parcelable? = null
private var searchView: SearchView? = null
private var filterMenuItem: MenuItem? = null
private var songListView: ListView? = null
private var songs: List<Song>? = null
private var titleAdapter: TitleAdapter<Song>? = null
private var songContentViewListener: SongContentViewListener? = null
private val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(WorshipSongApplication.context)
private val preferenceSettingService = UserPreferenceSettingService()
private val popupMenuService = PopupMenuService()
private var songService: SongService? = null
private var songBookService: SongBookService? = null
private var databaseService: DatabaseService? = null
private var presentationScreenService: PresentationScreenService? = null
private val userPreferenceSettingService = UserPreferenceSettingService()
private val type: String
get()
{
val bundle = arguments
return if (bundle != null && bundle.containsKey(CommonConstants.TYPE))
{
bundle.getString(CommonConstants.TYPE, Type.SONG.name)
} else
{
Type.SONG.name
}
}
private val objectId: Int
get()
{
val bundle = arguments
return bundle?.getInt(CommonConstants.ID) ?: 0
}
private val searchViewCloseListener: SearchView.OnCloseListener
get() = SearchView.OnCloseListener {
filterMenuItem!!.isVisible = false
false
}
private val searchViewClickListener: View.OnClickListener
get() = View.OnClickListener { filterMenuItem!!.isVisible = true }
private val queryTextListener: SearchView.OnQueryTextListener
get() = object : SearchView.OnQueryTextListener
{
override fun onQueryTextSubmit(query: String): Boolean
{
updateObjects(query)
return true
}
override fun onQueryTextChange(query: String): Boolean
{
updateObjects(query)
return true
}
}
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
if (savedInstanceState != null)
{
state = savedInstanceState.getParcelable(STATE_KEY)
}
databaseService = DatabaseService(activity!!)
songService = SongService(activity!!.applicationContext)
songBookService = SongBookService(activity!!.applicationContext)
presentationScreenService = PresentationScreenService(activity!!)
setHasOptionsMenu(true)
initSetUp()
}
private fun initSetUp()
{
databaseService!!.open()
loadSongs()
if (!sharedPreferences.contains(CommonConstants.SEARCH_BY_TITLE_KEY))
{
sharedPreferences.edit().putBoolean(CommonConstants.SEARCH_BY_TITLE_KEY, true).apply()
}
}
private fun loadSongs()
{
val type = type
val id = objectId
if (Type.AUTHOR.name.equals(type, ignoreCase = true))
{
songs = songService!!.findByAuthorId(id)
} else if (Type.TOPICS.name.equals(type, ignoreCase = true))
{
songs = songService!!.findByTopicId(id)
} else if (Type.SONG_BOOK.name.equals(type, ignoreCase = true))
{
songs = songService!!.findBySongBookId(id)
} else
{
songs = songService!!.findAll()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?
{
val view = inflater.inflate(R.layout.songs_layout, container, false)
setListView(view)
return view
}
private fun setListView(view: View)
{
songListView = view.findViewById<View>(R.id.song_list_view) as ListView
titleAdapter = TitleAdapter((activity as AppCompatActivity?)!!, R.layout.songs_layout)
titleAdapter!!.setTitleAdapterListener(this)
updateObjects("")
songListView!!.adapter = titleAdapter
songListView!!.onItemClickListener = onItemClickListener()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater)
{
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.action_bar_menu, menu)
// Associate searchable configuration with the SearchView
val searchManager = activity!!.getSystemService(Context.SEARCH_SERVICE) as SearchManager
searchView = menu!!.findItem(R.id.menu_search).actionView as SearchView
searchView!!.maxWidth = Integer.MAX_VALUE
searchView!!.setSearchableInfo(searchManager.getSearchableInfo(activity!!.componentName))
val image = searchView!!.findViewById<View>(R.id.search_close_btn) as ImageView
val drawable = image.drawable
drawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP)
searchView!!.setOnCloseListener(searchViewCloseListener)
searchView!!.setOnSearchClickListener(searchViewClickListener)
searchView!!.setOnQueryTextListener(queryTextListener)
val searchByText = sharedPreferences.getBoolean(CommonConstants.SEARCH_BY_TITLE_KEY, true)
searchView!!.queryHint = if (searchByText) getSearchByTitleOrNumberPlaceholder(type) else getString(R.string.hint_content)
filterMenuItem = menu.getItem(0).setVisible(false)
filterMenuItem!!.icon = ImageUtils.resizeBitmapImageFn(resources, BitmapFactory.decodeResource(resources, getResourceId(searchByText)), 35)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean
{
when (item.itemId)
{
android.R.id.home ->
{
activity!!.finish()
return true
}
R.id.filter ->
{
val builder = AlertDialog.Builder(ContextThemeWrapper(context, R.style.DialogTheme))
builder.setTitle(getString(R.string.search_title))
builder.setCancelable(true)
val title = if (Type.SONG_BOOK.name.equals(type, ignoreCase = true)) getString(R.string.search_title_or_content) else getString(R.string.search_type_title)
builder.setItems(arrayOf(title, getString(R.string.search_type_content))) { dialog, which ->
if (which == 0)
{
searchView!!.queryHint = getSearchByTitleOrNumberPlaceholder(type)
sharedPreferences.edit().putBoolean(CommonConstants.SEARCH_BY_TITLE_KEY, true).apply()
item.icon = ImageUtils.resizeBitmapImageFn(resources, BitmapFactory.decodeResource(resources, getResourceId(true)), 35)
} else
{
searchView!!.queryHint = getString(R.string.hint_content)
sharedPreferences.edit().putBoolean(CommonConstants.SEARCH_BY_TITLE_KEY, false).apply()
item.icon = ImageUtils.resizeBitmapImageFn(resources, BitmapFactory.decodeResource(resources, getResourceId(false)), 35)
}
searchView!!.setQuery(searchView!!.query, true)
}
builder.show()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
private fun getSearchByTitleOrNumberPlaceholder(type: String): String
{
return if (type.equals(Type.SONG_BOOK.name, ignoreCase = true))
{
getString(R.string.hint_title_or_number)
} else
{
getString(R.string.hint_title)
}
}
override fun onPrepareOptionsMenu(menu: Menu)
{
super.onPrepareOptionsMenu(menu)
}
override fun onResume()
{
super.onResume()
if (sharedPreferences.getBoolean(CommonConstants.UPDATED_SONGS_KEY, false))
{
updateObjects("")
sharedPreferences.edit().putBoolean(CommonConstants.UPDATED_SONGS_KEY, false).apply()
} else if (state != null)
{
songListView!!.onRestoreInstanceState(state)
} else
{
updateObjects("")
titleAdapter!!.addObjects(songService!!.filterSongs(type, "", songs!!))
}
}
override fun setUserVisibleHint(isVisibleToUser: Boolean)
{
super.setUserVisibleHint(isVisibleToUser)
if (isVisibleToUser)
{
if (activity != null)
{
CommonUtils.hideKeyboard(activity)
}
if (searchView != null)
{
val searchByText = sharedPreferences.getBoolean(CommonConstants.SEARCH_BY_TITLE_KEY, true)
searchView!!.queryHint = if (searchByText) getSearchByTitleOrNumberPlaceholder(type) else getString(R.string.hint_content)
}
if (filterMenuItem != null)
{
filterMenuItem!!.isVisible = false
}
}
}
internal fun getResourceId(searchByText: Boolean): Int
{
return if (searchByText) R.drawable.ic_titles else R.drawable.ic_content_paste
}
override fun onSaveInstanceState(outState: Bundle)
{
if (this.isAdded && songListView != null)
{
outState.putParcelable(STATE_KEY, songListView!!.onSaveInstanceState())
}
super.onSaveInstanceState(outState)
}
override fun onPause()
{
state = songListView!!.onSaveInstanceState()
super.onPause()
}
override fun setViews(objects: Map<String, Any>, song: Song?)
{
val titleTextView = objects[CommonConstants.TITLE_KEY] as TextView?
titleTextView!!.text = getTitle(song!!)
val presentingSong = Setting.instance.song
if (presentingSong != null && presentingSong.title == song.title && presentationScreenService!!.isPresentSong())
{
titleTextView.setTextColor(context!!.resources.getColor(R.color.light_navy_blue))
} else
{
val typedValue = TypedValue()
activity!!.theme.resolveAttribute(android.R.attr.textColor, typedValue, true)
titleTextView.setTextColor(typedValue.data)
}
val subTitleTextView = objects[CommonConstants.SUBTITLE_KEY] as TextView?
subTitleTextView!!.visibility = if (song.songBookNumber > 0) View.VISIBLE else View.GONE
subTitleTextView.text = getString(R.string.song_book_no) + " " + song.songBookNumber
val playImageView = objects[CommonConstants.PLAY_IMAGE_KEy] as ImageView?
playImageView!!.visibility = if (isShowPlayIcon(song)) View.VISIBLE else View.GONE
playImageView.setOnClickListener(imageOnClickListener(song.title!!))
val optionsImageView = objects[CommonConstants.OPTIONS_IMAGE_KEY] as ImageView?
optionsImageView!!.visibility = View.VISIBLE
optionsImageView.setOnClickListener(imageOnClickListener(song.title!!))
showSongBook(song, objects)
}
private fun showSongBook(song: Song, objects: Map<String, Any>)
{
val songBookNames = songBookService?.findFormattedSongBookNames(song.id)
val songBookTextView = objects[CommonConstants.SONG_BOOK_NAME_KEY] as TextView?
songBookTextView!!.visibility = if (canDisplaySongBook(song, songBookNames)) View.VISIBLE else View.GONE
songBookTextView.text = songBookNames!!.joinToString()
}
private fun canDisplaySongBook(song: Song, songBookNames: List<String>?) =
userPreferenceSettingService.displaySongBook && songBookNames!!.isNotEmpty() && isUserNotInSongBooksTab(song)
private fun isUserNotInSongBooksTab(song: Song) = song.songBookNumber == 0
private fun onItemClickListener(): AdapterView.OnItemClickListener
{
return AdapterView.OnItemClickListener { parent, view, position, id ->
val song = titleAdapter!!.getItem(position)
Setting.instance.position = 0
val titleList = ArrayList<String>()
titleList.add(song!!.title!!)
val bundle = Bundle()
bundle.putStringArrayList(CommonConstants.TITLE_LIST_KEY, titleList)
if (songContentViewListener == null)
{
val intent = Intent(context, SongContentViewActivity::class.java)
intent.putExtra(CommonConstants.SONG_BOOK_NUMBER_KEY, song.songBookNumber)
intent.putExtras(bundle)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context!!.startActivity(intent)
} else
{
songContentViewListener!!.displayContent(song.title!!, titleList, 0)
}
}
}
private fun getTitle(song: Song): String
{
try
{
return if (preferenceSettingService.isTamil && song.tamilTitle!!.length > 0) song.tamilTitle!!
else song.title!!
} catch (e: Exception)
{
return song.title!!
}
}
internal fun isShowPlayIcon(song: Song): Boolean
{
val urlKey = song.urlKey
return urlKey != null && urlKey.length > 0 && preferenceSettingService.isPlayVideo
}
private fun imageOnClickListener(title: String): View.OnClickListener
{
return View.OnClickListener { view -> popupMenuService.showPopupmenu(activity as AppCompatActivity, view, title, true) }
}
override fun defaultSortOrder(): Int
{
return 0
}
override val title: String
get()
{
return "titles"
}
override fun checked(): Boolean
{
return true
}
override fun setListenerAndBundle(songContentViewListener: SongContentViewListener?, bundle: Bundle)
{
this.songContentViewListener = songContentViewListener
}
private fun updateObjects(query: String)
{
activity!!.runOnUiThread {
if (titleAdapter != null)
{
titleAdapter!!.addObjects(songService!!.filterSongs(type, query, songs!!))
}
}
}
companion object
{
private val CLASS_NAME = SongsFragment::class.java.simpleName
private val STATE_KEY = "listViewState"
fun newInstance(bundle: Bundle): SongsFragment
{
val songsFragment = SongsFragment()
songsFragment.arguments = bundle
return songsFragment
}
}
}
| gpl-3.0 | 35d290a106cc999a885c2d93d4a8d2be | 35.869565 | 171 | 0.648771 | 5.121424 | false | false | false | false |
AcapellaSoft/Aconite | aconite-core/src/io/aconite/annotations/Methods.kt | 1 | 2483 | package io.aconite.annotations
/** Accepts custom [method] HTTP-method on [url] relative URL. */
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class HTTP(
/** http-method name */
val method: String,
/** relative (in module) url */
val url: String = ""
)
/**
* The function marked by this annotation must return an interface
* that represents the inner HTTP-module.
*/
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class MODULE(
/** relative (in module) url */
val value: String = ""
)
/** Accepts DELETE request on [value] relative URL. */
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class DELETE(
/** relative (in module) url */
val value: String = ""
)
/** Accepts GET request on [value] relative URL. */
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class GET(
/** relative (in module) url */
val value: String = ""
)
/** Accepts HEAD request on [value] relative URL. */
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class HEAD(
/** relative (in module) url */
val value: String = ""
)
/** Accepts OPTIONS request on [value] relative URL. */
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class OPTIONS(
/** relative (in module) url */
val value: String = ""
)
/** Accepts PATCH request on [value] relative URL. */
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class PATCH(
/** relative (in module) url */
val value: String = ""
)
/** Accepts POST request on [value] relative URL. */
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class POST(
/** relative (in module) url */
val value: String = ""
)
/** Accepts PUT request on [value] relative URL. */
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class PUT(
/** relative (in module) url */
val value: String = ""
)
/** Called before every request */
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class BeforeRequest
/** Called after every request */
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class AfterRequest | mit | 1a393dd844736048f51f9a9f07b780d8 | 26.910112 | 66 | 0.697543 | 4.340909 | false | false | false | false |
ansman/okhttp | okhttp/src/test/java/okhttp3/ServerTruncatesRequestTest.kt | 2 | 8429 | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer
import mockwebserver3.SocketPolicy
import okhttp3.Headers.Companion.headersOf
import okhttp3.internal.duplex.AsyncRequestBody
import okhttp3.internal.http2.ErrorCode
import okhttp3.testing.PlatformRule
import okhttp3.tls.internal.TlsUtil.localhost
import okio.BufferedSink
import okio.IOException
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Timeout
import org.junit.jupiter.api.extension.RegisterExtension
import org.junit.jupiter.api.fail
@Timeout(30)
@Tag("Slowish")
class ServerTruncatesRequestTest(
val server: MockWebServer
) {
@RegisterExtension @JvmField val platform = PlatformRule()
@RegisterExtension @JvmField var clientTestRule = OkHttpClientTestRule()
private val listener = RecordingEventListener()
private val handshakeCertificates = localhost()
private var client = clientTestRule.newClientBuilder()
.eventListenerFactory(clientTestRule.wrap(listener))
.build()
@BeforeEach fun setUp() {
platform.assumeNotOpenJSSE()
platform.assumeHttp2Support()
platform.assumeNotBouncyCastle()
}
@Test fun serverTruncatesRequestOnLongPostHttp1() {
serverTruncatesRequestOnLongPost(https = false)
}
@Test fun serverTruncatesRequestOnLongPostHttp2() {
enableProtocol(Protocol.HTTP_2)
serverTruncatesRequestOnLongPost(https = true)
}
private fun serverTruncatesRequestOnLongPost(https: Boolean) {
server.enqueue(MockResponse()
.setSocketPolicy(SocketPolicy.DO_NOT_READ_REQUEST_BODY)
.setBody("abc")
.apply { this.http2ErrorCode = ErrorCode.NO_ERROR.httpCode })
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.post(SlowRequestBody)
.build()
)
call.execute().use { response ->
assertThat(response.body!!.string()).isEqualTo("abc")
}
val expectedEvents = mutableListOf<String>()
// Start out with standard events...
expectedEvents += "CallStart"
expectedEvents += "ProxySelectStart"
expectedEvents += "ProxySelectEnd"
expectedEvents += "DnsStart"
expectedEvents += "DnsEnd"
expectedEvents += "ConnectStart"
if (https) {
expectedEvents += "SecureConnectStart"
expectedEvents += "SecureConnectEnd"
}
expectedEvents += "ConnectEnd"
expectedEvents += "ConnectionAcquired"
expectedEvents += "RequestHeadersStart"
expectedEvents += "RequestHeadersEnd"
expectedEvents += "RequestBodyStart"
// ... but we can read the response even after writing the request fails.
expectedEvents += "RequestFailed"
expectedEvents += "ResponseHeadersStart"
expectedEvents += "ResponseHeadersEnd"
expectedEvents += "ResponseBodyStart"
expectedEvents += "ResponseBodyEnd"
expectedEvents += "ConnectionReleased"
expectedEvents += "CallEnd"
assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents)
// Confirm that the connection pool was not corrupted by making another call.
makeSimpleCall()
}
/**
* If the server returns a full response, it doesn't really matter if the HTTP/2 stream is reset.
* Attempts to write the request body fails fast.
*/
@Test fun serverTruncatesRequestHttp2OnDuplexRequest() {
enableProtocol(Protocol.HTTP_2)
server.enqueue(MockResponse()
.setSocketPolicy(SocketPolicy.DO_NOT_READ_REQUEST_BODY)
.setBody("abc")
.apply { this.http2ErrorCode = ErrorCode.NO_ERROR.httpCode })
val requestBody = AsyncRequestBody()
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.post(requestBody)
.build()
)
call.execute().use { response ->
assertThat(response.body!!.string()).isEqualTo("abc")
val requestBodyOut = requestBody.takeSink()
try {
SlowRequestBody.writeTo(requestBodyOut)
fail("")
} catch (expected: IOException) {
}
try {
requestBodyOut.close()
fail("")
} catch (expected: IOException) {
}
}
// Confirm that the connection pool was not corrupted by making another call.
makeSimpleCall()
}
@Test fun serverTruncatesRequestButTrailersCanStillBeReadHttp1() {
serverTruncatesRequestButTrailersCanStillBeRead(http2 = false)
}
@Test fun serverTruncatesRequestButTrailersCanStillBeReadHttp2() {
enableProtocol(Protocol.HTTP_2)
serverTruncatesRequestButTrailersCanStillBeRead(http2 = true)
}
private fun serverTruncatesRequestButTrailersCanStillBeRead(http2: Boolean) {
val mockResponse = MockResponse()
.setSocketPolicy(SocketPolicy.DO_NOT_READ_REQUEST_BODY)
.apply {
this.trailers = headersOf("caboose", "xyz")
this.http2ErrorCode = ErrorCode.NO_ERROR.httpCode
}
// Trailers always work for HTTP/2, but only for chunked bodies in HTTP/1.
if (http2) {
mockResponse.setBody("abc")
} else {
mockResponse.setChunkedBody("abc", 1)
}
server.enqueue(mockResponse)
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.post(SlowRequestBody)
.build()
)
call.execute().use { response ->
assertThat(response.body!!.string()).isEqualTo("abc")
assertThat(response.trailers()).isEqualTo(headersOf("caboose", "xyz"))
}
}
@Test fun noAttemptToReadResponseIfLoadingRequestBodyIsSourceOfFailure() {
server.enqueue(MockResponse().setBody("abc"))
val requestBody = object : RequestBody() {
override fun contentType(): MediaType? = null
override fun writeTo(sink: BufferedSink) {
throw IOException("boom") // Despite this exception, 'sink' is healthy.
}
}
val callA = client.newCall(
Request.Builder()
.url(server.url("/"))
.post(requestBody)
.build()
)
try {
callA.execute()
fail("")
} catch (expected: IOException) {
assertThat(expected).hasMessage("boom")
}
assertThat(server.requestCount).isEqualTo(0)
// Confirm that the connection pool was not corrupted by making another call. This doesn't use
// makeSimpleCall() because it uses the MockResponse enqueued above.
val callB = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
callB.execute().use { response ->
assertThat(response.body!!.string()).isEqualTo("abc")
}
}
private fun makeSimpleCall() {
server.enqueue(MockResponse().setBody("healthy"))
val callB = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
callB.execute().use { response ->
assertThat(response.body!!.string()).isEqualTo("healthy")
}
}
private fun enableProtocol(protocol: Protocol) {
enableTls()
client = client.newBuilder()
.protocols(listOf(protocol, Protocol.HTTP_1_1))
.build()
server.protocols = client.protocols
}
private fun enableTls() {
client = client.newBuilder()
.sslSocketFactory(
handshakeCertificates.sslSocketFactory(),
handshakeCertificates.trustManager
)
.hostnameVerifier(RecordingHostnameVerifier())
.build()
server.useHttps(handshakeCertificates.sslSocketFactory(), false)
}
/** A request body that slowly trickles bytes, expecting to not complete. */
private object SlowRequestBody : RequestBody() {
override fun contentType(): MediaType? = null
override fun writeTo(sink: BufferedSink) {
for (i in 0 until 50) {
sink.writeUtf8("abc")
sink.flush()
Thread.sleep(100)
}
fail("")
}
}
}
| apache-2.0 | fd4563b34fd4b61362cd16ee021c9c88 | 29.539855 | 99 | 0.68644 | 4.374157 | false | false | false | false |
songzhw/AndroidArchitecture | deprecated/MVI/MVI101/MVI_Client/app/src/main/java/ca/six/mvi/biz/home/HomeData.kt | 1 | 757 | package ca.six.mvi.biz.home
class HomeData {
var isError: Boolean = false
var isLoading: Boolean = false
var error: Throwable? = null
var todos: List<Todo>? = null
constructor(error: Throwable){
this.error = error
this.isError = true
}
constructor(isLoading: Boolean){
this.isLoading = isLoading
}
constructor(todos: List<Todo>?) {
this.todos = todos
}
override fun toString(): String {
return "HomeData(isError=$isError, isLoading=$isLoading, error=$error, todos=$todos)"
}
// class Empty : HomeData{}
// class Loading : HomeData {}
// class TodoList(val todos: ArrayList<Todos>) : HomeData { }
// class Error(val error: Throwable) : HomeData { }
} | apache-2.0 | 73446d889adb572c019696d06a555038 | 22.6875 | 93 | 0.620872 | 4.005291 | false | false | false | false |
didi/DoraemonKit | Android/dokit/src/main/java/com/didichuxing/doraemonkit/aop/method_stack/MethodStackUtil.kt | 1 | 11023 | package com.didichuxing.doraemonkit.aop.method_stack
import android.app.Application
import android.util.Log
import com.didichuxing.doraemonkit.util.GsonUtils
import com.didichuxing.doraemonkit.util.LogUtils
import com.didichuxing.doraemonkit.aop.MethodCostUtil
import com.didichuxing.doraemonkit.kit.timecounter.TimeCounterManager
import java.util.*
import java.util.concurrent.ConcurrentHashMap
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2020/4/22-15:44
* 描 述:自定义函数入口调用栈的耗时工具类
* 修订历史:
* ================================================
*/
public object MethodStackUtil {
/**
* key className&methodName
*/
private val METHOD_STACKS: MutableList<ConcurrentHashMap<String, MethodInvokNode>> by lazy {
Collections.synchronizedList(mutableListOf<ConcurrentHashMap<String, MethodInvokNode>>())
}
/**
* 用来标识是静态函数对象
*/
private val staticMethodObject: StaticMethodObject by lazy {
StaticMethodObject()
}
private fun createMethodStackList(totalLevel: Int) {
if (METHOD_STACKS.size == totalLevel) {
return
}
METHOD_STACKS.clear()
for (index in 0 until totalLevel) {
METHOD_STACKS.add(index, ConcurrentHashMap())
}
}
/**
* @param currentLevel
* @param methodName
* @param classObj null 代表静态函数
*/
fun recodeObjectMethodCostStart(
totalLevel: Int,
thresholdTime: Int,
currentLevel: Int,
className: String?,
methodName: String,
desc: String?,
classObj: Any?
) {
try {
//先创建队列
createMethodStackList(totalLevel)
val methodInvokNode = MethodInvokNode()
methodInvokNode.startTimeMillis = System.currentTimeMillis()
methodInvokNode.currentThreadName = Thread.currentThread().name
methodInvokNode.className = className
methodInvokNode.methodName = methodName
methodInvokNode.level = currentLevel
METHOD_STACKS[currentLevel][String.format("%s&%s", className, methodName)] =
methodInvokNode
//特殊判定
if (currentLevel == 0) {
if (classObj is Application) {
if (methodName == "onCreate") {
TimeCounterManager.get().onAppCreateStart()
}
if (methodName == "attachBaseContext") {
TimeCounterManager.get().onAppAttachBaseContextStart()
}
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
/**
* @param currentLevel
* @param className
* @param methodName
* @param desc
* @param classObj null 代表静态函数
*/
fun recodeObjectMethodCostEnd(
thresholdTime: Int,
currentLevel: Int,
className: String,
methodName: String,
desc: String?,
classObj: Any?
) {
synchronized(MethodStackUtil::class.java) {
try {
val methodInvokNode =
METHOD_STACKS[currentLevel][String.format("%s&%s", className, methodName)]
if (methodInvokNode != null) {
methodInvokNode.setEndTimeMillis(System.currentTimeMillis())
bindNode(thresholdTime, currentLevel, methodInvokNode)
}
//打印函数调用栈
if (currentLevel == 0) {
if (methodInvokNode != null) {
toStack(classObj is Application, methodInvokNode)
}
if (classObj is Application) {
//Application 启动时间统计
if (methodName == "onCreate") {
TimeCounterManager.get().onAppCreateEnd()
}
if (methodName == "attachBaseContext") {
TimeCounterManager.get().onAppAttachBaseContextEnd()
}
}
//移除对象
METHOD_STACKS[0].remove("$className&$methodName")
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
private fun getParentMethod(currentClassName: String?, currentMethodName: String?): String {
val stackTraceElements = Thread.currentThread().stackTrace
var index = 0
for (i in stackTraceElements.indices) {
val stackTraceElement = stackTraceElements[i]
if (currentClassName == stackTraceElement.className && currentMethodName == stackTraceElement.methodName) {
index = i
break
}
}
val parentStackTraceElement = stackTraceElements[index + 1]
return String.format(
"%s&%s",
parentStackTraceElement.className,
parentStackTraceElement.methodName
)
}
private fun bindNode(thresholdTime: Int, currentLevel: Int, methodInvokNode: MethodInvokNode?) {
if (methodInvokNode == null) {
return
}
//过滤掉小于指定阈值的函数
if (methodInvokNode.getCostTimeMillis() <= thresholdTime) {
return
}
if (currentLevel >= 1) {
val parentMethodNode = METHOD_STACKS[currentLevel - 1][getParentMethod(
methodInvokNode.className,
methodInvokNode.methodName
)]
if (parentMethodNode != null) {
methodInvokNode.parent = parentMethodNode
parentMethodNode.addChild(methodInvokNode)
}
}
}
fun recodeStaticMethodCostStart(
totalLevel: Int,
thresholdTime: Int,
currentLevel: Int,
className: String?,
methodName: String,
desc: String?
) {
recodeObjectMethodCostStart(
totalLevel,
thresholdTime,
currentLevel,
className,
methodName,
desc,
staticMethodObject
)
}
fun recodeStaticMethodCostEnd(
thresholdTime: Int,
currentLevel: Int,
className: String,
methodName: String,
desc: String?
) {
recodeObjectMethodCostEnd(
thresholdTime,
currentLevel,
className,
methodName,
desc,
staticMethodObject
)
}
private fun jsonTravel(
methodStackBeans: MutableList<MethodStackBean>?,
methodInvokNodes: List<MethodInvokNode>?
) {
if (methodInvokNodes == null) {
return
}
for (methodInvokNode in methodInvokNodes) {
val methodStackBean = MethodStackBean()
methodStackBean.setCostTime(methodInvokNode.getCostTimeMillis())
methodStackBean.function = methodInvokNode.className + "&" + methodInvokNode.methodName
methodStackBean.children = ArrayList()
jsonTravel(methodStackBean.children, methodInvokNode.children)
methodStackBeans?.add(methodStackBean)
}
}
private fun stackTravel(
stringBuilder: StringBuilder,
methodInvokNodes: List<MethodInvokNode>?
) {
if (methodInvokNodes == null) {
return
}
for (methodInvokNode in methodInvokNodes) {
stringBuilder.append(
String.format(
"%s%s%s%s%s",
methodInvokNode.level,
SPACE_0,
methodInvokNode.getCostTimeMillis().toString() + "ms",
getSpaceString(methodInvokNode.level),
methodInvokNode.className + "&" + methodInvokNode.methodName
)
).append("\n")
stackTravel(stringBuilder, methodInvokNode.children)
}
}
fun toJson() {
val methodStackBeans: MutableList<MethodStackBean> = ArrayList()
for (methodInvokNode in METHOD_STACKS[0].values) {
val methodStackBean = MethodStackBean()
methodStackBean.setCostTime(methodInvokNode.getCostTimeMillis())
methodStackBean.function = methodInvokNode.className + "&" + methodInvokNode.methodName
methodStackBean.children = ArrayList()
jsonTravel(methodStackBean.children, methodInvokNode.children)
methodStackBeans.add(methodStackBean)
}
val json = GsonUtils.toJson(methodStackBeans)
LogUtils.json(json)
}
fun toStack(isAppStart: Boolean, methodInvokNode: MethodInvokNode) {
val stringBuilder = StringBuilder()
stringBuilder.append("=========DoKit函数调用栈==========").append("\n")
stringBuilder.append(String.format("%s %s %s", "level", "time", "function"))
.append("\n")
stringBuilder.append(
String.format(
"%s%s%s%s%s",
methodInvokNode.level,
SPACE_0,
methodInvokNode.getCostTimeMillis().toString() + "ms",
getSpaceString(methodInvokNode.level),
methodInvokNode.className + "&" + methodInvokNode.methodName
)
).append("\n")
stackTravel(stringBuilder, methodInvokNode.children)
Log.i(TAG, stringBuilder.toString())
if (isAppStart && methodInvokNode.level == 0) {
if (methodInvokNode.methodName == "onCreate") {
STR_APP_ON_CREATE = stringBuilder.toString()
}
if (methodInvokNode.methodName == "attachBaseContext") {
STR_APP_ATTACH_BASECONTEXT = stringBuilder.toString()
}
}
}
private fun getSpaceString(level: Int): String {
return when (level) {
0 -> SPACE_0
1 -> SPACE_1
2 -> SPACE_2
3 -> SPACE_3
4 -> SPACE_4
5 -> SPACE_5
6 -> SPACE_6
7 -> SPACE_7
else -> SPACE_0
}
}
private const val TAG = "DOKIT_SLOW_METHOD"
private const val SPACE_0 = "********"
private const val SPACE_1 = "*************"
private const val SPACE_2 = "*****************"
private const val SPACE_3 = "*********************"
private const val SPACE_4 = "*************************"
private const val SPACE_5 = "*****************************"
private const val SPACE_6 = "*********************************"
private const val SPACE_7 = "*************************************"
@JvmField
var STR_APP_ON_CREATE: String? = null
@JvmField
var STR_APP_ATTACH_BASECONTEXT: String? = null
} | apache-2.0 | de088a5f703b112533f79e72a4357420 | 32.273846 | 119 | 0.544345 | 4.944216 | false | false | false | false |
hypercube1024/firefly | firefly-net/src/test/kotlin/com/fireflysource/net/http/client/impl/TestHttp1ClientConnection.kt | 1 | 2176 | package com.fireflysource.net.http.client.impl
import com.fireflysource.net.http.common.model.HttpHeader
import com.fireflysource.net.http.common.model.HttpHeaderValue
import com.fireflysource.net.http.common.model.HttpMethod
import com.fireflysource.net.http.common.model.HttpURI
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
class TestHttp1ClientConnection {
@Test
@DisplayName("should add the HOST and KEEP_ALIVE headers")
fun testPrepareHttp1Headers() {
val request = AsyncHttpClientRequest()
request.method = HttpMethod.GET.value
request.uri = HttpURI("https://www.fireflysource.com/")
prepareHttp1Headers(request) { "defaultHost" }
assertTrue(request.httpFields.getValuesList(HttpHeader.HOST.value).isNotEmpty())
assertEquals("www.fireflysource.com", request.httpFields[HttpHeader.HOST.value])
assertEquals(HttpHeaderValue.KEEP_ALIVE.value, request.httpFields[HttpHeader.CONNECTION.value])
}
@Test
@DisplayName("should set default host header")
fun testDefaultHost() {
val request = AsyncHttpClientRequest()
request.method = HttpMethod.GET.value
request.uri = HttpURI("/echo0")
prepareHttp1Headers(request) { "defaultHost" }
assertTrue(request.httpFields.getValuesList(HttpHeader.HOST.value).isNotEmpty())
assertEquals("defaultHost", request.httpFields[HttpHeader.HOST.value])
}
@Test
@DisplayName("should not remove user setting headers")
fun testExistConnectionHeaders() {
val request = AsyncHttpClientRequest()
request.method = HttpMethod.GET.value
request.uri = HttpURI("https://www.fireflysource.com/")
request.httpFields.addCSV(HttpHeader.CONNECTION, HttpHeaderValue.UPGRADE.value, "HTTP2-Settings")
prepareHttp1Headers(request) { "" }
assertEquals(
"${HttpHeaderValue.UPGRADE.value}, HTTP2-Settings, ${HttpHeaderValue.KEEP_ALIVE.value}",
request.httpFields[HttpHeader.CONNECTION.value]
)
}
} | apache-2.0 | 12b108a36f816c7e7873679eff5da63a | 40.865385 | 105 | 0.727482 | 4.369478 | false | true | false | false |
Sefford/fraggle | fraggle/src/main/java/com/sefford/fraggle/NullBackStack.kt | 1 | 384 | package com.sefford.fraggle
import androidx.fragment.app.FragmentManager
object NullBackStack : FragmentManager.BackStackEntry {
override fun getId() = 0
override fun getName() = ""
override fun getBreadCrumbTitleRes() = 0
override fun getBreadCrumbShortTitleRes() = 0
override fun getBreadCrumbTitle() = ""
override fun getBreadCrumbShortTitle() = ""
} | apache-2.0 | 40b626332f7abdc8bd2b8f7ef057ba27 | 21.647059 | 55 | 0.731771 | 4.740741 | false | false | false | false |
jpeddicord/speedofsound | src/net/codechunk/speedofsound/service/SoundService.kt | 1 | 11555 | package net.codechunk.speedofsound.service
import android.Manifest
import android.app.*
import android.content.*
import android.content.pm.PackageManager
import android.location.Location
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.preference.PreferenceManager
import android.util.Log
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.google.android.gms.location.*
import net.codechunk.speedofsound.R
import net.codechunk.speedofsound.SpeedActivity
import net.codechunk.speedofsound.util.AppPreferences
/**
* The main sound control service.
*
* Responsible for adjusting the volume based on the current speed. Can be
* started and stopped externally, but is largely independent.
*/
class SoundService : Service() {
/**
* The current tracking state.
*/
var isTracking = false
private set
private lateinit var fusedLocationClient: FusedLocationProviderClient
private var localBroadcastManager: LocalBroadcastManager? = null
private var settings: SharedPreferences? = null
private var volumeThread: VolumeThread? = null
private val binder = LocalBinder()
private var volumeConversion: VolumeConversion? = null
/**
* Build a fancy-pants notification.
*/
private val notification: Notification
get() {
@RequiresApi(Build.VERSION_CODES.O)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_LOW
val name = getString(R.string.app_name)
val channel = NotificationChannel("main", name, importance)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
val notificationIntent = Intent(this, SpeedActivity::class.java)
val builder = NotificationCompat.Builder(this, "main")
builder.setContentTitle(getString(R.string.app_name))
builder.setContentText(getString(R.string.notification_text))
builder.setContentIntent(PendingIntent.getActivity(this, 0, notificationIntent, 0))
builder.setTicker(getString(R.string.ticker_text))
builder.setSmallIcon(R.drawable.ic_notification)
builder.setWhen(System.currentTimeMillis())
val stopIntent = Intent(this, SoundServiceManager::class.java)
stopIntent.putExtra(SET_TRACKING_STATE, false)
builder.addAction(R.drawable.ic_stop, getString(R.string.stop),
PendingIntent.getBroadcast(this, 0, stopIntent, PendingIntent.FLAG_ONE_SHOT))
return builder.build()
}
/**
* Custom location listener. Triggers volume changes based on the current
* average speed.
*/
private val locationUpdater = object : LocationCallback() {
private var previousLocation: Location? = null
/**
* Change the volume based on the current average speed. If speed is not
* available from the current location provider, calculate it from the
* previous location. After updating the average and updating the
* volume, send out a broadcast notifying of the changes.
*/
override fun onLocationResult(locations: LocationResult?) {
val location = locations?.lastLocation ?: return
// during shut-down, the volume thread might have finished.
// ignore location updates from this point on.
[email protected] ?: return
// use the GPS-provided speed if available
val speed: Float
if (location.hasSpeed()) {
speed = location.speed
} else {
// speed fall-back (mostly for the emulator)
speed = if (this.previousLocation != null) {
// get the distance between this and the previous update
val meters = previousLocation!!.distanceTo(location)
val timeDelta = (location.time - previousLocation!!.time).toFloat()
Log.v(TAG, "Location distance: $meters")
// convert to meters/second
1000 * meters / timeDelta
} else {
0f
}
this.previousLocation = location
}
val volume = [email protected]!!.speedToVolume(speed)
[email protected]!!.setTargetVolume(volume)
// send out a local broadcast with the details
val intent = Intent(LOCATION_UPDATE_BROADCAST)
intent.putExtra("location", location)
intent.putExtra("speed", speed)
intent.putExtra("volumePercent", (volume * 100).toInt())
[email protected]!!.sendBroadcast(intent)
}
}
/**
* Start up the service and initialize some values. Does not start tracking.
*/
override fun onCreate() {
Log.d(TAG, "Service starting up")
this.fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
// set up preferences
PreferenceManager.setDefaultValues(this, R.xml.preferences, false)
this.settings = PreferenceManager.getDefaultSharedPreferences(this)
AppPreferences.runUpgrade(this)
AppPreferences.updateNativeSpeeds(this.settings!!)
// register handlers & audio
this.localBroadcastManager = LocalBroadcastManager.getInstance(this)
this.volumeConversion = VolumeConversion()
this.volumeConversion!!.onSharedPreferenceChanged(this.settings!!, "") // set initial
}
/**
* Handle a start command.
*
* Return sticky mode to tell Android to keep the service active.
*/
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d(TAG, "Start command received")
// register pref watching
this.settings!!.registerOnSharedPreferenceChangeListener(this.volumeConversion)
LocalBroadcastManager
.getInstance(this)
.registerReceiver(this.messageReceiver, IntentFilter(SET_TRACKING_STATE))
// show mandatory notification
startForeground(R.string.notification_text, notification)
// check if we've been commanded to start tracking;
// we may be started only for the activity view and don't want to start
// anything up implicitly (note: don't handle stop requests here)
if (intent?.extras?.containsKey(SET_TRACKING_STATE) != null) {
Log.v(TAG, "Start command included tracking intent; starting tracking")
this.startTracking()
}
return START_STICKY
}
/**
* Service shut-down.
*/
override fun onDestroy() {
Log.d(TAG, "Service shutting down")
this.settings!!.unregisterOnSharedPreferenceChangeListener(this.volumeConversion)
LocalBroadcastManager.getInstance(this).unregisterReceiver(this.messageReceiver)
}
/**
* The only way to stop tracking is by sending a local broadcast to this service
* or by binding to it (for UI); stopping the service during onStartCommand can cause an
* ANR in 8.0+ due to the fact that a foreground service _must_ present itself.
*/
private val messageReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.extras?.containsKey(SET_TRACKING_STATE) != null) {
Log.v(TAG, "Commanded to change state")
val wanted = intent.extras!!.getBoolean(SET_TRACKING_STATE)
if (wanted) {
[email protected]()
} else {
[email protected]()
}
}
}
}
/**
* Start tracking. Find the best location provider (likely GPS), create an
* ongoing notification, and request location updates.
*/
fun startTracking() {
// ignore requests when we're already tracking
if (this.isTracking) {
return
}
// check runtime permission
val hasPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
if (hasPermission != PackageManager.PERMISSION_GRANTED) {
showNeedLocationToast(this)
return
}
// request location updates
val req = LocationRequest.create().apply {
interval = 1000
fastestInterval = 500
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
this.fusedLocationClient.requestLocationUpdates(req, this.locationUpdater, null)
// start up the volume thread
if (this.volumeThread == null) {
this.volumeThread = VolumeThread(this)
this.volumeThread!!.start()
}
// let everyone know
val intent = Intent(TRACKING_STATE_BROADCAST)
intent.putExtra("tracking", true)
[email protected]!!.sendBroadcast(intent)
this.isTracking = true
Log.d(TAG, "Tracking started")
}
/**
* Stop tracking. Remove the location updates and notification.
*/
fun stopTracking() {
// don't do anything if we're not tracking
if (!this.isTracking) {
return
}
// stop location updates
this.fusedLocationClient.removeLocationUpdates(this.locationUpdater)
// shut off the volume thread
if (this.volumeThread != null) {
this.volumeThread!!.interrupt()
this.volumeThread = null
}
// remove notification and go to background
stopForeground(true)
// let everyone know
val intent = Intent(TRACKING_STATE_BROADCAST)
intent.putExtra("tracking", false)
[email protected]!!.sendBroadcast(intent)
this.isTracking = false
Log.d(TAG, "Tracking stopped")
}
/**
* Service-level access for external classes and activities.
*/
inner class LocalBinder : Binder() {
/**
* Return the service associated with this binder.
*/
val service: SoundService
get() = this@SoundService
}
/**
* Return the binder associated with this service.
*/
override fun onBind(intent: Intent): IBinder? {
return this.binder
}
companion object {
private const val TAG = "SoundService"
/**
* Intent extra to set the tracking state.
*/
const val SET_TRACKING_STATE = "set-tracking-state"
/**
* Broadcast to notify that tracking has started or stopped.
*/
const val TRACKING_STATE_BROADCAST = "tracking-state-changed"
/**
* Location, speed, and sound update broadcast.
*/
const val LOCATION_UPDATE_BROADCAST = "location-update"
fun showNeedLocationToast(ctx: Context) {
val toast = Toast.makeText(ctx, ctx.getString(R.string.no_location_providers), Toast.LENGTH_LONG)
toast.show()
}
}
}
| gpl-2.0 | 947bb8ecc17e4b931baca88516382c2b | 35.222571 | 111 | 0.638252 | 5.108311 | false | false | false | false |
icapps/niddler-ui | client-lib/src/main/kotlin/com/icapps/niddler/lib/model/classifier/SimpleBodyClassifier.kt | 1 | 1854 | package com.icapps.niddler.lib.model.classifier
import com.icapps.niddler.lib.connection.model.NiddlerMessage
import com.icapps.niddler.lib.model.BodyFormat
import org.apache.http.entity.ContentType
/**
* @author nicolaverbeeck
*/
interface SimpleBodyClassifier {
fun classifyFormat(message: NiddlerMessage): BodyFormat
}
class HeaderBodyClassifier : SimpleBodyClassifier {
override fun classifyFormat(message: NiddlerMessage): BodyFormat {
val contentTypeHeader = message.headers?.get("content-type")
if (contentTypeHeader != null && !contentTypeHeader.isEmpty()) {
val contentTypeString = contentTypeHeader[0]
val parsedContentType = ContentType.parse(contentTypeString)
val type = classifyFromMimeType(parsedContentType.mimeType)
if (type != null)
return BodyFormat(type, parsedContentType.mimeType, parsedContentType.charset?.name())
}
return BodyFormat.NONE
}
protected fun classifyFromMimeType(mimeType: String): BodyFormatType? {
return when (mimeType.toLowerCase()) {
"application/json" ->
BodyFormatType.FORMAT_JSON
"application/xml", "text/xml", "application/dash+xml" ->
BodyFormatType.FORMAT_XML
"application/octet-stream" ->
BodyFormatType.FORMAT_BINARY
"text/html" ->
BodyFormatType.FORMAT_HTML
"text/plain" ->
BodyFormatType.FORMAT_PLAIN
"application/x-www-form-urlencoded" ->
BodyFormatType.FORMAT_FORM_ENCODED
"image/bmp", "image/png", "image/tiff", "image/jpg", "image/jpeg", "image/gif",
"image/webp", "application/svg+xml" ->
BodyFormatType.FORMAT_IMAGE
else -> null
}
}
} | apache-2.0 | ca46c49f4a18a9476245a7fd689e9d55 | 35.372549 | 102 | 0.63808 | 4.478261 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/preference/RandomizeAccountNamePreference.kt | 1 | 4841 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[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 de.vanita5.twittnuker.preference
import android.accounts.AccountManager
import android.content.Context
import android.content.res.TypedArray
import android.support.v4.util.ArraySet
import android.support.v7.preference.DialogPreference
import android.support.v7.preference.PreferenceDialogFragmentCompat
import android.support.v7.preference.PreferenceFragmentCompat
import android.support.v7.preference.PreferenceViewHolder
import android.support.v7.widget.SwitchCompat
import android.util.AttributeSet
import org.mariotaku.ktextension.Bundle
import org.mariotaku.ktextension.set
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.extension.model.getAccountKey
import de.vanita5.twittnuker.extension.model.getAccountUser
import de.vanita5.twittnuker.extension.model.renameTwidereAccount
import de.vanita5.twittnuker.model.util.AccountUtils
import de.vanita5.twittnuker.preference.iface.IDialogPreference
import de.vanita5.twittnuker.util.generateAccountName
import java.util.*
class RandomizeAccountNamePreference @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = R.attr.switchPreferenceCompatStyle,
defStyleRes: Int = 0
) : DialogPreference(context, attrs, defStyleAttr, defStyleRes), IDialogPreference {
init {
dialogTitle = title
dialogMessage = context.getString(R.string.preference_randomize_account_rename_accounts_confirm)
positiveButtonText = context.getString(android.R.string.ok)
negativeButtonText = context.getString(android.R.string.cancel)
}
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
val switchView = holder.findViewById(android.support.v7.preference.R.id.switchWidget) as SwitchCompat
switchView.isChecked = getPersistedBoolean(false)
}
override fun onGetDefaultValue(a: TypedArray, index: Int): Any {
return a.getBoolean(index, false)
}
override fun onClick() {
persistBoolean(!getPersistedBoolean(false))
notifyChanged()
super.onClick()
}
override fun displayDialog(fragment: PreferenceFragmentCompat) {
val df = RenameAccountsConfirmDialogFragment.newInstance(key, getPersistedBoolean(false))
df.setTargetFragment(fragment, 0)
df.show(fragment.fragmentManager, key)
}
class RenameAccountsConfirmDialogFragment : PreferenceDialogFragmentCompat() {
override fun onDialogClosed(positiveResult: Boolean) {
val am = AccountManager.get(context)
val enabled = arguments.getBoolean(ARG_VALUE)
if (enabled) {
val usedNames = ArraySet<String>()
AccountUtils.getAccounts(am).forEach { oldAccount ->
var newName: String
do {
newName = UUID.randomUUID().toString()
} while (usedNames.contains(newName))
am.renameTwidereAccount(oldAccount, newName)
usedNames.add(newName)
}
} else {
AccountUtils.getAccounts(am).forEach { oldAccount ->
val accountKey = oldAccount.getAccountKey(am)
val accountUser = oldAccount.getAccountUser(am)
val newName = generateAccountName(accountUser.screen_name, accountKey.host)
am.renameTwidereAccount(oldAccount, newName)
}
}
}
companion object {
const val ARG_VALUE = "value"
fun newInstance(key: String, value: Boolean): RenameAccountsConfirmDialogFragment {
val df = RenameAccountsConfirmDialogFragment()
df.arguments = Bundle {
this[ARG_KEY] = key
this[ARG_VALUE] = value
}
return df
}
}
}
} | gpl-3.0 | 2aa5919ab836926a0f3ccda21af7216f | 39.689076 | 109 | 0.689734 | 4.793069 | false | false | false | false |
stripe/stripe-android | identity/src/main/java/com/stripe/android/identity/ui/ConfirmationScreen.kt | 1 | 5255 | package com.stripe.android.identity.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTag
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.google.android.material.composethemeadapter.MdcTheme
import com.stripe.android.identity.R
import com.stripe.android.identity.networking.Resource
import com.stripe.android.identity.networking.models.VerificationPage
import com.stripe.android.uicore.text.Html
@Composable
internal fun ConfirmationScreen(
verificationPageState: Resource<VerificationPage>,
onError: (Throwable) -> Unit,
onComposeFinish: (VerificationPage) -> Unit,
onConfirmed: () -> Unit
) {
MdcTheme {
CheckVerificationPageAndCompose(
verificationPageResource = verificationPageState,
onError = onError
) {
val successPage = remember { it.success }
Column(
modifier = Modifier
.fillMaxSize()
.padding(
vertical = dimensionResource(id = R.dimen.page_vertical_margin),
horizontal = dimensionResource(id = R.dimen.page_horizontal_margin)
)
) {
Column(
modifier = Modifier
.weight(1f)
.verticalScroll(rememberScrollState())
) {
Box(
modifier = Modifier
.width(32.dp)
.height(32.dp)
.clip(RoundedCornerShape(10.dp))
.background(MaterialTheme.colors.primary),
contentAlignment = Alignment.Center
) {
Image(
painter = painterResource(id = R.drawable.clock_icon),
modifier = Modifier
.width(26.dp)
.height(26.dp),
contentDescription = stringResource(id = R.string.description_plus)
)
}
Text(
text = successPage.title,
modifier = Modifier
.fillMaxWidth()
.padding(
vertical = dimensionResource(id = R.dimen.item_vertical_margin)
)
.semantics {
testTag = confirmationTitleTag
},
fontSize = 24.sp,
fontWeight = FontWeight.Bold
)
Html(
html = successPage.body,
modifier = Modifier
.padding(bottom = dimensionResource(id = R.dimen.item_vertical_margin))
.semantics {
testTag = BODY_TAG
},
urlSpanStyle = SpanStyle(
textDecoration = TextDecoration.Underline,
color = MaterialTheme.colors.secondary
)
)
}
Button(
onClick = onConfirmed,
modifier = Modifier
.fillMaxWidth()
.semantics {
testTag = confirmationConfirmButtonTag
}
) {
Text(text = successPage.buttonText.uppercase())
}
}
LaunchedEffect(Unit) {
onComposeFinish(it)
}
}
}
}
internal const val confirmationTitleTag = "ConfirmationTitle"
internal const val confirmationConfirmButtonTag = "ConfirmButton"
| mit | 23637aef839a19ae4f1df8fc30a2f307 | 39.736434 | 99 | 0.559087 | 5.800221 | false | false | false | false |
googlearchive/android-RuntimePermissionsBasic | kotlinApp/Application/src/main/java/com/example/android/basicpermissions/MainActivity.kt | 3 | 5649 | /*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.basicpermissions
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.Button
import com.example.android.basicpermissions.camera.CameraPreviewActivity
import com.example.android.basicpermissions.util.checkSelfPermissionCompat
import com.example.android.basicpermissions.util.requestPermissionsCompat
import com.example.android.basicpermissions.util.shouldShowRequestPermissionRationaleCompat
import com.example.android.basicpermissions.util.showSnackbar
const val PERMISSION_REQUEST_CAMERA = 0
/**
* Launcher Activity that demonstrates the use of runtime permissions for Android M.
* This Activity requests permissions to access the camera
* ([android.Manifest.permission.CAMERA])
* when the 'Show Camera Preview' button is clicked to start [CameraPreviewActivity] once
* the permission has been granted.
*
* <p>First, the status of the Camera permission is checked using [ActivityCompat.checkSelfPermission]
* If it has not been granted ([PackageManager.PERMISSION_GRANTED]), it is requested by
* calling [ActivityCompat.requestPermissions]. The result of the request is
* returned to the
* [android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback], which starts
* if the permission has been granted.
*
* <p>Note that there is no need to check the API level, the support library
* already takes care of this. Similar helper methods for permissions are also available in
* ([ActivityCompat],
* [android.support.v4.content.ContextCompat] and [android.support.v4.app.Fragment]).
*/
class MainActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsResultCallback {
private lateinit var layout: View
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
layout = findViewById(R.id.main_layout)
// Register a listener for the 'Show Camera Preview' button.
findViewById<Button>(R.id.button_open_camera).setOnClickListener { showCameraPreview() }
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if (requestCode == PERMISSION_REQUEST_CAMERA) {
// Request for camera permission.
if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission has been granted. Start camera preview Activity.
layout.showSnackbar(R.string.camera_permission_granted, Snackbar.LENGTH_SHORT)
startCamera()
} else {
// Permission request was denied.
layout.showSnackbar(R.string.camera_permission_denied, Snackbar.LENGTH_SHORT)
}
}
}
private fun showCameraPreview() {
// Check if the Camera permission has been granted
if (checkSelfPermissionCompat(Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED) {
// Permission is already available, start camera preview
layout.showSnackbar(R.string.camera_permission_available, Snackbar.LENGTH_SHORT)
startCamera()
} else {
// Permission is missing and must be requested.
requestCameraPermission()
}
}
/**
* Requests the [android.Manifest.permission.CAMERA] permission.
* If an additional rationale should be displayed, the user has to launch the request from
* a SnackBar that includes additional information.
*/
private fun requestCameraPermission() {
// Permission has not been granted and must be requested.
if (shouldShowRequestPermissionRationaleCompat(Manifest.permission.CAMERA)) {
// Provide an additional rationale to the user if the permission was not granted
// and the user would benefit from additional context for the use of the permission.
// Display a SnackBar with a button to request the missing permission.
layout.showSnackbar(R.string.camera_access_required,
Snackbar.LENGTH_INDEFINITE, R.string.ok) {
requestPermissionsCompat(arrayOf(Manifest.permission.CAMERA),
PERMISSION_REQUEST_CAMERA)
}
} else {
layout.showSnackbar(R.string.camera_permission_not_available, Snackbar.LENGTH_SHORT)
// Request the permission. The result will be received in onRequestPermissionResult().
requestPermissionsCompat(arrayOf(Manifest.permission.CAMERA), PERMISSION_REQUEST_CAMERA)
}
}
private fun startCamera() {
val intent = Intent(this, CameraPreviewActivity::class.java)
startActivity(intent)
}
}
| apache-2.0 | 94ec30395dc8f233e61026b8e2bb927e | 43.132813 | 102 | 0.716056 | 4.937937 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsPath.kt | 2 | 6756 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.rust.lang.core.RsPsiPattern
import org.rust.lang.core.completion.RsCommonCompletionProvider
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.RsElementTypes.*
import org.rust.lang.core.resolve.*
import org.rust.lang.core.resolve.ref.*
import org.rust.lang.core.stubs.RsPathStub
import org.rust.lang.core.stubs.common.RsPathPsiOrStub
import org.rust.lang.core.types.ty.TyPrimitive
import org.rust.lang.doc.psi.RsDocPathLinkParent
private val RS_PATH_KINDS = tokenSetOf(IDENTIFIER, SELF, SUPER, CSELF, CRATE)
val RsPath.hasCself: Boolean get() = kind == PathKind.CSELF
/** For `Foo::bar::baz::quux` path returns `Foo` */
tailrec fun <T : RsPathPsiOrStub> T.basePath(): T {
@Suppress("UNCHECKED_CAST")
val qualifier = path as T?
return if (qualifier === null) this else qualifier.basePath()
}
/** For `Foo::bar` in `Foo::bar::baz::quux` returns `Foo::bar::baz::quux` */
tailrec fun RsPath.rootPath(): RsPath {
// Use `parent` instead of `context` because of better performance.
// Assume nobody set a context for a part of a path
val parent = parent
return if (parent is RsPath) parent.rootPath() else this
}
val RsPath.textRangeOfLastSegment: TextRange?
get() {
val referenceNameElement = referenceNameElement ?: return null
return TextRange(
referenceNameElement.startOffset, typeArgumentList?.endOffset ?: referenceNameElement.endOffset
)
}
enum class PathKind {
IDENTIFIER,
SELF,
SUPER,
CSELF,
CRATE,
MALFORMED
}
val RsPath.qualifier: RsPath?
get() {
path?.let { return it }
var ctx = context
while (ctx is RsPath) {
ctx = ctx.context
}
return (ctx as? RsUseSpeck)?.qualifier
}
val RsPath.isInsideDocLink: Boolean
get() = when (val parent = rootPath().parent) {
is RsDocPathLinkParent -> true
is RsTypeReference -> parent.ancestorStrict<RsPath>()?.isInsideDocLink ?: false
else -> false
}
fun RsPath.allowedNamespaces(isCompletion: Boolean = false, parent: PsiElement? = this.parent): Set<Namespace> = when (parent) {
is RsPath, is RsTraitRef, is RsStructLiteral, is RsPatStruct -> TYPES
is RsTypeReference -> when (parent.stubParent) {
is RsTypeArgumentList -> when {
// type A = Foo<T>
// ~ `T` can be either type or const argument
typeArgumentList == null && valueParameterList == null -> TYPES_N_VALUES
else -> TYPES
}
else -> TYPES
}
is RsUseSpeck -> when {
// use foo::bar::{self, baz};
// ~~~~~~~~
// use foo::bar::*;
// ~~~~~~~~
parent.useGroup != null || parent.isStarImport -> TYPES
// use foo::bar;
// ~~~~~~~~
else -> TYPES_N_VALUES_N_MACROS
}
is RsPathExpr -> when {
isCompletion && qualifier != null -> TYPES_N_VALUES_N_MACROS
/** unqualified macros are special cased in [RsCommonCompletionProvider.processPathVariants] */
isCompletion && qualifier == null -> TYPES_N_VALUES
else -> VALUES
}
is RsPatTupleStruct -> VALUES
is RsMacroCall -> MACROS
is RsPathCodeFragment -> parent.ns
// TODO: Use proper namespace based on disambiguator
is RsDocPathLinkParent -> TYPES_N_VALUES_N_MACROS
else -> TYPES_N_VALUES
}
val RsPath.resolveStatus: PathResolveStatus
get() {
val reference = reference ?: return PathResolveStatus.NO_REFERENCE
return if (TyPrimitive.fromPath(this) == null && reference.multiResolve().isEmpty()) {
PathResolveStatus.UNRESOLVED
} else {
PathResolveStatus.RESOLVED
}
}
enum class PathResolveStatus {
RESOLVED, UNRESOLVED, NO_REFERENCE
}
abstract class RsPathImplMixin : RsStubbedElementImpl<RsPathStub>,
RsPath {
constructor(node: ASTNode) : super(node)
constructor(stub: RsPathStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getReference(): RsPathReference? {
if (referenceName == null) return null
return when (val parent = parent) {
is RsMacroCall -> RsMacroPathReferenceImpl(this)
is RsMetaItem -> when {
RsPsiPattern.derivedTraitMetaItem.accepts(parent) -> RsDeriveTraitReferenceImpl(this)
RsPsiPattern.nonStdOuterAttributeMetaItem.accepts(parent) -> RsAttributeProcMacroReferenceImpl(this)
else -> null
}
is RsPath -> {
val rootPathParent = parent.rootPath().parent
if (rootPathParent !is RsMetaItem || RsPsiPattern.nonStdOuterAttributeMetaItem.accepts(rootPathParent)) {
RsPathReferenceImpl(this)
} else {
null
}
}
else -> RsPathReferenceImpl(this)
}
}
override val referenceNameElement: PsiElement?
get() = node.findChildByType(RS_PATH_KINDS)?.psi
override val referenceName: String?
get() {
val stub = greenStub
return if (stub != null) {
stub.referenceName
} else {
super.referenceName
}
}
override val containingMod: RsMod
get() {
// In the case of path inside vis restriction for mod item, containingMod must be the parent module:
// ```
// mod foo {
// pub(in self) mod bar {}
// //^ containingMod == `foo`
// ```
val visParent = (rootPath().parent as? RsVisRestriction)?.parent?.parent
return if (visParent is RsMod) visParent.containingMod else super<RsStubbedElementImpl>.containingMod
}
override val hasColonColon: Boolean get() = greenStub?.hasColonColon ?: (coloncolon != null)
override val kind: PathKind
get() {
val stub = greenStub
if (stub != null) return stub.kind
val child = node.findChildByType(RS_PATH_KINDS)
return when (child?.elementType) {
IDENTIFIER -> PathKind.IDENTIFIER
SELF -> PathKind.SELF
SUPER -> PathKind.SUPER
CSELF -> PathKind.CSELF
CRATE -> PathKind.CRATE
else -> PathKind.MALFORMED
}
}
}
| mit | 1a294355f64912c2b92b8589edf64f9a | 34.005181 | 128 | 0.613825 | 4.444737 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/intentions/MoveTypeConstraintToWhereClauseIntention.kt | 6 | 2532 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
class MoveTypeConstraintToWhereClauseIntention : RsElementBaseIntentionAction<RsTypeParameterList>() {
override fun getText() = "Move type constraint to where clause"
override fun getFamilyName() = text
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): RsTypeParameterList? {
val genericParams = element.ancestorStrict<RsTypeParameterList>() ?: return null
val hasTypeBounds = genericParams.typeParameterList.any { it.typeParamBounds != null }
val hasLifetimeBounds = genericParams.lifetimeParameterList.any { it.lifetimeParamBounds != null }
return if (hasTypeBounds || hasLifetimeBounds) genericParams else null
}
override fun invoke(project: Project, editor: Editor, ctx: RsTypeParameterList) {
val lifetimeBounds = ctx.lifetimeParameterList
val typeBounds = ctx.typeParameterList
val whereClause = RsPsiFactory(project).createWhereClause(lifetimeBounds, typeBounds)
val declaration = ctx.ancestorStrict<RsGenericDeclaration>() ?: return
val addedClause = declaration.addWhereClause(whereClause) ?: return
val offset = addedClause.textOffset + whereClause.textLength
editor.caretModel.moveToOffset(offset)
typeBounds.forEach { it.typeParamBounds?.delete() }
lifetimeBounds.forEach { it.lifetimeParamBounds?.delete() }
}
}
private fun RsGenericDeclaration.addWhereClause(whereClause: RsWhereClause): PsiElement? {
val existingWhereClause = this.whereClause
if (existingWhereClause != null) {
ensureTrailingComma(existingWhereClause.wherePredList)
existingWhereClause.addRangeAfter(
whereClause.wherePredList.first(),
whereClause.lastChild,
existingWhereClause.lastChild
)
return existingWhereClause
}
val anchor = when (this) {
is RsTypeAlias -> eq
is RsTraitOrImpl -> members
is RsFunction -> block
is RsStructItem -> semicolon ?: blockFields
is RsEnumItem -> enumBody
else -> error("Unhandled RustGenericDeclaration: $this")
} ?: return null
return addBefore(whereClause, anchor)
}
| mit | 169903da0a91c70226cb9ec3b97e1172 | 40.508197 | 117 | 0.723144 | 5.013861 | false | false | false | false |
androidx/androidx | work/work-multiprocess/src/androidTest/java/androidx/work/multiprocess/ListenableWorkerImplClientTest.kt | 3 | 6434 | /*
* 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.work.multiprocess
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.IBinder
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import androidx.work.impl.WorkManagerImpl
import androidx.work.impl.utils.SerialExecutorImpl
import androidx.work.impl.utils.futures.SettableFuture
import androidx.work.impl.utils.taskexecutor.TaskExecutor
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers.any
import org.mockito.ArgumentMatchers.anyInt
import org.mockito.ArgumentMatchers.anyString
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.mockito.Mockito.spy
import org.mockito.Mockito.verify
import java.util.concurrent.Executor
@RunWith(AndroidJUnit4::class)
public class ListenableWorkerImplClientTest {
private lateinit var mContext: Context
private lateinit var mWorkManager: WorkManagerImpl
private lateinit var mExecutor: Executor
private lateinit var mClient: ListenableWorkerImplClient
@Before
public fun setUp() {
if (Build.VERSION.SDK_INT <= 27) {
// Exclude <= API 27, from tests because it causes a SIGSEGV.
return
}
mContext = mock(Context::class.java)
mWorkManager = mock(WorkManagerImpl::class.java)
`when`(mContext.applicationContext).thenReturn(mContext)
mExecutor = Executor {
it.run()
}
val taskExecutor = mock(TaskExecutor::class.java)
`when`(taskExecutor.serialTaskExecutor).thenReturn(SerialExecutorImpl(mExecutor))
`when`(mWorkManager.workTaskExecutor).thenReturn(taskExecutor)
mClient = ListenableWorkerImplClient(mContext, mExecutor)
}
@Test
@MediumTest
public fun failGracefullyWhenBindFails() {
if (Build.VERSION.SDK_INT <= 27) {
// Exclude <= API 27, from tests because it causes a SIGSEGV.
return
}
`when`(
mContext.bindService(
any(Intent::class.java),
any(ServiceConnection::class.java),
anyInt()
)
).thenReturn(false)
val componentName = ComponentName("packageName", "className")
var exception: Throwable? = null
try {
mClient.getListenableWorkerImpl(componentName).get()
} catch (throwable: Throwable) {
exception = throwable
}
assertNotNull(exception)
val message = exception?.cause?.message ?: ""
assertTrue(message.contains("Unable to bind to service"))
}
@Test
@MediumTest
@Suppress("UNCHECKED_CAST")
public fun cleanUpWhenDispatcherFails() {
if (Build.VERSION.SDK_INT <= 27) {
// Exclude <= API 27, from tests because it causes a SIGSEGV.
return
}
val binder = mock(IBinder::class.java)
val remoteDispatcher =
mock(RemoteDispatcher::class.java) as RemoteDispatcher<IListenableWorkerImpl>
val remoteStub = mock(IListenableWorkerImpl::class.java)
val callback = spy(RemoteCallback())
val message = "Something bad happened"
`when`(remoteDispatcher.execute(remoteStub, callback)).thenThrow(RuntimeException(message))
`when`(remoteStub.asBinder()).thenReturn(binder)
val session = SettableFuture.create<IListenableWorkerImpl>()
session.set(remoteStub)
var exception: Throwable? = null
try {
mClient.execute(session, remoteDispatcher, callback).get()
} catch (throwable: Throwable) {
exception = throwable
}
assertNotNull(exception)
verify(callback).onFailure(message)
}
@Test
@MediumTest
@Suppress("UNCHECKED_CAST")
public fun cleanUpWhenSessionIsInvalid() {
if (Build.VERSION.SDK_INT <= 27) {
// Exclude <= API 27, from tests because it causes a SIGSEGV.
return
}
val remoteDispatcher =
mock(RemoteDispatcher::class.java) as RemoteDispatcher<IListenableWorkerImpl>
val callback = spy(RemoteCallback())
val session = SettableFuture.create<IListenableWorkerImpl>()
session.setException(RuntimeException("Something bad happened"))
var exception: Throwable? = null
try {
mClient.execute(session, remoteDispatcher, callback).get()
} catch (throwable: Throwable) {
exception = throwable
}
assertNotNull(exception)
verify(callback).onFailure(anyString())
}
@Test
@MediumTest
public fun cleanUpOnSuccessfulDispatch() {
if (Build.VERSION.SDK_INT <= 27) {
// Exclude <= API 27, from tests because it causes a SIGSEGV.
return
}
val binder = mock(IBinder::class.java)
val remoteDispatcher = RemoteDispatcher<IListenableWorkerImpl> { _, callback ->
callback.onSuccess(ByteArray(0))
}
val remoteStub = mock(IListenableWorkerImpl::class.java)
val callback = spy(RemoteCallback())
`when`(remoteStub.asBinder()).thenReturn(binder)
val session = SettableFuture.create<IListenableWorkerImpl>()
session.set(remoteStub)
var exception: Throwable? = null
try {
mClient.execute(session, remoteDispatcher, callback).get()
} catch (throwable: Throwable) {
exception = throwable
}
assertNull(exception)
verify(callback).onSuccess(any())
}
}
| apache-2.0 | 8226242e886a212375cbba424b8f5d71 | 35.146067 | 99 | 0.671278 | 4.741341 | false | true | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/ARB_vertex_attrib_binding.kt | 1 | 4219 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl.templates
import org.lwjgl.generator.*
import org.lwjgl.opengl.*
val ARB_vertex_attrib_binding = "ARBVertexAttribBinding".nativeClassGL("ARB_vertex_attrib_binding") {
documentation =
"""
Native bindings to the $registryLink extension.
OpenGL currently supports (at least) 16 vertex attributes and 16 vertex buffer bindings, with a fixed mapping between vertex attributes and vertex
buffer bindings. This extension allows the application to change the mapping between attributes and bindings, which can make it more efficient to update
vertex buffer bindings for interleaved vertex formats where many attributes share the same buffer.
This extension also separates the vertex binding update from the vertex attribute format update, which saves applications the effort of redundantly
specifying the same format state over and over.
Conceptually, this extension splits the state for generic vertex attribute arrays into:
${ul(
"""
An array of vertex buffer binding points, each of which specifies:
${ul(
"a bound buffer object",
"a starting offset for the vertex attribute data in that buffer object",
"a stride used by all attributes using that binding point, and",
"a frequency divisor used by all attributes using that binding point."
)}
""",
"""
An array of generic vertex attribute format information records, each of which specifies:
${ul(
"a reference to one of the new buffer binding points above",
"a component count and format, and a normalization flag for the attribute data, and",
"the offset of the attribute data relative to the base offset of each vertex found at the associated binding point."
)}
"""
)}
${GL43.promoted}
"""
IntConstant(
"Accepted by the {@code pname} parameter of GetVertexAttrib*v.",
"VERTEX_ATTRIB_BINDING"..0x82D4,
"VERTEX_ATTRIB_RELATIVE_OFFSET"..0x82D5
)
IntConstant(
"Accepted by the {@code target} parameter of GetBooleani_v, GetIntegeri_v, GetFloati_v, GetDoublei_v, and GetInteger64i_v.",
"VERTEX_BINDING_DIVISOR"..0x82D6,
"VERTEX_BINDING_OFFSET"..0x82D7,
"VERTEX_BINDING_STRIDE"..0x82D8,
"VERTEX_BINDING_BUFFER"..0x8F4F
)
IntConstant(
"Accepted by the {@code pname} parameter of GetIntegerv, ....",
"MAX_VERTEX_ATTRIB_RELATIVE_OFFSET"..0x82D9,
"MAX_VERTEX_ATTRIB_BINDINGS"..0x82DA
)
GL43 reuse "BindVertexBuffer"
GL43 reuse "VertexAttribFormat"
GL43 reuse "VertexAttribIFormat"
GL43 reuse "VertexAttribLFormat"
GL43 reuse "VertexAttribBinding"
GL43 reuse "VertexBindingDivisor"
val vaobj = GLuint.IN("vaobj", "the vertex array object")
var src = GL43["BindVertexBuffer"]
DependsOn("GL_EXT_direct_state_access")..void(
"VertexArrayBindVertexBufferEXT",
"DSA version of #BindVertexBuffer().",
vaobj,
src["bindingindex"],
src["buffer"],
src["offset"],
src["stride"]
)
src = GL43["VertexAttribFormat"]
DependsOn("GL_EXT_direct_state_access")..void(
"VertexArrayVertexAttribFormatEXT",
"DSA version of #VertexAttribFormat().",
vaobj,
src["attribindex"],
src["size"],
src["type"],
src["normalized"],
src["relativeoffset"]
)
src = GL43["VertexAttribIFormat"]
DependsOn("GL_EXT_direct_state_access")..void(
"VertexArrayVertexAttribIFormatEXT",
"DSA version of #VertexAttribIFormat().",
vaobj,
src["attribindex"],
src["size"],
src["type"],
src["relativeoffset"]
)
src = GL43["VertexAttribLFormat"]
DependsOn("GL_EXT_direct_state_access")..void(
"VertexArrayVertexAttribLFormatEXT",
"DSA version of #VertexAttribLFormat().",
vaobj,
src["attribindex"],
src["size"],
src["type"],
src["relativeoffset"]
)
src = GL43["VertexAttribBinding"]
DependsOn("GL_EXT_direct_state_access")..void(
"VertexArrayVertexAttribBindingEXT",
"DSA version of #VertexAttribBinding().",
vaobj,
src["attribindex"],
src["bindingindex"]
)
src = GL43["VertexBindingDivisor"]
DependsOn("GL_EXT_direct_state_access")..void(
"VertexArrayVertexBindingDivisorEXT",
"DSA version of #VertexBindingDivisor().",
vaobj,
src["bindingindex"],
src["divisor"]
)
} | bsd-3-clause | 0b9b301b27943debfd37d359d1566ed9 | 28.305556 | 154 | 0.723631 | 3.630809 | false | false | false | false |
goldmansachs/obevo | obevo-core/src/main/java/com/gs/obevo/impl/graph/GraphSorter.kt | 1 | 5164 | /**
* Copyright 2017 Goldman Sachs.
* 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.gs.obevo.impl.graph
import com.gs.obevo.util.CollectionUtil
import org.eclipse.collections.api.RichIterable
import org.eclipse.collections.api.list.ImmutableList
import org.eclipse.collections.impl.block.factory.Comparators
import org.eclipse.collections.impl.factory.Lists
import org.jgrapht.Graph
import org.jgrapht.graph.AsSubgraph
import org.jgrapht.graph.DefaultEdge
import org.jgrapht.traverse.TopologicalOrderIterator
import java.util.Comparator
/**
* Iterates through the inputs and graph to come up w/ a proper topological sorting.
*
* We expect that the graph elements should either be Comparable, or a Comparator be provided. This is to guarantee a
* consistent topological order, which is much friendlier for clients to debug and for consistency across different
* environments.
*
* (Note that on a given graph, we could have many valid topological orders, which is what we want to get consistency
* on - see https://en.wikipedia.org/wiki/Topological_sorting).
*/
class GraphSorter {
/**
* Sorts the graph to provide a consistent topological ordering. The vertices of the graph must implement [Comparable]
*
* @param graph The input graph
* @param subsetVertices The subset vertices of the graph we want to sort
*/
fun <T> sortChanges(graph: Graph<T, DefaultEdge>, subsetVertices: RichIterable<T>): ImmutableList<T> {
return sortChanges(graph, subsetVertices, null)
}
/**
* Sorts the graph to provide a consistent topological ordering.
*
* @param graph The input graph
* @param subsetVertices The subset vertices of the graph we want to sort
* @param comparator The comparator on which to order the vertices to guarantee a consistent topological ordering
*/
fun <T> sortChanges(graph: Graph<T, DefaultEdge>, subsetVertices: RichIterable<T>, comparator: Comparator<in T>?): ImmutableList<T> {
if (subsetVertices.toSet().size != subsetVertices.size()) {
throw IllegalStateException("Unexpected state - have some dupe elements here: $subsetVertices")
}
val subsetGraph = AsSubgraph(
graph, subsetVertices.toSet(), null)
// At one point, we _thought_ that the DirectedSubGraph was dropping vertices that don't have edges, so we
// manually add them back to the graph to ensure that we can still order them.
// However, that no longer seems to be the case. We add a check here just in case this comes up again.
if (subsetVertices.size() != subsetGraph.vertexSet().size) {
throw IllegalArgumentException("This case should never happen! [subsetVertices: " + subsetVertices + ", subsetGraphVertices: " + subsetGraph.vertexSet())
}
return sortChanges(subsetGraph, comparator)
}
/**
* Sorts the graph to provide a consistent topological ordering. The vertices of the graph must implement [Comparable]
*
* @param graph The input graph - all vertices in the graph will be returned in the output list
*/
fun <T> sortChanges(graph: Graph<T, DefaultEdge>): ImmutableList<T> {
return sortChanges(graph, null as Comparator<T>?)
}
/**
* Sorts the graph to provide a consistent topological ordering.
*
* @param graph The input graph - all vertices in the graph will be returned in the output list
* @param comparator The comparator on which to order the vertices to guarantee a consistent topological ordering
*/
fun <T> sortChanges(graph: Graph<T, DefaultEdge>, comparator: Comparator<in T>?): ImmutableList<T> {
if (graph.vertexSet().isEmpty()) {
return Lists.immutable.empty()
}
GraphUtil.validateNoCycles(graph)
val iterator = getTopologicalOrderIterator(graph, comparator)
return CollectionUtil.iteratorToList(iterator)
}
private fun <T> getTopologicalOrderIterator(graph: Graph<T, DefaultEdge>, comparator: Comparator<in T>?): TopologicalOrderIterator<T, DefaultEdge> {
if (comparator != null) {
return TopologicalOrderIterator(graph, comparator as Comparator<T>)
} else if (graph.vertexSet().iterator().next() is Comparable<*>) {
// ensure consistent output order
return TopologicalOrderIterator(graph, Comparators.naturalOrder<T>())
} else {
throw IllegalArgumentException("Unsortable graph elements - either need to provide a Comparator or have Comparable vertices to guarantee a consistent topological order")
}
}
}
| apache-2.0 | 2172c0ba86897dabdfd63e97c634670f | 45.107143 | 181 | 0.712045 | 4.482639 | false | false | false | false |
SimpleMobileTools/Simple-Calculator | app/src/main/kotlin/com/simplemobiletools/calculator/helpers/MyWidgetProvider.kt | 1 | 7271 | package com.simplemobiletools.calculator.helpers
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.view.View
import android.widget.RemoteViews
import com.simplemobiletools.calculator.R
import com.simplemobiletools.calculator.activities.MainActivity
import com.simplemobiletools.calculator.extensions.config
import com.simplemobiletools.commons.extensions.applyColorFilter
import com.simplemobiletools.commons.extensions.setText
class MyWidgetProvider : AppWidgetProvider(), Calculator {
companion object {
private var calc: CalculatorImpl? = null
private var storedUseCommaAsDecimalMark = false
private var decimalSeparator = DOT
private var groupingSeparator = COMMA
}
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
val config = context.config
appWidgetManager.getAppWidgetIds(getComponentName(context)).forEach {
val views = RemoteViews(context.packageName, R.layout.widget)
setupIntent(context, views, DECIMAL, R.id.btn_decimal)
setupIntent(context, views, ZERO, R.id.btn_0)
setupIntent(context, views, ONE, R.id.btn_1)
setupIntent(context, views, TWO, R.id.btn_2)
setupIntent(context, views, THREE, R.id.btn_3)
setupIntent(context, views, FOUR, R.id.btn_4)
setupIntent(context, views, FIVE, R.id.btn_5)
setupIntent(context, views, SIX, R.id.btn_6)
setupIntent(context, views, SEVEN, R.id.btn_7)
setupIntent(context, views, EIGHT, R.id.btn_8)
setupIntent(context, views, NINE, R.id.btn_9)
setupIntent(context, views, EQUALS, R.id.btn_equals)
setupIntent(context, views, PLUS, R.id.btn_plus)
setupIntent(context, views, MINUS, R.id.btn_minus)
setupIntent(context, views, MULTIPLY, R.id.btn_multiply)
setupIntent(context, views, DIVIDE, R.id.btn_divide)
setupIntent(context, views, PERCENT, R.id.btn_percent)
setupIntent(context, views, POWER, R.id.btn_power)
setupIntent(context, views, ROOT, R.id.btn_root)
setupIntent(context, views, CLEAR, R.id.btn_clear)
setupIntent(context, views, RESET, R.id.btn_reset)
setupAppOpenIntent(context, views, R.id.formula)
setupAppOpenIntent(context, views, R.id.result)
views.setViewVisibility(R.id.btn_reset, View.VISIBLE)
views.applyColorFilter(R.id.widget_background, config.widgetBgColor)
updateTextColors(views, config.widgetTextColor)
setupDecimalSeparator(views, config.useCommaAsDecimalMark)
appWidgetManager.updateAppWidget(it, views)
}
}
private fun getComponentName(context: Context) = ComponentName(context, MyWidgetProvider::class.java)
private fun setupIntent(context: Context, views: RemoteViews, action: String, id: Int) {
Intent(context, MyWidgetProvider::class.java).apply {
this.action = action
val pendingIntent = PendingIntent.getBroadcast(context, 0, this, PendingIntent.FLAG_IMMUTABLE)
views.setOnClickPendingIntent(id, pendingIntent)
}
}
private fun setupAppOpenIntent(context: Context, views: RemoteViews, id: Int) {
val intent = Intent(context, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
views.setOnClickPendingIntent(id, pendingIntent)
}
private fun updateTextColors(views: RemoteViews, color: Int) {
val viewIds = intArrayOf(
R.id.formula, R.id.result, R.id.btn_0, R.id.btn_1, R.id.btn_2, R.id.btn_3, R.id.btn_4, R.id.btn_5, R.id.btn_6,
R.id.btn_7, R.id.btn_8, R.id.btn_9, R.id.btn_percent, R.id.btn_power, R.id.btn_root, R.id.btn_clear, R.id.btn_reset, R.id.btn_divide,
R.id.btn_multiply, R.id.btn_minus, R.id.btn_plus, R.id.btn_decimal, R.id.btn_equals
)
for (i in viewIds) {
views.setTextColor(i, color)
}
}
override fun onReceive(context: Context, intent: Intent) {
when (val action = intent.action) {
DECIMAL, ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, EQUALS, CLEAR, RESET, PLUS, MINUS, MULTIPLY, DIVIDE, PERCENT, POWER, ROOT -> myAction(
action,
context
)
else -> super.onReceive(context, intent)
}
}
private fun myAction(action: String, context: Context) {
if (calc == null) {
calc = CalculatorImpl(this, context, decimalSeparator, groupingSeparator)
}
when (action) {
DECIMAL -> calc!!.numpadClicked(R.id.btn_decimal)
ZERO -> calc!!.numpadClicked(R.id.btn_0)
ONE -> calc!!.numpadClicked(R.id.btn_1)
TWO -> calc!!.numpadClicked(R.id.btn_2)
THREE -> calc!!.numpadClicked(R.id.btn_3)
FOUR -> calc!!.numpadClicked(R.id.btn_4)
FIVE -> calc!!.numpadClicked(R.id.btn_5)
SIX -> calc!!.numpadClicked(R.id.btn_6)
SEVEN -> calc!!.numpadClicked(R.id.btn_7)
EIGHT -> calc!!.numpadClicked(R.id.btn_8)
NINE -> calc!!.numpadClicked(R.id.btn_9)
EQUALS -> calc!!.handleEquals()
CLEAR -> calc!!.handleClear()
RESET -> calc!!.handleReset()
PLUS, MINUS, MULTIPLY, DIVIDE, PERCENT, POWER, ROOT -> calc!!.handleOperation(action)
}
}
override fun showNewResult(value: String, context: Context) {
val appWidgetManager = AppWidgetManager.getInstance(context) ?: return
appWidgetManager.getAppWidgetIds(getComponentName(context)).forEach {
val views = RemoteViews(context.packageName, R.layout.widget)
views.setText(R.id.result, value)
appWidgetManager.partiallyUpdateAppWidget(it, views)
}
}
override fun showNewFormula(value: String, context: Context) {
val appWidgetManager = AppWidgetManager.getInstance(context) ?: return
appWidgetManager.getAppWidgetIds(getComponentName(context)).forEach {
val views = RemoteViews(context.packageName, R.layout.widget)
views.setText(R.id.formula, value)
appWidgetManager.partiallyUpdateAppWidget(it, views)
}
}
override fun onDeleted(context: Context?, appWidgetIds: IntArray?) {
super.onDeleted(context, appWidgetIds)
calc = null
}
private fun setupDecimalSeparator(views: RemoteViews, useCommaAsDecimalMark: Boolean) {
storedUseCommaAsDecimalMark = useCommaAsDecimalMark
if (storedUseCommaAsDecimalMark) {
decimalSeparator = COMMA
groupingSeparator = DOT
} else {
decimalSeparator = DOT
groupingSeparator = COMMA
}
calc?.updateSeparators(decimalSeparator, groupingSeparator)
views.setTextViewText(R.id.btn_decimal, decimalSeparator)
}
}
| gpl-3.0 | e89463544580bf33034425b153944057 | 44.161491 | 167 | 0.65438 | 4.028255 | false | false | false | false |
inorichi/tachiyomi-extensions | multisrc/overrides/madara/pojokmanga/src/PojokManga.kt | 1 | 3631 | package eu.kanade.tachiyomi.extension.id.pojokmanga
import eu.kanade.tachiyomi.multisrc.madara.Madara
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Request
import java.text.SimpleDateFormat
import java.util.Locale
class PojokManga : Madara("Pojok Manga", "https://pojokmanga.com", "id", SimpleDateFormat("MMM dd, yyyy", Locale.US)) {
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
var url = "$baseUrl/${searchPage(page)}".toHttpUrlOrNull()!!.newBuilder()
url.addQueryParameter("s", query)
url.addQueryParameter("post_type", "wp-manga")
filters.forEach { filter ->
when (filter) {
is AuthorFilter -> {
if (filter.state.isNotBlank()) {
url.addQueryParameter("author", filter.state)
}
}
is ArtistFilter -> {
if (filter.state.isNotBlank()) {
url.addQueryParameter("artist", filter.state)
}
}
is YearFilter -> {
if (filter.state.isNotBlank()) {
url.addQueryParameter("release", filter.state)
}
}
is StatusFilter -> {
filter.state.forEach {
if (it.state) {
url.addQueryParameter("status[]", it.id)
}
}
}
is OrderByFilter -> {
if (filter.state != 0) {
url.addQueryParameter("m_orderby", filter.toUriPart())
}
}
is AdultContentFilter -> {
url.addQueryParameter("adult", filter.toUriPart())
}
is GenreConditionFilter -> {
url.addQueryParameter("op", filter.toUriPart())
}
is GenreList -> {
filter.state
.filter { it.state }
.let { list ->
if (list.isNotEmpty()) { list.forEach { genre -> url.addQueryParameter("genre[]", genre.id) } }
}
}
is ProjectFilter -> {
if (filter.toUriPart() == "project-filter-on") {
url = "$baseUrl/project/page/$page".toHttpUrlOrNull()!!.newBuilder()
}
}
}
}
return GET(url.toString(), headers)
}
override fun searchMangaSelector() = "div.c-tabs-item__content, div.page-item-detail"
protected class ProjectFilter : UriPartFilter(
"Filter Project",
arrayOf(
Pair("Show all manga", ""),
Pair("Show only project manga", "project-filter-on")
)
)
override fun getFilterList() = FilterList(
AuthorFilter(),
ArtistFilter(),
YearFilter(),
StatusFilter(getStatusList()),
OrderByFilter(),
AdultContentFilter(),
Filter.Separator(),
Filter.Header("Genres may not work for all sources"),
GenreConditionFilter(),
GenreList(getGenreList()),
Filter.Separator(),
Filter.Header("NOTE: cant be used with other filter!"),
Filter.Header("$name Project List page"),
ProjectFilter(),
)
}
| apache-2.0 | 64b9a7c82d60750a556a209828168580 | 37.221053 | 123 | 0.504544 | 5.254703 | false | false | false | false |
ohmae/DmsExplorer | mobile/src/main/java/net/mm2d/dmsexplorer/viewmodel/ControlPanelModel.kt | 1 | 8011 | /*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.dmsexplorer.viewmodel
import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
import androidx.databinding.library.baseAdapters.BR
import net.mm2d.android.util.Toaster
import net.mm2d.dmsexplorer.R
import net.mm2d.dmsexplorer.domain.model.PlayerModel
import net.mm2d.dmsexplorer.domain.model.PlayerModel.StatusListener
import net.mm2d.dmsexplorer.settings.RepeatMode
import net.mm2d.dmsexplorer.view.view.ScrubBar
import net.mm2d.dmsexplorer.view.view.ScrubBar.Accuracy
import net.mm2d.dmsexplorer.view.view.ScrubBar.ScrubBarListener
import java.util.*
/**
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
class ControlPanelModel internal constructor(
private val context: Context,
private val playerModel: PlayerModel
) : BaseObservable(), StatusListener {
private var repeatMode = RepeatMode.PLAY_ONCE
private var error: Boolean = false
var isSkipped: Boolean = false
private set
private var tracking: Boolean = false
private var onCompletionListener: (() -> Unit)? = null
private var onNextListener: (() -> Unit)? = null
private var onPreviousListener: (() -> Unit)? = null
private val handler = Handler(Looper.getMainLooper())
private val onCompletionTask = Runnable { onCompletion() }
@get:Bindable
var progressText = makeTimeText(0)
private set
@get:Bindable
var durationText = makeTimeText(0)
private set
var isPlaying: Boolean = false
private set(playing) {
if (isPlaying == playing) {
return
}
field = playing
playButtonResId = if (playing) R.drawable.ic_pause else R.drawable.ic_play
}
@get:Bindable
var isPrepared: Boolean = false
private set(prepared) {
field = prepared
notifyPropertyChanged(BR.prepared)
}
@get:Bindable
var duration: Int = 0
private set(duration) {
field = duration
notifyPropertyChanged(BR.duration)
if (duration > 0) {
isSeekable = true
}
setDurationText(duration)
isPrepared = true
}
@get:Bindable
var progress: Int = 0
private set(progress) {
if (tracking) {
return
}
setProgressText(progress)
field = progress
notifyPropertyChanged(BR.progress)
}
@get:Bindable
var isSeekable: Boolean = false
private set(seekable) {
field = seekable
notifyPropertyChanged(BR.seekable)
}
@get:Bindable
var playButtonResId = R.drawable.ic_play
private set(playButtonResId) {
field = playButtonResId
notifyPropertyChanged(BR.playButtonResId)
}
@get:Bindable
var scrubText = ""
private set(scrubText) {
field = scrubText
notifyPropertyChanged(BR.scrubText)
}
@get:Bindable
var isNextEnabled: Boolean = false
set(nextEnabled) {
field = nextEnabled
notifyPropertyChanged(BR.nextEnabled)
}
@get:Bindable
var isPreviousEnabled: Boolean = false
set(previousEnabled) {
field = previousEnabled
notifyPropertyChanged(BR.previousEnabled)
}
val seekBarListener: ScrubBarListener = object : ScrubBarListener {
override fun onProgressChanged(
seekBar: ScrubBar,
progress: Int,
fromUser: Boolean
) {
if (fromUser) {
setProgressText(progress)
}
}
override fun onStartTrackingTouch(seekBar: ScrubBar) {
tracking = true
}
override fun onStopTrackingTouch(seekBar: ScrubBar) {
tracking = false
isSkipped = true
playerModel.seekTo(seekBar.progress)
scrubText = ""
}
override fun onAccuracyChanged(
seekBar: ScrubBar,
@Accuracy accuracy: Int
) {
scrubText = getScrubText(accuracy)
}
}
init {
playerModel.setStatusListener(this)
isPreviousEnabled = true
}
internal fun terminate() {
playerModel.terminate()
}
internal fun restoreSaveProgress(position: Int) {
playerModel.restoreSaveProgress(position)
}
internal fun setOnCompletionListener(listener: (() -> Unit)?) {
onCompletionListener = listener
}
internal fun setSkipControlListener(onNext: (() -> Unit)?, onPrevious: (() -> Unit)?) {
onNextListener = onNext
onPreviousListener = onPrevious
}
fun onClickPlayPause() {
val playing = playerModel.isPlaying
if (playing) {
playerModel.pause()
} else {
playerModel.play()
}
isPlaying = !playing
}
fun onClickPlay() {
val playing = playerModel.isPlaying
if (!playing) {
playerModel.play()
isPlaying = true
}
}
fun onClickPause() {
onClickPlayPause()
}
fun setRepeatMode(mode: RepeatMode) {
repeatMode = mode
isNextEnabled = when (mode) {
RepeatMode.PLAY_ONCE,
RepeatMode.REPEAT_ONE -> false
RepeatMode.SEQUENTIAL,
RepeatMode.REPEAT_ALL -> true
}
}
fun onClickNext() {
if (!isNextEnabled) {
return
}
if (!playerModel.next()) {
onNextListener?.invoke()
}
}
fun onClickPrevious() {
if (!isPreviousEnabled) {
return
}
if (!playerModel.previous()) {
onPreviousListener?.invoke()
}
}
private fun setProgressText(progress: Int) {
progressText = makeTimeText(progress)
notifyPropertyChanged(BR.progressText)
}
private fun setDurationText(duration: Int) {
durationText = makeTimeText(duration)
notifyPropertyChanged(BR.durationText)
}
private fun getScrubText(accuracy: Int): String {
return when (accuracy) {
ScrubBar.ACCURACY_NORMAL -> context.getString(R.string.seek_bar_scrub_normal)
ScrubBar.ACCURACY_HALF -> context.getString(R.string.seek_bar_scrub_half)
ScrubBar.ACCURACY_QUARTER -> context.getString(R.string.seek_bar_scrub_quarter)
else -> ""
}
}
override fun notifyDuration(duration: Int) {
this.duration = duration
}
override fun notifyProgress(progress: Int) {
this.progress = progress
}
override fun notifyPlayingState(playing: Boolean) {
isPlaying = playing
}
override fun notifyChapterList(chapterList: List<Int>) {}
override fun onError(
what: Int,
extra: Int
): Boolean {
error = true
Toaster.show(context, R.string.toast_player_error)
handler.removeCallbacks(onCompletionTask)
handler.postDelayed(onCompletionTask, 1000)
return true
}
override fun onInfo(
what: Int,
extra: Int
): Boolean = false
override fun onCompletion() {
if (!error && repeatMode == RepeatMode.REPEAT_ONE) {
playerModel.seekTo(0)
return
}
onCompletionListener?.invoke()
}
fun hasError(): Boolean = error
companion object {
private fun makeTimeText(millisecond: Int): String = String.format(
Locale.US, "%01d:%02d:%02d",
(millisecond / 3600000).toLong(),
(millisecond / 60000 % 60).toLong(),
(millisecond / 1000 % 60).toLong()
)
}
}
| mit | f81ed7685fdd0fa5ff992d244ad4810d | 26.193878 | 91 | 0.600125 | 4.697415 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/notifications/receivers/NotificationReceiver.kt | 1 | 961 | package de.tum.`in`.tumcampusapp.component.notifications.receivers
import android.app.Notification
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationManagerCompat
import de.tum.`in`.tumcampusapp.component.notifications.NotificationScheduler
import de.tum.`in`.tumcampusapp.utils.Const
class NotificationReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (context == null || intent == null) {
return
}
val notificationId = intent.getIntExtra(Const.KEY_NOTIFICATION_ID, 0)
val notification = intent.getParcelableExtra<Notification>(Const.KEY_NOTIFICATION) ?: return
NotificationScheduler.removeActiveAlarm(context, notificationId.toLong())
NotificationManagerCompat
.from(context)
.notify(notificationId, notification)
}
} | gpl-3.0 | 9b99c8cdf351085c2a1cbd8f1244294f | 34.62963 | 100 | 0.736733 | 5.084656 | false | false | false | false |
Shockah/Godwit | core/src/pl/shockah/godwit/color/RGBColor.kt | 1 | 1303 | package pl.shockah.godwit.color
import pl.shockah.godwit.ease.ease
import kotlin.math.pow
import kotlin.math.sqrt
data class RGBColor(
val r: Float,
val g: Float,
val b: Float
) : IGColor<RGBColor>() {
constructor(lightness: Float) : this(lightness, lightness, lightness)
companion object {
val white = RGBColor(1f)
val black = RGBColor(0f)
val gray = RGBColor(0.5f)
val lightGray = RGBColor(0.75f)
val darkGray = RGBColor(0.25f)
val red = RGBColor(1f, 0f, 0f)
val green = RGBColor(0f, 1f, 0f)
val blue = RGBColor(0f, 0f, 1f)
val yellow = RGBColor(1f, 1f, 0f)
val fuchsia = RGBColor(1f, 0f, 1f)
val cyan = RGBColor(0f, 1f, 1f)
}
override val rgb = this
val hsl: HSLColor by lazy { HSLColor.from(this) }
val hsv: HSVColor by lazy { HSVColor.from(this) }
override fun getDistance(other: RGBColor): Float {
return sqrt((r - other.r).pow(2) + (g - other.g).pow(2) + (b - other.b).pow(2))
}
override fun ease(other: RGBColor, f: Float): RGBColor {
return RGBColor(
f.ease(r, other.r),
f.ease(g, other.g),
f.ease(b, other.b)
)
}
fun with(r: Float = this.r, g: Float = this.g, b: Float = this.b): RGBColor {
return RGBColor(r, g, b)
}
operator fun times(rgb: RGBColor): RGBColor {
return RGBColor(r * rgb.r, g * rgb.g, b * rgb.b)
}
} | apache-2.0 | 3c0afe4eabb9e180f3802778530e8d85 | 22.285714 | 81 | 0.653108 | 2.491396 | false | false | false | false |
google/private-compute-services | src/com/google/android/as/oss/assets/federatedcompute/NowPlayingUsagePolicy_FederatedCompute.kt | 1 | 2311 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.policies.federatedcompute
/** Data policy. */
val NowPlayingUsagePolicy_FederatedCompute =
flavoredPolicies(
name = "NowPlayingUsagePolicy_FederatedCompute",
policyType = MonitorOrImproveUserExperienceWithFederatedCompute,
) {
description =
"""
To provide usage statistics to monitor/improve Now Playing.
ALLOWED EGRESSES: FederatedCompute.
ALLOWED USAGES: Federated analytics.
"""
.trimIndent()
// The population is defined for Pixel 4+ devices per country. Most
// countries (besides the US) have a smaller population and hence the min
// round size is set to 500.
flavors(Flavor.ASI_PROD) { minRoundSize(minRoundSize = 500, minSecAggRoundSize = 0) }
consentRequiredForCollectionOrStorage(Consent.UsageAndDiagnosticsCheckbox)
presubmitReviewRequired(OwnersApprovalOnly)
checkpointMaxTtlDays(720)
target(NOW_PLAYING_RECOGNITION_EVENT_GENERATED_DTD, Duration.ofDays(14)) {
retention(StorageMedium.RAM)
retention(StorageMedium.DISK)
"timestampMillis" {
conditionalUsage("truncatedToDays", UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"countryCode" { rawUsage(UsageType.ANY) }
"shardVersion" { rawUsage(UsageType.ANY) }
"shardCountry" { rawUsage(UsageType.ANY) }
"packageName" {
conditionalUsage("top2000PackageNamesWith2000Wau", UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"recognitionResult" { rawUsage(UsageType.ANY) }
"recognitionTrigger" { rawUsage(UsageType.ANY) }
"detectedMusicScore" { rawUsage(UsageType.ANY) }
"comparisonToLastMatch" { rawUsage(UsageType.ANY) }
}
}
| apache-2.0 | 44d421450d49f469e2de4f6ec2a8154c | 36.274194 | 89 | 0.71614 | 4.311567 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/domain/step/interactor/StepIndexingInteractor.kt | 2 | 1822 | package org.stepik.android.domain.step.interactor
import android.content.Context
import com.google.firebase.appindexing.Action
import com.google.firebase.appindexing.FirebaseAppIndex
import com.google.firebase.appindexing.FirebaseUserActions
import com.google.firebase.appindexing.Indexable
import com.google.firebase.appindexing.builders.Actions
import com.google.firebase.appindexing.builders.Indexables
import org.stepic.droid.configuration.EndpointResolver
import org.stepic.droid.util.StringUtil
import org.stepik.android.model.Lesson
import org.stepik.android.model.Step
import org.stepik.android.model.Unit
import javax.inject.Inject
class StepIndexingInteractor
@Inject
constructor(
private val context: Context,
private val firebaseAppIndex: FirebaseAppIndex,
private val firebaseUserActions: FirebaseUserActions,
private val endpointResolver: EndpointResolver
) {
private var action: Action? = null
fun startIndexing(unit: Unit?, lesson: Lesson, step: Step) {
firebaseAppIndex.update(newIndexable(unit, lesson, step))
action = newAction(unit, lesson, step)
action?.let(firebaseUserActions::start)
}
fun endIndexing() {
action?.let(firebaseUserActions::end)
action = null
}
private fun newAction(unit: Unit?, lesson: Lesson, step: Step): Action =
Actions.newView(
StringUtil.getTitleForStep(context, lesson, step.position),
StringUtil.getUriForStep(endpointResolver.getBaseUrl(), lesson, unit, step)
)
private fun newIndexable(unit: Unit?, lesson: Lesson, step: Step): Indexable =
Indexables.newSimple(
StringUtil.getTitleForStep(context, lesson, step.position),
StringUtil.getUriForStep(endpointResolver.getBaseUrl(), lesson, unit, step)
)
} | apache-2.0 | a2ce3064a3195101178e80365d1bb376 | 35.46 | 87 | 0.748628 | 4.358852 | false | false | false | false |
Akjir/WiFabs | src/main/kotlin/net/kejira/wifabs/ui/fabric/FabricTilesView.kt | 1 | 5342 | /*
* Copyright (c) 2017 Stefan Neubert
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kejira.wifabs.ui.fabric
import javafx.collections.ObservableList
import javafx.event.EventHandler
import javafx.geometry.Insets
import javafx.scene.Node
import javafx.scene.control.ScrollPane
import javafx.scene.image.ImageView
import javafx.scene.input.MouseButton
import javafx.scene.input.MouseEvent
import javafx.scene.layout.Priority
import javafx.scene.layout.TilePane
import net.kejira.wifabs.*
import net.kejira.wifabs.fabric.Fabric
import net.kejira.wifabs.fabric.Fabrics
import net.kejira.wifabs.io.Images
import tornadofx.*
class FabricTilesView : View() {
override val root = ScrollPane()
private val tiles_pane: TilePane = tilepane {
padding = Insets(10.0)
vgap = 10.0
hgap = 10.0
}
val tiles = FabricTilesController(tiles_pane.children, root)
init {
with(root) {
content = tiles_pane
hgrow = Priority.ALWAYS
vgrow = Priority.ALWAYS
isFitToWidth = true
isFitToHeight = true
}
}
}
class FabricTile(fabric_id: Int, image_id: Int): ImageView() {
var fabricId = fabric_id
private set
init {
fitHeight = IMAGE_SIZE_THUMBNAIL
fitWidth = IMAGE_SIZE_THUMBNAIL
image = Images.loadThumbnail(image_id)
}
fun refresh(fabric: Fabric) {
image = Images.loadThumbnail(fabric.imageId)
}
}
class FabricTilesController(
private val tiles: ObservableList<Node>,
private val scroll_pane: ScrollPane
): Controller() {
private val fabric_view_controller: FabricViewController by inject()
private val tiles_cache = mutableMapOf<Int, FabricTile>()
private val tiles_selected = mutableListOf<FabricTile>()
private val tile_click_handler = EventHandler<MouseEvent> { event ->
if (event.button == MouseButton.PRIMARY) {
fabric_view_controller.selectFabric((event.source as FabricTile).fabricId)
}
}
private val multi_selection_mode = false
init {
subscribe<FabricDeleted> { removeTile(it.fabric) }
subscribe<SelectedFabricChanged> { selectTile(it.fabric) }
subscribe<SelectedFabricEdited> { tiles_cache[it.fabric.id]?.refresh(it.fabric) }
}
fun add(fabric: Fabric) {
if (!tiles_cache.contains(fabric.id)) {
tiles.add(createTile(fabric.id, fabric.imageId))
//TODO: minor bug: don't work if first element in new line - value stays at 1.0
if (scroll_pane.vvalueProperty().value < 1.0) {
scroll_pane.vvalueProperty().value = 1.0 // scroll down
}
}
}
private fun createTile(fabric_id: Int, image_id: Int): FabricTile {
val view = FabricTile(fabric_id, image_id)
view.onMouseClicked = tile_click_handler
tiles_cache[fabric_id] = view
return view
}
fun refresh() { tiles.setAll(tiles_cache.values) }
fun reload() {
tiles_cache.clear()
tiles_selected.clear()
Fabrics.attributes.forEach { createTile(it.id, it.imageId) }
}
private fun removeTile(fabric: Fabric) {
val tile = tiles_cache.remove(fabric.id)
if (tile != null) {
tiles_selected.remove(tile)
tiles.remove(tile)
}
}
private fun selectTile(fabric: Fabric?) { //TODO: what if not visible?
if (fabric != null) {
val view = tiles_cache[fabric.id]
if (view != null) {
if (multi_selection_mode) {
// not supported yet
} else {
if (tiles_selected.isEmpty()) {
view.effect = UI_EFFECT_SELECT
tiles_selected.add(view)
} else {
val old_view = tiles_selected.first()
if (old_view != view) {
old_view.effect = null
view .effect = UI_EFFECT_SELECT
tiles_selected.clear()
tiles_selected.add(view)
}
}
}
}
}
}
} | mit | a2279b987d7e882188ddc235fd6e74ec | 31.981481 | 91 | 0.621116 | 4.311542 | false | false | false | false |
winni67/AndroidAPS | app/src/main/java/info/nightscout/androidaps/utils/TddCalculator.kt | 3 | 2970 | package info.nightscout.androidaps.utils
import android.text.Spanned
import android.util.LongSparseArray
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.db.TDD
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import org.slf4j.LoggerFactory
object TddCalculator : TreatmentsPlugin() {
private val log = LoggerFactory.getLogger(L.DATATREATMENTS)
fun calculate(days: Long): LongSparseArray<TDD> {
val range = T.days(days + 1).msecs()
val startTime = MidnightTime.calc(DateUtil.now()) - T.days(days).msecs()
val endTime = MidnightTime.calc(DateUtil.now())
initializeData(range)
val result = LongSparseArray<TDD>()
for (t in treatmentsFromHistory) {
if (!t.isValid) continue
if (t.date < startTime || t.date > endTime) continue
val midnight = MidnightTime.calc(t.date)
val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0)
tdd.bolus += t.insulin
result.put(midnight, tdd)
}
for (t in startTime until endTime step T.mins(5).msecs()) {
val midnight = MidnightTime.calc(t)
val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0)
val tbr = getTempBasalFromHistory(t)
val profile = ProfileFunctions.getInstance().getProfile(t) ?: continue
val absoluteRate = tbr?.tempBasalConvertedToAbsolute(t, profile) ?: profile.getBasal(t)
tdd.basal += absoluteRate / 60.0 * 5.0
result.put(midnight, tdd)
}
for (i in 0 until result.size()) {
val tdd = result.valueAt(i)
tdd.total = tdd.bolus + tdd.basal
}
log.debug(result.toString())
return result
}
fun averageTDD(tdds: LongSparseArray<TDD>): TDD {
val totalTdd = TDD()
for (i in 0 until tdds.size()) {
val tdd = tdds.valueAt(i)
totalTdd.basal += tdd.basal
totalTdd.bolus += tdd.bolus
totalTdd.total += tdd.total
}
totalTdd.basal /= tdds.size().toDouble()
totalTdd.bolus /= tdds.size().toDouble()
totalTdd.total /= tdds.size().toDouble()
return totalTdd
}
fun stats(): Spanned {
val tdds = calculate(7)
val averageTdd = averageTDD(tdds)
return HtmlHelper.fromHtml(
"<b>" + MainApp.gs(R.string.tdd) + ":</b><br>" +
toText(tdds) +
"<b>" + MainApp.gs(R.string.average) + ":</b><br>" +
averageTdd.toText(tdds.size())
)
}
fun toText(tdds: LongSparseArray<TDD>): String {
var t = ""
for (i in 0 until tdds.size()) {
t += "${tdds.valueAt(i).toText()}<br>"
}
return t
}
} | agpl-3.0 | cf966d096956d94e908c6343f44cf245 | 35.679012 | 99 | 0.597643 | 3.793103 | false | false | false | false |
divinespear/jpa-schema-gradle-plugin | src/functionalTest/kotlin/io/github/divinespear/plugin/test/functional/hibernate/HibernateKotlinSpec.kt | 1 | 4236 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.github.divinespear.plugin.test.functional.hibernate
import io.github.divinespear.plugin.test.KotlinFunctionalSpec
import io.github.divinespear.plugin.test.helper.HIBERNATE_4_KOTLIN_PROPERTIES
import io.github.divinespear.plugin.test.helper.HIBERNATE_5_KOTLIN_PROPERTIES
import io.github.divinespear.plugin.test.helper.runHibernateTask
import io.kotest.core.test.TestType
import io.kotest.matchers.should
import io.kotest.matchers.string.contain
import java.io.File
class HibernateKotlinSpec : KotlinFunctionalSpec() {
private fun script(version: String, dependencySuffix: String, properties: String) =
"""
plugins {
id("io.github.divinespear.jpa-schema-generate")
}
repositories {
mavenCentral()
}
dependencies {
api("org.hibernate:hibernate-$dependencySuffix:$version")
implementation("org.springframework.boot:spring-boot:1.5.10.RELEASE")
runtimeOnly("com.h2database:h2:1.4.191")
runtimeOnly(fileTree(projectDir.relativeTo(file("lib"))) { include("*.jar") })
}
generateSchema {
vendor = "hibernate"
packageToScan = setOf("io.github.divinespear.model")
scriptAction = "drop-and-create"
properties = $properties
targets {
create("h2script") {
databaseProductName = "H2"
databaseMajorVersion = 1
databaseMinorVersion = 4
createOutputFileName = "h2-create.sql"
dropOutputFileName = "h2-drop.sql"
}
create("h2database") {
databaseAction = "drop-and-create"
scriptAction = null
jdbcDriver = "org.h2.Driver"
jdbcUrl = "jdbc:h2:${'$'}{buildDir}/generated-schema/test"
jdbcUser = "sa"
}
}
}
""".trimIndent()
init {
beforeTest {
if (it.type === TestType.Test) {
// copy example resources for test
val mainResourcesDir = testProjectDir.resolve("src/main/resources").apply {
mkdirs()
}
val resourceJavaDir = File("src/functionalTest/resources/meta/hibernate")
resourceJavaDir.copyRecursively(mainResourcesDir, true)
}
}
"task with persistence.xml" should {
"work on hibernate 5.2" {
runHibernateTask(
script(
"[5.2,5.3)",
"core",
HIBERNATE_5_KOTLIN_PROPERTIES
)
) {
it.output should contain("org.hibernate/hibernate-core/5.2.")
}
}
"work on hibernate 5.1" {
runHibernateTask(
script(
"[5.1,5.2)",
"entitymanager",
HIBERNATE_5_KOTLIN_PROPERTIES
)
) {
it.output should contain("org.hibernate/hibernate-core/5.1.")
}
}
"work on hibernate 5.0" {
runHibernateTask(
script(
"[5.0,5.1)",
"entitymanager",
HIBERNATE_5_KOTLIN_PROPERTIES
)
) {
it.output should contain("org.hibernate/hibernate-core/5.0.")
}
}
"work on hibernate 4.3" {
runHibernateTask(
script(
"[4.3,4.4)",
"entitymanager",
HIBERNATE_4_KOTLIN_PROPERTIES
)
) {
it.output should contain("org.hibernate/hibernate-core/4.3.")
}
}
}
}
}
| apache-2.0 | cea3dd59570dfddaeaaf917c7f127f9b | 30.849624 | 86 | 0.608121 | 4.165192 | false | true | false | false |
jsocle/jscole-hibernate | src/main/kotlin/com/github/jsocle/hibernate/HibernateProperties.kt | 1 | 2161 | package com.github.jsocle.hibernate
import org.hibernate.cfg.AvailableSettings
import java.util.*
import kotlin.reflect.KProperty
class HibernateProperties(connectionUrl: String? = null, hbm2ddlAuto: Hbm2ddlAuto? = null) {
val javaProperties = Properties()
var connectionUrl by StringPropertyDelegate(AvailableSettings.URL)
var hbm2ddlAuto by EnumPropertyDelegate(AvailableSettings.HBM2DDL_AUTO, Hbm2ddlAuto.values)
init {
this.connectionUrl = connectionUrl
this.hbm2ddlAuto = hbm2ddlAuto
}
operator
fun set(key: String, value: String) {
javaProperties[key] = value
}
operator fun get(key: String): String = javaProperties[key] as String
}
abstract class PropertyDelegate<T : Any>(private val key: String) {
operator fun getValue(hibernateProperties: HibernateProperties, propertyMetadata: KProperty<*>): T? {
if (hibernateProperties.javaProperties[key] == null) {
return null
}
return fromString(hibernateProperties.javaProperties[key] as String)
}
operator fun setValue(hibernateProperties: HibernateProperties, propertyMetadata: KProperty<*>, value: T?) {
if (value == null) {
hibernateProperties.javaProperties.remove(key)
} else {
hibernateProperties.javaProperties[key] = toString(value)
}
}
protected abstract fun fromString(value: String): T
protected abstract fun toString(value: T): String
}
class StringPropertyDelegate(key: String) : PropertyDelegate<String>(key) {
override fun fromString(value: String): String = value
override fun toString(value: String): String = value
}
class EnumPropertyDelegate<T : ValueEnum>(key: String, private val values: Array<T>) : PropertyDelegate<T>(key) {
override fun fromString(value: String): T = values.find { it.value == value }!!
override fun toString(value: T): String {
return value.value
}
}
interface ValueEnum {
val value: String
}
enum class Hbm2ddlAuto(override val value: String) : ValueEnum {
Update("update"), Create("create"), CreateDrop("create-drop"), Validate("validate")
}
| mit | 498ae87703761b280a30a2b3566f6e9f | 30.779412 | 113 | 0.703841 | 4.196117 | false | false | false | false |
googlearchive/android-VideoPlayer | videoplayerapp/src/main/java/com/example/android/videoplayersample/VideoActivity.kt | 1 | 5137 | /*
* Copyright 2018 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.videoplayersample
import android.app.PictureInPictureParams
import android.content.res.Configuration
import android.media.AudioManager
import android.os.Build
import android.os.Bundle
import android.support.v4.media.MediaDescriptionCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v7.app.AppCompatActivity
import android.util.Rational
import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector
import com.google.android.exoplayer2.ext.mediasession.TimelineQueueNavigator
import kotlinx.android.synthetic.main.activity_video.*
import org.jetbrains.anko.AnkoLogger
/**
* Allows playback of videos that are in a playlist, using [PlayerHolder] to load the and render
* it to the [com.google.android.exoplayer2.ui.PlayerView] to render the video output. Supports
* [MediaSessionCompat] and picture in picture as well.
*/
class VideoActivity : AppCompatActivity(), AnkoLogger {
private val mediaSession: MediaSessionCompat by lazy { createMediaSession() }
private val mediaSessionConnector: MediaSessionConnector by lazy {
createMediaSessionConnector()
}
private val playerState by lazy { PlayerState() }
private lateinit var playerHolder: PlayerHolder
// Android lifecycle hooks.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_video)
// While the user is in the app, the volume controls should adjust the music volume.
volumeControlStream = AudioManager.STREAM_MUSIC
createMediaSession()
createPlayer()
}
override fun onStart() {
super.onStart()
startPlayer()
activateMediaSession()
}
override fun onStop() {
super.onStop()
stopPlayer()
deactivateMediaSession()
}
override fun onDestroy() {
super.onDestroy()
releasePlayer()
releaseMediaSession()
}
// MediaSession related functions.
private fun createMediaSession(): MediaSessionCompat = MediaSessionCompat(this, packageName)
private fun createMediaSessionConnector(): MediaSessionConnector =
MediaSessionConnector(mediaSession).apply {
// If QueueNavigator isn't set, then mediaSessionConnector will not handle following
// MediaSession actions (and they won't show up in the minimized PIP activity):
// [ACTION_SKIP_PREVIOUS], [ACTION_SKIP_NEXT], [ACTION_SKIP_TO_QUEUE_ITEM]
setQueueNavigator(object : TimelineQueueNavigator(mediaSession) {
override fun getMediaDescription(windowIndex: Int): MediaDescriptionCompat {
return MediaCatalog[windowIndex]
}
})
}
// MediaSession related functions.
private fun activateMediaSession() {
// Note: do not pass a null to the 3rd param below, it will cause a NullPointerException.
// To pass Kotlin arguments to Java varargs, use the Kotlin spread operator `*`.
mediaSessionConnector.setPlayer(playerHolder.audioFocusPlayer, null)
mediaSession.isActive = true
}
private fun deactivateMediaSession() {
mediaSessionConnector.setPlayer(null, null)
mediaSession.isActive = false
}
private fun releaseMediaSession() {
mediaSession.release()
}
// ExoPlayer related functions.
private fun createPlayer() {
playerHolder = PlayerHolder(this, playerState, exoplayerview_activity_video)
}
private fun startPlayer() {
playerHolder.start()
}
private fun stopPlayer() {
playerHolder.stop()
}
private fun releasePlayer() {
playerHolder.release()
}
// Picture in Picture related functions.
override fun onUserLeaveHint() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
enterPictureInPictureMode(
with(PictureInPictureParams.Builder()) {
val width = 16
val height = 9
setAspectRatio(Rational(width, height))
build()
})
}
}
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean,
newConfig: Configuration?) {
exoplayerview_activity_video.useController = !isInPictureInPictureMode
}
} | apache-2.0 | bd3ac0a8d54315f5c0ca84ffcf7211a0 | 34.93007 | 100 | 0.680164 | 5.106362 | false | false | false | false |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/transactions/SyncNsTherapyEventTransaction.kt | 1 | 2116 | package info.nightscout.androidaps.database.transactions
import info.nightscout.androidaps.database.entities.TherapyEvent
/**
* Sync the TherapyEvents from NS
*/
class SyncNsTherapyEventTransaction(private val therapyEvent: TherapyEvent) :
Transaction<SyncNsTherapyEventTransaction.TransactionResult>() {
override fun run(): TransactionResult {
val result = TransactionResult()
val current: TherapyEvent? =
therapyEvent.interfaceIDs.nightscoutId?.let {
database.therapyEventDao.findByNSId(it)
}
if (current != null) {
// nsId exists, allow only invalidation
if (current.isValid && !therapyEvent.isValid) {
current.isValid = false
database.therapyEventDao.updateExistingEntry(current)
result.invalidated.add(current)
}
if (current.duration != therapyEvent.duration) {
current.duration = therapyEvent.duration
database.therapyEventDao.updateExistingEntry(current)
result.updatedDuration.add(current)
}
return result
}
// not known nsId
val existing = database.therapyEventDao.findByTimestamp(therapyEvent.type, therapyEvent.timestamp)
if (existing != null && existing.interfaceIDs.nightscoutId == null) {
// the same record, update nsId only
existing.interfaceIDs.nightscoutId = therapyEvent.interfaceIDs.nightscoutId
existing.isValid = therapyEvent.isValid
database.therapyEventDao.updateExistingEntry(existing)
result.updatedNsId.add(existing)
} else {
database.therapyEventDao.insertNewEntry(therapyEvent)
result.inserted.add(therapyEvent)
}
return result
}
class TransactionResult {
val updatedNsId = mutableListOf<TherapyEvent>()
val updatedDuration = mutableListOf<TherapyEvent>()
val inserted = mutableListOf<TherapyEvent>()
val invalidated = mutableListOf<TherapyEvent>()
}
} | agpl-3.0 | b52896b53fcf664e1e9687c427868dde | 36.140351 | 106 | 0.651701 | 5.657754 | false | false | false | false |
hurricup/intellij-community | platform/configuration-store-impl/src/ProjectStoreImpl.kt | 1 | 15017 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.ide.highlighter.WorkspaceFileType
import com.intellij.notification.Notifications
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeAndWaitIfNeed
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.*
import com.intellij.openapi.components.StateStorage.SaveSession
import com.intellij.openapi.components.ex.ComponentManagerEx
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.components.impl.stores.IProjectStore
import com.intellij.openapi.components.impl.stores.StoreUtil
import com.intellij.openapi.diagnostic.catchAndLog
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.impl.ProjectImpl
import com.intellij.openapi.project.impl.ProjectManagerImpl.UnableToSaveProjectNotification
import com.intellij.openapi.project.impl.ProjectStoreClassProvider
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.ReadonlyStatusHandler
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.*
import com.intellij.util.containers.forEachGuaranteed
import com.intellij.util.containers.isNullOrEmpty
import com.intellij.util.lang.CompoundRuntimeException
import org.jdom.Element
import java.io.File
import java.io.IOException
import java.nio.file.Path
import java.nio.file.Paths
const val PROJECT_FILE = "\$PROJECT_FILE$"
const val PROJECT_CONFIG_DIR = "\$PROJECT_CONFIG_DIR$"
val IProjectStore.nameFile: Path
get() = Paths.get(projectBasePath, Project.DIRECTORY_STORE_FOLDER, ProjectImpl.NAME_FILE)
internal val PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, false)
internal val DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, true)
abstract class ProjectStoreBase(override final val project: ProjectImpl) : ComponentStoreImpl(), IProjectStore {
// protected setter used in upsource
// Zelix KlassMaster - ERROR: Could not find method 'getScheme()'
var scheme = StorageScheme.DEFAULT
override final var loadPolicy = StateLoadPolicy.LOAD
override final fun isOptimiseTestLoadSpeed() = loadPolicy != StateLoadPolicy.LOAD
override final fun getStorageScheme() = scheme
override abstract val storageManager: StateStorageManagerImpl
protected val isDirectoryBased: Boolean
get() = scheme == StorageScheme.DIRECTORY_BASED
override final fun setOptimiseTestLoadSpeed(value: Boolean) {
// we don't load default state in tests as app store does because
// 1) we should not do it
// 2) it was so before, so, we preserve old behavior (otherwise RunManager will load template run configurations)
loadPolicy = if (value) StateLoadPolicy.NOT_LOAD else StateLoadPolicy.LOAD
}
override fun getProjectFilePath() = storageManager.expandMacro(PROJECT_FILE)
override final fun getWorkspaceFilePath() = storageManager.expandMacro(StoragePathMacros.WORKSPACE_FILE)
override final fun clearStorages() {
storageManager.clearStorages()
}
override final fun loadProjectFromTemplate(defaultProject: Project) {
defaultProject.save()
val element = (defaultProject.stateStore as DefaultProjectStoreImpl).getStateCopy() ?: return
LOG.catchAndLog {
removeWorkspaceComponentConfiguration(defaultProject, element)
}
(storageManager.getOrCreateStorage(PROJECT_FILE) as XmlElementStorage).setDefaultState(element)
}
override final fun getProjectBasePath(): String {
val path = PathUtilRt.getParentPath(projectFilePath)
return if (scheme == StorageScheme.DEFAULT) path else PathUtilRt.getParentPath(path)
}
// used in upsource
protected fun setPath(filePath: String, refreshVfs: Boolean, useOldWorkspaceContentIfExists: Boolean) {
val storageManager = storageManager
val fs = LocalFileSystem.getInstance()
if (FileUtilRt.extensionEquals(filePath, ProjectFileType.DEFAULT_EXTENSION)) {
scheme = StorageScheme.DEFAULT
storageManager.addMacro(PROJECT_FILE, filePath)
val workspacePath = composeWsPath(filePath)
storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, workspacePath)
if (refreshVfs) {
invokeAndWaitIfNeed {
VfsUtil.markDirtyAndRefresh(false, true, false, fs.refreshAndFindFileByPath(filePath), fs.refreshAndFindFileByPath(workspacePath))
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
// load state only if there are existing files
isOptimiseTestLoadSpeed = !File(filePath).exists()
}
}
else {
scheme = StorageScheme.DIRECTORY_BASED
val file = File(filePath)
// if useOldWorkspaceContentIfExists false, so, file path is expected to be correct (we must avoid file io operations)
val isDir = !useOldWorkspaceContentIfExists || file.isDirectory
val configDir = "${(if (isDir) filePath else PathUtilRt.getParentPath(filePath))}/${Project.DIRECTORY_STORE_FOLDER}"
storageManager.addMacro(PROJECT_CONFIG_DIR, configDir)
storageManager.addMacro(PROJECT_FILE, "$configDir/misc.xml")
storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, "$configDir/workspace.xml")
if (!isDir) {
val workspace = File(workspaceFilePath)
if (!workspace.exists()) {
useOldWorkspaceContent(filePath, workspace)
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
// load state only if there are existing files
isOptimiseTestLoadSpeed = !file.exists()
}
if (refreshVfs) {
invokeAndWaitIfNeed { VfsUtil.markDirtyAndRefresh(false, true, true, fs.refreshAndFindFileByPath(configDir)) }
}
}
}
override fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): Array<out Storage> {
val storages = stateSpec.storages
if (storages.isEmpty()) {
return arrayOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
if (isDirectoryBased) {
var result: MutableList<Storage>? = null
for (storage in storages) {
@Suppress("DEPRECATION")
if (storage.path != PROJECT_FILE) {
if (result == null) {
result = SmartList()
}
result.add(storage)
}
}
if (result.isNullOrEmpty()) {
return arrayOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
else {
result!!.sortWith(deprecatedComparator)
// if we create project from default, component state written not to own storage file, but to project file,
// we don't have time to fix it properly, so, ancient hack restored
result.add(DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION)
return result.toTypedArray()
}
}
else {
var result: MutableList<Storage>? = null
// FlexIdeProjectLevelCompilerOptionsHolder, FlexProjectLevelCompilerOptionsHolderImpl and CustomBeanRegistry
var hasOnlyDeprecatedStorages = true
for (storage in storages) {
@Suppress("DEPRECATION")
if (storage.path == PROJECT_FILE || storage.path == StoragePathMacros.WORKSPACE_FILE) {
if (result == null) {
result = SmartList()
}
result.add(storage)
if (!storage.deprecated) {
hasOnlyDeprecatedStorages = false
}
}
}
if (result.isNullOrEmpty()) {
return arrayOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
else {
if (hasOnlyDeprecatedStorages) {
result!!.add(PROJECT_FILE_STORAGE_ANNOTATION)
}
result!!.sortWith(deprecatedComparator)
return result.toTypedArray()
}
}
}
}
private open class ProjectStoreImpl(project: ProjectImpl, private val pathMacroManager: PathMacroManager) : ProjectStoreBase(project) {
private var lastSavedProjectName: String? = null
init {
assert(!project.isDefault)
}
override final fun getPathMacroManagerForDefaults() = pathMacroManager
override val storageManager = ProjectStateStorageManager(pathMacroManager.createTrackingSubstitutor(), project)
override fun setPath(filePath: String) {
setPath(filePath, true, true)
}
override fun getProjectName(): String {
if (isDirectoryBased) {
val baseDir = projectBasePath
val nameFile = nameFile
if (nameFile.exists()) {
try {
nameFile.inputStream().reader().useLines() { it.firstOrNull { !it.isEmpty() }?.trim() }?.let {
lastSavedProjectName = it
return it
}
}
catch (ignored: IOException) {
}
}
return PathUtilRt.getFileName(baseDir).replace(":", "")
}
else {
return PathUtilRt.getFileName(projectFilePath).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION)
}
}
private fun saveProjectName() {
if (!isDirectoryBased) {
return
}
val currentProjectName = project.name
if (lastSavedProjectName == currentProjectName) {
return
}
lastSavedProjectName = currentProjectName
val basePath = projectBasePath
if (currentProjectName == PathUtilRt.getFileName(basePath)) {
// name equals to base path name - just remove name
nameFile.delete()
}
else {
if (Paths.get(basePath).isDirectory()) {
nameFile.write(currentProjectName.toByteArray())
}
}
}
override fun doSave(saveSessions: List<SaveSession>, readonlyFiles: MutableList<Pair<SaveSession, VirtualFile>>, prevErrors: MutableList<Throwable>?): MutableList<Throwable>? {
try {
saveProjectName()
}
catch (e: Throwable) {
LOG.error("Unable to store project name", e)
}
var errors = prevErrors
beforeSave(readonlyFiles)
errors = super.doSave(saveSessions, readonlyFiles, errors)
val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
if (readonlyFiles.isEmpty()) {
for (notification in notifications) {
notification.expire()
}
return errors
}
if (!notifications.isEmpty()) {
throw IComponentStore.SaveCancelledException()
}
val status = runReadAction { ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(*getFilesList(readonlyFiles)) }
if (status.hasReadonlyFiles()) {
dropUnableToSaveProjectNotification(project, status.readonlyFiles)
throw IComponentStore.SaveCancelledException()
}
val oldList = readonlyFiles.toTypedArray()
readonlyFiles.clear()
for (entry in oldList) {
errors = executeSave(entry.first, readonlyFiles, errors)
}
CompoundRuntimeException.throwIfNotEmpty(errors)
if (!readonlyFiles.isEmpty()) {
dropUnableToSaveProjectNotification(project, getFilesList(readonlyFiles))
throw IComponentStore.SaveCancelledException()
}
return errors
}
protected open fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) {
}
}
private fun dropUnableToSaveProjectNotification(project: Project, readOnlyFiles: Array<VirtualFile>) {
val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
if (notifications.isEmpty()) {
Notifications.Bus.notify(UnableToSaveProjectNotification(project, readOnlyFiles), project)
}
else {
notifications[0].myFiles = readOnlyFiles
}
}
private fun getFilesList(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) = Array(readonlyFiles.size) { readonlyFiles[it].second }
private class ProjectWithModulesStoreImpl(project: ProjectImpl, pathMacroManager: PathMacroManager) : ProjectStoreImpl(project, pathMacroManager) {
override fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) {
super.beforeSave(readonlyFiles)
for (module in (ModuleManager.getInstance(project)?.modules ?: Module.EMPTY_ARRAY)) {
module.stateStore.save(readonlyFiles)
}
}
}
// used in upsource
class PlatformLangProjectStoreClassProvider : ProjectStoreClassProvider {
override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> {
return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectWithModulesStoreImpl::class.java
}
}
private class PlatformProjectStoreClassProvider : ProjectStoreClassProvider {
override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> {
return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectStoreImpl::class.java
}
}
private fun composeWsPath(filePath: String) = "${FileUtilRt.getNameWithoutExtension(filePath)}${WorkspaceFileType.DOT_DEFAULT_EXTENSION}"
private fun useOldWorkspaceContent(filePath: String, ws: File) {
val oldWs = File(composeWsPath(filePath))
if (!oldWs.exists()) {
return
}
try {
FileUtil.copyContent(oldWs, ws)
}
catch (e: IOException) {
LOG.error(e)
}
}
// public only to test
fun removeWorkspaceComponentConfiguration(defaultProject: Project, element: Element) {
val componentElements = element.getChildren("component")
if (componentElements.isEmpty()) {
return
}
val projectComponents = (defaultProject as ComponentManagerEx).getComponentInstancesOfType(PersistentStateComponent::class.java)
projectComponents.forEachGuaranteed {
val stateAnnotation = StoreUtil.getStateSpec(it.javaClass)
if (stateAnnotation == null || stateAnnotation.name.isNullOrEmpty()) {
return@forEachGuaranteed
}
val storage = stateAnnotation.storages.sortByDeprecated().firstOrNull() ?: return@forEachGuaranteed
if (storage.path != StoragePathMacros.WORKSPACE_FILE) {
return@forEachGuaranteed
}
val iterator = componentElements.iterator()
for (componentElement in iterator) {
if (componentElement.getAttributeValue("name") == stateAnnotation.name) {
iterator.remove()
break
}
}
}
return
} | apache-2.0 | 3d84f7557a52535aaa1ec8a65880168c | 35.451456 | 178 | 0.734434 | 5.172925 | false | false | false | false |
square/wire | wire-library/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/RuntimeEnumAdapter.kt | 1 | 1850 | /*
* Copyright 2013 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire
import com.squareup.wire.internal.identityOrNull
import java.lang.reflect.Method
/**
* Converts values of an enum to and from integers using reflection.
*/
class RuntimeEnumAdapter<E : WireEnum> internal constructor(
private val javaType: Class<E>,
syntax: Syntax
) : EnumAdapter<E>(javaType.kotlin, syntax, javaType.identityOrNull) {
// Obsolete; for Java classes generated before syntax were added.
constructor(javaType: Class<E>) : this(javaType, Syntax.PROTO_2)
private var fromValueMethod: Method? = null // Lazy to avoid reflection during class loading.
private fun getFromValueMethod(): Method {
return fromValueMethod ?: javaType.getMethod("fromValue", Int::class.javaPrimitiveType).also {
fromValueMethod = it
}
}
override fun fromValue(value: Int): E? = getFromValueMethod().invoke(null, value) as E
override fun equals(other: Any?) = other is RuntimeEnumAdapter<*> && other.type == type
override fun hashCode() = type.hashCode()
companion object {
@JvmStatic fun <E : WireEnum> create(
enumType: Class<E>
): RuntimeEnumAdapter<E> {
val defaultAdapter = get(enumType as Class<*>)
return RuntimeEnumAdapter(enumType, defaultAdapter.syntax)
}
}
}
| apache-2.0 | 35b3e71af637c261473b0b16ea964ef8 | 33.90566 | 98 | 0.728649 | 4.223744 | false | false | false | false |
k9mail/k-9 | app/ui/legacy/src/main/java/com/fsck/k9/ui/account/AccountImageModelLoader.kt | 2 | 3359 | package com.fsck.k9.ui.account
import android.graphics.Bitmap
import androidx.core.graphics.drawable.toBitmap
import com.bumptech.glide.Priority
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.Key
import com.bumptech.glide.load.Options
import com.bumptech.glide.load.data.DataFetcher
import com.bumptech.glide.load.model.ModelLoader
import com.bumptech.glide.load.model.ModelLoaderFactory
import com.bumptech.glide.load.model.MultiModelLoaderFactory
import com.fsck.k9.contacts.ContactPhotoLoader
import java.security.MessageDigest
/**
* A custom [ModelLoader] so we can use [AccountImageDataFetcher] to load the account image.
*/
internal class AccountImageModelLoader(
private val contactPhotoLoader: ContactPhotoLoader,
private val accountFallbackImageProvider: AccountFallbackImageProvider,
) : ModelLoader<AccountImage, Bitmap> {
override fun buildLoadData(
accountImage: AccountImage,
width: Int,
height: Int,
options: Options
): ModelLoader.LoadData<Bitmap> {
val dataFetcher = AccountImageDataFetcher(
contactPhotoLoader,
accountFallbackImageProvider,
accountImage
)
return ModelLoader.LoadData(accountImage, dataFetcher)
}
override fun handles(model: AccountImage) = true
}
data class AccountImage(val email: String, val color: Int) : Key {
override fun updateDiskCacheKey(messageDigest: MessageDigest) {
messageDigest.update(toString().toByteArray(Key.CHARSET))
}
}
/**
* Load an account image.
*
* Uses [ContactPhotoLoader] to try to load the user's contact photo (using the account's email address). If there's no
* such contact or it doesn't have a picture use the fallback image provided by [AccountFallbackImageProvider].
*
* We're not using Glide's own fallback mechanism because negative responses aren't cached and the next time the
* account image is requested another attempt will be made to load the contact photo.
*/
internal class AccountImageDataFetcher(
private val contactPhotoLoader: ContactPhotoLoader,
private val accountFallbackImageProvider: AccountFallbackImageProvider,
private val accountImage: AccountImage
) : DataFetcher<Bitmap> {
override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in Bitmap>) {
val bitmap = loadAccountImage() ?: createFallbackBitmap()
callback.onDataReady(bitmap)
}
private fun loadAccountImage(): Bitmap? {
return contactPhotoLoader.loadContactPhoto(accountImage.email)
}
private fun createFallbackBitmap(): Bitmap {
return accountFallbackImageProvider.getDrawable(accountImage.color).toBitmap()
}
override fun getDataClass() = Bitmap::class.java
override fun getDataSource() = DataSource.LOCAL
override fun cleanup() = Unit
override fun cancel() = Unit
}
internal class AccountImageModelLoaderFactory(
private val contactPhotoLoader: ContactPhotoLoader,
private val accountFallbackImageProvider: AccountFallbackImageProvider
) : ModelLoaderFactory<AccountImage, Bitmap> {
override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<AccountImage, Bitmap> {
return AccountImageModelLoader(contactPhotoLoader, accountFallbackImageProvider)
}
override fun teardown() = Unit
}
| apache-2.0 | 082f6c39d2c6e622f8af9a15f20d92b3 | 35.912088 | 119 | 0.759452 | 4.614011 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/interpret/test/TestInterpret3.kt | 1 | 3274 | package com.bajdcc.LALR1.interpret.test
import com.bajdcc.LALR1.grammar.Grammar
import com.bajdcc.LALR1.grammar.runtime.RuntimeCodePage
import com.bajdcc.LALR1.grammar.runtime.RuntimeException
import com.bajdcc.LALR1.interpret.Interpreter
import com.bajdcc.LALR1.syntax.handler.SyntaxException
import com.bajdcc.util.lexer.error.RegexException
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
object TestInterpret3 {
@JvmStatic
fun main(args: Array<String>) {
try {
val codes = arrayOf("import \"sys.base\";\n"
+ "var a = true;\n"
+ "if (a) {call g_print(\"ok\");}\n"
+ "else {call g_print(\"failed\");}", "import \"sys.base\";\n"
+ "call g_print(\n"
+ " call (func~(a,b,c) -> call a(b,c))(\"g_max\",5,6));\n", "import \"sys.base\";\n"
+ "var t = 0;\n"
+ "for (var i = 0; i < 10; i++) {\n"
+ " if (i % 2 == 0) {\n"
+ " continue;\n"
+ " }\n"
+ " let t = t + i;\n"
+ "}\n"
+ "call g_print(t);\n", "import \"sys.base\";\n"
+ "var enumerator = func ~(f, t, v) {\n"
+ " for (var i = f; i < t; i++) {\n"
+ " if (i % 2 == 0) {\n"
+ " continue;\n"
+ " }\n"
+ " call v(i);\n"
+ " }\n"
+ "};\n"
+ "var sum = 0;\n"
+ "var set = func ~(v) {\n"
+ " let sum = sum + v;\n"
+ "};\n"
+ "call enumerator(0, 10, set);\n"
+ "call g_print(sum);\n", "import \"sys.base\";" +
"var a=func~(){var f=func~()->call g_print(\"af\");call f();};" +
"var b=func~(){var f=func~()->call g_print(\"bf\");call f();};" +
"call a();call b();")
val interpreter = Interpreter()
val grammar = Grammar(codes[codes.size - 1])
println(grammar.toString())
val page = grammar.codePage
println(page.toString())
val baos = ByteArrayOutputStream()
RuntimeCodePage.exportFromStream(page, baos)
val bais = ByteArrayInputStream(baos.toByteArray())
interpreter.run("test_1", bais)
} catch (e: RegexException) {
System.err.println()
System.err.println(e.position.toString() + "," + e.message)
e.printStackTrace()
} catch (e: SyntaxException) {
System.err.println()
System.err.println(e.position.toString() + "," + e.message + " "
+ e.info)
e.printStackTrace()
} catch (e: RuntimeException) {
System.err.println()
System.err.println(e.position.toString() + ": " + e.info)
e.printStackTrace()
} catch (e: Exception) {
System.err.println()
System.err.println(e.message)
e.printStackTrace()
}
}
}
| mit | 3059a8e1a96186056a7e97ea20b19b2f | 39.925 | 107 | 0.441356 | 3.978129 | false | false | false | false |
mdaniel/intellij-community | plugins/ide-features-trainer/src/training/ui/FeaturesTrainerSettingsPanel.kt | 3 | 2421 | // 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.ui
import com.intellij.ide.util.PropertiesComponent
import com.intellij.lang.Language
import com.intellij.openapi.options.BoundConfigurable
import com.intellij.openapi.ui.DialogPanel
import com.intellij.ui.dsl.builder.bindItem
import com.intellij.ui.dsl.builder.bindSelected
import com.intellij.ui.dsl.builder.panel
import training.lang.LangManager
import training.learn.CourseManager
import training.learn.LearnBundle
import training.statistic.StatisticBase
import training.util.SHOW_NEW_LESSONS_NOTIFICATION
import training.util.getActionById
import training.util.resetPrimaryLanguage
private class FeaturesTrainerSettingsPanel : BoundConfigurable(LearnBundle.message("learn.options.panel.name"), null) {
override fun createPanel(): DialogPanel = panel {
val languagesExtensions = LangManager.getInstance().supportedLanguagesExtensions.sortedBy { it.language }
if (languagesExtensions.isNotEmpty()) {
row(LearnBundle.message("learn.option.main.language")) {
val options = languagesExtensions.mapNotNull { Language.findLanguageByID(it.language) }
.map { LanguageOption(it) }
comboBox(options)
.bindItem({
val languageName = LangManager.getInstance().state.languageName
options.find { it.id == languageName } ?: options[0]
}, { language -> resetPrimaryLanguage(languagesExtensions.first { it.language == language?.id }.instance) })
}
}
row {
button(LearnBundle.message("learn.option.reset.progress"), getActionById("ResetLearningProgressAction"), "settings")
}
row {
checkBox(LearnBundle.message("settings.checkbox.show.notifications.new.lessons"))
.bindSelected({ PropertiesComponent.getInstance().getBoolean(SHOW_NEW_LESSONS_NOTIFICATION, true) },
{
StatisticBase.logShowNewLessonsNotificationState(-1, CourseManager.instance.previousOpenedVersion, it)
PropertiesComponent.getInstance().setValue(SHOW_NEW_LESSONS_NOTIFICATION, it, true)
})
}
}
private data class LanguageOption(val language: Language) {
override fun toString(): String = language.displayName
val id get() = language.id
}
}
| apache-2.0 | 99239847f88e0dcd6098e4407d32fe5f | 47.42 | 140 | 0.721603 | 4.747059 | false | false | false | false |
WhisperSystems/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/conversation/ConversationUpdateTick.kt | 4 | 1204 | package org.thoughtcrime.securesms.conversation
import android.os.Handler
import android.os.Looper
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import java.util.concurrent.TimeUnit
/**
* Lifecycle-aware class which will call onTick every 1 minute.
* Used to ensure that conversation timestamps are updated appropriately.
*/
class ConversationUpdateTick(
private val onTickListener: OnTickListener
) : DefaultLifecycleObserver {
private val handler = Handler(Looper.getMainLooper())
private var isResumed = false
override fun onResume(owner: LifecycleOwner) {
isResumed = true
handler.removeCallbacksAndMessages(null)
onTick()
}
override fun onPause(owner: LifecycleOwner) {
isResumed = false
handler.removeCallbacksAndMessages(null)
}
private fun onTick() {
if (isResumed) {
onTickListener.onTick()
handler.removeCallbacksAndMessages(null)
handler.postDelayed(this::onTick, TIMEOUT)
}
}
interface OnTickListener {
fun onTick()
}
companion object {
@VisibleForTesting
val TIMEOUT = TimeUnit.MINUTES.toMillis(1)
}
}
| gpl-3.0 | 19eb331e1ef09f684200d8c7f646f4a7 | 22.607843 | 73 | 0.754983 | 4.894309 | false | false | false | false |
InsideZhou/Instep | dao/src/main/kotlin/instep/dao/sql/impl/DefaultConnectionProvider.kt | 1 | 3724 | package instep.dao.sql.impl
import instep.InstepLogger
import instep.dao.sql.*
import javax.sql.DataSource
import java.sql.Connection as JdbcConnection
class DefaultConnectionProvider(private val ds: DataSource, override val dialect: Dialect) : ConnectionProvider {
companion object {
private val transactionContextThreadLocal = ThreadLocal<DefaultTransactionContext>()
}
override val transactionRunner: TransactionRunner
init {
transactionRunner = DefaultTransactionRunner(this)
}
override fun getConnection(): JdbcConnection {
transactionContextThreadLocal.get()?.let {
return@getConnection it.connection
}
return Connection(ds.connection)
}
private class Connection(private val conn: JdbcConnection) : JdbcConnection by conn {
override fun rollback() {
transactionContextThreadLocal.get()?.run {
abort()
}
conn.rollback()
}
override fun commit() {
transactionContextThreadLocal.get()?.run {
return@commit
}
conn.commit()
}
override fun close() {
transactionContextThreadLocal.get()?.run {
return@close
}
conn.close()
}
}
private class DefaultTransactionRunner(private val connectionProvider: ConnectionProvider) : TransactionRunner {
private val logger = InstepLogger.getLogger(DefaultTransactionRunner::class.java)
override fun <R> with(level: Int?, action: TransactionContext.() -> R): R {
var transactionContext = transactionContextThreadLocal.get()
if (null == transactionContext) {
val conn = connectionProvider.getConnection()
if (null != level) {
conn.transactionIsolation = level
}
conn.autoCommit = false
transactionContext = DefaultTransactionContext(conn)
}
else {
if (null != level && level < transactionContext.connection.transactionIsolation) {
logger.message("nested transaction isolation level is lesser than outer.")
.context("nested", level)
.context("outer", transactionContext.connection.transactionIsolation)
.warn()
}
transactionContext.depth += 1
}
transactionContextThreadLocal.set(transactionContext)
val conn = transactionContext.connection
val sp = conn.setSavepoint()
var rolledback = true
try {
val result = action(transactionContext)
conn.releaseSavepoint(sp)
rolledback = false
return result
} catch (e: TransactionAbortException) {
conn.rollback(sp)
if (null == e.cause) {
@Suppress("UNCHECKED_CAST")
return null as R
}
else {
throw e
}
} catch (e: Exception) {
conn.rollback(sp)
throw TransactionAbortException(e)
}
finally {
if (transactionContext.depth > 0) {
transactionContext.depth -= 1
}
else {
transactionContextThreadLocal.set(null)
if (!rolledback) {
conn.commit()
}
conn.close()
}
}
}
}
} | bsd-2-clause | d46f98fc239a3f0535427523c0bcb3de | 30.302521 | 116 | 0.536251 | 6.055285 | false | false | false | false |
androidstarters/androidstarters.com | templates/buffer-clean-kotlin/cache/src/main/java/org/buffer/android/boilerplate/cache/BufferooCacheImpl.kt | 1 | 4439 | package <%= appPackage %>.cache
import android.database.sqlite.SQLiteDatabase
import io.reactivex.Completable
import io.reactivex.Single
import <%= appPackage %>.cache.db.Db
import <%= appPackage %>.cache.db.DbOpenHelper
import <%= appPackage %>.cache.db.constants.BufferooConstants
import <%= appPackage %>.cache.db.mapper.BufferooMapper
import <%= appPackage %>.cache.mapper.BufferooEntityMapper
import <%= appPackage %>.cache.model.CachedBufferoo
import <%= appPackage %>.data.model.BufferooEntity
import <%= appPackage %>.data.repository.BufferooCache
import javax.inject.Inject
/**
* Cached implementation for retrieving and saving Bufferoo instances. This class implements the
* [BufferooCache] from the Data layer as it is that layers responsibility for defining the
* operations in which data store implementation layers can carry out.
*/
class BufferooCacheImpl @Inject constructor(dbOpenHelper: DbOpenHelper,
private val entityMapper: BufferooEntityMapper,
private val mapper: BufferooMapper,
private val preferencesHelper: PreferencesHelper):
BufferooCache {
private val EXPIRATION_TIME = (60 * 10 * 1000).toLong()
private var database: SQLiteDatabase = dbOpenHelper.writableDatabase
/**
* Retrieve an instance from the database, used for tests
*/
internal fun getDatabase(): SQLiteDatabase {
return database
}
/**
* Remove all the data from all the tables in the database.
*/
override fun clearBufferoos(): Completable {
return Completable.defer {
database.beginTransaction()
try {
database.delete(Db.BufferooTable.TABLE_NAME, null, null)
database.setTransactionSuccessful()
} finally {
database.endTransaction()
}
Completable.complete()
}
}
/**
* Save the given list of [BufferooEntity] instances to the database.
*/
override fun saveBufferoos(bufferoos: List<BufferooEntity>): Completable {
return Completable.defer {
database.beginTransaction()
try {
bufferoos.forEach {
saveBufferoo(entityMapper.mapToCached(it))
}
database.setTransactionSuccessful()
} finally {
database.endTransaction()
}
Completable.complete()
}
}
/**
* Retrieve a list of [BufferooEntity] instances from the database.
*/
override fun getBufferoos(): Single<List<BufferooEntity>> {
return Single.defer<List<BufferooEntity>> {
val updatesCursor = database.rawQuery(BufferooConstants.QUERY_GET_ALL_BUFFEROOS, null)
val bufferoos = mutableListOf<BufferooEntity>()
while (updatesCursor.moveToNext()) {
val cachedBufferoo = mapper.parseCursor(updatesCursor)
bufferoos.add(entityMapper.mapFromCached(cachedBufferoo))
}
updatesCursor.close()
Single.just<List<BufferooEntity>>(bufferoos)
}
}
/**
* Helper method for saving a [CachedBufferoo] instance to the database.
*/
private fun saveBufferoo(cachedBufferoo: CachedBufferoo) {
database.insert(Db.BufferooTable.TABLE_NAME, null, mapper.toContentValues(cachedBufferoo))
}
/**
* Checked whether there are instances of [CachedBufferoo] stored in the cache
*/
override fun isCached(): Boolean {
return database.rawQuery(BufferooConstants.QUERY_GET_ALL_BUFFEROOS, null).count > 0
}
/**
* Set a point in time at when the cache was last updated
*/
override fun setLastCacheTime(lastCache: Long) {
preferencesHelper.lastCacheTime = lastCache
}
/**
* Check whether the current cached data exceeds the defined [EXPIRATION_TIME] time
*/
override fun isExpired(): Boolean {
val currentTime = System.currentTimeMillis()
val lastUpdateTime = this.getLastCacheUpdateTimeMillis()
return currentTime - lastUpdateTime > EXPIRATION_TIME
}
/**
* Get in millis, the last time the cache was accessed.
*/
private fun getLastCacheUpdateTimeMillis(): Long {
return preferencesHelper.lastCacheTime
}
} | mit | 6b404b799b568a9e909ee3fcbd5f1831 | 33.96063 | 98 | 0.640685 | 5.335337 | false | false | false | false |
caarmen/FRCAndroidWidget | app/src/main/kotlin/ca/rmen/android/frcwidget/FRCWidgetScheduler.kt | 1 | 8125 | /*
* French Revolutionary Calendar Android Widget
* Copyright (C) 2011 - 2017 Carmen Alvarez
*
* 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 ca.rmen.android.frcwidget
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.util.Log
import ca.rmen.android.frccommon.Constants
import ca.rmen.android.frccommon.compat.Api19Helper
import ca.rmen.android.frccommon.compat.ApiHelper
import ca.rmen.android.frccommon.compat.IntentCompat
import ca.rmen.android.frccommon.prefs.FRCPreferences
import java.util.Calendar
/**
*
* Periodically forces an update of all the widgets, depending on if they are set
* to be updated once a minute, or once a day.
*
* The update is done by sending a broadcast which will be received by the [FRCAppWidgetProvider]s.
*
* @author calvarez
*
*/
class FRCWidgetScheduler private constructor(context: Context) {
companion object {
private val TAG = Constants.TAG + FRCWidgetScheduler::class.java.simpleName
const val ACTION_WIDGET_UPDATE = "ca.rmen.android.frcwidget.UPDATE_WIDGET"
@Volatile
private var sInstance: FRCWidgetScheduler? = null
private lateinit var mUpdateWidgetPendingIntent: PendingIntent
private lateinit var mUpdateWidgetTomorrowPendingIntent: PendingIntent
fun getInstance(context: Context) = sInstance ?: synchronized(this) {
sInstance ?: FRCWidgetScheduler(context).also { sInstance = it }
}
}
init {
val updateWidgetIntent = Intent(ACTION_WIDGET_UPDATE)
IntentCompat.setPackage(updateWidgetIntent, context.packageName)
mUpdateWidgetPendingIntent = PendingIntent.getBroadcast(context.applicationContext, 0, updateWidgetIntent, PendingIntent.FLAG_UPDATE_CURRENT)
mUpdateWidgetTomorrowPendingIntent = PendingIntent.getBroadcast(context.applicationContext, 1, updateWidgetIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val filterOn = IntentFilter(Intent.ACTION_SCREEN_ON)
val filterOff = IntentFilter(Intent.ACTION_SCREEN_OFF)
val screenBroadcastReceiver = ScreenBroadcastReceiver()
context.applicationContext.registerReceiver(screenBroadcastReceiver, filterOn)
context.applicationContext.registerReceiver(screenBroadcastReceiver, filterOff)
}
/**
* Cancel any scheduled update alarms, reschedule an update alarm, and force an update now.
*/
fun schedule(context: Context) {
Log.v(TAG, "schedule")
val frequency = FRCPreferences.getInstance(context).updateFrequency
Log.v(TAG, "Start alarm with frequency " + frequency)
// If we show the time, we will update the widget every decimal "minute" (86.4 Gregorian seconds) starting
// one decimal "minute" from now.
var nextAlarmTime = System.currentTimeMillis() + frequency
val mgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
// If we only show the date, we will update the widget every day just before midnight
if (frequency == FRCPreferences.FREQUENCY_DAYS) {
nextAlarmTime = getTimeTomorrowMidnightMillis()
}
// Schedule the periodic updates.
mgr.setRepeating(AlarmManager.RTC, nextAlarmTime, frequency.toLong(), mUpdateWidgetPendingIntent)
scheduleTomorrow(context)
// Also send a broadcast to force an update now.
val updateIntent = Intent(ACTION_WIDGET_UPDATE)
IntentCompat.setPackage(updateIntent, context.packageName)
context.sendBroadcast(updateIntent)
Log.v(TAG, "Started updater")
}
/**
* A bug (or maybe expected behavior?) has been observed on Marshmallow.
* If the widget is supposed to update every night at midnight, the #schedule() method
* uses the setRepeating() api. If the device is idle (doze mode?) at midnight, we would expect the alarm
* to be triggered when the device wakes up later. This isn't the observed case however. It
* appears that if the device is idle when a setRepeating alarm is supposed to trigger, that
* specific alarm execution is skipped completely, and the alarm won't go off again until the next
* scheduled execution (the subsequent day at midnight). The user impact is that if the user
* goes to bed before midnight every day, turning off the device screen before going to bed, the
* widget will never (ever!) update.
*
* We attempt to workaround this by setting an exact alarm for tomorrow at midnight. With the
* setExact api, if the device is idle at midnight, the alarm may not trigger at midnight, but
* at least it will trigger when the device wakes up later, which is good enough for us.
*/
fun scheduleTomorrow(context: Context) {
if (ApiHelper.apiLevel >= Build.VERSION_CODES.KITKAT) {
val nextAlarmTime = getTimeTomorrowMidnightMillis()
Api19Helper.scheduleExact(context, nextAlarmTime, mUpdateWidgetTomorrowPendingIntent)
}
}
/**
* Perhaps unintuitive but maybe simplest way to get a timestamp for "tomorrow at midnight".
* This doesn't return a timestamp of tomorrow at midnight exactly, but tomorrow at midnight plus
* X seconds: X is the number of seconds past the current minute.
* For example, if right now it's April 16 at 14:42:37.558, this will return the timestamp for
* April 17 at 00:00:37.558.
*/
private fun getTimeTomorrowMidnightMillis(): Long {
val cal = Calendar.getInstance()
cal[Calendar.HOUR_OF_DAY] = 23
cal[Calendar.MINUTE] = 59
cal.add(Calendar.MINUTE, 1)
return cal.timeInMillis
}
/**
* Cancel any scheduled update alarms.
*/
fun cancel(context: Context) {
Log.v(TAG, "cancel")
val mgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
mgr.cancel(mUpdateWidgetPendingIntent)
}
/**
* In the mode where the time is displayed, we only want to be updating the widgets when the screen is on,
* because the update will occur every minute.
* TODO: this screen broadcast receiver will stop being triggered when the OS decides to kill
* our app process to free memory. We need to find a solution (if possible) for when the user
* has chosen to display the decimal clock. In that case, we want to update the widget every
* minute when the screen is on, and do nothing when the screen is off. However, if we want to
* "behave", if the user hasn't added any widget at all, we don't want to be doing anything
* at all during screen on/off events: so we shouldn't add a receiver for these events in the manifest.
*/
private inner class ScreenBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.v(TAG, "onReceive: intent = " + intent)
when (intent.action) {
Intent.ACTION_SCREEN_OFF -> {
val frequency = FRCPreferences.getInstance(context).updateFrequency
if (frequency < FRCPreferences.FREQUENCY_DAYS) {
cancel(context)
}
}
Intent.ACTION_SCREEN_ON -> {
schedule(context)
}
}
}
}
}
| gpl-3.0 | c384dc01bfe561b1de8ac1413baf658b | 45.164773 | 157 | 0.700923 | 4.546726 | false | false | false | false |
hzsweers/CatchUp | app/src/main/kotlin/io/sweers/catchup/ui/FontHelper.kt | 1 | 3052 | /*
* Copyright (C) 2019. Zac Sweers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sweers.catchup.ui
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.os.Handler
import android.os.HandlerThread
import androidx.core.provider.FontRequest
import androidx.core.provider.FontsContractCompat
import androidx.core.provider.FontsContractCompat.FontRequestCallback
import androidx.emoji.text.EmojiCompat
import androidx.emoji.text.EmojiCompat.InitCallback
import androidx.emoji.text.FontRequestEmojiCompatConfig
import io.sweers.catchup.util.d
import io.sweers.catchup.util.e
import io.sweers.catchup.util.injection.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class FontHelper @Inject constructor(
@ApplicationContext context: Context,
private val appConfig: dev.zacsweers.catchup.appconfig.AppConfig
) {
private var font: Typeface? = null
init {
load(context)
}
fun load(context: Context) {
d { "Downloading fonts" }
val emojiRequest = FontRequest(
"com.google.android.gms.fonts",
"com.google.android.gms",
"Noto Color Emoji Compat",
catchup.ui.core.R.array.com_google_android_gms_fonts_certs
)
val emojiConfig = FontRequestEmojiCompatConfig(context, emojiRequest)
.setEmojiSpanIndicatorEnabled(appConfig.isDebug)
.setEmojiSpanIndicatorColor(Color.GREEN)
.registerInitCallback(
object : InitCallback() {
override fun onInitialized() = d { "EmojiCompat initialized" }
override fun onFailed(throwable: Throwable?) {
e(throwable) { "EmojiCompat initialization failure." }
}
}
)
EmojiCompat.init(emojiConfig)
val request = FontRequest(
"com.google.android.gms.fonts",
"com.google.android.gms",
"Nunito",
catchup.ui.core.R.array.com_google_android_gms_fonts_certs
)
val callback = object : FontRequestCallback() {
override fun onTypefaceRetrieved(typeface: Typeface) {
d { "Font received" }
font = typeface
}
override fun onTypefaceRequestFailed(reason: Int) {
e { "Font download failed with reason $reason" }
}
}
FontsContractCompat.requestFont(
context.applicationContext,
request,
callback,
Handler(HandlerThread("FontDownloader").apply { start() }.looper)
)
}
/**
* Returns the font, or null if it's not present.
*/
fun getFont() = font
}
| apache-2.0 | c5445d097aac2aa19e7b2f95d244940f | 30.791667 | 75 | 0.715269 | 4.107672 | false | true | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/lang/documentation/ide/impl/quickSearch.kt | 8 | 4365 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("TestOnlyProblems") // KTIJ-19938
package com.intellij.lang.documentation.ide.impl
import com.intellij.ide.DataManager
import com.intellij.ide.actions.searcheverywhere.PSIPresentationBgRendererWrapper
import com.intellij.ide.util.gotoByName.QuickSearchComponent
import com.intellij.lang.documentation.ide.ui.DocumentationPopupUI
import com.intellij.lang.documentation.impl.DocumentationRequest
import com.intellij.lang.documentation.impl.documentationRequest
import com.intellij.lang.documentation.psi.PsiElementDocumentationTarget
import com.intellij.openapi.application.readAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.ComponentPopupBuilder
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.ui.ComponentUtil
import com.intellij.ui.popup.AbstractPopup
import com.intellij.ui.popup.HintUpdateSupply
import com.intellij.ui.popup.PopupUpdateProcessor
import com.intellij.util.ui.EDT
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.map
import java.awt.Component
import javax.swing.JComponent
internal fun quickSearchPopupContext(project: Project): PopupContext? {
val focusedComponent = WindowManagerEx.getInstanceEx().getFocusedComponent(project)
?: return null
return quickSearchPopupContext(project, focusedComponent)
?: hintUpdateSupplyPopupContext(project, focusedComponent)
}
private fun quickSearchPopupContext(project: Project, focusedComponent: Component): PopupContext? {
val quickSearchComponent = ComponentUtil.getParentOfType(QuickSearchComponent::class.java, focusedComponent)
?: return null
return QuickSearchPopupContext(project, quickSearchComponent)
}
private fun hintUpdateSupplyPopupContext(project: Project, focusedComponent: Component): PopupContext? {
val hintUpdateSupply = HintUpdateSupply.getSupply(focusedComponent as JComponent)
?: return null
return HintUpdateSupplyPopupContext(project, focusedComponent, hintUpdateSupply)
}
private abstract class UpdatingPopupContext(
private val project: Project,
) : SecondaryPopupContext() {
private val items = MutableSharedFlow<Any?>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
final override fun requestFlow(): Flow<DocumentationRequest?> = items.asRequestFlow()
final override fun preparePopup(builder: ComponentPopupBuilder) {
super.preparePopup(builder)
builder.addUserData(object : PopupUpdateProcessor(project) {
override fun updatePopup(lookupItemObject: Any?) {
items.tryEmit(lookupItemObject)
}
})
}
}
private class QuickSearchPopupContext(
project: Project,
private val searchComponent: QuickSearchComponent,
) : UpdatingPopupContext(project) {
override fun setUpPopup(popup: AbstractPopup, popupUI: DocumentationPopupUI) {
super.setUpPopup(popup, popupUI)
searchComponent.registerHint(popup)
Disposer.register(popup) {
searchComponent.unregisterHint()
}
}
override fun baseBoundsHandler(): PopupBoundsHandler {
return AdjusterPopupBoundsHandler(searchComponent as Component)
}
}
private class HintUpdateSupplyPopupContext(
project: Project,
private val referenceComponent: Component,
private val hintUpdateSupply: HintUpdateSupply,
) : UpdatingPopupContext(project) {
override fun setUpPopup(popup: AbstractPopup, popupUI: DocumentationPopupUI) {
super.setUpPopup(popup, popupUI)
hintUpdateSupply.registerHint(popup)
}
override fun baseBoundsHandler(): PopupBoundsHandler {
return DataContextPopupBoundsHandler {
DataManager.getInstance().getDataContext(referenceComponent)
}
}
}
private fun Flow<Any?>.asRequestFlow(): Flow<DocumentationRequest?> {
EDT.assertIsEdt()
return map {
readAction {
val targetElement = PSIPresentationBgRendererWrapper.toPsi(it) ?: return@readAction null
if (!targetElement.isValid) {
return@readAction null
}
PsiElementDocumentationTarget(targetElement.project, targetElement).documentationRequest()
}
}
}
| apache-2.0 | 7373fcf98eed7ca90b9230020b9bb9ce | 37.289474 | 120 | 0.788774 | 4.614165 | false | false | false | false |
marius-m/wt4 | remote/src/main/java/lt/markmerkk/worklogs/WorklogApi.kt | 1 | 12473 | package lt.markmerkk.worklogs
import lt.markmerkk.*
import lt.markmerkk.entities.Log
import lt.markmerkk.exceptions.AuthException
import lt.markmerkk.utils.LogFormatters
import net.rcarz.jiraclient.JiraException
import net.rcarz.jiraclient.RestException
import org.joda.time.DateTime
import org.joda.time.LocalDate
import org.slf4j.LoggerFactory
import rx.Completable
import rx.Observable
import rx.Single
import java.net.UnknownHostException
class WorklogApi(
private val timeProvider: TimeProvider,
private val jiraClientProvider: JiraClientProvider,
private val jiraWorklogInteractor: JiraWorklogInteractor,
private val ticketStorage: TicketStorage,
private val worklogStorage: WorklogStorage
) {
/**
* Fetches and stores remote [Log] into database
* Returns all the fresh worklogs from the network
* @throws AuthException whenever authorization fails (thrown in stream)
*/
fun fetchLogs(
fetchTime: DateTime,
start: LocalDate,
end: LocalDate
): Single<List<Log>> {
val startFormat = LogFormatters.formatDate.print(start)
val endFormat = LogFormatters.formatDate.print(end)
val jql = "(worklogDate >= \"$startFormat\" && worklogDate <= \"$endFormat\" && worklogAuthor = currentUser())"
val startAsDateTime = start.toDateTimeAtStartOfDay(timeProvider.dateTimeZone)
val endAsDateTime = end.toDateTimeAtStartOfDay(timeProvider.dateTimeZone)
return Completable.fromAction { logger.info("--- START: Fetching logs ($start / $end)... ---") }
.andThen(
jiraWorklogInteractor.searchWorklogs(
fetchTime = fetchTime,
jql = jql,
startDate = start,
endDate = end
).map { (ticket, worklogs) ->
val worklogsInDateRange = worklogs
.filter {
(it.time.start.isEqual(startAsDateTime) || it.time.start.isAfter(startAsDateTime))
&& it.time.start.isBefore(endAsDateTime)
}
Pair(ticket, worklogsInDateRange)
}
)
.onErrorResumeNext { error ->
logger.warnWithJiraException(
"Error fetching remote worklogs",
error
)
val isAuthException = error.isAuthException()
val noNetworkException = error.findException<UnknownHostException>()
val jiraException = error.findException<JiraException>()
when {
noNetworkException != null -> {
Observable.error(noNetworkException)
}
isAuthException -> {
jiraClientProvider.markAsError()
Observable.error(AuthException(error))
}
jiraException != null -> {
Observable.error(jiraException)
}
else -> Observable.empty()
}
}
.map { (ticket, worklogs) ->
ticketStorage.insertOrUpdateSync(ticket)
worklogs.forEach {
worklogStorage.insertOrUpdateSync(it)
}
worklogs
}
.flatMap { Observable.from(it) }
.toList()
.doOnCompleted { logger.info("--- END ---") }
.take(1)
.toSingle()
}
/**
* Removes all unknown remote [Log]'s from database. 'Unknown' - exist in jira and does not exist in our
* database as a remote log.
*/
fun deleteUnknownLogs(
apiWorklogsAsStream: Single<List<Log>>,
start: LocalDate,
end: LocalDate
): Completable {
return Completable.fromAction { logger.info("--- START: Deleting unknown logs... ---") }
.andThen(
worklogStorage.loadWorklogs(start, end)
.zipWith(
apiWorklogsAsStream,
{ logsDb, logsApi -> Pair(logsDb, logsApi) }
)
)
.map { (logsDb, logsApi) ->
val dbRemoteIds = logsDb
.filter { it.isRemote }
.map { it.remoteData!!.remoteId }
val apiRemoteIds = logsApi
.map { it.remoteData!!.remoteId }
dbRemoteIds
.subtract(apiRemoteIds)
.forEach {
logger.info("Deleting worklog with remote ID $it as it is not found on remote anymore")
worklogStorage.hardDeleteRemoteSync(it)
}
}
.toCompletable()
.doOnCompleted { logger.info("--- END ---") }
}
/**
* Removes all [Log] when are marked for deletion [Log.remoteData.isDelete]
* @throws AuthException when authorization fails (thrown in stream)
*/
fun deleteMarkedLogs(start: LocalDate, end: LocalDate): Completable {
return Completable.fromAction { logger.info("--- START: Deleting logs marked for deletion ($start to $end)... ---") }
.andThen(worklogStorage.loadWorklogs(start, end))
.flatMapObservable { Observable.from(it) }
.filter { it.isMarkedForDeletion }
.flatMapSingle { worklog ->
logger.warn("Trying to delete ${worklog.toStringShort()}")
jiraWorklogInteractor.delete(worklog)
.onErrorResumeNext { error ->
logger.warnWithJiraException("Error trying to delete ${worklog.toStringShort()}", error)
if (error.isAuthException()) {
jiraClientProvider.markAsError()
Single.error(AuthException(error))
} else {
val remoteId = worklog.remoteData?.remoteId ?: Const.NO_ID
Single.just(remoteId)
}
}.doOnSuccess { worklogStorage.hardDeleteRemoteSync(it) }
}
.toList()
.toCompletable()
.doOnCompleted { logger.info("--- END ---") }
}
/**
* Uploads all local logs for the provided time gap
* @throws AuthException whenever authorization fails (thrown in stream)
*/
fun uploadLogs(
fetchTime: DateTime,
start: LocalDate,
end: LocalDate
): Completable {
return Completable.fromAction { logger.info("--- START: Uploading local worklogs... ---") }
.andThen(worklogStorage.loadWorklogs(start, end))
.flatMapObservable { Observable.from(it) }
.flatMapSingle { uploadLog(fetchTime, it) }
.flatMap { uploadStatus ->
when (uploadStatus) {
is WorklogUploadSuccess -> {
logger.info("Success uploading ${uploadStatus.remoteLog.toStringLonger()}")
worklogStorage
.insertOrUpdate(uploadStatus.remoteLog)
.toObservable()
}
is WorklogUploadError -> {
logger.warnWithJiraException(
"Error uploading ${uploadStatus.localLog.toStringShort()}",
uploadStatus.error
)
Observable.empty()
}
is WorklogUploadValidationError -> {
logger.info("${uploadStatus.localLog.toStringShort()} not eligable for upload: ${uploadStatus.worklogValidateError.errorMessage}")
Observable.empty()
}
}
}
.toList()
.toCompletable()
.doOnCompleted { logger.info("--- END ---") }
}
/**
* Uploads provided [Log] if it's eligible for upload
* @throws AuthException whenever authorization fails (thrown in stream)
*/
fun uploadLog(
fetchTime: DateTime,
log: Log
): Single<WorklogUploadState> {
return Single.just(log.isEligibleForUpload())
.flatMap { uploadValidatorState ->
when (uploadValidatorState) {
is WorklogValid -> {
jiraWorklogInteractor.uploadWorklog(fetchTime, log)
.map<WorklogUploadState> { WorklogUploadSuccess(it) }
.onErrorResumeNext { error ->
if (error.isAuthException()) {
val logWithErrorMessage = log.appendSystemNote("Cannot upload: " +
"Authorization error. " +
"Check your connection with JIRA")
worklogStorage.updateSync(logWithErrorMessage)
Single.error(AuthException(error))
} else {
val errorAsRestException = error.findException<RestException>()
val errorAsJiraException = error.findException<JiraException>()
val logWithErrorMessage = when {
errorAsRestException != null -> {
log.appendSystemNote("Cannot upload: JIRA Error (${errorAsRestException.httpStatusCode}) ${errorAsRestException.httpResult}")
}
errorAsJiraException != null -> {
val errorAsJira = error as JiraException
log.appendSystemNote("Cannot upload: '${errorAsJira.message}'")
}
else -> log.appendSystemNote("Cannot upload: Unrecognized error, check 'Account settings' for more info")
}
worklogStorage.updateSync(logWithErrorMessage)
Single.just(WorklogUploadError(logWithErrorMessage, error))
}
}
}
is WorklogInvalidNoTicketCode,
is WorklogInvalidNoComment,
is WorklogInvalidDurationTooLittle -> {
val logWithErrorMessage = log.appendSystemNote("Cannot upload: ${uploadValidatorState.errorMessage}")
val worklogUploadValidationError = WorklogUploadValidationError(logWithErrorMessage, uploadValidatorState)
worklogStorage.updateSync(logWithErrorMessage)
Single.just(worklogUploadValidationError)
}
is WorklogInvalidAlreadyRemote -> {
Single.just(WorklogUploadValidationError(log, uploadValidatorState))
}
}
}
}
companion object {
private val logger = LoggerFactory.getLogger(Tags.JIRA)
}
} | apache-2.0 | ef965b52f786630562946246290dede1 | 48.697211 | 177 | 0.474625 | 6.42276 | false | false | false | false |
daviddenton/k2 | src/main/kotlin/io/github/daviddenton/k2/contract/Parameter.kt | 1 | 3163 | package io.github.daviddenton.k2.contract
import io.github.daviddenton.k2.contract.ParamType.*
import io.github.daviddenton.k2.util.then
import java.math.BigDecimal
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter.*
import java.util.*
class NamedParameter<Initial, Intermediate>(override val name: String,
override val description: String?,
override val parameter: Parameter<Initial>,
private val demux: (Intermediate) -> Iterable<Initial>,
private val validatePresence: (Iterable<Initial>) -> Intermediate?): Named, Iterable<Named> {
override fun iterator(): Iterator<Named> = listOf(this).iterator()
fun convert(rawValues: Iterable<String>): Intermediate? = validatePresence(rawValues.map(parameter::fromString))
fun <Bnd : Binding> toBindings(intermediate: Intermediate, createBinding: (NamedParameter<*, *>, String) -> Bnd): Iterable<Bnd> =
demux(intermediate).map(parameter::asString).map { createBinding(this, it) }
}
class Parameter<T> constructor(private val type: ParamType,
private val deserialize: (String) -> T,
private val serialize: (T) -> String = { it.toString() }) {
fun fromString(str: String): T = deserialize(str)
fun asString(t: T): String = serialize(t)
fun single(name: String, description: String? = null): NamedParameter<T, T> = NamedParameter(name, description, this, { listOf(it) }, { it.firstOrNull() })
fun multi(name: String, description: String? = null) = NamedParameter(name, description, this, { it }, { if (it.toList().isNotEmpty()) it else null })
fun <O> map(toNext: (T) -> O, fromNext: (O) -> T) = Parameter(type, deserialize.then(toNext), fromNext.then(serialize))
fun <O> map(toNext: (T) -> O): Parameter<O> = Parameter(type, deserialize.then(toNext))
companion object {
fun boolean() = Parameter(BooleanParamType, {
when {
it.toLowerCase() == "false" -> false
it.toLowerCase() == "true" -> true
else -> throw IllegalArgumentException("illegal boolean value")
}
}, Boolean::toString)
fun string() = Parameter(StringParamType, { it })
fun uuid() = Parameter(StringParamType, UUID::fromString)
fun long() = Parameter(NumberParamType, String::toLong)
fun int() = Parameter(NumberParamType, String::toInt)
fun double() = Parameter(NumberParamType, String::toDouble)
fun float() = Parameter(NumberParamType, String::toFloat)
fun bigDecimal() = Parameter(NumberParamType, ::BigDecimal)
fun localDate() = Parameter(StringParamType, LocalDate::parse, ISO_LOCAL_DATE::format)
fun zonedDateTime() = Parameter(StringParamType, ZonedDateTime::parse, ISO_ZONED_DATE_TIME::format)
fun localDateTime() = Parameter(StringParamType, LocalDateTime::parse, ISO_LOCAL_DATE_TIME::format)
}
}
| apache-2.0 | 3a6324479b61d1990d0c0032e8e6e5f9 | 50.852459 | 159 | 0.640531 | 4.380886 | false | false | false | false |
carrotengineer/Warren | src/main/kotlin/engineer/carrot/warren/warren/handler/KickHandler.kt | 2 | 1536 | package engineer.carrot.warren.warren.handler
import engineer.carrot.warren.kale.IKaleHandler
import engineer.carrot.warren.kale.irc.message.rfc1459.KickMessage
import engineer.carrot.warren.warren.loggerFor
import engineer.carrot.warren.warren.state.CaseMappingState
import engineer.carrot.warren.warren.state.ConnectionState
import engineer.carrot.warren.warren.state.JoinedChannelsState
class KickHandler(val connectionState: ConnectionState, val channelsState: JoinedChannelsState, val caseMappingState: CaseMappingState) : IKaleHandler<KickMessage> {
private val LOGGER = loggerFor<KickHandler>()
override val messageType = KickMessage::class.java
override fun handle(message: KickMessage, tags: Map<String, String?>) {
val kickedNicks = message.users
val channels = message.channels
for (kickedNick in kickedNicks) {
if (kickedNick == connectionState.nickname) {
// We were forcibly kicked
val removedChannels = channels.map { channel -> channelsState.remove(channel) }
LOGGER.debug("we were kicked from channels: $removedChannels")
} else {
// Someone else was kicked
for ((name, channel) in channelsState.all) {
if (channel.users.contains(kickedNick)) {
channel.users.remove(kickedNick)
}
}
}
}
LOGGER.trace("kicks happened - new channels state: $channelsState")
}
} | isc | 00f2c8136ae84e77746b61a7136ae0d4 | 37.425 | 165 | 0.670573 | 4.830189 | false | false | false | false |
airbnb/lottie-android | sample-compose/src/main/java/com/airbnb/lottie/sample/compose/lottiefiles/LottieFilesPage.kt | 1 | 3843 | package com.airbnb.lottie.sample.compose.lottiefiles
import androidx.annotation.StringRes
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.airbnb.lottie.sample.compose.R
import com.airbnb.lottie.sample.compose.composables.Marquee
enum class LottieFilesTab(@StringRes val stringRes: Int) {
Recent(R.string.tab_recent),
Popular(R.string.tab_popular),
Search(R.string.tab_search)
}
@Composable
fun LottieFilesPage(navController: NavController) {
var tab by rememberSaveable { mutableStateOf(LottieFilesTab.Recent) }
Column {
Marquee("LottieFiles")
LottieFilesTabBar(
selectedTab = tab,
onTabSelected = { tab = it },
)
when (tab) {
LottieFilesTab.Recent -> LottieFilesRecentAndPopularPage(navController, LottieFilesMode.Recent)
LottieFilesTab.Popular -> LottieFilesRecentAndPopularPage(navController, LottieFilesMode.Popular)
LottieFilesTab.Search -> LottieFilesSearchPage(navController)
}
}
}
@Composable
fun LottieFilesTabBar(
selectedTab: LottieFilesTab,
onTabSelected: (LottieFilesTab) -> Unit,
modifier: Modifier = Modifier
) {
Row(
horizontalArrangement = Arrangement.Start,
modifier = modifier
.fillMaxWidth(),
) {
for (tab in LottieFilesTab.values()) {
LottieFilesTabBarTab(
text = stringResource(tab.stringRes),
isSelected = tab == selectedTab,
onClick = { onTabSelected(tab) },
)
}
}
}
@Composable
fun LottieFilesTabBarTab(
text: String,
isSelected: Boolean,
onClick: () -> Unit
) {
val textWidth = remember { mutableStateOf(0) }
val pxRatio = with(LocalDensity.current) { 1.dp.toPx() }
val tabWidth by animateDpAsState(if (isSelected) (textWidth.value / pxRatio).dp else 0.dp)
val tabAlpha by animateFloatAsState(if (isSelected) 1f else 0f)
Column(
modifier = Modifier
.clickable(onClick = onClick)
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
Text(
text,
maxLines = 1,
modifier = Modifier
.onGloballyPositioned { textWidth.value = it.size.width }
.wrapContentWidth()
)
Box(
modifier = Modifier
.align(Alignment.CenterHorizontally)
.height(3.dp)
.background(MaterialTheme.colors.primary.copy(alpha = tabAlpha))
.width(tabWidth)
)
}
} | apache-2.0 | 00e297a8f70ad22560cb875f10add554 | 33.630631 | 109 | 0.710383 | 4.521176 | false | false | false | false |
mdanielwork/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/eventLog/FeatureUsageUiEventsImpl.kt | 4 | 3559 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.eventLog
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.internal.statistic.utils.isDevelopedByJetBrains
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.util.containers.ContainerUtil
private const val DIALOGS_ID = "ui.dialogs"
private const val SETTINGS_ID = "ui.settings"
private const val SETTINGS_DEFAULT = "ide.settings.third.party.plugin"
private const val DIALOGS_DEFAULT = "dialog.third.party.plugin"
class FeatureUsageUiEventsImpl : FeatureUsageUiEvents {
private val SELECT_CONFIGURABLE_DATA = HashMap<String, Any>()
private val APPLY_CONFIGURABLE_DATA = HashMap<String, Any>()
private val RESET_CONFIGURABLE_DATA = HashMap<String, Any>()
private val SHOW_DIALOG_DATA = ContainerUtil.newHashMap<String, Any>()
private val CLOSE_OK_DIALOG_DATA = ContainerUtil.newHashMap<String, Any>()
private val CLOSE_CANCEL_DIALOG_DATA = ContainerUtil.newHashMap<String, Any>()
private val CLOSE_CUSTOM_DIALOG_DATA = ContainerUtil.newHashMap<String, Any>()
init {
SELECT_CONFIGURABLE_DATA["type"] = "select"
APPLY_CONFIGURABLE_DATA["type"] = "apply"
RESET_CONFIGURABLE_DATA["type"] = "reset"
SHOW_DIALOG_DATA["type"] = "show"
CLOSE_OK_DIALOG_DATA["type"] = "close"
CLOSE_OK_DIALOG_DATA["code"] = DialogWrapper.OK_EXIT_CODE
CLOSE_CANCEL_DIALOG_DATA["type"] = "close"
CLOSE_CANCEL_DIALOG_DATA["code"] = DialogWrapper.CANCEL_EXIT_CODE
CLOSE_CUSTOM_DIALOG_DATA["type"] = "close"
CLOSE_CUSTOM_DIALOG_DATA["code"] = DialogWrapper.NEXT_USER_EXIT_CODE
}
override fun logSelectConfigurable(name: String, context: Class<*>) {
if (FeatureUsageLogger.isEnabled()) {
val report = toReport(context, name, SETTINGS_DEFAULT)
FeatureUsageLogger.log(SETTINGS_ID, report, SELECT_CONFIGURABLE_DATA)
}
}
override fun logApplyConfigurable(name: String, context: Class<*>) {
if (FeatureUsageLogger.isEnabled()) {
val report = toReport(context, name, SETTINGS_DEFAULT)
FeatureUsageLogger.log(SETTINGS_ID, report, APPLY_CONFIGURABLE_DATA)
}
}
override fun logResetConfigurable(name: String, context: Class<*>) {
if (FeatureUsageLogger.isEnabled()) {
val report = toReport(context, name, SETTINGS_DEFAULT)
FeatureUsageLogger.log(SETTINGS_ID, report, RESET_CONFIGURABLE_DATA)
}
}
override fun logShowDialog(name: String, context: Class<*>) {
if (FeatureUsageLogger.isEnabled()) {
val report = toReport(context, name, DIALOGS_DEFAULT)
FeatureUsageLogger.log(DIALOGS_ID, report, SHOW_DIALOG_DATA)
}
}
override fun logCloseDialog(name: String, exitCode: Int, context: Class<*>) {
if (FeatureUsageLogger.isEnabled()) {
val report = toReport(context, name, DIALOGS_DEFAULT)
if (exitCode == DialogWrapper.OK_EXIT_CODE) {
FeatureUsageLogger.log(DIALOGS_ID, report, CLOSE_OK_DIALOG_DATA)
}
else if (exitCode == DialogWrapper.CANCEL_EXIT_CODE) {
FeatureUsageLogger.log(DIALOGS_ID, report, CLOSE_CANCEL_DIALOG_DATA)
}
else {
FeatureUsageLogger.log(DIALOGS_ID, report, CLOSE_CUSTOM_DIALOG_DATA)
}
}
}
private fun toReport(context: Class<*>, name: String, defaultValue: String): String {
val pluginId = PluginManagerCore.getPluginByClassName(context.name)
return if (isDevelopedByJetBrains(pluginId)) name else defaultValue
}
} | apache-2.0 | 32750202f740df33b22c671751ecb192 | 40.882353 | 140 | 0.723237 | 4.012401 | false | true | false | false |
mdanielwork/intellij-community | platform/testGuiFramework/src/org/fest/swing/core/SmartWaitRobot.kt | 1 | 11914 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fest.swing.core
import com.intellij.util.ui.EdtInvocationManager
import org.fest.swing.awt.AWT
import org.fest.swing.edt.GuiActionRunner
import org.fest.swing.edt.GuiQuery
import org.fest.swing.hierarchy.ComponentHierarchy
import org.fest.swing.keystroke.KeyStrokeMap
import org.fest.swing.timing.Pause.pause
import org.fest.swing.util.Modifiers
import java.awt.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import javax.swing.JPopupMenu
import javax.swing.KeyStroke
import javax.swing.SwingUtilities
class SmartWaitRobot : Robot {
override fun moveMouse(component: Component) {
basicRobot.moveMouse(component)
}
override fun moveMouse(component: Component, point: Point) {
basicRobot.moveMouse(component, point)
}
override fun moveMouse(point: Point) {
basicRobot.moveMouse(point)
}
override fun click(component: Component) {
basicRobot.click(component)
}
override fun click(component: Component, mouseButton: MouseButton) {
basicRobot.click(component, mouseButton)
}
override fun click(component: Component, mouseButton: MouseButton, counts: Int) {
basicRobot.click(component, mouseButton, counts)
}
override fun click(component: Component, point: Point) {
basicRobot.click(component, point)
}
override fun showWindow(window: Window) {
basicRobot.showWindow(window)
}
override fun showWindow(window: Window, dimension: Dimension) {
basicRobot.showWindow(window, dimension)
}
override fun showWindow(window: Window, dimension: Dimension?, p2: Boolean) {
basicRobot.showWindow(window, dimension, p2)
}
override fun isActive(): Boolean = basicRobot.isActive
override fun pressAndReleaseKey(p0: Int, vararg p1: Int) {
basicRobot.pressAndReleaseKey(p0, *p1)
}
override fun showPopupMenu(component: Component): JPopupMenu = basicRobot.showPopupMenu(component)
override fun showPopupMenu(component: Component, point: Point): JPopupMenu = basicRobot.showPopupMenu(component, point)
override fun jitter(component: Component) {
basicRobot.jitter(component)
}
override fun jitter(component: Component, point: Point) {
basicRobot.jitter(component, point)
}
override fun pressModifiers(p0: Int) {
basicRobot.pressModifiers(p0)
}
override fun pressMouse(mouseButton: MouseButton) {
basicRobot.pressMouse(mouseButton)
}
override fun pressMouse(component: Component, point: Point) {
basicRobot.pressMouse(component, point)
}
override fun pressMouse(component: Component, point: Point, mouseButton: MouseButton) {
basicRobot.pressMouse(component, point, mouseButton)
}
override fun pressMouse(point: Point, mouseButton: MouseButton) {
basicRobot.pressMouse(point, mouseButton)
}
override fun hierarchy(): ComponentHierarchy =
basicRobot.hierarchy()
override fun releaseKey(p0: Int) {
basicRobot.releaseKey(p0)
}
override fun isDragging(): Boolean = basicRobot.isDragging
override fun printer(): ComponentPrinter = basicRobot.printer()
override fun type(char: Char) {
basicRobot.type(char)
}
override fun type(char: Char, component: Component) {
basicRobot.type(char, component)
}
override fun requireNoJOptionPaneIsShowing() {
basicRobot.requireNoJOptionPaneIsShowing()
}
override fun cleanUp() {
basicRobot.cleanUp()
}
override fun releaseMouse(mouseButton: MouseButton) {
basicRobot.releaseMouse(mouseButton)
}
override fun pressKey(p0: Int) {
basicRobot.pressKey(p0)
}
override fun settings(): Settings = basicRobot.settings()
override fun enterText(text: String) {
basicRobot.enterText(text)
}
override fun enterText(text: String, component: Component) {
basicRobot.enterText(text, component)
}
override fun releaseMouseButtons() {
basicRobot.releaseMouseButtons()
}
override fun rightClick(component: Component) {
basicRobot.rightClick(component)
}
override fun focus(component: Component) {
basicRobot.focus(component)
}
override fun doubleClick(component: Component) {
basicRobot.doubleClick(component)
}
override fun cleanUpWithoutDisposingWindows() {
basicRobot.cleanUpWithoutDisposingWindows()
}
override fun isReadyForInput(component: Component): Boolean = basicRobot.isReadyForInput(component)
override fun focusAndWaitForFocusGain(component: Component) {
basicRobot.focusAndWaitForFocusGain(component)
}
override fun releaseModifiers(p0: Int) {
basicRobot.releaseModifiers(p0)
}
override fun findActivePopupMenu(): JPopupMenu? = basicRobot.findActivePopupMenu()
override fun rotateMouseWheel(component: Component, p1: Int) {
basicRobot.rotateMouseWheel(component, p1)
}
override fun rotateMouseWheel(p0: Int) {
basicRobot.rotateMouseWheel(p0)
}
override fun pressAndReleaseKeys(vararg p0: Int) {
basicRobot.pressAndReleaseKeys(*p0)
}
override fun finder(): ComponentFinder = basicRobot.finder()
private val basicRobot: BasicRobot = BasicRobot.robotWithCurrentAwtHierarchyWithoutScreenLock() as BasicRobot
init {
settings().delayBetweenEvents(10)
}
private val waitConst = 30L
private var myAwareClick: Boolean = false
private val fastRobot: java.awt.Robot = java.awt.Robot()
override fun waitForIdle() {
if (myAwareClick) {
Thread.sleep(50)
} else {
pause(waitConst)
if (!SwingUtilities.isEventDispatchThread()) EdtInvocationManager.getInstance().invokeAndWait({ })
}
}
override fun close(w: Window) {
basicRobot.close(w)
basicRobot.waitForIdle()
}
//smooth mouse move
override fun moveMouse(x: Int, y: Int) {
val pauseConstMs = settings().delayBetweenEvents().toLong()
val n = 20
val start = MouseInfo.getPointerInfo().location
val dx = (x - start.x) / n.toDouble()
val dy = (y - start.y) / n.toDouble()
for (step in 1..n) {
try {
pause(pauseConstMs)
} catch (e: InterruptedException) {
e.printStackTrace()
}
basicRobot.moveMouse(
(start.x + dx * ((Math.log(1.0 * step / n) - Math.log(1.0 / n)) * n / (0 - Math.log(1.0 / n)))).toInt(),
(start.y + dy * ((Math.log(1.0 * step / n) - Math.log(1.0 / n)) * n / (0 - Math.log(1.0 / n)))).toInt())
}
basicRobot.moveMouse(x, y)
}
//smooth mouse move to component
override fun moveMouse(c: Component, x: Int, y: Int) {
moveMouseWithAttempts(c, x, y)
}
//smooth mouse move for find and click actions
override fun click(c: Component, where: Point, button: MouseButton, times: Int) {
moveMouseAndClick(c, where, button, times)
}
//we are replacing BasicRobot click with our click because the original one cannot handle double click rightly (BasicRobot creates unnecessary move event between click event which breaks clickCount from 2 to 1)
override fun click(where: Point, button: MouseButton, times: Int) {
moveMouseAndClick(null, where, button, times)
}
private fun moveMouseAndClick(c: Component? = null, where: Point, button: MouseButton, times: Int) {
if (c != null) moveMouse(c, where.x, where.y) else moveMouse(where.x, where.y)
//pause between moving cursor and performing a click.
pause(waitConst)
myEdtAwareClick(button, times, where, c)
}
private fun moveMouseWithAttempts(c: Component, x: Int, y: Int, attempts: Int = 3) {
if (attempts == 0) return
waitFor { c.isShowing }
val componentLocation: Point = requireNotNull(performOnEdt { AWT.translate(c, x, y) })
moveMouse(componentLocation.x, componentLocation.y)
val componentLocationAfterMove: Point = requireNotNull(performOnEdt { AWT.translate(c, x, y) })
val mouseLocation = MouseInfo.getPointerInfo().location
if (mouseLocation.x != componentLocationAfterMove.x || mouseLocation.y != componentLocationAfterMove.y)
moveMouseWithAttempts(c, x, y, attempts - 1)
}
private fun myInnerClick(button: MouseButton, times: Int, point: Point, component: Component?) {
if (component == null)
basicRobot.click(point, button, times)
else
basicRobot.click(component, point, button, times)
}
private fun waitFor(condition: () -> Boolean) {
val timeout = 5000 //5 sec
val cdl = CountDownLatch(1)
val executor = Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(Runnable {
if (condition()) {
cdl.countDown()
}
}, 0, 100, TimeUnit.MILLISECONDS)
cdl.await(timeout.toLong(), TimeUnit.MILLISECONDS)
executor.cancel(true)
}
fun fastPressAndReleaseKey(keyCode: Int, vararg modifiers: Int) {
val unifiedModifiers = InputModifiers.unify(*modifiers)
val updatedModifiers = Modifiers.updateModifierWithKeyCode(keyCode, unifiedModifiers)
fastPressModifiers(updatedModifiers)
if (updatedModifiers == unifiedModifiers) {
fastPressKey(keyCode)
fastReleaseKey(keyCode)
}
fastReleaseModifiers(updatedModifiers)
}
fun fastPressAndReleaseModifiers(vararg modifiers: Int) {
val unifiedModifiers = InputModifiers.unify(*modifiers)
fastPressModifiers(unifiedModifiers)
pause(50)
fastReleaseModifiers(unifiedModifiers)
}
fun fastPressAndReleaseKeyWithoutModifiers(keyCode: Int) {
fastPressKey(keyCode)
fastReleaseKey(keyCode)
}
fun shortcut(keyStoke: KeyStroke) {
fastPressAndReleaseKey(keyStoke.keyCode, keyStoke.modifiers)
}
fun shortcutAndTypeString(keyStoke: KeyStroke, string: String, delayBetweenShortcutAndTypingMs: Int = 0) {
fastPressAndReleaseKey(keyStoke.keyCode, keyStoke.modifiers)
fastTyping(string, delayBetweenShortcutAndTypingMs)
}
fun fastTyping(string: String, delayBetweenShortcutAndTypingMs: Int = 0) {
val keyCodeArray: IntArray = string
.map { KeyStrokeMap.keyStrokeFor(it)?.keyCode ?: throw Exception("Unable to get keystroke for char '$it'") }
.toIntArray()
if (delayBetweenShortcutAndTypingMs > 0) pause(delayBetweenShortcutAndTypingMs.toLong())
keyCodeArray.forEach { fastPressAndReleaseKeyWithoutModifiers(keyCode = it); pause(50) }
}
private fun fastPressKey(keyCode: Int) {
fastRobot.keyPress(keyCode)
}
private fun fastReleaseKey(keyCode: Int) {
fastRobot.keyRelease(keyCode)
}
private fun fastPressModifiers(modifierMask: Int) {
val keys = Modifiers.keysFor(modifierMask)
val keysSize = keys.size
(0 until keysSize)
.map { keys[it] }
.forEach { fastPressKey(it) }
}
private fun fastReleaseModifiers(modifierMask: Int) {
val modifierKeys = Modifiers.keysFor(modifierMask)
for (i in modifierKeys.indices.reversed())
fastReleaseKey(modifierKeys[i])
}
private fun myEdtAwareClick(button: MouseButton, times: Int, point: Point, component: Component?) {
awareClick {
//TODO: remove mouse clicks from EDT
// performOnEdt {
myInnerClick(button, times, point, component)
// }
}
waitForIdle()
}
private fun <T> performOnEdt(body: () -> T): T? =
GuiActionRunner.execute(object : GuiQuery<T>() {
override fun executeInEDT() = body.invoke()
})
private fun awareClick(body: () -> Unit) {
myAwareClick = true
body.invoke()
myAwareClick = false
}
} | apache-2.0 | df5f9f77ff964393130a4bdbf3019784 | 29.62982 | 212 | 0.71907 | 3.976636 | false | false | false | false |
iSoron/uhabits | uhabits-android/src/main/java/org/isoron/uhabits/activities/habits/list/views/HabitCardListController.kt | 1 | 5114 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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.isoron.uhabits.activities.habits.list.views
import dagger.Lazy
import org.isoron.uhabits.activities.habits.list.ListHabitsSelectionMenu
import org.isoron.uhabits.core.models.Habit
import org.isoron.uhabits.core.models.ModelObservable
import org.isoron.uhabits.core.ui.screens.habits.list.ListHabitsBehavior
import org.isoron.uhabits.inject.ActivityScope
import javax.inject.Inject
/**
* Controller responsible for receiving and processing the events generated by a
* HabitListView. These include selecting and reordering items, toggling
* checkmarks and clicking habits.
*/
@ActivityScope
class HabitCardListController @Inject constructor(
private val adapter: HabitCardListAdapter,
private val behavior: ListHabitsBehavior,
private val selectionMenu: Lazy<ListHabitsSelectionMenu>
) : HabitCardListView.Controller, ModelObservable.Listener {
private var activeMode: Mode
init {
this.activeMode = NormalMode()
adapter.observable.addListener(this)
}
override fun drop(from: Int, to: Int) {
if (from == to) return
cancelSelection()
val habitFrom = adapter.getItem(from)
val habitTo = adapter.getItem(to)
if (habitFrom == null || habitTo == null) return
adapter.performReorder(from, to)
behavior.onReorderHabit(habitFrom, habitTo)
}
override fun onItemClick(position: Int) {
activeMode.onItemClick(position)
}
override fun onItemLongClick(position: Int) {
activeMode.onItemLongClick(position)
}
override fun onModelChange() {
if (adapter.isSelectionEmpty) {
activeMode = NormalMode()
selectionMenu.get().onSelectionFinish()
}
}
fun onSelectionFinished() {
cancelSelection()
}
override fun startDrag(position: Int) {
activeMode.startDrag(position)
}
private fun toggleSelection(position: Int) {
adapter.toggleSelection(position)
activeMode = if (adapter.isSelectionEmpty) NormalMode() else SelectionMode()
}
private fun cancelSelection() {
adapter.clearSelection()
activeMode = NormalMode()
selectionMenu.get().onSelectionFinish()
}
interface HabitListener {
fun onHabitClick(habit: Habit)
fun onHabitReorder(from: Habit, to: Habit)
}
/**
* A Mode describes the behavior of the list upon clicking, long clicking
* and dragging an item. This depends on whether some items are already
* selected or not.
*/
private interface Mode {
fun onItemClick(position: Int)
fun onItemLongClick(position: Int): Boolean
fun startDrag(position: Int)
}
/**
* Mode activated when there are no items selected. Clicks trigger habit
* click. Long clicks start selection.
*/
internal inner class NormalMode : Mode {
override fun onItemClick(position: Int) {
val habit = adapter.getItem(position) ?: return
behavior.onClickHabit(habit)
}
override fun onItemLongClick(position: Int): Boolean {
startSelection(position)
return true
}
override fun startDrag(position: Int) {
startSelection(position)
}
private fun startSelection(position: Int) {
toggleSelection(position)
activeMode = SelectionMode()
selectionMenu.get().onSelectionStart()
}
}
/**
* Mode activated when some items are already selected. Clicks toggle
* item selection. Long clicks select more items.
*/
internal inner class SelectionMode : Mode {
override fun onItemClick(position: Int) {
toggleSelection(position)
notifyListener()
}
override fun onItemLongClick(position: Int): Boolean {
toggleSelection(position)
notifyListener()
return true
}
override fun startDrag(position: Int) {
toggleSelection(position)
notifyListener()
}
private fun notifyListener() {
if (activeMode is SelectionMode)
selectionMenu.get().onSelectionChange()
else
selectionMenu.get().onSelectionFinish()
}
}
}
| gpl-3.0 | e7abface37d5a2942e7d7da2873eabf5 | 29.987879 | 84 | 0.664385 | 4.800939 | false | false | false | false |
sys1yagi/DroiDon | app/src/main/java/com/sys1yagi/mastodon/android/ui/navigation/home/timeline/TimelineInteractor.kt | 1 | 2914 | package com.sys1yagi.mastodon.android.ui.navigation.home.timeline
import com.sys1yagi.mastodon.android.extensions.async
import com.sys1yagi.mastodon.android.extensions.toJob
import com.sys1yagi.mastodon.android.extensions.ui
import com.sys1yagi.mastodon4j.api.Range
import com.sys1yagi.mastodon4j.api.method.Statuses
import io.reactivex.disposables.Disposables
import kotlinx.coroutines.experimental.Job
import javax.inject.Inject
class TimelineInteractor
@Inject
constructor(
val timeline: StatusFetcher,
val statuses: Statuses
)
: TimelineContract.Interactor {
var out: TimelineContract.InteractorOutput? = null
var disposable = Disposables.empty()
var job: Job? = null
override fun startInteraction(out: TimelineContract.InteractorOutput) {
this.out = out
}
override fun stopInteraction(out: TimelineContract.InteractorOutput) {
disposable.dispose()
job?.cancel()
this.out = null
}
override fun getTimeline(range: Range) {
job = async {
val timeline = timeline.fetch(range).toJob()
ui {
try {
out?.onTimeline(timeline.await(), range)
} catch(e: Throwable) {
out?.onError(e)
}
}
}
}
override fun fav(statusId: Long) {
job = async {
val job = statuses.postFavourite(statusId).toJob()
ui {
try {
job.await()
out?.onFavResult(true, statusId)
} catch (e: Exception) {
out?.onFavResult(false, statusId)
}
}
}
}
override fun unfav(statusId: Long) {
job = async {
val job = statuses.postUnfavourite(statusId).toJob()
ui {
try {
job.await()
out?.onUnfavResult(true, statusId)
} catch(e: Throwable) {
out?.onUnfavResult(false, statusId)
}
}
}
}
override fun reblog(statusId: Long) {
job = async {
val job = statuses.postReblog(statusId).toJob()
ui {
try {
job.await()
out?.onReblogResult(true, statusId)
} catch(e: Throwable) {
out?.onReblogResult(false, statusId)
}
}
}
}
override fun unReblog(statusId: Long) {
job = async {
val job = statuses.postUnreblog(statusId).toJob()
ui {
try {
job.await()
out?.onUnreblogResult(true, statusId)
} catch(e: Throwable) {
out?.onUnreblogResult(false, statusId)
}
}
}
}
}
| mit | 8e95d99a72c643935b689ba85e650987 | 27.568627 | 75 | 0.521963 | 4.596215 | false | false | false | false |
PokeAPI/pokekotlin | src/test/kotlin/me/sargunvohra/lib/pokekotlin/test/model/ContestTest.kt | 2 | 2137 | package me.sargunvohra.lib.pokekotlin.test.model
import kotlin.test.assertEquals
import me.sargunvohra.lib.pokekotlin.model.ContestName
import me.sargunvohra.lib.pokekotlin.model.Effect
import me.sargunvohra.lib.pokekotlin.model.FlavorText
import me.sargunvohra.lib.pokekotlin.model.NamedApiResource
import me.sargunvohra.lib.pokekotlin.test.MockServer
import org.junit.Test
class ContestTest {
@Test
fun getContestType() {
MockServer.client.getContestType(4).apply {
assertEquals(4, id)
assertEquals("smart", name)
assertEquals(NamedApiResource("bitter", "berry-flavor", 4), berryFlavor)
assert(
ContestName(
name = "Smart",
color = "Green",
language = NamedApiResource("en", "language", 9)
) in names
)
}
}
@Test
fun getContestEffect() {
MockServer.client.getContestEffect(27).apply {
assertEquals(27, id)
assertEquals(2, appeal)
assertEquals(0, jam)
assert(
Effect(
effect = "If user appeals first this turn, earns six points instead of two.",
language = NamedApiResource("en", "language", 9)
) in effectEntries
)
assert(
FlavorText(
flavorText = "The appeal works great if performed first.",
language = NamedApiResource("en", "language", 9)
) in flavorTextEntries
)
}
}
@Test
fun getSuperContestEffect() {
MockServer.client.getSuperContestEffect(14).apply {
assertEquals(14, id)
assertEquals(2, appeal)
assert(
FlavorText(
flavorText = "Makes the order of contestants random in the next turn.",
language = NamedApiResource("en", "language", 9)
) in flavorTextEntries
)
assert(NamedApiResource("assist", "move", 274) in moves)
}
}
}
| apache-2.0 | 82301ba7f407ff97135d8d391f2ebd26 | 32.390625 | 97 | 0.557323 | 4.823928 | false | true | false | false |
MGaetan89/ShowsRage | app/src/main/kotlin/com/mgaetan89/showsrage/model/History.kt | 1 | 1085 | package com.mgaetan89.showsrage.model
import android.support.annotation.StringRes
import com.google.gson.annotations.SerializedName
import com.mgaetan89.showsrage.R
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class History : RealmObject() {
open var date: String? = null
open var episode: Int = 0
@PrimaryKey
open var id: String = ""
@SerializedName("indexerid")
open var indexerId: Int = 0
open var provider: String? = null
open var quality: String? = null
open var resource: String? = null
@SerializedName("resource_path")
open var resourcePath: String? = null
open var season: Int = 0
@SerializedName("show_name")
open var showName: String? = null
open var status: String? = null
@SerializedName("tvdbid")
open var tvDbId: Int = 0
open var version: Int = 0
@StringRes
fun getStatusTranslationResource(): Int {
val normalizedStatus = this.status?.toLowerCase()
return when (normalizedStatus) {
"downloaded" -> R.string.downloaded
"snatched" -> R.string.snatched
"subtitled" -> R.string.subtitled
else -> 0
}
}
}
| apache-2.0 | 0df8e8f6a87c73b34d55017819216281 | 26.125 | 51 | 0.733641 | 3.477564 | false | false | false | false |
Vizzuality/forest-watcher | react-native-mbtiles/android/src/main/java/com/cube/rnmbtiles/RNMBTileSource.kt | 1 | 4802 | package com.cube.rnmbtiles
import android.database.sqlite.SQLiteDatabase
import com.facebook.react.bridge.WritableNativeMap
import org.jetbrains.anko.db.MapRowParser
import org.jetbrains.anko.db.select
// Defines metadata for this source object.
// TODO: Pass this up to the JS layer.
data class RNMBTileMetadata(
var minZoomLevel: Int,
var maxZoomLevel: Int,
var isVector: Boolean,
var tms: Boolean,
var tileSize: Int,
var attribution: String?,
var layersJson: String?
)
{
val mappedMetadata: WritableNativeMap
get() {
var nativeMap: WritableNativeMap = WritableNativeMap()
nativeMap.putInt("minZoomLevel", minZoomLevel)
nativeMap.putInt("maxZoomLevel", maxZoomLevel)
nativeMap.putBoolean("isVector", isVector)
nativeMap.putBoolean("tms", tms)
nativeMap.putInt("tileSize", tileSize)
nativeMap.putString("attribution", attribution)
nativeMap.putString("layersJson", layersJson)
return nativeMap
}
}
// Defines various errors that may occur whilst working against this source.
sealed class RNMBTileSourceException : Exception() {
class CouldNotReadFileException : RNMBTileSourceException()
class TileNotFoundException : RNMBTileSourceException()
class UnsupportedFormatException : RNMBTileSourceException()
}
// Defines a MBTileSource object, which is used by the tileserver to query for given tile indexes.
class RNMBTileSource(var id: String, var filePath: String) {
companion object {
/// Defines the raster formats the app is supporting
val VALID_RASTER_FORMATS = listOf("jpg", "png")
/// Defines the vector formats the app is supporting
val VALID_VECTOR_FORMATS = listOf("pbf", "mvt")
}
// Defines metadata for this source object.
var metadata: RNMBTileMetadata? = null
// These two properties are used in the server for constructing response payloads.
var format: String? = null
var isVector: Boolean = false
// Defines a connection to the mbtiles database.
// TODO: Refactor this to use a non-deprecated database dependency.
private val database: SQLiteDatabase = try {
SQLiteDatabase.openOrCreateDatabase(filePath, null)
} catch (e: RuntimeException) {
throw RNMBTileSourceException.CouldNotReadFileException()
}
// Initialises a source object with the given path and identifier.
// We make various requests against the database, and pull out relevant metadata.
// This metadata can then be used within the JS layer to correctly render tiles.
init {
try {
val minZoomLevel = getMetadata("minzoom")?.toInt() ?: 0
val maxZoomLevel = getMetadata("maxzoom")?.toInt() ?: 0
format = getMetadata("format")
val tms = true
isVector = when (format) {
in VALID_VECTOR_FORMATS -> true
in VALID_RASTER_FORMATS -> false
else -> throw RNMBTileSourceException.UnsupportedFormatException()
}
val tileSize = 256
val attribution = getMetadata("attribution")
val layersJson = null// getMetadata("json")
metadata = RNMBTileMetadata(minZoomLevel = minZoomLevel, maxZoomLevel = maxZoomLevel, isVector = isVector, tms = tms, tileSize = tileSize, attribution = attribution, layersJson = layersJson)
} catch (error: RNMBTileSourceException) {
print(error.localizedMessage)
throw error
}
}
fun getMappedMetadata(): WritableNativeMap? {
return metadata?.mappedMetadata
}
// Given coordinates, queries the database and returns a tile if one exists.
fun getTile(z: Int, x: Int, y: Int): ByteArray {
return database.select("tiles")
.whereArgs("(zoom_level = {z}) and (tile_column = {x}) and (tile_row = {y})",
"z" to z, "x" to x, "y" to y)
.parseList(TilesParser)
.run { if (!isEmpty()) get(0) else null }
?: throw RNMBTileSourceException.TileNotFoundException()
}
// Given a metadata property, queries the database and returns it, if it exists.
private fun getMetadata(property: String): String? {
return database.select("metadata").whereSimple("name = ?", property).parseOpt(MetadataParser)?.second
}
}
object MetadataParser : MapRowParser<Pair<String, String>> {
override fun parseRow(columns: Map<String, Any?>): Pair<String, String> =
columns["name"] as String to columns["value"] as String
}
object TilesParser : MapRowParser<ByteArray> {
override fun parseRow(columns: Map<String, Any?>): ByteArray = columns["tile_data"] as ByteArray
}
| mit | 0d88203b4049ac1da05926551dc47254 | 38.68595 | 202 | 0.66389 | 4.534466 | false | false | false | false |
deso88/TinyGit | src/main/kotlin/hamburg/remme/tinygit/gui/builder/Buttons.kt | 1 | 1894 | package hamburg.remme.tinygit.gui.builder
import hamburg.remme.tinygit.greater0
import javafx.geometry.Pos
import javafx.scene.Node
import javafx.scene.control.Button
import javafx.scene.control.Hyperlink
import javafx.scene.control.Separator
import javafx.scene.control.ToolBar
import javafx.scene.input.KeyCombination
import javafx.scene.layout.Pane
import javafx.scene.layout.Priority
fun button(action: Action) = button {
text = action.text
graphic = action.icon?.invoke()
action.shortcut?.let { tooltip(KeyCombination.valueOf(it).displayText) }
action.disabled?.let { disabledWhen(it) }
setOnAction { action.handler() }
}
inline fun button(block: Button.() -> Unit): Button {
val button = Button()
block(button)
return button
}
inline fun link(block: Hyperlink.() -> Unit): Hyperlink {
val link = Hyperlink()
block(link)
return link
}
inline fun toolBar(block: ToolBarBuilder.() -> Unit): ToolBar {
val toolBar = ToolBarBuilder()
block(toolBar)
return toolBar
}
class ToolBarBuilder : ToolBar() {
fun addSpacer() {
+Pane().hgrow(Priority.ALWAYS)
}
operator fun Node.unaryPlus() {
items += this
}
operator fun Action.unaryPlus() {
+button(this)
}
operator fun ActionGroup.unaryPlus() {
if (items.isNotEmpty()) +Separator()
action.forEach { action ->
+stackPane {
+button(action)
action.count?.let {
+label {
addClass("count")
alignment(Pos.TOP_RIGHT)
visibleWhen(it.greater0()) // .run { action.disabled?.let { and(it.not()) } ?: this })
isMouseTransparent = true
textProperty().bind(it.asString())
}
}
}
}
}
}
| bsd-3-clause | e61baaff5df671b5948b59d1a739e43e | 25.305556 | 110 | 0.599261 | 4.334096 | false | false | false | false |
paplorinc/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/impl/LineStatusTrackerManager.kt | 1 | 40077 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.impl
import com.google.common.collect.HashMultiset
import com.google.common.collect.Multiset
import com.intellij.diagnostic.ThreadDumper
import com.intellij.icons.AllIcons
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationType
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.*
import com.intellij.openapi.command.CommandEvent
import com.intellij.openapi.command.CommandListener
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.components.BaseComponent
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.impl.DirectoryIndex
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.*
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.conflicts.ChangelistConflictFileStatusProvider
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vcs.checkin.CheckinHandlerFactory
import com.intellij.openapi.vcs.ex.ChangelistsLocalLineStatusTracker
import com.intellij.openapi.vcs.ex.LineStatusTracker
import com.intellij.openapi.vcs.ex.LocalLineStatusTracker
import com.intellij.openapi.vcs.ex.SimpleLocalLineStatusTracker
import com.intellij.openapi.vcs.history.VcsRevisionNumber
import com.intellij.openapi.vfs.*
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.EventDispatcher
import com.intellij.util.concurrency.Semaphore
import com.intellij.util.ui.UIUtil
import com.intellij.vcsUtil.VcsUtil
import org.jetbrains.annotations.CalledInAny
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.annotations.CalledInBackground
import org.jetbrains.annotations.TestOnly
import java.nio.charset.Charset
import java.util.*
import java.util.concurrent.Future
class LineStatusTrackerManager(
private val project: Project,
private val application: Application,
private val statusProvider: VcsBaseContentProvider,
private val changeListManager: ChangeListManagerImpl,
private val fileDocumentManager: FileDocumentManager,
private val fileEditorManager: FileEditorManagerEx,
@Suppress("UNUSED_PARAMETER") makeSureIndexIsInitializedFirst: DirectoryIndex
) : BaseComponent, LineStatusTrackerManagerI, Disposable {
private val LOCK = Any()
private var isDisposed = false
private val trackers = HashMap<Document, TrackerData>()
private val forcedDocuments = HashMap<Document, Multiset<Any>>()
private val eventDispatcher = EventDispatcher.create(Listener::class.java)
private var partialChangeListsEnabled = VcsApplicationSettings.getInstance().ENABLE_PARTIAL_CHANGELISTS && Registry.`is`("vcs.enable.partial.changelists")
private val documentsInDefaultChangeList = HashSet<Document>()
private var clmFreezeCounter: Int = 0
private val filesWithDamagedInactiveRanges = HashSet<VirtualFile>()
private val fileStatesAwaitingRefresh = HashMap<VirtualFile, ChangelistsLocalLineStatusTracker.State>()
private val loader: SingleThreadLoader<RefreshRequest, RefreshData> = MyBaseRevisionLoader()
companion object {
private val LOG = Logger.getInstance(LineStatusTrackerManager::class.java)
@JvmStatic
fun getInstance(project: Project): LineStatusTrackerManagerI {
return project.getComponent(LineStatusTrackerManagerI::class.java)
}
@JvmStatic
fun getInstanceImpl(project: Project): LineStatusTrackerManager {
return getInstance(project) as LineStatusTrackerManager
}
}
override fun initComponent() {
StartupManager.getInstance(project).registerPreStartupActivity {
if (isDisposed) return@registerPreStartupActivity
application.addApplicationListener(MyApplicationListener(), this)
val busConnection = project.messageBus.connect(this)
busConnection.subscribe(LineStatusTrackerSettingListener.TOPIC, MyLineStatusTrackerSettingListener())
busConnection.subscribe(VcsFreezingProcess.Listener.TOPIC, MyFreezeListener())
val fsManager = FileStatusManager.getInstance(project)
fsManager.addFileStatusListener(MyFileStatusListener(), this)
val editorFactory = EditorFactory.getInstance()
editorFactory.addEditorFactoryListener(MyEditorFactoryListener(), this)
editorFactory.eventMulticaster.addDocumentListener(MyDocumentListener(), this)
changeListManager.addChangeListListener(MyChangeListListener())
val virtualFileManager = VirtualFileManager.getInstance()
virtualFileManager.addVirtualFileListener(MyVirtualFileListener(), this)
busConnection.subscribe(CommandListener.TOPIC, MyCommandListener())
}
}
override fun dispose() {
isDisposed = true
synchronized(LOCK) {
for ((document, multiset) in forcedDocuments) {
for (requester in multiset.elementSet()) {
warn("Tracker for is being held on dispose by $requester", document)
}
}
forcedDocuments.clear()
for (data in trackers.values) {
unregisterTrackerInCLM(data)
data.tracker.release()
}
trackers.clear()
loader.dispose()
}
}
override fun getLineStatusTracker(document: Document): LineStatusTracker<*>? {
synchronized(LOCK) {
return trackers[document]?.tracker
}
}
override fun getLineStatusTracker(file: VirtualFile): LineStatusTracker<*>? {
val document = fileDocumentManager.getCachedDocument(file) ?: return null
return getLineStatusTracker(document)
}
@CalledInAwt
override fun requestTrackerFor(document: Document, requester: Any) {
application.assertIsDispatchThread()
synchronized(LOCK) {
val multiset = forcedDocuments.computeIfAbsent(document) { HashMultiset.create<Any>() }
multiset.add(requester)
if (trackers[document] == null) {
val virtualFile = fileDocumentManager.getFile(document) ?: return
installTracker(virtualFile, document)
}
}
}
@CalledInAwt
override fun releaseTrackerFor(document: Document, requester: Any) {
application.assertIsDispatchThread()
synchronized(LOCK) {
val multiset = forcedDocuments[document]
if (multiset == null || !multiset.contains(requester)) {
warn("Tracker release underflow by $requester", document)
return
}
multiset.remove(requester)
if (multiset.isEmpty()) {
forcedDocuments.remove(document)
checkIfTrackerCanBeReleased(document)
}
}
}
override fun invokeAfterUpdate(task: Runnable) {
loader.addAfterUpdateRunnable(task)
}
fun getTrackers(): List<LineStatusTracker<*>> {
synchronized(LOCK) {
return trackers.values.map { it.tracker }
}
}
fun addTrackerListener(listener: Listener, disposable: Disposable) {
eventDispatcher.addListener(listener, disposable)
}
open class ListenerAdapter : Listener
interface Listener : EventListener {
fun onTrackerAdded(tracker: LineStatusTracker<*>) {
}
fun onTrackerRemoved(tracker: LineStatusTracker<*>) {
}
}
@CalledInAwt
private fun checkIfTrackerCanBeReleased(document: Document) {
synchronized(LOCK) {
val data = trackers[document] ?: return
if (forcedDocuments.containsKey(document)) return
if (data.tracker is ChangelistsLocalLineStatusTracker) {
val hasPartialChanges = data.tracker.hasPartialState()
if (hasPartialChanges) {
log("checkIfTrackerCanBeReleased - hasPartialChanges", data.tracker.virtualFile)
return
}
val isLoading = loader.hasRequest(RefreshRequest(document))
if (isLoading) {
log("checkIfTrackerCanBeReleased - isLoading", data.tracker.virtualFile)
return
}
}
releaseTracker(document)
}
}
@CalledInAwt
private fun onEverythingChanged() {
application.assertIsDispatchThread()
synchronized(LOCK) {
if (isDisposed) return
log("onEverythingChanged", null)
val files = HashSet<VirtualFile>()
for (data in trackers.values) {
files.add(data.tracker.virtualFile)
}
for (document in forcedDocuments.keys) {
val file = fileDocumentManager.getFile(document)
if (file != null) files.add(file)
}
for (file in files) {
onFileChanged(file)
}
}
}
@CalledInAwt
private fun onFileChanged(virtualFile: VirtualFile) {
val document = fileDocumentManager.getCachedDocument(virtualFile) ?: return
synchronized(LOCK) {
if (isDisposed) return
log("onFileChanged", virtualFile)
val tracker = trackers[document]?.tracker
if (tracker == null) {
if (forcedDocuments.containsKey(document)) {
installTracker(virtualFile, document)
}
}
else {
val isPartialTrackerExpected = canCreatePartialTrackerFor(virtualFile)
val isPartialTracker = tracker is ChangelistsLocalLineStatusTracker
if (isPartialTrackerExpected == isPartialTracker) {
refreshTracker(tracker)
}
else {
releaseTracker(document)
installTracker(virtualFile, document)
}
}
}
}
private fun registerTrackerInCLM(data: TrackerData) {
val tracker = data.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) return
val filePath = VcsUtil.getFilePath(tracker.virtualFile)
if (data.clmFilePath != null) {
LOG.error("[registerTrackerInCLM] tracker already registered")
return
}
changeListManager.registerChangeTracker(filePath, tracker)
data.clmFilePath = filePath
}
private fun unregisterTrackerInCLM(data: TrackerData) {
val tracker = data.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) return
val filePath = data.clmFilePath
if (filePath == null) {
LOG.error("[unregisterTrackerInCLM] tracker is not registered")
return
}
changeListManager.unregisterChangeTracker(filePath, tracker)
data.clmFilePath = null
val actualFilePath = VcsUtil.getFilePath(tracker.virtualFile)
if (filePath != actualFilePath) {
LOG.error("[unregisterTrackerInCLM] unexpected file path: expected: $filePath, actual: $actualFilePath")
}
}
private fun reregisterTrackerInCLM(data: TrackerData) {
val tracker = data.tracker
if (tracker !is ChangelistsLocalLineStatusTracker) return
val oldFilePath = data.clmFilePath
val newFilePath = VcsUtil.getFilePath(tracker.virtualFile)
if (oldFilePath == null) {
LOG.error("[reregisterTrackerInCLM] tracker is not registered")
return
}
if (oldFilePath != newFilePath) {
changeListManager.unregisterChangeTracker(oldFilePath, tracker)
changeListManager.registerChangeTracker(newFilePath, tracker)
data.clmFilePath = newFilePath
}
}
private fun canGetBaseRevisionFor(virtualFile: VirtualFile?): Boolean {
if (isDisposed) return false
if (virtualFile == null || virtualFile is LightVirtualFile) return false
if (runReadAction { !virtualFile.isValid || virtualFile.fileType.isBinary || FileUtilRt.isTooLarge(virtualFile.length) }) return false
if (!statusProvider.isSupported(virtualFile)) return false
val status = FileStatusManager.getInstance(project).getStatus(virtualFile)
if (status == FileStatus.ADDED ||
status == FileStatus.DELETED ||
status == FileStatus.UNKNOWN ||
status == FileStatus.IGNORED) {
return false
}
return true
}
private fun canCreatePartialTrackerFor(virtualFile: VirtualFile): Boolean {
if (!arePartialChangelistsEnabled(virtualFile)) return false
val status = FileStatusManager.getInstance(project).getStatus(virtualFile)
if (status != FileStatus.MODIFIED &&
status != ChangelistConflictFileStatusProvider.MODIFIED_OUTSIDE &&
status != FileStatus.NOT_CHANGED) return false
val change = ChangeListManager.getInstance(project).getChange(virtualFile)
return change != null && change.javaClass == Change::class.java &&
(change.type == Change.Type.MODIFICATION || change.type == Change.Type.MOVED) &&
change.afterRevision is CurrentContentRevision
}
override fun arePartialChangelistsEnabled(virtualFile: VirtualFile): Boolean {
if (!partialChangeListsEnabled) return false
if (getTrackingMode() == LocalLineStatusTracker.Mode.SILENT) return false
val vcs = VcsUtil.getVcsFor(project, virtualFile)
return vcs != null && vcs.arePartialChangelistsSupported()
}
@CalledInAwt
private fun installTracker(virtualFile: VirtualFile, document: Document) {
if (!canGetBaseRevisionFor(virtualFile)) return
doInstallTracker(virtualFile, document)
}
@CalledInAwt
private fun doInstallTracker(virtualFile: VirtualFile, document: Document): LineStatusTracker<*>? {
application.assertIsDispatchThread()
synchronized(LOCK) {
if (isDisposed) return null
if (trackers[document] != null) return null
val tracker = if (canCreatePartialTrackerFor(virtualFile)) {
ChangelistsLocalLineStatusTracker.createTracker(project, document, virtualFile, getTrackingMode())
}
else {
SimpleLocalLineStatusTracker.createTracker(project, document, virtualFile, getTrackingMode())
}
val data = TrackerData(tracker)
trackers.put(document, data)
registerTrackerInCLM(data)
refreshTracker(tracker)
eventDispatcher.multicaster.onTrackerAdded(tracker)
if (clmFreezeCounter > 0) {
tracker.freeze()
}
log("Tracker installed", virtualFile)
return tracker
}
}
@CalledInAwt
private fun releaseTracker(document: Document) {
application.assertIsDispatchThread()
synchronized(LOCK) {
if (isDisposed) return
val data = trackers.remove(document) ?: return
eventDispatcher.multicaster.onTrackerRemoved(data.tracker)
unregisterTrackerInCLM(data)
data.tracker.release()
log("Tracker released", data.tracker.virtualFile)
}
}
private fun updateTrackingModes() {
synchronized(LOCK) {
if (isDisposed) return
val mode = getTrackingMode()
val trackers = trackers.values.map { it.tracker }
for (tracker in trackers) {
val document = tracker.document
val virtualFile = tracker.virtualFile
val isPartialTrackerExpected = canCreatePartialTrackerFor(virtualFile)
val isPartialTracker = tracker is ChangelistsLocalLineStatusTracker
if (isPartialTrackerExpected == isPartialTracker) {
tracker.mode = mode
}
else {
releaseTracker(document)
installTracker(virtualFile, document)
}
}
}
}
private fun getTrackingMode(): LocalLineStatusTracker.Mode {
val settings = VcsApplicationSettings.getInstance()
if (!settings.SHOW_LST_GUTTER_MARKERS) return LocalLineStatusTracker.Mode.SILENT
if (settings.SHOW_WHITESPACES_IN_LST) return LocalLineStatusTracker.Mode.SMART
return LocalLineStatusTracker.Mode.DEFAULT
}
@CalledInAwt
private fun refreshTracker(tracker: LocalLineStatusTracker<*>) {
synchronized(LOCK) {
if (isDisposed) return
loader.scheduleRefresh(RefreshRequest(tracker.document))
log("Refresh queued", tracker.virtualFile)
}
}
private inner class MyBaseRevisionLoader : SingleThreadLoader<RefreshRequest, RefreshData>() {
override fun loadRequest(request: RefreshRequest): Result<RefreshData> {
if (isDisposed) return Result.Canceled()
val document = request.document
val virtualFile = fileDocumentManager.getFile(document)
log("Loading started", virtualFile)
if (virtualFile == null || !virtualFile.isValid) {
log("Loading error: virtual file is not valid", virtualFile)
return Result.Error()
}
if (!canGetBaseRevisionFor(virtualFile)) {
log("Loading error: cant get base revision", virtualFile)
return Result.Error()
}
val baseContent = statusProvider.getBaseRevision(virtualFile)
if (baseContent == null) {
log("Loading error: base revision not found", virtualFile)
return Result.Error()
}
val newContentInfo = ContentInfo(baseContent.revisionNumber, virtualFile.charset)
synchronized(LOCK) {
val data = trackers[document]
if (data == null) {
log("Loading cancelled: tracker not found", virtualFile)
return Result.Canceled()
}
if (!shouldBeUpdated(data.contentInfo, newContentInfo)) {
log("Loading cancelled: no need to update", virtualFile)
return Result.Canceled()
}
}
val lastUpToDateContent = baseContent.loadContent()
if (lastUpToDateContent == null) {
log("Loading error: provider failure", virtualFile)
return Result.Error()
}
val converted = StringUtil.convertLineSeparators(lastUpToDateContent)
log("Loading successful", virtualFile)
return Result.Success(RefreshData(converted, newContentInfo))
}
@CalledInAwt
override fun handleResult(request: RefreshRequest, result: Result<RefreshData>) {
val document = request.document
when (result) {
is Result.Canceled -> handleCanceled(document)
is Result.Error -> handleError(document)
is Result.Success -> handleSuccess(document, result.data)
}
checkIfTrackerCanBeReleased(document)
}
private fun LineStatusTrackerManager.handleCanceled(document: Document) {
val virtualFile = fileDocumentManager.getFile(document) ?: return
val state = synchronized(LOCK) {
fileStatesAwaitingRefresh.remove(virtualFile) ?: return
}
val tracker = getLineStatusTracker(document)
if (tracker is ChangelistsLocalLineStatusTracker) {
tracker.restoreState(state)
log("Loading canceled: state restored", virtualFile)
}
}
private fun handleError(document: Document) {
synchronized(LOCK) {
val data = trackers[document] ?: return
data.tracker.dropBaseRevision()
data.contentInfo = null
}
}
private fun LineStatusTrackerManager.handleSuccess(document: Document,
refreshData: RefreshData) {
val virtualFile = fileDocumentManager.getFile(document)!!
synchronized(LOCK) {
val data = trackers[document]
if (data == null) {
log("Loading finished: tracker already released", virtualFile)
return
}
if (!shouldBeUpdated(data.contentInfo, refreshData.info)) {
log("Loading finished: no need to update", virtualFile)
return
}
data.contentInfo = refreshData.info
}
val tracker = getLineStatusTracker(document) as LocalLineStatusTracker<*>
tracker.setBaseRevision(refreshData.text)
log("Loading finished: success", virtualFile)
if (tracker is ChangelistsLocalLineStatusTracker) {
val state = fileStatesAwaitingRefresh.remove(tracker.virtualFile)
if (state != null) {
tracker.restoreState(state)
log("Loading finished: state restored", virtualFile)
}
}
}
}
private inner class MyFileStatusListener : FileStatusListener {
override fun fileStatusesChanged() {
onEverythingChanged()
}
override fun fileStatusChanged(virtualFile: VirtualFile) {
onFileChanged(virtualFile)
}
}
private inner class MyEditorFactoryListener : EditorFactoryListener {
override fun editorCreated(event: EditorFactoryEvent) {
val editor = event.editor
if (isTrackedEditor(editor)) {
requestTrackerFor(editor.document, editor)
}
}
override fun editorReleased(event: EditorFactoryEvent) {
val editor = event.editor
if (isTrackedEditor(editor)) {
releaseTrackerFor(editor.document, editor)
}
}
private fun isTrackedEditor(editor: Editor): Boolean {
return editor.project == null || editor.project == project
}
}
private inner class MyVirtualFileListener : VirtualFileListener {
override fun beforePropertyChange(event: VirtualFilePropertyEvent) {
if (VirtualFile.PROP_ENCODING == event.propertyName) {
onFileChanged(event.file)
}
}
override fun propertyChanged(event: VirtualFilePropertyEvent) {
if (event.isRename) {
handleFileMovement(event.file)
}
}
override fun fileMoved(event: VirtualFileMoveEvent) {
handleFileMovement(event.file)
}
private fun handleFileMovement(file: VirtualFile) {
if (!partialChangeListsEnabled) return
synchronized(LOCK) {
forEachTrackerUnder(file) { data ->
reregisterTrackerInCLM(data)
}
}
}
override fun fileDeleted(event: VirtualFileEvent) {
if (!partialChangeListsEnabled) return
synchronized(LOCK) {
forEachTrackerUnder(event.file) { data ->
releaseTracker(data.tracker.document)
}
}
}
private fun forEachTrackerUnder(file: VirtualFile, action: (TrackerData) -> Unit) {
if (file.isDirectory) {
val affected = trackers.values.filter { VfsUtil.isAncestor(file, it.tracker.virtualFile, false) }
for (data in affected) {
action(data)
}
}
else {
val document = fileDocumentManager.getCachedDocument(file) ?: return
val data = trackers[document] ?: return
action(data)
}
}
}
private inner class MyDocumentListener : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
if (!ApplicationManager.getApplication().isDispatchThread) return // disable for documents forUseInNonAWTThread
if (!partialChangeListsEnabled) return
val document = event.document
if (documentsInDefaultChangeList.contains(document)) return
val virtualFile = fileDocumentManager.getFile(document) ?: return
if (getLineStatusTracker(document) != null) return
if (!canGetBaseRevisionFor(virtualFile)) return
if (!canCreatePartialTrackerFor(virtualFile)) return
val changeList = changeListManager.getChangeList(virtualFile)
if (changeList != null && !changeList.isDefault) {
log("Tracker install from DocumentListener: ", virtualFile)
val tracker = doInstallTracker(virtualFile, document)
if (tracker is ChangelistsLocalLineStatusTracker) {
tracker.replayChangesFromDocumentEvents(listOf(event))
}
return
}
documentsInDefaultChangeList.add(document)
}
}
private inner class MyApplicationListener : ApplicationListener {
override fun afterWriteActionFinished(action: Any) {
documentsInDefaultChangeList.clear()
synchronized(LOCK) {
val documents = trackers.values.map { it.tracker.document }
for (document in documents) {
checkIfTrackerCanBeReleased(document)
}
}
}
}
private inner class MyLineStatusTrackerSettingListener : LineStatusTrackerSettingListener {
override fun settingsUpdated() {
partialChangeListsEnabled = VcsApplicationSettings.getInstance().ENABLE_PARTIAL_CHANGELISTS && Registry.`is`("vcs.enable.partial.changelists")
updateTrackingModes()
}
}
private inner class MyChangeListListener : ChangeListAdapter() {
override fun defaultListChanged(oldDefaultList: ChangeList?, newDefaultList: ChangeList?) {
runInEdt(ModalityState.any()) {
expireInactiveRangesDamagedNotifications()
EditorFactory.getInstance().allEditors
.filterIsInstance(EditorEx::class.java)
.forEach {
it.gutterComponentEx.repaint()
}
}
}
}
private inner class MyCommandListener : CommandListener {
override fun commandFinished(event: CommandEvent) {
if (!partialChangeListsEnabled) return
if (CommandProcessor.getInstance().currentCommand == null &&
!filesWithDamagedInactiveRanges.isEmpty()) {
showInactiveRangesDamagedNotification()
}
}
}
class CheckinFactory : CheckinHandlerFactory() {
override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler {
val project = panel.project
return object : CheckinHandler() {
override fun checkinSuccessful() {
resetExcludedFromCommit()
}
override fun checkinFailed(exception: MutableList<VcsException>?) {
resetExcludedFromCommit()
}
private fun resetExcludedFromCommit() {
runInEdt {
if (!project.isDisposed) getInstanceImpl(project).resetExcludedFromCommitMarkers()
}
}
}
}
}
private inner class MyFreezeListener : VcsFreezingProcess.Listener {
override fun onFreeze() {
runReadAction {
synchronized(LOCK) {
if (clmFreezeCounter == 0) {
for (data in trackers.values) {
try {
data.tracker.freeze()
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
clmFreezeCounter++
}
}
}
override fun onUnfreeze() {
runInEdt(ModalityState.any()) {
synchronized(LOCK) {
clmFreezeCounter--
if (clmFreezeCounter == 0) {
for (data in trackers.values) {
try {
data.tracker.unfreeze()
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
}
}
}
}
private fun shouldBeUpdated(oldInfo: ContentInfo?, newInfo: ContentInfo): Boolean {
if (oldInfo == null) return true
if (oldInfo.revision == newInfo.revision && oldInfo.revision != VcsRevisionNumber.NULL) {
return oldInfo.charset != newInfo.charset
}
return true
}
private class TrackerData(val tracker: LocalLineStatusTracker<*>,
var contentInfo: ContentInfo? = null,
var clmFilePath: FilePath? = null)
private class ContentInfo(val revision: VcsRevisionNumber, val charset: Charset)
private class RefreshRequest(val document: Document) {
override fun equals(other: Any?): Boolean = other is RefreshRequest && document == other.document
override fun hashCode(): Int = document.hashCode()
override fun toString(): String = "RefreshRequest: " + (FileDocumentManager.getInstance().getFile(document)?.path ?: "unknown")
}
private class RefreshData(val text: String, val info: ContentInfo)
private fun log(message: String, file: VirtualFile?) {
if (LOG.isDebugEnabled) {
if (file != null) {
LOG.debug(message + "; file: " + file.path)
}
else {
LOG.debug(message)
}
}
}
private fun warn(message: String, document: Document?) {
val file = document?.let { fileDocumentManager.getFile(it) }
warn(message, file)
}
private fun warn(message: String, file: VirtualFile?) {
if (file != null) {
LOG.warn(message + "; file: " + file.path)
}
else {
LOG.warn(message)
}
}
@CalledInAwt
fun resetExcludedFromCommitMarkers() {
application.assertIsDispatchThread()
synchronized(LOCK) {
val documents = mutableListOf<Document>()
for (data in trackers.values) {
val tracker = data.tracker
if (tracker is ChangelistsLocalLineStatusTracker) {
tracker.setExcludedFromCommit(false)
documents.add(tracker.document)
}
}
for (document in documents) {
checkIfTrackerCanBeReleased(document)
}
}
}
@CalledInAwt
internal fun collectPartiallyChangedFilesStates(): List<ChangelistsLocalLineStatusTracker.FullState> {
application.assertIsDispatchThread()
val result = mutableListOf<ChangelistsLocalLineStatusTracker.FullState>()
synchronized(LOCK) {
for (data in trackers.values) {
val tracker = data.tracker
if (tracker is ChangelistsLocalLineStatusTracker) {
val hasPartialChanges = tracker.affectedChangeListsIds.size > 1
if (hasPartialChanges) {
result.add(tracker.storeTrackerState())
}
}
}
}
return result
}
@CalledInAwt
internal fun restoreTrackersForPartiallyChangedFiles(trackerStates: List<ChangelistsLocalLineStatusTracker.State>) {
runWriteAction {
synchronized(LOCK) {
for (state in trackerStates) {
val virtualFile = state.virtualFile
val document = fileDocumentManager.getDocument(virtualFile) ?: continue
if (!canCreatePartialTrackerFor(virtualFile)) continue
val oldData = trackers[document]
val oldTracker = oldData?.tracker
if (oldTracker is ChangelistsLocalLineStatusTracker) {
val stateRestored = state is ChangelistsLocalLineStatusTracker.FullState &&
oldTracker.restoreState(state)
if (stateRestored) {
log("Tracker restore: reused, full restored", virtualFile)
}
else {
val isLoading = loader.hasRequest(RefreshRequest(document))
if (isLoading) {
fileStatesAwaitingRefresh.put(state.virtualFile, state)
log("Tracker restore: reused, restore scheduled", virtualFile)
}
else {
oldTracker.restoreState(state)
log("Tracker restore: reused, restored", virtualFile)
}
}
}
else {
val tracker = ChangelistsLocalLineStatusTracker.createTracker(project, document, virtualFile, getTrackingMode())
val data = TrackerData(tracker)
trackers.put(document, data)
if (oldTracker != null) {
eventDispatcher.multicaster.onTrackerRemoved(tracker)
unregisterTrackerInCLM(oldData)
oldTracker.release()
log("Tracker restore: removed existing", virtualFile)
}
registerTrackerInCLM(data)
refreshTracker(tracker)
eventDispatcher.multicaster.onTrackerAdded(tracker)
val stateRestored = state is ChangelistsLocalLineStatusTracker.FullState &&
tracker.restoreState(state)
if (stateRestored) {
log("Tracker restore: created, full restored", virtualFile)
}
else {
fileStatesAwaitingRefresh.put(state.virtualFile, state)
log("Tracker restore: created, restore scheduled", virtualFile)
}
}
}
loader.addAfterUpdateRunnable(Runnable {
synchronized(LOCK) {
log("Tracker restore: finished", null)
fileStatesAwaitingRefresh.clear()
}
})
}
}
}
@CalledInAwt
internal fun notifyInactiveRangesDamaged(virtualFile: VirtualFile) {
application.assertIsDispatchThread()
if (filesWithDamagedInactiveRanges.contains(virtualFile)) return
if (virtualFile == fileEditorManager.currentFile) return
filesWithDamagedInactiveRanges.add(virtualFile)
}
private fun showInactiveRangesDamagedNotification() {
val currentNotifications = NotificationsManager.getNotificationsManager()
.getNotificationsOfType(InactiveRangesDamagedNotification::class.java, project)
val lastNotification = currentNotifications.lastOrNull { !it.isExpired }
if (lastNotification != null) filesWithDamagedInactiveRanges.addAll(lastNotification.virtualFiles)
currentNotifications.forEach { it.expire() }
val files = filesWithDamagedInactiveRanges.toSet()
filesWithDamagedInactiveRanges.clear()
InactiveRangesDamagedNotification(project, files).notify(project)
}
@CalledInAwt
private fun expireInactiveRangesDamagedNotifications() {
filesWithDamagedInactiveRanges.clear()
val currentNotifications = NotificationsManager.getNotificationsManager()
.getNotificationsOfType(InactiveRangesDamagedNotification::class.java, project)
currentNotifications.forEach { it.expire() }
}
private class InactiveRangesDamagedNotification(project: Project, val virtualFiles: Set<VirtualFile>)
: Notification(VcsNotifier.STANDARD_NOTIFICATION.displayId,
AllIcons.Toolwindows.ToolWindowChanges,
null,
null,
VcsBundle.getString("lst.inactive.ranges.damaged.notification"),
NotificationType.INFORMATION,
null) {
init {
addAction(NotificationAction.createSimple("View Changes...") {
val defaultList = ChangeListManager.getInstance(project).defaultChangeList
val changes = defaultList.changes.filter { virtualFiles.contains(it.virtualFile) }
val window = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID)
window.activate { ChangesViewManager.getInstance(project).selectChanges(changes) }
expire()
})
}
}
@TestOnly
fun waitUntilBaseContentsLoaded() {
assert(ApplicationManager.getApplication().isUnitTestMode)
if (ApplicationManager.getApplication().isDispatchThread) {
UIUtil.dispatchAllInvocationEvents()
}
val semaphore = Semaphore()
semaphore.down()
loader.addAfterUpdateRunnable(Runnable {
semaphore.up()
})
val start = System.currentTimeMillis()
while (true) {
if (ApplicationManager.getApplication().isDispatchThread) {
UIUtil.dispatchAllInvocationEvents()
}
if (semaphore.waitFor(10)) {
return
}
if (System.currentTimeMillis() - start > 10000) {
loader.dumpInternalState()
System.err.println(ThreadDumper.dumpThreadsToString())
throw IllegalStateException("Couldn't await base contents")
}
}
}
@TestOnly
fun releaseAllTrackers() {
synchronized(LOCK) {
forcedDocuments.clear()
for (data in trackers.values) {
unregisterTrackerInCLM(data)
data.tracker.release()
}
trackers.clear()
}
}
}
/**
* Single threaded queue with the following properties:
* - Ignores duplicated requests (the first queued is used).
* - Allows to check whether request is scheduled or is waiting for completion.
* - Notifies callbacks when queue is exhausted.
*/
private abstract class SingleThreadLoader<Request, T> {
private val LOG = Logger.getInstance(SingleThreadLoader::class.java)
private val LOCK: Any = Any()
private val taskQueue = ArrayDeque<Request>()
private val waitingForRefresh = HashSet<Request>()
private val callbacksWaitingUpdateCompletion = ArrayList<Runnable>()
private var isScheduled: Boolean = false
private var isDisposed: Boolean = false
private var lastFuture: Future<*>? = null
@CalledInBackground
protected abstract fun loadRequest(request: Request): Result<T>
@CalledInAwt
protected abstract fun handleResult(request: Request, result: Result<T>)
@CalledInAwt
fun scheduleRefresh(request: Request) {
if (isDisposed) return
synchronized(LOCK) {
if (taskQueue.contains(request)) return
taskQueue.add(request)
schedule()
}
}
@CalledInAwt
fun dispose() {
val callbacks = mutableListOf<Runnable>()
synchronized(LOCK) {
isDisposed = true
taskQueue.clear()
waitingForRefresh.clear()
lastFuture?.cancel(true)
callbacks += callbacksWaitingUpdateCompletion
callbacksWaitingUpdateCompletion.clear()
}
executeCallbacks(callbacksWaitingUpdateCompletion)
}
@CalledInAwt
fun hasRequest(request: Request): Boolean {
synchronized(LOCK) {
for (refreshData in taskQueue) {
if (refreshData == request) return true
}
for (refreshData in waitingForRefresh) {
if (refreshData == request) return true
}
}
return false
}
@CalledInAny
fun addAfterUpdateRunnable(task: Runnable) {
val updateScheduled = putRunnableIfUpdateScheduled(task)
if (updateScheduled) return
runInEdt(ModalityState.any()) {
if (!putRunnableIfUpdateScheduled(task)) {
task.run()
}
}
}
private fun putRunnableIfUpdateScheduled(task: Runnable): Boolean {
synchronized(LOCK) {
if (taskQueue.isEmpty() && waitingForRefresh.isEmpty()) return false
callbacksWaitingUpdateCompletion.add(task)
return true
}
}
private fun schedule() {
if (isDisposed) return
synchronized(LOCK) {
if (isScheduled) return
if (taskQueue.isEmpty()) return
isScheduled = true
lastFuture = ApplicationManager.getApplication().executeOnPooledThread {
handleRequests()
}
}
}
private fun handleRequests() {
while (true) {
val request = synchronized(LOCK) {
val request = taskQueue.poll()
if (isDisposed || request == null) {
isScheduled = false
return
}
waitingForRefresh.add(request)
return@synchronized request
}
handleSingleRequest(request)
}
}
private fun handleSingleRequest(request: Request) {
val result: Result<T> = try {
loadRequest(request)
}
catch (e: Throwable) {
LOG.error(e)
Result.Error()
}
runInEdt(ModalityState.any()) {
try {
synchronized(LOCK) {
waitingForRefresh.remove(request)
}
handleResult(request, result)
}
finally {
notifyTrackerRefreshed(request)
}
}
}
@CalledInAwt
private fun notifyTrackerRefreshed(request: Request) {
if (isDisposed) return
val callbacks = mutableListOf<Runnable>()
synchronized(LOCK) {
if (taskQueue.isEmpty() && waitingForRefresh.isEmpty()) {
callbacks += callbacksWaitingUpdateCompletion
callbacksWaitingUpdateCompletion.clear()
}
}
executeCallbacks(callbacks)
}
@CalledInAwt
private fun executeCallbacks(callbacks: List<Runnable>) {
for (callback in callbacks) {
try {
callback.run()
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
@TestOnly
fun dumpInternalState() {
synchronized(LOCK) {
LOG.debug("isScheduled - $isScheduled")
LOG.debug("pending callbacks: ${callbacksWaitingUpdateCompletion.size}")
taskQueue.forEach {
LOG.debug("pending task: ${it}")
}
waitingForRefresh.forEach {
LOG.debug("waiting refresh: ${it}")
}
}
}
}
private sealed class Result<T> {
class Success<T>(val data: T) : Result<T>()
class Canceled<T> : Result<T>()
class Error<T> : Result<T>()
} | apache-2.0 | c90af9814e666388307e9b5d5e3a8286 | 30.732383 | 156 | 0.687252 | 5.391041 | false | false | false | false |
JetBrains/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/ToggleAmendCommitModeAction.kt | 1 | 2503 | // 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.vcs.commit
import com.intellij.ide.HelpTooltip
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.ex.CheckboxAction
import com.intellij.openapi.keymap.KeymapUtil.getFirstKeyboardShortcutText
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.actions.commit.getContextCommitWorkflowHandler
import com.intellij.vcs.commit.CommitSessionCounterUsagesCollector.CommitOption
import javax.swing.JComponent
class ToggleAmendCommitModeAction : CheckboxAction(), DumbAware {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun update(e: AnActionEvent) {
super.update(e)
val amendCommitHandler = getAmendCommitHandler(e)
with(e.presentation) {
isVisible = amendCommitHandler?.isAmendCommitModeSupported() == true
isEnabled = isVisible && amendCommitHandler?.isAmendCommitModeTogglingEnabled == true
}
}
override fun isSelected(e: AnActionEvent): Boolean = getAmendCommitHandler(e)?.isAmendCommitMode == true
override fun setSelected(e: AnActionEvent, state: Boolean) {
getAmendCommitHandler(e)!!.isAmendCommitMode = state
e.project?.let { project ->
CommitSessionCollector.getInstance(project).logCommitOptionToggled(CommitOption.AMEND, state)
}
}
private fun getAmendCommitHandler(e: AnActionEvent) = e.getContextCommitWorkflowHandler()?.amendCommitHandler
override fun createCustomComponent(presentation: Presentation, place: String): JComponent =
super.createCustomComponent(presentation, place).also { installHelpTooltip(it) }
override fun updateCustomComponent(checkBox: JComponent, presentation: Presentation) {
presentation.text = message("checkbox.amend")
presentation.description = null // prevents default tooltip on `checkBox`
super.updateCustomComponent(checkBox, presentation)
}
private fun installHelpTooltip(it: JComponent) {
HelpTooltip()
.setTitle(templatePresentation.text)
.setShortcut(getFirstKeyboardShortcutText("Vcs.ToggleAmendCommitMode"))
.setDescription(templatePresentation.description)
.installOn(it)
}
} | apache-2.0 | 0a628d40c04eac75cab6cb5faa8998db | 40.733333 | 140 | 0.794646 | 5.056566 | false | false | false | false |
mikepenz/Android-Iconics | google-material-typeface/google-material-typeface-sharp-library/src/main/java/com/mikepenz/iconics/typeface/library/googlematerial/SharpGoogleMaterial.kt | 1 | 51958 | /*
* Copyright 2020 Mike Penz
*
* 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.mikepenz.iconics.typeface.library.googlematerial
import com.mikepenz.iconics.typeface.IIcon
import com.mikepenz.iconics.typeface.ITypeface
import java.util.LinkedList
@Suppress("EnumEntryName")
object SharpGoogleMaterial : ITypeface {
override val fontRes: Int
get() = R.font.google_material_font_sharp_v4_0_0_0_original
override val characters: Map<String, Char> by lazy {
Icon.values().associate { it.name to it.character }
}
override val mappingPrefix: String
get() = "gms"
override val fontName: String
get() = "Google Material Sharp"
override val version: String
get() = "4.0.0.0.original"
override val iconCount: Int
get() = characters.size
override val icons: List<String>
get() = characters.keys.toCollection(LinkedList())
override val author: String
get() = "Google"
override val url: String
get() = "https://github.com/google/material-design-icons"
override val description: String
get() = "Material design icons are the official icon set from Google that are designed " +
"under the material design guidelines."
override val license: String
get() = "CC-BY 4.0"
override val licenseUrl: String
get() = "http://creativecommons.org/licenses/by/4.0/"
override fun getIcon(key: String): IIcon = Icon.valueOf(key)
enum class Icon constructor(override val character: Char) : IIcon {
gms_360('\ue577'),
gms_3d_rotation('\ue84d'),
gms_4k('\ue072'),
gms_5g('\uef38'),
gms_6_ft_apart('\uf21e'),
gms_ac_unit('\ueb3b'),
gms_access_alarm('\ue190'),
gms_access_alarms('\ue191'),
gms_access_time('\ue192'),
gms_accessibility('\ue84e'),
gms_accessibility_new('\ue92c'),
gms_accessible('\ue914'),
gms_accessible_forward('\ue934'),
gms_account_balance('\ue84f'),
gms_account_balance_wallet('\ue850'),
gms_account_box('\ue851'),
gms_account_circle('\ue853'),
gms_account_tree('\ue97a'),
gms_ad_units('\uef39'),
gms_adb('\ue60e'),
gms_add('\ue145'),
gms_add_a_photo('\ue439'),
gms_add_alarm('\ue193'),
gms_add_alert('\ue003'),
gms_add_box('\ue146'),
gms_add_business('\ue729'),
gms_add_circle('\ue147'),
gms_add_circle_outline('\ue148'),
gms_add_comment('\ue266'),
gms_add_ic_call('\ue97c'),
gms_add_location('\ue567'),
gms_add_location_alt('\uef3a'),
gms_add_photo_alternate('\ue43e'),
gms_add_road('\uef3b'),
gms_add_shopping_cart('\ue854'),
gms_add_task('\uf23a'),
gms_add_to_home_screen('\ue1fe'),
gms_add_to_photos('\ue39d'),
gms_add_to_queue('\ue05c'),
gms_addchart('\uef3c'),
gms_adjust('\ue39e'),
gms_admin_panel_settings('\uef3d'),
gms_agriculture('\uea79'),
gms_airline_seat_flat('\ue630'),
gms_airline_seat_flat_angled('\ue631'),
gms_airline_seat_individual_suite('\ue632'),
gms_airline_seat_legroom_extra('\ue633'),
gms_airline_seat_legroom_normal('\ue634'),
gms_airline_seat_legroom_reduced('\ue635'),
gms_airline_seat_recline_extra('\ue636'),
gms_airline_seat_recline_normal('\ue637'),
gms_airplanemode_active('\ue195'),
gms_airplanemode_inactive('\ue194'),
gms_airplanemode_off('\ue194'),
gms_airplanemode_on('\ue195'),
gms_airplay('\ue055'),
gms_airport_shuttle('\ueb3c'),
gms_alarm('\ue855'),
gms_alarm_add('\ue856'),
gms_alarm_off('\ue857'),
gms_alarm_on('\ue858'),
gms_album('\ue019'),
gms_align_horizontal_center('\ue00f'),
gms_align_horizontal_left('\ue00d'),
gms_align_horizontal_right('\ue010'),
gms_align_vertical_bottom('\ue015'),
gms_align_vertical_center('\ue011'),
gms_align_vertical_top('\ue00c'),
gms_all_inbox('\ue97f'),
gms_all_inclusive('\ueb3d'),
gms_all_out('\ue90b'),
gms_alt_route('\uf184'),
gms_alternate_email('\ue0e6'),
gms_amp_stories('\uea13'),
gms_analytics('\uef3e'),
gms_anchor('\uf1cd'),
gms_android('\ue859'),
gms_announcement('\ue85a'),
gms_apartment('\uea40'),
gms_api('\uf1b7'),
gms_app_blocking('\uef3f'),
gms_app_settings_alt('\uef41'),
gms_apps('\ue5c3'),
gms_architecture('\uea3b'),
gms_archive('\ue149'),
gms_arrow_back('\ue5c4'),
gms_arrow_back_ios('\ue5e0'),
gms_arrow_circle_down('\uf181'),
gms_arrow_circle_up('\uf182'),
gms_arrow_downward('\ue5db'),
gms_arrow_drop_down('\ue5c5'),
gms_arrow_drop_down_circle('\ue5c6'),
gms_arrow_drop_up('\ue5c7'),
gms_arrow_forward('\ue5c8'),
gms_arrow_forward_ios('\ue5e1'),
gms_arrow_left('\ue5de'),
gms_arrow_right('\ue5df'),
gms_arrow_right_alt('\ue941'),
gms_arrow_upward('\ue5d8'),
gms_art_track('\ue060'),
gms_article('\uef42'),
gms_aspect_ratio('\ue85b'),
gms_assessment('\ue85c'),
gms_assignment('\ue85d'),
gms_assignment_ind('\ue85e'),
gms_assignment_late('\ue85f'),
gms_assignment_return('\ue860'),
gms_assignment_returned('\ue861'),
gms_assignment_turned_in('\ue862'),
gms_assistant('\ue39f'),
gms_assistant_photo('\ue3a0'),
gms_atm('\ue573'),
gms_attach_email('\uea5e'),
gms_attach_file('\ue226'),
gms_attach_money('\ue227'),
gms_attachment('\ue2bc'),
gms_attribution('\uefdb'),
gms_audiotrack('\ue3a1'),
gms_auto_delete('\uea4c'),
gms_autorenew('\ue863'),
gms_av_timer('\ue01b'),
gms_baby_changing_station('\uf19b'),
gms_backpack('\uf19c'),
gms_backspace('\ue14a'),
gms_backup('\ue864'),
gms_backup_table('\uef43'),
gms_ballot('\ue172'),
gms_bar_chart('\ue26b'),
gms_batch_prediction('\uf0f5'),
gms_bathtub('\uea41'),
gms_battery_alert('\ue19c'),
gms_battery_charging_full('\ue1a3'),
gms_battery_full('\ue1a4'),
gms_battery_std('\ue1a5'),
gms_battery_unknown('\ue1a6'),
gms_beach_access('\ueb3e'),
gms_bedtime('\uef44'),
gms_beenhere('\ue52d'),
gms_bento('\uf1f4'),
gms_bike_scooter('\uef45'),
gms_biotech('\uea3a'),
gms_block('\ue14b'),
gms_bluetooth('\ue1a7'),
gms_bluetooth_audio('\ue60f'),
gms_bluetooth_connected('\ue1a8'),
gms_bluetooth_disabled('\ue1a9'),
gms_bluetooth_searching('\ue1aa'),
gms_blur_circular('\ue3a2'),
gms_blur_linear('\ue3a3'),
gms_blur_off('\ue3a4'),
gms_blur_on('\ue3a5'),
gms_book('\ue865'),
gms_book_online('\uf217'),
gms_bookmark('\ue866'),
gms_bookmark_border('\ue867'),
gms_bookmark_outline('\ue867'),
gms_bookmarks('\ue98b'),
gms_border_all('\ue228'),
gms_border_bottom('\ue229'),
gms_border_clear('\ue22a'),
gms_border_horizontal('\ue22c'),
gms_border_inner('\ue22d'),
gms_border_left('\ue22e'),
gms_border_outer('\ue22f'),
gms_border_right('\ue230'),
gms_border_style('\ue231'),
gms_border_top('\ue232'),
gms_border_vertical('\ue233'),
gms_branding_watermark('\ue06b'),
gms_brightness_1('\ue3a6'),
gms_brightness_2('\ue3a7'),
gms_brightness_3('\ue3a8'),
gms_brightness_4('\ue3a9'),
gms_brightness_5('\ue3aa'),
gms_brightness_6('\ue3ab'),
gms_brightness_7('\ue3ac'),
gms_brightness_auto('\ue1ab'),
gms_brightness_high('\ue1ac'),
gms_brightness_low('\ue1ad'),
gms_brightness_medium('\ue1ae'),
gms_broken_image('\ue3ad'),
gms_browser_not_supported('\uef47'),
gms_brush('\ue3ae'),
gms_bubble_chart('\ue6dd'),
gms_bug_report('\ue868'),
gms_build('\ue869'),
gms_build_circle('\uef48'),
gms_burst_mode('\ue43c'),
gms_business('\ue0af'),
gms_business_center('\ueb3f'),
gms_cached('\ue86a'),
gms_cake('\ue7e9'),
gms_calculate('\uea5f'),
gms_calendar_today('\ue935'),
gms_calendar_view_day('\ue936'),
gms_call('\ue0b0'),
gms_call_end('\ue0b1'),
gms_call_made('\ue0b2'),
gms_call_merge('\ue0b3'),
gms_call_missed('\ue0b4'),
gms_call_missed_outgoing('\ue0e4'),
gms_call_received('\ue0b5'),
gms_call_split('\ue0b6'),
gms_call_to_action('\ue06c'),
gms_camera('\ue3af'),
gms_camera_alt('\ue3b0'),
gms_camera_enhance('\ue8fc'),
gms_camera_front('\ue3b1'),
gms_camera_rear('\ue3b2'),
gms_camera_roll('\ue3b3'),
gms_campaign('\uef49'),
gms_cancel('\ue5c9'),
gms_cancel_presentation('\ue0e9'),
gms_cancel_schedule_send('\uea39'),
gms_card_giftcard('\ue8f6'),
gms_card_membership('\ue8f7'),
gms_card_travel('\ue8f8'),
gms_carpenter('\uf1f8'),
gms_casino('\ueb40'),
gms_cast('\ue307'),
gms_cast_connected('\ue308'),
gms_cast_for_education('\uefec'),
gms_category('\ue574'),
gms_center_focus_strong('\ue3b4'),
gms_center_focus_weak('\ue3b5'),
gms_change_history('\ue86b'),
gms_charging_station('\uf19d'),
gms_chat('\ue0b7'),
gms_chat_bubble('\ue0ca'),
gms_chat_bubble_outline('\ue0cb'),
gms_check('\ue5ca'),
gms_check_box('\ue834'),
gms_check_box_outline_blank('\ue835'),
gms_check_circle('\ue86c'),
gms_check_circle_outline('\ue92d'),
gms_checkroom('\uf19e'),
gms_chevron_left('\ue5cb'),
gms_chevron_right('\ue5cc'),
gms_child_care('\ueb41'),
gms_child_friendly('\ueb42'),
gms_chrome_reader_mode('\ue86d'),
gms_class('\ue86e'),
gms_clean_hands('\uf21f'),
gms_cleaning_services('\uf0ff'),
gms_clear('\ue14c'),
gms_clear_all('\ue0b8'),
gms_close('\ue5cd'),
gms_close_fullscreen('\uf1cf'),
gms_closed_caption('\ue01c'),
gms_closed_caption_disabled('\uf1dc'),
gms_cloud('\ue2bd'),
gms_cloud_circle('\ue2be'),
gms_cloud_done('\ue2bf'),
gms_cloud_download('\ue2c0'),
gms_cloud_off('\ue2c1'),
gms_cloud_queue('\ue2c2'),
gms_cloud_upload('\ue2c3'),
gms_code('\ue86f'),
gms_collections('\ue3b6'),
gms_collections_bookmark('\ue431'),
gms_color_lens('\ue3b7'),
gms_colorize('\ue3b8'),
gms_comment('\ue0b9'),
gms_comment_bank('\uea4e'),
gms_commute('\ue940'),
gms_compare('\ue3b9'),
gms_compare_arrows('\ue915'),
gms_compass_calibration('\ue57c'),
gms_computer('\ue30a'),
gms_confirmation_num('\ue638'),
gms_confirmation_number('\ue638'),
gms_connect_without_contact('\uf223'),
gms_construction('\uea3c'),
gms_contact_mail('\ue0d0'),
gms_contact_page('\uf22e'),
gms_contact_phone('\ue0cf'),
gms_contact_support('\ue94c'),
gms_contactless('\uea71'),
gms_contacts('\ue0ba'),
gms_content_copy('\uf08a'),
gms_content_cut('\uf08b'),
gms_content_paste('\uf098'),
gms_control_camera('\ue074'),
gms_control_point('\ue3ba'),
gms_control_point_duplicate('\ue3bb'),
gms_copy('\uf08a'),
gms_copyright('\ue90c'),
gms_coronavirus('\uf221'),
gms_corporate_fare('\uf1d0'),
gms_countertops('\uf1f7'),
gms_create('\ue150'),
gms_create_new_folder('\ue2cc'),
gms_credit_card('\ue870'),
gms_crop('\ue3be'),
gms_crop_16_9('\ue3bc'),
gms_crop_3_2('\ue3bd'),
gms_crop_5_4('\ue3bf'),
gms_crop_7_5('\ue3c0'),
gms_crop_din('\ue3c1'),
gms_crop_free('\ue3c2'),
gms_crop_landscape('\ue3c3'),
gms_crop_original('\ue3c4'),
gms_crop_portrait('\ue3c5'),
gms_crop_rotate('\ue437'),
gms_crop_square('\ue3c6'),
gms_cut('\uf08b'),
gms_dashboard('\ue871'),
gms_data_usage('\ue1af'),
gms_date_range('\ue916'),
gms_deck('\uea42'),
gms_dehaze('\ue3c7'),
gms_delete('\ue872'),
gms_delete_forever('\ue92b'),
gms_delete_outline('\ue92e'),
gms_delete_sweep('\ue16c'),
gms_departure_board('\ue576'),
gms_description('\ue873'),
gms_design_services('\uf10a'),
gms_desktop_access_disabled('\ue99d'),
gms_desktop_mac('\ue30b'),
gms_desktop_windows('\ue30c'),
gms_details('\ue3c8'),
gms_developer_board('\ue30d'),
gms_developer_mode('\ue1b0'),
gms_device_hub('\ue335'),
gms_device_unknown('\ue339'),
gms_devices('\ue1b1'),
gms_devices_other('\ue337'),
gms_dialer_sip('\ue0bb'),
gms_dialpad('\ue0bc'),
gms_directions('\ue52e'),
gms_directions_bike('\ue52f'),
gms_directions_boat('\ue532'),
gms_directions_bus('\ue530'),
gms_directions_car('\ue531'),
gms_directions_ferry('\ue532'),
gms_directions_off('\uf10f'),
gms_directions_railway('\ue534'),
gms_directions_run('\ue566'),
gms_directions_subway('\ue533'),
gms_directions_train('\ue534'),
gms_directions_transit('\ue535'),
gms_directions_walk('\ue536'),
gms_disabled_by_default('\uf230'),
gms_disc_full('\ue610'),
gms_dns('\ue875'),
gms_do_disturb('\uf08c'),
gms_do_disturb_alt('\uf08d'),
gms_do_disturb_off('\uf08e'),
gms_do_disturb_on('\uf08f'),
gms_do_not_step('\uf19f'),
gms_do_not_touch('\uf1b0'),
gms_dock('\ue30e'),
gms_domain('\ue7ee'),
gms_domain_disabled('\ue0ef'),
gms_domain_verification('\uef4c'),
gms_done('\ue876'),
gms_done_all('\ue877'),
gms_done_outline('\ue92f'),
gms_donut_large('\ue917'),
gms_donut_small('\ue918'),
gms_double_arrow('\uea50'),
gms_download('\uf090'),
gms_download_done('\uf091'),
gms_drafts('\ue151'),
gms_drag_handle('\ue25d'),
gms_drag_indicator('\ue945'),
gms_drive_eta('\ue613'),
gms_dry('\uf1b3'),
gms_duo('\ue9a5'),
gms_dvr('\ue1b2'),
gms_dynamic_feed('\uea14'),
gms_dynamic_form('\uf1bf'),
gms_east('\uf1df'),
gms_eco('\uea35'),
gms_edit('\ue3c9'),
gms_edit_attributes('\ue578'),
gms_edit_location('\ue568'),
gms_edit_road('\uef4d'),
gms_eject('\ue8fb'),
gms_elderly('\uf21a'),
gms_electric_bike('\ueb1b'),
gms_electric_car('\ueb1c'),
gms_electric_moped('\ueb1d'),
gms_electric_rickshaw('\ueb1e'),
gms_electric_scooter('\ueb1f'),
gms_electrical_services('\uf102'),
gms_elevator('\uf1a0'),
gms_email('\ue0be'),
gms_emoji_emotions('\uea22'),
gms_emoji_events('\uea23'),
gms_emoji_flags('\uea1a'),
gms_emoji_food_beverage('\uea1b'),
gms_emoji_nature('\uea1c'),
gms_emoji_objects('\uea24'),
gms_emoji_people('\uea1d'),
gms_emoji_symbols('\uea1e'),
gms_emoji_transportation('\uea1f'),
gms_engineering('\uea3d'),
gms_enhance_photo_translate('\ue8fc'),
gms_enhanced_encryption('\ue63f'),
gms_equalizer('\ue01d'),
gms_error('\ue000'),
gms_error_outline('\ue001'),
gms_escalator('\uf1a1'),
gms_escalator_warning('\uf1ac'),
gms_euro('\uea15'),
gms_euro_symbol('\ue926'),
gms_ev_station('\ue56d'),
gms_event('\ue878'),
gms_event_available('\ue614'),
gms_event_busy('\ue615'),
gms_event_note('\ue616'),
gms_event_seat('\ue903'),
gms_exit_to_app('\ue879'),
gms_expand_less('\ue5ce'),
gms_expand_more('\ue5cf'),
gms_explicit('\ue01e'),
gms_explore('\ue87a'),
gms_explore_off('\ue9a8'),
gms_exposure('\ue3ca'),
gms_exposure_minus_1('\ue3cb'),
gms_exposure_minus_2('\ue3cc'),
gms_exposure_neg_1('\ue3cb'),
gms_exposure_neg_2('\ue3cc'),
gms_exposure_plus_1('\ue3cd'),
gms_exposure_plus_2('\ue3ce'),
gms_exposure_zero('\ue3cf'),
gms_extension('\ue87b'),
gms_face('\ue87c'),
gms_face_unlock('\uf008'),
gms_facebook('\uf234'),
gms_fact_check('\uf0c5'),
gms_family_restroom('\uf1a2'),
gms_fast_forward('\ue01f'),
gms_fast_rewind('\ue020'),
gms_fastfood('\ue57a'),
gms_favorite('\ue87d'),
gms_favorite_border('\ue87e'),
gms_favorite_outline('\ue87e'),
gms_featured_play_list('\ue06d'),
gms_featured_video('\ue06e'),
gms_feedback('\ue87f'),
gms_fence('\uf1f6'),
gms_fiber_dvr('\ue05d'),
gms_fiber_manual_record('\ue061'),
gms_fiber_new('\ue05e'),
gms_fiber_pin('\ue06a'),
gms_fiber_smart_record('\ue062'),
gms_file_copy('\ue173'),
gms_filter('\ue3d3'),
gms_filter_1('\ue3d0'),
gms_filter_2('\ue3d1'),
gms_filter_3('\ue3d2'),
gms_filter_4('\ue3d4'),
gms_filter_5('\ue3d5'),
gms_filter_6('\ue3d6'),
gms_filter_7('\ue3d7'),
gms_filter_8('\ue3d8'),
gms_filter_9('\ue3d9'),
gms_filter_9_plus('\ue3da'),
gms_filter_alt('\uef4f'),
gms_filter_b_and_w('\ue3db'),
gms_filter_center_focus('\ue3dc'),
gms_filter_drama('\ue3dd'),
gms_filter_frames('\ue3de'),
gms_filter_hdr('\ue3df'),
gms_filter_list('\ue152'),
gms_filter_none('\ue3e0'),
gms_filter_tilt_shift('\ue3e2'),
gms_filter_vintage('\ue3e3'),
gms_find_in_page('\ue880'),
gms_find_replace('\ue881'),
gms_fingerprint('\ue90d'),
gms_fire_extinguisher('\uf1d8'),
gms_fireplace('\uea43'),
gms_first_page('\ue5dc'),
gms_fitness_center('\ueb43'),
gms_flag('\ue153'),
gms_flaky('\uef50'),
gms_flare('\ue3e4'),
gms_flash_auto('\ue3e5'),
gms_flash_off('\ue3e6'),
gms_flash_on('\ue3e7'),
gms_flight('\ue539'),
gms_flight_land('\ue904'),
gms_flight_takeoff('\ue905'),
gms_flip('\ue3e8'),
gms_flip_camera_android('\uea37'),
gms_flip_camera_ios('\uea38'),
gms_flip_to_back('\ue882'),
gms_flip_to_front('\ue883'),
gms_folder('\ue2c7'),
gms_folder_open('\ue2c8'),
gms_folder_shared('\ue2c9'),
gms_folder_special('\ue617'),
gms_follow_the_signs('\uf222'),
gms_font_download('\ue167'),
gms_food_bank('\uf1f2'),
gms_format_align_center('\ue234'),
gms_format_align_justify('\ue235'),
gms_format_align_left('\ue236'),
gms_format_align_right('\ue237'),
gms_format_bold('\ue238'),
gms_format_clear('\ue239'),
gms_format_color_reset('\ue23b'),
gms_format_indent_decrease('\ue23d'),
gms_format_indent_increase('\ue23e'),
gms_format_italic('\ue23f'),
gms_format_line_spacing('\ue240'),
gms_format_list_bulleted('\ue241'),
gms_format_list_numbered('\ue242'),
gms_format_list_numbered_rtl('\ue267'),
gms_format_paint('\ue243'),
gms_format_quote('\ue244'),
gms_format_shapes('\ue25e'),
gms_format_size('\ue245'),
gms_format_strikethrough('\ue246'),
gms_format_textdirection_l_to_r('\ue247'),
gms_format_textdirection_r_to_l('\ue248'),
gms_format_underline('\ue249'),
gms_format_underlined('\ue249'),
gms_forum('\ue0bf'),
gms_forward('\ue154'),
gms_forward_10('\ue056'),
gms_forward_30('\ue057'),
gms_forward_5('\ue058'),
gms_forward_to_inbox('\uf187'),
gms_foundation('\uf200'),
gms_free_breakfast('\ueb44'),
gms_fullscreen('\ue5d0'),
gms_fullscreen_exit('\ue5d1'),
gms_functions('\ue24a'),
gms_g_translate('\ue927'),
gms_gamepad('\ue30f'),
gms_games('\ue021'),
gms_gavel('\ue90e'),
gms_gesture('\ue155'),
gms_get_app('\ue884'),
gms_gif('\ue908'),
gms_golf_course('\ueb45'),
gms_gps_fixed('\ue1b3'),
gms_gps_not_fixed('\ue1b4'),
gms_gps_off('\ue1b5'),
gms_grade('\ue885'),
gms_gradient('\ue3e9'),
gms_grading('\uea4f'),
gms_grain('\ue3ea'),
gms_graphic_eq('\ue1b8'),
gms_grass('\uf205'),
gms_grid_off('\ue3eb'),
gms_grid_on('\ue3ec'),
gms_group('\ue7ef'),
gms_group_add('\ue7f0'),
gms_group_work('\ue886'),
gms_groups('\uf233'),
gms_handyman('\uf10b'),
gms_hd('\ue052'),
gms_hdr_off('\ue3ed'),
gms_hdr_on('\ue3ee'),
gms_hdr_strong('\ue3f1'),
gms_hdr_weak('\ue3f2'),
gms_headset('\ue310'),
gms_headset_mic('\ue311'),
gms_healing('\ue3f3'),
gms_hearing('\ue023'),
gms_hearing_disabled('\uf104'),
gms_height('\uea16'),
gms_help('\ue887'),
gms_help_center('\uf1c0'),
gms_help_outline('\ue8fd'),
gms_high_quality('\ue024'),
gms_highlight('\ue25f'),
gms_highlight_alt('\uef52'),
gms_highlight_off('\ue888'),
gms_highlight_remove('\ue888'),
gms_history('\ue889'),
gms_history_edu('\uea3e'),
gms_history_toggle_off('\uf17d'),
gms_home('\ue88a'),
gms_home_repair_service('\uf100'),
gms_home_work('\uea09'),
gms_horizontal_distribute('\ue014'),
gms_horizontal_rule('\uf108'),
gms_horizontal_split('\ue947'),
gms_hot_tub('\ueb46'),
gms_hotel('\ue53a'),
gms_hourglass_bottom('\uea5c'),
gms_hourglass_disabled('\uef53'),
gms_hourglass_empty('\ue88b'),
gms_hourglass_full('\ue88c'),
gms_hourglass_top('\uea5b'),
gms_house('\uea44'),
gms_house_siding('\uf202'),
gms_how_to_reg('\ue174'),
gms_how_to_vote('\ue175'),
gms_http('\ue902'),
gms_https('\ue88d'),
gms_hvac('\uf10e'),
gms_image('\ue3f4'),
gms_image_aspect_ratio('\ue3f5'),
gms_image_not_supported('\uf116'),
gms_image_search('\ue43f'),
gms_import_contacts('\ue0e0'),
gms_import_export('\ue0c3'),
gms_important_devices('\ue912'),
gms_inbox('\ue156'),
gms_indeterminate_check_box('\ue909'),
gms_info('\ue88e'),
gms_info_outline('\ue88f'),
gms_input('\ue890'),
gms_insert_chart('\ue24b'),
gms_insert_chart_outlined('\ue26a'),
gms_insert_comment('\ue24c'),
gms_insert_drive_file('\ue24d'),
gms_insert_emoticon('\ue24e'),
gms_insert_invitation('\ue24f'),
gms_insert_link('\ue250'),
gms_insert_photo('\ue251'),
gms_insights('\uf092'),
gms_integration_instructions('\uef54'),
gms_invert_colors('\ue891'),
gms_invert_colors_off('\ue0c4'),
gms_invert_colors_on('\ue891'),
gms_iso('\ue3f6'),
gms_keyboard('\ue312'),
gms_keyboard_arrow_down('\ue313'),
gms_keyboard_arrow_left('\ue314'),
gms_keyboard_arrow_right('\ue315'),
gms_keyboard_arrow_up('\ue316'),
gms_keyboard_backspace('\ue317'),
gms_keyboard_capslock('\ue318'),
gms_keyboard_control('\ue5d3'),
gms_keyboard_hide('\ue31a'),
gms_keyboard_return('\ue31b'),
gms_keyboard_tab('\ue31c'),
gms_keyboard_voice('\ue31d'),
gms_king_bed('\uea45'),
gms_kitchen('\ueb47'),
gms_label('\ue892'),
gms_label_important('\ue937'),
gms_label_important_outline('\ue948'),
gms_label_off('\ue9b6'),
gms_label_outline('\ue893'),
gms_landscape('\ue3f7'),
gms_language('\ue894'),
gms_laptop('\ue31e'),
gms_laptop_chromebook('\ue31f'),
gms_laptop_mac('\ue320'),
gms_laptop_windows('\ue321'),
gms_last_page('\ue5dd'),
gms_launch('\ue895'),
gms_layers('\ue53b'),
gms_layers_clear('\ue53c'),
gms_leaderboard('\uf20c'),
gms_leak_add('\ue3f8'),
gms_leak_remove('\ue3f9'),
gms_leave_bags_at_home('\uf23b'),
gms_legend_toggle('\uf11b'),
gms_lens('\ue3fa'),
gms_library_add('\ue02e'),
gms_library_add_check('\ue9b7'),
gms_library_books('\ue02f'),
gms_library_music('\ue030'),
gms_lightbulb_outline('\ue90f'),
gms_line_style('\ue919'),
gms_line_weight('\ue91a'),
gms_linear_scale('\ue260'),
gms_link('\ue157'),
gms_link_off('\ue16f'),
gms_linked_camera('\ue438'),
gms_list('\ue896'),
gms_list_alt('\ue0ee'),
gms_live_help('\ue0c6'),
gms_live_tv('\ue639'),
gms_local_activity('\ue53f'),
gms_local_airport('\ue53d'),
gms_local_atm('\ue53e'),
gms_local_attraction('\ue53f'),
gms_local_bar('\ue540'),
gms_local_cafe('\ue541'),
gms_local_car_wash('\ue542'),
gms_local_convenience_store('\ue543'),
gms_local_dining('\ue556'),
gms_local_drink('\ue544'),
gms_local_fire_department('\uef55'),
gms_local_florist('\ue545'),
gms_local_gas_station('\ue546'),
gms_local_grocery_store('\ue547'),
gms_local_hospital('\ue548'),
gms_local_hotel('\ue549'),
gms_local_laundry_service('\ue54a'),
gms_local_library('\ue54b'),
gms_local_mall('\ue54c'),
gms_local_movies('\ue54d'),
gms_local_offer('\ue54e'),
gms_local_parking('\ue54f'),
gms_local_pharmacy('\ue550'),
gms_local_phone('\ue551'),
gms_local_pizza('\ue552'),
gms_local_play('\ue553'),
gms_local_police('\uef56'),
gms_local_post_office('\ue554'),
gms_local_print_shop('\ue555'),
gms_local_printshop('\ue555'),
gms_local_restaurant('\ue556'),
gms_local_see('\ue557'),
gms_local_shipping('\ue558'),
gms_local_taxi('\ue559'),
gms_location_city('\ue7f1'),
gms_location_disabled('\ue1b6'),
gms_location_history('\ue55a'),
gms_location_off('\ue0c7'),
gms_location_on('\ue0c8'),
gms_location_searching('\ue1b7'),
gms_lock('\ue897'),
gms_lock_open('\ue898'),
gms_lock_outline('\ue899'),
gms_login('\uea77'),
gms_looks('\ue3fc'),
gms_looks_3('\ue3fb'),
gms_looks_4('\ue3fd'),
gms_looks_5('\ue3fe'),
gms_looks_6('\ue3ff'),
gms_looks_one('\ue400'),
gms_looks_two('\ue401'),
gms_loop('\ue028'),
gms_loupe('\ue402'),
gms_low_priority('\ue16d'),
gms_loyalty('\ue89a'),
gms_luggage('\uf235'),
gms_mail('\ue158'),
gms_mail_outline('\ue0e1'),
gms_map('\ue55b'),
gms_maps_ugc('\uef58'),
gms_mark_chat_read('\uf18b'),
gms_mark_chat_unread('\uf189'),
gms_mark_email_read('\uf18c'),
gms_mark_email_unread('\uf18a'),
gms_markunread('\ue159'),
gms_markunread_mailbox('\ue89b'),
gms_masks('\uf218'),
gms_maximize('\ue930'),
gms_mediation('\uefa7'),
gms_medical_services('\uf109'),
gms_meeting_room('\ueb4f'),
gms_memory('\ue322'),
gms_menu('\ue5d2'),
gms_menu_book('\uea19'),
gms_menu_open('\ue9bd'),
gms_merge_type('\ue252'),
gms_message('\ue0c9'),
gms_messenger('\ue0ca'),
gms_messenger_outline('\ue0cb'),
gms_mic('\ue029'),
gms_mic_none('\ue02a'),
gms_mic_off('\ue02b'),
gms_microwave('\uf204'),
gms_military_tech('\uea3f'),
gms_minimize('\ue931'),
gms_miscellaneous_services('\uf10c'),
gms_missed_video_call('\ue073'),
gms_mms('\ue618'),
gms_mobile_friendly('\ue200'),
gms_mobile_off('\ue201'),
gms_mobile_screen_share('\ue0e7'),
gms_mode('\uf097'),
gms_mode_comment('\ue253'),
gms_model_training('\uf0cf'),
gms_monetization_on('\ue263'),
gms_money('\ue57d'),
gms_money_off('\ue25c'),
gms_money_off_csred('\uf038'),
gms_monochrome_photos('\ue403'),
gms_mood('\ue7f2'),
gms_mood_bad('\ue7f3'),
gms_moped('\ueb28'),
gms_more('\ue619'),
gms_more_horiz('\ue5d3'),
gms_more_time('\uea5d'),
gms_more_vert('\ue5d4'),
gms_motion_photos_on('\ue9c1'),
gms_motion_photos_pause('\uf227'),
gms_motion_photos_paused('\ue9c2'),
gms_motorcycle('\ue91b'),
gms_mouse('\ue323'),
gms_move_to_inbox('\ue168'),
gms_movie('\ue02c'),
gms_movie_creation('\ue404'),
gms_movie_filter('\ue43a'),
gms_multiline_chart('\ue6df'),
gms_multiple_stop('\uf1b9'),
gms_multitrack_audio('\ue1b8'),
gms_museum('\uea36'),
gms_music_note('\ue405'),
gms_music_off('\ue440'),
gms_music_video('\ue063'),
gms_my_library_add('\ue02e'),
gms_my_library_books('\ue02f'),
gms_my_library_music('\ue030'),
gms_my_location('\ue55c'),
gms_nat('\uef5c'),
gms_nature('\ue406'),
gms_nature_people('\ue407'),
gms_navigate_before('\ue408'),
gms_navigate_next('\ue409'),
gms_navigation('\ue55d'),
gms_near_me('\ue569'),
gms_near_me_disabled('\uf1ef'),
gms_network_check('\ue640'),
gms_network_locked('\ue61a'),
gms_new_releases('\ue031'),
gms_next_plan('\uef5d'),
gms_next_week('\ue16a'),
gms_nfc('\ue1bb'),
gms_night_shelter('\uf1f1'),
gms_nights_stay('\uea46'),
gms_no_backpack('\uf237'),
gms_no_cell('\uf1a4'),
gms_no_drinks('\uf1a5'),
gms_no_encryption('\ue641'),
gms_no_encryption_gmailerrorred('\uf03f'),
gms_no_flash('\uf1a6'),
gms_no_food('\uf1a7'),
gms_no_luggage('\uf23b'),
gms_no_meals('\uf1d6'),
gms_no_meeting_room('\ueb4e'),
gms_no_photography('\uf1a8'),
gms_no_sim('\ue0cc'),
gms_no_stroller('\uf1af'),
gms_no_transfer('\uf1d5'),
gms_north('\uf1e0'),
gms_north_east('\uf1e1'),
gms_north_west('\uf1e2'),
gms_not_accessible('\uf0fe'),
gms_not_interested('\ue033'),
gms_not_listed_location('\ue575'),
gms_not_started('\uf0d1'),
gms_note('\ue06f'),
gms_note_add('\ue89c'),
gms_notes('\ue26c'),
gms_notification_important('\ue004'),
gms_notifications('\ue7f4'),
gms_notifications_active('\ue7f7'),
gms_notifications_none('\ue7f5'),
gms_notifications_off('\ue7f6'),
gms_notifications_on('\ue7f7'),
gms_notifications_paused('\ue7f8'),
gms_now_wallpaper('\ue1bc'),
gms_now_widgets('\ue1bd'),
gms_offline_bolt('\ue932'),
gms_offline_pin('\ue90a'),
gms_ondemand_video('\ue63a'),
gms_online_prediction('\uf0eb'),
gms_opacity('\ue91c'),
gms_open_in_browser('\ue89d'),
gms_open_in_full('\uf1ce'),
gms_open_in_new('\ue89e'),
gms_open_with('\ue89f'),
gms_outbond('\uf228'),
gms_outdoor_grill('\uea47'),
gms_outlet('\uf1d4'),
gms_outlined_flag('\ue16e'),
gms_pages('\ue7f9'),
gms_pageview('\ue8a0'),
gms_palette('\ue40a'),
gms_pan_tool('\ue925'),
gms_panorama('\ue40b'),
gms_panorama_fish_eye('\ue40c'),
gms_panorama_fisheye('\ue40c'),
gms_panorama_horizontal('\ue40d'),
gms_panorama_vertical('\ue40e'),
gms_panorama_wide_angle('\ue40f'),
gms_party_mode('\ue7fa'),
gms_paste('\uf098'),
gms_pause('\ue034'),
gms_pause_circle_filled('\ue035'),
gms_pause_circle_outline('\ue036'),
gms_pause_presentation('\ue0ea'),
gms_payment('\ue8a1'),
gms_payments('\uef63'),
gms_pedal_bike('\ueb29'),
gms_pending('\uef64'),
gms_pending_actions('\uf1bb'),
gms_people('\ue7fb'),
gms_people_alt('\uea21'),
gms_people_outline('\ue7fc'),
gms_perm_camera_mic('\ue8a2'),
gms_perm_contact_cal('\ue8a3'),
gms_perm_contact_calendar('\ue8a3'),
gms_perm_data_setting('\ue8a4'),
gms_perm_device_info('\ue8a5'),
gms_perm_device_information('\ue8a5'),
gms_perm_identity('\ue8a6'),
gms_perm_media('\ue8a7'),
gms_perm_phone_msg('\ue8a8'),
gms_perm_scan_wifi('\ue8a9'),
gms_person('\ue7fd'),
gms_person_add('\ue7fe'),
gms_person_add_alt_1('\uef65'),
gms_person_add_disabled('\ue9cb'),
gms_person_outline('\ue7ff'),
gms_person_pin('\ue55a'),
gms_person_pin_circle('\ue56a'),
gms_person_remove('\uef66'),
gms_person_remove_alt_1('\uef67'),
gms_person_search('\uf106'),
gms_personal_video('\ue63b'),
gms_pest_control('\uf0fa'),
gms_pest_control_rodent('\uf0fd'),
gms_pets('\ue91d'),
gms_phone('\ue0cd'),
gms_phone_android('\ue324'),
gms_phone_bluetooth_speaker('\ue61b'),
gms_phone_callback('\ue649'),
gms_phone_disabled('\ue9cc'),
gms_phone_enabled('\ue9cd'),
gms_phone_forwarded('\ue61c'),
gms_phone_in_talk('\ue61d'),
gms_phone_iphone('\ue325'),
gms_phone_locked('\ue61e'),
gms_phone_missed('\ue61f'),
gms_phone_paused('\ue620'),
gms_phonelink('\ue326'),
gms_phonelink_erase('\ue0db'),
gms_phonelink_lock('\ue0dc'),
gms_phonelink_off('\ue327'),
gms_phonelink_ring('\ue0dd'),
gms_phonelink_setup('\ue0de'),
gms_photo('\ue410'),
gms_photo_album('\ue411'),
gms_photo_camera('\ue412'),
gms_photo_filter('\ue43b'),
gms_photo_library('\ue413'),
gms_photo_size_select_actual('\ue432'),
gms_photo_size_select_large('\ue433'),
gms_photo_size_select_small('\ue434'),
gms_picture_as_pdf('\ue415'),
gms_picture_in_picture('\ue8aa'),
gms_picture_in_picture_alt('\ue911'),
gms_pie_chart('\ue6c4'),
gms_pie_chart_outline('\uf044'),
gms_pin_drop('\ue55e'),
gms_place('\ue55f'),
gms_plagiarism('\uea5a'),
gms_play_arrow('\ue037'),
gms_play_circle_fill('\ue038'),
gms_play_circle_filled('\ue038'),
gms_play_circle_outline('\ue039'),
gms_play_for_work('\ue906'),
gms_playlist_add('\ue03b'),
gms_playlist_add_check('\ue065'),
gms_playlist_play('\ue05f'),
gms_plumbing('\uf107'),
gms_plus_one('\ue800'),
gms_point_of_sale('\uf17e'),
gms_policy('\uea17'),
gms_poll('\ue801'),
gms_polymer('\ue8ab'),
gms_pool('\ueb48'),
gms_portable_wifi_off('\ue0ce'),
gms_portrait('\ue416'),
gms_post_add('\uea20'),
gms_power('\ue63c'),
gms_power_input('\ue336'),
gms_power_off('\ue646'),
gms_power_settings_new('\ue8ac'),
gms_precision_manufacturing('\uf049'),
gms_pregnant_woman('\ue91e'),
gms_present_to_all('\ue0df'),
gms_preview('\uf1c5'),
gms_print('\ue8ad'),
gms_print_disabled('\ue9cf'),
gms_priority_high('\ue645'),
gms_privacy_tip('\uf0dc'),
gms_psychology('\uea4a'),
gms_public('\ue80b'),
gms_public_off('\uf1ca'),
gms_publish('\ue255'),
gms_published_with_changes('\uf232'),
gms_push_pin('\uf10d'),
gms_qr_code('\uef6b'),
gms_qr_code_2('\ue00a'),
gms_qr_code_scanner('\uf206'),
gms_query_builder('\ue8ae'),
gms_question_answer('\ue8af'),
gms_queue('\ue03c'),
gms_queue_music('\ue03d'),
gms_queue_play_next('\ue066'),
gms_quick_contacts_dialer('\ue0cf'),
gms_quick_contacts_mail('\ue0d0'),
gms_quickreply('\uef6c'),
gms_radio('\ue03e'),
gms_radio_button_checked('\ue837'),
gms_radio_button_off('\ue836'),
gms_radio_button_on('\ue837'),
gms_radio_button_unchecked('\ue836'),
gms_rate_review('\ue560'),
gms_read_more('\uef6d'),
gms_receipt('\ue8b0'),
gms_receipt_long('\uef6e'),
gms_recent_actors('\ue03f'),
gms_record_voice_over('\ue91f'),
gms_redeem('\ue8b1'),
gms_redo('\ue15a'),
gms_reduce_capacity('\uf21c'),
gms_refresh('\ue5d5'),
gms_remove('\ue15b'),
gms_remove_circle('\ue15c'),
gms_remove_circle_outline('\ue15d'),
gms_remove_from_queue('\ue067'),
gms_remove_red_eye('\ue417'),
gms_remove_shopping_cart('\ue928'),
gms_reorder('\ue8fe'),
gms_repeat('\ue040'),
gms_repeat_one('\ue041'),
gms_replay('\ue042'),
gms_replay_10('\ue059'),
gms_replay_30('\ue05a'),
gms_replay_5('\ue05b'),
gms_reply('\ue15e'),
gms_reply_all('\ue15f'),
gms_report('\ue160'),
gms_report_gmailerrorred('\uf052'),
gms_report_off('\ue170'),
gms_report_problem('\ue8b2'),
gms_request_page('\uf22c'),
gms_request_quote('\uf1b6'),
gms_restaurant('\ue56c'),
gms_restaurant_menu('\ue561'),
gms_restore('\ue8b3'),
gms_restore_from_trash('\ue938'),
gms_restore_page('\ue929'),
gms_rice_bowl('\uf1f5'),
gms_ring_volume('\ue0d1'),
gms_roofing('\uf201'),
gms_room('\ue8b4'),
gms_room_preferences('\uf1b8'),
gms_room_service('\ueb49'),
gms_rotate_90_degrees_ccw('\ue418'),
gms_rotate_left('\ue419'),
gms_rotate_right('\ue41a'),
gms_rounded_corner('\ue920'),
gms_router('\ue328'),
gms_rowing('\ue921'),
gms_rss_feed('\ue0e5'),
gms_rule('\uf1c2'),
gms_rule_folder('\uf1c9'),
gms_run_circle('\uef6f'),
gms_rv_hookup('\ue642'),
gms_sanitizer('\uf21d'),
gms_satellite('\ue562'),
gms_save('\ue161'),
gms_save_alt('\ue171'),
gms_scanner('\ue329'),
gms_scatter_plot('\ue268'),
gms_schedule('\ue8b5'),
gms_school('\ue80c'),
gms_science('\uea4b'),
gms_score('\ue269'),
gms_screen_lock_landscape('\ue1be'),
gms_screen_lock_portrait('\ue1bf'),
gms_screen_lock_rotation('\ue1c0'),
gms_screen_rotation('\ue1c1'),
gms_screen_share('\ue0e2'),
gms_sd_card('\ue623'),
gms_sd_card_alert('\uf057'),
gms_sd_storage('\ue1c2'),
gms_search('\ue8b6'),
gms_search_off('\uea76'),
gms_security('\ue32a'),
gms_select_all('\ue162'),
gms_self_improvement('\uea78'),
gms_send('\ue163'),
gms_sensor_door('\uf1b5'),
gms_sensor_window('\uf1b4'),
gms_sentiment_dissatisfied('\ue811'),
gms_sentiment_satisfied('\ue813'),
gms_sentiment_satisfied_alt('\ue0ed'),
gms_sentiment_very_dissatisfied('\ue814'),
gms_sentiment_very_satisfied('\ue815'),
gms_set_meal('\uf1ea'),
gms_settings('\ue8b8'),
gms_settings_applications('\ue8b9'),
gms_settings_backup_restore('\ue8ba'),
gms_settings_bluetooth('\ue8bb'),
gms_settings_brightness('\ue8bd'),
gms_settings_cell('\ue8bc'),
gms_settings_display('\ue8bd'),
gms_settings_ethernet('\ue8be'),
gms_settings_input_antenna('\ue8bf'),
gms_settings_input_component('\ue8c0'),
gms_settings_input_composite('\ue8c1'),
gms_settings_input_hdmi('\ue8c2'),
gms_settings_input_svideo('\ue8c3'),
gms_settings_overscan('\ue8c4'),
gms_settings_phone('\ue8c5'),
gms_settings_power('\ue8c6'),
gms_settings_remote('\ue8c7'),
gms_settings_system_daydream('\ue1c3'),
gms_settings_voice('\ue8c8'),
gms_share('\ue80d'),
gms_shop('\ue8c9'),
gms_shop_two('\ue8ca'),
gms_shopping_bag('\uf1cc'),
gms_shopping_basket('\ue8cb'),
gms_shopping_cart('\ue8cc'),
gms_short_text('\ue261'),
gms_show_chart('\ue6e1'),
gms_shuffle('\ue043'),
gms_shutter_speed('\ue43d'),
gms_sick('\uf220'),
gms_signal_cellular_4_bar('\ue1c8'),
gms_signal_cellular_alt('\ue202'),
gms_signal_cellular_connected_no_internet_4_bar('\ue1cd'),
gms_signal_cellular_no_sim('\ue1ce'),
gms_signal_cellular_null('\ue1cf'),
gms_signal_cellular_off('\ue1d0'),
gms_signal_wifi_4_bar('\ue1d8'),
gms_signal_wifi_4_bar_lock('\ue1d9'),
gms_signal_wifi_off('\ue1da'),
gms_sim_card('\ue32b'),
gms_single_bed('\uea48'),
gms_skip_next('\ue044'),
gms_skip_previous('\ue045'),
gms_slideshow('\ue41b'),
gms_slow_motion_video('\ue068'),
gms_smart_button('\uf1c1'),
gms_smartphone('\ue32c'),
gms_smoke_free('\ueb4a'),
gms_smoking_rooms('\ueb4b'),
gms_sms('\ue625'),
gms_sms_failed('\ue626'),
gms_snippet_folder('\uf1c7'),
gms_snooze('\ue046'),
gms_soap('\uf1b2'),
gms_sort('\ue164'),
gms_sort_by_alpha('\ue053'),
gms_source('\uf1c4'),
gms_south('\uf1e3'),
gms_south_east('\uf1e4'),
gms_south_west('\uf1e5'),
gms_spa('\ueb4c'),
gms_space_bar('\ue256'),
gms_speaker('\ue32d'),
gms_speaker_group('\ue32e'),
gms_speaker_notes('\ue8cd'),
gms_speaker_notes_off('\ue92a'),
gms_speaker_phone('\ue0d2'),
gms_speed('\ue9e4'),
gms_spellcheck('\ue8ce'),
gms_sports('\uea30'),
gms_sports_bar('\uf1f3'),
gms_sports_baseball('\uea51'),
gms_sports_basketball('\uea26'),
gms_sports_cricket('\uea27'),
gms_sports_esports('\uea28'),
gms_sports_football('\uea29'),
gms_sports_golf('\uea2a'),
gms_sports_handball('\uea33'),
gms_sports_hockey('\uea2b'),
gms_sports_kabaddi('\uea34'),
gms_sports_mma('\uea2c'),
gms_sports_motorsports('\uea2d'),
gms_sports_rugby('\uea2e'),
gms_sports_soccer('\uea2f'),
gms_sports_tennis('\uea32'),
gms_sports_volleyball('\uea31'),
gms_square_foot('\uea49'),
gms_stacked_line_chart('\uf22b'),
gms_stairs('\uf1a9'),
gms_star('\ue838'),
gms_star_border('\ue83a'),
gms_star_border_purple500('\uf099'),
gms_star_half('\ue839'),
gms_star_outline('\uf06f'),
gms_star_purple500('\uf09a'),
gms_star_rate('\uf0ec'),
gms_stars('\ue8d0'),
gms_stay_current_landscape('\ue0d3'),
gms_stay_current_portrait('\ue0d4'),
gms_stay_primary_landscape('\ue0d5'),
gms_stay_primary_portrait('\ue0d6'),
gms_sticky_note_2('\uf1fc'),
gms_stop('\ue047'),
gms_stop_circle('\uef71'),
gms_stop_screen_share('\ue0e3'),
gms_storage('\ue1db'),
gms_store('\ue8d1'),
gms_store_mall_directory('\ue563'),
gms_storefront('\uea12'),
gms_straighten('\ue41c'),
gms_streetview('\ue56e'),
gms_strikethrough_s('\ue257'),
gms_stroller('\uf1ae'),
gms_style('\ue41d'),
gms_subdirectory_arrow_left('\ue5d9'),
gms_subdirectory_arrow_right('\ue5da'),
gms_subject('\ue8d2'),
gms_subscript('\uf111'),
gms_subscriptions('\ue064'),
gms_subtitles('\ue048'),
gms_subtitles_off('\uef72'),
gms_subway('\ue56f'),
gms_superscript('\uf112'),
gms_supervised_user_circle('\ue939'),
gms_supervisor_account('\ue8d3'),
gms_support('\uef73'),
gms_support_agent('\uf0e2'),
gms_surround_sound('\ue049'),
gms_swap_calls('\ue0d7'),
gms_swap_horiz('\ue8d4'),
gms_swap_horizontal_circle('\ue933'),
gms_swap_vert('\ue8d5'),
gms_swap_vert_circle('\ue8d6'),
gms_swap_vertical_circle('\ue8d6'),
gms_switch_camera('\ue41e'),
gms_switch_left('\uf1d1'),
gms_switch_right('\uf1d2'),
gms_switch_video('\ue41f'),
gms_sync('\ue627'),
gms_sync_alt('\uea18'),
gms_sync_disabled('\ue628'),
gms_sync_problem('\ue629'),
gms_system_update('\ue62a'),
gms_system_update_alt('\ue8d7'),
gms_system_update_tv('\ue8d7'),
gms_tab('\ue8d8'),
gms_tab_unselected('\ue8d9'),
gms_table_chart('\ue265'),
gms_table_rows('\uf101'),
gms_table_view('\uf1be'),
gms_tablet('\ue32f'),
gms_tablet_android('\ue330'),
gms_tablet_mac('\ue331'),
gms_tag_faces('\ue420'),
gms_tap_and_play('\ue62b'),
gms_tapas('\uf1e9'),
gms_terrain('\ue564'),
gms_text_fields('\ue262'),
gms_text_format('\ue165'),
gms_text_rotate_up('\ue93a'),
gms_text_rotate_vertical('\ue93b'),
gms_text_rotation_angledown('\ue93c'),
gms_text_rotation_angleup('\ue93d'),
gms_text_rotation_down('\ue93e'),
gms_text_rotation_none('\ue93f'),
gms_text_snippet('\uf1c6'),
gms_textsms('\ue0d8'),
gms_texture('\ue421'),
gms_theaters('\ue8da'),
gms_thermostat('\uf076'),
gms_thumb_down('\ue8db'),
gms_thumb_down_alt('\ue816'),
gms_thumb_up('\ue8dc'),
gms_thumb_up_alt('\ue817'),
gms_thumbs_up_down('\ue8dd'),
gms_time_to_leave('\ue62c'),
gms_timelapse('\ue422'),
gms_timeline('\ue922'),
gms_timer('\ue425'),
gms_timer_10('\ue423'),
gms_timer_3('\ue424'),
gms_timer_off('\ue426'),
gms_title('\ue264'),
gms_toc('\ue8de'),
gms_today('\ue8df'),
gms_toggle_off('\ue9f5'),
gms_toggle_on('\ue9f6'),
gms_toll('\ue8e0'),
gms_tonality('\ue427'),
gms_topic('\uf1c8'),
gms_touch_app('\ue913'),
gms_tour('\uef75'),
gms_toys('\ue332'),
gms_track_changes('\ue8e1'),
gms_traffic('\ue565'),
gms_train('\ue570'),
gms_tram('\ue571'),
gms_transfer_within_a_station('\ue572'),
gms_transform('\ue428'),
gms_transit_enterexit('\ue579'),
gms_translate('\ue8e2'),
gms_trending_down('\ue8e3'),
gms_trending_flat('\ue8e4'),
gms_trending_neutral('\ue8e4'),
gms_trending_up('\ue8e5'),
gms_trip_origin('\ue57b'),
gms_tty('\uf1aa'),
gms_tune('\ue429'),
gms_turned_in('\ue8e6'),
gms_turned_in_not('\ue8e7'),
gms_tv('\ue333'),
gms_tv_off('\ue647'),
gms_two_wheeler('\ue9f9'),
gms_umbrella('\uf1ad'),
gms_unarchive('\ue169'),
gms_undo('\ue166'),
gms_unfold_less('\ue5d6'),
gms_unfold_more('\ue5d7'),
gms_unpublished('\uf236'),
gms_unsubscribe('\ue0eb'),
gms_update('\ue923'),
gms_update_disabled('\ue075'),
gms_upgrade('\uf0fb'),
gms_upload('\uf09b'),
gms_usb('\ue1e0'),
gms_verified('\uef76'),
gms_verified_user('\ue8e8'),
gms_vertical_align_bottom('\ue258'),
gms_vertical_align_center('\ue259'),
gms_vertical_align_top('\ue25a'),
gms_vertical_distribute('\ue076'),
gms_vertical_split('\ue949'),
gms_vibration('\ue62d'),
gms_video_call('\ue070'),
gms_video_collection('\ue04a'),
gms_video_label('\ue071'),
gms_video_library('\ue04a'),
gms_video_settings('\uea75'),
gms_videocam('\ue04b'),
gms_videocam_off('\ue04c'),
gms_videogame_asset('\ue338'),
gms_view_agenda('\ue8e9'),
gms_view_array('\ue8ea'),
gms_view_carousel('\ue8eb'),
gms_view_column('\ue8ec'),
gms_view_comfortable('\ue42a'),
gms_view_comfy('\ue42a'),
gms_view_compact('\ue42b'),
gms_view_day('\ue8ed'),
gms_view_headline('\ue8ee'),
gms_view_list('\ue8ef'),
gms_view_module('\ue8f0'),
gms_view_quilt('\ue8f1'),
gms_view_sidebar('\uf114'),
gms_view_stream('\ue8f2'),
gms_view_week('\ue8f3'),
gms_vignette('\ue435'),
gms_visibility('\ue8f4'),
gms_visibility_off('\ue8f5'),
gms_voice_chat('\ue62e'),
gms_voice_over_off('\ue94a'),
gms_voicemail('\ue0d9'),
gms_volume_down('\ue04d'),
gms_volume_mute('\ue04e'),
gms_volume_off('\ue04f'),
gms_volume_up('\ue050'),
gms_vpn_key('\ue0da'),
gms_vpn_lock('\ue62f'),
gms_wallet_giftcard('\ue8f6'),
gms_wallet_membership('\ue8f7'),
gms_wallet_travel('\ue8f8'),
gms_wallpaper('\ue1bc'),
gms_warning('\ue002'),
gms_warning_amber('\uf083'),
gms_wash('\uf1b1'),
gms_watch('\ue334'),
gms_watch_later('\ue924'),
gms_water_damage('\uf203'),
gms_waves('\ue176'),
gms_wb_auto('\ue42c'),
gms_wb_cloudy('\ue42d'),
gms_wb_incandescent('\ue42e'),
gms_wb_iridescent('\ue436'),
gms_wb_sunny('\ue430'),
gms_wc('\ue63d'),
gms_web('\ue051'),
gms_web_asset('\ue069'),
gms_weekend('\ue16b'),
gms_west('\uf1e6'),
gms_whatshot('\ue80e'),
gms_wheelchair_pickup('\uf1ab'),
gms_where_to_vote('\ue177'),
gms_widgets('\ue1bd'),
gms_wifi('\ue63e'),
gms_wifi_calling('\uef77'),
gms_wifi_lock('\ue1e1'),
gms_wifi_off('\ue648'),
gms_wifi_protected_setup('\uf0fc'),
gms_wifi_tethering('\ue1e2'),
gms_wine_bar('\uf1e8'),
gms_work('\ue8f9'),
gms_work_off('\ue942'),
gms_work_outline('\ue943'),
gms_wrap_text('\ue25b'),
gms_wrong_location('\uef78'),
gms_wysiwyg('\uf1c3'),
gms_youtube_searched_for('\ue8fa'),
gms_zoom_in('\ue8ff'),
gms_zoom_out('\ue900'),
gms_zoom_out_map('\ue56b');
override val typeface: ITypeface by lazy { SharpGoogleMaterial }
}
}
| apache-2.0 | cae48f90345dad394f7e7caa0dcd2605 | 34.563313 | 98 | 0.533084 | 3.264514 | false | false | false | false |
Hexworks/snap | src/main/kotlin/org/codetome/snap/framework/SnapConfig.kt | 1 | 2674 | package org.codetome.snap.framework
import org.codetome.snap.adapter.InMemoryRepository
import org.codetome.snap.adapter.SparkRestServiceGenerator
import org.codetome.snap.adapter.parser.*
import org.codetome.snap.model.data.Schema
import org.codetome.snap.model.rest.RestService
import org.codetome.snap.service.impl.ParamChecker
import org.codetome.snap.service.impl.SnapService
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.io.File
@Configuration
open class SnapConfig {
@Value("\${descriptor:}")
lateinit var descriptor: String
lateinit var restService: RestService
@Bean fun descriptorFile(paramChecker: ParamChecker): File {
return paramChecker.checkDescriptor(descriptor)
}
@Bean
open fun restServiceGenerator() = SparkRestServiceGenerator()
@Bean
open fun paramChecker() = ParamChecker()
@Bean
open fun snapService() = SnapService(
restServiceGenerator = restServiceGenerator(),
markdownParser = markdownParser())
@Bean
open fun headerSegmentParser() = MarkdownHeaderSegmentParser()
@Bean
open fun descriptionSegmentParser() = MarkdownDescriptionSegmentParser()
@Bean
open fun segmentTypeAnalyzer() = MarkdownSegmentTypeAnalyzer()
@Bean
open fun schemaSegmentParser() = MarkdownSchemaSegmentParser(segmentTypeAnalyzer())
@Bean
open fun listSegmentParser() = MarkdownListSegmentParser()
@Bean
open fun restMethodSegmentParser() = MarkdownRestMethodSegmentParser(
segmentTypeAnalyzer = segmentTypeAnalyzer(),
headerSegmentParser = headerSegmentParser(),
descriptionSegmentParser = descriptionSegmentParser(),
listSegmentParser = listSegmentParser())
@Bean
open fun endpointSegmentParser() = MarkdownEndpointSegmentParser(
segmentTypeAnalyzer = segmentTypeAnalyzer(),
schemaSegmentParser = schemaSegmentParser(),
headerSegmentParser = headerSegmentParser(),
restMethodSegmentParser = restMethodSegmentParser(),
descriptionSegmentParser = descriptionSegmentParser())
@Bean
open fun markdownRootSegmentParser() = MarkdownRootSegmentParser(
headerSegmentParser = headerSegmentParser(),
descriptionSegmentParser = descriptionSegmentParser(),
endpointSegmentParser = endpointSegmentParser(),
segmentTypeAnalyzer = segmentTypeAnalyzer())
@Bean
open fun markdownParser() = MarkdownParser(markdownRootSegmentParser())
} | agpl-3.0 | d810c57f326f8b618117a28c4bd11814 | 33.294872 | 87 | 0.739716 | 5.446029 | false | false | false | false |
datafrost1997/GitterChat | app/src/main/java/com/devslopes/datafrost1997/gitterchat/Services/AuthService.kt | 1 | 6055 | package com.devslopes.datafrost1997.gitterchat.Services
import android.content.Context
import android.content.Intent
import android.support.v4.content.LocalBroadcastManager
import android.util.Log
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.devslopes.datafrost1997.gitterchat.Controller.App
import com.devslopes.datafrost1997.gitterchat.Utilities.*
import org.json.JSONException
import org.json.JSONObject
/**
* Created by datafrost1997 on 13/10/17.
*/
object AuthService {
// var isLoggedIn = false
// var userEmail = ""
// var authToken = ""
fun registerUser(email: String, password: String, complete: (Boolean) -> Unit) {
val jsonBody = JSONObject()
jsonBody.put("email",email)
jsonBody.put("password", password)
val requestBody = jsonBody.toString()
val registerRequest = object : StringRequest(Method.POST, URL_REGISTER, Response.Listener { response ->
complete(true)
}, Response.ErrorListener { error ->
Log.d("Error", "Could not register User: $error")
complete(false)
}) {
override fun getBodyContentType(): String {
return "application/json; charset=utf-8"
}
override fun getBody(): ByteArray {
return requestBody.toByteArray()
}
}
App.prefs.requestQueue.add(registerRequest)
}
fun loginUser( email: String, password: String, complete: (Boolean) -> Unit) {
val jsonBody = JSONObject()
jsonBody.put("email",email)
jsonBody.put("password", password)
val requestBody = jsonBody.toString()
val loginRequest = object : JsonObjectRequest(Method.POST, URL_LOGIN, null, Response.Listener { response ->
// Point where the JSON Object is parsed.
// println(response)
try {
App.prefs.userEmail = response.getString("user")
App.prefs.authToken = response.getString("token")
App.prefs.isLoggedIn = true
complete(true)
} catch (e: JSONException) {
Log.d("JSON", "EXC:" + e.localizedMessage)
complete(false)
}
}, Response.ErrorListener { error ->
// Point where the Error is dealt with.
Log.d("Error", "Could not login User: $error")
complete(false)
}) {
override fun getBodyContentType(): String {
return "application/json; charset=utf-8"
}
override fun getBody(): ByteArray {
return requestBody.toByteArray()
}
}
App.prefs.requestQueue.add(loginRequest)
}
fun createUser(name: String, email: String, avatarName: String, avatarColor: String, complete: (Boolean) -> Unit) {
val jsonBody = JSONObject()
jsonBody.put("name",name)
jsonBody.put("email", email)
jsonBody.put("avatarName", avatarName)
jsonBody.put("avatarColor", avatarColor)
val requestBody = jsonBody.toString()
val createRequest = object : JsonObjectRequest(Method.POST, URL_CREATE_USER, null, Response.Listener { response ->
try {
UserDataService.name = response.getString("name")
UserDataService.email = response.getString("email")
UserDataService.avatarName = response.getString("avatarName")
UserDataService.avatarColor = response.getString("avatarColor")
UserDataService.id = response.getString("_id")
complete(true)
} catch (e: JSONException) {
Log.d("JSON", "EXC " + e.localizedMessage)
complete(false)
}
}, Response.ErrorListener { error ->
Log.d("Error", "Could not add User: $error")
complete(false)
}) {
override fun getBodyContentType(): String {
return "application/json; charset=utf-8"
}
override fun getBody(): ByteArray {
return requestBody.toByteArray()
}
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String> ()
headers.put("Authorization", "Bearer ${App.prefs.authToken}")
return headers
}
}
App.prefs.requestQueue.add(createRequest)
}
fun findUserByEmail (context: Context, complete: (Boolean) -> Unit) {
var findUserRequest = object: JsonObjectRequest(Method.GET, "$URL_GET_USER${App.prefs.userEmail}", null, Response.Listener { response ->
try {
UserDataService.name = response.getString("name")
UserDataService.email = response.getString("email")
UserDataService.avatarName = response.getString("avatarName")
UserDataService.avatarColor = response.getString("avatarColor")
UserDataService.id = response.getString("_id")
val userDataChange = Intent(BROADCAST_USER_DATA_CHANGE)
LocalBroadcastManager.getInstance(context).sendBroadcast(userDataChange)
complete(true)
} catch (e: JSONException) {
Log.d("Json", "EXC: " + e.localizedMessage)
}
}, Response.ErrorListener { error ->
Log.d("Error", "Couldn't Find User")
complete(false)
}) {
override fun getBodyContentType(): String {
return "application/json; charset=utf-8"
}
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String> ()
headers.put("Authorization", "Bearer ${App.prefs.authToken}")
return headers
}
}
App.prefs.requestQueue.add(findUserRequest)
}
} | gpl-3.0 | 4f87dba37a15d57dfcd9f98bd01a11a1 | 36.614907 | 144 | 0.595871 | 4.867363 | false | false | false | false |
android/wear-os-samples | TimeText/timetext/src/main/java/com/example/android/wearable/timetext/TextViewWrapper.kt | 1 | 1815 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.wearable.timetext
import android.view.View
import android.widget.TextView
import androidx.wear.widget.CurvedTextView
/**
* A wrapper around a [TextView] like object, that may not actually extend [TextView] (like a [CurvedTextView]).
*/
interface TextViewWrapper {
val view: View
var text: CharSequence?
var textColor: Int
}
/**
* A [TextViewWrapper] wrapping a [CurvedTextView].
*/
class CurvedTextViewWrapper(
override val view: CurvedTextView
) : TextViewWrapper {
override var text: CharSequence?
get() = view.text
set(value) {
view.text = value?.toString().orEmpty()
}
override var textColor: Int
get() = view.textColor
set(value) {
view.textColor = value
}
}
/**
* A [TextViewWrapper] wrapping a [TextView].
*/
class NormalTextViewWrapper(
override val view: TextView
) : TextViewWrapper {
override var text: CharSequence?
get() = view.text
set(value) {
view.text = value
}
override var textColor: Int
get() = view.currentTextColor
set(value) {
view.setTextColor(value)
}
}
| apache-2.0 | f157f24915906530e0b8847807d5e672 | 26.089552 | 112 | 0.669421 | 4.240654 | false | false | false | false |
Kiskae/DiscordKt | implementation/src/main/kotlin/net/serverpeon/discord/internal/ws/data/inbound/Misc.kt | 1 | 3243 | package net.serverpeon.discord.internal.ws.data.inbound
import com.google.gson.annotations.SerializedName
import net.serverpeon.discord.internal.data.EventInput
import net.serverpeon.discord.internal.jsonmodels.*
import net.serverpeon.discord.model.*
interface Misc : Event {
data class UserUpdate(val self: SelfModel) : Misc {
override fun <T : EventInput<T>> accept(visitor: T, handler: EventInput.Handler<T>)
= handler.userUpdate(visitor, this)
}
data class Ready(val data: ReadyEventModel) : Misc {
override fun <T : EventInput<T>> accept(visitor: T, handler: EventInput.Handler<T>)
= handler.ready(visitor, this)
}
data class MembersChunk(val members: List<MemberModel>, val guild_id: DiscordId<Guild>) : Misc {
override fun <T : EventInput<T>> accept(visitor: T, handler: EventInput.Handler<T>)
= handler.guildMemberChunks(visitor, this)
}
data class Resumed(val heartbeat_interval: Long) : Misc {
override fun <T : EventInput<T>> accept(visitor: T, handler: EventInput.Handler<T>)
= handler.resumed(visitor, this)
}
data class TypingStart(val user_id: DiscordId<User>,
val timestamp: Long,
val channel_id: DiscordId<Channel>) : Misc {
override fun <T : EventInput<T>> accept(visitor: T, handler: EventInput.Handler<T>)
= handler.typingStart(visitor, this)
}
/**
* If the presence update is for a relationship instead of a guild member, 'roles' and 'guild_id' will be null
*/
data class PresenceUpdate(val user: UserRef,
val status: Status,
val roles: List<DiscordId<Role>>?,
val guild_id: DiscordId<Guild>?,
val game: Playing?) : Misc {
override fun <T : EventInput<T>> accept(visitor: T, handler: EventInput.Handler<T>)
= handler.presenceUpdate(visitor, this)
/**
* Includes username, discriminator, bot and avatar if one of those changes (or it seems at random other places)
* Should be used to update the user model
*/
data class UserRef(val id: DiscordId<User>,
val username: String?,
val discriminator: String?,
val avatar: DiscordId<User.Avatar>?,
val bot: Boolean?) {
fun toUserModel(): UserModel {
require(username != null)
require(discriminator != null)
return UserModel(username!!, id, discriminator!!, avatar, bot)
}
}
data class Playing(val name: String)
enum class Status {
@SerializedName("online")
ONLINE,
@SerializedName("offline")
OFFLINE,
@SerializedName("idle")
IDLE
}
}
data class VoiceStateUpdate(val update: VoiceStateModel) : Misc {
override fun <T : EventInput<T>> accept(visitor: T, handler: EventInput.Handler<T>)
= handler.voiceStateUpdate(visitor, this)
}
} | mit | 11bbad84e694ebd21995aea31913c6b6 | 39.55 | 120 | 0.580327 | 4.672911 | false | false | false | false |
ttomsu/orca | orca-core/src/main/java/com/netflix/spinnaker/orca/pipeline/persistence/DualExecutionRepository.kt | 1 | 12361 | /*
* Copyright 2018 Netflix, 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.netflix.spinnaker.orca.pipeline.persistence
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.ORCHESTRATION
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.api.pipeline.models.PipelineExecution
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository.ExecutionComparator
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository.ExecutionCriteria
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Primary
import org.springframework.stereotype.Component
import rx.Observable
/**
* Intended for performing red/black Orca deployments which do not share the
* same persistence backend.
*
* In order to use this class, you will need to enable it and then define the
* class name of both primary and previous execution repositories. It's
* expected that you have multiple execution repository backends wired up.
*/
@Primary
@Component
@ConditionalOnExpression("\${execution-repository.dual.enabled:false}")
class DualExecutionRepository(
@Value("\${execution-repository.dual.primary-class:}") private val primaryClass: String,
@Value("\${execution-repository.dual.previous-class:}") private val previousClass: String,
@Value("\${execution-repository.dual.primary-name:}") private val primaryName: String,
@Value("\${execution-repository.dual.previous-name:}") private val previousName: String,
allRepositories: List<ExecutionRepository>,
applicationContext: ApplicationContext
) : ExecutionRepository {
private val log = LoggerFactory.getLogger(javaClass)
lateinit var primary: ExecutionRepository
lateinit var previous: ExecutionRepository
init {
allRepositories.forEach {
log.info("Available ExecutionRepository: $it")
}
val findExecutionRepositoryByClass = { className: String ->
val repositoryClass = Class.forName(className)
allRepositories.find { repo ->
repositoryClass.isInstance(repo) ||
(repo is DelegatingExecutionRepository<*> && repositoryClass.isInstance(repo.getDelegate()))
} ?: throw IllegalStateException("No ExecutionRepository bean of class $className found")
}
val findExecutionRepository = { beanName: String, beanClass: String ->
if (beanName.isNotBlank()) {
applicationContext.getBean(beanName) as ExecutionRepository
} else {
findExecutionRepositoryByClass(beanClass)
}
}
primary = findExecutionRepository(primaryName, primaryClass)
previous = findExecutionRepository(previousName, previousClass)
}
private fun select(execution: PipelineExecution): ExecutionRepository {
return select(execution.type, execution.id)
}
private fun select(type: ExecutionType?, id: String): ExecutionRepository {
if (type == null) {
return select(id)
} else {
if (primary.hasExecution(type, id)) {
return primary
} else if (previous.hasExecution(type, id)) {
return previous
}
return primary
}
}
private fun select(id: String): ExecutionRepository {
return when {
primary.hasExecution(PIPELINE, id) -> primary
previous.hasExecution(PIPELINE, id) -> previous
primary.hasExecution(ORCHESTRATION, id) -> primary
previous.hasExecution(ORCHESTRATION, id) -> previous
else -> primary
}
}
override fun store(execution: PipelineExecution) {
select(execution).store(execution)
}
override fun storeStage(stage: StageExecution) {
select(stage.execution).storeStage(stage)
}
override fun updateStageContext(stage: StageExecution) {
select(stage.execution).updateStageContext(stage)
}
override fun removeStage(execution: PipelineExecution, stageId: String) {
select(execution).removeStage(execution, stageId)
}
override fun addStage(stage: StageExecution) {
select(stage.execution).addStage(stage)
}
override fun cancel(type: ExecutionType, id: String) {
select(type, id).cancel(type, id)
}
override fun cancel(type: ExecutionType, id: String, user: String?, reason: String?) {
select(type, id).cancel(type, id, user, reason)
}
override fun pause(type: ExecutionType, id: String, user: String?) {
select(type, id).pause(type, id, user)
}
override fun resume(type: ExecutionType, id: String, user: String?) {
select(type, id).resume(type, id, user)
}
override fun resume(type: ExecutionType, id: String, user: String?, ignoreCurrentStatus: Boolean) {
select(type, id).resume(type, id, user, ignoreCurrentStatus)
}
override fun isCanceled(type: ExecutionType?, id: String): Boolean {
return select(type, id).isCanceled(type, id)
}
override fun updateStatus(type: ExecutionType?, id: String, status: ExecutionStatus) {
select(type, id).updateStatus(type, id, status)
}
override fun retrieve(type: ExecutionType, id: String): PipelineExecution {
return select(type, id).retrieve(type, id)
}
override fun delete(type: ExecutionType, id: String) {
return select(type, id).delete(type, id)
}
override fun delete(type: ExecutionType, idsToDelete: MutableList<String>) {
// NOTE: Not a great implementation, but this method right now is only used on SqlExecutionRepository which has
// a performant implementation
idsToDelete.forEach { id ->
delete(type, id)
}
}
override fun retrieve(type: ExecutionType): Observable<PipelineExecution> {
return Observable.merge(
primary.retrieve(type),
previous.retrieve(type)
).distinct { it.id }
}
override fun retrieve(type: ExecutionType, criteria: ExecutionCriteria): Observable<PipelineExecution> {
return Observable.merge(
primary.retrieve(type, criteria),
previous.retrieve(type, criteria)
).distinct { it.id }
}
override fun retrievePipelinesForApplication(application: String): Observable<PipelineExecution> {
return Observable.merge(
primary.retrievePipelinesForApplication(application),
previous.retrievePipelinesForApplication(application)
).distinct { it.id }
}
override fun retrievePipelinesForPipelineConfigId(
pipelineConfigId: String,
criteria: ExecutionCriteria
): Observable<PipelineExecution> {
return Observable.merge(
primary.retrievePipelinesForPipelineConfigId(pipelineConfigId, criteria),
previous.retrievePipelinesForPipelineConfigId(pipelineConfigId, criteria)
).distinct { it.id }
}
override fun retrievePipelinesForPipelineConfigIdsBetweenBuildTimeBoundary(
pipelineConfigIds: MutableList<String>,
buildTimeStartBoundary: Long,
buildTimeEndBoundary: Long,
executionCriteria: ExecutionCriteria
): List<PipelineExecution> {
return primary
.retrievePipelinesForPipelineConfigIdsBetweenBuildTimeBoundary(
pipelineConfigIds,
buildTimeStartBoundary,
buildTimeEndBoundary,
executionCriteria
)
.plus(previous.retrievePipelinesForPipelineConfigIdsBetweenBuildTimeBoundary(
pipelineConfigIds,
buildTimeStartBoundary,
buildTimeEndBoundary,
executionCriteria)
).distinctBy { it.id }
}
override fun retrieveAllPipelinesForPipelineConfigIdsBetweenBuildTimeBoundary(
pipelineConfigIds: List<String>,
buildTimeStartBoundary: Long,
buildTimeEndBoundary: Long,
executionCriteria: ExecutionCriteria
): List<PipelineExecution> {
return primary
.retrieveAllPipelinesForPipelineConfigIdsBetweenBuildTimeBoundary(
pipelineConfigIds,
buildTimeStartBoundary,
buildTimeEndBoundary,
executionCriteria
).plus(previous.retrieveAllPipelinesForPipelineConfigIdsBetweenBuildTimeBoundary(
pipelineConfigIds,
buildTimeStartBoundary,
buildTimeEndBoundary,
executionCriteria)
).distinctBy { it.id }
}
override fun retrieveOrchestrationsForApplication(
application: String,
criteria: ExecutionCriteria
): Observable<PipelineExecution> {
return Observable.merge(
primary.retrieveOrchestrationsForApplication(application, criteria),
previous.retrieveOrchestrationsForApplication(application, criteria)
).distinct { it.id }
}
override fun retrieveOrchestrationsForApplication(
application: String,
criteria: ExecutionCriteria,
sorter: ExecutionComparator?
): MutableList<PipelineExecution> {
val result = Observable.merge(
Observable.from(primary.retrieveOrchestrationsForApplication(application, criteria, sorter)),
Observable.from(previous.retrieveOrchestrationsForApplication(application, criteria, sorter))
).toList().toBlocking().single().distinctBy { it.id }.toMutableList()
return if (sorter != null) {
result.asSequence().sortedWith(sorter as Comparator<in PipelineExecution>).toMutableList()
} else {
result
}
}
override fun retrieveByCorrelationId(executionType: ExecutionType, correlationId: String): PipelineExecution {
return try {
primary.retrieveByCorrelationId(executionType, correlationId)
} catch (e: ExecutionNotFoundException) {
previous.retrieveByCorrelationId(executionType, correlationId)
}
}
override fun retrieveOrchestrationForCorrelationId(correlationId: String): PipelineExecution {
return try {
primary.retrieveOrchestrationForCorrelationId(correlationId)
} catch (e: ExecutionNotFoundException) {
previous.retrieveOrchestrationForCorrelationId(correlationId)
}
}
override fun retrievePipelineForCorrelationId(correlationId: String): PipelineExecution {
return try {
primary.retrievePipelineForCorrelationId(correlationId)
} catch (e: ExecutionNotFoundException) {
previous.retrievePipelineForCorrelationId(correlationId)
}
}
override fun retrieveBufferedExecutions(): MutableList<PipelineExecution> {
return Observable.merge(
Observable.from(primary.retrieveBufferedExecutions()),
Observable.from(previous.retrieveBufferedExecutions())
).toList().toBlocking().single().distinctBy { it.id }.toMutableList()
}
override fun retrieveAllApplicationNames(executionType: ExecutionType?): MutableList<String> {
return Observable.merge(
Observable.from(primary.retrieveAllApplicationNames(executionType)),
Observable.from(previous.retrieveAllApplicationNames(executionType))
).toList().toBlocking().single().distinct().toMutableList()
}
override fun retrieveAllApplicationNames(
executionType: ExecutionType?,
minExecutions: Int
): MutableList<String> {
return Observable.merge(
Observable.from(primary.retrieveAllApplicationNames(executionType, minExecutions)),
Observable.from(previous.retrieveAllApplicationNames(executionType, minExecutions))
).toList().toBlocking().single().distinct().toMutableList()
}
override fun hasExecution(type: ExecutionType, id: String): Boolean {
return primary.hasExecution(type, id) || previous.hasExecution(type, id)
}
override fun retrieveAllExecutionIds(type: ExecutionType): MutableList<String> {
return Observable.merge(
Observable.from(primary.retrieveAllExecutionIds(type)),
Observable.from(previous.retrieveAllExecutionIds(type))
).toList().toBlocking().single().distinct().toMutableList()
}
}
| apache-2.0 | 52f3e246c29c66d0f313401a3a192953 | 36.231928 | 115 | 0.747917 | 4.817225 | false | true | false | false |
cortinico/myo-emg-visualizer | myonnaise/src/test/java/com/ncorti/myonnaise/MyoTest.kt | 1 | 5769 | package com.ncorti.myonnaise
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.content.Context
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class MyoTest {
private lateinit var mockContext: Context
private lateinit var mockBlDevice: BluetoothDevice
@Before
fun setup() {
mockBlDevice = mock {
on(mock.name) doReturn "42"
on(mock.address) doReturn "11:22:33:44:55:66"
}
mockContext = mock {}
}
@Test
fun getName() {
assertEquals("42", Myo(mockBlDevice).name)
}
@Test
fun getAddress() {
assertEquals("42", Myo(mockBlDevice).name)
}
@Test
fun getDefaultFrequency() {
assertEquals(0, Myo(mockBlDevice).frequency)
}
@Test
fun updatingFrequencyToNonDefault() {
val myo = Myo(mockBlDevice)
myo.frequency = 50
assertEquals(50, myo.frequency)
}
@Test
fun updatingFrequencyToNonSupported_ResetToDefault() {
val myo = Myo(mockBlDevice)
myo.frequency = MYO_MAX_FREQUENCY + 1
assertEquals(0, myo.frequency)
}
@Test
fun connect_callGattConnection() {
val mockContext = mock<Context> {}
val myo = Myo(mockBlDevice)
myo.connect(mockContext)
verify(mockBlDevice).connectGatt(eq(mockContext), eq(false), eq(myo))
}
@Test
fun connect_publishConnectingEvent() {
val mockContext = mock<Context> {}
val myo = Myo(mockBlDevice)
myo.connect(mockContext)
myo.statusObservable().test().assertValue(MyoStatus.CONNECTING)
}
@Test
fun disconnect_closeGatt() {
val myo = Myo(mockBlDevice)
myo.gatt = mock {}
myo.disconnect()
verify(myo.gatt)?.close()
}
@Test
fun disconnect_publishEvents() {
val myo = Myo(mockBlDevice)
myo.gatt = mock {}
myo.disconnect()
myo.statusObservable().test().assertValue(MyoStatus.DISCONNECTED)
myo.controlObservable().test().assertValue(MyoControlStatus.NOT_STREAMING)
}
@Test
fun isConnected_whenActuallyConnected() {
val myo = Myo(mockBlDevice)
myo.connectionStatusSubject.onNext(MyoStatus.CONNECTED)
assertTrue(myo.isConnected())
myo.connectionStatusSubject.onNext(MyoStatus.READY)
assertTrue(myo.isConnected())
}
@Test
fun isConnected_whenNotConnected() {
val myo = Myo(mockBlDevice)
myo.connectionStatusSubject.onNext(MyoStatus.CONNECTING)
assertFalse(myo.isConnected())
myo.connectionStatusSubject.onNext(MyoStatus.DISCONNECTED)
assertFalse(myo.isConnected())
}
@Test
fun isStreaming_whenActuallyStreaming() {
val myo = Myo(mockBlDevice)
myo.controlStatusSubject.onNext(MyoControlStatus.STREAMING)
assertTrue(myo.isStreaming())
}
@Test
fun isStreaming_whenNotStreaming() {
val myo = Myo(mockBlDevice)
myo.controlStatusSubject.onNext(MyoControlStatus.NOT_STREAMING)
assertFalse(myo.isStreaming())
}
@Test
fun sendCommand_withCharacteristicNotReady() {
val myo = Myo(mockBlDevice)
myo.characteristicCommand = null
assertFalse(myo.sendCommand(CommandList.vibration1()))
}
@Test
fun sendCommand_withCharacteristicReady_writeTheCommand() {
val myo = Myo(mockBlDevice)
myo.gatt = mock { }
myo.characteristicCommand = mock {
on(mock.properties) doReturn BluetoothGattCharacteristic.PROPERTY_WRITE
}
assertTrue(myo.sendCommand(CommandList.vibration1()))
verify(myo.gatt)?.writeCharacteristic(myo.characteristicCommand)
}
@Test
fun sendCommand_withStartStreamingCommand_publishEvent() {
val myo = Myo(mockBlDevice)
myo.gatt = mock { }
myo.characteristicCommand = mock {
on(mock.properties) doReturn BluetoothGattCharacteristic.PROPERTY_WRITE
}
myo.sendCommand(CommandList.emgFilteredOnly())
myo.controlObservable().test().assertValue(MyoControlStatus.STREAMING)
}
@Test
fun sendCommand_withStopStreamingCommand_publishEvent() {
val myo = Myo(mockBlDevice)
myo.gatt = mock { }
myo.characteristicCommand = mock {
on(mock.properties) doReturn BluetoothGattCharacteristic.PROPERTY_WRITE
}
myo.sendCommand(CommandList.stopStreaming())
myo.controlObservable().test().assertValue(MyoControlStatus.NOT_STREAMING)
}
@Test
fun writeDescriptor_withEmptyQueue_writeImmediately() {
val mockDescriptor = mock<BluetoothGattDescriptor> {}
val myo = Myo(mockBlDevice)
val mockGatt = mock<BluetoothGatt> {}
myo.writeQueue.clear()
myo.writeDescriptor(mockGatt, mockDescriptor)
verify(mockGatt).writeDescriptor(any())
}
@Test
fun writeDescriptor_withNotEmptyQueue_postponeWrite() {
val mockDescriptor = mock<BluetoothGattDescriptor> {}
val myo = Myo(mockBlDevice)
myo.gatt = mock {}
myo.writeQueue.add(mockDescriptor)
myo.writeDescriptor(mock {}, mockDescriptor)
verify(myo.gatt, never())?.writeDescriptor(mockDescriptor)
}
} | mit | 6b8e9a0b3e7d5d87308cfe72c3fbd50d | 27.706468 | 83 | 0.670827 | 4.20481 | false | true | false | false |
DanielMartinus/Konfetti | samples/compose-kotlin/src/main/java/nl/dionsegijn/xml/compose/ComposeActivity.kt | 1 | 3411 | package nl.dionsegijn.xml.compose
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.appcompat.content.res.AppCompatResources
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import nl.dionsegijn.konfetti.compose.KonfettiView
import nl.dionsegijn.konfetti.compose.OnParticleSystemUpdateListener
import nl.dionsegijn.konfetti.core.PartySystem
import nl.dionsegijn.xml.compose.ui.theme.KonfettiTheme
class ComposeActivity : ComponentActivity() {
private val viewModel by viewModels<KonfettiViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
KonfettiTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
KonfettiUI(viewModel)
}
}
}
}
}
@Composable
fun KonfettiUI(viewModel: KonfettiViewModel = KonfettiViewModel()) {
val state: KonfettiViewModel.State by viewModel.state.observeAsState(
KonfettiViewModel.State.Idle
)
val drawable = AppCompatResources.getDrawable(LocalContext.current, R.drawable.ic_heart)
when (val newState = state) {
KonfettiViewModel.State.Idle -> {
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Button(onClick = { viewModel.festive() }) {
Text(
text = "Festive",
)
}
Button(onClick = { viewModel.explode() }) {
Text(
text = "Explode",
)
}
Button(onClick = { viewModel.parade() }) {
Text(
text = "Parade",
)
}
Button(onClick = { viewModel.rain() }) {
Text(
text = "Rain",
)
}
}
}
is KonfettiViewModel.State.Started -> KonfettiView(
modifier = Modifier.fillMaxSize(),
parties = newState.party,
updateListener = object : OnParticleSystemUpdateListener {
override fun onParticleSystemEnded(system: PartySystem, activeSystems: Int) {
if (activeSystems == 0) viewModel.ended()
}
}
)
}
}
| isc | 0100ce728ce23633995458c40de931db | 35.287234 | 93 | 0.621812 | 5.137048 | false | false | false | false |
hannesa2/AndroidSlidingUpPanel | library/src/main/java/com/sothree/slidinguppanel/positionhelper/impl/RecyclerViewScrollPositionHelper.kt | 1 | 1218 | package com.sothree.slidinguppanel.positionhelper.impl
import android.view.View
import androidx.recyclerview.widget.RecyclerView
open class RecyclerViewScrollPositionHelper : AbstractScrollPositionHelper<RecyclerView>() {
override fun isSupport(view: View): Boolean {
return view is RecyclerView && view.childCount > 0
}
override fun getPosition(view: RecyclerView, isSlidingUp: Boolean): Int {
val lm = view.layoutManager
return when {
view.adapter == null -> return 0
isSlidingUp -> {
val firstChild = view.getChildAt(0)
// Approximate the scroll position based on the top child and the first visible item
view.getChildLayoutPosition(firstChild) * lm!!.getDecoratedMeasuredHeight(firstChild) - lm.getDecoratedTop(firstChild)
}
else -> {
val lastChild = view.getChildAt(view.childCount - 1)
// Approximate the scroll position based on the bottom child and the last visible item
(view.adapter!!.itemCount - 1) * lm!!.getDecoratedMeasuredHeight(lastChild) + lm.getDecoratedBottom(lastChild) - view.bottom
}
}
}
} | apache-2.0 | 4084bed5798a674ced59975720aadb83 | 44.148148 | 140 | 0.658456 | 5.053942 | false | false | false | false |
curiosityio/Wendy | wendy/src/main/java/com/levibostian/wendy/service/PendingTask.kt | 1 | 5678 | package com.levibostian.wendy.service
import android.support.annotation.WorkerThread
import com.levibostian.wendy.db.PendingTaskFields
import com.levibostian.wendy.db.PersistedPendingTask
import com.levibostian.wendy.types.PendingTaskResult
import java.text.SimpleDateFormat
import java.util.*
/**
* Represents a single task to perform. Usually used to sync offline data stored on the device with online remote storage.
*
* To use this class, create a subclass of it. It is not marked as abstract because these files are saved into a sqlite database and in order to do that, this file cannot be abstract.
*
* @property taskId ID of the [PendingTask]. After you have used [Wendy.addTask] to add this task to Wendy, this property will become populated and available to you. It is then up to *you* to hang onto this ID if you want to reference it later on.
* @property createdAt The date/time that the task was created.
* @property manuallyRun Sometimes you may want your user to be in charge of when a task is run. Setting [manuallyRun] to true will assert that this task does not get run automatically by the Wendy task runner. You will need to manually run the task yourself via [Wendy.runTask].
* @property groupId If this task needs to be run after a set of previous tasks before it were all successfully run then mark this property with an identifier for the group. Wendy will run through all the tasks of this group until one of them fails. When one fails, Wendy will then skip all the other tasks belonging to this group and move on.
* @property dataId This field is used to help you identify what offline device data needs to be synced with online remote storage. Example: You have a sqlite database table named Employees. Your user creates a new Employee in your app. First, you will create a new Employee table row for this new employee and then create a new CreateEmployeePendingTask instance to sync this new Employees sqlite row with your online remote storage. Set [dataId] to the newly created Employee table row id. So then when your CreateEmployeePendingTask instance is run by Wendy, you can query your database and sync that data with your remote storage.
* @property tag This is annoying, I know. I hope to remove it soon. This identifies your subclass with Wendy so when Wendy queries your [PendingTask] in the sqlite DB, it knows to run your subclass. It's recommended to set the tag to: `NameOfYourSubclass::class.java.simpleName`.
*
* *Note:* The [tag] and [dataId] are the 2 properties that determine a unique instance of [PendingTask]. Wendy is configured to mark [tag] and [dataId] as unique constraints in the Wendy task database. So, even if the [groupId], [manuallyRun] is defined differently between 2 [PendingTask] instances, Wendy will write and run the most recently added [PendingTask].
*/
abstract class PendingTask(override var manuallyRun: Boolean,
override var dataId: String?,
override var groupId: String?,
override var tag: String): PendingTaskFields {
var taskId: Long? = null
override var createdAt: Long = Date().time
/**
* The method Wendy calls when it's time for your task to run. This is where you will perform database operations on the device, perform API calls, etc.
*
* When you are done performing the task, return if the task was run successfully or not. You have 3 options as outlined in [PendingTaskResult].
*
* This method is run on a background thread for you already. Make sure to run all of your code in a synchronous style. If you would like to run async code, check out the `BEST_PRACTICES.md` file in the root of this project to learn more on how you could do this.
*
* @see PendingTaskResult to learn about the different results you may return after the task runs.
*/
@WorkerThread abstract fun runTask(): PendingTaskResult
/**
* Override this to dynamically set if this task is ready to run or not.
*/
open fun isReadyToRun(): Boolean = true
/**
* Use to go from [PersistedPendingTask] to [PendingTask] after running a SQLite query.
*/
internal fun fromSqlObject(pendingTask: PersistedPendingTask): PendingTask {
this.taskId = pendingTask.id
this.createdAt = pendingTask.createdAt
this.manuallyRun = pendingTask.manuallyRun
this.groupId = pendingTask.groupId
this.dataId = pendingTask.dataId
this.tag = pendingTask.tag
return this
}
/**
* Print contents of [PendingTask].
*/
override fun toString(): String {
val dateFormatter = SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z", Locale.ENGLISH)
return "taskId: $taskId, created at: ${dateFormatter.format(createdAt)}, manually run: $manuallyRun, group id: ${groupId ?: "none"}, data id: ${dataId ?: "none"}, tag: $tag"
}
/**
* Run comparisons between two instances of [PendingTask].
*/
final override fun equals(other: Any?): Boolean {
if (other !is PendingTask) return false
// If the tasks have the same task id, we can assume they are the same already.
if (other.taskId == this.taskId) return true
// If they have the same dataId and tag, then they are the same in SQL unique terms.
return other.dataId == this.dataId &&
other.tag == this.tag
}
/**
* Your typical Java hashCode() function to match [equals].
*/
final override fun hashCode(): Int {
var result = dataId?.hashCode() ?: 0
result = 31 * result + tag.hashCode()
return result
}
} | mit | 114833c74fe3df90ff145ba16819aae3 | 59.414894 | 634 | 0.714688 | 4.425565 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/swapBinaryExpression/multipleOperandsWithDifferentPrecedence6.kt | 9 | 123 | // AFTER-WARNING: Variable 'rabbit' is never used
fun main() {
val rabbit = 4 + 2 == 12 ||<caret> true && 5 + 5 == 10
} | apache-2.0 | daac917a7d04b148a4070642c6e85333 | 30 | 58 | 0.569106 | 3.153846 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/repo/GitUnversionedFilesHolder.kt | 5 | 1266 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.repo
import com.intellij.dvcs.repo.VcsManagedFilesHolderBase
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.changes.VcsManagedFilesHolder
import git4idea.GitVcs
class GitUnversionedFilesHolder(val manager: GitRepositoryManager) : VcsManagedFilesHolderBase() {
private val allHolders get() = manager.repositories.asSequence().map { it.untrackedFilesHolder }
override fun isInUpdatingMode() = allHolders.any(GitUntrackedFilesHolder::isInUpdateMode)
override fun containsFile(file: FilePath): Boolean {
val repository = manager.getRepositoryForFileQuick(file) ?: return false
return repository.untrackedFilesHolder.containsFile(file)
}
override fun values() = allHolders.flatMap { it.untrackedFilePaths }.toList()
class Provider(project: Project) : VcsManagedFilesHolder.Provider {
private val gitVcs = GitVcs.getInstance(project)
private val manager = GitRepositoryManager.getInstance(project)
override fun getVcs() = gitVcs
override fun createHolder() = GitUnversionedFilesHolder(manager)
}
}
| apache-2.0 | 0ede19aff0e84242127798fa2b7a4c3c | 41.2 | 140 | 0.795419 | 4.473498 | false | false | false | false |
miketrewartha/positional | app/src/main/kotlin/io/trewartha/positional/ui/location/help/LocationHelpFragment.kt | 1 | 1847 | package io.trewartha.positional.ui.location.help
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.hilt.navigation.fragment.hiltNavGraphViewModels
import androidx.navigation.fragment.findNavController
import com.google.android.material.transition.MaterialSharedAxis
import dagger.hilt.android.AndroidEntryPoint
import io.noties.markwon.Markwon
import io.trewartha.positional.R
import io.trewartha.positional.databinding.LocationHelpFragmentBinding
import javax.inject.Inject
@AndroidEntryPoint
class LocationHelpFragment : Fragment() {
@Inject
lateinit var markwon: Markwon
private var _viewBinding: LocationHelpFragmentBinding? = null
private val viewBinding get() = _viewBinding!!
private val viewModel: LocationHelpViewModel by hiltNavGraphViewModels(R.id.nav_graph)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enterTransition = MaterialSharedAxis(MaterialSharedAxis.Z, true)
returnTransition = MaterialSharedAxis(MaterialSharedAxis.Z, false)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_viewBinding = LocationHelpFragmentBinding.inflate(inflater, container, false)
return viewBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewBinding.toolbar.setNavigationOnClickListener { findNavController().popBackStack() }
markwon.setMarkdown(viewBinding.textView, viewModel.helpContent)
}
override fun onDestroyView() {
super.onDestroyView()
_viewBinding = null
}
} | mit | d02b68b39a15f079bd7569264a51e85c | 33.222222 | 95 | 0.767731 | 4.912234 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/subscriptions/SubscriptionDetailsView.kt | 1 | 8616 | package com.habitrpg.android.habitica.ui.views.subscriptions
import android.content.Context
import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.SubscriptionDetailsBinding
import com.habitrpg.android.habitica.extensions.layoutInflater
import com.habitrpg.android.habitica.models.user.SubscriptionPlan
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import java.text.DateFormat
import java.util.*
class SubscriptionDetailsView : LinearLayout {
lateinit var binding: SubscriptionDetailsBinding
private var plan: SubscriptionPlan? = null
var onShowSubscriptionOptions: (() -> Unit)? = null
var currentUserID: String? = null
constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {
setupView()
}
constructor(context: Context) : super(context) {
setupView()
}
private fun setupView() {
binding = SubscriptionDetailsBinding.inflate(context.layoutInflater, this, true)
binding.changeSubscriptionButton.setOnClickListener { changeSubscriptionButtonTapped() }
binding.heartIcon.setImageDrawable(BitmapDrawable(context.resources, HabiticaIconsHelper.imageOfHeartLightBg()))
}
fun setPlan(plan: SubscriptionPlan) {
this.plan = plan
updateSubscriptionStatusPill(plan)
var duration: String? = null
if (plan.planId != null && plan.dateTerminated == null) {
if (plan.planId == SubscriptionPlan.PLANID_BASIC || plan.planId == SubscriptionPlan.PLANID_BASICEARNED) {
duration = resources.getString(R.string.month)
} else if (plan.planId == SubscriptionPlan.PLANID_BASIC3MONTH) {
duration = resources.getString(R.string.three_months)
} else if (plan.planId == SubscriptionPlan.PLANID_BASIC6MONTH || plan.planId == SubscriptionPlan.PLANID_GOOGLE6MONTH) {
duration = resources.getString(R.string.six_months)
} else if (plan.planId == SubscriptionPlan.PLANID_BASIC12MONTH) {
duration = resources.getString(R.string.twelve_months)
}
}
when {
duration != null -> binding.subscriptionDurationTextView.text = resources.getString(R.string.subscription_duration, duration)
plan.isGroupPlanSub -> binding.subscriptionDurationTextView.setText(R.string.member_group_plan)
plan.dateTerminated != null -> binding.subscriptionDurationTextView.text = resources.getString(R.string.ending_on, DateFormat.getDateInstance().format(plan.dateTerminated ?: Date()))
}
if (plan.extraMonths > 0) {
binding.subscriptionCreditWrapper.visibility = View.VISIBLE
if (plan.extraMonths == 1) {
binding.subscriptionCreditTextView.text = resources.getString(R.string.one_month)
} else {
binding.subscriptionCreditTextView.text = resources.getString(R.string.x_months, plan.extraMonths)
}
} else {
binding.subscriptionCreditWrapper.visibility = View.GONE
}
when (plan.paymentMethod) {
"Amazon Payments" -> binding.paymentProcessorImageView.setImageResource(R.drawable.payment_amazon)
"Apple" -> binding.paymentProcessorImageView.setImageResource(R.drawable.payment_apple)
"Google" -> binding.paymentProcessorImageView.setImageResource(R.drawable.payment_google)
"PayPal" -> binding.paymentProcessorImageView.setImageResource(R.drawable.payment_paypal)
"Stripe" -> binding.paymentProcessorImageView.setImageResource(R.drawable.payment_stripe)
else -> {
if (plan.isGiftedSub) {
binding.paymentProcessorImageView.setImageResource(R.drawable.payment_gift)
binding.subscriptionPaymentMethodTextview.text = context.getString(R.string.gifted)
} else {
binding.paymentProcessorWrapper.visibility = View.GONE
}
}
}
if (plan.consecutive?.count == 1) {
binding.monthsSubscribedTextView.text = resources.getString(R.string.one_month)
} else {
binding.monthsSubscribedTextView.text = resources.getString(R.string.x_months, plan.consecutive?.count ?: 0)
}
binding.gemCapTextView.text = plan.totalNumberOfGems().toString()
binding.currentHourglassesTextView.text = plan.consecutive?.trinkets.toString()
binding.changeSubscriptionButton.visibility = View.VISIBLE
if (plan.paymentMethod != null) {
binding.changeSubscriptionTitle.setText(R.string.cancel_subscription)
if (plan.paymentMethod == "Google") {
binding.changeSubscriptionDescription.setText(R.string.cancel_subscription_google_description)
binding.changeSubscriptionButton.setText(R.string.open_in_store)
} else {
if (plan.isGroupPlanSub) {
/*if (plan.ownerID == currentUserID) {
binding.changeSubscriptionDescription.setText(R.string.cancel_subscription_group_plan_owner)
} else {*/
binding.changeSubscriptionDescription.setText(R.string.cancel_subscription_group_plan)
binding.changeSubscriptionButton.visibility = View.GONE
//}
} else {
binding.changeSubscriptionDescription.setText(R.string.cancel_subscription_notgoogle_description)
}
binding.changeSubscriptionButton.setText(R.string.visit_habitica_website)
}
}
if (plan.dateTerminated != null) {
binding.changeSubscriptionTitle.setText(R.string.resubscribe)
binding.changeSubscriptionDescription.setText(R.string.resubscribe_description)
binding.changeSubscriptionButton.setText(R.string.renew_subscription)
}
}
private fun updateSubscriptionStatusPill(plan: SubscriptionPlan) {
if (plan.isActive) {
if (plan.dateTerminated != null) {
if (plan.isGiftedSub) {
binding.subscriptionStatusNotRecurring.visibility = View.VISIBLE
binding.subscriptionStatusCancelled.visibility = View.GONE
} else {
binding.subscriptionStatusNotRecurring.visibility = View.GONE
binding.subscriptionStatusCancelled.visibility = View.VISIBLE
}
binding.subscriptionStatusActive.visibility = View.GONE
binding.subscriptionStatusGroupPlan.visibility = View.GONE
} else {
if (plan.isGroupPlanSub) {
binding.subscriptionStatusGroupPlan.visibility = View.VISIBLE
binding.subscriptionStatusActive.visibility = View.GONE
binding.subscriptionStatusNotRecurring.visibility = View.GONE
} else {
binding.subscriptionStatusActive.visibility = View.VISIBLE
binding.subscriptionStatusNotRecurring.visibility = View.GONE
binding.subscriptionStatusGroupPlan.visibility = View.GONE
}
}
binding.subscriptionStatusInactive.visibility = View.GONE
} else {
binding.subscriptionStatusActive.visibility = View.GONE
binding.subscriptionStatusInactive.visibility = View.VISIBLE
binding.subscriptionStatusNotRecurring.visibility = View.GONE
binding.subscriptionStatusGroupPlan.visibility = View.GONE
}
}
private fun changeSubscriptionButtonTapped() {
if (plan?.paymentMethod != null) {
val url = if (plan?.paymentMethod == "Google") {
"https://play.google.com/store/account/subscriptions"
} else {
context.getString(R.string.base_url) + "/"
}
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
} else if (plan?.dateTerminated != null) {
onShowSubscriptionOptions?.invoke()
}
}
}
| gpl-3.0 | c1e17bddc68d3e8865e4d26c804d9e5d | 47.517241 | 194 | 0.643338 | 4.971725 | false | false | false | false |
firebase/firebase-android-sdk | firebase-dynamic-links/ktx/src/main/kotlin/com/google/firebase/dynamiclinks/ktx/FirebaseDynamicLinks.kt | 1 | 7049 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.firebase.dynamiclinks.ktx
import androidx.annotation.Keep
import com.google.android.gms.tasks.Task
import com.google.firebase.FirebaseApp
import com.google.firebase.components.Component
import com.google.firebase.components.ComponentRegistrar
import com.google.firebase.dynamiclinks.DynamicLink
import com.google.firebase.dynamiclinks.FirebaseDynamicLinks
import com.google.firebase.dynamiclinks.PendingDynamicLinkData
import com.google.firebase.dynamiclinks.ShortDynamicLink
import com.google.firebase.ktx.Firebase
import com.google.firebase.platforminfo.LibraryVersionComponent
/** Returns the [FirebaseDynamicLinks] instance of the default [FirebaseApp]. */
val Firebase.dynamicLinks: FirebaseDynamicLinks
get() = FirebaseDynamicLinks.getInstance()
/** Returns the [FirebaseDynamicLinks] instance of a given [FirebaseApp]. */
fun Firebase.dynamicLinks(app: FirebaseApp): FirebaseDynamicLinks {
return FirebaseDynamicLinks.getInstance(app)
}
/**
* Creates a [DynamicLink.AndroidParameters] object initialized using the [init] function and sets
* it to the [DynamicLink.Builder]
*/
fun DynamicLink.Builder.androidParameters(init: DynamicLink.AndroidParameters.Builder.() -> Unit) {
val builder = DynamicLink.AndroidParameters.Builder()
builder.init()
setAndroidParameters(builder.build())
}
/**
* Creates a [DynamicLink.AndroidParameters] object initialized with the specified [packageName] and
* using the [init] function and sets it to the [DynamicLink.Builder]
*/
fun DynamicLink.Builder.androidParameters(
packageName: String,
init: DynamicLink.AndroidParameters.Builder.() -> Unit
) {
val builder = DynamicLink.AndroidParameters.Builder(packageName)
builder.init()
setAndroidParameters(builder.build())
}
/**
* Creates a [DynamicLink.IosParameters] object initialized with the specified [bundleId] and using
* the [init] function and sets it to the [DynamicLink.Builder]
*/
fun DynamicLink.Builder.iosParameters(
bundleId: String,
init: DynamicLink.IosParameters.Builder.() -> Unit
) {
val builder = DynamicLink.IosParameters.Builder(bundleId)
builder.init()
setIosParameters(builder.build())
}
/**
* Creates a [DynamicLink.GoogleAnalyticsParameters] object initialized using the [init] function
* and sets it to the [DynamicLink.Builder]
*/
fun DynamicLink.Builder.googleAnalyticsParameters(
init: DynamicLink.GoogleAnalyticsParameters.Builder.() -> Unit
) {
val builder = DynamicLink.GoogleAnalyticsParameters.Builder()
builder.init()
setGoogleAnalyticsParameters(builder.build())
}
/**
* Creates a [DynamicLink.GoogleAnalyticsParameters] object initialized with the specified [source],
* [medium], [campaign] and using the [init] function and sets it to the [DynamicLink.Builder].
*/
fun DynamicLink.Builder.googleAnalyticsParameters(
source: String,
medium: String,
campaign: String,
init: DynamicLink.GoogleAnalyticsParameters.Builder.() -> Unit
) {
val builder = DynamicLink.GoogleAnalyticsParameters.Builder(source, medium, campaign)
builder.init()
setGoogleAnalyticsParameters(builder.build())
}
/**
* Creates a [DynamicLink.ItunesConnectAnalyticsParameters] object initialized using the [init]
* function and sets it to the [DynamicLink.Builder]
*/
fun DynamicLink.Builder.itunesConnectAnalyticsParameters(
init: DynamicLink.ItunesConnectAnalyticsParameters.Builder.() -> Unit
) {
val builder = DynamicLink.ItunesConnectAnalyticsParameters.Builder()
builder.init()
setItunesConnectAnalyticsParameters(builder.build())
}
/**
* Creates a [DynamicLink.SocialMetaTagParameters] object initialized using the [init] function and
* sets it to the [DynamicLink.Builder]
*/
fun DynamicLink.Builder.socialMetaTagParameters(
init: DynamicLink.SocialMetaTagParameters.Builder.() -> Unit
) {
val builder = DynamicLink.SocialMetaTagParameters.Builder()
builder.init()
setSocialMetaTagParameters(builder.build())
}
/**
* Creates a [DynamicLink.NavigationInfoParameters] object initialized using the [init] function and
* sets it to the [DynamicLink.Builder]
*/
fun DynamicLink.Builder.navigationInfoParameters(
init: DynamicLink.NavigationInfoParameters.Builder.() -> Unit
) {
val builder = DynamicLink.NavigationInfoParameters.Builder()
builder.init()
setNavigationInfoParameters(builder.build())
}
/** Creates a [DynamicLink] object initialized using the [init] function. */
fun FirebaseDynamicLinks.dynamicLink(init: DynamicLink.Builder.() -> Unit): DynamicLink {
val builder = FirebaseDynamicLinks.getInstance().createDynamicLink()
builder.init()
return builder.buildDynamicLink()
}
/** Creates a [ShortDynamicLink] object initialized using the [init] function. */
fun FirebaseDynamicLinks.shortLinkAsync(
init: DynamicLink.Builder.() -> Unit
): Task<ShortDynamicLink> {
val builder = FirebaseDynamicLinks.getInstance().createDynamicLink()
builder.init()
return builder.buildShortDynamicLink()
}
/** Creates a [ShortDynamicLink] object initialized using the [init] function. */
fun FirebaseDynamicLinks.shortLinkAsync(
suffix: Int,
init: DynamicLink.Builder.() -> Unit
): Task<ShortDynamicLink> {
val builder = FirebaseDynamicLinks.getInstance().createDynamicLink()
builder.init()
return builder.buildShortDynamicLink(suffix)
}
/** Destructuring declaration for [ShortDynamicLink] to provide shortLink. */
operator fun ShortDynamicLink.component1() = shortLink
/** Destructuring declaration for [ShortDynamicLink] to provide previewLink. */
operator fun ShortDynamicLink.component2() = previewLink
/** Destructuring declaration for [ShortDynamicLink] to provide warnings. */
operator fun ShortDynamicLink.component3(): List<ShortDynamicLink.Warning> = warnings
/** Destructuring declaration for [PendingDynamicLinkData] to provide link. */
operator fun PendingDynamicLinkData.component1() = link
/** Destructuring declaration for [PendingDynamicLinkData] to provide minimumAppVersion. */
operator fun PendingDynamicLinkData.component2() = minimumAppVersion
/** Destructuring declaration for [PendingDynamicLinkData] to provide clickTimestamp. */
operator fun PendingDynamicLinkData.component3() = clickTimestamp
internal const val LIBRARY_NAME: String = "fire-dl-ktx"
/** @suppress */
@Keep
class FirebaseDynamicLinksKtxRegistrar : ComponentRegistrar {
override fun getComponents(): List<Component<*>> =
listOf(LibraryVersionComponent.create(LIBRARY_NAME, BuildConfig.VERSION_NAME))
}
| apache-2.0 | a024e925ec653f33eb816e0ec80241ea | 36.494681 | 100 | 0.783941 | 4.285106 | false | false | false | false |
Zhouzhouzhou/AndroidDemo | app/src/main/java/com/zhou/android/common/CommonRecyclerAdapter.kt | 1 | 1268 | package com.zhou.android.common
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
/**
* Created by mxz on 2020/5/22.
*/
abstract class CommonRecyclerAdapter<T, R : CommonRecyclerAdapter.ViewHolder>(val context: Context, val data: List<T>)
: RecyclerView.Adapter<R>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): R {
return getViewHolder(context, parent, viewType)
}
override fun getItemCount(): Int = data.size
override fun onBindViewHolder(holder: R, position: Int) {
onBind(holder, data[position], position)
}
abstract fun onBind(holder: R, item: T, pos: Int)
abstract fun getViewHolder(context: Context, parent: ViewGroup, viewType: Int): R
open class ViewHolder(private val layout: View) : RecyclerView.ViewHolder(layout) {
private val cache = SparseArray<View>()
@Suppress("UNCHECKED_CAST")
fun <T : View> getView(id: Int): T {
var view = cache[id]
if (view == null) {
view = layout.findViewById(id)
cache.put(id, view)
}
return view as T
}
}
}
| mit | abe01ee12f6d481c7a893ddc6b6dfe34 | 28.488372 | 118 | 0.652208 | 4.255034 | false | false | false | false |
JetBrains/kotlin-native | runtime/src/main/kotlin/kotlin/native/internal/NativePtr.kt | 2 | 2020 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
@file:Suppress("RESERVED_MEMBER_INSIDE_INLINE_CLASS")
package kotlin.native.internal
@TypedIntrinsic(IntrinsicType.INTEROP_GET_NATIVE_NULL_PTR)
external fun getNativeNullPtr(): NativePtr
class NativePtr @PublishedApi internal constructor(private val value: NonNullNativePtr?) {
companion object {
// TODO: make it properly precreated, maybe use an intrinsic for that.
val NULL = getNativeNullPtr()
}
@TypedIntrinsic(IntrinsicType.INTEROP_NATIVE_PTR_PLUS_LONG)
external operator fun plus(offset: Long): NativePtr
@TypedIntrinsic(IntrinsicType.INTEROP_NATIVE_PTR_TO_LONG)
external fun toLong(): Long
override fun equals(other: Any?) = (other is NativePtr) && kotlin.native.internal.areEqualByValue(this, other)
override fun hashCode() = this.toLong().hashCode()
override fun toString() = "0x${this.toLong().toString(16)}"
internal fun isNull(): Boolean = (value == null)
}
@PublishedApi
internal class NonNullNativePtr private constructor() { // TODO: refactor to use this type widely.
@Suppress("NOTHING_TO_INLINE")
inline fun toNativePtr() = NativePtr(this)
override fun toString() = toNativePtr().toString()
override fun hashCode() = toNativePtr().hashCode()
override fun equals(other: Any?) = other is NonNullNativePtr
&& kotlin.native.internal.areEqualByValue(this.toNativePtr(), other.toNativePtr())
}
@ExportTypeInfo("theNativePtrArrayTypeInfo")
internal class NativePtrArray {
@SymbolName("Kotlin_NativePtrArray_get")
external public operator fun get(index: Int): NativePtr
@SymbolName("Kotlin_NativePtrArray_set")
external public operator fun set(index: Int, value: NativePtr): Unit
val size: Int
get() = getArrayLength()
@SymbolName("Kotlin_NativePtrArray_getArrayLength")
external private fun getArrayLength(): Int
}
| apache-2.0 | 5099c4e89800acbda07e68c554a4f4c7 | 32.114754 | 114 | 0.724752 | 4.234801 | false | false | false | false |
jwren/intellij-community | platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/impl/jps/serialization/jpsTestUtils.kt | 1 | 14266 | // 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.ide.impl.jps.serialization
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.components.PathMacroMap
import com.intellij.openapi.components.impl.ModulePathMacroManager
import com.intellij.openapi.components.impl.ProjectPathMacroManager
import com.intellij.openapi.project.ExternalStorageConfigurationManager
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.systemIndependentPath
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.testFramework.UsefulTestCase
import com.intellij.workspaceModel.ide.JpsFileEntitySource
import com.intellij.workspaceModel.ide.JpsProjectConfigLocation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.impl.url.toVirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import junit.framework.AssertionFailedError
import org.jdom.Element
import org.jetbrains.jps.model.serialization.JDomSerializationUtil
import org.jetbrains.jps.model.serialization.PathMacroUtil
import org.jetbrains.jps.util.JpsPathUtil
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import java.io.File
import java.nio.file.Path
import java.util.function.Supplier
internal val sampleDirBasedProjectFile = File(PathManagerEx.getCommunityHomePath(), "jps/model-serialization/testData/sampleProject")
internal val sampleFileBasedProjectFile = File(PathManagerEx.getCommunityHomePath(),
"jps/model-serialization/testData/sampleProject-ipr/sampleProject.ipr")
internal data class LoadedProjectData(
val storage: WorkspaceEntityStorage,
val serializers: JpsProjectSerializersImpl,
val configLocation: JpsProjectConfigLocation,
val originalProjectDir: File
) {
val projectDirUrl: String
get() = configLocation.baseDirectoryUrlString
val projectDir: File
get() = File(VfsUtilCore.urlToPath(configLocation.baseDirectoryUrlString))
}
internal fun copyAndLoadProject(originalProjectFile: File, virtualFileManager: VirtualFileUrlManager): LoadedProjectData {
val (projectDir, originalProjectDir) = copyProjectFiles(originalProjectFile)
val originalBuilder = WorkspaceEntityStorageBuilder.create()
val projectFile = if (originalProjectFile.isFile) File(projectDir, originalProjectFile.name) else projectDir
val configLocation = toConfigLocation(projectFile.toPath(), virtualFileManager)
val serializers = loadProject(configLocation, originalBuilder, virtualFileManager) as JpsProjectSerializersImpl
val loadedProjectData = LoadedProjectData(originalBuilder.toStorage(), serializers, configLocation, originalProjectDir)
serializers.checkConsistency(loadedProjectData.configLocation, loadedProjectData.storage, virtualFileManager)
return loadedProjectData
}
internal fun copyProjectFiles(originalProjectFile: File): Pair<File, File> {
val projectDir = FileUtil.createTempDirectory("jpsProjectTest", null)
val originalProjectDir = if (originalProjectFile.isFile) originalProjectFile.parentFile else originalProjectFile
FileUtil.copyDir(originalProjectDir, projectDir)
return projectDir to originalProjectDir
}
internal fun loadProject(configLocation: JpsProjectConfigLocation, originalBuilder: WorkspaceEntityStorageBuilder, virtualFileManager: VirtualFileUrlManager,
fileInDirectorySourceNames: FileInDirectorySourceNames = FileInDirectorySourceNames.empty(),
externalStorageConfigurationManager: ExternalStorageConfigurationManager? = null): JpsProjectSerializers {
val cacheDirUrl = configLocation.baseDirectoryUrl.append("cache")
return JpsProjectEntitiesLoader.loadProject(configLocation, originalBuilder, File(VfsUtil.urlToPath(cacheDirUrl.url)).toPath(),
TestErrorReporter, virtualFileManager, fileInDirectorySourceNames,
externalStorageConfigurationManager)
}
internal fun JpsProjectSerializersImpl.saveAllEntities(storage: WorkspaceEntityStorage, configLocation: JpsProjectConfigLocation) {
val writer = JpsFileContentWriterImpl(configLocation)
saveAllEntities(storage, writer)
writer.writeFiles()
}
internal fun assertDirectoryMatches(actualDir: File, expectedDir: File, filesToIgnore: Set<String>, componentsToIgnore: List<String>) {
val actualFiles = actualDir.walk().filter { it.isFile }.associateBy { FileUtil.toSystemIndependentName(FileUtil.getRelativePath(actualDir, it)!!) }
val expectedFiles = expectedDir.walk()
.filter { it.isFile }
.associateBy { FileUtil.toSystemIndependentName(FileUtil.getRelativePath(expectedDir, it)!!) }
.filterKeys { it !in filesToIgnore }
for (actualPath in actualFiles.keys) {
val actualFile = actualFiles.getValue(actualPath)
if (actualPath in expectedFiles) {
val expectedFile = expectedFiles.getValue(actualPath)
if (actualFile.extension in setOf("xml", "iml", "ipr")) {
val expectedTag = JDOMUtil.load(expectedFile)
componentsToIgnore.forEach {
val toIgnore = JDomSerializationUtil.findComponent(expectedTag, it)
if (toIgnore != null) {
expectedTag.removeContent(toIgnore)
}
}
val actualTag = JDOMUtil.load(actualFile)
assertEquals("Different content in $actualPath", JDOMUtil.write(expectedTag), JDOMUtil.write(actualTag))
}
else {
assertEquals("Different content in $actualPath", expectedFile.readText(), actualFile.readText())
}
}
}
UsefulTestCase.assertEmpty(actualFiles.keys - expectedFiles.keys)
UsefulTestCase.assertEmpty(expectedFiles.keys - actualFiles.keys)
}
internal fun createProjectSerializers(projectDir: File,
virtualFileManager: VirtualFileUrlManager): Pair<JpsProjectSerializersImpl, JpsProjectConfigLocation> {
val configLocation = toConfigLocation(projectDir.toPath(), virtualFileManager)
val reader = CachingJpsFileContentReader(configLocation)
val externalStoragePath = projectDir.toPath().resolve("cache")
val serializer = JpsProjectEntitiesLoader.createProjectSerializers(configLocation, reader, externalStoragePath, true,
virtualFileManager) as JpsProjectSerializersImpl
return serializer to configLocation
}
fun JpsProjectSerializersImpl.checkConsistency(configLocation: JpsProjectConfigLocation,
storage: WorkspaceEntityStorage,
virtualFileManager: VirtualFileUrlManager) {
fun getNonNullActualFileUrl(source: EntitySource): String {
return getActualFileUrl(source) ?: throw AssertionFailedError("file name is not registered for $source")
}
directorySerializerFactoriesByUrl.forEach { (url, directorySerializer) ->
assertEquals(url, directorySerializer.directoryUrl)
val fileSerializers = serializerToDirectoryFactory.getKeysByValue(directorySerializer) ?: emptyList()
val directoryFileUrls = JpsPathUtil.urlToFile(url).listFiles { file: File -> file.isFile }?.map { JpsPathUtil.pathToUrl(it.systemIndependentPath) } ?: emptyList()
assertEquals(directoryFileUrls.sorted(), fileSerializers.map { getNonNullActualFileUrl(it.internalEntitySource) }.sorted())
}
moduleListSerializersByUrl.forEach { (url, fileSerializer) ->
assertEquals(url, fileSerializer.fileUrl)
val fileSerializers = moduleSerializers.getKeysByValue(fileSerializer) ?: emptyList()
val urlsFromFactory = fileSerializer.loadFileList(CachingJpsFileContentReader(configLocation), virtualFileManager)
assertEquals(urlsFromFactory.map { it.first.url }.sorted(), fileSerializers.map { getNonNullActualFileUrl(it.internalEntitySource) }.sorted())
}
fileSerializersByUrl.keys.associateWith { fileSerializersByUrl.getValues(it) }.forEach { (url, serializers) ->
serializers.forEach {
assertEquals(url, getNonNullActualFileUrl(it.internalEntitySource))
}
}
moduleSerializers.keys.forEach {
assertTrue(it in fileSerializersByUrl.getValues(getNonNullActualFileUrl(it.internalEntitySource)))
}
serializerToDirectoryFactory.keys.forEach {
assertTrue(it in fileSerializersByUrl.getValues(getNonNullActualFileUrl(it.internalEntitySource)))
}
fun <E : WorkspaceEntity> isSerializerWithoutEntities(serializer: JpsFileEntitiesSerializer<E>) =
serializer is JpsFileEntityTypeSerializer<E> && storage.entities(serializer.mainEntityClass).none { serializer.entityFilter(it) }
val allSources = storage.entitiesBySource { true }
val urlsFromSources = allSources.keys.filterIsInstance<JpsFileEntitySource>().mapTo(HashSet()) { getNonNullActualFileUrl(it) }
assertEquals(urlsFromSources.sorted(), fileSerializersByUrl.keys.associateWith { fileSerializersByUrl.getValues(it) }
.filterNot { entry -> entry.value.all { isSerializerWithoutEntities(it)} }.map { it.key }.sorted())
val fileIdFromEntities = allSources.keys.filterIsInstance(JpsFileEntitySource.FileInDirectory::class.java).mapTo(HashSet()) { it.fileNameId }
val unregisteredIds = fileIdFromEntities - fileIdToFileName.keys.toSet()
assertTrue("Some fileNameId aren't registered: ${unregisteredIds}", unregisteredIds.isEmpty())
val staleIds = fileIdToFileName.keys.toSet() - fileIdFromEntities
assertTrue("There are stale mapping for some fileNameId: ${staleIds.joinToString { "$it -> ${fileIdToFileName.get(it)}" }}", staleIds.isEmpty())
}
internal fun File.asConfigLocation(virtualFileManager: VirtualFileUrlManager): JpsProjectConfigLocation = toConfigLocation(toPath(), virtualFileManager)
internal fun toConfigLocation(file: Path, virtualFileManager: VirtualFileUrlManager): JpsProjectConfigLocation {
if (FileUtil.extensionEquals(file.fileName.toString(), "ipr")) {
val iprFile = file.toVirtualFileUrl(virtualFileManager)
return JpsProjectConfigLocation.FileBased(iprFile, virtualFileManager.getParentVirtualUrl(iprFile)!!)
}
else {
val projectDir = file.toVirtualFileUrl(virtualFileManager)
return JpsProjectConfigLocation.DirectoryBased(projectDir, projectDir.append(PathMacroUtil.DIRECTORY_STORE_NAME))
}
}
internal class JpsFileContentWriterImpl(private val configLocation: JpsProjectConfigLocation) : JpsFileContentWriter {
val urlToComponents = LinkedHashMap<String, LinkedHashMap<String, Element?>>()
override fun saveComponent(fileUrl: String, componentName: String, componentTag: Element?) {
urlToComponents.computeIfAbsent(fileUrl) { LinkedHashMap() }[componentName] = componentTag
}
override fun getReplacePathMacroMap(fileUrl: String): PathMacroMap {
return if (isModuleFile(JpsPathUtil.urlToFile(fileUrl)))
ModulePathMacroManager.createInstance(configLocation::projectFilePath, Supplier { JpsPathUtil.urlToOsPath(fileUrl) }).replacePathMap
else
ProjectPathMacroManager.createInstance(configLocation::projectFilePath,
{ JpsPathUtil.urlToPath(configLocation.baseDirectoryUrlString) },
null).replacePathMap
}
internal fun writeFiles() {
urlToComponents.forEach { (url, newComponents) ->
val components = HashMap(newComponents)
val file = JpsPathUtil.urlToFile(url)
val replaceMacroMap = getReplacePathMacroMap(url)
val newRootElement = when {
isModuleFile(file) -> Element("module")
FileUtil.filesEqual(File(JpsPathUtil.urlToPath(configLocation.baseDirectoryUrlString), ".idea"), file.parentFile.parentFile) -> null
else -> Element("project")
}
fun isEmptyComponentTag(componentTag: Element) = componentTag.contentSize == 0 && componentTag.attributes.all { it.name == "name" }
val rootElement: Element?
if (newRootElement != null) {
if (file.exists()) {
val oldElement = JDOMUtil.load(file)
oldElement.getChildren("component")
.filterNot { it.getAttributeValue("name") in components }
.map { it.clone() }
.associateByTo(components) { it.getAttributeValue("name") }
}
components.entries.sortedBy { it.key }.forEach { (name, element) ->
if (element != null && !isEmptyComponentTag(element)) {
if (name == DEPRECATED_MODULE_MANAGER_COMPONENT_NAME) {
element.getChildren("option").forEach {
newRootElement.setAttribute(it.getAttributeValue("key")!!, it.getAttributeValue("value")!!)
}
}
else {
newRootElement.addContent(element)
}
}
}
if (!JDOMUtil.isEmpty(newRootElement)) {
newRootElement.setAttribute("version", "4")
rootElement = newRootElement
}
else {
rootElement = null
}
}
else {
val singleComponent = components.values.single()
rootElement = if (singleComponent != null && !isEmptyComponentTag(singleComponent)) singleComponent else null
}
if (rootElement != null) {
replaceMacroMap.substitute(rootElement, true, true)
FileUtil.createParentDirs(file)
JDOMUtil.write(rootElement, file)
}
else {
FileUtil.delete(file)
}
}
}
private fun isModuleFile(file: File) = (FileUtil.extensionEquals(file.absolutePath, "iml")
|| file.parentFile.name == "modules" && file.parentFile.parentFile.name != ".idea")
}
internal object TestErrorReporter : ErrorReporter {
override fun reportError(message: String, file: VirtualFileUrl) {
throw AssertionFailedError("Failed to load ${file.url}: $message")
}
} | apache-2.0 | 51f3a234edd9045d1c397859f4127b24 | 52.037175 | 166 | 0.749474 | 5.476392 | false | true | false | false |
androidx/androidx | compose/material/material/src/commonMain/kotlin/androidx/compose/material/Menu.kt | 3 | 10930 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntRect
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.PopupPositionProvider
import kotlin.math.max
import kotlin.math.min
@Suppress("ModifierParameter")
@Composable
internal fun DropdownMenuContent(
expandedStates: MutableTransitionState<Boolean>,
transformOriginState: MutableState<TransformOrigin>,
modifier: Modifier = Modifier,
content: @Composable ColumnScope.() -> Unit
) {
// Menu open/close animation.
val transition = updateTransition(expandedStates, "DropDownMenu")
val scale by transition.animateFloat(
transitionSpec = {
if (false isTransitioningTo true) {
// Dismissed to expanded
tween(
durationMillis = InTransitionDuration,
easing = LinearOutSlowInEasing
)
} else {
// Expanded to dismissed.
tween(
durationMillis = 1,
delayMillis = OutTransitionDuration - 1
)
}
}
) {
if (it) {
// Menu is expanded.
1f
} else {
// Menu is dismissed.
0.8f
}
}
val alpha by transition.animateFloat(
transitionSpec = {
if (false isTransitioningTo true) {
// Dismissed to expanded
tween(durationMillis = 30)
} else {
// Expanded to dismissed.
tween(durationMillis = OutTransitionDuration)
}
}
) {
if (it) {
// Menu is expanded.
1f
} else {
// Menu is dismissed.
0f
}
}
Card(
modifier = Modifier.graphicsLayer {
scaleX = scale
scaleY = scale
this.alpha = alpha
transformOrigin = transformOriginState.value
},
elevation = MenuElevation
) {
Column(
modifier = modifier
.padding(vertical = DropdownMenuVerticalPadding)
.width(IntrinsicSize.Max)
.verticalScroll(rememberScrollState()),
content = content
)
}
}
@Composable
internal fun DropdownMenuItemContent(
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
contentPadding: PaddingValues = MenuDefaults.DropdownMenuItemContentPadding,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
content: @Composable RowScope.() -> Unit
) {
// TODO(popam, b/156911853): investigate replacing this Row with ListItem
Row(
modifier = modifier
.clickable(
enabled = enabled,
onClick = onClick,
interactionSource = interactionSource,
indication = rememberRipple(true)
)
.fillMaxWidth()
// Preferred min and max width used during the intrinsic measurement.
.sizeIn(
minWidth = DropdownMenuItemDefaultMinWidth,
maxWidth = DropdownMenuItemDefaultMaxWidth,
minHeight = DropdownMenuItemDefaultMinHeight
)
.padding(contentPadding),
verticalAlignment = Alignment.CenterVertically
) {
val typography = MaterialTheme.typography
ProvideTextStyle(typography.subtitle1) {
val contentAlpha = if (enabled) ContentAlpha.high else ContentAlpha.disabled
CompositionLocalProvider(LocalContentAlpha provides contentAlpha) {
content()
}
}
}
}
/**
* Contains default values used for [DropdownMenuItem].
*/
object MenuDefaults {
/**
* Default padding used for [DropdownMenuItem].
*/
val DropdownMenuItemContentPadding = PaddingValues(
horizontal = DropdownMenuItemHorizontalPadding,
vertical = 0.dp
)
}
// Size defaults.
private val MenuElevation = 8.dp
internal val MenuVerticalMargin = 48.dp
private val DropdownMenuItemHorizontalPadding = 16.dp
internal val DropdownMenuVerticalPadding = 8.dp
private val DropdownMenuItemDefaultMinWidth = 112.dp
private val DropdownMenuItemDefaultMaxWidth = 280.dp
private val DropdownMenuItemDefaultMinHeight = 48.dp
// Menu open/close animation.
internal const val InTransitionDuration = 120
internal const val OutTransitionDuration = 75
internal fun calculateTransformOrigin(
parentBounds: IntRect,
menuBounds: IntRect
): TransformOrigin {
val pivotX = when {
menuBounds.left >= parentBounds.right -> 0f
menuBounds.right <= parentBounds.left -> 1f
menuBounds.width == 0 -> 0f
else -> {
val intersectionCenter =
(
max(parentBounds.left, menuBounds.left) +
min(parentBounds.right, menuBounds.right)
) / 2
(intersectionCenter - menuBounds.left).toFloat() / menuBounds.width
}
}
val pivotY = when {
menuBounds.top >= parentBounds.bottom -> 0f
menuBounds.bottom <= parentBounds.top -> 1f
menuBounds.height == 0 -> 0f
else -> {
val intersectionCenter =
(
max(parentBounds.top, menuBounds.top) +
min(parentBounds.bottom, menuBounds.bottom)
) / 2
(intersectionCenter - menuBounds.top).toFloat() / menuBounds.height
}
}
return TransformOrigin(pivotX, pivotY)
}
// Menu positioning.
/**
* Calculates the position of a Material [DropdownMenu].
*/
// TODO(popam): Investigate if this can/should consider the app window size rather than screen size
@Immutable
internal data class DropdownMenuPositionProvider(
val contentOffset: DpOffset,
val density: Density,
val onPositionCalculated: (IntRect, IntRect) -> Unit = { _, _ -> }
) : PopupPositionProvider {
override fun calculatePosition(
anchorBounds: IntRect,
windowSize: IntSize,
layoutDirection: LayoutDirection,
popupContentSize: IntSize
): IntOffset {
// The min margin above and below the menu, relative to the screen.
val verticalMargin = with(density) { MenuVerticalMargin.roundToPx() }
// The content offset specified using the dropdown offset parameter.
val contentOffsetX = with(density) { contentOffset.x.roundToPx() }
val contentOffsetY = with(density) { contentOffset.y.roundToPx() }
// Compute horizontal position.
val toRight = anchorBounds.left + contentOffsetX
val toLeft = anchorBounds.right - contentOffsetX - popupContentSize.width
val toDisplayRight = windowSize.width - popupContentSize.width
val toDisplayLeft = 0
val x = if (layoutDirection == LayoutDirection.Ltr) {
sequenceOf(
toRight,
toLeft,
// If the anchor gets outside of the window on the left, we want to position
// toDisplayLeft for proximity to the anchor. Otherwise, toDisplayRight.
if (anchorBounds.left >= 0) toDisplayRight else toDisplayLeft
)
} else {
sequenceOf(
toLeft,
toRight,
// If the anchor gets outside of the window on the right, we want to position
// toDisplayRight for proximity to the anchor. Otherwise, toDisplayLeft.
if (anchorBounds.right <= windowSize.width) toDisplayLeft else toDisplayRight
)
}.firstOrNull {
it >= 0 && it + popupContentSize.width <= windowSize.width
} ?: toLeft
// Compute vertical position.
val toBottom = maxOf(anchorBounds.bottom + contentOffsetY, verticalMargin)
val toTop = anchorBounds.top - contentOffsetY - popupContentSize.height
val toCenter = anchorBounds.top - popupContentSize.height / 2
val toDisplayBottom = windowSize.height - popupContentSize.height - verticalMargin
val y = sequenceOf(toBottom, toTop, toCenter, toDisplayBottom).firstOrNull {
it >= verticalMargin &&
it + popupContentSize.height <= windowSize.height - verticalMargin
} ?: toTop
onPositionCalculated(
anchorBounds,
IntRect(x, y, x + popupContentSize.width, y + popupContentSize.height)
)
return IntOffset(x, y)
}
}
| apache-2.0 | 192aae87b4625ae47ecfca81d160ab12 | 35.801347 | 99 | 0.65828 | 5.252283 | false | false | false | false |
androidx/androidx | room/integration-tests/kotlintestapp/src/androidTest/java/androidx/room/integration/kotlintestapp/test/FlowQueryTest.kt | 3 | 10518 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.integration.kotlintestapp.test
import androidx.room.integration.kotlintestapp.vo.Book
import androidx.room.withTransaction
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.async
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.produceIn
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.yield
import org.junit.After
import org.junit.Assert.fail
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
@MediumTest
@RunWith(AndroidJUnit4::class)
class FlowQueryTest : TestDatabaseTest() {
@After
fun teardown() {
// At the end of all tests, query executor should be idle.
countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS)
assertThat(countingTaskExecutorRule.isIdle).isTrue()
}
@Test
fun collectBooks_takeOne() = runBlocking {
booksDao.addAuthors(TestUtil.AUTHOR_1)
booksDao.addPublishers(TestUtil.PUBLISHER)
booksDao.addBooks(TestUtil.BOOK_1, TestUtil.BOOK_2)
booksDao.getBooksFlow().take(1).collect {
assertThat(it)
.isEqualTo(listOf(TestUtil.BOOK_1, TestUtil.BOOK_2))
}
}
@Test
fun collectBooks_first() = runBlocking {
booksDao.addAuthors(TestUtil.AUTHOR_1)
booksDao.addPublishers(TestUtil.PUBLISHER)
booksDao.addBooks(TestUtil.BOOK_1, TestUtil.BOOK_2)
val result = booksDao.getBooksFlow().first()
assertThat(result)
.isEqualTo(listOf(TestUtil.BOOK_1, TestUtil.BOOK_2))
}
@Test
fun collectBooks_first_inTransaction() = runBlocking {
booksDao.addAuthors(TestUtil.AUTHOR_1)
booksDao.addPublishers(TestUtil.PUBLISHER)
booksDao.addBooks(TestUtil.BOOK_1)
database.withTransaction {
booksDao.insertBookSuspend(TestUtil.BOOK_2)
val result = booksDao.getBooksFlow().first()
assertThat(result)
.isEqualTo(listOf(TestUtil.BOOK_1, TestUtil.BOOK_2))
}
}
@Test
fun collectBooks_async() = runBlocking {
booksDao.addAuthors(TestUtil.AUTHOR_1)
booksDao.addPublishers(TestUtil.PUBLISHER)
booksDao.addBooks(TestUtil.BOOK_1, TestUtil.BOOK_2)
val latch = CountDownLatch(1)
val job = async(Dispatchers.IO) {
booksDao.getBooksFlow().collect {
assertThat(it)
.isEqualTo(listOf(TestUtil.BOOK_1, TestUtil.BOOK_2))
latch.countDown()
}
}
latch.await()
job.cancelAndJoin()
}
@Test
fun receiveBooks_async_update() = runBlocking {
booksDao.addAuthors(TestUtil.AUTHOR_1)
booksDao.addPublishers(TestUtil.PUBLISHER)
booksDao.addBooks(TestUtil.BOOK_1, TestUtil.BOOK_2)
val firstResultLatch = CountDownLatch(1)
val secondResultLatch = CountDownLatch(1)
val results = mutableListOf<List<Book>>()
val job = async(Dispatchers.IO) {
booksDao.getBooksFlow().collect {
when (results.size) {
0 -> {
results.add(it)
firstResultLatch.countDown()
}
1 -> {
results.add(it)
secondResultLatch.countDown()
}
else -> fail("Should have only collected 2 results.")
}
}
}
firstResultLatch.await()
booksDao.insertBookSuspend(TestUtil.BOOK_3)
secondResultLatch.await()
assertThat(results.size).isEqualTo(2)
assertThat(results[0])
.isEqualTo(listOf(TestUtil.BOOK_1, TestUtil.BOOK_2))
assertThat(results[1])
.isEqualTo(listOf(TestUtil.BOOK_1, TestUtil.BOOK_2, TestUtil.BOOK_3))
job.cancelAndJoin()
}
@Test
fun receiveBooks() = runBlocking {
booksDao.addAuthors(TestUtil.AUTHOR_1)
booksDao.addPublishers(TestUtil.PUBLISHER)
booksDao.addBooks(TestUtil.BOOK_1, TestUtil.BOOK_2)
val channel = booksDao.getBooksFlow().produceIn(this)
assertThat(channel.receive())
.isEqualTo(listOf(TestUtil.BOOK_1, TestUtil.BOOK_2))
assertThat(channel.isEmpty).isTrue()
channel.cancel()
}
@Test
fun receiveBooks_update() = runBlocking {
booksDao.addAuthors(TestUtil.AUTHOR_1)
booksDao.addPublishers(TestUtil.PUBLISHER)
booksDao.addBooks(TestUtil.BOOK_1, TestUtil.BOOK_2)
val channel = booksDao.getBooksFlow().produceIn(this)
assertThat(channel.receive())
.isEqualTo(listOf(TestUtil.BOOK_1, TestUtil.BOOK_2))
booksDao.insertBookSuspend(TestUtil.BOOK_3)
drain() // drain async invalidate
yield()
assertThat(channel.receive())
.isEqualTo(listOf(TestUtil.BOOK_1, TestUtil.BOOK_2, TestUtil.BOOK_3))
assertThat(channel.isEmpty).isTrue()
channel.cancel()
}
@Test
fun receiveBooks_update_multipleChannels() = runBlocking {
booksDao.addAuthors(TestUtil.AUTHOR_1)
booksDao.addPublishers(TestUtil.PUBLISHER)
booksDao.addBooks(TestUtil.BOOK_1, TestUtil.BOOK_2)
val channels = Array(4) {
booksDao.getBooksFlow().produceIn(this)
}
channels.forEach {
assertThat(it.receive())
.isEqualTo(listOf(TestUtil.BOOK_1, TestUtil.BOOK_2))
}
booksDao.insertBookSuspend(TestUtil.BOOK_3)
drain() // drain async invalidate
yield()
channels.forEach {
assertThat(it.receive())
.isEqualTo(listOf(TestUtil.BOOK_1, TestUtil.BOOK_2, TestUtil.BOOK_3))
assertThat(it.isEmpty).isTrue()
it.cancel()
}
}
@Test
fun receiveBooks_update_multipleChannels_inTransaction() = runBlocking {
booksDao.addAuthors(TestUtil.AUTHOR_1)
booksDao.addPublishers(TestUtil.PUBLISHER)
booksDao.addBooks(TestUtil.BOOK_1, TestUtil.BOOK_2)
val channels = Array(4) {
booksDao.getBooksFlowInTransaction().produceIn(this)
}
channels.forEach {
assertThat(it.receive())
.isEqualTo(listOf(TestUtil.BOOK_1, TestUtil.BOOK_2))
}
booksDao.insertBookSuspend(TestUtil.BOOK_3)
drain() // drain async invalidate
yield()
channels.forEach {
assertThat(it.receive())
.isEqualTo(listOf(TestUtil.BOOK_1, TestUtil.BOOK_2, TestUtil.BOOK_3))
assertThat(it.isEmpty).isTrue()
it.cancel()
}
}
@Test
fun receiveBooks_latestUpdateOnly() = runBlocking {
booksDao.addAuthors(TestUtil.AUTHOR_1)
booksDao.addPublishers(TestUtil.PUBLISHER)
booksDao.addBooks(TestUtil.BOOK_1, TestUtil.BOOK_2)
val channel = booksDao.getBooksFlow().buffer(Channel.CONFLATED).produceIn(this)
assertThat(channel.receive())
.isEqualTo(listOf(TestUtil.BOOK_1, TestUtil.BOOK_2))
booksDao.insertBookSuspend(TestUtil.BOOK_3)
drain() // drain async invalidate
yield()
booksDao.deleteBookSuspend(TestUtil.BOOK_1)
drain() // drain async invalidate
yield()
assertThat(channel.receive())
.isEqualTo(listOf(TestUtil.BOOK_2, TestUtil.BOOK_3))
assertThat(channel.isEmpty).isTrue()
channel.cancel()
}
@Test
fun receiveBooks_async() = runBlocking {
booksDao.addAuthors(TestUtil.AUTHOR_1)
booksDao.addPublishers(TestUtil.PUBLISHER)
booksDao.addBooks(TestUtil.BOOK_1, TestUtil.BOOK_2)
val latch = CountDownLatch(1)
val job = async(Dispatchers.IO) {
for (result in booksDao.getBooksFlow().produceIn(this)) {
assertThat(result)
.isEqualTo(listOf(TestUtil.BOOK_1, TestUtil.BOOK_2))
latch.countDown()
}
}
latch.await()
job.cancelAndJoin()
}
@Test
fun receiveBook_async_update_null() = runBlocking {
booksDao.addAuthors(TestUtil.AUTHOR_1)
booksDao.addPublishers(TestUtil.PUBLISHER)
booksDao.addBooks(TestUtil.BOOK_1)
val firstResultLatch = CountDownLatch(1)
val secondResultLatch = CountDownLatch(1)
val results = mutableListOf<Book?>()
val job = async(Dispatchers.IO) {
booksDao.getOneBooksFlow(TestUtil.BOOK_1.bookId).collect {
when (results.size) {
0 -> {
results.add(it)
firstResultLatch.countDown()
}
1 -> {
results.add(it)
secondResultLatch.countDown()
}
else -> fail("Should have only collected 2 results.")
}
}
}
firstResultLatch.await()
booksDao.deleteBookSuspend(TestUtil.BOOK_1)
secondResultLatch.await()
assertThat(results.size).isEqualTo(2)
assertThat(results[0])
.isEqualTo(TestUtil.BOOK_1)
assertThat(results[1])
.isNull()
job.cancelAndJoin()
}
} | apache-2.0 | 9535845e4e4d63b362ab7b91a502b461 | 31.76947 | 87 | 0.627971 | 4.389816 | false | true | false | false |
MoonlightOwl/Yui | src/main/kotlin/totoro/yui/util/api/Wiki.kt | 1 | 1660 | package totoro.yui.util.api
import com.beust.klaxon.JsonObject
import com.beust.klaxon.Parser
import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.result.Result
import totoro.yui.util.api.data.WikiArticle
object Wiki {
fun search(request: String, country: String, success: (WikiArticle) -> Unit, failure: () -> Unit) {
("https://$country.wikipedia.org/w/api.php?action=query&generator=search&gsrsearch=$request" +
"&gsrlimit=1&prop=extracts|info&inprop=url&exintro&explaintext&exchars=400&format=json&utf8=true")
.httpGet().responseString { _, _, result ->
when (result) {
is Result.Failure -> failure()
is Result.Success -> {
val json = Parser().parse(StringBuilder(result.value)) as JsonObject
val query = json.obj("query")
val pages = query?.obj("pages")
if (pages != null && pages.keys.isNotEmpty()) {
val article = pages.obj(pages.keys.first())
val title = article?.string("title")
val url = article?.string("fullurl")
val snippet = article?.string("extract")
if (title != null && url != null && snippet != null)
success(WikiArticle(title, url, snippet))
else failure()
} else failure()
}
}
}
}
}
| mit | 5223e855f18007e1407444ca0a6a4a2f | 49.30303 | 110 | 0.490964 | 4.925816 | false | false | false | false |
androidx/androidx | compose/animation/animation-core/src/commonMain/kotlin/androidx/compose/animation/core/InternalMutatorMutex.kt | 3 | 6793 | /*
* 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.animation.core
import androidx.compose.runtime.Stable
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
/*** This is an internal copy of androidx.compose.foundation.MutatorMutex. Do not modify. ***/
/**
* Priorities for performing mutation on state.
*
* [MutatePriority] values follow the natural ordering of `enum class` values; a value that
* compares as `>` to another has a higher priority. A mutation of equal or greater priority will
* interrupt the current mutation in progress.
*/
internal enum class MutatePriority {
/**
* The default priority for mutations. Can be interrupted by other [Default], [UserInput] or
* [PreventUserInput] priority operations.
* [Default] priority should be used for programmatic animations or changes that should not
* interrupt user input.
*/
Default,
/**
* An elevated priority for mutations meant for implementing direct user interactions.
* Can be interrupted by other [UserInput] or [PreventUserInput] priority operations.
*/
UserInput,
/**
* A high-priority mutation that can only be interrupted by other [PreventUserInput] priority
* operations. [PreventUserInput] priority should be used for operations that user input should
* not be able to interrupt.
*/
PreventUserInput
}
/**
* Mutual exclusion for UI state mutation over time.
*
* [mutate] permits interruptible state mutation over time using a standard [MutatePriority].
* A [MutatorMutex] enforces that only a single writer can be active at a time for a particular
* state resource. Instead of queueing callers that would acquire the lock like a traditional
* [Mutex], new attempts to [mutate] the guarded state will either cancel the current mutator or
* if the current mutator has a higher priority, the new caller will throw [CancellationException].
*
* [MutatorMutex] should be used for implementing hoisted state objects that many mutators may
* want to manipulate over time such that those mutators can coordinate with one another. The
* [MutatorMutex] instance should be hidden as an implementation detail. For example:
*
*/
@Stable
internal class MutatorMutex {
private class Mutator(val priority: MutatePriority, val job: Job) {
fun canInterrupt(other: Mutator) = priority >= other.priority
fun cancel() = job.cancel()
}
private val currentMutator = AtomicReference<Mutator?>(null)
private val mutex = Mutex()
private fun tryMutateOrCancel(mutator: Mutator) {
while (true) {
val oldMutator = currentMutator.get()
if (oldMutator == null || mutator.canInterrupt(oldMutator)) {
if (currentMutator.compareAndSet(oldMutator, mutator)) {
oldMutator?.cancel()
break
}
} else throw CancellationException("Current mutation had a higher priority")
}
}
/**
* Enforce that only a single caller may be active at a time.
*
* If [mutate] is called while another call to [mutate] or [mutateWith] is in progress, their
* [priority] values are compared. If the new caller has a [priority] equal to or higher than
* the call in progress, the call in progress will be cancelled, throwing
* [CancellationException] and the new caller's [block] will be invoked. If the call in
* progress had a higher [priority] than the new caller, the new caller will throw
* [CancellationException] without invoking [block].
*
* @param priority the priority of this mutation; [MutatePriority.Default] by default. Higher
* priority mutations will interrupt lower priority mutations.
* @param block mutation code to run mutually exclusive with any other call to [mutate] or
* [mutateWith].
*/
suspend fun <R> mutate(
priority: MutatePriority = MutatePriority.Default,
block: suspend () -> R
) = coroutineScope {
val mutator = Mutator(priority, coroutineContext[Job]!!)
tryMutateOrCancel(mutator)
mutex.withLock {
try {
block()
} finally {
currentMutator.compareAndSet(mutator, null)
}
}
}
/**
* Enforce that only a single caller may be active at a time.
*
* If [mutateWith] is called while another call to [mutate] or [mutateWith] is in progress,
* their [priority] values are compared. If the new caller has a [priority] equal to or
* higher than the call in progress, the call in progress will be cancelled, throwing
* [CancellationException] and the new caller's [block] will be invoked. If the call in
* progress had a higher [priority] than the new caller, the new caller will throw
* [CancellationException] without invoking [block].
*
* This variant of [mutate] calls its [block] with a [receiver], removing the need to create
* an additional capturing lambda to invoke it with a receiver object. This can be used to
* expose a mutable scope to the provided [block] while leaving the rest of the state object
* read-only. For example:
*
* @param receiver the receiver `this` that [block] will be called with
* @param priority the priority of this mutation; [MutatePriority.Default] by default. Higher
* priority mutations will interrupt lower priority mutations.
* @param block mutation code to run mutually exclusive with any other call to [mutate] or
* [mutateWith].
*/
suspend fun <T, R> mutateWith(
receiver: T,
priority: MutatePriority = MutatePriority.Default,
block: suspend T.() -> R
) = coroutineScope {
val mutator = Mutator(priority, coroutineContext[Job]!!)
tryMutateOrCancel(mutator)
mutex.withLock {
try {
receiver.block()
} finally {
currentMutator.compareAndSet(mutator, null)
}
}
}
}
| apache-2.0 | f9c7f2f95372a87650cbb4665e6433ca | 40.420732 | 99 | 0.686589 | 4.66232 | false | false | false | false |
Briseus/Lurker | app/src/main/java/torille/fi/lurkforreddit/search/SearchViewAdapter.kt | 1 | 4349 | package torille.fi.lurkforreddit.search
import android.support.v7.util.SortedList
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.util.SortedListAdapterCallback
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import torille.fi.lurkforreddit.R
import torille.fi.lurkforreddit.data.models.view.SearchResult
internal class SearchViewAdapter internal constructor(private val mClickListener: SearchFragment.SearchClickListener) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val results: SortedList<SearchResult>
init {
results = SortedList(
SearchResult::class.java,
object : SortedListAdapterCallback<SearchResult>(this) {
override fun compare(o1: SearchResult, o2: SearchResult): Int {
if (o1.title == o2.title) {
return 0
}
return -1
}
override fun areContentsTheSame(
oldItem: SearchResult,
newItem: SearchResult
): Boolean {
return oldItem == newItem
}
override fun areItemsTheSame(item1: SearchResult, item2: SearchResult): Boolean {
return item1.title == item2.title
}
})
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
VIEW_ITEM -> SearchViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.item_search, parent, false)
)
else -> ProgressViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.item_progressbar, parent, false)
)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is SearchViewHolder) {
holder.bind(results.get(position))
} else if (holder is ProgressViewHolder) {
holder.progressBar.isIndeterminate = true
}
}
override fun getItemViewType(position: Int): Int {
return if (results.get(position).title == "Progressbar") {
VIEW_PROGRESS
} else {
VIEW_ITEM
}
}
override fun getItemCount(): Int {
return results.size()
}
internal fun addResults(newResults: List<SearchResult>) {
val position = results.size() - 1
results.removeItemAt(position)
addAll(newResults)
}
private fun addAll(newResults: List<SearchResult>) {
results.beginBatchedUpdates()
newResults.map { results.add(it) }
results.endBatchedUpdates()
}
internal fun addProgressBar() {
val dummy = SearchResult(title = "Progressbar")
addAll(listOf(dummy))
}
internal fun clear() {
results.clear()
}
internal inner class SearchViewHolder(v: View) : RecyclerView.ViewHolder(v) {
val title: TextView = v.findViewById(R.id.subreddit_title)
private val infoText: TextView = v.findViewById(R.id.subreddits_infotext)
private val description: TextView = v.findViewById(R.id.subreddit_description)
private val subscribe: Button = v.findViewById(R.id.subreddit_subscribe)
init {
description.movementMethod = LinkMovementMethod.getInstance()
description.linksClickable = true
v.setOnClickListener { mClickListener.onSearchClick(results.get(adapterPosition).subreddit) }
}
fun bind(result: SearchResult) {
title.text = result.title
description.text = result.description
subscribe.text = result.subscriptionInfo
infoText.text = result.infoText
}
}
private class ProgressViewHolder internal constructor(v: View) : RecyclerView.ViewHolder(v) {
internal val progressBar: ProgressBar = v.findViewById(R.id.progressBar)
}
companion object {
private val VIEW_ITEM = 1
private val VIEW_PROGRESS = 0
}
} | mit | 3d51a58d698dc3424f42323ef991f6fd | 32.984375 | 119 | 0.62888 | 5.010369 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/remote/hosting/ui/RepositoryAndAccountSelectorViewModelBase.kt | 2 | 3490 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.remote.hosting.ui
import com.intellij.collaboration.async.combineState
import com.intellij.collaboration.auth.AccountManager
import com.intellij.collaboration.auth.ServerAccount
import com.intellij.collaboration.util.URIUtil
import com.intellij.util.childScope
import git4idea.remote.hosting.HostedGitRepositoriesManager
import git4idea.remote.hosting.HostedGitRepositoryMapping
import git4idea.remote.hosting.ui.RepositoryAndAccountSelectorViewModel.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
abstract class RepositoryAndAccountSelectorViewModelBase<M : HostedGitRepositoryMapping, A : ServerAccount>(
parentCs: CoroutineScope,
repositoriesManager: HostedGitRepositoriesManager<M>,
accountManager: AccountManager<A, *>,
private val onSelected: suspend (M, A) -> Unit
) : RepositoryAndAccountSelectorViewModel<M, A> {
private val cs = parentCs.childScope(Dispatchers.Main)
final override val repositoriesState = repositoriesManager.knownRepositoriesState
final override val repoSelectionState = MutableStateFlow<M?>(null)
final override val accountsState = combineState(cs, accountManager.accountsState, repoSelectionState) { accounts, repo ->
if (repo == null) {
emptyList()
}
else {
accounts.filter { URIUtil.equalWithoutSchema(it.server.toURI(), repo.repository.serverPath.toURI()) }
}
}
final override val accountSelectionState = MutableStateFlow<A?>(null)
@OptIn(ExperimentalCoroutinesApi::class)
final override val missingCredentialsState: StateFlow<Boolean?> =
accountSelectionState.transformLatest {
if (it == null) {
emit(false)
}
else {
emit(null)
coroutineScope {
accountManager.getCredentialsState(this, it).collect { creds ->
emit(creds == null)
}
}
}
}.stateIn(cs, SharingStarted.Eagerly, null)
private val submissionErrorState = MutableStateFlow<Error.SubmissionError?>(null)
final override val errorState: StateFlow<Error?> =
combineState(cs, missingCredentialsState, submissionErrorState) { missingCredentials, submissionError ->
if (missingCredentials == true) {
Error.MissingCredentials
}
else {
submissionError
}
}
private val submittingState = MutableStateFlow(false)
final override val busyState: StateFlow<Boolean> =
combineState(cs, missingCredentialsState, submittingState) { missingCredentials, submitting ->
missingCredentials == null || submitting
}
final override val submitAvailableState: StateFlow<Boolean> =
combine(repoSelectionState, accountSelectionState, missingCredentialsState) { repo, acc, credsMissing ->
repo != null && acc != null && credsMissing == false
}.stateIn(cs, SharingStarted.Eagerly, false)
override fun submitSelection() {
val repo = repoSelectionState.value ?: return
val account = accountSelectionState.value ?: return
cs.launch {
submittingState.value = true
try {
onSelected(repo, account)
submissionErrorState.value = null
}
catch (ce: CancellationException) {
throw ce
}
catch (e: Throwable) {
submissionErrorState.value = Error.SubmissionError(repo, account, e)
}
finally {
submittingState.value = false
}
}
}
} | apache-2.0 | 66135b6af93a94f5be781b4c1209d700 | 34.622449 | 123 | 0.724928 | 4.76776 | false | false | false | false |
android/compose-samples | JetLagged/app/src/main/java/com/example/jetlagged/JetLaggedHeaderTabs.kt | 1 | 3597 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetlagged
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.TabPosition
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.example.jetlagged.ui.theme.SmallHeadingStyle
import com.example.jetlagged.ui.theme.White
import com.example.jetlagged.ui.theme.Yellow
enum class SleepTab(val title: Int) {
Day(R.string.sleep_tab_day_heading),
Week(R.string.sleep_tab_week_heading),
Month(R.string.sleep_tab_month_heading),
SixMonths(R.string.sleep_tab_six_months_heading),
OneYear(R.string.sleep_tab_one_year_heading)
}
@Composable
fun JetLaggedHeaderTabs(
onTabSelected: (SleepTab) -> Unit,
selectedTab: SleepTab,
modifier: Modifier = Modifier,
) {
ScrollableTabRow(
modifier = modifier,
edgePadding = 12.dp,
selectedTabIndex = selectedTab.ordinal,
containerColor = White,
indicator = { tabPositions: List<TabPosition> ->
Box(
Modifier
.tabIndicatorOffset(tabPositions[selectedTab.ordinal])
.fillMaxSize()
.padding(horizontal = 2.dp)
.border(BorderStroke(2.dp, Yellow), RoundedCornerShape(10.dp))
)
},
divider = { }
) {
SleepTab.values().forEachIndexed { index, sleepTab ->
val selected = index == selectedTab.ordinal
SleepTabText(
sleepTab = sleepTab,
selected = selected,
onTabSelected = onTabSelected,
index = index
)
}
}
}
private val textModifier = Modifier
.padding(vertical = 6.dp, horizontal = 4.dp)
@Composable
private fun SleepTabText(
sleepTab: SleepTab,
selected: Boolean,
index: Int,
onTabSelected: (SleepTab) -> Unit,
) {
Tab(
modifier = Modifier
.padding(horizontal = 2.dp)
.clip(RoundedCornerShape(16.dp)),
selected = selected,
unselectedContentColor = Color.Black,
selectedContentColor = Color.Black,
onClick = {
onTabSelected(SleepTab.values()[index])
}
) {
Text(
modifier = textModifier,
text = stringResource(id = sleepTab.title),
style = SmallHeadingStyle
)
}
}
| apache-2.0 | fcc66a86e7424d1884aa00cb9376fc89 | 32.305556 | 82 | 0.679177 | 4.266904 | false | false | false | false |
quran/quran_android | app/src/test/java/com/quran/labs/androidquran/presenter/bookmark/BookmarkPresenterTest.kt | 2 | 10259 | package com.quran.labs.androidquran.presenter.bookmark
import android.content.Context
import android.content.res.Resources
import com.quran.data.core.QuranInfo
import com.quran.data.model.bookmark.Bookmark
import com.quran.data.model.bookmark.BookmarkData
import com.quran.data.model.bookmark.RecentPage
import com.quran.data.model.bookmark.Tag
import com.quran.data.pageinfo.common.MadaniDataSource
import com.quran.labs.androidquran.dao.bookmark.BookmarkResult
import com.quran.labs.androidquran.data.QuranDisplayData
import com.quran.labs.androidquran.database.BookmarksDBAdapter
import com.quran.labs.androidquran.model.bookmark.BookmarkModel
import com.quran.labs.androidquran.model.bookmark.RecentPageModel
import com.quran.labs.androidquran.ui.helpers.QuranRowFactory
import com.quran.labs.androidquran.util.QuranSettings
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.android.plugins.RxAndroidPlugins
import io.reactivex.rxjava3.schedulers.Schedulers
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
import com.google.common.truth.Truth.assertThat
import com.quran.labs.awaitTerminalEvent
import org.mockito.ArgumentMatchers.anyInt
import org.mockito.Mock
import org.mockito.Mockito.`when` as whenever
import org.mockito.MockitoAnnotations
class BookmarkPresenterTest {
companion object {
private val TAG_LIST: MutableList<Tag> = ArrayList(2)
private val RECENT_LIST: MutableList<RecentPage> = ArrayList(1)
private val AYAH_BOOKMARKS_LIST: MutableList<Bookmark> = ArrayList(2)
private val MIXED_BOOKMARKS_LIST: MutableList<Bookmark>
private val RESOURCE_ARRAY: Array<String>
private val AYAH_BOOKMARKS_ROW_COUNT_WHEN_GROUPED_BY_TAG: Int
private val MIXED_BOOKMARKS_ROW_COUNT_WHEN_GROUPED_BY_TAG: Int
@BeforeClass
@JvmStatic
fun setup() {
RxAndroidPlugins.setInitMainThreadSchedulerHandler { Schedulers.io() }
}
init {
// a list of two tags
TAG_LIST.add(Tag(1, "First Tag"))
TAG_LIST.add(Tag(2, "Second Tag"))
// recent page
RECENT_LIST.add(RecentPage(42, System.currentTimeMillis()))
// two ayah bookmarks
AYAH_BOOKMARKS_LIST.add(
Bookmark(42, 46, 1, 502, System.currentTimeMillis(), listOf(2L))
)
AYAH_BOOKMARKS_LIST.add(Bookmark(2, 2, 4, 2, System.currentTimeMillis() - 60000))
// two ayah bookmarks and one page bookmark
MIXED_BOOKMARKS_LIST = ArrayList(AYAH_BOOKMARKS_LIST)
MIXED_BOOKMARKS_LIST.add(
0,
Bookmark(23, null, null, 400, System.currentTimeMillis() + 1, listOf(1L, 2L))
)
// we return this fake array when getStringArray is called
RESOURCE_ARRAY = Array(114) { it.toString() }
// figure out how many rows the bookmarks would occupy if grouped by tags - this is really
// the max between number of tags and 1 for each bookmark.
var total = 0
for (bookmark in AYAH_BOOKMARKS_LIST) {
val tags = bookmark.tags.size
total += tags.coerceAtLeast(1)
}
AYAH_BOOKMARKS_ROW_COUNT_WHEN_GROUPED_BY_TAG = total
total = 0
for (bookmark in MIXED_BOOKMARKS_LIST) {
val tags = bookmark.tags.size
total += tags.coerceAtLeast(1)
}
MIXED_BOOKMARKS_ROW_COUNT_WHEN_GROUPED_BY_TAG = total
}
}
@Mock
private lateinit var appContext: Context
@Mock
private lateinit var resources: Resources
@Mock
private lateinit var settings: QuranSettings
@Mock
private lateinit var bookmarksAdapter: BookmarksDBAdapter
@Mock
private lateinit var recentPageModel: RecentPageModel
@Before
fun setupTest() {
MockitoAnnotations.openMocks(this@BookmarkPresenterTest)
QuranSettings.setInstance(settings)
whenever(appContext.getString(anyInt())).thenReturn("Test")
whenever(appContext.resources).thenReturn(resources)
whenever(resources.getStringArray(anyInt())).thenReturn(RESOURCE_ARRAY)
whenever(appContext.applicationContext).thenReturn(appContext)
}
@Test
fun testBookmarkObservableAyahBookmarksByDate() {
val model: BookmarkModel = object : BookmarkModel(bookmarksAdapter, recentPageModel) {
override fun getBookmarkDataObservable(sortOrder: Int): Single<BookmarkData> {
return Single.zip(
Single.just(ArrayList()),
Single.just(AYAH_BOOKMARKS_LIST),
Single.just(ArrayList())
) { tags: List<Tag>, bookmarks: List<Bookmark>, recentPages: List<RecentPage> ->
BookmarkData(tags, bookmarks, recentPages)
}
}
}
val presenter = makeBookmarkPresenter(model)
val result = getBookmarkResultByDateAndValidate(presenter, false)
assertThat(result.tagMap).isEmpty()
// 1 for the header, plus one row per item
assertThat(result.rows).hasSize(AYAH_BOOKMARKS_LIST.size + 1)
}
@Test
fun testBookmarkObservableMixedBookmarksByDate() {
val model: BookmarkModel = object : BookmarkModel(bookmarksAdapter, recentPageModel) {
override fun getBookmarkDataObservable(sortOrder: Int): Single<BookmarkData> {
return Single.zip(
Single.just(ArrayList()),
Single.just(MIXED_BOOKMARKS_LIST),
Single.just(ArrayList())
) { tags: List<Tag>, bookmarks: List<Bookmark>, recentPages: List<RecentPage> ->
BookmarkData(tags, bookmarks, recentPages)
}
}
}
val presenter = makeBookmarkPresenter(model)
val (rows, tagMap) = getBookmarkResultByDateAndValidate(presenter, false)
assertThat(tagMap).isEmpty()
// 1 for "page bookmarks" and 1 for "ayah bookmarks"
assertThat(rows).hasSize(MIXED_BOOKMARKS_LIST.size + 2)
}
@Test
fun testBookmarkObservableMixedBookmarksByDateWithRecentPage() {
val model: BookmarkModel = object : BookmarkModel(bookmarksAdapter, recentPageModel) {
override fun getBookmarkDataObservable(sortOrder: Int): Single<BookmarkData> {
return Single.zip(
Single.just(TAG_LIST),
Single.just(MIXED_BOOKMARKS_LIST),
Single.just(RECENT_LIST)
) { tags: List<Tag>, bookmarks: List<Bookmark>, recentPages: List<RecentPage> ->
BookmarkData(tags, bookmarks, recentPages)
}
}
}
whenever(settings.lastPage).thenReturn(42)
val presenter = makeBookmarkPresenter(model)
val (rows, tagMap) = getBookmarkResultByDateAndValidate(presenter, false)
assertThat(tagMap).hasSize(2)
// 2 for "current page", 1 for "page bookmarks" and 1 for "ayah bookmarks"
assertThat(rows).hasSize(MIXED_BOOKMARKS_LIST.size + 4)
}
@Test
fun testBookmarkObservableAyahBookmarksGroupedByTag() {
val model: BookmarkModel = object : BookmarkModel(bookmarksAdapter, recentPageModel) {
override fun getBookmarkDataObservable(sortOrder: Int): Single<BookmarkData> {
return Single.zip(
Single.just(TAG_LIST),
Single.just(AYAH_BOOKMARKS_LIST),
Single.just(ArrayList())
) { tags: List<Tag>, bookmarks: List<Bookmark>, recentPages: List<RecentPage> ->
BookmarkData(tags, bookmarks, recentPages)
}
}
}
val presenter = makeBookmarkPresenter(model)
val (rows, tagMap) = getBookmarkResultByDateAndValidate(presenter, true)
assertThat(tagMap).hasSize(2)
// number of tags (or 1) for each bookmark, plus number of tags (headers), plus unsorted
assertThat(rows).hasSize(
AYAH_BOOKMARKS_ROW_COUNT_WHEN_GROUPED_BY_TAG + TAG_LIST.size + 1
)
}
@Test
fun testBookmarkObservableMixedBookmarksGroupedByTag() {
val model: BookmarkModel = object : BookmarkModel(bookmarksAdapter, recentPageModel) {
override fun getBookmarkDataObservable(sortOrder: Int): Single<BookmarkData> {
return Single.zip(
Single.just(TAG_LIST),
Single.just(MIXED_BOOKMARKS_LIST),
Single.just(ArrayList())
) { tags: List<Tag>, bookmarks: List<Bookmark>, recentPages: List<RecentPage> ->
BookmarkData(tags, bookmarks, recentPages)
}
}
}
val presenter = makeBookmarkPresenter(model)
val (rows, tagMap) = getBookmarkResultByDateAndValidate(presenter, true)
assertThat(tagMap).hasSize(2)
// number of tags (or 1) for each bookmark, plus number of tags (headers), plus unsorted
assertThat(rows).hasSize(
MIXED_BOOKMARKS_ROW_COUNT_WHEN_GROUPED_BY_TAG + TAG_LIST.size + 1
)
}
@Test
fun testBookmarkObservableMixedBookmarksGroupedByTagWithRecentPage() {
val model: BookmarkModel = object : BookmarkModel(bookmarksAdapter, recentPageModel) {
override fun getBookmarkDataObservable(sortOrder: Int): Single<BookmarkData> {
return Single.zip(
Single.just(TAG_LIST),
Single.just(MIXED_BOOKMARKS_LIST),
Single.just(RECENT_LIST)
) { tags: List<Tag>, bookmarks: List<Bookmark>, recentPages: List<RecentPage> ->
BookmarkData(tags, bookmarks, recentPages)
}
}
}
val presenter = makeBookmarkPresenter(model)
val (rows, tagMap) = getBookmarkResultByDateAndValidate(presenter, true)
assertThat(tagMap).hasSize(2)
// number of tags (or 1) for each bookmark, plus number of tags (headers), plus unsorted, plus
// current page header, plus current page
assertThat(rows).hasSize(
MIXED_BOOKMARKS_ROW_COUNT_WHEN_GROUPED_BY_TAG + TAG_LIST.size + 1 + 2
)
}
private fun makeBookmarkPresenter(model: BookmarkModel): BookmarkPresenter {
val quranInfo = QuranInfo(MadaniDataSource())
val quranDisplayData = QuranDisplayData(quranInfo)
return object : BookmarkPresenter(
appContext,
model,
settings,
null,
QuranRowFactory(quranInfo, quranDisplayData),
quranInfo
) {
public override fun subscribeToChanges() {
// nothing
}
}
}
private fun getBookmarkResultByDateAndValidate(
presenter: BookmarkPresenter,
groupByTags: Boolean,
): BookmarkResult {
val testObserver = presenter
.getBookmarksListObservable(BookmarksDBAdapter.SORT_DATE_ADDED, groupByTags)
.test()
testObserver.awaitTerminalEvent()
testObserver.assertNoErrors()
testObserver.assertValueCount(1)
return testObserver.values()[0]
}
}
| gpl-3.0 | 976419cede294020be249d30750e796d | 34.49827 | 98 | 0.707086 | 4.150081 | false | true | false | false |
Adven27/Exam | exam-core/src/main/java/io/github/adven27/concordion/extensions/exam/core/CommandRegistry.kt | 1 | 2279 | package io.github.adven27.concordion.extensions.exam.core
import io.github.adven27.concordion.extensions.exam.core.commands.BeforeEachExampleCommand
import io.github.adven27.concordion.extensions.exam.core.commands.ExamExampleCommand
import io.github.adven27.concordion.extensions.exam.core.commands.GivenCommand
import io.github.adven27.concordion.extensions.exam.core.commands.JsonCheckCommand
import io.github.adven27.concordion.extensions.exam.core.commands.JsonEqualsCommand
import io.github.adven27.concordion.extensions.exam.core.commands.JsonEqualsFileCommand
import io.github.adven27.concordion.extensions.exam.core.commands.NamedExamCommand
import io.github.adven27.concordion.extensions.exam.core.commands.SetVarCommand
import io.github.adven27.concordion.extensions.exam.core.commands.TextEqualsCommand
import io.github.adven27.concordion.extensions.exam.core.commands.TextEqualsFileCommand
import io.github.adven27.concordion.extensions.exam.core.commands.ThenCommand
import io.github.adven27.concordion.extensions.exam.core.commands.WaitCommand
import io.github.adven27.concordion.extensions.exam.core.commands.WhenCommand
import io.github.adven27.concordion.extensions.exam.core.commands.XmlCheckCommand
import io.github.adven27.concordion.extensions.exam.core.commands.XmlEqualsCommand
import io.github.adven27.concordion.extensions.exam.core.commands.XmlEqualsFileCommand
class CommandRegistry(jsonVerifier: ContentVerifier, xmlVerifier: ContentVerifier) {
private val commands = mutableListOf<NamedExamCommand>(
GivenCommand(),
WhenCommand(),
ThenCommand(),
ExamExampleCommand("div"),
BeforeEachExampleCommand("div"),
SetVarCommand("set", "pre"),
WaitCommand("span"),
JsonCheckCommand("div", jsonVerifier),
XmlCheckCommand("div", xmlVerifier),
TextEqualsCommand(),
TextEqualsFileCommand(),
XmlEqualsCommand(),
XmlEqualsFileCommand(),
JsonEqualsCommand(),
JsonEqualsFileCommand(),
)
fun getBy(name: String): NamedExamCommand? = commands.firstOrNull { it.name == name }
fun register(cmds: List<NamedExamCommand>) {
commands.addAll(cmds)
}
fun commands(): List<NamedExamCommand> = ArrayList(commands)
}
| mit | 7e69be0eb8f780cae9c530da92a0ea5a | 44.58 | 90 | 0.786749 | 4.128623 | false | false | false | false |
BILLyTheLiTTle/KotlinExperiments | src/main/kotlin/coroutines/Scopes.kt | 1 | 2558 | package coroutines
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
fun main(args: Array<String>) {
val scoped = ScopedCoroutine()
// Run it in a ScopedCoroutine (scoped) --> Coroutine scope active: true
val job1 = runBlocking { scoped.doIt() }
println("Coroutine scope active (job1): ${job1.isActive}")
Thread.sleep(500)
// Run it in a GlobalScope (!= scoped context) --> Global scope active: true
val job2 = runBlocking { scoped.doItGlobally() }
println("Global scope active (job2): ${job2.isActive}")
Thread.sleep(500)
// Run it in a ScopedCoroutine (!= scoped context) --> Other coroutine scope active: true
val job3 = runBlocking { scoped.doItInOtherScope() }
println("Other coroutine scope active (job3): ${job3.isActive}")
Thread.sleep(500)
// Run it in a ScopedCoroutine(scoped context) --> Another(but same!) coroutine scope active: true
val job4 = CoroutineScope(scoped.coroutineContext).launch { doItInAnyScope() }
println("Any(but same!) coroutine scope active (job4): ${job4.isActive}")
Thread.sleep(500)
scoped.coroutineContext.cancel()
println("== Canceling ==")
Thread.sleep(500)
// The ScopedCoroutine scoped is canceled so does job1 --> Coroutine scope active: false
println("Coroutine scope active (job1): ${job1.isActive}")
Thread.sleep(500)
// The ScopedCoroutine scoped is canceled but job2 is not because is a GlobalScope coroutine(!=scoped context) --> Global scope active: true
println("Global scope active (job2): ${job2.isActive}")
Thread.sleep(500)
// The ScopedCoroutine scoped is canceled but job3 is not because is a ScopedCoroutine(!=scoped context) --> Other coroutine scope active: true
println("Other coroutine scope active (job3): ${job3.isActive}")
Thread.sleep(500)
// The ScopedCoroutine scoped is canceled so does job4 because is a ScopedCoroutine(scoped context) --> Another(but same!) coroutine scope active: false
println("Any(but same!) coroutine scope active (job4): ${job4.isActive}")
}
class ScopedCoroutine(): CoroutineScope {
var scopedJob = Job()
override val coroutineContext: CoroutineContext
get() = scopedJob
fun doIt() = launch(Dispatchers.IO) { delay(100000) }
fun doItGlobally() = GlobalScope.launch(Dispatchers.IO) { delay(100000) }
fun doItInOtherScope() = CoroutineScope(Dispatchers.IO).launch { delay(100000) }
}
private suspend fun doItInAnyScope() = coroutineScope { launch(Dispatchers.IO) { delay(100000) } } | gpl-3.0 | 0835d011a9d51cef46f3376ca1ed37d7 | 43.12069 | 156 | 0.706802 | 4.221122 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/command/account/AccountDenyLinkCommand.kt | 1 | 3781 | /*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.players.bukkit.command.account
import com.rpkit.players.bukkit.RPKPlayersBukkit
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import com.rpkit.players.bukkit.profile.RPKProfileImpl
import com.rpkit.players.bukkit.profile.RPKProfileProvider
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
class AccountDenyLinkCommand(private val plugin: RPKPlayersBukkit): CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (sender !is Player) {
sender.sendMessage(plugin.messages["not-from-console"])
return true
}
if (args.size <= 1) {
sender.sendMessage(plugin.messages["account-deny-link-usage"])
return true
}
val type = args[0]
val id = args[1].toIntOrNull()
when (type.toLowerCase()) {
"minecraft" -> {
if (id == null) {
sender.sendMessage(plugin.messages["account-deny-link-invalid-id"])
return true
}
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender)
if (minecraftProfile == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile-self"])
return true
}
val linkRequests = minecraftProfileProvider.getMinecraftProfileLinkRequests(minecraftProfile)
val linkRequest = linkRequests.firstOrNull { request -> request.profile.id == id }
if (linkRequest == null) {
sender.sendMessage(plugin.messages["account-deny-link-invalid-request"])
return true
}
minecraftProfileProvider.removeMinecraftProfileLinkRequest(linkRequest)
if (linkRequests.isNotEmpty()) {
sender.sendMessage(plugin.messages["account-deny-link-valid"])
return true
}
// If they no longer have any link requests pending, we can create a new profile for them based on their
// Minecraft profile.
val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class)
val profile = RPKProfileImpl(
minecraftProfile.minecraftUsername,
""
)
profileProvider.addProfile(profile)
minecraftProfile.profile = profile
minecraftProfileProvider.updateMinecraftProfile(minecraftProfile)
sender.sendMessage(plugin.messages["account-deny-link-profile-created"])
return true
}
else -> {
sender.sendMessage(plugin.messages["account-deny-link-invalid-type"])
return true
}
}
}
} | apache-2.0 | 54c042e9fb2569542b5ac81f18e21ef4 | 44.566265 | 128 | 0.633695 | 5.302945 | false | false | false | false |
square/sqldelight | sqldelight-compiler/src/main/kotlin/com/squareup/sqldelight/core/lang/IntermediateType.kt | 1 | 5600 | /*
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.squareup.sqldelight.core.lang
import com.alecstrong.sql.psi.core.psi.Queryable
import com.alecstrong.sql.psi.core.psi.SqlBindExpr
import com.alecstrong.sql.psi.core.psi.SqlColumnDef
import com.intellij.psi.util.PsiTreeUtil
import com.squareup.kotlinpoet.BOOLEAN
import com.squareup.kotlinpoet.BYTE
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FLOAT
import com.squareup.kotlinpoet.INT
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.SHORT
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.asClassName
import com.squareup.sqldelight.core.compiler.integration.adapterName
import com.squareup.sqldelight.core.dialect.api.DialectType
import com.squareup.sqldelight.core.lang.psi.ColumnTypeMixin
import com.squareup.sqldelight.core.lang.util.isArrayParameter
/**
* Internal representation for a column type, which has SQLite data affinity as well as JVM class
* type.
*/
internal data class IntermediateType(
val dialectType: DialectType,
val javaType: TypeName = dialectType.javaType,
/**
* The column definition this type is sourced from, or null if there is none.
*/
val column: SqlColumnDef? = null,
/**
* The name of this intermediate type as exposed in the generated api.
*/
val name: String = "value",
/**
* The original bind argument expression this intermediate type comes from.
*/
val bindArg: SqlBindExpr? = null,
/**
* Whether or not this argument is extracted from a different type
*/
val extracted: Boolean = false,
/**
* The types assumed to be compatible with this type. Validated at runtime.
*/
val assumedCompatibleTypes: List<IntermediateType> = emptyList(),
) {
fun asNullable() = copy(javaType = javaType.copy(nullable = true))
fun asNonNullable() = copy(javaType = javaType.copy(nullable = false))
fun nullableIf(predicate: Boolean): IntermediateType {
return if (predicate) asNullable() else asNonNullable()
}
fun argumentType() = if (bindArg?.isArrayParameter() == true) {
Collection::class.asClassName().parameterizedBy(javaType)
} else {
javaType
}
/**
* @return A [CodeBlock] which binds this type to [columnIndex] on [STATEMENT_NAME].
*
* eg: statement.bindBytes(0, queryWrapper.tableNameAdapter.columnNameAdapter.encode(column))
*/
fun preparedStatementBinder(
columnIndex: String
): CodeBlock {
val name = if (javaType.isNullable) "it" else this.name
val value = (column?.columnType as ColumnTypeMixin?)?.adapter()?.let { adapter ->
val adapterName = PsiTreeUtil.getParentOfType(column, Queryable::class.java)!!.tableExposed().adapterName
dialectType.encode(CodeBlock.of("$CUSTOM_DATABASE_NAME.$adapterName.%N.encode($name)", adapter))
} ?: when (javaType.copy(nullable = false)) {
FLOAT -> CodeBlock.of("$name.toDouble()")
BYTE -> CodeBlock.of("$name.toLong()")
SHORT -> CodeBlock.of("$name.toLong()")
INT -> CodeBlock.of("$name.toLong()")
BOOLEAN -> CodeBlock.of("if ($name) 1L else 0L")
else -> {
return dialectType.prepareStatementBinder(columnIndex, dialectType.encode(CodeBlock.of(this.name)))
}
}
if (javaType.isNullable) {
return dialectType.prepareStatementBinder(
columnIndex,
CodeBlock.builder()
.add("${this.name}?.let { ")
.add(value)
.add(" }")
.build()
)
}
return dialectType.prepareStatementBinder(columnIndex, value)
}
fun cursorGetter(columnIndex: Int): CodeBlock {
var cursorGetter = dialectType.cursorGetter(columnIndex)
if (!javaType.isNullable) {
cursorGetter = CodeBlock.of("$cursorGetter!!")
}
return (column?.columnType as ColumnTypeMixin?)?.adapter()?.let { adapter ->
val adapterName = PsiTreeUtil.getParentOfType(column, Queryable::class.java)!!.tableExposed().adapterName
if (javaType.isNullable) {
CodeBlock.of("%L?.let { $CUSTOM_DATABASE_NAME.$adapterName.%N.decode(%L) }", cursorGetter, adapter, dialectType.decode(CodeBlock.of("it")))
} else {
CodeBlock.of("$CUSTOM_DATABASE_NAME.$adapterName.%N.decode(%L)", adapter, dialectType.decode(cursorGetter))
}
} ?: when (javaType) {
FLOAT -> CodeBlock.of("$cursorGetter.toFloat()")
FLOAT.copy(nullable = true) -> CodeBlock.of("$cursorGetter?.toFloat()")
BYTE -> CodeBlock.of("$cursorGetter.toByte()")
BYTE.copy(nullable = true) -> CodeBlock.of("$cursorGetter?.toByte()")
SHORT -> CodeBlock.of("$cursorGetter.toShort()")
SHORT.copy(nullable = true) -> CodeBlock.of("$cursorGetter?.toShort()")
INT -> CodeBlock.of("$cursorGetter.toInt()")
INT.copy(nullable = true) -> CodeBlock.of("$cursorGetter?.toInt()")
BOOLEAN -> CodeBlock.of("$cursorGetter == 1L")
BOOLEAN.copy(nullable = true) -> CodeBlock.of("$cursorGetter?.let { it == 1L }")
else -> cursorGetter
}
}
}
| apache-2.0 | 1b220c19760f1c0ded79ae5d229b7463 | 38.160839 | 147 | 0.700714 | 4.182226 | false | false | false | false |
DR-YangLong/spring-boot-kotlin-demo | src/main/kotlin/site/yanglong/promotion/config/DruidStatConfig.kt | 1 | 1866 | package site.yanglong.promotion.config
import com.alibaba.druid.support.http.StatViewServlet
import com.alibaba.druid.support.http.WebStatFilter
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.web.servlet.FilterRegistrationBean
import org.springframework.boot.web.servlet.ServletRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
/**
* package: site.yanglong.promotion.config <br/>
* functional describe:druid monitor
*
* @author DR.YangLong [[email protected]]
* @version 1.0 2017/7/12
*/
@Configuration
@ConfigurationProperties(prefix = "druid.stat")
class DruidStatConfig {
var userName:String?=null
var password:String?=null
var resetEnable:String?=null
var allow:String?=null
var deny:String?=null
@Bean
fun druidStatServlet(): ServletRegistrationBean {
val servletRegistrationBean = ServletRegistrationBean()
servletRegistrationBean.setServlet(StatViewServlet())
servletRegistrationBean.addUrlMappings("/druid/*")
servletRegistrationBean.initParameters = mapOf("allow" to allow, "deny" to deny,
"loginUsername" to userName,
"loginPassword" to password,
"resetEnable" to resetEnable)
return servletRegistrationBean
}
@Bean
fun druidStatFilter(): FilterRegistrationBean {
val filterRegistrationBean = FilterRegistrationBean()
filterRegistrationBean.filter = WebStatFilter()
filterRegistrationBean.setName("druidWebStatFilter")
filterRegistrationBean.urlPatterns = listOf("/druid/**")
filterRegistrationBean.initParameters = mapOf("exclusions" to "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")
return filterRegistrationBean
}
} | apache-2.0 | 74512718528d217d26b4511cbc4ac371 | 37.102041 | 122 | 0.737406 | 4.390588 | false | true | false | false |
openbase/jul | module/transformation/src/main/java/org/openbase/rct/examples/Cross_lib_provider.kt | 1 | 7147 | package org.openbase.rct.examples
import org.openbase.rct.*
import org.openbase.rct.TransformerFactory.TransformerFactoryException
import org.slf4j.LoggerFactory
import java.util.logging.Level
import java.util.logging.Logger
import javax.media.j3d.Transform3D
import javax.vecmath.Quat4f
import javax.vecmath.Vector3d
import javax.vecmath.Vector4d
/*-
* #%L
* RCT
* %%
* Copyright (C) 2015 - 2022 openbase.org
* %%
* 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 General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/ /**
*
* @author nkoester
*/
class Cross_lib_provider {
var receiver: TransformReceiver? = null
private fun yrp2q(roll: Float, pitch: Float, yaw: Float): Quat4f {
val halfYaw = yaw * 0.5f
val halfPitch = pitch * 0.5f
val halfRoll = roll * 0.5f
val cosYaw = Math.cos(halfYaw.toDouble()).toFloat()
val sinYaw = Math.sin(halfYaw.toDouble()).toFloat()
val cosPitch = Math.cos(halfPitch.toDouble()).toFloat()
val sinPitch = Math.sin(halfPitch.toDouble()).toFloat()
val cosRoll = Math.cos(halfRoll.toDouble()).toFloat()
val sinRoll = Math.sin(halfRoll.toDouble()).toFloat()
return Quat4f(
sinRoll * cosPitch * cosYaw - cosRoll * sinPitch * sinYaw, //x
cosRoll * sinPitch * cosYaw + sinRoll * cosPitch * sinYaw, //y
cosRoll * cosPitch * sinYaw - sinRoll * sinPitch * cosYaw, //z
cosRoll * cosPitch * cosYaw + sinRoll * sinPitch * sinYaw
) //formerly yzx
}
@Throws(InterruptedException::class, TransformerException::class, TransformerFactoryException::class)
private fun provide() {
var publisher = TransformerFactory.getInstance().createTransformPublisher("java_provider")
////////////////
// STATIC
////////////////
// Define the translation
val translation = Vector3d(0.0, 1.0, 1.0)
// Define the rotation
//Quat4f rotation = yrp2q(0.0f, 0.0f, 0.0f);
val rotation = yrp2q(0.0f, 0.0f, -Math.PI.toFloat() / 2)
val rot_val = Math.PI.toFloat() / 2
val rot_val_d = Math.PI / 2
println("Using translation: $translation")
println("Using rotation : $rotation")
// Create the transformation
val transform = Transform3D(rotation, translation, 1.0)
val transform_base_java = Transform(transform, "base", "java_static", System.currentTimeMillis())
// Publish the static offset
println("Sending static transform now ...")
publisher.sendTransform(transform_base_java, TransformType.STATIC)
////////////////
// DYNAMIC
////////////////
// translate further along the original y axis
val translation_dyn = Vector3d(-1.0, 0.0, -2.0)
// Define the rotation
val rotation_dyn = yrp2q(0.0f, 0.0f, -Math.PI.toFloat() / 2)
// Create the transformation
val transform_dyn = Transform3D(rotation_dyn, translation_dyn, 1.0)
println("Sending dynamic transform now ...")
// Publish the static offset
while (true) {
val transform_java_java_dynamic =
Transform(transform_dyn, "java_static", "java_dynamic", System.currentTimeMillis())
publisher.sendTransform(transform_java_java_dynamic, TransformType.DYNAMIC)
}
}
@Throws(InterruptedException::class, TransformerException::class)
private fun transform_now(source: String, target: String, point: Vector4d): Vector4d {
val `when` = System.currentTimeMillis()
return if (receiver!!.canTransform(target, source, `when`)) {
val (transform, parentNode, childNode) = receiver!!.lookupTransform(target, source, `when`)
println("[$childNode] --> [$parentNode]")
val point4d = Vector4d(point.x, point.y, point.z, 1.0)
transform.transform(point4d)
point4d
} else {
println("Error: Cannot transfrom $source --> $target")
Vector4d()
}
}
@Throws(InterruptedException::class, TransformerException::class, TransformerFactoryException::class)
private fun test() {
receiver = TransformerFactory.getInstance().createTransformReceiver()
println("Gathering available transformations ...")
Thread.sleep(1000)
// The different systems and the base
val targets = arrayOf("java_static", "java_dynamic", "python_static", "python_dynamic")
val base = "base"
val point = Vector4d(1.0, 1.0, 1.0, 1.0)
println("Point to transform: $point\n")
for (target in targets) {
// Forward transfrom
val transformed_point = transform_now(base, target, point)
println("[$point] --> [$transformed_point]")
// Backward transfrom
val re_transformed_point = transform_now(target, base, transformed_point)
println("[$transformed_point] --> [$re_transformed_point]")
println()
}
System.exit(0)
}
companion object {
private val logger = LoggerFactory.getLogger(Cross_lib_provider::class.java)
fun usage() {
println("ERROR: Please provide task argument!")
println()
println("Usage: program [TASK_ARGUMENT] (where TASK_ARGUMENT is either 'provide' or 'test')")
}
@JvmStatic
fun main(args: Array<String>) {
if (args.size == 1) {
val start_type = args[0]
try {
val prov = Cross_lib_provider()
if (start_type == "provide") {
prov.provide()
} else if (start_type == "test") {
prov.test()
} else {
println("Unknown type: $start_type")
usage()
}
} catch (ex: InterruptedException) {
Logger.getLogger(Cross_lib_provider::class.java.name).log(Level.SEVERE, null, ex)
} catch (ex: TransformerException) {
Logger.getLogger(Cross_lib_provider::class.java.name).log(Level.SEVERE, null, ex)
} catch (ex: TransformerFactoryException) {
Logger.getLogger(Cross_lib_provider::class.java.name).log(Level.SEVERE, null, ex)
}
} else {
println("No arg given ...")
usage()
}
}
}
}
| lgpl-3.0 | 99d1a4a120a2b828c8170451f78a6aeb | 39.607955 | 105 | 0.596754 | 4.167347 | false | false | false | false |
premnirmal/StockTicker | app/src/main/kotlin/com/github/premnirmal/ticker/home/MainActivity.kt | 1 | 8221 | package com.github.premnirmal.ticker.home
import android.Manifest
import android.os.Build.VERSION
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
import androidx.activity.viewModels
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.lifecycleScope
import com.github.premnirmal.ticker.analytics.ClickEvent
import com.github.premnirmal.ticker.base.BaseActivity
import com.github.premnirmal.ticker.components.InAppMessage
import com.github.premnirmal.ticker.hasNotificationPermission
import com.github.premnirmal.ticker.network.CommitsProvider
import com.github.premnirmal.ticker.network.NewsProvider
import com.github.premnirmal.ticker.news.NewsFeedFragment
import com.github.premnirmal.ticker.notifications.NotificationsHandler
import com.github.premnirmal.ticker.portfolio.search.SearchFragment
import com.github.premnirmal.ticker.settings.SettingsParentFragment
import com.github.premnirmal.ticker.showDialog
import com.github.premnirmal.ticker.viewBinding
import com.github.premnirmal.ticker.widget.WidgetDataProvider
import com.github.premnirmal.ticker.widget.WidgetsFragment
import com.github.premnirmal.tickerwidget.BuildConfig
import com.github.premnirmal.tickerwidget.R
import com.github.premnirmal.tickerwidget.databinding.ActivityMainBinding
import com.google.android.material.elevation.SurfaceColors
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* Created by premnirmal on 2/25/16.
*/
@AndroidEntryPoint
class MainActivity : BaseActivity<ActivityMainBinding>() {
companion object {
private const val DIALOG_SHOWN: String = "DIALOG_SHOWN"
private val FRAGMENT_MAP =
mapOf<Int, String>(R.id.action_portfolio to HomeFragment::class.java.name,
R.id.action_widgets to WidgetsFragment::class.java.name,
R.id.action_search to SearchFragment::class.java.name,
R.id.action_settings to SettingsParentFragment::class.java.name,
R.id.action_feed to NewsFeedFragment::class.java.name)
}
@Inject internal lateinit var widgetDataProvider: WidgetDataProvider
@Inject internal lateinit var commitsProvider: CommitsProvider
@Inject internal lateinit var newsProvider: NewsProvider
@Inject internal lateinit var appReviewManager: IAppReviewManager
@Inject internal lateinit var notificationsHandler: NotificationsHandler
private var currentChild: ChildFragment? = null
private var rateDialogShown = false
override val simpleName: String = "MainActivity"
override val binding: ActivityMainBinding by viewBinding(ActivityMainBinding::inflate)
private val viewModel: MainViewModel by viewModels()
private lateinit var requestPermissionLauncher: ActivityResultLauncher<String>
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
super.onCreate(savedInstanceState)
initCaches()
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility or
(View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
window.navigationBarColor = SurfaceColors.SURFACE_2.getColor(this)
savedInstanceState?.let { rateDialogShown = it.getBoolean(DIALOG_SHOWN, false) }
binding.bottomNavigation.setOnItemSelectedListener { onNavigationItemSelected(it) }
binding.bottomNavigation.setOnItemReselectedListener { onNavigationItemReselected(it) }
currentChild = if (savedInstanceState == null) {
val fragment = HomeFragment()
supportFragmentManager.beginTransaction()
.add(R.id.fragment_container, fragment, fragment.javaClass.name)
.commit()
fragment
} else {
supportFragmentManager.findFragmentById(R.id.fragment_container) as ChildFragment
}
val tutorialShown = appPreferences.tutorialShown()
if (!tutorialShown) {
showTutorial()
}
if (appPreferences.getLastSavedVersionCode() < BuildConfig.VERSION_CODE) {
showWhatsNew()
}
if (VERSION.SDK_INT >= 33) {
requestPermissionLauncher = registerForActivityResult(RequestPermission()) { granted ->
if (granted) {
notificationsHandler.initialize()
} else {
InAppMessage.showMessage(this, R.string.notification_alerts_required_message)
}
}
viewModel.requestNotificationPermission.observe(this) {
if (it == true) {
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
viewModel.resetRequestNotificationPermission()
}
}
}
if (VERSION.SDK_INT >= 33 && appPreferences.notificationAlerts() && !hasNotificationPermission()) {
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
viewModel.showTutorial.observe(this) {
if (it == true) {
showTutorial()
viewModel.resetShowTutorial()
}
}
viewModel.showWhatsNew.observe(this) {
if (it == true) {
showWhatsNew()
viewModel.resetShowWhatsNew()
}
}
viewModel.openSearchWidgetId.observe(this) {
it?.let {
openSearch(it)
viewModel.resetOpenSearch()
}
}
}
override fun onResume() {
super.onResume()
binding.bottomNavigation.menu.findItem(R.id.action_widgets).isEnabled = widgetDataProvider.hasWidget()
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putBoolean(DIALOG_SHOWN, rateDialogShown)
super.onSaveInstanceState(outState)
}
private fun initCaches() {
// not sure why news provider is not getting initialised, so added this check
if (::newsProvider.isInitialized) newsProvider.initCache()
if (appPreferences.getLastSavedVersionCode() < BuildConfig.VERSION_CODE) {
commitsProvider.initCache()
}
}
private fun onNavigationItemSelected(item: MenuItem): Boolean {
val itemId = item.itemId
var fragment = supportFragmentManager.findFragmentByTag(FRAGMENT_MAP[itemId])
if (fragment == null) {
fragment = when (itemId) {
R.id.action_portfolio -> HomeFragment()
R.id.action_widgets -> WidgetsFragment()
R.id.action_search -> SearchFragment()
R.id.action_settings -> SettingsParentFragment()
R.id.action_feed -> NewsFeedFragment()
else -> {
throw IllegalStateException("Unknown bottom nav itemId: $itemId - ${item.title}")
}
}
if (fragment != currentChild) {
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment, fragment::class.java.name)
.commit()
} else return false
}
currentChild = fragment as ChildFragment
analytics.trackClickEvent(
ClickEvent("BottomNavClick")
.addProperty("NavItem", item.title.toString())
)
if (!rateDialogShown && !appPreferences.shouldPromptRate()) {
appReviewManager.launchReviewFlow(this)
rateDialogShown = true
}
return true
}
private fun onNavigationItemReselected(item: MenuItem) {
val itemId = item.itemId
val fragment = supportFragmentManager.findFragmentByTag(FRAGMENT_MAP[itemId])
(fragment as? ChildFragment)?.scrollToTop()
}
private fun showTutorial() {
showDialog(getString(R.string.how_to_title), getString(R.string.how_to))
appPreferences.setTutorialShown(true)
}
private fun showWhatsNew() {
val dialog = showDialog(
getString(R.string.whats_new_in, BuildConfig.VERSION_NAME),
getString(R.string.loading)
)
lifecycleScope.launch {
commitsProvider.fetchWhatsNew().apply {
if (wasSuccessful) {
val whatsNew = data.joinToString("\n\u25CF ", "\u25CF ")
dialog.setMessage(whatsNew)
appPreferences.saveVersionCode(BuildConfig.VERSION_CODE)
} else {
dialog.setMessage("${getString(R.string.error_fetching_whats_new)}\n\n :( ${error.message.orEmpty()}")
}
}
}
}
private fun openSearch(widgetId: Int) {
binding.bottomNavigation.selectedItemId = R.id.action_search
}
} | gpl-3.0 | 54e7953a8129c9132c254057ac0a80c8 | 37.064815 | 112 | 0.733974 | 4.618539 | false | false | false | false |
systemallica/ValenBisi | app/src/main/kotlin/com/systemallica/valenbisi/activities/MainActivity.kt | 1 | 7788 | package com.systemallica.valenbisi.activities
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentTransaction
import androidx.preference.PreferenceManager.getDefaultSharedPreferences
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
import com.google.android.play.core.install.InstallState
import com.google.android.play.core.install.model.AppUpdateType
import com.google.android.play.core.install.model.InstallStatus
import com.google.android.play.core.install.model.UpdateAvailability
import com.systemallica.valenbisi.R
import com.systemallica.valenbisi.databinding.ActivityMainBinding
import com.systemallica.valenbisi.fragments.AboutFragment
import com.systemallica.valenbisi.fragments.MapsFragment
import com.systemallica.valenbisi.fragments.SettingsFragment
import kotlin.system.exitProcess
class MainActivity : AppCompatActivity() {
private lateinit var inflatedFragment: CharSequence
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
initActivity()
if (savedInstanceState == null) {
//Inflate main fragment
val fragmentTransaction = supportFragmentManager.beginTransaction()
// Change fragment
fragmentTransaction.replace(R.id.containerView, MapsFragment()).commitNow()
title = getString(R.string.app_name)
inflatedFragment = getString(R.string.app_name)
binding.bottomNavigationView.menu.getItem(0).isChecked = true
} else {
inflatedFragment = savedInstanceState.getCharSequence("inflatedFragment")!!
}
checkInternetAccess()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putCharSequence("inflatedFragment", inflatedFragment)
}
private fun initActivity() {
setSupportActionBar(binding.toolbar)
setOnNavigationListener()
initNavBarColor()
}
private fun checkInternetAccess() {
//Check if current network has internet access
val cm =
applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork = cm.activeNetwork
val networkCapabilities = cm.getNetworkCapabilities(cm.activeNetwork)
val isConnected = networkCapabilities?.hasCapability(NET_CAPABILITY_INTERNET)
//React to the check
if (activeNetwork == null || (isConnected != null && !isConnected)) {
AlertDialog.Builder(this)
.setTitle(R.string.no_internet)
.setMessage(R.string.no_internet_message)
.setPositiveButton(R.string.close
) { _, _ ->
exitProcess(0)
}
.setNegativeButton(R.string.continuer
) { _, _ ->
// Do nothing
}
.setIcon(R.drawable.icon_alert)
.show()
} else {
// Check for updates if there's an internet connection
getLatestVersion()
}
}
private fun setOnNavigationListener() {
binding.bottomNavigationView.setOnItemSelectedListener { item ->
if (inflatedFragment == item.title) return@setOnItemSelectedListener false
val id = item.itemId
val fragmentTransaction = supportFragmentManager.beginTransaction()
when (id) {
R.id.nav_map -> {
inflatedFragment = item.title
fragmentTransaction.replace(R.id.containerView, MapsFragment())
}
R.id.nav_settings -> {
inflatedFragment = item.title
fragmentTransaction.replace(R.id.containerView, SettingsFragment())
}
R.id.nav_about -> {
inflatedFragment = item.title
fragmentTransaction.replace(R.id.containerView, AboutFragment())
}
}
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commitNow()
return@setOnItemSelectedListener true
}
}
private fun initNavBarColor() {
val userSettings = getDefaultSharedPreferences(applicationContext)
val navBar = userSettings.getBoolean("navBar", true)
val colorPrimary = ContextCompat.getColor(applicationContext, R.color.colorPrimary)
if (navBar) {
window.navigationBarColor = colorPrimary
}
}
// Create a listener to track request state updates.
private val updateStateListener = { state: InstallState ->
Log.i("valenbisi", state.installStatus().toString())
if (state.installStatus() == InstallStatus.DOWNLOADING) {
val bytesDownloaded = state.bytesDownloaded()
val totalBytesToDownload = state.totalBytesToDownload()
Log.i("valenbisi", bytesDownloaded.toString())
Log.i("valenbisi", totalBytesToDownload.toString())
}
if (state.installStatus() == InstallStatus.DOWNLOADED) {
Log.i("valenbisi", "launch snackbar")
popupForCompleteUpdate()
}
}
private fun getLatestVersion() {
val appUpdateManager = AppUpdateManagerFactory.create(this)
val appUpdateInfoTask = appUpdateManager.appUpdateInfo
appUpdateInfoTask.addOnFailureListener { appUpdateInfo ->
Log.e("valenbisi update error", appUpdateInfo.toString())
}
// Checks that the platform will allow the specified type of update.
appUpdateInfoTask.addOnSuccessListener { appUpdateInfo ->
Log.i("valenbisi update", appUpdateInfo.toString())
// Before starting an update, register a listener for updates.
appUpdateManager.registerListener(updateStateListener)
Log.i("valenbisi update type", appUpdateInfo.updateAvailability().toString())
if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE) {
appUpdateManager.startUpdateFlowForResult(
appUpdateInfo,
AppUpdateType.FLEXIBLE,
this,
1)
}
}
}
private fun popupForCompleteUpdate() {
runOnUiThread {
val builder = AlertDialog.Builder(this@MainActivity)
builder.setTitle(R.string.update_download)
.setMessage(R.string.update_download)
.setIcon(R.drawable.icon_update)
.setPositiveButton(R.string.update_ok) { _, _ ->
val appUpdateManager = AppUpdateManagerFactory.create(applicationContext)
appUpdateManager.completeUpdate()
appUpdateManager.unregisterListener(updateStateListener)
}
.setNegativeButton(R.string.update_not_now) { _, _ ->
// Do nothing
}
val dialog = builder.create()
dialog.show()
}
}
public override fun onDestroy() {
super.onDestroy()
}
}
| gpl-3.0 | d47eda2cf2e67c4531c924f891b644db | 38.532995 | 104 | 0.637391 | 5.38217 | false | false | false | false |
googlecodelabs/android-compose-codelabs | NavigationCodelab/app/src/main/java/com/example/compose/rally/ui/components/DetailsScreen.kt | 1 | 2983 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.compose.rally.ui.components
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
/**
* Generic component used by the accounts and bills screens to show a chart and a list of items.
*/
@Composable
fun <T> StatementBody(
modifier: Modifier = Modifier,
items: List<T>,
colors: (T) -> Color,
amounts: (T) -> Float,
amountsTotal: Float,
circleLabel: String,
rows: @Composable (T) -> Unit
) {
Column(modifier = modifier.verticalScroll(rememberScrollState())) {
Box(Modifier.padding(16.dp)) {
val accountsProportion = items.extractProportions { amounts(it) }
val circleColors = items.map { colors(it) }
AnimatedCircle(
accountsProportion,
circleColors,
Modifier
.height(300.dp)
.align(Alignment.Center)
.fillMaxWidth()
)
Column(modifier = Modifier.align(Alignment.Center)) {
Text(
text = circleLabel,
style = MaterialTheme.typography.body1,
modifier = Modifier.align(Alignment.CenterHorizontally)
)
Text(
text = formatAmount(amountsTotal),
style = MaterialTheme.typography.h2,
modifier = Modifier.align(Alignment.CenterHorizontally)
)
}
}
Spacer(Modifier.height(10.dp))
Card {
Column(modifier = Modifier.padding(12.dp)) {
items.forEach { item ->
rows(item)
}
}
}
}
}
| apache-2.0 | cb5281e74ec679287e27961cbdf59026 | 34.939759 | 96 | 0.649011 | 4.682889 | false | false | false | false |
nickthecoder/tickle | tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/util/CodeEditor.kt | 1 | 8575 | /*
Tickle
Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.tickle.editor.util
import javafx.application.Platform
import javafx.event.EventHandler
import javafx.scene.control.ContextMenu
import javafx.scene.control.Label
import javafx.scene.control.MenuItem
import javafx.scene.control.SeparatorMenuItem
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import javafx.scene.input.MouseEvent
import javafx.scene.layout.BorderPane
import javafx.scene.layout.VBox
import uk.co.nickthecoder.tedi.SourceCodeWordIterator
import uk.co.nickthecoder.tedi.TediArea
import uk.co.nickthecoder.tedi.syntax.GroovySyntax
import uk.co.nickthecoder.tedi.syntax.HighlightMatchedPairs
import uk.co.nickthecoder.tedi.ui.FindBar
import uk.co.nickthecoder.tedi.ui.RemoveHiddenChildren
import uk.co.nickthecoder.tedi.ui.ReplaceBar
import uk.co.nickthecoder.tedi.ui.TextInputControlMatcher
import uk.co.nickthecoder.tedi.util.requestFocusOnSceneAvailable
import uk.co.nickthecoder.tickle.scripts.ScriptException
import java.io.File
import java.util.regex.Pattern
class CodeEditor {
val borderPane = BorderPane()
val tediArea = TediArea()
private val error = Label("")
private val findAndReplaceBox = VBox()
private val matcher = TextInputControlMatcher(tediArea)
private val findBar = FindBar(matcher)
private val replaceBar = ReplaceBar(matcher)
init {
with(tediArea) {
styleClass.add("code")
displayLineNumbers = true
wordIterator = SourceCodeWordIterator()
GroovySyntax.instance.attach(tediArea)
HighlightMatchedPairs(tediArea)
}
findBar.toolBar.styleClass.add(".bottom")
replaceBar.toolBar.styleClass.add(".bottom")
RemoveHiddenChildren(findAndReplaceBox.children)
findAndReplaceBox.children.addAll(error, findBar.toolBar, replaceBar.toolBar)
// Hides the find and replace toolbars.
matcher.inUse = false
with(borderPane) {
center = tediArea
bottom = findAndReplaceBox
}
error.isVisible = false
error.styleClass.add("code-error")
borderPane.addEventFilter(KeyEvent.KEY_PRESSED) { onKeyPressed(it) }
tediArea.addEventFilter(MouseEvent.MOUSE_PRESSED) { onMousePressedRelease(it) }
tediArea.addEventFilter(MouseEvent.MOUSE_RELEASED) { onMousePressedRelease(it) }
}
fun highlightError(e: ScriptException) {
val line = e.line
if (line != null) {
error.onMouseClicked = EventHandler {
tediArea.requestFocus()
Platform.runLater {
positionCaret(line, e.column)
}
}
tediArea.requestFocus()
Platform.runLater {
positionCaret(line, e.column)
}
} else {
error.onMouseClicked = null
}
error.text = e.message
error.isVisible = true
tediArea.requestFocus()
}
fun hideError() {
error.isVisible = false
}
fun positionCaret(line: Int, column: Int?) {
if (column == null) {
tediArea.positionCaret(tediArea.positionOfLine(line - 1))
} else {
tediArea.positionCaret(tediArea.positionOfLine(line - 1, column - 1))
}
}
fun load(file: File) {
tediArea.text = file.readText()
}
fun save(file: File) {
file.writeText(tediArea.text)
}
fun onMousePressedRelease(event: MouseEvent) {
if (event.isPopupTrigger) {
tediArea.contextMenu = buildContextMenu(event)
tediArea.contextMenu?.let {
tediArea.contextMenu.show(tediArea, event.screenX, event.screenY)
event.consume()
}
}
}
fun buildContextMenu(event: MouseEvent): ContextMenu? {
val menu = ContextMenu()
var addSeparator = false
fun addItem(item: MenuItem) {
if (addSeparator && menu.items.isNotEmpty()) {
menu.items.add(SeparatorMenuItem())
}
menu.items.add(item)
}
val word = wordAt(event)
if (word != null) {
val classNames = findClasses(word)
classNames.filter { !isImported(it) }.forEach { className ->
val item2 = MenuItem("Import $className")
item2.onAction = EventHandler { addImport(className) }
addItem(item2)
val pack = packageName(className)
val item1 = MenuItem("Import $pack.*")
item1.onAction = EventHandler { addImport("$pack.*") }
addItem(item1)
}
if (classNames.size > 1) addSeparator = true
}
return if (menu.items.isEmpty()) null else menu
}
fun isImported(className: String): Boolean {
val im = importPattern.matcher(tediArea.text)
while (im.find()) {
val imp = im.group("IMPORT")
if (imp == className || imp == "${packageName(className)}.*") {
return true
}
}
return false
}
fun packageName(className: String) = className.substring(0, className.lastIndexOf('.'))
fun findClasses(word: String): List<String> {
return ClassMetaData.simpleClassNameToNames[word] ?: emptyList()
}
fun addImport(imp: String) {
tediArea.insertText(importPosition(), "import $imp\n")
}
fun importPosition(): Int {
val text = tediArea.text
var pos = 0
val pm = packagePattern.matcher(text)
while (pm.find()) {
pos = tediArea.positionOfLine(1 + tediArea.lineForPosition(pm.start()))
}
val im = importPattern.matcher(text)
while (im.find()) {
pos = tediArea.positionOfLine(1 + tediArea.lineForPosition(im.start()))
}
return pos
}
fun wordAt(event: MouseEvent): String? {
val pos = tediArea.positionForPoint(event.x, event.y)
val (line, column) = tediArea.lineColumnForPosition(pos)
val lineText = tediArea.paragraphs[line].text
// Find the word at the given point
val matcher = wordPattern.matcher(lineText)
while (matcher.find()) {
if (matcher.start() <= column && matcher.end() >= column) {
return lineText.substring(matcher.start(), matcher.end())
}
}
return null
}
fun onKeyPressed(event: KeyEvent) {
var consume = true
if (event.isControlDown) {
when (event.code) {
// Toggle Line Numbers
KeyCode.L -> tediArea.displayLineNumbers = !tediArea.displayLineNumbers
// FIND
KeyCode.F -> {
matcher.inUse = true
findBar.find.requestFocusOnSceneAvailable()
}
// Replace (R is already used for "Run")
KeyCode.H -> {
val wasInUse = matcher.inUse
replaceBar.toolBar.isVisible = true
if (wasInUse) {
replaceBar.replacement.requestFocusOnSceneAvailable()
}
}
else -> consume = false
}
} else {
when (event.code) {
KeyCode.ESCAPE -> {
matcher.inUse = false
tediArea.requestFocus()
}
else -> consume = false
}
}
if (consume) {
event.consume()
}
}
companion object {
val wordPattern: Pattern = Pattern.compile("\\b\\w+?\\b")
val packagePattern: Pattern = Pattern.compile("^\\spackage", Pattern.MULTILINE)
val importPattern: Pattern = Pattern.compile("^\\s*import\\s(?<IMPORT>.*)\\s", Pattern.MULTILINE)
}
}
| gpl-3.0 | 14fb1ce9a3aa233a984cc368f6f97f4a | 31.236842 | 105 | 0.605948 | 4.433816 | false | false | false | false |
Kotlin/anko | anko/idea-plugin/preview/src/org/jetbrains/kotlin/android/dslpreview/AnkoNlPreviewManager.kt | 2 | 7970 | package org.jetbrains.kotlin.android.dslpreview
import com.android.tools.idea.common.model.NlModel
import com.android.tools.idea.gradle.project.GradleProjectInfo
import com.android.tools.idea.gradle.project.build.invoker.GradleBuildInvoker
import com.android.tools.idea.project.AndroidProjectInfo
import com.android.tools.idea.uibuilder.editor.NlPreviewForm
import com.android.tools.idea.uibuilder.editor.NlPreviewManager
import com.intellij.ide.highlighter.XmlFileType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.util.Computable
import com.intellij.openapi.wm.ToolWindow
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.xml.XmlFile
import com.intellij.util.Alarm
import org.jetbrains.android.uipreview.ViewLoaderExtension
import org.jetbrains.kotlin.idea.util.InfinitePeriodicalTask
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import java.awt.BorderLayout
import java.awt.event.ItemEvent
import javax.swing.ComboBoxModel
import javax.swing.DefaultComboBoxModel
import javax.swing.JPanel
class AnkoNlPreviewManager(
project: Project,
fileEditorManager: FileEditorManager?
) : NlPreviewManager(project, fileEditorManager), Disposable {
internal val classResolver = DslPreviewClassResolver(project)
internal var myActivityListModel: DefaultComboBoxModel<Any> = DefaultComboBoxModel()
private val viewLoaderExtension by lazy {
val area = Extensions.getArea(project)
if (area.hasExtensionPoint(ViewLoaderExtension.EP_NAME.name)) {
area.getExtensionPoint(ViewLoaderExtension.EP_NAME).extensions.firstIsInstanceOrNull<AnkoViewLoaderExtension>()
} else {
null
}
}
init {
ApplicationManager.getApplication().invokeLater {
val task = Computable { UpdateActivityNameTask(this) }
InfinitePeriodicalTask(1000, Alarm.ThreadToUse.SWING_THREAD, this@AnkoNlPreviewManager, task).start()
}
GradleBuildInvoker.getInstance(project).add {
ApplicationManager.getApplication().invokeLater {
refresh()
}
}
}
override fun getToolWindowId() = "Anko Layout Preview"
override fun getComponentName() = "AnkoNlPreviewManager"
public override fun getToolWindow() = super.getToolWindow()
override fun getBoundXmlFile(file: PsiFile?): XmlFile? {
if (file is XmlFile) {
return file
} else if (file !is KtFile) {
return null
}
val ankoPreviewFrom = previewForm as? AnkoPreviewForm ?: return null
val module = ModuleUtilCore.findModuleForPsiElement(file) ?: return null
return if (refresh() || ankoPreviewFrom.xmlFile == null) {
generateStubXmlFile(module, file).also {
ankoPreviewFrom.xmlFile = it
}
} else {
ankoPreviewFrom.xmlFile
}
}
private fun getActiveTextEditor(): TextEditor? {
if (!ApplicationManager.getApplication().isReadAccessAllowed) {
return ApplicationManager.getApplication().runReadAction(Computable<TextEditor> { getActiveTextEditor() })
}
ApplicationManager.getApplication().assertReadAccessAllowed()
val fileEditors = fileEditorManager?.selectedEditors
if (fileEditors != null && fileEditors.isNotEmpty() && fileEditors[0] is TextEditor) {
val textEditor = fileEditors[0] as TextEditor
if (isApplicableEditor(textEditor, null)) {
return textEditor
}
}
return null
}
private fun generateStubXmlFile(module: Module, originalFile: KtFile): LayoutPsiFile {
val filename = "anko_preview.xml"
val content = """<?xml version="1.0" encoding="utf-8"?>
<__anko.preview.View xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"/>"""
val psiFile = PsiFileFactory.getInstance(project).createFileFromText(filename, XmlFileType.INSTANCE, content)
return LayoutPsiFile(psiFile as XmlFile, originalFile, module)
}
private fun refresh(): Boolean {
val toolWindow: ToolWindow = toolWindow ?: return false
if (!toolWindow.isVisible) return false
val viewLoaderExtension = this.viewLoaderExtension ?: return false
val description = myActivityListModel.selectedItem as? PreviewClassDescription
?: classResolver.getOnCursorPreviewClassDescription()
if (description != null && viewLoaderExtension.description != description) {
viewLoaderExtension.description = description
return true
}
return false
}
override fun isApplicableEditor(textEditor: TextEditor, file: PsiFile?): Boolean {
val psiFile =
file ?: PsiDocumentManager.getInstance(project).getPsiFile(textEditor.editor.document) ?: return false
if (!GradleProjectInfo.getInstance(project).isBuildWithGradle &&
!AndroidProjectInfo.getInstance(project).isLegacyIdeaAndroidProject) {
return false
}
return psiFile is KtFile
}
private val fileEditorManager: FileEditorManager?
get() = with(NlPreviewManager::class.java.getDeclaredField("myFileEditorManager")) {
val oldAccessible = isAccessible
try {
isAccessible = true
get(this@AnkoNlPreviewManager) as? FileEditorManager
} finally {
isAccessible = oldAccessible
}
}
override fun initToolWindow() {
super.initToolWindow()
resolveAvailableClasses()
}
override fun createPreviewForm(): NlPreviewForm = AnkoPreviewForm(this)
internal fun updatePreview() {
getActiveTextEditor()?.let { notifyFileShown(it, true) }
}
fun resolveAvailableClasses() {
val activityClasses = classResolver
.getAncestors(DslPreviewClassResolver.ANKO_COMPONENT_CLASS_NAME)
.filter { classResolver.isClassApplicableForPreview(it.ktClass) }
with(myActivityListModel) {
selectedItem = null
removeAllElements()
val items = activityClasses
items.sortedBy { it.toString() }.forEach { addElement(it) }
}
}
override fun isUseInteractiveSelector() = false
override fun dispose() {}
}
class AnkoPreviewForm(private val ankoPreviewManager: AnkoNlPreviewManager) : NlPreviewForm(ankoPreviewManager) {
var xmlFile: XmlFile? = null
override fun setActiveModel(model: NlModel?) {
super.setActiveModel(model)
if (model != null) {
(this.toolbarComponent as? JPanel)?.let { addLayoutComboBox(it) }
}
}
private fun addLayoutComboBox(panel: JPanel) {
if (panel.components.firstIsInstanceOrNull<PreviewCandidateComboBox>() != null) {
return
}
val comboBox = PreviewCandidateComboBox(ankoPreviewManager.myActivityListModel)
comboBox.addItemListener { itemEvent ->
if (itemEvent.stateChange == ItemEvent.SELECTED) {
ankoPreviewManager.updatePreview()
}
}
panel.add(comboBox, BorderLayout.SOUTH)
}
}
class PreviewCandidateComboBox(model: ComboBoxModel<Any>) : ComboBox<Any>(model)
| apache-2.0 | 3fbce47e6c6a2c2a6d81ee2ef97d550a | 36.952381 | 123 | 0.692346 | 4.947238 | false | false | false | false |
kittinunf/ReactiveAndroid | reactiveandroid-ui/src/androidTest/kotlin/com/github/kittinunf/reactiveandroid/view/TestMenuItem.kt | 1 | 7466 | package com.github.kittinunf.reactiveandroid.view
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.view.ActionProvider
import android.view.ContextMenu
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.SubMenu
import android.view.View
class TestMenuItem(val context: Context) : MenuItem {
var menuItemClickListener: MenuItem.OnMenuItemClickListener? = null
var actionExpandListener: MenuItem.OnActionExpandListener? = null
var actionViewExpanded = false
var menuActionView: View? = null
var menuIcon: Drawable? = null
var menuCheckable = false
var menuIsChecked = false
var menuEnabled = false
var menuVisible = false
var menuTitle: CharSequence = ""
fun performClick() {
menuItemClickListener?.onMenuItemClick(this)
}
override fun setOnMenuItemClickListener(listener: MenuItem.OnMenuItemClickListener?): MenuItem {
menuItemClickListener = listener
return this
}
override fun expandActionView(): Boolean {
if (actionViewExpanded) return false
val shouldExpand = actionExpandListener?.onMenuItemActionExpand(this) ?: false
if (!shouldExpand) return false
actionViewExpanded = true
return true
}
override fun collapseActionView(): Boolean {
if (!actionViewExpanded) return false
val shouldCollapse = actionExpandListener?.onMenuItemActionCollapse(this) ?: false
if (!shouldCollapse) return false
actionViewExpanded = false
return true
}
override fun isActionViewExpanded(): Boolean {
return actionViewExpanded
}
override fun setOnActionExpandListener(listener: MenuItem.OnActionExpandListener?): MenuItem {
actionExpandListener = listener
return this
}
override fun getActionView(): View? {
return menuActionView
}
override fun setActionView(view: View?): MenuItem {
menuActionView = view
return this
}
override fun setActionView(resId: Int): MenuItem {
menuActionView = LayoutInflater.from(context).inflate(resId, null)
return this
}
override fun setIcon(icon: Drawable?): MenuItem {
menuIcon = icon
return this
}
override fun setIcon(iconRes: Int): MenuItem {
menuIcon = context.getDrawable(iconRes)
return this
}
override fun getIcon(): Drawable? {
return menuIcon
}
override fun isCheckable(): Boolean {
return menuCheckable
}
override fun setCheckable(checkable: Boolean): MenuItem {
menuCheckable = checkable
return this
}
override fun isChecked(): Boolean {
return menuIsChecked
}
override fun setChecked(checked: Boolean): MenuItem {
menuIsChecked = checked
return this
}
override fun setEnabled(enabled: Boolean): MenuItem {
menuEnabled = enabled
return this
}
override fun isEnabled(): Boolean {
return menuEnabled
}
override fun setVisible(visible: Boolean): MenuItem {
menuVisible = visible
return this
}
override fun isVisible(): Boolean {
return menuVisible
}
override fun setTitle(title: CharSequence?): MenuItem {
title?.let {
menuTitle = it
}
return this
}
override fun setTitle(title: Int): MenuItem {
menuTitle = context.getString(title)
return this
}
override fun getTitle(): CharSequence {
return menuTitle
}
override fun setAlphabeticShortcut(alphaChar: Char): MenuItem {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getOrder(): Int {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun hasSubMenu(): Boolean {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMenuInfo(): ContextMenu.ContextMenuInfo {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getItemId(): Int {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getAlphabeticShortcut(): Char {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setIntent(intent: Intent?): MenuItem {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setShortcut(numericChar: Char, alphaChar: Char): MenuItem {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setShowAsActionFlags(actionEnum: Int): MenuItem {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getIntent(): Intent {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getActionProvider(): ActionProvider {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setShowAsAction(actionEnum: Int) {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getGroupId(): Int {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setActionProvider(actionProvider: ActionProvider?): MenuItem {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setTitleCondensed(title: CharSequence?): MenuItem {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getSubMenu(): SubMenu {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getNumericShortcut(): Char {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getTitleCondensed(): CharSequence {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setNumericShortcut(numericChar: Char): MenuItem {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
| mit | 2adee43b64bf3b056bfcd22a62e616de | 31.320346 | 138 | 0.69917 | 5.588323 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.