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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/util/quickfixUtil.kt | 1 | 2764 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.util
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.resolve.getDataFlowValueFactory
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtPrimaryConstructor
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoAfter
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.ifEmpty
inline fun <reified T : PsiElement> Diagnostic.createIntentionForFirstParentOfType(
factory: (T) -> KotlinQuickFixAction<T>?
) = psiElement.getNonStrictParentOfType<T>()?.let(factory)
fun createIntentionFactory(
factory: (Diagnostic) -> IntentionAction?
) = object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic) = factory(diagnostic)
}
fun KtPrimaryConstructor.addConstructorKeyword(): PsiElement? {
val modifierList = this.modifierList ?: return null
val psiFactory = KtPsiFactory(this)
val constructor = if (valueParameterList == null) {
psiFactory.createPrimaryConstructor("constructor()")
} else {
psiFactory.createConstructorKeyword()
}
return addAfter(constructor, modifierList)
}
fun getDataFlowAwareTypes(
expression: KtExpression,
bindingContext: BindingContext = expression.analyze(),
originalType: KotlinType? = bindingContext.getType(expression)
): Collection<KotlinType> {
if (originalType == null) return emptyList()
val dataFlowInfo = bindingContext.getDataFlowInfoAfter(expression)
val dataFlowValueFactory = expression.getResolutionFacade().getDataFlowValueFactory()
val expressionType = bindingContext.getType(expression) ?: return listOf(originalType)
val dataFlowValue = dataFlowValueFactory.createDataFlowValue(
expression, expressionType, bindingContext, expression.getResolutionFacade().moduleDescriptor
)
return dataFlowInfo.getCollectedTypes(dataFlowValue, expression.languageVersionSettings).ifEmpty { listOf(originalType) }
}
| apache-2.0 | 6e16969f06b2bf2d976d22d1b233bd44 | 45.847458 | 158 | 0.809334 | 5.07156 | false | false | false | false |
WillowChat/Kale | src/main/kotlin/chat/willow/kale/irc/prefix/PrefixParser.kt | 2 | 1294 | package chat.willow.kale.irc.prefix
import chat.willow.kale.irc.CharacterCodes
object PrefixParser : IPrefixParser {
override fun parse(rawPrefix: String): Prefix? {
var raw = rawPrefix
if (raw.isEmpty()) {
return null
}
var nick = raw
var user: String? = null
var host: String? = null
val indexOfLastAt = rawPrefix.indexOfLast { character -> character == CharacterCodes.AT }
if (indexOfLastAt >= 0) {
raw = rawPrefix.substring(0, indexOfLastAt)
nick = raw
host = if (rawPrefix.length > indexOfLastAt + 2) {
rawPrefix.substring(indexOfLastAt + 1, rawPrefix.length)
} else {
""
}
}
val indexOfFirstExclam = raw.indexOfFirst { character -> character == CharacterCodes.EXCLAM }
if (indexOfFirstExclam >= 0) {
nick = raw.substring(0, indexOfFirstExclam)
user = if (raw.length > indexOfFirstExclam + 2) {
raw.substring(indexOfFirstExclam + 1, raw.length)
} else {
""
}
}
if (nick.isEmpty()) {
return null
}
return Prefix(nick = nick, user = user, host = host)
}
} | isc | e2271dde5a004f184f968ed9dbc94ad6 | 25.979167 | 101 | 0.53864 | 4.462069 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputWeekDay.kt | 1 | 3105 | package info.nightscout.androidaps.plugins.general.automation.elements
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.annotation.StringRes
import com.dpro.widgets.WeekdaysPicker
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import java.util.*
class InputWeekDay(injector: HasAndroidInjector) : Element(injector) {
enum class DayOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
fun toCalendarInt(): Int {
return calendarInts[ordinal]
}
@get:StringRes val shortName: Int
get() = shortNames[ordinal]
companion object {
private val calendarInts = intArrayOf(
Calendar.MONDAY,
Calendar.TUESDAY,
Calendar.WEDNESDAY,
Calendar.THURSDAY,
Calendar.FRIDAY,
Calendar.SATURDAY,
Calendar.SUNDAY
)
private val shortNames = intArrayOf(
R.string.weekday_monday_short,
R.string.weekday_tuesday_short,
R.string.weekday_wednesday_short,
R.string.weekday_thursday_short,
R.string.weekday_friday_short,
R.string.weekday_saturday_short,
R.string.weekday_sunday_short
)
fun fromCalendarInt(day: Int): DayOfWeek {
for (i in calendarInts.indices) {
if (calendarInts[i] == day) return values()[i]
}
throw IllegalStateException("Invalid day")
}
}
}
val weekdays = BooleanArray(DayOfWeek.values().size)
init {
for (day in DayOfWeek.values()) set(day, false)
}
fun setAll(value:Boolean) {
for (day in DayOfWeek.values()) set(day, value)
}
operator fun set(day: DayOfWeek, value: Boolean): InputWeekDay {
weekdays[day.ordinal] = value
return this
}
fun isSet(day: DayOfWeek): Boolean = weekdays[day.ordinal]
fun getSelectedDays(): List<Int> {
val selectedDays: MutableList<Int> = ArrayList()
for (i in weekdays.indices) {
val day = DayOfWeek.values()[i]
val selected = weekdays[i]
if (selected) selectedDays.add(day.toCalendarInt())
}
return selectedDays
}
override fun addToLayout(root: LinearLayout) {
val weekdaysPicker = WeekdaysPicker(root.context)
weekdaysPicker.setEditable(true)
weekdaysPicker.selectedDays = getSelectedDays()
weekdaysPicker.setOnWeekdaysChangeListener { _: View?, i: Int, list: List<Int?> -> set(DayOfWeek.fromCalendarInt(i), list.contains(i)) }
weekdaysPicker.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
weekdaysPicker.sundayFirstDay = Calendar.getInstance().firstDayOfWeek == Calendar.SUNDAY
weekdaysPicker.redrawDays()
root.addView(weekdaysPicker)
}
}
| agpl-3.0 | a36ae3aa6bef28ba89d8246c739feacc | 33.5 | 144 | 0.623188 | 4.726027 | false | false | false | false |
ericfabreu/ktmdb | ktmdb/src/main/kotlin/com/ericfabreu/ktmdb/utils/ListHelper.kt | 1 | 8519 | package com.ericfabreu.ktmdb.utils
import com.beust.klaxon.JsonArray
import com.beust.klaxon.JsonObject
import com.ericfabreu.ktmdb.utils.MediaHelper.ImageFile
/**
* A collection of list classes used throughout the library.
*/
@Suppress("UNCHECKED_CAST", "UNUSED")
object ListHelper {
// Note: Not all sort types are supported by all functions
enum class SortBy(val type: String) {
CREATED_ASC("created_at.asc"),
CREATED_DESC("created_at.desc"),
FIRST_AIR_DATE_ASC("first_air_date.asc"),
FIRST_AIR_DATE_DESC("first_air_date.desc"),
ORIGINAL_ORDER_ASC("original_order.asc"),
ORIGINAL_ORDER_DESC("original_order.desc"),
ORIGINAL_TITLE_ASC("original_title.asc"),
ORIGINAL_TITLE_DESC("original_title.desc"),
POPULARITY_ASC("popularity.asc"),
POPULARITY_DESC("popularity.desc"),
PRIMARY_RELEASE_DATE_ASC("primary_release_date.asc"),
PRIMARY_RELEASE_DATE_DESC("primary_release_date.desc"),
RELEASE_ASC("release_date.asc"),
RELEASE_DESC("release_date.desc"),
REVENUE_ASC("revenue.asc"),
REVENUE_DESC("revenue.desc"),
TITLE_ASC("title.asc"),
TITLE_DESC("title.desc"),
VOTE_AVERAGE_ASC("vote_average.asc"),
VOTE_AVERAGE_DESC("vote_average.desc"),
VOTE_COUNT_ASC("vote_count.asc"),
VOTE_COUNT_DESC("vote_count.desc");
// Necessary to work with QueryMap
override fun toString() = type
}
/**
* Holds the original and new value of a single TMDb change.
* NOTE: if the changed value is not a string, this will store a Json string instead of
* an instance of a specific class/object since there might be too many different types
* of items that could be changed.
*
* TODO: figure out all possible cases for `value`/`originalValue` and handle them if possible.
*/
data class ChangeItem(private val item: JsonObject) {
companion object {
internal const val KEY_ID = "items"
internal const val KEY_VALUE = "key"
}
val id = item["id"] as String
val action = item["action"] as String
val time = item["time"] as String
val language = item["iso_639_1"] as String?
val value = item["value"].toString()
val originalValue = item["original_value"].toString()
}
data class EpisodeItem(private val item: JsonObject) {
val airDate = item["air_date"] as String
val episodeNumber = item["episode_number"] as Int
val name = item["name"] as String
val id = item["id"] as Int
val rating = item["rating"]?.toString()?.toDouble()
val seasonNumber = item["season_number"] as Int
val stillPath = item["still_path"] as String?
val showId = item["show_id"] as Int
val voteAverage = item["vote_average"].toString().toDouble()
val voteCount = item["vote_count"] as Int
}
data class ImageList(private val lst: JsonObject) {
private val backdropLst = lst["backdrops"] as JsonArray<JsonObject>
private val posterLst = lst["posters"] as JsonArray<JsonObject>
val backdrops = backdropLst.map { ImageFile(it) }
val posters = posterLst.map { ImageFile(it) }
}
data class IsoItem(private val item: JsonObject, private val idKey: String,
private val valueKey: String) {
val id = item[idKey] as String
val value = item[valueKey] as String
}
data class MediaAccountState(private val item: JsonObject) {
val favorite = item["favorite"] as Boolean
val rating = JsonHelper.getAccountStateRating(item["rated"])
val watchlist = item["watchlist"] as Boolean
}
data class MovieItem(private val item: JsonObject) {
val adult = item["adult"] as Boolean
val backdropPath = item["backdrop_path"] as String?
val genreIds = item["genre_ids"] as List<Int>
val id = item["id"] as Int
val originalLanguage = item["original_language"] as String
val originalTitle = item["original_title"] as String
val overview = item["overview"] as String?
val releaseDate = item["release_date"] as String
val posterPath = item["poster_path"] as String?
val popularity = item["popularity"].toString().toDouble()
val title = item["title"] as String
val video = item["video"] as Boolean
val voteAverage = item["vote_average"].toString().toDouble()
val voteCount = item["vote_count"] as Int
/* Used for personal ratings. If `item` is from just a regular (user-independent) list,
* this becomes a copy of `voteAverage` to avoid future confusion. */
val rating = (item["rating"] ?: voteAverage).toString().toDouble()
}
/**
* Class used for lists of both movies and TV shows where the order is important. It only
* keeps the data fields that are present in both types of objects.
*/
data class MovieTvItem(private val item: JsonObject) {
// This variable is always null for TV shows, but it might be too important to drop
val adult = item["adult"] as Boolean?
val backdropPath = item["backdrop_path"] as String?
val genreIds = item["genre_ids"] as List<Int>
val id = item["id"] as Int
val isMovie = item["media_type"] as String == MediaHelper.MediaType.MOVIE.str
val originalLanguage = item["original_language"] as String
val originalTitle = (if (isMovie) item["original_title"] else
item["original_name"]) as String
val overview = item["overview"] as String?
val popularity = item["popularity"].toString().toDouble()
val posterPath = item["poster_path"] as String?
val releaseDate = (if (isMovie) item["release_date"] else item["first_air_date"]) as String?
val title = (if (isMovie) item["title"] else item["name"]) as String
val voteAverage = item["vote_average"].toString().toDouble()
val voteCount = item["vote_count"] as Int
}
data class NamedItem(private val item: JsonObject) {
val id = item["id"] as Int
val name = item["name"] as String
}
data class PagedList<out T>(private val lst: JsonObject,
private val container: (JsonObject) -> T) {
val page = (lst["page"] ?: 0) as Int
val totalPages = (lst["total_pages"] ?: 0) as Int
val totalResults = (lst["total_results"] ?: 0) as Int
private val results = lst["results"] as? JsonArray<JsonObject>
val items = results?.map { container(it) } ?: emptyList<T>()
}
data class TmdbList(private val item: JsonObject) {
val description = item["description"] as String
val favoriteCount = item["favorite_count"] as Int
val id = item["id"] as Int
val itemCount = item["item_count"] as Int
val language = item["iso_639_1"] as String
val listType = item["list_type"] as String
val name = item["name"] as String
val posterPath = item["poster_path"] as String?
}
data class TvExternalIds(private val item: JsonObject) {
val imdbId = item["imdb_id"] as String?
val freebaseMid = item["freebase_mid"] as String?
val freebaseId = item["freebase_id"] as String?
val tvdbId = item["tvdb_id"] as Int?
val tvRageId = item["tvRage_id"] as Int?
}
data class TvItem(private val item: JsonObject) {
val backdropPath = item["backdrop_path"] as String?
val firstAirDate = item["first_air_date"] as String
val genreIds = item["genre_ids"] as List<Int>
val id = item["id"] as Int
val name = item["name"] as String
val originCountry = item["origin_country"] as List<String>
val originalLanguage = item["original_language"] as String
val originalName = item["original_name"] as String
val overview = item["overview"] as String?
val popularity = item["popularity"] as Double
val posterPath = item["poster_path"] as String?
val voteAverage = item["vote_average"].toString().toDouble()
val voteCount = item["vote_count"] as Int
/* Used for personal ratings. If `item` is from just a regular (user-independent) list,
* this becomes a copy of `voteAverage` to avoid future confusion. */
val rating = (item["rating"] ?: voteAverage).toString().toDouble()
}
}
| mit | 9602288b40dd91959d672a1a2983d886 | 43.369792 | 100 | 0.627656 | 4.192421 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ui2/ColumnLayout.kt | 1 | 5005 | package de.fabmax.kool.modules.ui2
import de.fabmax.kool.KoolContext
import de.fabmax.kool.math.MutableVec2f
import kotlin.math.max
import kotlin.math.round
object ColumnLayout : Layout {
override fun measureContentSize(uiNode: UiNode, ctx: KoolContext) {
VerticalLayout.measure(uiNode, true)
}
override fun layoutChildren(uiNode: UiNode, ctx: KoolContext) {
VerticalLayout.layout(uiNode, true)
}
}
object ReverseColumnLayout : Layout {
override fun measureContentSize(uiNode: UiNode, ctx: KoolContext) {
VerticalLayout.measure(uiNode, false)
}
override fun layoutChildren(uiNode: UiNode, ctx: KoolContext) {
VerticalLayout.layout(uiNode, false)
}
}
private object VerticalLayout {
fun measure(uiNode: UiNode, isTopToBottom: Boolean) = uiNode.run {
val modWidth = modifier.width
val modHeight = modifier.height
var measuredWidth = 0f
var measuredHeight = 0f
var isDynamicWidth = true
var isDynamicHeight = true
if (modWidth is Dp) {
measuredWidth = modWidth.px
isDynamicWidth = false
}
if (modHeight is Dp) {
measuredHeight = modHeight.px
isDynamicHeight = false
}
if (isDynamicWidth || isDynamicHeight) {
// determine content size based on child sizes
var prevMargin = paddingTopPx
val indices = if (isTopToBottom) children.indices else children.indices.reversed()
for (i in indices) {
val child = children[i]
if (isDynamicWidth) {
val pStart = max(paddingStartPx, child.marginStartPx)
val pEnd = max(paddingEndPx, child.marginEndPx)
measuredWidth = max(measuredWidth, round(child.contentWidthPx + pStart + pEnd))
}
if (isDynamicHeight) {
measuredHeight += round(child.contentHeightPx) + round(max(prevMargin, child.marginTopPx))
prevMargin = child.marginBottomPx
}
if (i == children.lastIndex && isDynamicHeight) {
measuredHeight += round(max(prevMargin, paddingBottomPx))
}
}
if (modWidth is Grow) measuredWidth = modWidth.clampPx(measuredWidth, measuredWidth)
if (modHeight is Grow) measuredHeight = modHeight.clampPx(measuredHeight, measuredHeight)
}
setContentSize(measuredWidth, measuredHeight)
}
fun layout(uiNode: UiNode, isTopToBottom: Boolean) = uiNode.run {
val growSpace = determineAvailableGrowSpace(isTopToBottom)
var y = if (isTopToBottom) topPx else bottomPx
var prevMargin = if (isTopToBottom) paddingTopPx else paddingBottomPx
for (i in children.indices) {
val child = children[i]
val growSpaceH = growSpace.x / growSpace.y
val growSpaceW = widthPx - max(paddingStartPx, child.marginStartPx) - max(paddingEndPx, child.marginEndPx)
val layoutW = round(child.computeWidthFromDimension(growSpaceW))
val layoutH = round(child.computeHeightFromDimension(growSpaceH))
val layoutX = round(uiNode.computeChildLocationX(child, layoutW))
val ch = child.modifier.height
if (ch is Grow) {
growSpace.x -= layoutH
growSpace.y -= ch.weight
}
val layoutY: Float
if (isTopToBottom) {
y += round(max(prevMargin, child.marginTopPx))
prevMargin = child.marginBottomPx
layoutY = round(y)
y += layoutH
} else {
y -= round(max(prevMargin, child.marginBottomPx))
prevMargin = child.marginTopPx
y -= layoutH
layoutY = round(y)
}
child.setBounds(layoutX, layoutY, layoutX + layoutW, layoutY + layoutH)
}
}
private fun UiNode.determineAvailableGrowSpace(isTopToBottom: Boolean): MutableVec2f {
var prevMargin = paddingTopPx
var remainingSpace = heightPx
var totalWeight = 0f
val indices = if (isTopToBottom) children.indices else children.indices.reversed()
for (i in indices) {
val child = children[i]
when (val childH = child.modifier.height) {
is Dp -> remainingSpace -= childH.px
is Grow -> totalWeight += childH.weight
FitContent -> remainingSpace -= child.contentHeightPx
}
remainingSpace -= max(prevMargin, child.marginTopPx)
prevMargin = child.marginBottomPx
if (i == uiNode.children.lastIndex) {
remainingSpace -= max(prevMargin, uiNode.paddingBottomPx)
}
}
if (totalWeight == 0f) totalWeight = 1f
return MutableVec2f(remainingSpace, totalWeight)
}
}
| apache-2.0 | 4004dd9f484cf9909116e6911a1f78f8 | 37.206107 | 118 | 0.603197 | 4.651487 | false | false | false | false |
zdary/intellij-community | java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaInjectedFileChangesHandler.kt | 2 | 10251 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.source.tree.injected
import com.intellij.codeInsight.editorActions.CopyPastePreProcessor
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.ex.DocumentEx
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.component1
import com.intellij.openapi.util.component2
import com.intellij.psi.*
import com.intellij.psi.PsiLanguageInjectionHost.Shred
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.impl.PsiDocumentManagerBase
import com.intellij.psi.impl.source.resolve.FileContextUtil
import com.intellij.psi.impl.source.tree.injected.changesHandler.*
import com.intellij.psi.util.createSmartPointer
import com.intellij.util.SmartList
import com.intellij.util.containers.ContainerUtil
import kotlin.math.max
internal class JavaInjectedFileChangesHandler(shreds: List<Shred>, editor: Editor, newDocument: Document, injectedFile: PsiFile) :
CommonInjectedFileChangesHandler(shreds, editor, newDocument, injectedFile) {
init {
// Undo breaks fragment markers completely, so rebuilding them in that case
myHostDocument.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
if (UndoManager.getInstance(myProject).isUndoInProgress) {
(PsiDocumentManager.getInstance(myProject) as PsiDocumentManagerBase).addRunOnCommit(myHostDocument) {
rebuildMarkers(markersWholeRange(markers) ?: failAndReport("can't get marker range in undo", event))
}
}
}
}, this)
}
override fun commitToOriginal(e: DocumentEvent) {
val psiDocumentManager = PsiDocumentManager.getInstance(myProject)
val hostPsiFile = psiDocumentManager.getPsiFile(myHostDocument) ?: failAndReport("no psiFile $myHostDocument", e)
val affectedRange = TextRange.from(e.offset, max(e.newLength, e.oldLength))
val affectedMarkers = markers.filter { affectedRange.intersects(it.fragmentMarker) }
val guardedRanges = guardedBlocks.mapTo(HashSet()) { it.range }
if (affectedMarkers.isEmpty() && guardedRanges.any { it.intersects(affectedRange) }) {
// changed guarded blocks are on fragment document editor conscience, we just ignore them silently
return
}
if (!hasInjectionsInOriginFile(affectedMarkers, hostPsiFile)) {
// can't go on if there is already no injection, maybe someone just uninjected them?
myInvalidated = true
return
}
var workingRange: TextRange? = null
val markersToRemove = SmartList<MarkersMapping>()
for ((affectedMarker, markerText) in distributeTextToMarkers(affectedMarkers, affectedRange, e.offset + e.newLength)
.let(this::promoteLinesEnds)) {
val rangeInHost = affectedMarker.hostMarker.range
myHostEditor.caretModel.moveToOffset(rangeInHost.startOffset)
val newText = CopyPastePreProcessor.EP_NAME.extensionList.fold(markerText) { newText, preProcessor ->
preProcessor.preprocessOnPaste(myProject, hostPsiFile, myHostEditor, newText, null)
}
//TODO: cover additional clauses with tests (multiple languages injected into one host)
if (newText.isEmpty() && affectedMarker.fragmentRange !in guardedRanges && affectedMarker.host?.contentRange == rangeInHost) {
markersToRemove.add(affectedMarker)
}
myHostDocument.replaceString(rangeInHost.startOffset, rangeInHost.endOffset, newText)
workingRange = workingRange union TextRange.from(rangeInHost.startOffset, newText.length)
}
workingRange = workingRange ?: failAndReport("no workingRange", e)
psiDocumentManager.commitDocument(myHostDocument)
if (markersToRemove.isNotEmpty()) {
val remainingRange = removeHostsFromConcatenation(markersToRemove)
if (remainingRange != null) {
workingRange = remainingRange
getInjectionHostAtRange(hostPsiFile, remainingRange)?.let { host ->
myHostEditor.caretModel.moveToOffset(
ElementManipulators.getOffsetInElement(host) + host.textRange.startOffset
)
}
}
}
val wholeRange = markersWholeRange(affectedMarkers) union workingRange ?: failAndReport("no wholeRange", e)
CodeStyleManager.getInstance(myProject).reformatRange(
hostPsiFile, wholeRange.startOffset, wholeRange.endOffset, true)
rebuildMarkers(workingRange)
updateFileContextElementIfNeeded(hostPsiFile, workingRange)
}
private fun updateFileContextElementIfNeeded(hostPsiFile: PsiFile, workingRange: TextRange) {
val fragmentPsiFile = PsiDocumentManager.getInstance(myProject).getCachedPsiFile(myFragmentDocument) ?: return
val injectedPointer = fragmentPsiFile.getUserData(FileContextUtil.INJECTED_IN_ELEMENT) ?: return
if (injectedPointer.element != null) return // still valid no need to update
val newHost = getInjectionHostAtRange(hostPsiFile, workingRange) ?: return
fragmentPsiFile.putUserData(FileContextUtil.INJECTED_IN_ELEMENT, newHost.createSmartPointer())
}
private var myInvalidated = false
override fun isValid(): Boolean = !myInvalidated && super.isValid()
private fun hasInjectionsInOriginFile(affectedMarkers: List<MarkersMapping>, hostPsiFile: PsiFile): Boolean {
val injectedLanguageManager = InjectedLanguageManager.getInstance(myProject)
return affectedMarkers.any { marker ->
marker.hostElementRange?.let { injectedLanguageManager.getCachedInjectedDocumentsInRange(hostPsiFile, it).isNotEmpty() } ?: false
}
}
private fun rebuildMarkers(contextRange: TextRange) {
val psiDocumentManager = PsiDocumentManager.getInstance(myProject)
psiDocumentManager.commitDocument(myHostDocument)
val hostPsiFile = psiDocumentManager.getPsiFile(myHostDocument) ?: failAndReport("no psiFile $myHostDocument")
val injectedLanguageManager = InjectedLanguageManager.getInstance(myProject)
val newInjectedFile = getInjectionHostAtRange(hostPsiFile, contextRange)?.let { host ->
val injectionRange = run {
val hostRange = host.textRange
val contextRangeTrimmed = hostRange.intersection(contextRange) ?: hostRange
contextRangeTrimmed.shiftLeft(hostRange.startOffset)
}
injectedLanguageManager.getInjectedPsiFiles(host)
.orEmpty()
.asSequence()
.filter { (_, range) -> range.length > 0 && injectionRange.contains(range) }
.mapNotNull { it.first as? PsiFile }
.firstOrNull()
}
if (newInjectedFile !== myInjectedFile) {
myInjectedFile = newInjectedFile ?: myInjectedFile
markers.forEach { it.dispose() }
markers.clear()
//some hostless shreds could exist for keeping guarded values
val hostfulShreds = InjectedLanguageUtil.getShreds(myInjectedFile).filter { it.host != null }
val markersFromShreds = getMarkersFromShreds(hostfulShreds)
markers.addAll(markersFromShreds)
}
}
private val guardedBlocks get() = (myFragmentDocument as DocumentEx).guardedBlocks
private fun promoteLinesEnds(mapping: List<Pair<MarkersMapping, String>>): Iterable<Pair<MarkersMapping, String>> {
val result = ArrayList<Pair<MarkersMapping, String>>(mapping.size)
var transfer = ""
val reversed = ContainerUtil.reverse(mapping)
for (i in reversed.indices) {
val (marker, text) = reversed[i]
if (text == "\n" && reversed.getOrNull(i + 1)?.second?.endsWith("\n") == false) {
result.add(Pair(marker, ""))
transfer += "\n"
}
else if (transfer != "") {
result.add(Pair(marker, text + transfer))
transfer = ""
}
else {
result.add(reversed[i])
}
}
return ContainerUtil.reverse(result)
}
private fun markersWholeRange(affectedMarkers: List<MarkersMapping>): TextRange? =
affectedMarkers.asSequence()
.filter { it.host?.isValid ?: false }
.mapNotNull { it.hostElementRange }
.takeIf { it.any() }?.reduce(TextRange::union)
private fun getFollowingElements(host: PsiLanguageInjectionHost): List<PsiElement>? {
val result = SmartList<PsiElement>()
for (sibling in host.nextSiblings) {
if (intermediateElement(sibling)) {
result.add(sibling)
}
else {
return result
}
}
return null
}
private fun removeHostsFromConcatenation(hostsToRemove: List<MarkersMapping>): TextRange? {
val psiPolyadicExpression = hostsToRemove.asSequence().mapNotNull { it.host?.parent as? PsiPolyadicExpression }.distinct().singleOrNull()
for (marker in hostsToRemove.reversed()) {
val host = marker.host ?: continue
val relatedElements = getFollowingElements(host) ?: host.prevSiblings.takeWhile(::intermediateElement).toList()
if (relatedElements.isNotEmpty()) {
host.delete()
marker.hostMarker.dispose()
for (related in relatedElements) {
if (related.isValid) {
related.delete()
}
}
}
}
if (psiPolyadicExpression != null) {
// distinct because Java could duplicate operands sometimes (EA-142380), mb something is wrong with the removal code upper ?
psiPolyadicExpression.operands.distinct().singleOrNull()?.let { onlyRemaining ->
return psiPolyadicExpression.replace(onlyRemaining).textRange
}
}
return null
}
}
private infix fun TextRange?.union(another: TextRange?) = another?.let { this?.union(it) ?: it } ?: this
private fun intermediateElement(psi: PsiElement) =
psi is PsiWhiteSpace || (psi is PsiJavaToken && psi.tokenType == JavaTokenType.PLUS)
private val PsiElement.nextSiblings: Sequence<PsiElement>
get() = generateSequence(this.nextSibling) { it.nextSibling }
private val PsiElement.prevSiblings: Sequence<PsiElement>
get() = generateSequence(this.prevSibling) { it.prevSibling }
| apache-2.0 | 2e482b81f05b659a388f0f37f5c54a08 | 40.840816 | 141 | 0.733489 | 4.734873 | false | false | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/jdkDownloader/JdkDownloader.kt | 1 | 4401 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.projectRoots.impl.jdkDownloader
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.*
import com.intellij.openapi.projectRoots.SimpleJavaSdkType.notSimpleJavaSdkTypeIfAlternativeExistsAndNotDependentSdkType
import com.intellij.openapi.roots.ui.configuration.projectRoot.SdkDownload
import com.intellij.openapi.roots.ui.configuration.projectRoot.SdkDownloadTask
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.registry.Registry
import java.util.function.Consumer
import javax.swing.JComponent
internal class JdkDownloader : SdkDownload, JdkDownloaderBase {
private val LOG = logger<JdkDownloader>()
override fun supportsDownload(sdkTypeId: SdkTypeId): Boolean {
if (!Registry.`is`("jdk.downloader")) return false
if (ApplicationManager.getApplication().isUnitTestMode) return false
return notSimpleJavaSdkTypeIfAlternativeExistsAndNotDependentSdkType().value(sdkTypeId)
}
override fun showDownloadUI(sdkTypeId: SdkTypeId,
sdkModel: SdkModel,
parentComponent: JComponent,
selectedSdk: Sdk?,
sdkCreatedCallback: Consumer<SdkDownloadTask>) {
val project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(parentComponent))
if (project?.isDisposed == true) return
val items = runTaskAndReportError(project,
"Downloading the list of available JDKs...",
"Failed to download the list of installable JDKs") {
JdkListDownloader.downloadForUI(it)
} ?: return
if (project?.isDisposed == true) return
val (jdkItem, jdkHome) = JdkDownloadDialog(project, parentComponent, sdkTypeId, items).selectJdkAndPath() ?: return
/// prepare the JDK to be installed (e.g. create home dir, write marker file)
val request = runTaskAndReportError(project, "Preparing JDK target folder...", "Failed to prepare JDK installation to $jdkHome") {
JdkInstaller.prepareJdkInstallation(jdkItem, jdkHome)
} ?: return
sdkCreatedCallback.accept(newDownloadTask(request))
}
private inline fun <T : Any> runTaskAndReportError(project: Project?,
title: String,
errorMessage: String,
crossinline action: (ProgressIndicator) -> T): T? {
val task = object : Task.WithResult<T?, Exception>(project, title, true) {
override fun compute(indicator: ProgressIndicator): T? {
try {
return action(indicator)
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Exception) {
val msg = "$errorMessage. ${e.message}"
LOG.warn(msg, e)
invokeLater {
Messages.showMessageDialog(project,
msg,
JdkDownloadDialog.DIALOG_TITLE,
Messages.getErrorIcon()
)
}
return null
}
}
}
return ProgressManager.getInstance().run(task)
}
}
internal interface JdkDownloaderBase {
fun newDownloadTask(request: JdkInstallRequest): SdkDownloadTask {
return object : SdkDownloadTask {
override fun getSuggestedSdkName() = request.item.suggestedSdkName
override fun getPlannedHomeDir() = request.targetDir.absolutePath
override fun getPlannedVersion() = request.item.versionString
override fun doDownload(indicator: ProgressIndicator) {
JdkInstaller.installJdk(request, indicator)
}
}
}
}
| apache-2.0 | 724ed5c25a62d7724375560adeb4b148 | 43.454545 | 140 | 0.673711 | 5.208284 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/decompiledDeclarations/KtLightFieldForDecompiledDeclaration.kt | 2 | 3036 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.caches.lightClasses.decompiledDeclarations
import com.intellij.psi.*
import com.intellij.psi.impl.PsiVariableEx
import com.intellij.psi.javadoc.PsiDocComment
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.elements.KtLightElementBase
import org.jetbrains.kotlin.asJava.elements.KtLightFieldForSourceDeclarationSupport
import org.jetbrains.kotlin.asJava.elements.KtLightMember
import org.jetbrains.kotlin.idea.caches.lightClasses.LightMemberOriginForCompiledField
import org.jetbrains.kotlin.psi.KtDeclaration
open class KtLightFieldForDecompiledDeclaration(
private val fldDelegate: PsiField,
private val fldParent: KtLightClass,
override val lightMemberOrigin: LightMemberOriginForCompiledField
) : KtLightElementBase(fldParent), PsiField, KtLightFieldForSourceDeclarationSupport, KtLightMember<PsiField>, PsiVariableEx {
override val kotlinOrigin: KtDeclaration? get() = lightMemberOrigin.originalElement
override fun hasModifierProperty(name: String): Boolean = fldDelegate.hasModifierProperty(name)
override fun setInitializer(initializer: PsiExpression?) {
fldDelegate.initializer = initializer
}
override fun getContainingClass(): KtLightClass = fldParent
override fun normalizeDeclaration() = fldDelegate.normalizeDeclaration()
override fun getNameIdentifier(): PsiIdentifier = fldDelegate.nameIdentifier
override fun getName(): String = fldDelegate.name
override fun getInitializer(): PsiExpression? = fldDelegate.initializer
override fun getDocComment(): PsiDocComment? = fldDelegate.docComment
override fun getTypeElement(): PsiTypeElement? = fldDelegate.typeElement
override fun getModifierList(): PsiModifierList? = fldDelegate.modifierList
override fun hasInitializer(): Boolean = fldDelegate.hasInitializer()
override fun getType(): PsiType = fldDelegate.type
override fun isDeprecated(): Boolean = fldDelegate.isDeprecated
override fun setName(name: String): PsiElement = fldDelegate.setName(name)
override fun computeConstantValue(): Any? = fldDelegate.computeConstantValue()
override fun computeConstantValue(visitedVars: MutableSet<PsiVariable>?): Any? = (fldDelegate as? PsiVariableEx)?.computeConstantValue(visitedVars)
override fun equals(other: Any?): Boolean = other is KtLightFieldForDecompiledDeclaration &&
name == other.name &&
fldParent == other.fldParent &&
fldDelegate == other.fldDelegate
override fun hashCode(): Int = name.hashCode()
override fun copy(): PsiElement = this
override fun clone(): Any = this
override fun toString(): String = "${this.javaClass.simpleName} of $fldParent"
override val clsDelegate: PsiField = fldDelegate
override fun isValid(): Boolean = parent.isValid
} | apache-2.0 | a0414970bd2aa900e538db63805c6b9a | 40.60274 | 158 | 0.780303 | 5.180887 | false | false | false | false |
siosio/intellij-community | java/compiler/tests/com/intellij/compiler/artifacts/propertybased/ArtifactTestUtils.kt | 1 | 2820 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.compiler.artifacts.propertybased
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.project.Project
import com.intellij.packaging.artifacts.Artifact
import com.intellij.packaging.artifacts.ArtifactManager
import com.intellij.packaging.elements.CompositePackagingElement
import com.intellij.packaging.elements.PackagingElement
import com.intellij.packaging.impl.artifacts.workspacemodel.toElement
import com.intellij.packaging.impl.elements.ArtifactRootElementImpl
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.ArtifactEntity
import com.intellij.workspaceModel.storage.bridgeEntities.PackagingElementEntity
import org.junit.Assert
internal fun artifact(project: Project, name: String): Artifact {
val bridgeArtifact = runReadAction { ArtifactManager.getInstance(project).findArtifact(name) }
Assert.assertNotNull(bridgeArtifact)
return bridgeArtifact!!
}
internal fun artifactEntity(project: Project, name: String): ArtifactEntity {
val artifactEntities = WorkspaceModel.getInstance(project).entityStorage.current.entities(ArtifactEntity::class.java)
val artifactEntity = artifactEntities.find { it.name == name }
Assert.assertNotNull(artifactEntity)
return artifactEntity!!
}
internal fun assertTreesEquals(project: Project, left: PackagingElement<*>, right: PackagingElementEntity) {
val rightElement = right.toElement(project, WorkspaceEntityStorageBuilder.create())
assertElementsEquals(left, rightElement)
}
internal fun assertElementsEquals(left: PackagingElement<*>, right: PackagingElement<*>) {
if (left !is ArtifactRootElementImpl || right !is ArtifactRootElementImpl) {
if (!left.isEqualTo(right)) {
Assert.fail("Elements are not equals. $left <-> $right")
}
}
if (left is CompositePackagingElement<*> && right is CompositePackagingElement<*>) {
val leftChildren = left.children
val rightChildren = right.children
if (leftChildren.size != rightChildren.size) {
Assert.fail("Elements have different amount of children. Left: ${leftChildren} != right: ${rightChildren}")
}
if (leftChildren.size != left.nonWorkspaceModelChildren.size) {
Assert.fail("Element has different amount of children in store and internally.")
}
if (rightChildren.size != right.nonWorkspaceModelChildren.size) {
Assert.fail("Element has different amount of children in store and internally.")
}
for (i in leftChildren.indices) {
assertElementsEquals(leftChildren[i], rightChildren[i])
}
}
}
| apache-2.0 | 424f5b5b189eb6ce591272cb4d489258 | 43.0625 | 140 | 0.787589 | 4.615385 | false | false | false | false |
TeamNewPipe/NewPipe | app/src/main/java/org/schabi/newpipe/local/feed/service/FeedLoadManager.kt | 1 | 11917 | package org.schabi.newpipe.local.feed.service
import android.content.Context
import androidx.preference.PreferenceManager
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.core.Notification
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.functions.Consumer
import io.reactivex.rxjava3.processors.PublishProcessor
import io.reactivex.rxjava3.schedulers.Schedulers
import org.schabi.newpipe.R
import org.schabi.newpipe.database.feed.model.FeedGroupEntity
import org.schabi.newpipe.database.subscription.NotificationMode
import org.schabi.newpipe.extractor.ListInfo
import org.schabi.newpipe.extractor.stream.StreamInfoItem
import org.schabi.newpipe.local.feed.FeedDatabaseManager
import org.schabi.newpipe.local.subscription.SubscriptionManager
import org.schabi.newpipe.util.ExtractorHelper
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
class FeedLoadManager(private val context: Context) {
private val subscriptionManager = SubscriptionManager(context)
private val feedDatabaseManager = FeedDatabaseManager(context)
private val notificationUpdater = PublishProcessor.create<String>()
private val currentProgress = AtomicInteger(-1)
private val maxProgress = AtomicInteger(-1)
private val cancelSignal = AtomicBoolean()
private val feedResultsHolder = FeedResultsHolder()
val notification: Flowable<FeedLoadState> = notificationUpdater.map { description ->
FeedLoadState(description, maxProgress.get(), currentProgress.get())
}
/**
* Start checking for new streams of a subscription group.
* @param groupId The ID of the subscription group to load. When using
* [FeedGroupEntity.GROUP_ALL_ID], all subscriptions are loaded. When using
* [GROUP_NOTIFICATION_ENABLED], only subscriptions with enabled notifications for new streams
* are loaded. Using an id of a group created by the user results in that specific group to be
* loaded.
* @param ignoreOutdatedThreshold When `false`, only subscriptions which have not been updated
* within the `feed_update_threshold` are checked for updates. This threshold can be set by
* the user in the app settings. When `true`, all subscriptions are checked for new streams.
*/
fun startLoading(
groupId: Long = FeedGroupEntity.GROUP_ALL_ID,
ignoreOutdatedThreshold: Boolean = false,
): Single<List<Notification<FeedUpdateInfo>>> {
val defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val useFeedExtractor = defaultSharedPreferences.getBoolean(
context.getString(R.string.feed_use_dedicated_fetch_method_key),
false
)
val outdatedThreshold = if (ignoreOutdatedThreshold) {
OffsetDateTime.now(ZoneOffset.UTC)
} else {
val thresholdOutdatedSeconds = (
defaultSharedPreferences.getString(
context.getString(R.string.feed_update_threshold_key),
context.getString(R.string.feed_update_threshold_default_value)
) ?: context.getString(R.string.feed_update_threshold_default_value)
).toInt()
OffsetDateTime.now(ZoneOffset.UTC).minusSeconds(thresholdOutdatedSeconds.toLong())
}
/**
* subscriptions which have not been updated within the feed updated threshold
*/
val outdatedSubscriptions = when (groupId) {
FeedGroupEntity.GROUP_ALL_ID -> feedDatabaseManager.outdatedSubscriptions(outdatedThreshold)
GROUP_NOTIFICATION_ENABLED -> feedDatabaseManager.outdatedSubscriptionsWithNotificationMode(
outdatedThreshold, NotificationMode.ENABLED
)
else -> feedDatabaseManager.outdatedSubscriptionsForGroup(groupId, outdatedThreshold)
}
return outdatedSubscriptions
.take(1)
.doOnNext {
currentProgress.set(0)
maxProgress.set(it.size)
}
.filter { it.isNotEmpty() }
.observeOn(AndroidSchedulers.mainThread())
.doOnNext {
notificationUpdater.onNext("")
broadcastProgress()
}
.observeOn(Schedulers.io())
.flatMap { Flowable.fromIterable(it) }
.takeWhile { !cancelSignal.get() }
.parallel(PARALLEL_EXTRACTIONS, PARALLEL_EXTRACTIONS * 2)
.runOn(Schedulers.io(), PARALLEL_EXTRACTIONS * 2)
.filter { !cancelSignal.get() }
.map { subscriptionEntity ->
var error: Throwable? = null
try {
// check for and load new streams
// either by using the dedicated feed method or by getting the channel info
val listInfo = if (useFeedExtractor) {
ExtractorHelper
.getFeedInfoFallbackToChannelInfo(
subscriptionEntity.serviceId,
subscriptionEntity.url
)
.onErrorReturn {
error = it // store error, otherwise wrapped into RuntimeException
throw it
}
.blockingGet()
} else {
ExtractorHelper
.getChannelInfo(
subscriptionEntity.serviceId,
subscriptionEntity.url,
true
)
.onErrorReturn {
error = it // store error, otherwise wrapped into RuntimeException
throw it
}
.blockingGet()
} as ListInfo<StreamInfoItem>
return@map Notification.createOnNext(
FeedUpdateInfo(
subscriptionEntity,
listInfo
)
)
} catch (e: Throwable) {
if (error == null) {
// do this to prevent blockingGet() from wrapping into RuntimeException
error = e
}
val request = "${subscriptionEntity.serviceId}:${subscriptionEntity.url}"
val wrapper =
FeedLoadService.RequestException(subscriptionEntity.uid, request, error!!)
return@map Notification.createOnError<FeedUpdateInfo>(wrapper)
}
}
.sequential()
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(NotificationConsumer())
.observeOn(Schedulers.io())
.buffer(BUFFER_COUNT_BEFORE_INSERT)
.doOnNext(DatabaseConsumer())
.subscribeOn(Schedulers.io())
.toList()
.flatMap { x -> postProcessFeed().toSingleDefault(x.flatten()) }
}
fun cancel() {
cancelSignal.set(true)
}
private fun broadcastProgress() {
FeedEventManager.postEvent(FeedEventManager.Event.ProgressEvent(currentProgress.get(), maxProgress.get()))
}
/**
* Keep the feed and the stream tables small
* to reduce loading times when trying to display the feed.
* <br>
* Remove streams from the feed which are older than [FeedDatabaseManager.FEED_OLDEST_ALLOWED_DATE].
* Remove streams from the database which are not linked / used by any table.
*/
private fun postProcessFeed() = Completable.fromRunnable {
FeedEventManager.postEvent(FeedEventManager.Event.ProgressEvent(R.string.feed_processing_message))
feedDatabaseManager.removeOrphansOrOlderStreams()
FeedEventManager.postEvent(FeedEventManager.Event.SuccessResultEvent(feedResultsHolder.itemsErrors))
}.doOnSubscribe {
currentProgress.set(-1)
maxProgress.set(-1)
notificationUpdater.onNext(context.getString(R.string.feed_processing_message))
FeedEventManager.postEvent(FeedEventManager.Event.ProgressEvent(R.string.feed_processing_message))
}.subscribeOn(Schedulers.io())
private inner class NotificationConsumer : Consumer<Notification<FeedUpdateInfo>> {
override fun accept(item: Notification<FeedUpdateInfo>) {
currentProgress.incrementAndGet()
notificationUpdater.onNext(item.value?.name.orEmpty())
broadcastProgress()
}
}
private inner class DatabaseConsumer : Consumer<List<Notification<FeedUpdateInfo>>> {
override fun accept(list: List<Notification<FeedUpdateInfo>>) {
feedDatabaseManager.database().runInTransaction {
for (notification in list) {
when {
notification.isOnNext -> {
val subscriptionId = notification.value!!.uid
val info = notification.value!!.listInfo
notification.value!!.newStreams = filterNewStreams(
notification.value!!.listInfo.relatedItems
)
feedDatabaseManager.upsertAll(subscriptionId, info.relatedItems)
subscriptionManager.updateFromInfo(subscriptionId, info)
if (info.errors.isNotEmpty()) {
feedResultsHolder.addErrors(
FeedLoadService.RequestException.wrapList(
subscriptionId,
info
)
)
feedDatabaseManager.markAsOutdated(subscriptionId)
}
}
notification.isOnError -> {
val error = notification.error
feedResultsHolder.addError(error!!)
if (error is FeedLoadService.RequestException) {
feedDatabaseManager.markAsOutdated(error.subscriptionId)
}
}
}
}
}
}
private fun filterNewStreams(list: List<StreamInfoItem>): List<StreamInfoItem> {
return list.filter {
!feedDatabaseManager.doesStreamExist(it) &&
it.uploadDate != null &&
// Streams older than this date are automatically removed from the feed.
// Therefore, streams which are not in the database,
// but older than this date, are considered old.
it.uploadDate!!.offsetDateTime().isAfter(
FeedDatabaseManager.FEED_OLDEST_ALLOWED_DATE
)
}
}
}
companion object {
/**
* Constant used to check for updates of subscriptions with [NotificationMode.ENABLED].
*/
const val GROUP_NOTIFICATION_ENABLED = -2L
/**
* How many extractions will be running in parallel.
*/
private const val PARALLEL_EXTRACTIONS = 6
/**
* Number of items to buffer to mass-insert in the database.
*/
private const val BUFFER_COUNT_BEFORE_INSERT = 20
}
}
| gpl-3.0 | bbadaf83ef01aa90212364a54026f126 | 43.137037 | 114 | 0.587312 | 5.790573 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/dialogs/VoterDialogListener.kt | 1 | 2501 | package io.github.feelfreelinux.wykopmobilny.ui.dialogs
import android.text.SpannableStringBuilder
import android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.Gravity
import android.view.View
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Author
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Voter
import io.github.feelfreelinux.wykopmobilny.ui.modules.profile.ProfileActivity
import io.github.feelfreelinux.wykopmobilny.utils.api.getGroupColor
import io.github.feelfreelinux.wykopmobilny.utils.appendNewSpan
import io.github.feelfreelinux.wykopmobilny.utils.getActivityContext
import io.github.feelfreelinux.wykopmobilny.utils.isVisible
import kotlinx.android.synthetic.main.dialog_voters.view.*
typealias VotersDialogListener = (List<Voter>) -> Unit
fun createVotersDialogListener(
dialog: com.google.android.material.bottomsheet.BottomSheetDialog,
votersDialogView: View
): (List<Voter>) -> Unit = {
if (dialog.isShowing) {
votersDialogView.progressView.isVisible = false
votersDialogView.votersTextView.isVisible = true
val spannableStringBuilder = SpannableStringBuilder()
it
.map { voter -> voter.author }
.forEachIndexed { index, author ->
val span = ClickableUserSpan(author)
spannableStringBuilder.appendNewSpan(author.nick, span, SPAN_EXCLUSIVE_EXCLUSIVE)
if (index < it.size - 1) spannableStringBuilder.append(", ")
}
if (spannableStringBuilder.isEmpty()) {
votersDialogView.votersTextView.gravity = Gravity.CENTER
spannableStringBuilder.append(votersDialogView.context.getString(R.string.dialogNoVotes))
}
votersDialogView.votersTextView.movementMethod = (LinkMovementMethod.getInstance()) // Auuu
votersDialogView.votersTextView.text = spannableStringBuilder
}
}
class ClickableUserSpan(val author: Author) : ClickableSpan() {
override fun onClick(authorView: View) {
val activity = authorView.getActivityContext()
activity?.startActivity(ProfileActivity.createIntent(activity, author.nick))
}
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.color = getGroupColor(author.group)
ds.isUnderlineText = false
}
} | mit | c67e184da09dbb271a96a01284454917 | 42.894737 | 101 | 0.753299 | 4.614391 | false | false | false | false |
550609334/Twobbble | app/src/main/java/com/twobbble/tools/Utils.kt | 1 | 11740 | package com.twobbble.tools
import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.location.LocationManager
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.Uri
import android.os.Build
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import com.google.gson.internal.bind.util.ISO8601Utils
import com.twobbble.application.App
import org.jetbrains.anko.displayMetrics
import java.io.ByteArrayOutputStream
import java.io.File
import java.math.BigDecimal
import java.text.DecimalFormat
import java.text.ParseException
import java.text.ParsePosition
import java.text.SimpleDateFormat
import kotlin.concurrent.thread
/**
* Created by liuzipeng on 16/7/8.
*/
object Utils {
/**
* 判断网络可不可用
* @return true为可用
*/
fun isNetworkAvailable(context: Context): Boolean {
val cm: ConnectivityManager? = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val info = cm?.activeNetworkInfo
if (info != null) {
return info.isAvailable && info.isConnected
}
return false
}
/**
* sp转px
* @param sp
* *
* @param metrics
* *
* @return
*/
fun sp2px(sp: Int): Float {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp.toFloat(), App.instance.displayMetrics)
}
/**
* dp转px
* @param dp
* *
* @param metrics
* *
* @return
*/
fun dp2px(dp: Int): Float {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(), App.instance.displayMetrics)
}
fun dp2px(dp: Float): Float {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, App.instance.displayMetrics)
}
/**
* 获取版本号
* @param context
* *
* @return
*/
fun getVersion(context: Context): String = try {
val pi = context.packageManager.getPackageInfo(context.packageName, 0)
pi.versionName
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
"版本未知"
}
/**
* 获取版本代号
* @param context
* *
* @return
*/
fun getVersionCode(context: Context): Int {
try {
val pi = context.packageManager.getPackageInfo(context.packageName, 0)
return pi.versionCode
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
return 0
}
}
//Android获取一个用于打开APK文件的intent
fun openApk(context: Context, file: File) {
val intent = Intent()
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.action = Intent.ACTION_VIEW
val uri = Uri.fromFile(file)
intent.setDataAndType(uri, "application/vnd.android.package-archive")
context.startActivity(intent)
}
/**
* 判断手机GPS是否可用
* @param context
* *
* @return
*/
fun isGpsEnable(context: Context): Boolean {
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
val network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
if (gps || network) {
return true
}
return false
}
/**
* 隐藏软键盘
* @param editText
*/
fun hideKeyboard(editText: EditText) {
val imm = editText
.context.getSystemService(
Context.INPUT_METHOD_SERVICE) as InputMethodManager
if (imm.isActive) {
imm.hideSoftInputFromWindow(
editText.applicationWindowToken, 0)
}
}
@SuppressLint("MissingPermission")
/**
* 获取imei
* @param context
* *
* @return
*/
fun getDeviceImei(context: Context): String {
val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
return telephonyManager.deviceId
}
@SuppressLint("MissingPermission")
/**
* 获取手机号码
* @param context
* *
* @return
*/
fun getPhoneNumber(context: Context): String {
val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
return telephonyManager.line1Number.substring(3, 14)
}
/**
* 判断该系统是否在5.0以上 是否支持Material Design
* @return
*/
fun supportMaterial(): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return false
}
return true
}
/**
* 将16进制转为2进制
* @param hexString
* *
* @return
*/
fun convertHexToBinary2(hexString: String): String {
val l = java.lang.Long.parseLong(hexString, 16)
val binaryString = java.lang.Long.toBinaryString(l)
val shouldBinaryLen = hexString.length * 4
val addZero = StringBuffer()
val addZeroNum = shouldBinaryLen - binaryString.length
for (i in 1..addZeroNum) {
addZero.append("0")
}
return addZero.toString() + binaryString
}
/**
* 获取一个View的宽度
* @param view
* *
* @return
*/
fun getViewWidth(view: View): Int {
view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
return view.measuredWidth
}
/**
* 获取一个View的高度
* @param view
* *
* @return
*/
fun getViewHeight(view: View): Int {
view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
return view.measuredHeight
}
/**
* 保留一位小数
* @param num
* *
* @return
*/
fun keepOneDecimal(num: Double): String {
val formater = DecimalFormat()
formater.maximumFractionDigits = 1
return formater.format(num)
}
/**
* 格式化文件大小单位
* @param size
* *
* @return
*/
fun formatFileSize(size: Double): String {
val kiloByte = size / 1024
if (kiloByte < 1) {
return "${size}Byte"
}
val megaByte = kiloByte / 1024
if (megaByte < 1) {
val result1 = BigDecimal(kiloByte.toString())
return "${result1.setScale(2, BigDecimal.ROUND_HALF_UP)
.toPlainString()}KB"
}
val gigaByte = megaByte / 1024
if (gigaByte < 1) {
val result2 = BigDecimal(gigaByte.toString())
return "${result2.setScale(2, BigDecimal.ROUND_HALF_UP)
.toPlainString()}MB"
}
val teraBytes = gigaByte / 1024
if (teraBytes < 1) {
val result3 = BigDecimal(teraBytes.toString())
return "${result3.setScale(2, BigDecimal.ROUND_HALF_UP)
.toPlainString()}GB"
}
val result4 = BigDecimal(teraBytes)
return "${result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()}TB"
}
/**
* 删除指定目录下文件及目录
* @param deleteThisPath
* *
* @param filePath
* *
* @return
*/
fun deleteFolderFile(filePath: String, deleteThisPath: Boolean) {
Thread {
if (!TextUtils.isEmpty(filePath)) {
try {
val file = File(filePath)
if (file.isDirectory) {// 如果下面还有文件
val files = file.listFiles()
for (i in files.indices) {
deleteFolderFile(files[i].absolutePath, true)
}
}
if (deleteThisPath) {
if (!file.isDirectory) {// 如果是文件,删除
file.delete()
} else {// 目录
if (file.listFiles().isEmpty()) {// 目录下没有文件或者目录,删除
file.delete()
}
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}.start()
}
/**
* 判断当前进程是否是主进程
* @param context
* *
* @return
*/
fun inMainProcess(context: Context): Boolean {
val packageName = context.packageName
val processName = Utils.getProcessName(context)
return packageName == processName
}
/**
* 获取当前进程名
* @param context
* *
* @return 进程名
*/
fun getProcessName(context: Context): String? {
var processName: String? = null
// ActivityManager
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
while (true) {
for (info in am.runningAppProcesses) {
if (info.pid == android.os.Process.myPid()) {
processName = info.processName
break
}
}
// go home
if (!TextUtils.isEmpty(processName)) {
return processName
}
// take a rest and again
try {
Thread.sleep(100L)
} catch (ex: InterruptedException) {
ex.printStackTrace()
}
}
}
//将bitmap转换为byte[]格式
fun bmpToByteArray(bitmap: Bitmap, needRecycle: Boolean): ByteArray {
val output = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)
if (needRecycle) {
bitmap.recycle()
}
val result = output.toByteArray()
try {
output.close()
} catch (e: Exception) {
e.printStackTrace()
}
return result
}
fun hasNavigationBar(context: Context): Boolean {
//通过判断设备是否有返回键、菜单键(不是虚拟键,是手机屏幕外的按键)来确定是否有navigation bar
val hasMenuKey = ViewConfiguration.get(context)
.hasPermanentMenuKey()
val hasBackKey = KeyCharacterMap
.deviceHasKey(KeyEvent.KEYCODE_BACK)
return !hasMenuKey && !hasBackKey
}
fun formatDateUseCh(ms: Long): String {
val dateFormat = SimpleDateFormat("yyyy-MM-dd")
return dateFormat.format(ms)
}
fun formatTimeUseCh(ms: Long): String {
val dateFormat = SimpleDateFormat("HH:mm:ss")
return dateFormat.format(ms)
}
fun parseISO8601(date: String): Long {
return ISO8601Utils.parse(date, ParsePosition(0)).time
}
}
| apache-2.0 | 2418ab57e0a28a89b5ce8e4eef83793a | 25.850356 | 116 | 0.577052 | 4.519792 | false | false | false | false |
hotchemi/PermissionsDispatcher | ktx-sample/src/main/java/permissions/dispatcher/ktx/sample/camera/CameraPreviewFragment.kt | 1 | 3627 | package permissions.dispatcher.ktx.sample.camera
import android.annotation.SuppressLint
import android.hardware.Camera
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import androidx.fragment.app.Fragment
import permissions.dispatcher.ktx.sample.R
/**
* Displays a [CameraPreview] of the first [Camera].
* An error message is displayed if the Camera is not available.
*
*
* This Fragment is only used to illustrate that access to the Camera API has been granted (or
* denied) as part of the runtime permissions model. It is not relevant for the use of the
* permissions API.
*
*
* Implementation is based directly on the documentation at
* http://developer.android.com/guide/topics/media/camera.html
*/
class CameraPreviewFragment : Fragment() {
private var preview: CameraPreview? = null
private var camera: Camera? = null
@SuppressLint("InflateParams")
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_camera, null)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val button: Button? = view.findViewById(R.id.back)
button?.setOnClickListener {
fragmentManager?.popBackStack()
}
initCamera()
}
private fun initCamera() {
camera = getCameraInstance(CAMERA_ID)?.also { camera ->
val cameraInfo = Camera.CameraInfo().also { Camera.getCameraInfo(CAMERA_ID, it) }
// Get the rotation of the screen to adjust the preview image accordingly.
val displayRotation = activity?.windowManager?.defaultDisplay?.rotation
val previewFrameLayout: FrameLayout? = view?.findViewById(R.id.camera_preview)
previewFrameLayout?.removeAllViews()
if (displayRotation == null) {
return
}
preview?.setCamera(camera, cameraInfo, displayRotation) ?: run {
// Create the Preview view and set it as the content of this Activity.
context?.let {
preview = CameraPreview(it, camera, cameraInfo, displayRotation)
}
}
previewFrameLayout?.addView(preview)
}
}
override fun onResume() {
super.onResume()
camera ?: initCamera()
}
override fun onPause() {
super.onPause()
// Stop camera access
releaseCamera()
}
private fun releaseCamera() {
camera?.release()?.run { camera = null }
// release destroyed preview
preview = null
}
companion object {
private const val TAG = "CameraPreview"
/**
* Id of the camera to access. 0 is the first camera.
*/
private const val CAMERA_ID = 0
fun newInstance(): CameraPreviewFragment = CameraPreviewFragment()
/** A safe way to get an instance of the Camera object. */
fun getCameraInstance(cameraId: Int): Camera? = try {
// attempt to get a Camera instance
Camera.open(cameraId)
} catch (e: Exception) {
// Camera is not available (in use or does not exist)
Log.d(TAG, "Camera " + cameraId + " is not available: " + e.message)
null
}
}
}
| apache-2.0 | f1acb116830fce802dd09220a8659a24 | 33.542857 | 94 | 0.62917 | 4.894737 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeInfo.kt | 1 | 27189 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.changeSignature
import com.intellij.lang.Language
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.psi.*
import com.intellij.psi.search.searches.OverridingMethodsSearch
import com.intellij.refactoring.changeSignature.*
import com.intellij.refactoring.util.CanonicalTypes
import com.intellij.usageView.UsageInfo
import com.intellij.util.VisibilityUtil
import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.builtins.isNonExtensionFunctionType
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.DescriptorVisibility
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaOrKotlinMemberDescriptor
import org.jetbrains.kotlin.idea.core.unquote
import org.jetbrains.kotlin.idea.j2k.j2k
import org.jetbrains.kotlin.idea.project.TargetPlatformDetector
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinMethodDescriptor.Kind
import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinCallableDefinitionUsage
import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinCallerUsage
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.isIdentifier
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.jvm.annotations.findJvmOverloadsAnnotation
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.utils.keysToMap
open class KotlinChangeInfo(
val methodDescriptor: KotlinMethodDescriptor,
private var name: String = methodDescriptor.name,
var newReturnTypeInfo: KotlinTypeInfo = KotlinTypeInfo(true, methodDescriptor.baseDescriptor.returnType),
var newVisibility: DescriptorVisibility = methodDescriptor.visibility,
parameterInfos: List<KotlinParameterInfo> = methodDescriptor.parameters,
receiver: KotlinParameterInfo? = methodDescriptor.receiver,
val context: PsiElement,
primaryPropagationTargets: Collection<PsiElement> = emptyList(),
var checkUsedParameters: Boolean = false,
) : ChangeInfo, UserDataHolder by UserDataHolderBase() {
private val innerChangeInfo: MutableList<KotlinChangeInfo> = mutableListOf()
fun registerInnerChangeInfo(changeInfo: KotlinChangeInfo) {
innerChangeInfo += changeInfo
}
private class JvmOverloadSignature(
val method: PsiMethod,
val mandatoryParams: Set<KtParameter>,
val defaultValues: Set<KtExpression>
) {
fun constrainBy(other: JvmOverloadSignature): JvmOverloadSignature {
return JvmOverloadSignature(
method,
mandatoryParams.intersect(other.mandatoryParams),
defaultValues.intersect(other.defaultValues)
)
}
}
private val originalReturnTypeInfo = methodDescriptor.returnTypeInfo
private val originalReceiverTypeInfo = methodDescriptor.receiver?.originalTypeInfo
var receiverParameterInfo: KotlinParameterInfo? = receiver
set(value) {
if (value != null && value !in newParameters) {
newParameters.add(value)
}
field = value
}
private val newParameters = parameterInfos.toMutableList()
private val originalPsiMethods = method.toLightMethods()
private val originalParameters = (method as? KtFunction)?.valueParameters ?: emptyList()
private val originalSignatures = makeSignatures(originalParameters, originalPsiMethods, { it }, { it.defaultValue })
private val oldNameToParameterIndex: Map<String, Int> by lazy {
val map = HashMap<String, Int>()
val parameters = methodDescriptor.baseDescriptor.valueParameters
parameters.indices.forEach { i -> map[parameters[i].name.asString()] = i }
map
}
private val isParameterSetOrOrderChangedLazy: Boolean by lazy {
val signatureParameters = getNonReceiverParameters()
methodDescriptor.receiver != receiverParameterInfo ||
signatureParameters.size != methodDescriptor.parametersCount ||
signatureParameters.indices.any { i -> signatureParameters[i].oldIndex != i }
}
private var isPrimaryMethodUpdated: Boolean = false
private var javaChangeInfos: List<JavaChangeInfo>? = null
var originalToCurrentMethods: Map<PsiMethod, PsiMethod> = emptyMap()
private set
val parametersToRemove: BooleanArray
get() {
val originalReceiver = methodDescriptor.receiver
val hasReceiver = methodDescriptor.receiver != null
val receiverShift = if (hasReceiver) 1 else 0
val toRemove = BooleanArray(receiverShift + methodDescriptor.parametersCount) { true }
if (hasReceiver) {
toRemove[0] = receiverParameterInfo == null && hasReceiver && originalReceiver !in getNonReceiverParameters()
}
for (parameter in newParameters) {
parameter.oldIndex.takeIf { it >= 0 }?.let { oldIndex ->
toRemove[receiverShift + oldIndex] = false
}
}
return toRemove
}
fun getOldParameterIndex(oldParameterName: String): Int? = oldNameToParameterIndex[oldParameterName]
override fun isParameterTypesChanged(): Boolean = true
override fun isParameterNamesChanged(): Boolean = true
override fun isParameterSetOrOrderChanged(): Boolean = isParameterSetOrOrderChangedLazy
fun getNewParametersCount(): Int = newParameters.size
fun hasAppendedParametersOnly(): Boolean {
val oldParamCount = originalBaseFunctionDescriptor.valueParameters.size
return newParameters.asSequence().withIndex().all { (i, p) -> if (i < oldParamCount) p.oldIndex == i else p.isNewParameter }
}
override fun getNewParameters(): Array<KotlinParameterInfo> = newParameters.toTypedArray()
fun getNonReceiverParametersCount(): Int = newParameters.size - (if (receiverParameterInfo != null) 1 else 0)
fun getNonReceiverParameters(): List<KotlinParameterInfo> {
methodDescriptor.baseDeclaration.let { if (it is KtProperty || it is KtParameter) return emptyList() }
return receiverParameterInfo?.let { receiver -> newParameters.filter { it != receiver } } ?: newParameters
}
fun setNewParameter(index: Int, parameterInfo: KotlinParameterInfo) {
newParameters[index] = parameterInfo
}
@JvmOverloads
fun addParameter(parameterInfo: KotlinParameterInfo, atIndex: Int = -1) {
if (atIndex >= 0) {
newParameters.add(atIndex, parameterInfo)
} else {
newParameters.add(parameterInfo)
}
}
fun removeParameter(index: Int) {
val parameterInfo = newParameters.removeAt(index)
if (parameterInfo == receiverParameterInfo) {
receiverParameterInfo = null
}
}
fun clearParameters() {
newParameters.clear()
receiverParameterInfo = null
}
fun hasParameter(parameterInfo: KotlinParameterInfo): Boolean =
parameterInfo in newParameters
override fun isGenerateDelegate(): Boolean = false
override fun getNewName(): String = name.takeIf { it != "<no name provided>" }?.quoteIfNeeded() ?: name
fun setNewName(value: String) {
name = value
}
override fun isNameChanged(): Boolean = name != methodDescriptor.name
fun isVisibilityChanged(): Boolean = newVisibility != methodDescriptor.visibility
override fun getMethod(): PsiElement {
return methodDescriptor.method
}
override fun isReturnTypeChanged(): Boolean = !newReturnTypeInfo.isEquivalentTo(originalReturnTypeInfo)
fun isReceiverTypeChanged(): Boolean {
val receiverInfo = receiverParameterInfo ?: return originalReceiverTypeInfo != null
return originalReceiverTypeInfo == null || !receiverInfo.currentTypeInfo.isEquivalentTo(originalReceiverTypeInfo)
}
override fun getLanguage(): Language = KotlinLanguage.INSTANCE
var propagationTargetUsageInfos: List<UsageInfo> = ArrayList()
private set
var primaryPropagationTargets: Collection<PsiElement> = emptyList()
set(value) {
field = value
val result = LinkedHashSet<UsageInfo>()
fun add(element: PsiElement) {
element.unwrapped?.let {
val usageInfo = when (it) {
is KtNamedFunction, is KtConstructor<*>, is KtClassOrObject ->
KotlinCallerUsage(it as KtNamedDeclaration)
is PsiMethod ->
CallerUsageInfo(it, true, true)
else ->
return
}
result.add(usageInfo)
}
}
for (caller in value) {
add(caller)
OverridingMethodsSearch.search(caller.getRepresentativeLightMethod() ?: continue).forEach(::add)
}
propagationTargetUsageInfos = result.toList()
}
init {
this.primaryPropagationTargets = primaryPropagationTargets
}
private fun renderReturnTypeIfNeeded(): String? {
val typeInfo = newReturnTypeInfo
if (kind != Kind.FUNCTION) return null
if (typeInfo.type?.isUnit() == true) return null
return typeInfo.render()
}
fun getNewSignature(inheritedCallable: KotlinCallableDefinitionUsage<PsiElement>): String {
val buffer = StringBuilder()
val isCustomizedVisibility = newVisibility != DescriptorVisibilities.DEFAULT_VISIBILITY
if (kind == Kind.PRIMARY_CONSTRUCTOR) {
buffer.append(newName)
if (isCustomizedVisibility) {
buffer.append(' ').append(newVisibility).append(" constructor ")
}
} else {
if (!DescriptorUtils.isLocal(inheritedCallable.originalCallableDescriptor) && isCustomizedVisibility) {
buffer.append(newVisibility).append(' ')
}
buffer.append(if (kind == Kind.SECONDARY_CONSTRUCTOR) KtTokens.CONSTRUCTOR_KEYWORD else KtTokens.FUN_KEYWORD).append(' ')
if (kind == Kind.FUNCTION) {
receiverParameterInfo?.let {
val typeInfo = it.currentTypeInfo
if (typeInfo.type != null && typeInfo.type.isNonExtensionFunctionType) {
buffer.append("(${typeInfo.render()})")
} else {
buffer.append(typeInfo.render())
}
buffer.append('.')
}
buffer.append(newName)
}
}
buffer.append(getNewParametersSignature(inheritedCallable))
renderReturnTypeIfNeeded()?.let { buffer.append(": ").append(it) }
return buffer.toString()
}
fun getNewParametersSignature(inheritedCallable: KotlinCallableDefinitionUsage<*>): String {
return "(" + getNewParametersSignatureWithoutParentheses(inheritedCallable) + ")"
}
fun getNewParametersSignatureWithoutParentheses(
inheritedCallable: KotlinCallableDefinitionUsage<*>
): String {
val signatureParameters = getNonReceiverParameters()
val isLambda = inheritedCallable.declaration is KtFunctionLiteral
if (isLambda && signatureParameters.size == 1 && !signatureParameters[0].requiresExplicitType(inheritedCallable)) {
return signatureParameters[0].getDeclarationSignature(0, inheritedCallable).text
}
return signatureParameters.indices.joinToString(separator = ", ") { i ->
signatureParameters[i].getDeclarationSignature(i, inheritedCallable).text
}
}
fun renderReceiverType(inheritedCallable: KotlinCallableDefinitionUsage<*>): String? {
val receiverTypeText = receiverParameterInfo?.currentTypeInfo?.render() ?: return null
val typeSubstitutor = inheritedCallable.typeSubstitutor ?: return receiverTypeText
val currentBaseFunction = inheritedCallable.baseFunction.currentCallableDescriptor ?: return receiverTypeText
val receiverType = currentBaseFunction.extensionReceiverParameter!!.type
if (receiverType.isError) return receiverTypeText
return receiverType.renderTypeWithSubstitution(typeSubstitutor, receiverTypeText, false)
}
fun renderReturnType(inheritedCallable: KotlinCallableDefinitionUsage<*>): String {
val defaultRendering = newReturnTypeInfo.render()
val typeSubstitutor = inheritedCallable.typeSubstitutor ?: return defaultRendering
val currentBaseFunction = inheritedCallable.baseFunction.currentCallableDescriptor ?: return defaultRendering
val returnType = currentBaseFunction.returnType!!
if (returnType.isError) return defaultRendering
return returnType.renderTypeWithSubstitution(typeSubstitutor, defaultRendering, false)
}
fun primaryMethodUpdated() {
isPrimaryMethodUpdated = true
javaChangeInfos = null
for (info in innerChangeInfo) {
info.primaryMethodUpdated()
}
}
private fun <Parameter> makeSignatures(
parameters: List<Parameter>,
psiMethods: List<PsiMethod>,
getPsi: (Parameter) -> KtParameter,
getDefaultValue: (Parameter) -> KtExpression?
): List<JvmOverloadSignature> {
val defaultValueCount = parameters.count { getDefaultValue(it) != null }
if (psiMethods.size != defaultValueCount + 1) return emptyList()
val mandatoryParams = parameters.toMutableList()
val defaultValues = ArrayList<KtExpression>()
return psiMethods.map { method ->
JvmOverloadSignature(method, mandatoryParams.asSequence().map(getPsi).toSet(), defaultValues.toSet()).apply {
val param = mandatoryParams.removeLast { getDefaultValue(it) != null } ?: return@apply
defaultValues.add(getDefaultValue(param)!!)
}
}
}
private fun <T> MutableList<T>.removeLast(condition: (T) -> Boolean): T? {
val index = indexOfLast(condition)
return if (index >= 0) removeAt(index) else null
}
fun getOrCreateJavaChangeInfos(): List<JavaChangeInfo>? {
fun initCurrentSignatures(currentPsiMethods: List<PsiMethod>): List<JvmOverloadSignature> {
val parameterInfoToPsi = methodDescriptor.original.parameters.zip(originalParameters).toMap()
val dummyParameter = KtPsiFactory(method).createParameter("dummy")
return makeSignatures(
parameters = newParameters,
psiMethods = currentPsiMethods,
getPsi = { parameterInfoToPsi[it] ?: dummyParameter },
getDefaultValue = { it.defaultValue },
)
}
fun matchOriginalAndCurrentMethods(currentPsiMethods: List<PsiMethod>): Map<PsiMethod, PsiMethod> {
if (!(isPrimaryMethodUpdated && originalBaseFunctionDescriptor is FunctionDescriptor && originalBaseFunctionDescriptor.findJvmOverloadsAnnotation() != null)) {
return (originalPsiMethods.zip(currentPsiMethods)).toMap()
}
if (originalPsiMethods.isEmpty() || currentPsiMethods.isEmpty()) return emptyMap()
currentPsiMethods.singleOrNull()?.let { method -> return originalPsiMethods.keysToMap { method } }
val currentSignatures = initCurrentSignatures(currentPsiMethods)
return originalSignatures.associateBy({ it.method }) { originalSignature ->
var constrainedCurrentSignatures = currentSignatures.map { it.constrainBy(originalSignature) }
val maxMandatoryCount = constrainedCurrentSignatures.maxOf { it.mandatoryParams.size }
constrainedCurrentSignatures = constrainedCurrentSignatures.filter { it.mandatoryParams.size == maxMandatoryCount }
val maxDefaultCount = constrainedCurrentSignatures.maxOf { it.defaultValues.size }
constrainedCurrentSignatures.last { it.defaultValues.size == maxDefaultCount }.method
}
}
/*
* When primaryMethodUpdated is false, changes to the primary Kotlin declaration are already confirmed, but not yet applied.
* It means that originalPsiMethod has already expired, but new one can't be created until Kotlin declaration is updated
* (signified by primaryMethodUpdated being true). It means we can't know actual PsiType, visibility, etc.
* to use in JavaChangeInfo. However they are not actually used at this point since only parameter count and order matters here
* So we resort to this hack and pass around "default" type (void) and visibility (package-local)
*/
fun createJavaChangeInfo(
originalPsiMethod: PsiMethod,
currentPsiMethod: PsiMethod,
newName: String,
newReturnType: PsiType?,
newParameters: Array<ParameterInfoImpl>
): JavaChangeInfo? {
if (!newName.unquote().isIdentifier()) return null
val newVisibility = if (isPrimaryMethodUpdated)
VisibilityUtil.getVisibilityModifier(currentPsiMethod.modifierList)
else
PsiModifier.PACKAGE_LOCAL
val propagationTargets = primaryPropagationTargets.asSequence()
.mapNotNull { it.getRepresentativeLightMethod() }
.toSet()
val javaChangeInfo = ChangeSignatureProcessor(
method.project,
originalPsiMethod,
false,
newVisibility,
newName,
CanonicalTypes.createTypeWrapper(newReturnType ?: PsiType.VOID),
newParameters,
arrayOf<ThrownExceptionInfo>(),
propagationTargets,
emptySet()
).changeInfo
javaChangeInfo.updateMethod(currentPsiMethod)
return javaChangeInfo
}
fun getJavaParameterInfos(
originalPsiMethod: PsiMethod,
currentPsiMethod: PsiMethod,
newParameterList: List<KotlinParameterInfo>
): MutableList<ParameterInfoImpl> {
val defaultValuesToSkip = newParameterList.size - currentPsiMethod.parameterList.parametersCount
val defaultValuesToRetain = newParameterList.count { it.defaultValue != null } - defaultValuesToSkip
val oldIndices = newParameterList.map { it.oldIndex }.toIntArray()
// TODO: Ugly code, need to refactor Change Signature data model
var defaultValuesRemained = defaultValuesToRetain
for (param in newParameterList) {
if (param.isNewParameter || param.defaultValue == null || defaultValuesRemained-- > 0) continue
newParameterList.asSequence()
.withIndex()
.filter { it.value.oldIndex >= param.oldIndex }
.toList()
.forEach { oldIndices[it.index]-- }
}
defaultValuesRemained = defaultValuesToRetain
val oldParameterCount = originalPsiMethod.parameterList.parametersCount
var indexInCurrentPsiMethod = 0
return newParameterList.asSequence().withIndex().mapNotNullTo(ArrayList()) map@{ pair ->
val (i, info) = pair
if (info.defaultValue != null && defaultValuesRemained-- <= 0) return@map null
val oldIndex = oldIndices[i]
val javaOldIndex = when {
methodDescriptor.receiver == null -> oldIndex
info == methodDescriptor.receiver -> 0
oldIndex >= 0 -> oldIndex + 1
else -> -1
}
if (javaOldIndex >= oldParameterCount) return@map null
val type = if (isPrimaryMethodUpdated)
currentPsiMethod.parameterList.parameters[indexInCurrentPsiMethod++].type
else
PsiType.VOID
val defaultValue = info.defaultValueForCall ?: info.defaultValue
ParameterInfoImpl(javaOldIndex, info.name, type, defaultValue?.text ?: "")
}
}
fun createJavaChangeInfoForFunctionOrGetter(
originalPsiMethod: PsiMethod,
currentPsiMethod: PsiMethod,
isGetter: Boolean
): JavaChangeInfo? {
val newParameterList = listOfNotNull(receiverParameterInfo) + getNonReceiverParameters()
val newJavaParameters = getJavaParameterInfos(originalPsiMethod, currentPsiMethod, newParameterList).toTypedArray()
val newName = if (isGetter) JvmAbi.getterName(newName) else newName
return createJavaChangeInfo(originalPsiMethod, currentPsiMethod, newName, currentPsiMethod.returnType, newJavaParameters)
}
fun createJavaChangeInfoForSetter(originalPsiMethod: PsiMethod, currentPsiMethod: PsiMethod): JavaChangeInfo? {
val newJavaParameters = getJavaParameterInfos(originalPsiMethod, currentPsiMethod, listOfNotNull(receiverParameterInfo))
val oldIndex = if (methodDescriptor.receiver != null) 1 else 0
val parameters = currentPsiMethod.parameterList.parameters
if (isPrimaryMethodUpdated) {
val newIndex = if (receiverParameterInfo != null) 1 else 0
val setterParameter = parameters[newIndex]
newJavaParameters.add(ParameterInfoImpl(oldIndex, setterParameter.name, setterParameter.type))
} else {
if (receiverParameterInfo != null) {
if (newJavaParameters.isEmpty()) {
newJavaParameters.add(ParameterInfoImpl(oldIndex, "receiver", PsiType.VOID))
}
}
if (oldIndex < parameters.size) {
val setterParameter = parameters[oldIndex]
newJavaParameters.add(ParameterInfoImpl(oldIndex, setterParameter.name, setterParameter.type))
}
}
val newName = JvmAbi.setterName(newName)
return createJavaChangeInfo(originalPsiMethod, currentPsiMethod, newName, PsiType.VOID, newJavaParameters.toTypedArray())
}
if (!TargetPlatformDetector.getPlatform(method.containingFile as KtFile).isJvm()) return null
if (javaChangeInfos == null) {
val method = method
originalToCurrentMethods = matchOriginalAndCurrentMethods(method.toLightMethods())
javaChangeInfos = originalToCurrentMethods.entries.mapNotNull {
val (originalPsiMethod, currentPsiMethod) = it
when (method) {
is KtFunction, is KtClassOrObject ->
createJavaChangeInfoForFunctionOrGetter(originalPsiMethod, currentPsiMethod, false)
is KtProperty, is KtParameter -> {
val accessorName = originalPsiMethod.name
when {
JvmAbi.isGetterName(accessorName) ->
createJavaChangeInfoForFunctionOrGetter(originalPsiMethod, currentPsiMethod, true)
JvmAbi.isSetterName(accessorName) ->
createJavaChangeInfoForSetter(originalPsiMethod, currentPsiMethod)
else -> null
}
}
else -> null
}
}
}
return javaChangeInfos
}
}
val KotlinChangeInfo.originalBaseFunctionDescriptor: CallableDescriptor
get() = methodDescriptor.baseDescriptor
val KotlinChangeInfo.kind: Kind get() = methodDescriptor.kind
val KotlinChangeInfo.oldName: String?
get() = (methodDescriptor.method as? KtFunction)?.name
fun KotlinChangeInfo.getAffectedCallables(): Collection<UsageInfo> = methodDescriptor.affectedCallables + propagationTargetUsageInfos
fun ChangeInfo.toJetChangeInfo(
originalChangeSignatureDescriptor: KotlinMethodDescriptor,
resolutionFacade: ResolutionFacade
): KotlinChangeInfo {
val method = method as PsiMethod
val functionDescriptor = method.getJavaOrKotlinMemberDescriptor(resolutionFacade) as CallableDescriptor
val parameterDescriptors = functionDescriptor.valueParameters
//noinspection ConstantConditions
val originalParameterDescriptors = originalChangeSignatureDescriptor.baseDescriptor.valueParameters
val newParameters = newParameters.withIndex().map { pair ->
val (i, info) = pair
val oldIndex = info.oldIndex
val currentType = parameterDescriptors[i].type
val defaultValueText = info.defaultValue
val defaultValueExpr =
when {
info is KotlinAwareJavaParameterInfoImpl -> info.kotlinDefaultValue
language.`is`(JavaLanguage.INSTANCE) && !defaultValueText.isNullOrEmpty() -> {
PsiElementFactory.getInstance(method.project).createExpressionFromText(defaultValueText, null).j2k()
}
else -> null
}
val parameterType = if (oldIndex >= 0) originalParameterDescriptors[oldIndex].type else currentType
val originalKtParameter = originalParameterDescriptors.getOrNull(oldIndex)?.source?.getPsi() as? KtParameter
val valOrVar = originalKtParameter?.valOrVarKeyword?.toValVar() ?: KotlinValVar.None
KotlinParameterInfo(
callableDescriptor = functionDescriptor,
originalIndex = oldIndex,
name = info.name,
originalTypeInfo = KotlinTypeInfo(false, parameterType),
defaultValueForCall = defaultValueExpr,
valOrVar = valOrVar
).apply {
currentTypeInfo = KotlinTypeInfo(false, currentType)
}
}
return KotlinChangeInfo(
originalChangeSignatureDescriptor,
newName,
KotlinTypeInfo(true, functionDescriptor.returnType),
functionDescriptor.visibility,
newParameters,
null,
method
)
}
| apache-2.0 | a78457c98ad5705a99b2aa62fae8b7a1 | 43.426471 | 171 | 0.670124 | 6.246037 | false | false | false | false |
K0zka/kerub | src/test/kotlin/com/github/kerubistan/kerub/utils/junix/mpstat/MPStatTest.kt | 2 | 1722 | package com.github.kerubistan.kerub.utils.junix.mpstat
import com.github.kerubistan.kerub.model.dynamic.CpuStat
import com.github.kerubistan.kerub.sshtestutils.mockProcess
import com.nhaarman.mockito_kotlin.mock
import org.apache.sshd.client.session.ClientSession
import org.junit.Assert
import org.junit.Test
class MPStatTest {
private val testInput = """Linux 4.1.6-201.fc22.x86_64 (localshot) 11/02/2015 _x86_64_ (2 CPU)
07:11:03 AM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle
07:11:04 AM all 10.88 0.00 8.81 0.00 0.00 0.52 0.00 0.00 0.00 79.79
07:11:04 AM 0 13.27 0.00 11.22 0.00 0.00 1.02 0.00 0.00 0.00 74.49
07:11:04 AM 1 9.28 0.00 6.19 0.00 0.00 0.00 0.00 0.00 0.00 84.54
07:11:04 AM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle
07:11:05 AM all 31.79 0.00 6.67 0.00 0.00 0.00 0.00 0.00 0.00 61.54
07:11:05 AM 0 32.99 0.00 8.25 0.00 0.00 0.00 0.00 0.00 0.00 58.76
07:11:05 AM 1 30.61 0.00 6.12 0.00 0.00 0.00 0.00 0.00 0.00 63.27
"""
val session : ClientSession = mock()
@Test
fun monitor() {
session.mockProcess("mpstat.*".toRegex(), output = testInput)
var stat = listOf<CpuStat>()
MPStat.monitor(session, { stat += it } , interval = 1)
Assert.assertEquals(0, stat[0].cpuNr)
Assert.assertEquals(13.27, stat[0].user.toDouble(), 0.1)
Assert.assertEquals(11.22, stat[0].system.toDouble(), 0.1)
Assert.assertEquals(74.49, stat[0].idle.toDouble(), 0.1)
Assert.assertEquals(0.toDouble(), stat[0].ioWait.toDouble(), 0.1)
}
} | apache-2.0 | 82d7db1fbc49b67c9415a0f81c85b9f2 | 41.02439 | 97 | 0.607433 | 2.470588 | false | true | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/badges/gifts/flow/GiftFlowViewModel.kt | 1 | 4618 | package org.thoughtcrime.securesms.badges.gifts.flow
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.kotlin.plusAssign
import io.reactivex.rxjava3.kotlin.subscribeBy
import io.reactivex.rxjava3.subjects.PublishSubject
import org.signal.core.util.logging.Log
import org.signal.core.util.money.FiatMoney
import org.thoughtcrime.securesms.badges.models.Badge
import org.thoughtcrime.securesms.components.settings.app.subscription.DonationEvent
import org.thoughtcrime.securesms.contacts.paged.ContactSearchKey
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.util.InternetConnectionObserver
import org.thoughtcrime.securesms.util.rx.RxStore
import java.util.Currency
/**
* Maintains state as a user works their way through the gift flow.
*/
class GiftFlowViewModel(
private val giftFlowRepository: GiftFlowRepository
) : ViewModel() {
private val store = RxStore(
GiftFlowState(
currency = SignalStore.donationsValues().getOneTimeCurrency()
)
)
private val disposables = CompositeDisposable()
private val eventPublisher: PublishSubject<DonationEvent> = PublishSubject.create()
private val networkDisposable: Disposable
val state: Flowable<GiftFlowState> = store.stateFlowable
val events: Observable<DonationEvent> = eventPublisher
val snapshot: GiftFlowState get() = store.state
init {
refresh()
networkDisposable = InternetConnectionObserver
.observe()
.distinctUntilChanged()
.subscribe { isConnected ->
if (isConnected) {
retry()
}
}
}
fun retry() {
if (!disposables.isDisposed && store.state.stage == GiftFlowState.Stage.FAILURE) {
store.update { it.copy(stage = GiftFlowState.Stage.INIT) }
refresh()
}
}
fun refresh() {
disposables.clear()
disposables += SignalStore.donationsValues().observableOneTimeCurrency.subscribe { currency ->
store.update {
it.copy(
currency = currency
)
}
}
disposables += giftFlowRepository.getGiftPricing().subscribe { giftPrices ->
store.update {
it.copy(
giftPrices = giftPrices,
stage = getLoadState(it, giftPrices = giftPrices)
)
}
}
disposables += giftFlowRepository.getGiftBadge().subscribeBy(
onSuccess = { (giftLevel, giftBadge) ->
store.update {
it.copy(
giftLevel = giftLevel,
giftBadge = giftBadge,
stage = getLoadState(it, giftBadge = giftBadge)
)
}
},
onError = { throwable ->
Log.w(TAG, "Could not load gift badge", throwable)
store.update {
it.copy(
stage = GiftFlowState.Stage.FAILURE
)
}
}
)
}
override fun onCleared() {
disposables.clear()
}
fun setSelectedContact(selectedContact: ContactSearchKey.RecipientSearchKey) {
store.update {
it.copy(recipient = Recipient.resolved(selectedContact.recipientId))
}
}
fun getSupportedCurrencyCodes(): List<String> {
return store.state.giftPrices.keys.map { it.currencyCode }
}
private fun getLoadState(
oldState: GiftFlowState,
giftPrices: Map<Currency, FiatMoney>? = null,
giftBadge: Badge? = null,
): GiftFlowState.Stage {
if (oldState.stage != GiftFlowState.Stage.INIT) {
return oldState.stage
}
if (giftPrices?.isNotEmpty() == true) {
return if (oldState.giftBadge != null) {
GiftFlowState.Stage.READY
} else {
GiftFlowState.Stage.INIT
}
}
if (giftBadge != null) {
return if (oldState.giftPrices.isNotEmpty()) {
GiftFlowState.Stage.READY
} else {
GiftFlowState.Stage.INIT
}
}
return GiftFlowState.Stage.INIT
}
fun setAdditionalMessage(additionalMessage: CharSequence) {
store.update { it.copy(additionalMessage = additionalMessage) }
}
companion object {
private val TAG = Log.tag(GiftFlowViewModel::class.java)
}
class Factory(
private val repository: GiftFlowRepository
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return modelClass.cast(
GiftFlowViewModel(
repository
)
) as T
}
}
}
| gpl-3.0 | de8a528836e154ec70566e1551968d39 | 27.158537 | 98 | 0.685362 | 4.381404 | false | false | false | false |
androidx/androidx | camera/camera-core/src/test/java/androidx/camera/core/imagecapture/FakeTakePictureRequest.kt | 3 | 3752 | /*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.core.imagecapture
import android.graphics.Matrix
import android.graphics.Rect
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCapture.OnImageCapturedCallback
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.ImageProxy
import androidx.camera.core.imagecapture.Utils.JPEG_QUALITY
import androidx.camera.core.imagecapture.Utils.ROTATION_DEGREES
import androidx.camera.core.impl.CameraCaptureCallback
import androidx.camera.core.impl.utils.executor.CameraXExecutors.mainThreadExecutor
import java.util.concurrent.Executor
/**
* Fake [TakePictureRequest].
*/
class FakeTakePictureRequest() : TakePictureRequest() {
var imageCapturedCallback: OnImageCapturedCallback? = null
var onImageSavedCallback: ImageCapture.OnImageSavedCallback? = null
var fileOptions: ImageCapture.OutputFileOptions? = null
var exceptionReceived: ImageCaptureException? = null
var imageReceived: ImageProxy? = null
var fileReceived: ImageCapture.OutputFileResults? = null
constructor(type: Type) : this() {
when (type) {
Type.IN_MEMORY -> {
imageCapturedCallback = object : OnImageCapturedCallback() {
override fun onCaptureSuccess(image: ImageProxy) {
imageReceived = image
}
override fun onError(exception: ImageCaptureException) {
exceptionReceived = exception
}
}
}
Type.ON_DISK -> {
onImageSavedCallback = object : ImageCapture.OnImageSavedCallback {
override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
fileReceived = outputFileResults
}
override fun onError(exception: ImageCaptureException) {
exceptionReceived = exception
}
}
}
}
}
override fun getAppExecutor(): Executor {
return mainThreadExecutor()
}
override fun getInMemoryCallback(): OnImageCapturedCallback? {
return imageCapturedCallback
}
override fun getOnDiskCallback(): ImageCapture.OnImageSavedCallback? {
return onImageSavedCallback
}
override fun getOutputFileOptions(): ImageCapture.OutputFileOptions? {
return fileOptions
}
internal override fun getCropRect(): Rect {
return Rect(0, 0, 640, 480)
}
internal override fun getSensorToBufferTransform(): Matrix {
return Matrix()
}
internal override fun getRotationDegrees(): Int {
return ROTATION_DEGREES
}
internal override fun getJpegQuality(): Int {
return JPEG_QUALITY
}
internal override fun getCaptureMode(): Int {
return ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY
}
override fun getSessionConfigCameraCaptureCallbacks(): MutableList<CameraCaptureCallback> {
return arrayListOf()
}
enum class Type {
IN_MEMORY, ON_DISK
}
} | apache-2.0 | 1162e7e3666736f36e08924d32f55c75 | 32.212389 | 98 | 0.674574 | 5.262272 | false | false | false | false |
androidx/androidx | compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/fancy/FlingGameDemo.kt | 3 | 4479 | /*
* 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.animation.demos.fancy
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationEndReason
import androidx.compose.animation.core.VectorConverter
import androidx.compose.animation.core.exponentialDecay
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.drag
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChange
import androidx.compose.ui.input.pointer.util.VelocityTracker
import androidx.compose.ui.tooling.preview.Preview
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
@Preview
@Composable
fun FlingGameDemo() {
Box(Modifier.fillMaxSize()) {
Text("Throw me around, see what happens", Modifier.align(Alignment.Center))
val anim = remember { Animatable(Offset(100f, 100f), Offset.VectorConverter) }
Box(
Modifier.fillMaxSize().pointerInput(Unit) {
coroutineScope {
while (true) {
val velocityTracker = VelocityTracker()
awaitPointerEventScope {
val pointerId = awaitFirstDown().run {
launch {
anim.snapTo(position)
}
id
}
drag(pointerId) {
launch {
anim.snapTo(anim.value + it.positionChange())
}
velocityTracker.addPosition(
it.uptimeMillis,
it.position
)
}
}
val (x, y) = velocityTracker.calculateVelocity()
anim.updateBounds(
Offset(100f, 100f),
Offset(size.width.toFloat() - 100f, size.height.toFloat() - 100f)
)
launch {
var startVelocity = Offset(x, y)
do {
val result = anim.animateDecay(startVelocity, exponentialDecay())
startVelocity = result.endState.velocity
with(anim) {
if (value.x == upperBound?.x || value.x == lowerBound?.x) {
// x dimension hits bounds
startVelocity = startVelocity.copy(x = -startVelocity.x)
}
if (value.y == upperBound?.y || value.y == lowerBound?.y) {
// y dimension hits bounds
startVelocity = startVelocity.copy(y = -startVelocity.y)
}
}
} while (result.endReason == AnimationEndReason.BoundReached)
}
}
}
}.drawWithContent {
drawCircle(Color(0xff3c1361), 100f, anim.value)
}
)
}
}
| apache-2.0 | 535f0bb4f3ba5bceb77f64b8f347b139 | 42.911765 | 97 | 0.539853 | 5.570896 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/layout/BeyondBoundsLayout.kt | 3 | 4961 | /*
* 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
*
* 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.ui.layout
import androidx.compose.ui.modifier.ProvidableModifierLocal
import androidx.compose.ui.modifier.modifierLocalOf
import kotlin.jvm.JvmInline
/**
* A modifier local that provides access to a [BeyondBoundsLayout] that a child can use to
* ask a parent to layout more items that are beyond its visible bounds.
*/
val ModifierLocalBeyondBoundsLayout: ProvidableModifierLocal<BeyondBoundsLayout?> =
modifierLocalOf { null }
/**
* Layout extra items in the specified direction.
*
* A [BeyondBoundsLayout] instance can be obtained by consuming the
* [BeyondBoundsLayout modifier local][ModifierLocalBeyondBoundsLayout].
* It can be used to send a request to layout more items in a particular
* [direction][LayoutDirection]. This can be useful when composition or layout is determined lazily,
* as with a LazyColumn. The request is received by any parent up the hierarchy that provides this
* modifier local.
*/
interface BeyondBoundsLayout {
/**
* Send a request to layout more items in the specified
* [direction][LayoutDirection]. The request is received by a parent up the
* hierarchy. The parent adds one item at a time and calls [block] after each item is added.
* The parent continues adding new items as long as [block] returns null. Once you have all
* the items you need, you can perform some operation and return a non-null value. Returning
* this value stops the laying out of beyond bounds items. (Note that you have to return a
* non-null value stop iterating).
*
* @param direction The direction from the visible bounds in which more items are requested.
* @param block Continue to layout more items until this block returns a non null item.
* @return The value returned by the last run of [block]. If we layout all the available
* items then the returned value is null. When this function returns all the beyond bounds items
* may be disposed. Therefore you have to perform any custom logic within the [block] and return
* the value you need.
*/
fun <T> layout(
direction: LayoutDirection,
block: BeyondBoundsScope.() -> T?
): T?
/**
* The scope used in [BeyondBoundsLayout.layout].
*/
interface BeyondBoundsScope {
/**
* Whether we have more content to lay out in the specified direction.
*/
val hasMoreContent: Boolean
}
/**
* The direction (from the visible bounds) that a [BeyondBoundsLayout] is requesting more items
* to be laid.
*/
@JvmInline
value class LayoutDirection internal constructor(
@Suppress("unused") private val value: Int
) {
companion object {
/**
* Direction used in [BeyondBoundsLayout.layout] to request the layout of extra items
* before the current bounds.
*/
val Before = LayoutDirection(1)
/**
* Direction used in [BeyondBoundsLayout.layout] to request the layout of extra items
* after the current bounds.
*/
val After = LayoutDirection(2)
/**
* Direction used in [BeyondBoundsLayout.layout] to request the layout of extra items
* to the left of the current bounds.
*/
val Left = LayoutDirection(3)
/**
* Direction used in [BeyondBoundsLayout.layout] to request the layout of extra items
* to the right of the current bounds.
*/
val Right = LayoutDirection(4)
/**
* Direction used in [BeyondBoundsLayout.layout] to request the layout of extra items
* above the current bounds.
*/
val Above = LayoutDirection(5)
/**
* Direction used in [BeyondBoundsLayout.layout] to request the layout of extra items
* below the current bounds.
*/
val Below = LayoutDirection(6)
}
override fun toString(): String = when (this) {
Before -> "Before"
After -> "After"
Left -> "Left"
Right -> "Right"
Above -> "Above"
Below -> "Below"
else -> "invalid LayoutDirection"
}
}
}
| apache-2.0 | 9eca45d4ab047330851a2274bbc8e9e2 | 39.333333 | 100 | 0.649466 | 4.956044 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsProcessor.kt | 4 | 19751 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations
import com.intellij.ide.IdeDeprecatedMessagesBundle
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.ide.util.EditorHelper
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.refactoring.move.MoveCallback
import com.intellij.refactoring.move.MoveMultipleElementsViewDescriptor
import com.intellij.refactoring.move.moveClassesOrPackages.MoveClassHandler
import com.intellij.refactoring.rename.RenameUtil
import com.intellij.refactoring.util.NonCodeUsageInfo
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.refactoring.util.TextOccurrencesUtil
import com.intellij.usageView.UsageInfo
import com.intellij.usageView.UsageViewDescriptor
import com.intellij.usageView.UsageViewUtil
import com.intellij.util.IncorrectOperationException
import com.intellij.util.containers.CollectionFactory
import com.intellij.util.containers.HashingStrategy
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration
import org.jetbrains.kotlin.asJava.findFacadeClass
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.asJava.toLightElements
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.idea.base.util.quoteIfNeeded
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.idea.base.util.projectScope
import org.jetbrains.kotlin.idea.base.util.restrictByFileType
import org.jetbrains.kotlin.idea.codeInsight.shorten.addToBeShortenedDescendantsToWaitingSet
import org.jetbrains.kotlin.idea.codeInsight.shorten.performDelayedRefactoringRequests
import org.jetbrains.kotlin.idea.core.deleteSingle
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesHandlerFactory
import org.jetbrains.kotlin.idea.refactoring.broadcastRefactoringExit
import org.jetbrains.kotlin.idea.refactoring.move.*
import org.jetbrains.kotlin.idea.refactoring.move.moveFilesOrDirectories.MoveKotlinClassHandler
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.utils.ifEmpty
import org.jetbrains.kotlin.utils.keysToMap
import kotlin.math.max
import kotlin.math.min
interface Mover : (KtNamedDeclaration, KtElement) -> KtNamedDeclaration {
object Default : Mover {
override fun invoke(originalElement: KtNamedDeclaration, targetContainer: KtElement): KtNamedDeclaration {
return when (targetContainer) {
is KtFile -> {
val declarationContainer: KtElement =
if (targetContainer.isScript()) targetContainer.script!!.blockExpression else targetContainer
declarationContainer.add(originalElement) as KtNamedDeclaration
}
is KtClassOrObject -> targetContainer.addDeclaration(originalElement)
else -> error("Unexpected element: ${targetContainer.getElementTextWithContext()}")
}.apply {
val container = originalElement.containingClassOrObject
if (container is KtObjectDeclaration &&
container.isCompanion() &&
container.declarations.singleOrNull() == originalElement &&
KotlinFindUsagesHandlerFactory(container.project).createFindUsagesHandler(container, false)
.findReferencesToHighlight(container, LocalSearchScope(container.containingFile)).isEmpty()
) {
container.deleteSingle()
} else {
originalElement.deleteSingle()
}
}
}
}
}
sealed class MoveSource {
abstract val elementsToMove: Collection<KtNamedDeclaration>
class Elements(override val elementsToMove: Collection<KtNamedDeclaration>) : MoveSource()
class File(val file: KtFile) : MoveSource() {
override val elementsToMove: Collection<KtNamedDeclaration>
get() = file.declarations.filterIsInstance<KtNamedDeclaration>()
}
}
fun MoveSource(declaration: KtNamedDeclaration) = MoveSource.Elements(listOf(declaration))
fun MoveSource(declarations: Collection<KtNamedDeclaration>) = MoveSource.Elements(declarations)
fun MoveSource(file: KtFile) = MoveSource.File(file)
class MoveDeclarationsDescriptor @JvmOverloads constructor(
val project: Project,
val moveSource: MoveSource,
val moveTarget: KotlinMoveTarget,
val delegate: MoveDeclarationsDelegate,
val searchInCommentsAndStrings: Boolean = true,
val searchInNonCode: Boolean = true,
val deleteSourceFiles: Boolean = false,
val moveCallback: MoveCallback? = null,
val openInEditor: Boolean = false,
val allElementsToMove: List<PsiElement>? = null,
val analyzeConflicts: Boolean = true,
val searchReferences: Boolean = true
)
class ConflictUsageInfo(element: PsiElement, val messages: Collection<String>) : UsageInfo(element)
private object ElementHashingStrategy : HashingStrategy<PsiElement> {
override fun equals(e1: PsiElement?, e2: PsiElement?): Boolean {
if (e1 === e2) return true
// Name should be enough to distinguish different light elements based on the same original declaration
if (e1 is KtLightDeclaration<*, *> && e2 is KtLightDeclaration<*, *>) {
return e1.kotlinOrigin == e2.kotlinOrigin && e1.name == e2.name
}
return false
}
override fun hashCode(e: PsiElement?): Int {
return when (e) {
null -> 0
is KtLightDeclaration<*, *> -> (e.kotlinOrigin?.hashCode() ?: 0) * 31 + (e.name?.hashCode() ?: 0)
else -> e.hashCode()
}
}
}
class MoveKotlinDeclarationsProcessor(
val descriptor: MoveDeclarationsDescriptor,
val mover: Mover = Mover.Default,
private val throwOnConflicts: Boolean = false
) : BaseRefactoringProcessor(descriptor.project) {
companion object {
const val REFACTORING_ID = "move.kotlin.declarations"
}
val project get() = descriptor.project
private var nonCodeUsages: Array<NonCodeUsageInfo>? = null
private val moveEntireFile = descriptor.moveSource is MoveSource.File
private val elementsToMove = descriptor.moveSource.elementsToMove.filter { e ->
e.parent != descriptor.moveTarget.getTargetPsiIfExists(e)
}
private val kotlinToLightElementsBySourceFile = elementsToMove
.groupBy { it.containingKtFile }
.mapValues { it.value.keysToMap { declaration -> declaration.toLightElements().ifEmpty { listOf(declaration) } } }
private val conflicts = MultiMap<PsiElement, String>()
override fun getRefactoringId() = REFACTORING_ID
override fun createUsageViewDescriptor(usages: Array<out UsageInfo>): UsageViewDescriptor {
val targetContainerFqName = descriptor.moveTarget.targetContainerFqName?.let {
if (it.isRoot) IdeDeprecatedMessagesBundle.message("default.package.presentable.name") else it.asString()
} ?: IdeDeprecatedMessagesBundle.message("default.package.presentable.name")
return MoveMultipleElementsViewDescriptor(elementsToMove.toTypedArray(), targetContainerFqName)
}
fun getConflictsAsUsages(): List<UsageInfo> = conflicts.entrySet().map { ConflictUsageInfo(it.key, it.value) }
public override fun findUsages(): Array<UsageInfo> {
if (!descriptor.searchReferences || elementsToMove.isEmpty()) return UsageInfo.EMPTY_ARRAY
val newContainerName = descriptor.moveTarget.targetContainerFqName?.asString() ?: ""
fun getSearchScope(element: PsiElement): GlobalSearchScope? {
val projectScope = project.projectScope()
val ktDeclaration = element.namedUnwrappedElement as? KtNamedDeclaration ?: return projectScope
if (ktDeclaration.hasModifier(KtTokens.PRIVATE_KEYWORD)) return projectScope
val moveTarget = descriptor.moveTarget
val (oldContainer, newContainer) = descriptor.delegate.getContainerChangeInfo(ktDeclaration, moveTarget)
val targetModule = moveTarget.getTargetModule(project) ?: return projectScope
if (oldContainer != newContainer || ktDeclaration.module != targetModule) return projectScope
// Check if facade class may change
if (newContainer is ContainerInfo.Package) {
val javaScope = projectScope.restrictByFileType(JavaFileType.INSTANCE)
val currentFile = ktDeclaration.containingKtFile
val newFile = when (moveTarget) {
is KotlinMoveTargetForExistingElement -> moveTarget.targetElement as? KtFile ?: return null
is KotlinMoveTargetForDeferredFile -> return javaScope
else -> return null
}
val currentFacade = currentFile.findFacadeClass()
val newFacade = newFile.findFacadeClass()
return if (currentFacade?.qualifiedName != newFacade?.qualifiedName) javaScope else null
}
return null
}
fun UsageInfo.intersectsWith(usage: UsageInfo): Boolean {
if (element?.containingFile != usage.element?.containingFile) return false
val firstSegment = segment ?: return false
val secondSegment = usage.segment ?: return false
return max(firstSegment.startOffset, secondSegment.startOffset) <= min(firstSegment.endOffset, secondSegment.endOffset)
}
fun collectUsages(kotlinToLightElements: Map<KtNamedDeclaration, List<PsiNamedElement>>, result: MutableCollection<UsageInfo>) {
kotlinToLightElements.values.flatten().flatMapTo(result) { lightElement ->
val searchScope = getSearchScope(lightElement) ?: return@flatMapTo emptyList()
val elementName = lightElement.name ?: return@flatMapTo emptyList()
val newFqName = StringUtil.getQualifiedName(newContainerName, elementName)
val foundReferences = HashSet<PsiReference>()
val results = ReferencesSearch
.search(lightElement, searchScope)
.mapNotNullTo(ArrayList()) { ref ->
if (foundReferences.add(ref) && elementsToMove.none { it.isAncestor(ref.element) }) {
createMoveUsageInfoIfPossible(ref, lightElement, addImportToOriginalFile = true, isInternal = false)
} else null
}
val name = lightElement.kotlinFqName?.quoteIfNeeded()?.asString()
if (name != null) {
fun searchForKotlinNameUsages(results: ArrayList<UsageInfo>) {
TextOccurrencesUtil.findNonCodeUsages(
lightElement,
searchScope,
name,
descriptor.searchInCommentsAndStrings,
descriptor.searchInNonCode,
FqName(newFqName).quoteIfNeeded().asString(),
results
)
}
val facadeContainer = lightElement.parent as? KtLightClassForFacade
if (facadeContainer != null) {
val oldFqNameWithFacade = StringUtil.getQualifiedName(facadeContainer.qualifiedName, elementName)
val newFqNameWithFacade = StringUtil.getQualifiedName(
StringUtil.getQualifiedName(newContainerName, facadeContainer.name),
elementName
)
TextOccurrencesUtil.findNonCodeUsages(
lightElement,
searchScope,
oldFqNameWithFacade,
descriptor.searchInCommentsAndStrings,
descriptor.searchInNonCode,
FqName(newFqNameWithFacade).quoteIfNeeded().asString(),
results
)
ArrayList<UsageInfo>().also { searchForKotlinNameUsages(it) }.forEach { kotlinNonCodeUsage ->
if (results.none { it.intersectsWith(kotlinNonCodeUsage) }) {
results.add(kotlinNonCodeUsage)
}
}
} else {
searchForKotlinNameUsages(results)
}
}
MoveClassHandler.EP_NAME.extensions.filter { it !is MoveKotlinClassHandler }.forEach { handler ->
handler.preprocessUsages(results)
}
results
}
}
val usages = ArrayList<UsageInfo>()
val conflictChecker = MoveConflictChecker(
project,
elementsToMove,
descriptor.moveTarget,
elementsToMove.first(),
allElementsToMove = descriptor.allElementsToMove
)
for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) {
val internalUsages = LinkedHashSet<UsageInfo>()
val externalUsages = LinkedHashSet<UsageInfo>()
if (moveEntireFile) {
val changeInfo = ContainerChangeInfo(
ContainerInfo.Package(sourceFile.packageFqName),
descriptor.moveTarget.targetContainerFqName?.let { ContainerInfo.Package(it) } ?: ContainerInfo.UnknownPackage
)
internalUsages += sourceFile.getInternalReferencesToUpdateOnPackageNameChange(changeInfo)
} else {
kotlinToLightElements.keys.forEach {
val packageNameInfo = descriptor.delegate.getContainerChangeInfo(it, descriptor.moveTarget)
internalUsages += it.getInternalReferencesToUpdateOnPackageNameChange(packageNameInfo)
}
}
internalUsages += descriptor.delegate.findInternalUsages(descriptor)
collectUsages(kotlinToLightElements, externalUsages)
if (descriptor.analyzeConflicts) {
conflictChecker.checkAllConflicts(externalUsages, internalUsages, conflicts)
descriptor.delegate.collectConflicts(descriptor, internalUsages, conflicts)
}
usages += internalUsages
usages += externalUsages
}
return UsageViewUtil.removeDuplicatedUsages(usages.toTypedArray())
}
override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean {
return showConflicts(conflicts, refUsages.get())
}
override fun showConflicts(conflicts: MultiMap<PsiElement, String>, usages: Array<out UsageInfo>?): Boolean {
if (throwOnConflicts && !conflicts.isEmpty) throw RefactoringConflictsFoundException()
return super.showConflicts(conflicts, usages)
}
override fun performRefactoring(usages: Array<out UsageInfo>) = doPerformRefactoring(usages.toList())
internal fun doPerformRefactoring(usages: List<UsageInfo>) {
fun moveDeclaration(declaration: KtNamedDeclaration, moveTarget: KotlinMoveTarget): KtNamedDeclaration {
val targetContainer = moveTarget.getOrCreateTargetPsi(declaration)
descriptor.delegate.preprocessDeclaration(descriptor, declaration)
if (moveEntireFile) return declaration
return mover(declaration, targetContainer).apply {
addToBeShortenedDescendantsToWaitingSet()
}
}
val (oldInternalUsages, externalUsages) = usages.partition { it is KotlinMoveUsage && it.isInternal }
val newInternalUsages = ArrayList<UsageInfo>()
markInternalUsages(oldInternalUsages)
val usagesToProcess = ArrayList(externalUsages)
try {
descriptor.delegate.preprocessUsages(descriptor, usages)
val oldToNewElementsMapping = CollectionFactory.createCustomHashingStrategyMap<PsiElement, PsiElement>(ElementHashingStrategy)
val newDeclarations = ArrayList<KtNamedDeclaration>()
for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) {
for ((oldDeclaration, oldLightElements) in kotlinToLightElements) {
val elementListener = transaction?.getElementListener(oldDeclaration)
val newDeclaration = moveDeclaration(oldDeclaration, descriptor.moveTarget)
newDeclarations += newDeclaration
oldToNewElementsMapping[oldDeclaration] = newDeclaration
oldToNewElementsMapping[sourceFile] = newDeclaration.containingKtFile
elementListener?.elementMoved(newDeclaration)
for ((oldElement, newElement) in oldLightElements.asSequence().zip(newDeclaration.toLightElements().asSequence())) {
oldToNewElementsMapping[oldElement] = newElement
}
if (descriptor.openInEditor) {
EditorHelper.openInEditor(newDeclaration)
}
}
if (descriptor.deleteSourceFiles && sourceFile.declarations.isEmpty()) {
sourceFile.delete()
}
}
val internalUsageScopes: List<KtElement> = if (moveEntireFile) {
newDeclarations.asSequence().map { it.containingKtFile }.distinct().toList()
} else {
newDeclarations
}
internalUsageScopes.forEach { newInternalUsages += restoreInternalUsages(it, oldToNewElementsMapping) }
usagesToProcess += newInternalUsages
nonCodeUsages = postProcessMoveUsages(usagesToProcess, oldToNewElementsMapping).toTypedArray()
performDelayedRefactoringRequests(project)
} catch (e: IncorrectOperationException) {
nonCodeUsages = null
RefactoringUIUtil.processIncorrectOperation(myProject, e)
} finally {
cleanUpInternalUsages(newInternalUsages + oldInternalUsages)
}
}
override fun performPsiSpoilingRefactoring() {
nonCodeUsages?.let { nonCodeUsages -> RenameUtil.renameNonCodeUsages(myProject, nonCodeUsages) }
descriptor.moveCallback?.refactoringCompleted()
}
fun execute(usages: List<UsageInfo>) {
execute(usages.toTypedArray())
}
override fun doRun() {
try {
super.doRun()
} finally {
broadcastRefactoringExit(myProject, refactoringId)
}
}
override fun getCommandName(): String = KotlinBundle.message("command.move.declarations")
}
| apache-2.0 | 38a4b35802a2a64777bbf3b5b58c6169 | 47.290954 | 138 | 0.673029 | 5.857355 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis-api-providers-ide-impl/src/org/jetbrains/kotlin/analysis/providers/ide/trackers/KotlinFirOutOfBlockModificationTracker.kt | 1 | 7308 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.analysis.providers.ide.trackers
import com.intellij.ProjectTopics
import com.intellij.lang.ASTNode
import com.intellij.openapi.Disposable
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.pom.PomManager
import com.intellij.pom.PomModelAspect
import com.intellij.pom.event.PomModelEvent
import com.intellij.pom.event.PomModelListener
import com.intellij.pom.tree.TreeAspect
import com.intellij.pom.tree.events.TreeChangeEvent
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.FileElement
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.analysis.low.level.api.fir.element.builder.getNonLocalContainingInBodyDeclarationWith
import org.jetbrains.kotlin.analysis.low.level.api.fir.file.structure.isReanalyzableContainer
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.util.module
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong
internal class KotlinFirModificationTrackerService(project: Project) : Disposable {
init {
PomManager.getModel(project).addModelListener(Listener())
subscribeForRootChanges(project)
}
private val _projectGlobalOutOfBlockInKotlinFilesModificationCount = AtomicLong()
val projectGlobalOutOfBlockInKotlinFilesModificationCount: Long
get() = _projectGlobalOutOfBlockInKotlinFilesModificationCount.get()
fun getOutOfBlockModificationCountForModules(module: Module): Long =
moduleModificationsState.getModificationsCountForModule(module)
private val moduleModificationsState = ModuleModificationsState()
private val treeAspect = TreeAspect.getInstance(project)
override fun dispose() {}
fun increaseModificationCountForAllModules() {
_projectGlobalOutOfBlockInKotlinFilesModificationCount.incrementAndGet()
moduleModificationsState.increaseModificationCountForAllModules()
}
@TestOnly
fun increaseModificationCountForModule(module: Module) {
moduleModificationsState.increaseModificationCountForModule(module)
}
private fun subscribeForRootChanges(project: Project) {
project.messageBus.connect(this).subscribe(
ProjectTopics.PROJECT_ROOTS,
object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) = increaseModificationCountForAllModules()
}
)
}
private inner class Listener : PomModelListener {
override fun isAspectChangeInteresting(aspect: PomModelAspect): Boolean =
treeAspect == aspect
override fun modelChanged(event: PomModelEvent) {
val changeSet = event.getChangeSet(treeAspect) as TreeChangeEvent? ?: return
val psi = changeSet.rootElement.psi
if (psi.language != KotlinLanguage.INSTANCE) return
val changedElements = changeSet.changedElements
handleChangedElementsInAllModules(changedElements, changeSet, psi)
}
private fun handleChangedElementsInAllModules(
changedElements: Array<out ASTNode>,
changeSet: TreeChangeEvent,
changeSetRootElementPsi: PsiElement
) {
if (!changeSetRootElementPsi.isPhysical) {
/**
* Element which do not belong to a project should not cause OOBM
*/
return
}
if (changedElements.isEmpty()) {
incrementModificationCountForFileChange(changeSet)
} else {
incrementModificationCountForSpecificElements(changedElements, changeSet)
}
}
private fun incrementModificationCountForSpecificElements(
changedElements: Array<out ASTNode>,
changeSet: TreeChangeEvent
) {
require(changedElements.isNotEmpty())
var isOutOfBlockChangeInAnyModule = false
changedElements.forEach { element ->
val isOutOfBlock = element.isOutOfBlockChange(changeSet)
isOutOfBlockChangeInAnyModule = isOutOfBlockChangeInAnyModule || isOutOfBlock
if (isOutOfBlock) {
incrementModificationTrackerForContainingModule(element)
}
}
if (isOutOfBlockChangeInAnyModule) {
_projectGlobalOutOfBlockInKotlinFilesModificationCount.incrementAndGet()
}
}
private fun incrementModificationCountForFileChange(changeSet: TreeChangeEvent) {
val fileElement = changeSet.rootElement as FileElement ?: return
incrementModificationTrackerForContainingModule(fileElement)
_projectGlobalOutOfBlockInKotlinFilesModificationCount.incrementAndGet()
}
private fun incrementModificationTrackerForContainingModule(element: ASTNode) {
element.psi.module?.let { module ->
moduleModificationsState.increaseModificationCountForModule(module)
}
}
private fun ASTNode.isOutOfBlockChange(changeSet: TreeChangeEvent): Boolean {
val nodes = changeSet.getChangesByElement(this).affectedChildren
return nodes.any(::isOutOfBlockChange)
}
private fun isOutOfBlockChange(node: ASTNode): Boolean {
val psi = node.psi ?: return true
if (!psi.isValid) {
/**
* If PSI is not valid, well something bad happened, OOBM won't hurt
*/
return true
}
val container = psi.getNonLocalContainingInBodyDeclarationWith() ?: return true
return !isReanalyzableContainer(container)
}
}
}
private class ModuleModificationsState {
private val modificationCountForModule = ConcurrentHashMap<Module, ModuleModifications>()
private val state = AtomicLong()
fun getModificationsCountForModule(module: Module) = modificationCountForModule.compute(module) { _, modifications ->
val currentState = state.get()
when {
modifications == null -> ModuleModifications(0, currentState)
modifications.state == currentState -> modifications
else -> ModuleModifications(modificationsCount = modifications.modificationsCount + 1, state = currentState)
}
}!!.modificationsCount
fun increaseModificationCountForAllModules() {
state.incrementAndGet()
}
fun increaseModificationCountForModule(module: Module) {
modificationCountForModule.compute(module) { _, modifications ->
val currentState = state.get()
when (modifications) {
null -> ModuleModifications(0, currentState)
else -> ModuleModifications(modifications.modificationsCount + 1, currentState)
}
}
}
private data class ModuleModifications(val modificationsCount: Long, val state: Long)
} | apache-2.0 | 284791b2381c21947059a578dbf8ffca | 40.528409 | 158 | 0.700055 | 5.818471 | false | false | false | false |
smmribeiro/intellij-community | java/idea-ui/src/com/intellij/ide/starters/local/GeneratorContext.kt | 9 | 2127 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.starters.local
import com.intellij.openapi.projectRoots.JavaSdkVersion
import com.intellij.openapi.vfs.VirtualFile
internal class GeneratorContext(
val starterId: String,
val moduleName: String,
val group: String,
val artifact: String,
val version: String,
val testRunnerId: String?,
val rootPackage: String,
val sdkVersion: JavaSdkVersion?,
private val languageId: String,
private val libraryIds: Set<String>,
private val dependencyConfig: DependencyConfig,
private val properties: Map<String, String>,
val assets: List<GeneratorAsset>,
val outputDirectory: VirtualFile
) {
fun hasLanguage(languageId: String): Boolean {
return this.languageId == languageId
}
fun hasLibrary(libraryId: String): Boolean {
return libraryIds.contains(libraryId)
}
fun hasAnyLibrary(vararg ids: String): Boolean {
return ids.any { libraryIds.contains(it) }
}
fun hasAllLibraries(vararg ids: String): Boolean {
return ids.all { libraryIds.contains(it) }
}
fun getVersion(group: String, artifact: String): String? {
return dependencyConfig.dependencies.find { it.group == group && it.artifact == artifact }?.version
}
fun getBomProperty(propertyId: String): String? {
return dependencyConfig.properties[propertyId]
}
fun getProperty(propertyId: String): String? {
return properties[propertyId]
}
/**
* Renders propertyId as ${propertyId}.
*/
fun asPlaceholder(propertyId: String): String {
return "\${$propertyId}"
}
fun isSdkAtLeast(version: String): Boolean {
val desiredSdkVersion = JavaSdkVersion.fromVersionString(version)
return desiredSdkVersion != null && sdkVersion != null && sdkVersion.isAtLeast(desiredSdkVersion)
}
val rootPackagePath: String
get() {
return rootPackage.replace(".", "/").removeSuffix("/")
}
val sdkFeatureVersion: Int
get() {
return sdkVersion?.maxLanguageLevel?.toJavaVersion()?.feature ?: 8
}
} | apache-2.0 | aa31351ad1b3e2bf331a905a7b5e847e | 28.555556 | 140 | 0.720733 | 4.496829 | false | true | false | false |
ThatsNoMoon/KDA | src/main/kotlin/com/thatsnomoon/kda/extensions/UserExtensions.kt | 1 | 6386 | /*
* Copyright 2018 Benjamin Scherer
* 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.thatsnomoon.kda.extensions
import kotlinx.coroutines.experimental.Deferred
import net.dv8tion.jda.core.MessageBuilder
import net.dv8tion.jda.core.entities.*
import java.io.File
import java.io.InputStream
import java.time.Duration
/**
* Opens a private channel with this User.
*
* @param delay [Duration] to wait before queueing this action
*
* @return A [Deferred] that resolves to the User's [PrivateChannel]
*/
fun User.getPrivateChannel(delay: Duration = Duration.ZERO): Deferred<PrivateChannel> =
this.openPrivateChannel() after delay
/**
* Sends a message to this User.
*
* @param message Message to send to this User.
* @param delay [Duration] to wait before queueing this action
*
* @return A [Deferred] that resolves to the sent Message
*/
fun User.send(message: Message, delay: Duration = Duration.ZERO): Deferred<Message> =
this.getPrivateChannel() flatMap { it.send(message, delay) }
/**
* Sends a message to this User, using a MessageBuilder to build the message.
*
* @param init Function to call on a MessageBuilder to form a Message to send.
* @param delay [Duration] to wait before queueing this action
*
* @return A [Deferred] that resolves to the sent Message
*/
inline fun User.send(delay: Duration = Duration.ZERO, init: MessageBuilder.() -> Unit): Deferred<Message> {
val builder = MessageBuilder()
builder.init()
return this.getPrivateChannel() flatMap { it.send(builder.build(), delay) }
}
/**
* Sends a message to this User.
*
* @param text Content of the Message to send.
* @param delay [Duration] to wait before queueing this action
*
* @return A [Deferred] that resolves to the sent Message
*/
fun User.send(text: String, delay: Duration = Duration.ZERO): Deferred<Message> =
this.getPrivateChannel() flatMap { it.send(text, delay) }
/**
* Sends an embed to this User.
*
* @param embed MessageEmbed to send
* @param delay [Duration] to wait before queueing this action
*
* @return A [Deferred] that resolves to the sent Message
*/
fun User.send(embed: MessageEmbed, delay: Duration = Duration.ZERO): Deferred<Message> =
this.getPrivateChannel() flatMap { it.send(embed, delay) }
/**
* Sends a message with a file to this User.
*
* @param data File to send
* @param filename Name of the file to send
* @param message Message to send with this file
* @param delay [Duration] to wait before queueing this action
*
* @return A [Deferred] that resolves to the sent Message
*/
fun User.sendWithFile(data: ByteArray, filename: String, message: Message? = null, delay: Duration = Duration.ZERO): Deferred<Message> =
this.getPrivateChannel() flatMap { it.sendWithFile(data, filename, message, delay) }
/**
* Sends a message with a file to this User.
*
* @param data File to send
* @param filename Name of the file to send
* @param init Function to "build" the message to send, i.e. set content and options
* @param delay [Duration] to wait before queueing this action
*
* @return A [Deferred] that resolves to the sent Message
*/
fun User.sendWithFile(data: ByteArray, filename: String, delay: Duration = Duration.ZERO, init: MessageBuilder.() -> Unit): Deferred<Message> {
val builder = MessageBuilder()
builder.init()
return this.getPrivateChannel() flatMap { it.sendWithFile(data, filename, builder.build(), delay) }
}
/**
* Sends a message with a file to this User.
*
* @param file File to send
* @param filename Name of the file to send (default: [file].name)
* @param message Message to send with this file
* @param delay [Duration] to wait before queueing this action
*
* @return A [Deferred] that resolves to the sent Message
*/
fun User.sendWithFile(file: File, filename: String = file.name, message: Message? = null, delay: Duration = Duration.ZERO): Deferred<Message> =
this.getPrivateChannel() flatMap { it.sendWithFile(file, filename, message, delay) }
/**
* Sends a message with a file to this User.
*
* @param file File to send
* @param filename Name of the file to send (default: [file].name)
* @param init Function to "build" the message to send, i.e. set content and options
* @param delay [Duration] to wait before queueing this action
*
* @return A [Deferred] that resolves to the sent Message
*/
fun User.sendWithFile(file: File, filename: String = file.name, delay: Duration = Duration.ZERO, init: MessageBuilder.() -> Unit): Deferred<Message> {
val builder = MessageBuilder()
builder.init()
return this.getPrivateChannel() flatMap { it.sendWithFile(file, filename, builder.build(), delay) }
}
/**
* Sends a message with a file to this User.
*
* @param data File to send
* @param filename Name of the file to send
* @param message Message to send with this file
* @param delay [Duration] to wait before queueing this action
*
* @return A [Deferred] that resolves to the sent Message
*/
fun User.sendWithFile(data: InputStream, filename: String, message: Message? = null, delay: Duration = Duration.ZERO): Deferred<Message> =
this.getPrivateChannel() flatMap { it.sendWithFile(data, filename, message, delay) }
/**
* Sends a message with a file to this User.
*
* @param data File to send
* @param filename Name of the file to send
* @param init Function to "build" the message to send, i.e. set content and options
* @param delay [Duration] to wait before queueing this action
*
* @return A [Deferred] that resolves to the sent Message
*/
fun User.sendWithFile(data: InputStream, filename: String, delay: Duration = Duration.ZERO, init: MessageBuilder.() -> Unit): Deferred<Message> {
val builder = MessageBuilder()
builder.init()
return this.getPrivateChannel() flatMap { it.sendWithFile(data, filename, builder.build(), delay) }
}
| apache-2.0 | 83b3ca7b48c60f97cf1506578028a9b8 | 37.011905 | 150 | 0.717507 | 3.875 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpData.kt | 1 | 3922 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.pullUp
import com.intellij.psi.PsiNamedElement
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KtPsiClassWrapper
import org.jetbrains.kotlin.idea.refactoring.memberInfo.getClassDescriptorIfAny
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.utils.collectDescriptorsFiltered
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.substitutions.getTypeSubstitution
import org.jetbrains.kotlin.utils.keysToMapExceptNulls
class KotlinPullUpData(
val sourceClass: KtClassOrObject,
val targetClass: PsiNamedElement,
val membersToMove: Collection<KtNamedDeclaration>
) {
val resolutionFacade = sourceClass.getResolutionFacade()
val sourceClassContext = resolutionFacade.analyzeWithAllCompilerChecks(sourceClass).bindingContext
val sourceClassDescriptor = sourceClassContext[BindingContext.DECLARATION_TO_DESCRIPTOR, sourceClass] as ClassDescriptor
val memberDescriptors = membersToMove.keysToMapExceptNulls {
when (it) {
is KtPsiClassWrapper -> it.psiClass.getJavaClassDescriptor(resolutionFacade)
is KtParameter -> sourceClassContext[BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, it]
else -> sourceClassContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it]
}
}
val targetClassDescriptor = targetClass.getClassDescriptorIfAny(resolutionFacade)!!
val superEntryForTargetClass = sourceClass.getSuperTypeEntryByDescriptor(targetClassDescriptor, sourceClassContext)
val targetClassSuperResolvedCall = superEntryForTargetClass.getResolvedCall(sourceClassContext)
private val typeParametersInSourceClassContext by lazy {
sourceClassDescriptor.declaredTypeParameters + sourceClass.getResolutionScope(sourceClassContext, resolutionFacade)
.collectDescriptorsFiltered(DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS)
.filterIsInstance<TypeParameterDescriptor>()
}
val sourceToTargetClassSubstitutor: TypeSubstitutor by lazy {
val substitution = LinkedHashMap<TypeConstructor, TypeProjection>()
typeParametersInSourceClassContext.forEach {
substitution[it.typeConstructor] = TypeProjectionImpl(TypeIntersector.getUpperBoundsAsType(it))
}
val superClassSubstitution = getTypeSubstitution(targetClassDescriptor.defaultType, sourceClassDescriptor.defaultType)
?: emptyMap<TypeConstructor, TypeProjection>()
for ((typeConstructor, typeProjection) in superClassSubstitution) {
val subClassTypeParameter = typeProjection.type.constructor.declarationDescriptor as? TypeParameterDescriptor
?: continue
val superClassTypeParameter = typeConstructor.declarationDescriptor
?: continue
substitution[subClassTypeParameter.typeConstructor] = TypeProjectionImpl(superClassTypeParameter.defaultType)
}
TypeSubstitutor.create(substitution)
}
val isInterfaceTarget: Boolean = targetClassDescriptor.kind == ClassKind.INTERFACE
}
| apache-2.0 | cc981a710c693cab6e3716928c9d14fd | 49.935065 | 158 | 0.801377 | 5.818991 | false | false | false | false |
Coding/Coding-Android | app/src/main/java/net/coding/program/project/MainProjectFragment.kt | 1 | 7551 | package net.coding.program.project
import android.Manifest
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.fragment_main_project.*
import kotlinx.android.synthetic.main.top_tip.*
import net.coding.program.R
import net.coding.program.common.Global
import net.coding.program.common.GlobalCommon
import net.coding.program.common.GlobalData
import net.coding.program.common.event.EventFilter
import net.coding.program.common.event.EventPosition
import net.coding.program.common.ui.BaseFragment
import net.coding.program.common.umeng.UmengEvent
import net.coding.program.common.util.PermissionUtil
import net.coding.program.login.auth.QRScanActivity
import net.coding.program.maopao.MaopaoAddActivity_
import net.coding.program.network.HttpObserverRaw
import net.coding.program.network.Network
import net.coding.program.network.model.common.AppVersion
import net.coding.program.project.init.create.ProjectCreateActivity_
import net.coding.program.search.SearchProjectActivity_
import net.coding.program.task.add.TaskAddActivity_
import net.coding.program.terminal.TerminalActivity
import net.coding.program.user.AddFollowActivity_
import org.androidannotations.api.builder.FragmentBuilder
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
class MainProjectFragment : BaseFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_main_project, container, false)
}
internal fun initMainProjectFragment() {
toolbarTitle.text = "我的项目"
mainProjectToolbar.inflateMenu(R.menu.menu_fragment_project)
mainProjectToolbar.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.action_create_friend -> action_create_friend()
R.id.action_create -> action_create()
R.id.action_create_task -> action_create_task()
R.id.action_create_maopao -> action_create_maopao()
R.id.action_scan -> action_scan()
R.id.action_2fa -> action_2fa()
R.id.action_search -> action_search()
}
true
}
val fragment = ProjectFragment_()
childFragmentManager.beginTransaction()
.add(R.id.container, fragment)
.commit()
}
private fun getVersion(): Int {
try {
val pInfo = activity!!.getPackageManager().getPackageInfo(activity!!.getPackageName(), 0);
return pInfo.versionCode
} catch (e: java.lang.Exception) {
Global.errorLog(e)
}
return 1
}
// 检查客户端是否有更新
private fun checkNeedUpdate() {
updateTip()
Network.getRetrofit(activity)
.getAppVersion()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : HttpObserverRaw<AppVersion>(activity) {
override fun onSuccess(data: AppVersion) {
super.onSuccess(data)
activity!!.getSharedPreferences("version", Context.MODE_PRIVATE)
.edit()
.putInt("NewAppVersion", data.build)
.apply()
updateTip()
}
override fun onFail(errorCode: Int, error: String) {}
})
}
private fun updateTip() {
val versionCode = getVersion()
val share = activity!!.getSharedPreferences("version", Context.MODE_PRIVATE)
val newVersion = share.getInt("NewAppVersion", 0)
if (versionCode < newVersion) {
topTip.visibility = View.VISIBLE
closeTipButton.setOnClickListener { topTip.visibility = View.GONE }
topTipText.setText(R.string.tip_update_app)
topTip.setOnClickListener { Global.updateByMarket(activity) }
} else {
topTip.visibility = View.GONE
}
}
private fun soldOutTip() {
topTip.visibility = View.VISIBLE
closeTipButton.setOnClickListener { topTip.visibility = View.GONE }
topTipText.setText(R.string.sold_out_app)
topTip.setOnClickListener { Global.updateByMarket(activity) }
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
terminalClick.setOnClickListener { terminalClick() }
toolbarTitle.setOnClickListener { toolbarTitle() }
initMainProjectFragment()
soldOutTip()
}
internal fun toolbarTitle() {
EventBus.getDefault().post(EventFilter(0))
}
internal fun terminalClick() {
val i = Intent(activity, TerminalActivity::class.java)
startActivity(i)
}
override fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
}
override fun onStop() {
super.onStop()
EventBus.getDefault().unregister(this)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEvent(eventPosition: EventPosition) {
toolbarTitle?.text = eventPosition.title
}
internal fun action_create_friend() {
umengEvent(UmengEvent.LOCAL, "快捷添加好友")
AddFollowActivity_.intent(this).start()
}
internal fun action_create() {
umengEvent(UmengEvent.LOCAL, "快捷创建项目")
ProjectCreateActivity_.intent(this).start()
}
internal fun action_create_task() {
umengEvent(UmengEvent.LOCAL, "快捷创建任务")
TaskAddActivity_.intent(this).mUserOwner(GlobalData.sUserObject).start()
}
internal fun action_create_maopao() {
umengEvent(UmengEvent.LOCAL, "快捷创建冒泡")
MaopaoAddActivity_.intent(this).start()
}
internal fun action_scan() {
RxPermissions(activity!!)
.request(Manifest.permission.CAMERA)
.subscribe { granted ->
if (granted!!) {
val intent = Intent(activity, QRScanActivity::class.java)
intent.putExtra(QRScanActivity.EXTRA_OPEN_AUTH_LIST, true)
startActivity(intent)
}
}
}
internal fun action_2fa() {
RxPermissions(activity!!)
.request(*PermissionUtil.CAMERA)
.subscribe { granted ->
if (granted!!) {
GlobalCommon.start2FAActivity(activity)
}
}
}
internal fun action_search() {
SearchProjectActivity_.intent(this!!).start()
activity!!.overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out)
}
class FragmentBuilder_ : FragmentBuilder<MainProjectFragment.FragmentBuilder_, MainProjectFragment>() {
override fun build(): net.coding.program.project.MainProjectFragment {
val fragment_ = MainProjectFragment()
fragment_.arguments = args
return fragment_
}
}
}
| mit | 7bac8747d9a1a8f08b1148e6bb70b871 | 34.093897 | 116 | 0.640669 | 4.560708 | false | false | false | false |
myunusov/maxur-mserv | maxur-mserv-core/src/test/kotlin/org/maxur/mserv/frame/command/ServiceCommandSpec.kt | 1 | 2615 | package org.maxur.mserv.frame.command
import org.assertj.core.api.Assertions
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.maxur.mserv.frame.LocatorImpl
import org.maxur.mserv.frame.TestLocatorHolder
import org.maxur.mserv.frame.embedded.EmbeddedService
import org.maxur.mserv.frame.event.MicroserviceStartedEvent
import org.maxur.mserv.frame.event.MicroserviceStoppedEvent
import org.maxur.mserv.frame.event.WebServerStartedEvent
import org.maxur.mserv.frame.event.WebServerStoppedEvent
import org.maxur.mserv.frame.kotlin.Locator
import org.maxur.mserv.frame.runner.KRunner
import org.maxur.mserv.frame.runner.Kotlin
import org.maxur.mserv.frame.service.MicroServiceBuilder
class ServiceCommandSpec : Spek({
describe("Execute Service Commands") {
LocatorImpl.holder = TestLocatorHolder
var runner: KRunner? = null
beforeEachTest {
runner = Kotlin.runner {
withoutProperties()
services += service {
ref = object : EmbeddedService {
override fun start() = listOf(WebServerStartedEvent())
override fun stop() = listOf(WebServerStoppedEvent())
}
}
}
}
context("restart command") {
it("should create new id") {
val service = runner!!.build()
val command = ServiceCommand.Restart(service, Locator.bean(MicroServiceBuilder::class)!!)
service.start()
val stream = command.execute()
Assertions.assertThat(stream.map { it::class })
.isEqualTo(listOf(
WebServerStoppedEvent::class,
MicroserviceStoppedEvent::class,
WebServerStartedEvent::class,
MicroserviceStartedEvent::class
))
service.stop()
}
}
context("stop command ") {
it("should create new id") {
val service = runner!!.build()
val command = ServiceCommand.Stop(service)
service.start()
val stream = command.execute()
Assertions.assertThat(stream.map { it::class })
.isEqualTo(listOf(
WebServerStoppedEvent::class,
MicroserviceStoppedEvent::class
))
}
}
}
}) | apache-2.0 | c6ba91e91e35695d6d0a08faebccfc24 | 36.913043 | 105 | 0.590057 | 5.07767 | false | false | false | false |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/project/Mito/Model/ImageSetInfo.kt | 1 | 24180 | package stan.androiddemo.project.Mito.Model
import android.os.Parcel
import android.os.Parcelable
import okhttp3.Call
import okhttp3.Response
import org.jsoup.Jsoup
import org.litepal.crud.DataSupport
import stan.androiddemo.Model.ResultInfo
import stan.androiddemo.errcode_html_resolve_error
import stan.androiddemo.errcode_netword_error
import stan.androiddemo.errcode_result_not_found
import stan.androiddemo.tool.HttpTool
import java.io.IOException
import java.lang.Exception
import java.net.URLEncoder
import java.util.regex.Pattern
/**
* Created by stanhu on 4/8/2017.
*/
const val PCImage = "http://www.5857.com/list-9"
const val PadImage = "http://www.5857.com/list-10"
const val PhoneImage = "http://www.5857.com/list-11"
const val EssentialImage = "http://www.5857.com/list-37"
class ImageSetInfo() :DataSupport(),Parcelable{
var url = ""
var category = ""
var title = ""
var mainTag = ""
var tags = ArrayList<String>()
var resolution = Resolution()
var resolutionStr:String = ""
var theme = ""
var mainImage = ""
var images = ArrayList<String>()
var count = 0
var imgBelongCat = 0
var isCollected = false
var hashId = 0
var type = 0 //普通壁纸 1动态壁纸
var duration = 0 //
var durationStr = ""
var size = 0
var sizeStr = ""
constructor(parcel: Parcel) : this() {
url = parcel.readString()
category = parcel.readString()
title = parcel.readString()
mainTag = parcel.readString()
resolution = parcel.readParcelable(Resolution::class.java.classLoader)
theme = parcel.readString()
mainImage = parcel.readString()
count = parcel.readInt()
type = parcel.readInt()
durationStr = parcel.readString()
sizeStr = parcel.readString()
}
companion object CREATOR : Parcelable.Creator<ImageSetInfo> {
override fun createFromParcel(parcel: Parcel): ImageSetInfo {
return ImageSetInfo(parcel)
}
override fun newArray(size: Int): Array<ImageSetInfo?> {
return arrayOfNulls(size)
}
fun imageSets(type:Int,cat:String,resolution: Resolution,theme:String, index:Int, cb: ((imageSets: ResultInfo)->Unit)){
val fixedIndex = index + 1
var baseUrl = PCImage
if (type == 1){
baseUrl = PadImage
}
else if (type == 2){
baseUrl = PhoneImage
}
else if (type == 3){
baseUrl = EssentialImage
}
var url = baseUrl + "-" + ImageSetInfo.themeToUrlPara(theme) + "-" + ImageSetInfo.catToUrlPara(cat) + "-0-" + resolution.resolutionCode + "-0-"+fixedIndex+".html"
when(type){
1->{
url = baseUrl + "-" + ImageSetInfo.themeToUrlPara(theme) + "-" + ImageSetInfo.catToUrlPara(cat) + "-" + resolution.resolutionCode + "-0-0-"+fixedIndex+".html"
}
2->{
url = baseUrl + "-" + ImageSetInfo.themeToUrlPara(theme) + "-" + ImageSetInfo.catToUrlPara(cat) + "-0-0-"+ resolution.resolutionCode + "-" +fixedIndex+".html"
}
}
print(url)
HttpTool.get(url,object :okhttp3.Callback{
var result = ResultInfo()
override fun onFailure(call: Call?, e: IOException?) {
result.code = errcode_netword_error
result.message = "网络错误,请重新再试"
cb(result)
e?.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
val arrImageSets = ArrayList<ImageSetInfo>()
try {
val responseText = response.body()!!.string()
val js = Jsoup.parse(responseText)
val imageSets = js.select("ul.clearfix").first().children()
if (imageSets.count() == 1 && imageSets.first().children().count() == 0){
result.code = errcode_result_not_found
result.message = "无有找到图片"
cb(result)
return
}
val reg = Regex("\\D+")
for (set in imageSets){
val imageSet = ImageSetInfo()
val img = set.select("div.listbox").first()
imageSet.mainImage = img.select("a>img").first().attr("src")
if(imageSet.mainImage.startsWith("//")){
imageSet.mainImage = "http:" + imageSet.mainImage
}
imageSet.title = img.select("a>span").first().text()
imageSet.url = img.select("a").first().attr("href")
if(imageSet.url.startsWith("//")){
imageSet.url = "http:" + imageSet.url
}
val c = img.select("em.page_num").first().text().replace(reg,"").toIntOrNull()
if (c != null){
imageSet.count = c!!
}
val imageInfo = set.select("div.listbott").first()
imageSet.category = imageInfo.select("em").first().text()
var res = imageInfo.select("span.fbl").first().text()
if (res.contains("(")){
res = res.split("(")[0]
}
imageSet.resolution = Resolution(res)
if (imageSet.resolution.pixelX == 0){
when(type){
0-> imageSet.resolution = Resolution.standardComputerResolution
1-> imageSet.resolution = Resolution.standardPadResolution
2-> imageSet.resolution = Resolution.standardPhoneResolution
3-> imageSet.resolution = Resolution.standardEssentialResolution
}
}
imageSet.hashId = imageSet.url.hashCode()
imageSet.resolutionStr = imageSet.resolution.toString()
imageSet.theme = imageInfo.select("span.color").first().text()
arrImageSets.add(imageSet)
}
result.data = arrImageSets
cb(result)
}
catch (e:Exception){
result.code = errcode_html_resolve_error
result.message = "HTML解析错误或者没有图片"
cb(result)
e.printStackTrace()
}
}
})
}
fun hotImages(index:Int,cb:((imageSets: ResultInfo)->Unit)){
val url = "http://www.5857.com/html/hotlist-${index}.html"
HttpTool.get(url,object :okhttp3.Callback{
var result = ResultInfo()
override fun onFailure(call: Call?, e: IOException?) {
result.code = errcode_netword_error
result.message = "网络错误,请重新再试"
cb(result)
e?.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
val arrImageSets = ArrayList<ImageSetInfo>()
try {
val responseText = response.body()!!.string()
val js = Jsoup.parse(responseText)
val imageSets = js.select("ul.clearfix").first().children()
if (imageSets.count() == 1 && imageSets.first().children().count() == 0){
result.code = errcode_result_not_found
result.message = "无有找到图片"
cb(result)
return
}
val reg = Regex("\\D+")
for (set in imageSets){
val imageSet = ImageSetInfo()
val img = set.select("div.listbox").first()
imageSet.mainImage = img.select("a>img").first().attr("src")
if(imageSet.mainImage.startsWith("//")){
imageSet.mainImage = "http:" + imageSet.mainImage
}
imageSet.title = img.select("a>span").first().text()
imageSet.url = img.select("a").first().attr("href")
if(imageSet.url.startsWith("//")){
imageSet.url = "http:" + imageSet.url
}
val c = img.select("em.page_num").first().text().replace(reg,"").toIntOrNull()
if (c != null){
imageSet.count = c!!
}
val imageInfo = set.select("div.listbott").first()
imageSet.category = imageInfo.select("em").first().text()
var res = imageInfo.select("span.fbl").first().text()
if (res.contains("(")){
res = res.split("(")[0]
}
imageSet.resolution = Resolution(res)
if (imageSet.resolution.pixelX == 0){
imageSet.resolution = Resolution.standardPhoneResolution
}
imageSet.hashId = imageSet.url.hashCode()
imageSet.resolutionStr = imageSet.resolution.toString()
imageSet.theme = imageInfo.select("span.color").first().text()
arrImageSets.add(imageSet)
}
result.data = arrImageSets
cb(result)
}
catch (e:Exception){
result.code = errcode_html_resolve_error
result.message = "HTML解析错误或者没有图片"
cb(result)
e.printStackTrace()
}
}
})
}
fun searchImages(keyword:String,index:Int,cb:(imageSets: ResultInfo) -> Unit){
val url = "http://www.5857.com/index.php?m=search&c=index&a=init&typeid=3&q=" + URLEncoder.encode(keyword,"UTF-8") + "&page=" + index
HttpTool.get(url,object :okhttp3.Callback{
var result = ResultInfo()
override fun onFailure(call: Call?, e: IOException?) {
result.code = errcode_netword_error
result.message = "网络错误,请重新再试"
cb(result)
e?.printStackTrace()
}
override fun onResponse(call: Call?, response: Response?) {
try {
val responseText = response!!.body()!!.string()
val js = Jsoup.parse(responseText)
val tags = js.select("ul.clearfix").first().children()
// val count = js.select("div.position").text()
// val s = Pattern.compile("[^0-9]").matcher(count)
// do not need all image count now
val reg = Regex("\\D+")
val arrImageSets = ArrayList<ImageSetInfo>()
for (l in tags){
val imageSet = ImageSetInfo()
val img = l.select("div.listbox").first() ?: continue
imageSet.mainImage = img.select("a>img").first().attr("src")
if(imageSet.mainImage.startsWith("//")){
imageSet.mainImage = "http:" + imageSet.mainImage
}
imageSet.title = img.select("a>span").first().text()
imageSet.url = img.select("a").first().attr("href")
if(imageSet.url.startsWith("//")){
imageSet.url = "http:" + imageSet.url
}
val c = img.select("em.page_num").first().text().replace(reg,"").toIntOrNull()
if (c != null){
imageSet.count = c!!
}
val imageInfo = l.select("div.listbott").first() ?: continue
imageSet.category = imageInfo.select("em>a").first().text()
var res = imageInfo.select("span.fbl>a").first().text()
if (res.contains("(")){
res = res.split("(")[0]
}
if (res.contains("其他")){
res = "1920x1080"
}
imageSet.hashId = imageSet.url.hashCode()
imageSet.resolution = Resolution(res)
imageSet.resolutionStr = imageSet.resolution.toString()
imageSet.theme = imageInfo.select("span.color>a").first().text()
arrImageSets.add(imageSet)
}
result.data = arrImageSets
cb(result)
}
catch (e:Exception){
result.code = errcode_html_resolve_error
result.message = "HTML解析错误或者结果不存在"
cb(result)
e.printStackTrace()
}
}
})
}
//获取同类图片集合
fun imageSet(imgSet: ImageSetInfo,cb: (imageSets: ResultInfo) -> Unit){
HttpTool.get(imgSet.url,object :okhttp3.Callback{
var result = ResultInfo()
override fun onFailure(call: Call?, e: IOException?) {
result.code = errcode_netword_error
result.message = "网络错误,请重新再试"
cb(result)
e?.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
try {
val responseText = response.body()!!.string()
val js = Jsoup.parse(responseText)
if(imgSet.count == 1){
val tags = js.select("div.con-tags").first().select("a")
for (tag in tags){
imgSet.tags.add(tag.text())
}
val img = js.select("a.photo-a").first().child(0).attr("src")
imgSet.images.add(img)
}
else{
val tags = js.select("p.main_center_bianqin_fl").first().select("a")
for (tag in tags){
imgSet.tags.add(tag.select("span").text())
}
val imgs = js.select("div.img-box").first().select("a")
for (img in imgs){
var i = img.select("img").first().attr("src")
if(!i.contains("wechatpc")){
if(i.startsWith("//")){
i = "http:$i"
}
imgSet.images.add(i)
}
}
}
result.data = imgSet
cb(result)
}
catch (e:Exception){
result.code = errcode_html_resolve_error
result.message = "HTML解析错误"
cb(result)
e.printStackTrace()
}
}
})
}
fun dynamicSets(cat: String,index: Int,cb: (imageSets: ResultInfo) -> Unit){
val url = "http://www.5857.com/list-42-0-${catToUrlPara(cat)}-0-0-0-${index}.html"
HttpTool.get(url,object :okhttp3.Callback{
var result = ResultInfo()
override fun onFailure(call: Call?, e: IOException?) {
result.code = errcode_netword_error
result.message = "网络错误,请重新再试"
cb(result)
e?.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
val arrImageSets = ArrayList<ImageSetInfo>()
try {
val responseText = response.body()!!.string()
val js = Jsoup.parse(responseText)
val imageSets = js.select("ul.clearfix").first().children()
if (imageSets.count() == 1 && imageSets.first().children().count() == 0){
result.code = errcode_result_not_found
result.message = "无有找到图片"
cb(result)
return
}
val reg = Regex("\\D+")
for (set in imageSets){
val imageSet = ImageSetInfo()
val img = set.select("div.listbox").first()
imageSet.mainImage = img.select("a>img").first().attr("src")
if(imageSet.mainImage.startsWith("//")){
imageSet.mainImage = "http:" + imageSet.mainImage
}
imageSet.title = img.select("a>span").first().text()
imageSet.url = img.select("a").first().attr("href")
if(imageSet.url.startsWith("//")){
imageSet.url = "http:" + imageSet.url
}
val imageInfo = set.select("div.listbott").first()
imageSet.category = imageInfo.select("span>a").first().text()
imageSet.resolution = Resolution("340x604")
imageSet.hashId = imageSet.url.hashCode()
imageSet.resolutionStr = imageSet.resolution.toString()
imageSet.sizeStr = imageInfo.select("span").first().text()
imageSet.durationStr = imageInfo.select("em").first().text()
arrImageSets.add(imageSet)
}
result.data = arrImageSets
cb(result)
}
catch (e:Exception){
result.code = errcode_html_resolve_error
result.message = "HTML解析错误或者没有图片"
cb(result)
e.printStackTrace()
}
}
})
}
fun getVideoLink(url:String,cb: (videoLink: ResultInfo) -> Unit){
HttpTool.get(url,object :okhttp3.Callback{
var result = ResultInfo()
override fun onFailure(call: Call?, e: IOException?) {
result.code = errcode_netword_error
result.message = "网络错误,请重新再试"
cb(result)
e?.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
try {
val responseText = response.body()!!.string()
val js = Jsoup.parse(responseText)
val video = js.select("div.js-video").first().child(0).attr("src")
if(video.startsWith("//")){
result.data = "http:" + video
}
else{
result.data = video
}
cb(result)
}
catch (e:Exception){
result.code = errcode_html_resolve_error
result.message = "HTML解析错误"
cb(result)
e.printStackTrace()
}
}
})
}
fun catToUrlPara(str:String):Int{
when(str){
"全部"->return 0
"美女"->return 3365
"性感"->return 3437
"明星"->return 3366
"风光"->return 3367
"卡通"->return 3368
"创意"->return 3370
"汽车"->return 3371
"游戏"->return 3372
"建筑"->return 3373
"影视"->return 3374
"植物"->return 3376
"动物"->return 3377
"节庆"->return 3378
"可爱"->return 3379
"静物"->return 3369
"体育"->return 3380
"日历"->return 3424
"唯美"->return 3430
"其它"->return 3431
"系统"->return 3434
"动漫"->return 3444
"非主流"->return 3375
"小清新"->return 3381
"娱乐明星"->return 3456
"网络红人"->return 3457
"歌曲舞蹈"->return 3458
"影视大全"->return 3459
"动漫卡通"->return 3460
"游戏天地"->return 3461
"动物萌宠"->return 3462
"风景名胜"->return 3463
"天生尤物"->return 3464
"其他视频"->return 3465
}
return 0
}
fun themeToUrlPara(str:String):Int{
when(str){
"全部"->return 0
"红色"->return 3383
"橙色"->return 3384
"黄色"->return 3385
"绿色"->return 3386
"紫色"->return 3387
"粉色"->return 3388
"青色"->return 3389
"蓝色"->return 3390
"棕色"->return 3391
"白色"->return 3392
"黑色"->return 3393
"银色"->return 3394
"灰色"->return 3395
}
return 0
}
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(url)
parcel.writeString(category)
parcel.writeString(title)
parcel.writeString(mainTag)
parcel.writeParcelable(resolution, flags)
parcel.writeString(theme)
parcel.writeString(mainImage)
parcel.writeInt(count)
parcel.writeInt(type)
parcel.writeString(sizeStr)
parcel.writeString(durationStr)
}
override fun describeContents(): Int {
return 0
}
}
| mit | 4309fd0e2cf599980197ad19149844d7 | 43.714556 | 179 | 0.428892 | 5.215877 | false | false | false | false |
MyCollab/mycollab | mycollab-services/src/main/java/com/mycollab/module/file/PathUtils.kt | 3 | 1676 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.file
/**
* @author MyCollab Ltd
* @since 5.0.10
*/
object PathUtils {
@JvmStatic
fun buildPath(sAccountId: Int?, objectPath: String): String {
return (if (sAccountId == null) "" else sAccountId.toString() + "/") + objectPath
}
@JvmStatic
fun getProjectLogoPath(accountId: Int?, projectId: Int?): String =
"$accountId/project/$projectId/.attachments"
@JvmStatic
fun getEntityLogoPath(accountId: Int?): String = "$accountId/.assets"
@JvmStatic
fun getProjectDocumentPath(accountId: Int?, projectId: Int?): String =
"$accountId/project/$projectId/.page"
@JvmStatic
fun buildLogoPath(sAccountId: Int?, logoFileName: String, logoSize: Int?): String =
"$sAccountId/.assets/${logoFileName}_$logoSize.png"
@JvmStatic
fun buildFavIconPath(sAccountId: Int?, favIconFileName: String): String =
"$sAccountId/.assets/$favIconFileName.ico"
}
| agpl-3.0 | 1db71be5ef1048c154bb380fedb6be9f | 34.638298 | 89 | 0.695522 | 4.328165 | false | false | false | false |
kerubistan/kerub | src/main/kotlin/com/github/kerubistan/kerub/planner/PlanComparator.kt | 2 | 1816 | package com.github.kerubistan.kerub.planner
import com.github.kerubistan.kerub.planner.costs.Risk
import com.github.kerubistan.kerub.planner.costs.TimeCost
import com.github.kerubistan.kerub.planner.costs.Violation
import io.github.kerubistan.kroki.collections.concat
/**
* Compares two plans by costs (time, IO, risk), violations, outcome.
*
* This comparison could be quite complex if it could consider all
* aspects. E.g. a few gigs of disk write on an otherwise idle server
* should be still better than doing the same on a heavily loaded server.
*
* For now something basic should do, just to introduce the concept that
* plans are not equally good.
*
* If the costs are equal or we have no idea for a comparison yet, then
* the shorter plan is better.
*/
object PlanComparator : Comparator<Plan> {
private val Plan.costs get() = this.steps.map { it.getCost() }.concat().groupBy { it.javaClass.kotlin }
/**
* The order that tells which cost types to compare first when comparing plans.
* Therefore e.g. a plan with violations should be evaluated as less good than
* one without violations.
*/
private val costTypeOrder = listOf(
Violation::class,
Risk::class,
TimeCost::class
)
override fun compare(first: Plan, second: Plan): Int {
val firstCosts = first.costs
val secondCosts = second.costs
val costTypes = (firstCosts.keys + secondCosts.keys).sortedBy {
val index = costTypeOrder.indexOf(it)
if (index == -1) {
costTypeOrder.size + 1
} else {
index
}
}
costTypes.forEach { costType ->
val first = firstCosts[costType] ?: listOf()
val second = firstCosts[costType] ?: listOf()
//TODO compare two list of costs, they are of the same type
}
//lots of things to do
return first.steps.size.compareTo(second.steps.size)
}
} | apache-2.0 | 5d7b42b3bf15d40b133ba3906481afaf | 28.786885 | 104 | 0.720264 | 3.546875 | false | false | false | false |
duftler/clouddriver | cats/cats-sql/src/main/kotlin/com/netflix/spinnaker/cats/sql/SqlProviderCache.kt | 1 | 11104 | package com.netflix.spinnaker.cats.sql
import com.netflix.spinnaker.cats.agent.CacheResult
import com.netflix.spinnaker.cats.cache.CacheData
import com.netflix.spinnaker.cats.cache.CacheFilter
import com.netflix.spinnaker.cats.cache.DefaultCacheData
import com.netflix.spinnaker.cats.cache.WriteableCache
import com.netflix.spinnaker.cats.provider.ProviderCache
import com.netflix.spinnaker.cats.sql.cache.SqlCache
import com.netflix.spinnaker.clouddriver.core.provider.agent.Namespace.CLUSTERS
import com.netflix.spinnaker.clouddriver.core.provider.agent.Namespace.NAMED_IMAGES
import com.netflix.spinnaker.clouddriver.core.provider.agent.Namespace.ON_DEMAND
import org.slf4j.LoggerFactory
import org.slf4j.MDC
import kotlin.contracts.ExperimentalContracts
@ExperimentalContracts
class SqlProviderCache(private val backingStore: WriteableCache) : ProviderCache {
companion object {
private const val ALL_ID = "_ALL_" // this implementation ignores this entirely
private val log = LoggerFactory.getLogger(javaClass)
}
init {
if (backingStore !is SqlCache) {
throw IllegalStateException("SqlProviderCache must be wired with a SqlCache backingStore")
}
}
/**
* Filters the supplied list of identifiers to only those that exist in the cache.
*
* @param type the type of the item
* @param identifiers the identifiers for the items
* @return the list of identifiers that are present in the cache from the provided identifiers
*/
override fun existingIdentifiers(type: String, identifiers: MutableCollection<String>): MutableCollection<String> {
return backingStore.existingIdentifiers(type, identifiers)
}
/**
* Returns the identifiers for the specified type that match the provided glob.
*
* @param type The type for which to retrieve identifiers
* @param glob The glob to match against the identifiers
* @return the identifiers for the type that match the glob
*/
override fun filterIdentifiers(type: String?, glob: String?): MutableCollection<String> {
return backingStore.filterIdentifiers(type, glob)
}
/**
* Retrieves all the items for the specified type
*
* @param type the type for which to retrieve items
* @return all the items for the type
*/
override fun getAll(type: String): MutableCollection<CacheData> {
return getAll(type, null as CacheFilter?)
}
override fun getAll(type: String, identifiers: MutableCollection<String>?): MutableCollection<CacheData> {
return getAll(type, identifiers, null)
}
override fun getAll(type: String, cacheFilter: CacheFilter?): MutableCollection<CacheData> {
validateTypes(type)
return backingStore.getAll(type, cacheFilter)
}
override fun getAll(
type: String,
identifiers: MutableCollection<String>?,
cacheFilter: CacheFilter?
): MutableCollection<CacheData> {
validateTypes(type)
return backingStore.getAll(type, identifiers, cacheFilter)
}
override fun supportsGetAllByApplication(): Boolean {
return true
}
override fun getAllByApplication(type: String, application: String): Map<String, MutableCollection<CacheData>> {
return getAllByApplication(type, application, null)
}
override fun getAllByApplication(
type: String,
application: String,
cacheFilter: CacheFilter?
): Map<String, MutableCollection<CacheData>> {
validateTypes(type)
return backingStore.getAllByApplication(type, application, cacheFilter)
}
override fun getAllByApplication(
types: Collection<String>,
application: String,
filters: Map<String, CacheFilter?>
): Map<String, MutableCollection<CacheData>> {
validateTypes(types)
return backingStore.getAllByApplication(types, application, filters)
}
/**
* Retrieves the items for the specified type matching the provided identifiers
*
* @param type the type for which to retrieve items
* @param identifiers the identifiers
* @return the items matching the type and identifiers
*/
override fun getAll(type: String, vararg identifiers: String): MutableCollection<CacheData> {
return getAll(type, identifiers.toMutableList())
}
/**
* Gets a single item from the cache by type and id
*
* @param type the type of the item
* @param id the id of the item
* @return the item matching the type and id
*/
override fun get(type: String, id: String?): CacheData? {
return get(type, id, null)
}
override fun get(type: String, id: String?, cacheFilter: CacheFilter?): CacheData? {
if (ALL_ID == id) {
log.warn("Unexpected request for $ALL_ID for type: $type, cacheFilter: $cacheFilter")
return null
}
validateTypes(type)
return backingStore.get(type, id, cacheFilter) ?: return null
}
override fun evictDeletedItems(type: String, ids: Collection<String>) {
try {
MDC.put("agentClass", "evictDeletedItems")
backingStore.evictAll(type, ids)
} finally {
MDC.remove("agentClass")
}
}
/**
* Retrieves all the identifiers for a type
*
* @param type the type for which to retrieve identifiers
* @return the identifiers for the type
*/
override fun getIdentifiers(type: String): MutableCollection<String> {
validateTypes(type)
return backingStore.getIdentifiers(type)
}
override fun putCacheResult(
source: String,
authoritativeTypes: MutableCollection<String>,
cacheResult: CacheResult
) {
try {
MDC.put("agentClass", "$source putCacheResult")
// TODO every source type should have an authoritative agent and every agent should be authoritative for something
// TODO terrible hack because no AWS agent is authoritative for clusters, fix in ClusterCachingAgent
// TODO same with namedImages - fix in AWS ImageCachingAgent
if (
source.contains("clustercaching", ignoreCase = true) &&
!authoritativeTypes.contains(CLUSTERS.ns) &&
cacheResult.cacheResults
.any {
it.key.startsWith(CLUSTERS.ns)
}
) {
authoritativeTypes.add(CLUSTERS.ns)
} else if (
source.contains("imagecaching", ignoreCase = true) &&
cacheResult.cacheResults
.any {
it.key.startsWith(NAMED_IMAGES.ns)
}
) {
authoritativeTypes.add(NAMED_IMAGES.ns)
}
cacheResult.cacheResults
.filter {
it.key.contains(ON_DEMAND.ns, ignoreCase = true)
}
.forEach {
authoritativeTypes.add(it.key)
}
val cachedTypes = mutableSetOf<String>()
// Update resource table from Authoritative sources only
when {
// OnDemand agents should only be treated as authoritative and don't use standard eviction logic
source.contains(ON_DEMAND.ns, ignoreCase = true) -> cacheResult.cacheResults
// And OnDemand agents shouldn't update other resource type tables
.filter {
it.key.contains(ON_DEMAND.ns, ignoreCase = true)
}
.forEach {
cacheDataType(it.key, source, it.value, authoritative = true, cleanup = false)
}
authoritativeTypes.isNotEmpty() -> cacheResult.cacheResults
.filter {
authoritativeTypes.contains(it.key)
}
.forEach {
cacheDataType(it.key, source, it.value, authoritative = true)
cachedTypes.add(it.key)
}
else -> // If there are no authoritative types in cacheResult, override all as authoritative without cleanup
cacheResult.cacheResults
.forEach {
cacheDataType(it.key, source, it.value, authoritative = true, cleanup = false)
cachedTypes.add(it.key)
}
}
// Update relationships for non-authoritative types
if (!source.contains(ON_DEMAND.ns, ignoreCase = true)) {
cacheResult.cacheResults
.filter {
!cachedTypes.contains(it.key)
}
.forEach {
cacheDataType(it.key, source, it.value, authoritative = false)
}
}
if (cacheResult.evictions.isNotEmpty()) {
cacheResult.evictions.forEach {
evictDeletedItems(it.key, it.value)
}
}
} finally {
MDC.remove("agentClass")
}
}
override fun addCacheResult(
source: String,
authoritativeTypes: MutableCollection<String>,
cacheResult: CacheResult
) {
try {
MDC.put("agentClass", "$source putCacheResult")
val cachedTypes = mutableSetOf<String>()
if (authoritativeTypes.isNotEmpty()) {
cacheResult.cacheResults
.filter {
authoritativeTypes.contains(it.key)
}
.forEach {
cacheDataType(it.key, source, it.value, authoritative = true, cleanup = false)
cachedTypes.add(it.key)
}
}
cacheResult.cacheResults
.filter { !cachedTypes.contains(it.key) }
.forEach {
cacheDataType(it.key, source, it.value, authoritative = false, cleanup = false)
}
} finally {
MDC.remove("agentClass")
}
}
override fun putCacheData(type: String, cacheData: CacheData) {
try {
MDC.put("agentClass", "putCacheData")
backingStore.merge(type, cacheData)
} finally {
MDC.remove("agentClass")
}
}
fun cleanOnDemand(maxAgeMs: Long): Int {
return (backingStore as SqlCache).cleanOnDemand(maxAgeMs)
}
private fun validateTypes(type: String) {
validateTypes(listOf(type))
}
private fun validateTypes(types: Collection<String>) {
val invalid = types
.asSequence()
.filter { it.contains(":") }
.toSet()
if (invalid.isNotEmpty()) {
throw IllegalArgumentException("Invalid types: $invalid")
}
}
private fun cacheDataType(type: String, agent: String, items: Collection<CacheData>, authoritative: Boolean) {
cacheDataType(type, agent, items, authoritative, cleanup = true)
}
private fun cacheDataType(
type: String,
agent: String,
items: Collection<CacheData>,
authoritative: Boolean,
cleanup: Boolean
) {
val toStore = ArrayList<CacheData>(items.size + 1)
items.forEach {
toStore.add(uniqueifyRelationships(it, agent))
}
// OnDemand agents are always updated incrementally and should not trigger auto-cleanup at the WriteableCache layer
val cleanupOverride =
if (agent.contains(ON_DEMAND.ns, ignoreCase = true) || type.contains(ON_DEMAND.ns, ignoreCase = true)) {
false
} else {
cleanup
}
(backingStore as SqlCache).mergeAll(type, agent, toStore, authoritative, cleanupOverride)
}
private fun uniqueifyRelationships(source: CacheData, sourceAgentType: String): CacheData {
val relationships = HashMap<String, Collection<String>>(source.relationships.size)
for ((key, value) in source.relationships) {
relationships["$key:$sourceAgentType"] = value
}
return DefaultCacheData(source.id, source.ttlSeconds, source.attributes, relationships)
}
}
| apache-2.0 | 0c1072fa3fc10d1c9e649a60fc694009 | 31.658824 | 120 | 0.678584 | 4.580858 | false | false | false | false |
JetBrains/teamcity-azure-plugin | plugin-azure-server/src/main/kotlin/jetbrains/buildServer/clouds/azure/arm/connector/tasks/AzureThrottlerActionTasks.kt | 1 | 1941 | /*
* Copyright 2000-2021 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 jetbrains.buildServer.clouds.azure.arm.connector.tasks
class AzureThrottlerActionTasks {
enum class Values {
CreateDeployment,
CreateResourceGroup,
DeleteResourceGroup,
StopVirtualMachine,
StartVirtualMachine,
RestartVirtualMachine,
DeleteDeployment
}
companion object {
val CreateDeployment = AzureTaskDescriptorImpl(Values.CreateDeployment, { notifications -> CreateDeploymentTaskImpl(notifications) })
val CreateResourceGroup = AzureTaskDescriptorImpl(Values.CreateResourceGroup, { CreateResourceGroupTaskImpl() })
val DeleteResourceGroup = AzureTaskDescriptorImpl(Values.DeleteResourceGroup, { DeleteResourceGroupTaskImpl() })
val StopVirtualMachine = AzureTaskDescriptorImpl(Values.StopVirtualMachine, { notifications -> StopVirtualMachineTaskImpl(notifications) })
val StartVirtualMachine = AzureTaskDescriptorImpl(Values.StartVirtualMachine, { notifications -> StartVirtualMachineTaskImpl(notifications) })
val RestartVirtualMachine = AzureTaskDescriptorImpl(Values.RestartVirtualMachine, { notifications -> RestartVirtualMachineTaskImpl(notifications) })
val DeleteDeployment = AzureTaskDescriptorImpl(Values.DeleteDeployment, { notifications -> DeleteDeploymentTaskImpl(notifications) })
}
}
| apache-2.0 | 3494e4cf9ccb087505143fa15979b172 | 48.769231 | 156 | 0.763524 | 5.028497 | false | false | false | false |
Ufkoku/AndroidMVPHelper | app/src/main/kotlin/com/ufkoku/demo_app/ui/view/adapter/DataAdapter.kt | 1 | 1580 | package com.ufkoku.demo_app.ui.view.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.ufkoku.demo_app.R
import com.ufkoku.demo_app.entity.AwesomeEntity
class DataAdapter(context: Context, private val entities: List<AwesomeEntity>) : RecyclerView.Adapter<DataAdapter.AdapterViewHolder>() {
private val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
var listener: AdapterListener? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AdapterViewHolder {
return AdapterViewHolder(inflater.inflate(R.layout.list_item, parent, false))
}
override fun onBindViewHolder(holder: AdapterViewHolder, position: Int) {
holder.bind(entities[position])
}
override fun getItemCount(): Int {
return entities.size
}
inner class AdapterViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val textView: TextView
private var binded: AwesomeEntity? = null
init {
textView = itemView as TextView
textView.setOnClickListener { listener?.onItemClicked(binded!!) }
}
fun bind(entity: AwesomeEntity) {
binded = entity
textView.text = entity.importantDataField.toString()
}
}
interface AdapterListener {
fun onItemClicked(entity: AwesomeEntity)
}
}
| apache-2.0 | 9496a69b2c9c4e77c723185a6801adb4 | 27.727273 | 136 | 0.716456 | 4.54023 | false | false | false | false |
dmcg/hamkrest | src/main/kotlin/com/natpryce/hamkrest/assertion/assert.kt | 1 | 2794 | @file:JvmName("Assert")
package com.natpryce.hamkrest.assertion
import com.natpryce.hamkrest.MatchResult
import com.natpryce.hamkrest.Matcher
import com.natpryce.hamkrest.describe
import kotlin.reflect.KFunction1
import kotlin.reflect.KFunction2
private fun noMessage() = ""
class Assertion(val valueDescriber: (Any?) -> String) {
fun <T> that(actual: T, criteria: Matcher<T>, message: () -> String = ::noMessage) {
val judgement = criteria(actual)
if (judgement is MatchResult.Mismatch) {
throw AssertionError(
message().let { if (it.isEmpty()) it else it + ": " } +
"expected: a value that ${valueDescriber(criteria)}\n" +
"but ${valueDescriber(judgement)}")
}
}
}
fun <T> Assertion.that(actual: T, criteria: KFunction1<T, Boolean>, message: () -> String = ::noMessage) {
that(actual, Matcher(criteria), message)
}
fun <T, U> Assertion.that(actual: T, criteria: KFunction2<T, U, Boolean>, other: U, message: () -> String = ::noMessage) {
that(actual, Matcher(criteria, other), message)
}
/**
* An Assertion that uses the Hamkrest's `describe` function to describe values.
*/
val assert = Assertion(::describe)
/**
* Asserts that [criteria] matches [actual].
* @throws AssertionError if there is a mismatch
*/
fun <T> assertThat(actual: T, criteria: Matcher<T>) {
assert.that(actual, criteria)
}
/**
* Asserts that [criteria] matches [actual]. On failure, the diagnostic is prefixed with [message].
* @throws AssertionError if there is a mismatch
*/
fun <T> assertThat(message: String, actual: T, criteria: Matcher<T>) {
assert.that(actual, criteria, { message })
}
/**
* Asserts that [criteria] returns true for [actual].
*
* @throws AssertionError if there is a mismatch
*/
fun <T> assertThat(actual: T, criteria: KFunction1<T, Boolean>) {
assert.that(actual, criteria)
}
/**
* Asserts that [criteria] returns true for [actual]. On failure, the diagnostic is prefixed with [message].
* @throws AssertionError if there is a mismatch
*/
fun <T> assertThat(message: String, actual: T, criteria: KFunction1<T, Boolean>) {
assert.that(actual, criteria, { message })
}
/**
* Asserts that [criteria]([actual], [other]) returns true. On failure, the diagnostic is prefixed with [message].
* @throws AssertionError if there is a mismatch
*/
fun <T, U> assertThat(message: String, actual: T, criteria: KFunction2<T, U, Boolean>, other: U) {
assert.that(actual, criteria, other, { message })
}
/**
* Asserts that [criteria]([actual], [other]) returns true.
* @throws AssertionError if there is a mismatch
*/
fun <T, U> assertThat(actual: T, criteria: KFunction2<T, U, Boolean>, other: U) {
assert.that(actual, criteria, other)
}
| apache-2.0 | abfb7002eb15bc1bd2544e8413374ef5 | 30.393258 | 122 | 0.672513 | 3.64752 | false | false | false | false |
rharter/windy-city-devcon-android | app/src/main/kotlin/com/gdgchicagowest/windycitydevcon/features/main/MainActivity.kt | 1 | 3479 | package com.gdgchicagowest.windycitydevcon.features.main
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import android.view.View
import com.gdgchicagowest.windycitydevcon.R
import com.gdgchicagowest.windycitydevcon.ext.getAppComponent
import com.gdgchicagowest.windycitydevcon.features.info.InfoView
import com.gdgchicagowest.windycitydevcon.features.location.LocationView
import com.gdgchicagowest.windycitydevcon.features.sessiondetail.SessionDetailActivity
import com.gdgchicagowest.windycitydevcon.features.sessions.SessionDateView
import com.gdgchicagowest.windycitydevcon.features.sessions.SessionNavigator
import com.gdgchicagowest.windycitydevcon.features.speakerdetail.SpeakerDetailActivity
import com.gdgchicagowest.windycitydevcon.features.speakerdetail.SpeakerNavigator
import com.gdgchicagowest.windycitydevcon.features.speakerlist.SpeakerListView
import com.gdgchicagowest.windycitydevcon.model.Session
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(), SessionNavigator, SpeakerNavigator, NavigationView.OnNavigationItemSelectedListener {
lateinit var component: MainComponent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
component = getAppComponent().mainComponent(MainModule(this, this))
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
val toggle = ActionBarDrawerToggle(this, drawer_layout, toolbar, R.string.open_drawer, R.string.close_drawer)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
showView(R.id.action_schedule)
nav_view.setNavigationItemSelectedListener(this)
nav_view.setCheckedItem(R.id.action_schedule)
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
if (showView(item.itemId)) {
drawer_layout.closeDrawers()
return true
} else {
return false
}
}
private fun showView(viewId: Int): Boolean {
val view: View? = when (viewId) {
R.id.action_schedule -> SessionDateView(this)
R.id.action_speakers -> SpeakerListView(this)
R.id.action_location -> LocationView(this)
R.id.action_info -> InfoView(this)
else -> null
}
if (view != null) {
content.removeAllViews()
content.addView(view)
return true
}
return false
}
override fun getSystemService(name: String?): Any {
when (name) {
"component" -> return component
else -> return super.getSystemService(name)
}
}
override fun showSession(session: Session) {
val intent = Intent(this, SessionDetailActivity::class.java)
intent.putExtra("session_id", session.id)
startActivity(intent)
}
override fun nagivateToSpeaker(id: String, image: View?) {
SpeakerDetailActivity.navigate(this, id, image)
}
} | apache-2.0 | c750f546778fedfa21134f1ddb22feb4 | 36.021277 | 127 | 0.718597 | 4.798621 | false | false | false | false |
mvarnagiris/mvp | mvp/src/main/kotlin/com/mvcoding/mvp/Presenter.kt | 1 | 4910 | package com.mvcoding.mvp
import io.reactivex.*
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
abstract class Presenter<VIEW : Presenter.View>(private vararg val behaviors: Behavior<VIEW>) {
private lateinit var compositeDisposable: CompositeDisposable
private var view: VIEW? = null
private var viewDelegate: VIEW? = null
infix fun attach(view: VIEW) {
ensureViewIsNotAttached(view)
this.view = view
viewDelegate = decorateView(view)
compositeDisposable = CompositeDisposable()
behaviors.forEach { it attach viewDelegate as VIEW }
onViewAttached(viewDelegate as VIEW)
}
infix fun detach(view: VIEW) {
ensureGivenViewIsAttached(view)
compositeDisposable.dispose()
behaviors.forEach { it detach viewDelegate as VIEW }
onViewDetached(viewDelegate as VIEW)
this.view = null
this.viewDelegate = null
}
protected open fun decorateView(view: VIEW): VIEW = view
operator fun plus(view: VIEW) {
attach(view)
}
operator fun minus(view: VIEW) {
detach(view)
}
protected open fun onViewAttached(view: VIEW) {
}
protected open fun onViewDetached(view: VIEW) {
}
private fun disposeOnDetach(disposable: Disposable) {
compositeDisposable.add(disposable)
}
protected fun <T> Observable<T>.subscribeUntilDetached(): Disposable = subscribe().apply { disposeOnDetach(this) }
protected fun <T> Flowable<T>.subscribeUntilDetached(): Disposable = subscribe().apply { disposeOnDetach(this) }
protected fun <T> Single<T>.subscribeUntilDetached(): Disposable = subscribe().apply { disposeOnDetach(this) }
protected fun <T> Maybe<T>.subscribeUntilDetached(): Disposable = subscribe().apply { disposeOnDetach(this) }
protected fun Completable.subscribeUntilDetached(): Disposable = subscribe().apply { disposeOnDetach(this) }
protected fun <T> Observable<T>.subscribeUntilDetached(onNext: (T) -> Unit): Disposable = subscribe(onNext).apply { disposeOnDetach(this) }
protected fun <T> Flowable<T>.subscribeUntilDetached(onNext: (T) -> Unit): Disposable = subscribe(onNext).apply { disposeOnDetach(this) }
protected fun <T> Single<T>.subscribeUntilDetached(onSuccess: (T) -> Unit): Disposable = subscribe(onSuccess).apply { disposeOnDetach(this) }
protected fun <T> Maybe<T>.subscribeUntilDetached(onSuccess: (T) -> Unit): Disposable = subscribe(onSuccess).apply { disposeOnDetach(this) }
protected fun Completable.subscribeUntilDetached(onComplete: () -> Unit): Disposable = subscribe(onComplete).apply { disposeOnDetach(this) }
protected fun <T> Observable<T>.subscribeUntilDetached(onNext: (T) -> Unit, onError: (Throwable) -> Unit): Disposable =
subscribe(onNext, onError).apply { disposeOnDetach(this) }
protected fun <T> Flowable<T>.subscribeUntilDetached(onNext: (T) -> Unit, onError: (Throwable) -> Unit): Disposable =
subscribe(onNext, onError).apply { disposeOnDetach(this) }
protected fun <T> Single<T>.subscribeUntilDetached(onSuccess: (T) -> Unit, onError: (Throwable) -> Unit): Disposable =
subscribe(onSuccess, onError).apply { disposeOnDetach(this) }
protected fun <T> Maybe<T>.subscribeUntilDetached(onSuccess: (T) -> Unit, onError: (Throwable) -> Unit): Disposable =
subscribe(onSuccess, onError).apply { disposeOnDetach(this) }
protected fun Completable.subscribeUntilDetached(onComplete: () -> Unit, onError: (Throwable) -> Unit): Disposable =
subscribe(onComplete, onError).apply { disposeOnDetach(this) }
protected fun <T> Observable<T>.subscribeUntilDetached(onNext: (T) -> Unit, onError: (Throwable) -> Unit, onComplete: () -> Unit): Disposable =
subscribe(onNext, onError, onComplete).apply { disposeOnDetach(this) }
protected fun <T> Flowable<T>.subscribeUntilDetached(onNext: (T) -> Unit, onError: (Throwable) -> Unit, onComplete: () -> Unit): Disposable =
subscribe(onNext, onError, onComplete).apply { disposeOnDetach(this) }
protected fun <T> Maybe<T>.subscribeUntilDetached(onSuccess: (T) -> Unit, onError: (Throwable) -> Unit, onComplete: () -> Unit): Disposable =
subscribe(onSuccess, onError, onComplete).apply { disposeOnDetach(this) }
private fun ensureViewIsNotAttached(view: VIEW) {
if (this.view != null) throw IllegalStateException("Cannot attach $view, because ${this.view} is already attached")
}
private fun ensureGivenViewIsAttached(view: VIEW) {
if (this.view == null)
throw IllegalStateException("View is already detached.")
else if (this.view != view)
throw IllegalStateException("Trying to detach different view. We have view: ${this.view}. Trying to detach view: $view")
}
interface View
} | apache-2.0 | 308782df5ad700c65ba1063a402c6e1d | 48.11 | 147 | 0.697352 | 4.459582 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/util/Recti.kt | 1 | 1419 | /*
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.util
import org.joml.Vector2d
/**
* A rectangle using Ints.
* Note, the right and bottom values are EXCLUSIVE, so width = right - left
*
* The Y axis points up, so top > bottom
*
* For a rectangle with the y axis pointing down, use [YDownRect] instead.
*/
data class Recti(
var left: Int,
var bottom: Int,
var right: Int,
var top: Int) {
val width
get() = right - left
val height
get() = top - bottom
fun contains(screenPosition: Vector2d): Boolean {
return screenPosition.x >= left && screenPosition.x < right && screenPosition.y >= bottom && screenPosition.y < top
}
override fun toString(): String = "($left,$bottom , $right,$top)"
}
| gpl-3.0 | 942f85bf0181bdf7e984c80ef2889929 | 29.191489 | 123 | 0.699789 | 3.997183 | false | false | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/ide/template/macros/RustCollectionElementNameMacro.kt | 1 | 2735 | package org.rust.ide.template.macros
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.codeInsight.template.Expression
import com.intellij.codeInsight.template.ExpressionContext
import com.intellij.codeInsight.template.Result
import com.intellij.codeInsight.template.TextResult
import com.intellij.codeInsight.template.macro.MacroBase
import com.intellij.openapi.util.text.StringUtil
import org.rust.lang.refactoring.RustNamesValidator
class RustCollectionElementNameMacro : MacroBase("rustCollectionElementName", "rustCollectionElementName()") {
override fun calculateResult(params: Array<out Expression>, context: ExpressionContext, quick: Boolean): Result? {
var param = getCollectionExprStr(params, context) ?: return null
val lastDot = param.lastIndexOf('.')
if (lastDot >= 0) {
param = param.substring(lastDot + 1)
}
val lastDoubleColon = param.lastIndexOf("::")
if (lastDoubleColon > 0) {
param = param.substring(0, lastDoubleColon)
}
if (param.endsWith(')')) {
val lastParen = param.lastIndexOf('(')
if (lastParen > 0) {
param = param.substring(0, lastParen)
}
}
val name = unpluralize(param) ?: return null
if (RustNamesValidator().isIdentifier(name, context.project)) {
return TextResult(name)
} else {
return null
}
}
override fun calculateLookupItems(params: Array<out Expression>, context: ExpressionContext): Array<out LookupElement>? {
val result = calculateResult(params, context) ?: return null
val words = result.toString().split('_')
if (words.size > 1) {
val lookups = mutableListOf<LookupElement>()
for (i in words.indices) {
val element = words.subList(i, words.size).joinToString("_")
lookups.add(LookupElementBuilder.create(element))
}
return lookups.toTypedArray()
} else {
return null
}
}
companion object {
private fun getCollectionExprStr(params: Array<out Expression>, context: ExpressionContext): String? =
params.singleOrNull()?.calculateResult(context)?.toString()
private fun unpluralize(name: String): String? {
for (prefix in SUFFIXES) {
if (name.endsWith(prefix)) {
return name.substring(0, name.length - prefix.length)
}
}
return StringUtil.unpluralize(name)
}
private val SUFFIXES = arrayOf("_list", "_set")
}
}
| mit | 742c23aa9f3a90c411e51182cae6ef33 | 36.986111 | 125 | 0.635832 | 4.866548 | false | false | false | false |
android/user-interface-samples | Text/app/src/main/java/com/example/android/text/ui/home/HomeFragment.kt | 1 | 2661 | /*
* Copyright (C) 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
*
* 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.text.ui.home
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import androidx.interpolator.view.animation.FastOutLinearInInterpolator
import androidx.interpolator.view.animation.LinearOutSlowInInterpolator
import androidx.transition.Fade
import androidx.transition.Transition
import com.example.android.text.R
import com.example.android.text.databinding.HomeFragmentBinding
import com.example.android.text.demo.Demos
import com.example.android.text.ui.viewBindings
private const val TransitionDuration = 300L
/**
* Shows the list of demos in this sample.
*/
class HomeFragment : Fragment(R.layout.home_fragment) {
private val binding by viewBindings(HomeFragmentBinding::bind)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
exitTransition = createTransition(true)
reenterTransition = createTransition(false)
binding.demoList.adapter = DemoListAdapter(
onDemoClick = { demo ->
parentFragmentManager.commit {
setReorderingAllowed(true)
addToBackStack(null)
replace(R.id.content, demo.fragment().apply {
enterTransition = createTransition(false)
returnTransition = createTransition(true)
})
}
activity?.title = demo.title
}
).apply {
submitList(Demos)
}
}
private fun createTransition(isLeaving: Boolean): Transition {
return Fade().apply {
if (isLeaving) {
duration = TransitionDuration / 3
startDelay = 0L
interpolator = FastOutLinearInInterpolator()
} else {
duration = TransitionDuration / 3 * 2
startDelay = TransitionDuration / 3
interpolator = LinearOutSlowInInterpolator()
}
}
}
}
| apache-2.0 | b042938fa5ae7aaea50eeec5c209861d | 34.959459 | 75 | 0.665915 | 4.900552 | false | false | false | false |
MHP-A-Porsche-Company/CDUI-Showcase-Android | app/src/main/kotlin/com/mhp/showcase/block/eventstream/EventStreamBlockView.kt | 1 | 1654 | package com.mhp.showcase.block.eventstream
import android.annotation.SuppressLint
import android.content.Context
import android.widget.RelativeLayout
import android.widget.TextView
import com.mhp.showcase.R
import com.mhp.showcase.block.BaseBlockView
import org.androidannotations.annotations.AfterViews
import org.androidannotations.annotations.EViewGroup
import org.androidannotations.annotations.ViewById
import java.text.SimpleDateFormat
import java.util.*
@SuppressLint("ViewConstructor")
@EViewGroup(R.layout.view_block_event_stream)
open class EventStreamBlockView(context: Context) : RelativeLayout(context), BaseBlockView<EventStreamBlock> {
@ViewById(R.id.title)
protected lateinit var title: TextView
@ViewById(R.id.subtitle)
protected lateinit var subtitle: TextView
@ViewById(R.id.date)
protected lateinit var date: TextView
override var block: EventStreamBlock? = null
set(value) {
field = value
afterViews()
}
@AfterViews
override fun afterViews() {
if (block != null) {
title.text = block?.title
subtitle.text = block?.subtitle
val df = SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH)
date.text = df.format(Date(block?.date!!)).toUpperCase()
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as EventStreamBlockView
if (block != other.block) return false
return true
}
override fun hashCode(): Int {
return block?.hashCode() ?: 0
}
} | mit | 1337157946b6f98f59e9eac746303c2d | 27.534483 | 110 | 0.689843 | 4.398936 | false | false | false | false |
jitsi/jitsi-videobridge | rtp/src/main/kotlin/org/jitsi/rtp/rtcp/RtcpHeader.kt | 1 | 5005 | /*
* Copyright @ 2018 - present 8x8, 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 org.jitsi.rtp.rtcp
import org.jitsi.rtp.extensions.bytearray.getBitAsBool
import org.jitsi.rtp.extensions.bytearray.putBitAsBoolean
import org.jitsi.rtp.extensions.bytearray.putInt
import org.jitsi.rtp.extensions.bytearray.putShort
import org.jitsi.rtp.util.getBitsAsInt
import org.jitsi.rtp.util.getByteAsInt
import org.jitsi.rtp.util.getIntAsLong
import org.jitsi.rtp.util.getShortAsInt
import org.jitsi.rtp.util.putNumberAsBits
/**
* Models the RTCP header as defined in https://tools.ietf.org/html/rfc3550#section-6.1
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |V=2|P| RC | PT=SR=200 | length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | SSRC of sender |
* +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
*
* length: 16 bits
* The length of this RTCP packet in 32-bit words minus one,
* including the header and any padding. (The offset of one makes
* zero a valid length and avoids a possible infinite loop in
* scanning a compound RTCP packet, while counting 32-bit words
* avoids a validity check for a multiple of 4.)
*
* @author Brian Baldino
*
* TODO: Use the same utility function in RtpHeader and RtcpHeader
*/
class RtcpHeader {
companion object {
const val SIZE_BYTES = 8
const val VERSION_OFFSET = 0
const val PADDING_OFFSET = 0
const val REPORT_COUNT_OFFSET = 0
const val PACKET_TYPE_OFFSET = 1
const val LENGTH_OFFSET = 2
const val SENDER_SSRC_OFFSET = 4
fun getVersion(buf: ByteArray, headerStartOffset: Int): Int =
buf.getBitsAsInt(headerStartOffset + VERSION_OFFSET, 0, 2)
fun setVersion(buf: ByteArray, headerStartOffset: Int, version: Int) =
buf.putNumberAsBits(headerStartOffset + VERSION_OFFSET, 0, 2, version)
fun hasPadding(buf: ByteArray, headerStartOffset: Int): Boolean =
buf.getBitAsBool(headerStartOffset + PADDING_OFFSET, 2)
fun setPadding(buf: ByteArray, headerStartOffset: Int, hasPadding: Boolean) =
buf.putBitAsBoolean(headerStartOffset + PADDING_OFFSET, 2, hasPadding)
fun getReportCount(buf: ByteArray, headerStartOffset: Int): Int =
buf.getBitsAsInt(headerStartOffset + REPORT_COUNT_OFFSET, 3, 5)
fun setReportCount(buf: ByteArray, headerStartOffset: Int, reportCount: Int) =
buf.putNumberAsBits(headerStartOffset + REPORT_COUNT_OFFSET, 3, 5, reportCount)
fun getPacketType(buf: ByteArray, headerStartOffset: Int): Int =
buf.getByteAsInt(headerStartOffset + PACKET_TYPE_OFFSET)
fun setPacketType(buf: ByteArray, headerStartOffset: Int, packetType: Int) =
buf.set(headerStartOffset + PACKET_TYPE_OFFSET, packetType.toByte())
// TODO document (bytes or words?)
fun getLength(buf: ByteArray, headerStartOffset: Int): Int =
buf.getShortAsInt(headerStartOffset + LENGTH_OFFSET)
fun setLength(buf: ByteArray, headerStartOffset: Int, length: Int) =
buf.putShort(headerStartOffset + LENGTH_OFFSET, length.toShort())
fun getSenderSsrc(buf: ByteArray, headerStartOffset: Int): Long =
buf.getIntAsLong(headerStartOffset + SENDER_SSRC_OFFSET)
fun setSenderSsrc(buf: ByteArray, headerStartOffset: Int, senderSsrc: Long) =
buf.putInt(headerStartOffset + SENDER_SSRC_OFFSET, senderSsrc.toInt())
}
}
data class RtcpHeaderBuilder(
var version: Int = 2,
var hasPadding: Boolean = false,
var reportCount: Int = -1,
var packetType: Int = -1,
var length: Int = -1,
var senderSsrc: Long = 0
) {
fun build(): ByteArray {
val buf = ByteArray(RtcpHeader.SIZE_BYTES)
writeTo(buf, 0)
return buf
}
fun writeTo(buf: ByteArray, offset: Int) {
RtcpHeader.setVersion(buf, offset, version)
RtcpHeader.setPadding(buf, offset, hasPadding)
RtcpHeader.setReportCount(buf, offset, reportCount)
RtcpHeader.setPacketType(buf, offset, packetType)
RtcpHeader.setLength(buf, offset, length)
RtcpHeader.setSenderSsrc(buf, offset, senderSsrc)
}
}
| apache-2.0 | 715d5bbb2b3fc8ac8cd1274fee467ba4 | 42.521739 | 91 | 0.646154 | 3.904056 | false | false | false | false |
JackParisi/DroidBox | droidbox/src/main/java/com/github/giacomoparisi/droidbox/logs/CrashReportingTree.kt | 1 | 912 | package com.github.giacomoparisi.droidbox.logs
import android.util.Log
import com.google.firebase.crash.FirebaseCrash
import timber.log.Timber
/**
* Created by Giacomo Parisi on 30/06/2017.
* https://github.com/giacomoParisi
*/
class CrashReportingTree : Timber.Tree() {
/**
*
* Send the exception to Firebase after the priority is not VERBOSE or DEBUG
*
* @param priority The priority value of the exception
* @param tag The tag of the exception
* @param message The error message of the exception
* @param t The exception that need to be analyzed
*/
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
if (priority == Log.VERBOSE || priority == Log.DEBUG) {
return
}
FirebaseCrash.logcat(priority, tag, message)
if (t != null) {
FirebaseCrash.report(t)
}
}
} | apache-2.0 | e9c28f84b9864028afc452f6e18384a9 | 26.666667 | 83 | 0.645833 | 4.126697 | false | false | false | false |
vmmaldonadoz/android-reddit-example | Reddit/app/src/main/java/com/thirdmono/reddit/presentation/details/DetailsActivity.kt | 1 | 4417 | package com.thirdmono.reddit.presentation.details
import android.graphics.Color
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.v4.content.ContextCompat
import com.squareup.picasso.Picasso
import com.thirdmono.reddit.R
import com.thirdmono.reddit.data.entity.SubReddit
import com.thirdmono.reddit.data.entity.Thing
import com.thirdmono.reddit.databinding.ActivityDetailsBinding
import com.thirdmono.reddit.domain.utils.Constants
import com.thirdmono.reddit.domain.utils.Utils
import com.thirdmono.reddit.ifNotNullOrBlank
import com.thirdmono.reddit.presentation.BaseActivity
import timber.log.Timber
import java.util.*
class DetailsActivity : BaseActivity() {
lateinit var title: String
private var thing: Thing? = null
private var subReddit: SubReddit? = null
lateinit var binding: ActivityDetailsBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDetailsBinding.inflate(layoutInflater)
setContentView(binding.root)
setupToolbar()
showDetail(savedInstanceState)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(Constants.REDDIT_SELECTED_KEY, Utils.toString(thing))
}
private fun showDetail(savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
if (intent != null && intent.getStringExtra(Constants.REDDIT_SELECTED_KEY) != null) {
thing = Utils.valueOf(intent.getStringExtra(Constants.REDDIT_SELECTED_KEY))
}
} else {
thing = Utils.valueOf(savedInstanceState.getString(Constants.REDDIT_SELECTED_KEY, ""))
subReddit = thing!!.data
}
if (thing != null) {
subReddit = thing!!.data
setupDetailHeader()
setupDetailBody()
} else {
Timber.e("showDetail(): Error retrieving the data for the detailed view.")
}
}
private fun setupDetailHeader() {
title = subReddit?.displayName.orEmpty()
binding.subredditName.text = String.format("r/%s", title)
binding.subredditSubscribers.text = String.format(Locale.getDefault(), "%d Subscribers", subReddit?.subscribers)
subReddit?.bannerImg.ifNotNullOrBlank { bannerImage ->
Picasso.with(this)
.load(bannerImage)
.fit()
.centerCrop()
.into(binding.subredditBanner)
}
subReddit?.keyColor.ifNotNullOrBlank { color ->
binding.toolbar.setBackgroundColor(Color.parseColor(color))
binding.subredditBanner.setBackgroundColor(Color.parseColor(color))
}
subReddit?.iconImg.ifNotNullOrBlank { icon ->
Picasso.with(this)
.load(icon)
.fit()
.centerCrop()
.into(binding.subredditIcon)
}
}
private fun setupDetailBody() {
binding.subredditPublicDescription.text = subReddit?.publicDescription.orEmpty()
binding.subredditFullDescription.setMarkDownText(subReddit?.description.orEmpty())
binding.subredditFullDescription.isOpenUrlInBrowser = true
}
private fun setupToolbar() {
setSupportActionBar(binding.toolbar)
binding.toolbar.setNavigationIcon(R.drawable.ic_action_back)
binding.toolbar.setNavigationOnClickListener { onBackPressed() }
binding.toolbarLayout.title = " "
binding.toolbarLayout.setExpandedTitleColor(ContextCompat.getColor(this, android.R.color.transparent))
binding.appBar.addOnOffsetChangedListener(object : AppBarLayout.OnOffsetChangedListener {
var isShow = false
var scrollRange = -1
override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {
if (scrollRange == -1) {
scrollRange = appBarLayout.totalScrollRange
}
if (scrollRange + verticalOffset == 0) {
binding.toolbarLayout.title = title
isShow = true
} else if (isShow) {
binding.toolbarLayout.title = " "
isShow = false
}
}
})
}
}
| apache-2.0 | a4f9b72753dad350adfe10626b992fe0 | 35.808333 | 120 | 0.647046 | 5.013621 | false | false | false | false |
mallowigi/a-file-icon-idea | common/src/main/java/com/mallowigi/config/ConfigurableBase.kt | 1 | 3779 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015-2022 Elior "Mallowigi" Boukhobza
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mallowigi.config
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.options.BaseConfigurable
import com.intellij.openapi.options.ConfigurationException
import com.intellij.util.ui.UIUtil
import com.mallowigi.config.ui.SettingsFormUI
import javax.swing.JComponent
/**
* Configurable base
*
* @param FORM
* @param CONFIG
*/
@Suppress("OutdatedDocumentation")
abstract class ConfigurableBase<FORM : SettingsFormUI?, CONFIG : PersistentStateComponent<*>?> :
BaseConfigurable() {
/** Return the created form. */
@Volatile
private var form: FORM? = null
/** Returns the config object for this setting. */
protected abstract val config: CONFIG
/** Apply settings. */
@Throws(ConfigurationException::class)
override fun apply() {
initComponent()
doApply(form, config)
}
/**
* Creates the component and link it to a config
*
* @return the created component
*/
override fun createComponent(): JComponent? {
initComponent()
setFormState(form, config)
return (form ?: return null).content
}
/** Dispose the FORM on dispose. */
@Synchronized
override fun disposeUIResources() {
dispose()
form?.dispose()
form = null
}
/**
* Used to disable the apply button
*
* @return true if modified
*/
override fun isModified(): Boolean {
isModified = checkModified(form, config)
return super.isModified()
}
/** Reset settings. */
override fun reset() {
initComponent()
setFormState(form, config)
}
/**
* Checks whether the user has modified the settings
*
* @param form the form
* @param config the config
* @return true if modified
*/
protected abstract fun checkModified(form: FORM?, config: CONFIG): Boolean
/** Create the Form UI for the settings. */
protected abstract fun createForm(): FORM
/**
* Called when applying settings
*
* @param form the form
* @param config the config
*/
@Throws(ConfigurationException::class)
protected abstract fun doApply(form: FORM?, config: CONFIG)
/**
* Link a form to a config
*
* @param form the form
* @param config the config
*/
protected abstract fun setFormState(form: FORM?, config: CONFIG)
/** Dispose resources. */
private fun dispose() {
// Do nothing
}
/** Creates the component with Swing. */
@Synchronized
private fun initComponent() {
if (form == null) {
form = UIUtil.invokeAndWaitIfNeeded<FORM> {
val form = createForm()
form!!.init()
form
}
}
}
}
| mit | 4a06104b9fb46077147dfea4dc80d3d4 | 26.384058 | 96 | 0.693305 | 4.378911 | false | true | false | false |
sklegg/twserver | src/main/kotlin/sklegg/gameobjects/ships/EscapePod.kt | 1 | 2487 | package sklegg.gameobjects.ships
import sklegg.gameobjects.ships.AbstractShip
/**
* Created by scott on 12/20/16.
* Escape pod ship
*/
class EscapePod(shipName: String) : AbstractShip() {
/* what are initial values for new ships? */
/* move to constructor? */
override var shipName: String = ""
override var manufacturer: String = ""
override var atomicDetonators: Int = 0
override var markerBeacons: Int = 0
override var corbomite: Int = 0
override var cloakingDevices: Int = 0
override var armidMines: Int = 0
override var etherProbes: Int = 0
override var limpitMines: Int = 0
override var photonMissiles: Int = 0
override var hasPlanetScanner: Boolean = false
override var numFighters: Int = 0
override var numHolds: Int = 0
override var numGenesisTorpedoes: Int = 0
override var numMineDisruptors: Int = 0
override var numShields: Int = 0
override var hasTranswarpDrive: Boolean = false
override var hasPsychicProbe: Boolean = false
override val shipType: String
get() = "Escape Pod"
override val purchaseCost: Int
get() = 0
override val maxAtomicDetonators: Int
get() = 5
override val maxMarkerBeacons: Int
get() = 0
override val maxCorbomite: Int
get() = 1500
override val maxCloaking: Int
get() = 5
override val maxArmidMines: Int
get() = 0
override val maxEtherProbes: Int
get() = 25
override val maxLimpitMines: Int
get() = 0
override val maxPhotonMissiles: Int
get() = 0
override val planetScanner: Boolean
get() = false
override val turnsPerWarp: Int
get() = 6
override val defensiveShipOdds: Int
get() = 8
override val longRangeScanner: String
get() = "Holo"
override val maxFighters: Int
get() = 50
override val maxFightersPerAttack: Int
get() = 10
override val maxGenesisTorpedoes: Int
get() = 0
override val maxHolds: Int
get() = 5
override val maxMineDisrupters: Int
get() = 10
override val maxShields: Int
get() = 50
override val offensiveShipOdds: Int
get() = 8
override val psychicProbe: Boolean
get() = false
override val shipValue: String
get() = "Low"
override val transportRange: Int
get() = 0
override val transwarpDrive: Boolean
get() = false
} | mit | 706ca6bc57816bce4e8adb22a6c7d668 | 21.214286 | 52 | 0.631685 | 4.083744 | false | false | false | false |
Ekito/koin | koin-projects/koin-core/src/test/java/org/koin/core/ScopeAPITest.kt | 1 | 3144 | package org.koin.core
import org.junit.Assert.*
import org.junit.Test
import org.koin.Simple
import org.koin.core.error.NoScopeDefFoundException
import org.koin.core.error.ScopeAlreadyCreatedException
import org.koin.core.qualifier.named
import org.koin.core.scope.Scope
import org.koin.core.scope.ScopeCallback
import org.koin.dsl.koinApplication
import org.koin.dsl.module
class ScopeAPITest {
val scopeKey = named("KEY")
val koin = koinApplication {
modules(
module {
scope(scopeKey) {
scoped { A() }
}
}
)
}.koin
@Test
fun `create a scope instance`() {
val scopeId = "myScope"
val scope1 = koin.createScope(scopeId, scopeKey)
val scope2 = koin.getScope(scopeId)
assertEquals(scope1, scope2)
}
@Test
fun `can't find a non created scope instance`() {
val scopeId = "myScope"
try {
koin.getScope(scopeId)
fail()
} catch (e: Exception) {
e.printStackTrace()
}
}
@Test
fun `create different scopes`() {
val scope1 = koin.createScope("myScope1", scopeKey)
val scope2 = koin.createScope("myScope2", scopeKey)
assertNotEquals(scope1, scope2)
}
@Test
fun `can't create scope instance with unknown scope def`() {
try {
koin.createScope("myScope", named("a_scope"))
fail()
} catch (e: NoScopeDefFoundException) {
e.printStackTrace()
}
}
@Test
fun `create scope instance with scope def`() {
assertNotNull(koin.createScope("myScope", scopeKey))
}
@Test
fun `can't create a new scope if not closed`() {
koin.createScope("myScope1", scopeKey)
try {
koin.createScope("myScope1", scopeKey)
fail()
} catch (e: ScopeAlreadyCreatedException) {
e.printStackTrace()
}
}
@Test
fun `can't get a closed scope`() {
val scope = koin.createScope("myScope1", scopeKey)
scope.close()
try {
koin.getScope("myScope1")
fail()
} catch (e: Exception) {
e.printStackTrace()
}
}
@Test
fun `reuse a closed scope`() {
val scope = koin.createScope("myScope1", scopeKey)
scope.close()
try {
scope.get<Simple.ComponentA>()
fail()
} catch (e: Exception) {
e.printStackTrace()
}
}
@Test
fun `find a scope by id`() {
val scopeId = "myScope"
val scope1 = koin.createScope(scopeId, scopeKey)
assertEquals(scope1, koin.getScope(scope1.id))
}
@Test
fun `scope callback`() {
val scopeId = "myScope"
val scope1 = koin.createScope(scopeId, scopeKey)
var closed = false
scope1.registerCallback(object : ScopeCallback {
override fun onScopeClose(scope: Scope) {
closed = true
}
})
scope1.close()
assertTrue(closed)
}
}
| apache-2.0 | bc27f7ef9779699fedfaab59fbdf8ab3 | 23.372093 | 64 | 0.556934 | 4.214477 | false | true | false | false |
Reyurnible/gitsalad-android | app/src/main/kotlin/com/hosshan/android/salad/repository/github/StarringRepository.kt | 1 | 844 | package com.hosshan.android.salad.repository.github
import com.hosshan.android.salad.repository.github.entity.Repository
import com.hosshan.android.salad.repository.github.entity.User
import com.hosshan.android.salad.repository.github.service.StarringService
import rx.Observable
/**
* StarringRepository
*/
class StarringRepository(private val service: StarringService) {
fun stargazers(owner: String,
repository: String): Observable<List<User>> = service.stargazers(owner, repository)
fun starred(sort: String? = null,
direction: String? = null): Observable<Repository> = service.starred(sort, direction)
fun starred(username: String,
sort: String? = null,
direction: String? = null): Observable<Repository> = service.starred(username, sort, direction)
}
| mit | 42d096e225d9d921380cff33f51350e3 | 35.695652 | 111 | 0.720379 | 4.22 | false | false | false | false |
google/ksp | compiler-plugin/src/main/kotlin/com/google/devtools/ksp/processing/impl/JvmUtils.kt | 1 | 1234 | /*
* Copyright 2021 Google LLC
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.processing.impl
internal val JVM_STATIC_ANNOTATION_FQN = "kotlin.jvm.JvmStatic"
internal val JVM_DEFAULT_ANNOTATION_FQN = "kotlin.jvm.JvmDefault"
internal val JVM_DEFAULT_WITHOUT_COMPATIBILITY_ANNOTATION_FQN = "kotlin.jvm.JvmDefaultWithoutCompatibility"
internal val JVM_STRICTFP_ANNOTATION_FQN = "kotlin.jvm.Strictfp"
internal val JVM_SYNCHRONIZED_ANNOTATION_FQN = "kotlin.jvm.Synchronized"
internal val JVM_TRANSIENT_ANNOTATION_FQN = "kotlin.jvm.Transient"
internal val JVM_VOLATILE_ANNOTATION_FQN = "kotlin.jvm.Volatile"
| apache-2.0 | e3778756df984916379ee0cd31459058 | 46.461538 | 107 | 0.780389 | 3.993528 | false | false | false | false |
AllanWang/Frost-for-Facebook | app/src/main/kotlin/com/pitchedapps/frost/web/FrostWebViewClients2.kt | 1 | 5541 | /*
* Copyright 2018 Allan Wang
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pitchedapps.frost.web
import android.graphics.Bitmap
import android.graphics.Color
import android.webkit.WebResourceRequest
import android.webkit.WebView
import ca.allanwang.kau.utils.withAlpha
import com.pitchedapps.frost.enums.ThemeCategory
import com.pitchedapps.frost.injectors.JsActions
import com.pitchedapps.frost.injectors.JsAssets
import com.pitchedapps.frost.injectors.jsInject
import com.pitchedapps.frost.utils.L
import com.pitchedapps.frost.utils.isFacebookUrl
import com.pitchedapps.frost.utils.isMessengerUrl
import com.pitchedapps.frost.utils.launchImageActivity
import com.pitchedapps.frost.views.FrostWebView
import dagger.Binds
import dagger.Module
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import javax.inject.Inject
import javax.inject.Qualifier
/**
* Created by Allan Wang on 2017-05-31.
*
* Collection of webview clients
*/
@Qualifier @Retention(AnnotationRetention.BINARY) annotation class FrostWebClient
@EntryPoint
@InstallIn(FrostWebComponent::class)
interface FrostWebClientEntryPoint {
@FrostWebScoped @FrostWebClient fun webClient(): FrostWebViewClient
}
@Module
@InstallIn(FrostWebComponent::class)
interface FrostWebViewClientModule {
@Binds @FrostWebClient fun webClient(binds: FrostWebViewClient2): FrostWebViewClient
}
/** The default webview client */
open class FrostWebViewClient2
@Inject
constructor(web: FrostWebView, @FrostRefresh private val refreshEmit: FrostEmitter<Boolean>) :
FrostWebViewClient(web) {
init {
L.i { "Refresh web client 2" }
}
override fun doUpdateVisitedHistory(view: WebView, url: String?, isReload: Boolean) {
super.doUpdateVisitedHistory(view, url, isReload)
urlSupportsRefresh = urlSupportsRefresh(url)
web.parent.swipeAllowedByPage = urlSupportsRefresh
view.jsInject(JsAssets.AUTO_RESIZE_TEXTAREA.maybe(prefs.autoExpandTextBox), prefs = prefs)
v { "History $url; refresh $urlSupportsRefresh" }
}
private fun urlSupportsRefresh(url: String?): Boolean {
if (url == null) return false
if (url.isMessengerUrl) return false
if (!url.isFacebookUrl) return true
if (url.contains("soft=composer")) return false
if (url.contains("sharer.php") || url.contains("sharer-dialog.php")) return false
return true
}
private fun WebView.facebookJsInject() {
jsInject(*facebookJsInjectors.toTypedArray(), prefs = prefs)
}
private fun WebView.messengerJsInject() {
jsInject(themeProvider.injector(ThemeCategory.MESSENGER), prefs = prefs)
}
override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
if (url == null) return
v { "loading $url ${web.settings.userAgentString}" }
refreshEmit(true)
}
private fun injectBackgroundColor() {
web.setBackgroundColor(
when {
isMain -> Color.TRANSPARENT
web.url.isFacebookUrl -> themeProvider.bgColor.withAlpha(255)
else -> Color.WHITE
}
)
}
override fun onPageCommitVisible(view: WebView, url: String?) {
super.onPageCommitVisible(view, url)
injectBackgroundColor()
when {
url.isFacebookUrl -> {
v { "FB Page commit visible" }
view.facebookJsInject()
}
url.isMessengerUrl -> {
v { "Messenger Page commit visible" }
view.messengerJsInject()
}
else -> {
refreshEmit(false)
}
}
}
override fun onPageFinished(view: WebView, url: String?) {
url ?: return
v { "finished $url" }
if (!url.isFacebookUrl && !url.isMessengerUrl) {
refreshEmit(false)
return
}
onPageFinishedActions(url)
}
internal override fun injectAndFinish() {
v { "page finished reveal" }
refreshEmit(false)
injectBackgroundColor()
when {
web.url.isFacebookUrl -> {
web.jsInject(
JsActions.LOGIN_CHECK,
JsAssets.TEXTAREA_LISTENER,
JsAssets.HEADER_BADGES.maybe(isMain),
prefs = prefs
)
web.facebookJsInject()
}
web.url.isMessengerUrl -> {
web.messengerJsInject()
}
}
}
/**
* Helper to format the request and launch it returns true to override the url returns false if we
* are already in an overlaying activity
*/
private fun launchRequest(request: WebResourceRequest): Boolean {
v { "Launching url: ${request.url}" }
return web.requestWebOverlay(request.url.toString())
}
private fun launchImage(url: String, text: String? = null, cookie: String? = null): Boolean {
v { "Launching image: $url" }
web.context.launchImageActivity(url, text, cookie)
if (web.canGoBack()) web.goBack()
return true
}
}
private const val EMIT_THEME = 0b1
private const val EMIT_ID = 0b10
private const val EMIT_COMPLETE = EMIT_THEME or EMIT_ID
private const val EMIT_FINISH = 0
| gpl-3.0 | c029fdc5dccc9474948419fb6a372912 | 29.783333 | 100 | 0.715394 | 3.986331 | false | false | false | false |
Shynixn/BlockBall | blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/commandmenu/GameSettingsPage.kt | 1 | 14161 | package com.github.shynixn.blockball.core.logic.business.commandmenu
import com.github.shynixn.blockball.api.business.enumeration.*
import com.github.shynixn.blockball.api.business.service.ProxyService
import com.github.shynixn.blockball.api.persistence.entity.Arena
import com.github.shynixn.blockball.api.persistence.entity.ChatBuilder
import com.github.shynixn.blockball.core.logic.persistence.entity.ChatBuilderEntity
import com.google.inject.Inject
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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 OTHERwwt
* 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.
*/
class GameSettingsPage @Inject constructor(private val proxyService: ProxyService) :
Page(ID, MainSettingsPage.ID) {
companion object {
/** Id of the page. */
const val ID = 29
}
/**
* Returns the key of the command when this page should be executed.
*
* @return key
*/
override fun getCommandKey(): MenuPageKey {
return MenuPageKey.GAMESETTINGS
}
/**
* Executes actions for this page.
*
* @param cache cache
*/
override fun <P> execute(
player: P,
command: MenuCommand,
cache: Array<Any?>,
args: Array<String>
): MenuCommandResult {
val arena = cache[0] as Arena
if (command == MenuCommand.GAMESETTINGS_LEAVESPAWNPOINT) {
arena.meta.lobbyMeta.leaveSpawnpoint =
proxyService.toPosition(proxyService.getEntityLocation<Any, P>(player))
} else if (command == MenuCommand.GAMESETTINGS_LOBBYSPAWNPOINT) {
arena.meta.minigameMeta.lobbySpawnpoint =
proxyService.toPosition(proxyService.getEntityLocation<Any, P>(player))
} else if (command == MenuCommand.GAMESETTINGS_TOGGLE_EVENTEAMS) {
arena.meta.lobbyMeta.onlyAllowEventTeams = !arena.meta.lobbyMeta.onlyAllowEventTeams
} else if (command == MenuCommand.GAMESETTINGS_TOGGLE_INSTATFORCEFIELD) {
arena.meta.hubLobbyMeta.instantForcefieldJoin = !arena.meta.hubLobbyMeta.instantForcefieldJoin
} else if (command == MenuCommand.GAMESETTINGS_TOGGLE_RESETEMPTY) {
arena.meta.hubLobbyMeta.resetArenaOnEmpty = !arena.meta.hubLobbyMeta.resetArenaOnEmpty
} else if (command == MenuCommand.GAMESETTINGS_BUNGEEKICKMESSAGE && args.size >= 3) {
arena.meta.bungeeCordMeta.kickMessage = mergeArgs(2, args)
} else if (command == MenuCommand.GAMESETTINGS_BUNGEELEAVEKICKMESSAGE && args.size >= 3) {
arena.meta.bungeeCordMeta.leaveKickMessage = mergeArgs(2, args)
} else if (command == MenuCommand.GAMESETTINGS_BUNGEEFALLBACKSERVER && args.size >= 3) {
arena.meta.bungeeCordMeta.fallbackServer = mergeArgs(2, args)
} else if (command == MenuCommand.GAMESETTINGS_MAXSCORE && args.size == 3 && args[2].toIntOrNull() != null) {
arena.meta.lobbyMeta.maxScore = args[2].toInt()
} else if (command == MenuCommand.GAMESETTINGS_LOBBYDURATION && args.size == 3 && args[2].toIntOrNull() != null) {
arena.meta.minigameMeta.lobbyDuration = args[2].toInt()
} else if (command == MenuCommand.GAMESETTINGS_CALLBACK_BUKKITGAMEMODES && args.size == 3 && args[2].toIntOrNull() != null) {
arena.meta.lobbyMeta.gamemode = GameMode.values()[args[2].toInt()]
} else if (command == MenuCommand.GAMESETTINGS_REMAININGPLAYERSMESSAGE && args.size > 3) {
arena.meta.minigameMeta.playersRequiredToStartMessage = mergeArgs(2, args)
} else if (command == MenuCommand.GAMESETTINGS_TOGGLE_TELEPORTONJOIN) {
arena.meta.hubLobbyMeta.teleportOnJoin = !arena.meta.hubLobbyMeta.teleportOnJoin
if (!arena.meta.hubLobbyMeta.teleportOnJoin) {
arena.meta.hubLobbyMeta.instantForcefieldJoin = true
}
}
return super.execute(player, command, cache, args)
}
/**
* Builds the page content.
*
* @param cache cache
* @return content
*/
override fun buildPage(cache: Array<Any?>): ChatBuilder {
val arena = cache[0] as Arena
var leaveSpawnpoint = "none"
if (arena.meta.lobbyMeta.leaveSpawnpoint != null) {
leaveSpawnpoint = arena.meta.lobbyMeta.leaveSpawnpoint!!.toString()
}
var lobbySpawnpoint = "none"
if (arena.meta.minigameMeta.lobbySpawnpoint != null) {
lobbySpawnpoint = arena.meta.minigameMeta.lobbySpawnpoint!!.toString()
}
val builder = ChatBuilderEntity()
.component("- Max Score: " + arena.meta.lobbyMeta.maxScore).builder()
.component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color)
.setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.GAMESETTINGS_MAXSCORE.command)
.setHoverText("Amount of goals a team has to score in order to win.")
.builder().nextLine()
.component("- Leave Spawnpoint: $leaveSpawnpoint").builder()
.component(MenuClickableItem.LOCATION.text).setColor(MenuClickableItem.LOCATION.color)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.GAMESETTINGS_LEAVESPAWNPOINT.command)
.setHoverText("Sets the spawnpoint for people who leave the match.")
.builder().nextLine()
.component("- Gamemode: " + arena.meta.lobbyMeta.gamemode.name).builder()
.component(MenuClickableItem.SELECT.text).setColor(MenuClickableItem.SELECT.color)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.LIST_BUKKITGAMESMODES.command)
.setHoverText("Minecraft gamemode (Survival, Adventure, Creative) the players will be inside of a game.")
.builder().nextLine()
.component("- Even teams enabled: " + arena.meta.lobbyMeta.onlyAllowEventTeams).builder()
.component(MenuClickableItem.TOGGLE.text).setColor(MenuClickableItem.TOGGLE.color)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.GAMESETTINGS_TOGGLE_EVENTEAMS.command)
.setHoverText("Forces players to join the other team regardless of their choice to have the same amount of players on both teams.")
.builder().nextLine()
if (arena.gameType == GameType.MINIGAME || arena.gameType == GameType.BUNGEE) {
builder.component("- Match Times:").builder()
.component(" [page..]").setColor(ChatColor.YELLOW)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.MATCHTIMES_OPEN.command)
.setHoverText("Opens the match times page.").builder().nextLine()
builder.component("- Lobby Duration: " + arena.meta.minigameMeta.lobbyDuration).builder()
.component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color)
.setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.GAMESETTINGS_LOBBYDURATION.command)
.setHoverText("Amount of seconds until a lobby is going to start when it reached its min amount of red and blue players.")
.builder().nextLine()
.component("- Lobby Spawnpoint: $lobbySpawnpoint").builder()
.component(MenuClickableItem.LOCATION.text).setColor(MenuClickableItem.LOCATION.color)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.GAMESETTINGS_LOBBYSPAWNPOINT.command)
.setHoverText("Sets the spawnpoint for people who join the lobby.")
.builder().nextLine()
builder.component("- Remaining Players Message:").builder()
.component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color)
.setHoverText(arena.meta.minigameMeta.playersRequiredToStartMessage).builder()
.component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color)
.setClickAction(
ChatClickAction.SUGGEST_COMMAND,
MenuCommand.GAMESETTINGS_REMAININGPLAYERSMESSAGE.command
)
.setHoverText(ChatColor.UNDERLINE.toString() + "Minigame exclusive\n" + ChatColor.RESET + "Message being send to the action bar of players who wait for more players in the lobby.")
.builder().nextLine()
}
if (arena.gameType == GameType.BUNGEE) {
builder.component("- Full Server Kick Message: ").builder()
.component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color)
.setHoverText(arena.meta.bungeeCordMeta.kickMessage)
.builder()
.component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color)
.setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.GAMESETTINGS_BUNGEEKICKMESSAGE.command)
.setHoverText(ChatColor.UNDERLINE.toString() + "BungeeCord exclusive\n" + ChatColor.RESET + "Message being send to players who try to join a running or a full server.")
.builder().nextLine()
builder.component("- Leave Server Kick Message: ").builder()
.component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color)
.setHoverText(arena.meta.bungeeCordMeta.leaveKickMessage)
.builder()
.component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color)
.setClickAction(
ChatClickAction.SUGGEST_COMMAND,
MenuCommand.GAMESETTINGS_BUNGEELEAVEKICKMESSAGE.command
)
.setHoverText(ChatColor.UNDERLINE.toString() + "BungeeCord exclusive\n" + ChatColor.RESET + "Message being send to players who leave a game. Can be used with third party BungeeCord plugins to determine the fallback servers.")
.builder().nextLine()
builder.component("- Fallback Server: ").builder()
.component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color)
.setHoverText(arena.meta.bungeeCordMeta.fallbackServer)
.builder()
.component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color)
.setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.GAMESETTINGS_BUNGEEFALLBACKSERVER.command)
.setHoverText(ChatColor.UNDERLINE.toString() + "BungeeCord exclusive\n" + ChatColor.RESET + "Fallback server when a player leaves the match.")
.builder().nextLine()
} else if (arena.gameType == GameType.HUBGAME) {
builder.component("- Join Message: ").builder()
.component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color)
.setHoverText(arena.meta.hubLobbyMeta.joinMessage.toSingleLine()).builder()
.component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.MULTILINES_HUBGAMEJOINMESSAGE.command)
.setHoverText(ChatColor.UNDERLINE.toString() + "HubGame exclusive\n" + ChatColor.RESET + "Message being send to players who touch the forcefield.")
.builder().nextLine()
.component("- Reset on empty: " + arena.meta.hubLobbyMeta.resetArenaOnEmpty).builder()
.component(MenuClickableItem.TOGGLE.text).setColor(MenuClickableItem.TOGGLE.color)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.GAMESETTINGS_TOGGLE_RESETEMPTY.command)
.setHoverText(ChatColor.UNDERLINE.toString() + "HubGame exclusive\n" + ChatColor.RESET + "Should the HubGame game be reset to it's starting stage when everyone has left the game?")
.builder().nextLine()
.component("- Teleport on join: " + arena.meta.hubLobbyMeta.teleportOnJoin).builder()
.component(MenuClickableItem.TOGGLE.text).setColor(MenuClickableItem.TOGGLE.color)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.GAMESETTINGS_TOGGLE_TELEPORTONJOIN.command)
.setHoverText(ChatColor.UNDERLINE.toString() + "HubGame exclusive\n" + ChatColor.RESET + "Should players be teleported to the spawnpoint on join? Automatically enables instant forcefield join when being disabled.")
.builder().nextLine()
.component("- Instant forcefield join: " + arena.meta.hubLobbyMeta.instantForcefieldJoin).builder()
.component(MenuClickableItem.TOGGLE.text).setColor(MenuClickableItem.TOGGLE.color)
.setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.GAMESETTINGS_TOGGLE_INSTATFORCEFIELD.command)
.setHoverText(ChatColor.UNDERLINE.toString() + "HubGame exclusive\n" + ChatColor.RESET + "Should players join the game immediately after running into the forcefield? Teams get automatically selected.")
.builder().nextLine()
}
return builder
}
} | apache-2.0 | f902f6894ea33ed11e4836228c2c21bf | 62.506726 | 241 | 0.678977 | 4.55045 | false | false | false | false |
beyama/winter | winter-compiler/src/main/java/io/jentz/winter/compiler/model/InjectTargetModel.kt | 1 | 4620 | package io.jentz.winter.compiler.model
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.asTypeName
import com.squareup.kotlinpoet.metadata.ImmutableKmClass
import com.squareup.kotlinpoet.metadata.ImmutableKmProperty
import com.squareup.kotlinpoet.metadata.KotlinPoetMetadataPreview
import com.squareup.kotlinpoet.metadata.isNullable
import io.jentz.winter.compiler.*
import javax.lang.model.element.*
import javax.lang.model.util.ElementFilter
data class InjectTargetModel(
val originatingElement: Element,
val targetName: String,
val targetTypeName: TypeName,
val isNullable: Boolean,
val qualifier: String?,
val targetType: TargetType,
val fqdn: String
) {
enum class TargetType { Field, Method, Property }
companion object {
@KotlinPoetMetadataPreview
fun forElement(originatingElement: Element, kmClass: ImmutableKmClass?): InjectTargetModel {
val typeElement: TypeElement = originatingElement.enclosingElement as TypeElement
val fqdn = "${typeElement.qualifiedName}.${originatingElement.simpleName}"
val variableElement: VariableElement
val targetName: String
val targetType: TargetType
val kmProperty: ImmutableKmProperty?
val qualifier: String?
when (originatingElement.kind) {
ElementKind.FIELD -> {
variableElement = originatingElement as VariableElement
kmProperty = kmClass
?.properties
?.find { it.fieldSignature?.name == variableElement.simpleName.toString() }
?.takeIf { it.hasAccessibleSetter }
targetName = kmProperty?.name ?: variableElement.simpleName.toString()
val propertyQualifier = kmProperty?.let { getPropertyQualifier(it, typeElement) }
qualifier = propertyQualifier ?: variableElement.qualifier
targetType = if (kmProperty == null) TargetType.Field else TargetType.Property
}
ElementKind.METHOD -> {
val setter = originatingElement as ExecutableElement
require(setter.parameters.size == 1) {
"Setter for setter injection must have exactly one parameter not " +
"${originatingElement.parameters.size} ($fqdn)."
}
variableElement = setter.parameters.first()
kmProperty = kmClass
?.properties
?.find { it.setterSignature?.name == setter.simpleName.toString() }
?.takeIf { it.hasAccessibleSetter }
targetName = kmProperty?.name ?: setter.simpleName.toString()
val argumentQualifier = setter.parameters.first().qualifier
val propertyQualifier = kmProperty?.let { getPropertyQualifier(it, typeElement) }
qualifier = propertyQualifier ?: argumentQualifier ?: setter.qualifier
targetType = if (kmProperty == null) TargetType.Method else TargetType.Property
}
else -> error("BUG: Unexpected element kind `${originatingElement.kind}`.")
}
require(!originatingElement.isPrivate || kmProperty?.hasAccessibleSetter == true) {
"Cannot inject into private fields or properties ($fqdn)."
}
val targetTypeName = kmProperty?.returnType?.asTypeName()
?: variableElement.asType().asTypeName().kotlinTypeName
return InjectTargetModel(
originatingElement = originatingElement,
targetName = targetName,
targetTypeName = targetTypeName,
isNullable = kmProperty?.returnType?.isNullable ?: variableElement.isNullable,
qualifier = qualifier,
targetType = targetType,
fqdn = fqdn
)
}
@KotlinPoetMetadataPreview
private fun getPropertyQualifier(
kmProperty: ImmutableKmProperty,
typeElement: TypeElement
): String? {
return kmProperty
.syntheticMethodForAnnotations
?.let { signature ->
ElementFilter
.methodsIn(typeElement.enclosedElements)
.find { it.simpleName.contentEquals(signature.name) }
}?.qualifier
}
}
}
| apache-2.0 | 66031b26ff7537dd51a107e8d0fdc0eb | 38.827586 | 101 | 0.601948 | 5.992218 | false | false | false | false |
komu/siilinkari | src/main/kotlin/siilinkari/ast/RelationalOp.kt | 1 | 251 | package siilinkari.ast
enum class RelationalOp(private val repr: String) {
Equals("=="),
NotEquals("!="),
LessThan("<"),
LessThanOrEqual("<="),
GreaterThan(">"),
GreaterThanOrEqual(">=");
override fun toString() = repr
}
| mit | 46f72f0bce24a495fddaad3e80c08cb9 | 19.916667 | 51 | 0.601594 | 4.183333 | false | false | false | false |
jtlalka/fiszki | app/src/main/kotlin/net/tlalka/fiszki/view/adapters/TestsAdapter.kt | 1 | 1453 | package net.tlalka.fiszki.view.adapters
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import net.tlalka.fiszki.R
import net.tlalka.fiszki.model.entities.Lesson
class TestsAdapter(context: Context, elements: List<Lesson>) : AbstractAdapter<Lesson>(context, elements) {
override fun getView(position: Int, convertView: View?, viewGroup: ViewGroup?): View {
val itemView = super.getItemView(convertView, viewGroup, R.layout.test_list_item)
itemView.tag = itemView.tag ?: ViewHolderPattern(itemView)
val lesson = super.getItem(position)
val viewHolderPattern = itemView.tag as ViewHolderPattern
viewHolderPattern.score.text = getString(R.string.test_score_value, lesson.score)
viewHolderPattern.name.text = getString(R.string.list_item, position + 1, lesson.name)
viewHolderPattern.desc.text = lesson.levelType.name
return itemView
}
private class ViewHolderPattern(view: View) {
val icon: ImageView = view.findViewById<View>(R.id.test_list_icon) as ImageView
val score: TextView = view.findViewById<View>(R.id.test_list_score) as TextView
val name: TextView = view.findViewById<View>(R.id.test_list_name) as TextView
val desc: TextView = view.findViewById<View>(R.id.test_list_desc) as TextView
}
}
| mit | e1fd6a0a5f17e364a50616df9bca64c2 | 40.735294 | 107 | 0.717137 | 4.036111 | false | true | false | false |
Jonatino/Vision | src/main/kotlin/org/anglur/vision/util/extensions/ThreadExtensions.kt | 1 | 1411 | /*
* Vision - free remote desktop software built with Kotlin
* Copyright (C) 2016 Jonathan Beaudoin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.anglur.vision.util.extensions
import javafx.application.Platform
fun fxThread(start: Boolean = true, isDaemon: Boolean = false, contextClassLoader: ClassLoader? = null, name: String? = null, priority: Int = -1, block: () -> Unit): Thread {
val thread = object : Thread() {
override fun run() = Platform.runLater {
block()
}
}
if (isDaemon)
thread.isDaemon = true
if (priority > 0)
thread.priority = priority
if (name != null)
thread.name = name
if (contextClassLoader != null)
thread.contextClassLoader = contextClassLoader
if (start)
thread.start()
return thread
} | gpl-3.0 | 3b9e38f03d8a1a97c71972447e1930ce | 33.439024 | 174 | 0.699504 | 3.887052 | false | false | false | false |
outadoc/Twistoast-android | twistoast/src/main/kotlin/fr/outadev/twistoast/ConfigurationManager.kt | 1 | 3245 | /*
* Twistoast - ConfigurationManager.kt
* Copyright (C) 2013-2016 Baptiste Candellier
*
* Twistoast 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.
*
* Twistoast 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 fr.outadev.twistoast
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
/**
* Manages application preferences. Use this to read or write application settings instead
* of directly calling SharedPreferences.get*.
*/
class ConfigurationManager(context: Context = ApplicationTwistoast.instance) {
private val preferences: SharedPreferences
init {
preferences = PreferenceManager.getDefaultSharedPreferences(context)
}
val applicationThemeColor: Int
get() = preferences.getInt("pref_app_theme", -1)
val nightMode: String
get() = preferences.getString("pref_night_mode", "system")
val autoRefresh: Boolean
get() = preferences.getBoolean("pref_auto_refresh", true)
var adsAreRemoved: Boolean
get() = preferences.getBoolean("pref_disable_ads", false)
set(removed) = preferences.edit().putBoolean("pref_disable_ads", removed).apply()
val useColorInPebbleApp: Boolean
get() = preferences.getBoolean("pref_pebble_use_color", true)
val trafficNotificationsEnabled: Boolean
get() = preferences.getBoolean("pref_enable_notif_traffic", true)
val trafficNotificationsRing: Boolean
get() = preferences.getBoolean("pref_notif_traffic_ring", true)
val trafficNotificationsVibrate: Boolean
get() = preferences.getBoolean("pref_notif_traffic_vibrate", true)
val watchNotificationsRing: Boolean
get() = preferences.getBoolean("pref_notif_watched_ring", true)
val watchNotificationsVibrate: Boolean
get() = preferences.getBoolean("pref_notif_watched_vibrate", true)
var lastTrafficNotificationId: Int
get() = preferences.getInt("last_traffic_notif_id", -1)
set(id) = preferences.edit().putInt("last_traffic_notif_id", id).apply()
var listSortOrder: Database.SortBy
get() = stringToSortCriteria(preferences.getString("pref_list_sortby", "line"))
set(sortOrder) = preferences.edit().putString("pref_list_sortby", sortCriteriaToString(sortOrder)).apply()
private fun stringToSortCriteria(sortBy: String): Database.SortBy {
when (sortBy.toLowerCase()) {
"stop" -> return Database.SortBy.STOP
"line" -> return Database.SortBy.LINE
else -> return Database.SortBy.LINE
}
}
private fun sortCriteriaToString(sortBy: Database.SortBy): String {
return sortBy.name.toLowerCase()
}
}
| gpl-3.0 | 02d3f0924d424f62d1c9314fc18ec7c4 | 35.875 | 114 | 0.711864 | 4.457418 | false | false | false | false |
android/architecture-samples | app/src/main/java/com/example/android/architecture/blueprints/todoapp/taskdetail/TaskDetailViewModel.kt | 1 | 4538 | /*
* Copyright (C) 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 com.example.android.architecture.blueprints.todoapp.taskdetail
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.android.architecture.blueprints.todoapp.R
import com.example.android.architecture.blueprints.todoapp.TodoDestinationsArgs
import com.example.android.architecture.blueprints.todoapp.data.Result
import com.example.android.architecture.blueprints.todoapp.data.Result.Success
import com.example.android.architecture.blueprints.todoapp.data.Task
import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository
import com.example.android.architecture.blueprints.todoapp.util.Async
import com.example.android.architecture.blueprints.todoapp.util.WhileUiSubscribed
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* UiState for the Details screen.
*/
data class TaskDetailUiState(
val task: Task? = null,
val isLoading: Boolean = false,
val userMessage: Int? = null,
val isTaskDeleted: Boolean = false
)
/**
* ViewModel for the Details screen.
*/
@HiltViewModel
class TaskDetailViewModel @Inject constructor(
private val tasksRepository: TasksRepository,
savedStateHandle: SavedStateHandle
) : ViewModel() {
val taskId: String = savedStateHandle[TodoDestinationsArgs.TASK_ID_ARG]!!
private val _userMessage: MutableStateFlow<Int?> = MutableStateFlow(null)
private val _isLoading = MutableStateFlow(false)
private val _isTaskDeleted = MutableStateFlow(false)
private val _taskAsync = tasksRepository.getTaskStream(taskId)
.map { handleResult(it) }
.onStart { emit(Async.Loading) }
val uiState: StateFlow<TaskDetailUiState> = combine(
_userMessage, _isLoading, _isTaskDeleted, _taskAsync
) { userMessage, isLoading, isTaskDeleted, taskAsync ->
when (taskAsync) {
Async.Loading -> {
TaskDetailUiState(isLoading = true)
}
is Async.Success -> {
TaskDetailUiState(
task = taskAsync.data,
isLoading = isLoading,
userMessage = userMessage,
isTaskDeleted = isTaskDeleted
)
}
}
}
.stateIn(
scope = viewModelScope,
started = WhileUiSubscribed,
initialValue = TaskDetailUiState(isLoading = true)
)
fun deleteTask() = viewModelScope.launch {
tasksRepository.deleteTask(taskId)
_isTaskDeleted.value = true
}
fun setCompleted(completed: Boolean) = viewModelScope.launch {
val task = uiState.value.task ?: return@launch
if (completed) {
tasksRepository.completeTask(task)
showSnackbarMessage(R.string.task_marked_complete)
} else {
tasksRepository.activateTask(task)
showSnackbarMessage(R.string.task_marked_active)
}
}
fun refresh() {
_isLoading.value = true
viewModelScope.launch {
tasksRepository.refreshTask(taskId)
_isLoading.value = false
}
}
fun snackbarMessageShown() {
_userMessage.value = null
}
private fun showSnackbarMessage(message: Int) {
_userMessage.value = message
}
private fun handleResult(tasksResult: Result<Task>): Async<Task?> =
if (tasksResult is Success) {
Async.Success(tasksResult.data)
} else {
showSnackbarMessage(R.string.loading_tasks_error)
Async.Success(null)
}
}
| apache-2.0 | 5d689b0e0d2f7ffe6662239ec0b51cc7 | 34.178295 | 86 | 0.69502 | 4.673532 | false | false | false | false |
KentVu/vietnamese-t9-ime | lib/src/main/java/com/vutrankien/t9vietnamese/lib/VietnameseWordSeed.kt | 1 | 2247 | /*
* Vietnamese-t9-ime: T9 input method for Vietnamese.
* Copyright (C) 2020 Vu Tran Kien.
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.vutrankien.t9vietnamese.lib
import java.text.Normalizer
object VietnameseWordSeed {
/* 774 0x306 COMBINING BREVE */
private const val BREVE = '̆'
/* 770 0x302 COMBINING CIRCUMFLEX ACCENT */
private const val CIRCUMFLEX_ACCENT = '̂'
/* 795 31B COMBINING HORN */
private const val HORN = '̛'
/* 803 323 COMBINING DOT BELOW */
private const val DOT_BELOW = '̣'
fun getFromJavaResource(): Lazy<Sequence<String>> {
return lazy {
val sortedWords = sortedSetOf<String>() // use String's "natural" ordering
javaClass.classLoader.getResourceAsStream("/vi-DauMoi.dic").bufferedReader().useLines {
it.forEach { line ->
sortedWords.add(line.decomposeVietnamese())
}
}
sortedWords.asSequence()
}
}
fun String.decomposeVietnamese(): String {
return Normalizer.normalize(
this,
Normalizer.Form.NFKD
)
// rearrange intonation and vowel-mark order.
.replace("([eE])$DOT_BELOW$CIRCUMFLEX_ACCENT".toRegex(), "$1$CIRCUMFLEX_ACCENT$DOT_BELOW")
// recombine specific vowels.
.replace(
("([aA][$BREVE$CIRCUMFLEX_ACCENT])|([uUoO]$HORN)|[oOeE]$CIRCUMFLEX_ACCENT").toRegex()
) {
Normalizer.normalize(
it.value,
Normalizer.Form.NFKC
)
}
}
} | gpl-3.0 | 585ada684c244a27d17f3dd19128d87b | 34.0625 | 102 | 0.618814 | 3.97695 | false | false | false | false |
laurencegw/jenjin | jenjin-core/src/main/kotlin/com/binarymonks/jj/core/extensions/collections.kt | 1 | 3581 | package com.binarymonks.jj.core.extensions
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.utils.Array
import com.badlogic.gdx.utils.ObjectMap
import com.badlogic.gdx.utils.ObjectSet
import com.binarymonks.jj.core.Copyable
import com.binarymonks.jj.core.JJ
import com.binarymonks.jj.core.forceCopy
import com.binarymonks.jj.core.pools.newArray
import com.binarymonks.jj.core.pools.newObjectMap
import com.binarymonks.jj.core.pools.recycle
/**
* Copies the map with [Copyable] awareness for values. Uses pooled Object maps via [newObjectMap]
*/
fun <K, V> ObjectMap<K, V>.copy(): ObjectMap<K, V> {
val clone: ObjectMap<K, V> = newObjectMap()
@Suppress("UNCHECKED_CAST")
for (entry in this) {
val value = entry.value
val valueCopy = forceCopy(value) as V
clone.put(entry.key, valueCopy)
}
return clone
}
fun <K, V> ObjectMap<K, V>.recycle() {
JJ.B.pools.recycle(this)
}
/**
* Merges a map into this map. Keys will be overriden by the mergeFrom map.
*
* Returns the original
*/
fun <K, V> ObjectMap<K, V>.merge(mergeFrom: ObjectMap<K, V>): ObjectMap<K, V> {
for (entry in mergeFrom) {
this.put(entry.key, entry.value)
}
return this
}
/**
* Lets you build your maps entries
*/
fun <K, V> ObjectMap<K, V>.build(builder: ObjectMap<K, V>.() -> Unit): ObjectMap<K, V> {
this.builder()
return this
}
/**
* Copies the array with [Copyable] awareness for values
*/
fun <T> Array<T>.copy(): Array<T> {
val clone: Array<T> = Array()
@Suppress("UNCHECKED_CAST")
this.forEach {
val valueCopy = forceCopy(it) as T
clone.add(valueCopy)
}
return clone
}
/**
* Lets you build your array
*/
fun <T> Array<T>.build(builder: Array<T>.() -> Unit): Array<T> {
this.builder()
return this
}
fun <T> Array<T>.addVar(vararg add: T): Array<T> {
add.forEach { this.add(it) }
return this
}
fun <T> Array<T>.addAll(objectSet: ObjectSet<T>): Array<T> {
objectSet.forEach { this.add(it) }
return this
}
/**
* Copies the set with [Copyable] awareness for values
*/
fun <T> ObjectSet<T>.copy(): ObjectSet<T> {
val clone: ObjectSet<T> = ObjectSet()
@Suppress("UNCHECKED_CAST")
this.forEach {
val valueCopy = forceCopy(it) as T
clone.add(valueCopy)
}
return clone
}
fun <T> ObjectSet<T>.addVar(vararg add: T): ObjectSet<T> {
add.forEach { this.add(it) }
return this
}
private val emptyArraySingleton: Array<*> = Array<Any>()
@Suppress("UNCHECKED_CAST")
fun <T> emptyGDXArray(): Array<T> {
return emptyArraySingleton as Array<T>
}
fun <T> ObjectSet<T>.randomMembers(numberToSelect: Int, selected: ObjectSet<T>) {
if (numberToSelect > this.size || numberToSelect < 0) {
throw Exception("Cannot select $numberToSelect from ${this.size}")
}
val pool: Array<T> = newArray()
pool.addAll(this)
val originalSize = selected.size
while ((selected.size - originalSize) < numberToSelect) {
selected.add(pool.removeIndex(MathUtils.random(0, pool.size - 1)))
}
recycle(pool)
}
fun <T> Array<T>.randomMembers(numberToSelect: Int, selected: Array<T>) {
if (numberToSelect > this.size || numberToSelect < 0) {
throw Exception("Cannot select $numberToSelect from ${this.size}")
}
val pool: Array<T> = newArray()
pool.addAll(this)
val originalSize = selected.size
while ((selected.size - originalSize) < numberToSelect) {
selected.add(pool.removeIndex(MathUtils.random(0, pool.size - 1)))
}
recycle(pool)
}
| apache-2.0 | ca9fa02f5d835a9dd910fccbddb8a01e | 24.76259 | 98 | 0.657917 | 3.324977 | false | false | false | false |
alashow/music-android | modules/base-android/src/main/java/tm/alashow/base/util/IntentUtils.kt | 1 | 1585 | /*
* Copyright (C) 2019, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.base.util
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.core.net.toUri
object IntentUtils {
fun openUrl(context: Context, url: String) {
try {
val intent = Intent(Intent.ACTION_VIEW, url.toUri())
startActivity(context, intent)
} catch (e: ActivityNotFoundException) {
RemoteLogger.exception(e)
}
}
fun openFile(context: Context, uri: Uri, mimeType: String) {
try {
val intent = Intent()
intent.action = Intent.ACTION_VIEW
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION
intent.setDataAndType(uri, mimeType)
startActivity(context, intent)
} catch (e: ActivityNotFoundException) {
RemoteLogger.exception(e)
}
}
/**
* Open given intent as [Activity].
* Just a wrapper so custom stuff can be done just before opening new activity.
*/
fun startActivity(context: Context, intent: Intent, extras: Bundle? = null) {
if (extras != null)
context.startActivity(intent, extras)
else
context.startActivity(intent)
}
}
fun Intent.clearTop() {
flags =
Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
}
| apache-2.0 | 6bd9b931e6963ec59abcc6dca4844a5b | 29.480769 | 141 | 0.64795 | 4.283784 | false | false | false | false |
microg/android_packages_apps_GmsCore | play-services-maps-core-mapbox/src/main/kotlin/org/microg/gms/maps/mapbox/utils/typeConverter.kt | 1 | 3805 | /*
* Copyright (C) 2019 microG Project Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.microg.gms.maps.mapbox.utils
import android.os.Bundle
import com.google.android.gms.maps.internal.ICancelableCallback
import com.mapbox.mapboxsdk.camera.CameraPosition
import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.mapboxsdk.geometry.LatLngBounds
import com.mapbox.mapboxsdk.geometry.VisibleRegion
import com.mapbox.mapboxsdk.maps.MapboxMap
import com.google.android.gms.maps.model.CameraPosition as GmsCameraPosition
import com.google.android.gms.maps.model.LatLng as GmsLatLng
import com.google.android.gms.maps.model.LatLngBounds as GmsLatLngBounds
import com.google.android.gms.maps.model.VisibleRegion as GmsVisibleRegion
fun GmsLatLng.toMapbox(): LatLng =
LatLng(latitude, longitude)
fun GmsLatLngBounds.toMapbox(): LatLngBounds =
LatLngBounds.from(this.northeast.latitude, this.northeast.longitude, this.southwest.latitude, this.southwest.longitude)
fun GmsCameraPosition.toMapbox(): CameraPosition =
CameraPosition.Builder()
.target(target.toMapbox())
.zoom(zoom.toDouble() - 1.0)
.tilt(tilt.toDouble())
.bearing(bearing.toDouble())
.build()
fun ICancelableCallback.toMapbox(): MapboxMap.CancelableCallback =
object : MapboxMap.CancelableCallback {
override fun onFinish() = [email protected]()
override fun onCancel() = [email protected]()
}
fun Bundle.toMapbox(): Bundle {
val newBundle = Bundle(this)
val oldLoader = newBundle.classLoader
newBundle.classLoader = GmsLatLng::class.java.classLoader
for (key in newBundle.keySet()) {
val value = newBundle.get(key)
when (value) {
is GmsCameraPosition -> newBundle.putParcelable(key, value.toMapbox())
is GmsLatLng -> newBundle.putParcelable(key, value.toMapbox())
is GmsLatLngBounds -> newBundle.putParcelable(key, value.toMapbox())
is Bundle -> newBundle.putBundle(key, value.toMapbox())
}
}
newBundle.classLoader = oldLoader
return newBundle
}
fun LatLng.toGms(): GmsLatLng = GmsLatLng(latitude, longitude)
fun LatLngBounds.toGms(): GmsLatLngBounds = GmsLatLngBounds(southWest.toGms(), northEast.toGms())
fun CameraPosition.toGms(): GmsCameraPosition =
GmsCameraPosition(target.toGms(), zoom.toFloat() + 1.0f, tilt.toFloat(), bearing.toFloat())
fun Bundle.toGms(): Bundle {
val newBundle = Bundle(this)
val oldLoader = newBundle.classLoader
newBundle.classLoader = LatLng::class.java.classLoader
for (key in newBundle.keySet()) {
val value = newBundle.get(key)
when (value) {
is CameraPosition -> newBundle.putParcelable(key, value.toGms())
is LatLng -> newBundle.putParcelable(key, value.toGms())
is LatLngBounds -> newBundle.putParcelable(key, value.toGms())
is Bundle -> newBundle.putBundle(key, value.toGms())
}
}
newBundle.classLoader = oldLoader
return newBundle
}
fun VisibleRegion.toGms(): GmsVisibleRegion =
GmsVisibleRegion(nearLeft.toGms(), nearRight.toGms(), farLeft.toGms(), farRight.toGms(), latLngBounds.toGms())
| apache-2.0 | 4686ab8855356a866938d5e4563bafef | 39.478723 | 127 | 0.708804 | 4.113514 | false | false | false | false |
microg/android_packages_apps_GmsCore | play-services-nearby-core-ui/src/main/kotlin/org/microg/gms/nearby/core/ui/BarChartPreference.kt | 1 | 1893 | /*
* SPDX-FileCopyrightText: 2020, microG Project Team
* SPDX-License-Identifier: Apache-2.0
*/
package org.microg.gms.nearby.core.ui
import android.content.Context
import android.util.AttributeSet
import androidx.preference.Preference
import androidx.preference.PreferenceViewHolder
import com.db.williamchart.data.Scale
import com.db.williamchart.view.BarChartView
class BarChartPreference : Preference {
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?) : super(context)
init {
layoutResource = R.layout.preference_bar_chart
}
private lateinit var chart: BarChartView
var labelsFormatter: (Float) -> String = { it.toString() }
set(value) {
field = value
if (this::chart.isInitialized) {
chart.labelsFormatter = value
}
}
var scale: Scale? = null
set(value) {
field = value
if (value != null && this::chart.isInitialized) {
chart.scale = value
}
}
var data: LinkedHashMap<String, Float> = linkedMapOf()
set(value) {
field = value
if (this::chart.isInitialized) {
chart.animate(data)
}
}
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
chart = holder.itemView as? BarChartView ?: holder.findViewById(R.id.bar_chart) as BarChartView
chart.labelsFormatter = labelsFormatter
scale?.let { chart.scale = it }
chart.animate(data)
}
}
| apache-2.0 | 7fcf469f85a8d7f3979544b20b86ded3 | 32.803571 | 144 | 0.648177 | 4.422897 | false | false | false | false |
googlecodelabs/android-paging | basic/start/app/src/main/java/com/example/android/codelabs/paging/ui/ArticleAdapter.kt | 1 | 1957 | /*
* 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.android.codelabs.paging.ui
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import com.example.android.codelabs.paging.data.Article
import com.example.android.codelabs.paging.databinding.ArticleViewholderBinding
/**
* Adapter for an [Article] [List].
*/
class ArticleAdapter : ListAdapter<Article, ArticleViewHolder>(ARTICLE_DIFF_CALLBACK) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder =
ArticleViewHolder(
ArticleViewholderBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false,
)
)
override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) {
val tile = getItem(position)
if (tile != null) {
holder.bind(tile)
}
}
companion object {
private val ARTICLE_DIFF_CALLBACK = object : DiffUtil.ItemCallback<Article>() {
override fun areItemsTheSame(oldItem: Article, newItem: Article): Boolean =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: Article, newItem: Article): Boolean =
oldItem == newItem
}
}
}
| apache-2.0 | dd8cf5a58adb27ee90cc2f2fcd842367 | 33.946429 | 90 | 0.692897 | 4.681818 | false | false | false | false |
infinum/android_dbinspector | dbinspector/src/test/kotlin/com/infinum/dbinspector/ui/pragma/tableinfo/TableInfoViewModelTest.kt | 1 | 1132 | package com.infinum.dbinspector.ui.pragma.tableinfo
import com.infinum.dbinspector.domain.UseCases
import com.infinum.dbinspector.shared.BaseTest
import io.mockk.mockk
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
import org.koin.core.module.Module
import org.koin.dsl.module
import org.koin.test.get
@DisplayName("TableInfoViewModel tests")
internal class TableInfoViewModelTest : BaseTest() {
override fun modules(): List<Module> = listOf(
module {
factory { mockk<UseCases.OpenConnection>() }
factory { mockk<UseCases.CloseConnection>() }
factory { mockk<UseCases.GetTablePragma>() }
}
)
@Test
fun `Get table info pragma`() {
val given = "my_table"
val expected = "PRAGMA \"table_info\"(\"$given\")"
val viewModel = TableInfoViewModel(get(), get(), get())
val actual = viewModel.pragmaStatement(given)
assertTrue(actual.isNotBlank())
assertEquals(expected, actual)
}
}
| apache-2.0 | 1b2fe6dc5558121322eecf928ca7758f | 29.594595 | 63 | 0.696996 | 4.208178 | false | true | false | false |
akvo/akvo-flow-mobile | app/src/main/java/org/akvo/flow/presentation/datapoints/list/DataPointsListFragment.kt | 1 | 15806 | /*
* Copyright (C) 2017-2021 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Flow.
*
* Akvo Flow 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.
*
* Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.akvo.flow.presentation.datapoints.list
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.PorterDuff
import android.location.Criteria
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ImageView
import android.widget.ListView
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.SearchView
import androidx.core.content.ContextCompat
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import org.akvo.flow.R
import org.akvo.flow.app.FlowApp
import org.akvo.flow.utils.entity.SurveyGroup
import org.akvo.flow.injector.component.ApplicationComponent
import org.akvo.flow.injector.component.DaggerViewComponent
import org.akvo.flow.presentation.datapoints.DataPointSyncSnackBarManager
import org.akvo.flow.presentation.datapoints.list.entity.ListDataPoint
import org.akvo.flow.tracking.TrackingListener
import org.akvo.flow.ui.Navigator
import org.akvo.flow.ui.fragment.OrderByDialogFragment
import org.akvo.flow.ui.fragment.OrderByDialogFragment.OrderByDialogListener
import org.akvo.flow.ui.fragment.RecordListListener
import org.akvo.flow.util.ConstantUtil
import org.akvo.flow.util.WeakLocationListener
import timber.log.Timber
import java.lang.ref.WeakReference
import javax.inject.Inject
class DataPointsListFragment : Fragment(), LocationListener, AdapterView.OnItemClickListener,
OrderByDialogListener, DataPointsListView {
@Inject
lateinit var dataPointSyncSnackBarManager: DataPointSyncSnackBarManager
@Inject
lateinit var navigator: Navigator
@Inject
lateinit var presenter: DataPointsListPresenter
private lateinit var weakLocationListener: WeakLocationListener
private var mLocationManager: LocationManager? = null
private var mLatitude: Double? = null
private var mLongitude: Double? = null
private var mListener: RecordListListener? = null
private var trackingListener: TrackingListener? = null
private lateinit var mAdapter: DataPointListAdapter
private lateinit var listView: ListView
private lateinit var emptyTitleTv: TextView
private lateinit var emptySubTitleTv: TextView
private lateinit var emptyIv: ImageView
private lateinit var progressBar: ProgressBar
private var searchView: SearchView? = null
private var menuRes: Int? = null
/**
* BroadcastReceiver to notify of data synchronisation. This should be
* fired from [DataPointUploadWorker]
*/
private val dataSyncReceiver: BroadcastReceiver = DataSyncBroadcastReceiver(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initializeInjector()
setHasOptionsMenu(true)
}
override fun onAttach(context: Context) {
super.onAttach(context)
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
val activity = activity
mListener = try {
activity as RecordListListener?
} catch (e: ClassCastException) {
throw ClassCastException(
activity.toString()
+ " must implement SurveyedLocalesFragmentListener"
)
}
trackingListener = if (activity !is TrackingListener) {
throw IllegalArgumentException("Activity must implement TrackingListener")
} else {
activity
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.data_points_list_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
mLocationManager = activity!!.applicationContext
.getSystemService(Context.LOCATION_SERVICE) as LocationManager
weakLocationListener = WeakLocationListener(this)
val view = view!!
listView = view.findViewById(R.id.locales_lv)
val emptyView = view.findViewById<View>(R.id.empty_view)
listView.emptyView = emptyView
emptyTitleTv = view.findViewById(R.id.empty_title_tv)
emptySubTitleTv = view.findViewById(R.id.empty_subtitle_tv)
emptyIv = view.findViewById(R.id.empty_iv)
val surveyGroup = arguments
?.getSerializable(ConstantUtil.SURVEY_EXTRA) as SurveyGroup?
mAdapter = DataPointListAdapter(activity)
listView.adapter = mAdapter
listView.onItemClickListener = this
progressBar = view.findViewById(R.id.progress)
updateProgressDrawable()
presenter.setView(this)
presenter.onDataReady(surveyGroup)
}
private fun updateProgressDrawable() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
val progressDrawable = progressBar.indeterminateDrawable
progressDrawable?.setColorFilter(
ContextCompat.getColor(activity!!, R.color.colorAccent),
PorterDuff.Mode.MULTIPLY
)
}
}
private fun initializeInjector() {
val viewComponent = DaggerViewComponent.builder()
.applicationComponent(applicationComponent)
.build()
viewComponent.inject(this)
}
private val applicationComponent: ApplicationComponent
get() = (activity!!.application as FlowApp).getApplicationComponent()
override fun onResume() {
super.onResume()
LocalBroadcastManager.getInstance(activity!!).registerReceiver(
dataSyncReceiver,
IntentFilter(ConstantUtil.ACTION_DATA_SYNC)
)
if (searchView == null || searchView!!.isIconified) {
updateLocation()
presenter.loadDataPoints(mLatitude, mLongitude)
}
listView.onItemClickListener = this
}
private fun updateLocation() {
val criteria = Criteria()
criteria.accuracy = Criteria.ACCURACY_FINE
val provider = mLocationManager?.getBestProvider(criteria, true)
try {
if (provider != null) {
val loc = mLocationManager!!.getLastKnownLocation(provider)
if (loc != null) {
mLatitude = loc.latitude
mLongitude = loc.longitude
}
mLocationManager!!.requestLocationUpdates(provider, 1000, 0f, weakLocationListener)
}
} catch (e: SecurityException) {
Timber.e("Missing permission")
}
}
override fun onPause() {
super.onPause()
LocalBroadcastManager.getInstance(activity!!).unregisterReceiver(dataSyncReceiver)
mLocationManager?.removeUpdates(weakLocationListener)
}
override fun onStop() {
super.onStop()
mLocationManager?.removeUpdates(weakLocationListener)
}
override fun onDetach() {
super.onDetach()
mListener = null
trackingListener = null
}
override fun onDestroy() {
presenter.destroy()
super.onDestroy()
}
fun onNewSurveySelected(surveyGroup: SurveyGroup?) {
arguments!!.putSerializable(ConstantUtil.SURVEY_EXTRA, surveyGroup)
presenter.onNewSurveySelected(surveyGroup)
}
override fun showOrderByDialog(orderBy: Int) {
val dialogFragment: DialogFragment = OrderByDialogFragment.instantiate(orderBy)
dialogFragment.setTargetFragment(this, 0)
dialogFragment.show(fragmentManager!!, OrderByDialogFragment.FRAGMENT_ORDER_BY_TAG)
}
override fun showNoSurveySelected() {
emptyTitleTv.setText(R.string.no_survey_selected_text)
emptySubTitleTv.text = ""
}
override fun showNoDataPoints(monitored: Boolean) {
emptyTitleTv.setText(R.string.no_datapoints_error_text)
val subtitleResource =
if (monitored) R.string.no_records_subtitle_monitored else R.string.no_records_subtitle_non_monitored
emptySubTitleTv.setText(subtitleResource)
emptyIv.setImageResource(R.drawable.ic_format_list_bulleted)
}
override fun showLoading() {
progressBar.visibility = View.VISIBLE
}
override fun hideLoading() {
progressBar.visibility = View.GONE
}
override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
listView.onItemClickListener = null
val (_, _, localeId) = mAdapter.getItem(position)
mListener!!.onDatapointSelected(localeId)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
menuRes?.let { menuRes ->
inflater.inflate(menuRes, menu)
setUpSearchView(menu)
}
super.onCreateOptionsMenu(menu, inflater)
}
private fun setUpSearchView(menu: Menu) {
val searchMenuItem = menu.findItem(R.id.search)
searchView = searchMenuItem.actionView as SearchView
searchView?.let { searchView ->
searchView.setIconifiedByDefault(true)
searchView.queryHint = getString(R.string.search_hint)
searchView.setOnQueryTextListener(object :
SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
// Empty
return false
}
override fun onQueryTextChange(newText: String): Boolean {
if (!TextUtils.isEmpty(newText)) {
presenter.getFilteredDataPoints(newText)
} else {
presenter.loadDataPoints(mLatitude, mLongitude)
}
return false
}
})
}
searchMenuItem.setOnActionExpandListener(
object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(item: MenuItem): Boolean {
trackingListener?.logSearchEvent()
mAdapter.displayIds(true)
return true
}
override fun onMenuItemActionCollapse(item: MenuItem): Boolean {
presenter.loadDataPoints(mLatitude, mLongitude)
mAdapter.displayIds(false)
return true
}
})
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.order_by -> {
presenter.onOrderByClicked()
trackingListener?.logSortEvent()
true
}
R.id.download -> {
presenter.onDownloadPressed()
trackingListener?.logDownloadEvent(LIST_TAB)
true
}
R.id.upload -> {
presenter.onUploadPressed()
trackingListener?.logUploadEvent(LIST_TAB)
true
}
else -> false
}
}
override fun onOrderByClick(order: Int) {
presenter.onOrderByClick(order)
trackingListener?.logOrderEvent(order)
}
override fun onLocationChanged(location: Location) {
// a single location is all we need
mLocationManager!!.removeUpdates(weakLocationListener)
mLatitude = location.latitude
mLongitude = location.longitude
presenter.loadDataPoints(mLatitude, mLongitude)
}
override fun onProviderDisabled(provider: String) {
// EMPTY
}
override fun onProviderEnabled(provider: String) {
// EMPTY
}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
// EMPTY
}
private fun refreshLocalData() {
presenter.loadDataPoints(mLatitude, mLongitude)
}
override fun displayData(listDataPoints: List<ListDataPoint>) {
mAdapter.setDataPoints(listDataPoints)
}
override fun showErrorMissingLocation() {
//TODO: should we prompt the user to enable location?
Toast.makeText(activity, R.string.locale_list_error_unknown_location, Toast.LENGTH_SHORT)
.show()
}
override fun showNonMonitoredMenu() {
menuRes = R.menu.datapoints_list
reloadMenu()
}
override fun showMonitoredMenu() {
menuRes = R.menu.datapoints_list_monitored
reloadMenu()
}
override fun hideMenu() {
menuRes = null
reloadMenu()
}
private fun reloadMenu() {
activity?.invalidateOptionsMenu()
}
override fun showDownloadedResults(numberOfNewDataPoints: Int) {
dataPointSyncSnackBarManager.showDownloadedResults(numberOfNewDataPoints, view)
}
override fun showErrorAssignmentMissing() {
dataPointSyncSnackBarManager.showErrorAssignmentMissing(view)
}
override fun showErrorNoNetwork() {
dataPointSyncSnackBarManager.showErrorNoNetwork(view) { presenter.onDownloadPressed() }
}
override fun showErrorSync() {
dataPointSyncSnackBarManager.showErrorSync(view) { presenter.onDownloadPressed() }
}
override fun displayNoSearchResultsFound() {
emptyTitleTv.setText(R.string.no_search_results_error_text)
emptySubTitleTv.text = ""
emptyIv.setImageResource(R.drawable.ic_search_results_error)
}
override fun showNoDataPointsToSync() {
dataPointSyncSnackBarManager.showNoDataPointsToDownload(view)
}
fun enableItemClicks() {
listView.onItemClickListener = this
}
class DataSyncBroadcastReceiver(fragment: DataPointsListFragment) :
BroadcastReceiver() {
private val fragmentWeakRef: WeakReference<DataPointsListFragment> = WeakReference(fragment)
override fun onReceive(context: Context, intent: Intent) {
Timber.i("Survey Instance status has changed. Refreshing UI...")
val fragment = fragmentWeakRef.get()
fragment?.refreshLocalData()
}
}
companion object {
private const val LIST_TAB = 0
@JvmStatic
fun newInstance(surveyGroup: SurveyGroup?): DataPointsListFragment {
val fragment = DataPointsListFragment()
val args = Bundle()
args.putSerializable(ConstantUtil.SURVEY_EXTRA, surveyGroup)
fragment.arguments = args
return fragment
}
}
}
| gpl-3.0 | 55eb3162d119af97295fa31f370fd356 | 33.814978 | 113 | 0.672276 | 5.123501 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/widget/TimestampView.kt | 1 | 4544 | package com.boardgamegeek.ui.widget
import android.content.Context
import android.os.Parcel
import android.os.Parcelable
import android.text.Html
import android.text.SpannedString
import android.util.AttributeSet
import android.view.View
import androidx.core.content.withStyledAttributes
import androidx.core.view.ViewCompat
import com.boardgamegeek.R
import com.boardgamegeek.extensions.formatTimestamp
import com.boardgamegeek.extensions.trimTrailingWhitespace
class TimestampView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = android.R.attr.textViewStyle,
defStyleRes: Int = 0
) : SelfUpdatingView(context, attrs, defStyleAttr) {
var timestamp: Long = 0
set(value) {
field = value
updateText()
}
var format: String = ""
set(value) {
field = value
updateText()
}
var formatArg: String? = null
set(value) {
field = value
updateText()
}
private var isForumTimeStamp: Boolean = false
private var includeTime: Boolean = false
private var defaultMessage: String = ""
private var hideWhenEmpty: Boolean = false
init {
context.withStyledAttributes(attrs, R.styleable.TimestampView, defStyleAttr, defStyleRes) {
isForumTimeStamp = getBoolean(R.styleable.TimestampView_isForumTimestamp, false)
includeTime = getBoolean(R.styleable.TimestampView_includeTime, false)
defaultMessage = getString(R.styleable.TimestampView_emptyMessage).orEmpty()
hideWhenEmpty = getBoolean(R.styleable.TimestampView_hideWhenEmpty, false)
format = getString(R.styleable.TimestampView_format).orEmpty()
}
if (maxLines == -1 || maxLines == Integer.MAX_VALUE) {
maxLines = 1
}
updateText()
}
override fun onSaveInstanceState(): Parcelable? {
val superState = super.onSaveInstanceState()
return if (superState != null) {
val savedState = SavedState(superState)
savedState.timestamp = timestamp
savedState.format = format
savedState.formatArg = formatArg
savedState
} else {
superState
}
}
override fun onRestoreInstanceState(state: Parcelable) {
val ss = state as SavedState
super.onRestoreInstanceState(ss.superState)
timestamp = ss.timestamp
format = ss.format
formatArg = ss.formatArg
}
@Synchronized
override fun updateText() {
if (!ViewCompat.isAttachedToWindow(this@TimestampView)) return
if (timestamp <= 0) {
if (hideWhenEmpty) visibility = View.GONE
text = defaultMessage
} else {
if (hideWhenEmpty) visibility = View.VISIBLE
val formattedTimestamp = timestamp.formatTimestamp(context, includeTime, isForumTimeStamp)
text = if (format.isNotEmpty()) {
@Suppress("DEPRECATION")
Html.fromHtml(String.format(
Html.toHtml(SpannedString([email protected])),
formattedTimestamp,
formatArg)
).trimTrailingWhitespace()
} else {
formattedTimestamp
}
}
}
internal class SavedState : BaseSavedState {
internal var timestamp: Long = 0
internal var format: String = ""
internal var formatArg: String? = null
constructor(superState: Parcelable) : super(superState)
constructor(source: Parcel) : super(source) {
timestamp = source.readLong()
format = source.readString().orEmpty()
formatArg = source.readString()
}
override fun writeToParcel(out: Parcel, flags: Int) {
super.writeToParcel(out, flags)
out.writeLong(timestamp)
out.writeString(format)
out.writeString(formatArg)
}
companion object {
@JvmField
@Suppress("unused")
val CREATOR = object : Parcelable.Creator<SavedState> {
override fun createFromParcel(source: Parcel): SavedState {
return SavedState(source)
}
override fun newArray(size: Int): Array<SavedState?> {
return arrayOfNulls(size)
}
}
}
}
}
| gpl-3.0 | 83ea41a6a4ee93d1a5bf0dc2cb5b21f6 | 31.927536 | 102 | 0.607394 | 5.241061 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/adapter/GameCollectionItemAdapter.kt | 1 | 5858 | package com.boardgamegeek.ui.adapter
import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.core.text.HtmlCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.boardgamegeek.R
import com.boardgamegeek.databinding.WidgetCollectionRowBinding
import com.boardgamegeek.entities.CollectionItemEntity
import com.boardgamegeek.extensions.*
import com.boardgamegeek.provider.BggContract
import com.boardgamegeek.ui.GameCollectionItemActivity
import com.boardgamegeek.util.XmlApiMarkupConverter
import kotlin.properties.Delegates
class GameCollectionItemAdapter(private val context: Context) : RecyclerView.Adapter<GameCollectionItemAdapter.ViewHolder>(), AutoUpdatableAdapter {
private val xmlConverter by lazy { XmlApiMarkupConverter(context) }
var gameYearPublished: Int by Delegates.observable(CollectionItemEntity.YEAR_UNKNOWN) { _, oldValue, newValue ->
@SuppressLint("NotifyDataSetChanged")
if (oldValue != newValue) notifyDataSetChanged()
}
var items: List<CollectionItemEntity> by Delegates.observable(emptyList()) { _, oldValue, newValue ->
autoNotify(oldValue, newValue) { old, new ->
old.collectionId == new.collectionId
}
}
override fun getItemCount() = items.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(parent.inflate(R.layout.widget_collection_row), xmlConverter)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(items.getOrNull(position), gameYearPublished)
}
class ViewHolder(itemView: View, private val markupConverter: XmlApiMarkupConverter) : RecyclerView.ViewHolder(itemView) {
private val binding = WidgetCollectionRowBinding.bind(itemView)
fun bind(item: CollectionItemEntity?, gameYearPublished: Int) {
if (item == null) return
binding.thumbnail.loadThumbnailInList(item.thumbnailUrl)
binding.status.setTextOrHide(describeStatuses(item, itemView.context).formatList())
binding.comment.setTextMaybeHtml(markupConverter.toHtml(item.comment), HtmlCompat.FROM_HTML_MODE_COMPACT, false)
binding.comment.isVisible = item.comment.isNotBlank()
val description = if (item.collectionName.isNotBlank() && item.collectionName != item.gameName ||
item.collectionYearPublished != CollectionItemEntity.YEAR_UNKNOWN && item.collectionYearPublished != gameYearPublished
) {
if (item.collectionYearPublished == CollectionItemEntity.YEAR_UNKNOWN) {
item.collectionName
} else {
"${item.collectionName} (${item.collectionYearPublished.asYear(itemView.context)})"
}
} else ""
binding.description.setTextOrHide(description)
if (item.rating in 1.0..10.0) {
binding.rating.text = item.rating.asPersonalRating(itemView.context)
binding.rating.setTextViewBackground(item.rating.toColor(BggColors.ratingColors))
binding.rating.isVisible = true
} else {
binding.rating.isVisible = false
}
if (item.hasPrivateInfo()) {
binding.privateInfo.text = item.getPrivateInfo(itemView.context)
binding.privateInfo.isVisible = true
} else {
binding.privateInfo.isVisible = false
}
binding.privateComment.setTextMaybeHtml(markupConverter.toHtml(item.privateComment), HtmlCompat.FROM_HTML_MODE_COMPACT, false)
binding.privateComment.isVisible = item.privateComment.isNotBlank()
if (item.collectionId != BggContract.INVALID_ID) {
itemView.setOnClickListener {
GameCollectionItemActivity.start(
itemView.context,
item.internalId,
item.gameId,
item.gameName,
item.collectionId,
item.collectionName,
item.thumbnailUrl,
item.heroImageUrl,
gameYearPublished,
item.collectionYearPublished
)
}
}
}
private fun describeStatuses(item: CollectionItemEntity, ctx: Context): List<String> {
val statuses = mutableListOf<String>()
if (item.own) statuses.add(ctx.getString(R.string.collection_status_own))
if (item.previouslyOwned) statuses.add(ctx.getString(R.string.collection_status_prev_owned))
if (item.forTrade) statuses.add(ctx.getString(R.string.collection_status_for_trade))
if (item.wantInTrade) statuses.add(ctx.getString(R.string.collection_status_want_in_trade))
if (item.wantToBuy) statuses.add(ctx.getString(R.string.collection_status_want_to_buy))
if (item.wantToPlay) statuses.add(ctx.getString(R.string.collection_status_want_to_play))
if (item.preOrdered) statuses.add(ctx.getString(R.string.collection_status_preordered))
if (item.wishList) statuses.add(item.wishListPriority.asWishListPriority(ctx))
if (statuses.isEmpty()) {
if (item.numberOfPlays > 0) {
statuses.add(ctx.getString(R.string.played))
} else {
if (item.rating > 0.0) statuses.add(ctx.getString(R.string.rated))
if (item.comment.isNotBlank()) statuses.add(ctx.getString(R.string.commented))
}
}
return statuses
}
}
}
| gpl-3.0 | 4ecd08dcdc6f7688a61b19754bed3487 | 47.016393 | 148 | 0.6521 | 4.849338 | false | false | false | false |
Kotlin/kotlinx.serialization | core/commonMain/src/kotlinx/serialization/internal/PluginGeneratedSerialDescriptor.kt | 1 | 5452 | /*
* Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("OPTIONAL_DECLARATION_USAGE_IN_NON_COMMON_SOURCE", "UNUSED")
package kotlinx.serialization.internal
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.CompositeDecoder.Companion.UNKNOWN_NAME
/**
* Implementation that plugin uses to implement descriptors for auto-generated serializers.
*/
@PublishedApi
@OptIn(ExperimentalSerializationApi::class)
internal open class PluginGeneratedSerialDescriptor(
override val serialName: String,
private val generatedSerializer: GeneratedSerializer<*>? = null,
final override val elementsCount: Int
) : SerialDescriptor, CachedNames {
override val kind: SerialKind get() = StructureKind.CLASS
override val annotations: List<Annotation> get() = classAnnotations ?: emptyList()
private var added = -1
private val names = Array(elementsCount) { "[UNINITIALIZED]" }
private val propertiesAnnotations = arrayOfNulls<MutableList<Annotation>?>(elementsCount)
// Classes rarely have annotations, so we can save up a bit of allocations here
private var classAnnotations: MutableList<Annotation>? = null
private val elementsOptionality = BooleanArray(elementsCount)
public override val serialNames: Set<String> get() = indices.keys
private var indices: Map<String, Int> = emptyMap()
// Cache child serializers, they are not cached by the implementation for nullable types
private val childSerializers: Array<KSerializer<*>> by lazy(LazyThreadSafetyMode.PUBLICATION) { generatedSerializer?.childSerializers() ?: EMPTY_SERIALIZER_ARRAY }
// Lazy because of JS specific initialization order (#789)
internal val typeParameterDescriptors: Array<SerialDescriptor> by lazy(LazyThreadSafetyMode.PUBLICATION) {
generatedSerializer?.typeParametersSerializers()?.map { it.descriptor }.compactArray()
}
// Can be without synchronization but Native will likely break due to freezing
private val _hashCode: Int by lazy(LazyThreadSafetyMode.PUBLICATION) { hashCodeImpl(typeParameterDescriptors) }
public fun addElement(name: String, isOptional: Boolean = false) {
names[++added] = name
elementsOptionality[added] = isOptional
propertiesAnnotations[added] = null
if (added == elementsCount - 1) {
indices = buildIndices()
}
}
public fun pushAnnotation(annotation: Annotation) {
val list = propertiesAnnotations[added].let {
if (it == null) {
val result = ArrayList<Annotation>(1)
propertiesAnnotations[added] = result
result
} else {
it
}
}
list.add(annotation)
}
public fun pushClassAnnotation(a: Annotation) {
if (classAnnotations == null) {
classAnnotations = ArrayList(1)
}
classAnnotations!!.add(a)
}
override fun getElementDescriptor(index: Int): SerialDescriptor {
return childSerializers.getChecked(index).descriptor
}
override fun isElementOptional(index: Int): Boolean = elementsOptionality.getChecked(index)
override fun getElementAnnotations(index: Int): List<Annotation> =
propertiesAnnotations.getChecked(index) ?: emptyList()
override fun getElementName(index: Int): String = names.getChecked(index)
override fun getElementIndex(name: String): Int = indices[name] ?: UNKNOWN_NAME
private fun buildIndices(): Map<String, Int> {
val indices = HashMap<String, Int>()
for (i in names.indices) {
indices[names[i]] = i
}
return indices
}
override fun equals(other: Any?): Boolean = equalsImpl(other) { otherDescriptor ->
typeParameterDescriptors.contentEquals(otherDescriptor.typeParameterDescriptors)
}
override fun hashCode(): Int = _hashCode
override fun toString(): String {
return (0 until elementsCount).joinToString(", ", "$serialName(", ")") { i ->
getElementName(i) + ": " + getElementDescriptor(i).serialName
}
}
}
@OptIn(ExperimentalSerializationApi::class)
internal inline fun <reified SD : SerialDescriptor> SD.equalsImpl(
other: Any?,
typeParamsAreEqual: (otherDescriptor: SD) -> Boolean
): Boolean {
if (this === other) return true
if (other !is SD) return false
if (serialName != other.serialName) return false
if (!typeParamsAreEqual(other)) return false
if (this.elementsCount != other.elementsCount) return false
for (index in 0 until elementsCount) {
if (getElementDescriptor(index).serialName != other.getElementDescriptor(index).serialName) return false
if (getElementDescriptor(index).kind != other.getElementDescriptor(index).kind) return false
}
return true
}
@OptIn(ExperimentalSerializationApi::class)
internal fun SerialDescriptor.hashCodeImpl(typeParams: Array<SerialDescriptor>): Int {
var result = serialName.hashCode()
result = 31 * result + typeParams.contentHashCode()
val elementDescriptors = elementDescriptors
val namesHash = elementDescriptors.elementsHashCodeBy { it.serialName }
val kindHash = elementDescriptors.elementsHashCodeBy { it.kind }
result = 31 * result + namesHash
result = 31 * result + kindHash
return result
}
| apache-2.0 | ef1f91338f91349655569cf5bfca87f3 | 39.992481 | 167 | 0.704512 | 4.942883 | false | false | false | false |
sbhachu/kotlin-bootstrap | app/src/main/kotlin/com/sbhachu/bootstrap/extensions/listener/PageWatcher.kt | 1 | 1128 | package com.sbhachu.bootstrap.extensions.listener
import android.support.v4.view.ViewPager
open class PageWatcher : ViewPager.SimpleOnPageChangeListener() {
private var _onPageScrolled: ((position: Int, positionOffset: Float, positionOffsetPixels: Int) -> Unit)? = null
private var _onPageScrollStateChanged: ((state: Int) -> Unit)? = null
private var _onPageSelected: ((position: Int) -> Unit)? = null
override fun onPageScrollStateChanged(state: Int) {
_onPageScrollStateChanged?.invoke(state)
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
_onPageScrolled?.invoke(position, positionOffset, positionOffsetPixels)
}
override fun onPageSelected(position: Int) {
_onPageSelected?.invoke(position)
}
fun onPageScrollStateChanged(listener: (Int?) -> Unit) {
_onPageScrollStateChanged = listener
}
fun onPageScrolled(listener: (Int?, Float?, Int?) -> Unit) {
_onPageScrolled = listener
}
fun onPageSelected(listener: (Int?) -> Unit) {
_onPageSelected = listener
}
} | apache-2.0 | a3521bbf12e97dcdd046459e253e6bab | 32.205882 | 116 | 0.695035 | 4.925764 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/api/util/collections/ImmutableList.kt | 1 | 2811 | /*
* 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>.
*/
@file:Suppress("NOTHING_TO_INLINE")
package org.lanternpowered.api.util.collections
import com.google.common.collect.ImmutableList
import org.lanternpowered.api.util.sequences.collect
import java.util.stream.Stream
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
/**
* Converts this [Stream] into an [ImmutableList].
*/
inline fun <T> Sequence<T>.toImmutableList(): ImmutableList<T> = collect(ImmutableList.toImmutableList())
/**
* Converts this [Stream] into an [ImmutableList].
*/
inline fun <T> Stream<T>.toImmutableList(): ImmutableList<T> = collect(ImmutableList.toImmutableList())
/**
* Converts this [Iterable] into an [ImmutableList].
*/
inline fun <T> Iterable<T>.toImmutableList(): ImmutableList<T> = ImmutableList.copyOf(this)
/**
* Converts this [Array] into an [ImmutableList].
*/
inline fun <T> Array<T>.toImmutableList(): ImmutableList<T> = ImmutableList.copyOf(this)
/**
* Converts this [IntArray] into an [ImmutableList].
*/
fun IntArray.toImmutableList(): ImmutableList<Int> = ImmutableList.builder<Int>().apply { forEach { add(it) } }.build()
/**
* Converts this [DoubleArray] into an [ImmutableList].
*/
fun DoubleArray.toImmutableList(): ImmutableList<Double> = ImmutableList.builder<Double>().apply { forEach { add(it) } }.build()
/**
* Converts this [LongArray] into an [ImmutableList].
*/
fun LongArray.toImmutableList(): ImmutableList<Long> = ImmutableList.builder<Long>().apply { forEach { add(it) } }.build()
/**
* Gets an empty [ImmutableList].
*/
inline fun <T> immutableListOf(): ImmutableList<T> = ImmutableList.of()
/**
* Constructs a new [ImmutableList] with the given values.
*/
inline fun <T> immutableListOf(vararg values: T) = values.asList().toImmutableList()
/**
* Constructs a new [ImmutableList] builder.
*/
inline fun <T> immutableListBuilderOf(): ImmutableList.Builder<T> = ImmutableList.builder<T>()
/**
* Constructs a new [ImmutableList].
*/
inline fun <T> buildImmutableList(fn: ImmutableList.Builder<T>.() -> Unit): ImmutableList<T> {
contract {
callsInPlace(fn, InvocationKind.EXACTLY_ONCE)
}
return ImmutableList.builder<T>().apply(fn).build()
}
/**
* Constructs a new [ImmutableList].
*/
inline fun <T> buildImmutableList(capacity: Int, fn: ImmutableList.Builder<T>.() -> Unit): ImmutableList<T> {
contract {
callsInPlace(fn, InvocationKind.EXACTLY_ONCE)
}
return ImmutableList.builderWithExpectedSize<T>(capacity).apply(fn).build()
}
| mit | 43c534e3933a7b92915232149601c40c | 30.58427 | 128 | 0.716115 | 3.931469 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/duchy/deploy/gcloud/daemon/mill/liquidlegionsv2/GcsLiquidLegionsV2MillDaemon.kt | 1 | 1503 | // Copyright 2020 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.duchy.deploy.gcloud.daemon.mill.liquidlegionsv2
import org.wfanet.measurement.common.commandLineMain
import org.wfanet.measurement.duchy.deploy.common.daemon.mill.liquidlegionsv2.LiquidLegionsV2MillDaemon
import org.wfanet.measurement.gcloud.gcs.GcsFromFlags
import org.wfanet.measurement.gcloud.gcs.GcsStorageClient
import picocli.CommandLine
@CommandLine.Command(
name = "GcsLiquidLegionsV2MillDaemon",
description = ["Liquid Legions V2 Mill daemon."],
mixinStandardHelpOptions = true,
showDefaultValues = true
)
class GcsLiquidLegionsV2MillDaemon : LiquidLegionsV2MillDaemon() {
@CommandLine.Mixin private lateinit var gcsFlags: GcsFromFlags.Flags
override fun run() {
val gcs = GcsFromFlags(gcsFlags)
run(GcsStorageClient.fromFlags(gcs))
}
}
fun main(args: Array<String>) = commandLineMain(GcsLiquidLegionsV2MillDaemon(), args)
| apache-2.0 | 845b3518f2e67d1ffb75d0b9a1db8135 | 38.552632 | 103 | 0.787092 | 4.062162 | false | false | false | false |
crunchersaspire/worshipsongs-android | app/src/main/java/org/worshipsongs/fragment/SongContentLandscapeViewFragment.kt | 3 | 4559 | package org.worshipsongs.fragment
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ScrollView
import android.widget.TextView
import androidx.fragment.app.Fragment
import org.worshipsongs.CommonConstants
import org.worshipsongs.R
import org.worshipsongs.service.CustomTagColorService
import org.worshipsongs.service.UserPreferenceSettingService
/**
* author:madasamy
* version:2.1.0
*/
class SongContentLandscapeViewFragment : Fragment()
{
private var preferenceSettingService: UserPreferenceSettingService? = null
private var customTagColorService: CustomTagColorService? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?
{
val view = inflater.inflate(R.layout.song_content_landscape_view_fragment, container, false) as View
hideStatusBar()
customTagColorService = CustomTagColorService()
preferenceSettingService = UserPreferenceSettingService()
val bundle = arguments
val title = bundle!!.getString(CommonConstants.TITLE_KEY)
val content = bundle.getString("content")
val authorName = bundle.getString("authorName")
val position = bundle.getString("position")
val size = bundle.getString("size")
val chord = bundle.getString("chord")
setScrollView(view)
setContent(content, view)
setSongTitle(view, title, chord)
setAuthorName(view, authorName)
setSongSlide(view, position, size)
return view
}
private fun hideStatusBar()
{
if (Build.VERSION.SDK_INT < 16)
{
activity!!.window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
} else
{
val decorView = activity!!.window.decorView
val uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN
decorView.systemUiVisibility = uiOptions
}
}
private fun setScrollView(view: View)
{
val scrollView = view.findViewById<View>(R.id.verse_land_scape_scrollview) as ScrollView
scrollView.setBackgroundColor(preferenceSettingService!!.presentationBackgroundColor)
}
private fun setContent(content: String?, view: View)
{
val textView = view.findViewById<View>(R.id.text) as TextView
textView.text = content
val text = textView.text.toString()
textView.text = ""
customTagColorService!!.setCustomTagTextView(textView, text, preferenceSettingService!!.presentationPrimaryColor, preferenceSettingService!!.presentationSecondaryColor)
textView.textSize = preferenceSettingService!!.landScapeFontSize
textView.setTextColor(preferenceSettingService!!.primaryColor)
textView.isVerticalScrollBarEnabled = true
}
private fun setSongTitle(view: View, title: String?, chord: String?)
{
val songTitleTextView = view.findViewById<View>(R.id.song_title) as TextView
val formattedTitle = resources.getString(R.string.title) + " " + title + " " + getChord(chord)
songTitleTextView.text = formattedTitle
songTitleTextView.setTextColor(preferenceSettingService!!.presentationPrimaryColor)
}
private fun getChord(chord: String?): String
{
return if (chord != null && chord.length > 0)
{
" [$chord]"
} else ""
}
private fun setAuthorName(view: View, authorName: String?)
{
val authorNameTextView = view.findViewById<View>(R.id.author_name) as TextView
val formattedAuthor = resources.getString(R.string.author) + " " + authorName
authorNameTextView.text = formattedAuthor
authorNameTextView.setTextColor(preferenceSettingService!!.presentationPrimaryColor)
}
private fun setSongSlide(view: View, position: String?, size: String?)
{
val songSlideTextView = view.findViewById<View>(R.id.song_slide) as TextView
val slidePosition = resources.getString(R.string.slide) + " " + getSongSlideValue(position, size)
songSlideTextView.text = slidePosition
songSlideTextView.setTextColor(preferenceSettingService!!.presentationPrimaryColor)
}
private fun getSongSlideValue(currentPosition: String?, size: String?): String
{
val slidePosition = Integer.parseInt(currentPosition!!) + 1
return "$slidePosition of $size"
}
}
| gpl-3.0 | d3600fa4b1fd83327123bf141c4b2fba | 37.965812 | 176 | 0.70805 | 4.829449 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/ActivityErrorHandler.kt | 1 | 2508 | package com.pr0gramm.app.ui
import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.fragment.app.FragmentActivity
import com.pr0gramm.app.ui.dialogs.ErrorDialogFragment
import com.pr0gramm.app.util.ErrorFormatting
import java.io.PrintWriter
import java.io.StringWriter
import java.lang.ref.WeakReference
/**
*/
class ActivityErrorHandler(application: Application) : ErrorDialogFragment.OnErrorDialogHandler, Application.ActivityLifecycleCallbacks {
private val nullValue = WeakReference<FragmentActivity>(null)
private var current = nullValue
private var pendingError: Throwable? = null
private var pendingFormatter: ErrorFormatting.Formatter? = null
init {
application.registerActivityLifecycleCallbacks(this)
}
override fun showErrorDialog(error: Throwable, formatter: ErrorFormatting.Formatter) {
val activity = current.get()
if (activity != null) {
val message = if (formatter.handles(error)) {
formatter.getMessage(activity, error)
} else {
StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString()
}
ErrorDialogFragment.showErrorString(activity.supportFragmentManager, message)
// reset any pending errors
pendingError = null
pendingFormatter = null
} else {
this.pendingError = error
this.pendingFormatter = formatter
}
}
override fun onActivityResumed(activity: Activity) {
if (activity is FragmentActivity) {
current = WeakReference(activity)
if (pendingError != null && pendingFormatter != null) {
showErrorDialog(pendingError!!, pendingFormatter!!)
}
}
}
override fun onActivityPaused(activity: Activity) {
if (current.get() === activity) {
current = nullValue
}
}
override fun onActivityStopped(activity: Activity) {
if (current.get() === activity) {
current = nullValue
}
}
override fun onActivityDestroyed(activity: Activity) {
if (current.get() === activity) {
current = nullValue
}
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
override fun onActivityStarted(activity: Activity) {}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
}
| mit | f07dbdb3807d2cec5c563c7117b1213f | 29.585366 | 137 | 0.662281 | 5.20332 | false | false | false | false |
raziel057/FrameworkBenchmarks | frameworks/Kotlin/pronghorn/src/main/kotlin/pronghorn/utils/MongoDBHandlerHelpers.kt | 29 | 6121 | package pronghorn.utils
import com.jsoniter.output.JsonStream
import com.mongodb.ServerAddress
import com.mongodb.async.client.*
import com.mongodb.client.model.Filters
import com.mongodb.client.model.UpdateOneModel
import com.mongodb.connection.ClusterSettings
import com.mongodb.connection.ConnectionPoolSettings
import org.bson.Document
import org.bson.codecs.configuration.CodecRegistries
import pronghorn.types.Fortune
import pronghorn.types.World
import pronghorn.types.codecs.FortuneCodec
import pronghorn.types.codecs.WorldCodec
import tech.pronghorn.coroutines.awaitable.InternalFuture
import tech.pronghorn.coroutines.awaitable.await
import tech.pronghorn.http.HttpExchange
import tech.pronghorn.mongodb.MultiplexMongoDBStreamFactoryFactory
import tech.pronghorn.server.HttpServerWorker
import tech.pronghorn.server.requesthandlers.SuspendableHttpRequestHandler
import java.io.ByteArrayOutputStream
import java.util.SplittableRandom
import java.util.TreeSet
private val queriesBytes = "queries".toByteArray(Charsets.US_ASCII)
abstract class MongoDBHandlerHelpers(worker: HttpServerWorker) : SuspendableHttpRequestHandler(), JsonSupport {
private val mongoClient = worker.getOrPutAttachment(MongoDBClientAttachmentKey, { createMongoClient(worker) })
protected val random = SplittableRandom()
override final val outputStream = ByteArrayOutputStream()
override final val stream = JsonStream(outputStream, 32)
protected fun getWorldCollection(): MongoCollection<World> {
return mongoClient
.getDatabase(TestConfig.dbName)
.getCollection(TestConfig.worldCollectionName)
.withDocumentClass(World::class.java)
}
protected fun getFortunesCollection(): MongoCollection<Fortune> {
return mongoClient
.getDatabase(TestConfig.dbName)
.getCollection(TestConfig.fortunesCollectionName)
.withDocumentClass(Fortune::class.java)
}
private fun createMongoClient(worker: HttpServerWorker): MongoClient {
val poolSettings = ConnectionPoolSettings.builder()
.minSize(1)
.maxSize(Int.MAX_VALUE) // connections are multiplexed via Pronghorn Stream, so max size is irrelevant
.maxWaitQueueSize(0)
.build()
val clusterSettings = ClusterSettings.builder()
.hosts(listOf(ServerAddress(TestConfig.dbHost, TestConfig.dbPort)))
.build()
val multiplexedFactory = MultiplexMongoDBStreamFactoryFactory(worker)
val codecRegistry = CodecRegistries.fromRegistries(
MongoClients.getDefaultCodecRegistry(),
CodecRegistries.fromCodecs(FortuneCodec, WorldCodec)
)
val settings = MongoClientSettings.builder()
.clusterSettings(clusterSettings)
.connectionPoolSettings(poolSettings)
.streamFactoryFactory(multiplexedFactory)
.codecRegistry(codecRegistry)
.build()
val client = MongoClients.create(settings)
worker.registerShutdownMethod {
client.close()
}
return client
}
protected fun getQueryCount(exchange: HttpExchange): Int {
return Math.max(1, Math.min(500, exchange.requestUrl.getQueryParamAsInt(queriesBytes) ?: 1))
}
suspend protected fun findWorld(collection: MongoCollection<World>): World {
val future = InternalFuture<World>()
val promise = future.promise()
val id = random.nextInt(10000) + 1
collection.find(Document("_id", id)).first { world, ex ->
when {
world != null -> promise.complete(world)
ex != null -> promise.completeExceptionally(ex)
else -> promise.completeExceptionally(Exception("Missing document."))
}
}
return await(future)
}
@Suppress("UNCHECKED_CAST")
protected fun findWorlds(collection: MongoCollection<World>,
promise: InternalFuture.InternalPromise<Array<World>>,
count: Int,
results: Array<World?> = arrayOfNulls(count)) {
val id = count
val searchDocument = Document("_id", id)
collection.find(searchDocument).first { world, ex ->
when {
world != null -> {
results[count - 1] = world
if (count == 1) {
promise.complete(results as Array<World>)
}
else {
findWorlds(collection, promise, count - 1, results)
}
}
ex != null -> promise.completeExceptionally(ex)
else -> promise.completeExceptionally(Exception("Missing document."))
}
}
}
protected suspend fun findFortunes(collection: MongoCollection<Fortune>): TreeSet<Fortune> {
val future = InternalFuture<Unit>()
val promise = future.promise()
val fortunes = TreeSet<Fortune>()
collection.find().into(fortunes, { _, _ -> promise.complete(Unit) })
await(future)
return fortunes
}
protected suspend fun writeWorlds(collection: MongoCollection<World>,
results: Array<World>) {
val updateFuture = InternalFuture<Unit>()
val updatePromise = updateFuture.promise()
val updates = results.map { result ->
UpdateOneModel<World>(
Filters.eq("_id", result.id),
Document("\$set", Document("randomNumber", result.randomNumber))
)
}
collection.bulkWrite(updates, { result, ex ->
when {
result != null -> updatePromise.complete(Unit)
ex != null -> updatePromise.completeExceptionally(ex)
else -> updatePromise.completeExceptionally(Exception("Unexpected update failure."))
}
})
await(updateFuture)
}
}
| bsd-3-clause | d1c3eb57b414be61be45cd55866606ca | 38.490323 | 118 | 0.637968 | 5.182896 | false | false | false | false |
ansman/okhttp | okhttp-sse/src/main/kotlin/okhttp3/sse/internal/RealEventSource.kt | 2 | 3051 | /*
* Copyright (C) 2018 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.sse.internal
import java.io.IOException
import okhttp3.Call
import okhttp3.Callback
import okhttp3.EventListener
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.internal.EMPTY_RESPONSE
import okhttp3.internal.connection.RealCall
import okhttp3.sse.EventSource
import okhttp3.sse.EventSourceListener
class RealEventSource(
private val request: Request,
private val listener: EventSourceListener
) : EventSource, ServerSentEventReader.Callback, Callback {
private lateinit var call: RealCall
fun connect(client: OkHttpClient) {
val client = client.newBuilder()
.eventListener(EventListener.NONE)
.build()
call = client.newCall(request) as RealCall
call.enqueue(this)
}
override fun onResponse(call: Call, response: Response) {
processResponse(response)
}
fun processResponse(response: Response) {
response.use {
if (!response.isSuccessful) {
listener.onFailure(this, null, response)
return
}
val body = response.body!!
if (!body.isEventStream()) {
listener.onFailure(this,
IllegalStateException("Invalid content-type: ${body.contentType()}"), response)
return
}
// This is a long-lived response. Cancel full-call timeouts.
call.timeoutEarlyExit()
// Replace the body with an empty one so the callbacks can't see real data.
val response = response.newBuilder()
.body(EMPTY_RESPONSE)
.build()
val reader = ServerSentEventReader(body.source(), this)
try {
listener.onOpen(this, response)
while (reader.processNextEvent()) {
}
} catch (e: Exception) {
listener.onFailure(this, e, response)
return
}
listener.onClosed(this)
}
}
private fun ResponseBody.isEventStream(): Boolean {
val contentType = contentType() ?: return false
return contentType.type == "text" && contentType.subtype == "event-stream"
}
override fun onFailure(call: Call, e: IOException) {
listener.onFailure(this, e, null)
}
override fun request(): Request = request
override fun cancel() {
call.cancel()
}
override fun onEvent(id: String?, type: String?, data: String) {
listener.onEvent(this, id, type, data)
}
override fun onRetryChange(timeMs: Long) {
// Ignored. We do not auto-retry.
}
}
| apache-2.0 | dc89a8bb97b62a207f8e600d459575e2 | 27.514019 | 91 | 0.690921 | 4.249304 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/dialogs/ColorPalettePicker.kt | 1 | 4672 | package org.tasks.dialogs
import android.app.Activity
import android.app.Activity.RESULT_OK
import android.app.Dialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import dagger.hilt.android.AndroidEntryPoint
import org.tasks.R
import org.tasks.billing.Inventory
import org.tasks.billing.PurchaseActivity
import org.tasks.databinding.DialogIconPickerBinding
import org.tasks.dialogs.ColorPickerAdapter.Palette
import org.tasks.dialogs.ColorWheelPicker.Companion.newColorWheel
import org.tasks.themes.ColorProvider
import org.tasks.themes.ThemeColor
import javax.inject.Inject
@AndroidEntryPoint
class ColorPalettePicker : DialogFragment() {
companion object {
private const val FRAG_TAG_COLOR_PICKER = "frag_tag_color_picker"
private const val EXTRA_PALETTE = "extra_palette"
const val EXTRA_SELECTED = ColorWheelPicker.EXTRA_SELECTED
fun newColorPalette(
target: Fragment?,
rc: Int,
palette: Palette
): ColorPalettePicker {
return newColorPalette(target, rc, 0, palette)
}
fun newColorPalette(
target: Fragment?,
rc: Int,
selected: Int,
palette: Palette = Palette.COLORS
): ColorPalettePicker {
val args = Bundle()
args.putSerializable(EXTRA_PALETTE, palette)
args.putInt(EXTRA_SELECTED, selected)
val dialog = ColorPalettePicker()
dialog.setTargetFragment(target, rc)
dialog.arguments = args
return dialog
}
}
interface Pickable : Parcelable {
val pickerColor: Int
val isFree: Boolean
}
interface ColorPickedCallback {
fun onColorPicked(index: Int)
}
@Inject lateinit var dialogBuilder: DialogBuilder
@Inject lateinit var inventory: Inventory
@Inject lateinit var colorProvider: ColorProvider
private lateinit var colors: List<Pickable>
private lateinit var palette: Palette
var callback: ColorPickedCallback? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val binding = DialogIconPickerBinding.inflate(LayoutInflater.from(context))
palette = requireArguments().getSerializable(EXTRA_PALETTE) as Palette
colors = when (palette) {
Palette.COLORS -> colorProvider.getThemeColors()
Palette.ACCENTS -> colorProvider.getAccentColors()
Palette.LAUNCHERS -> ThemeColor.LAUNCHER_COLORS.map { color ->
ThemeColor(context, requireContext().getColor(color))
}
Palette.WIDGET -> colorProvider.getWidgetColors()
}
val iconPickerAdapter = ColorPickerAdapter(requireActivity(), inventory, this::onSelected)
with(binding.icons) {
layoutManager = IconLayoutManager(context)
adapter = iconPickerAdapter
}
iconPickerAdapter.submitList(colors)
val builder =
dialogBuilder
.newDialog()
.setView(binding.root)
if (palette == Palette.COLORS || palette == Palette.WIDGET) {
builder.setNeutralButton(R.string.color_wheel) { _, _ ->
val selected = arguments?.getInt(EXTRA_SELECTED) ?: 0
newColorWheel(targetFragment, targetRequestCode, selected)
.show(parentFragmentManager, FRAG_TAG_COLOR_PICKER)
}
}
if (inventory.purchasedThemes()) {
builder.setNegativeButton(R.string.cancel, null)
} else {
builder.setPositiveButton(R.string.upgrade_to_pro) { _: DialogInterface?, _: Int ->
startActivity(Intent(context, PurchaseActivity::class.java))
}
}
return builder.show()
}
override fun onAttach(activity: Activity) {
super.onAttach(activity)
if (activity is ColorPickedCallback) {
callback = activity
}
}
private fun onSelected(index: Int) {
val result = when (palette) {
Palette.COLORS, Palette.WIDGET -> (colors[index] as ThemeColor).originalColor
else -> index
}
dialog?.dismiss()
if (targetFragment == null) {
callback?.onColorPicked(result)
} else {
val data = Intent().putExtra(EXTRA_SELECTED, result)
targetFragment?.onActivityResult(targetRequestCode, RESULT_OK, data)
}
}
} | gpl-3.0 | 3f102a27ea5b597f4ce95dc56d03e086 | 34.135338 | 98 | 0.649401 | 4.954401 | false | false | false | false |
jospint/Architecture-Components-DroidDevs | ArchitectureComponents/app/src/main/java/com/jospint/droiddevs/architecturecomponents/data/googlemaps/model/PlaceModels.kt | 1 | 1305 | package com.jospint.droiddevs.architecturecomponents.data.googlemaps.model
import com.squareup.moshi.Json
import paperparcel.PaperParcel
import paperparcel.PaperParcelable
@PaperParcel
data class PlaceResponse(
@Json(name = "html_attributions") val htmlAttributions: List<String>?,
val results: List<PlaceResult>?,
val status: String?): PaperParcelable {
companion object {
@JvmField val CREATOR = PaperParcelPlaceResponse.CREATOR
}
}
@PaperParcel
data class PlaceResult(
@Json(name = "formatted_address") val formattedAddress: String?,
val geometry: Geometry?,
val icon: String?,
val id: String?,
val name: String?,
val photos: List<Photo>?,
@Json(name = "place_id") val placeId: String?,
val reference: String?,
val types: List<String>?): PaperParcelable {
companion object {
@JvmField val CREATOR = PaperParcelPlaceResult.CREATOR
}
}
@PaperParcel
data class Photo(
val height: Int?,
val width: Int?,
@Json(name = "html_attributions") val htmlAttributions: List<String>?,
@Json(name = "photo_reference") val photoReference: String?): PaperParcelable {
companion object {
@JvmField val CREATOR = PaperParcelPhoto.CREATOR
}
} | apache-2.0 | 6f8fdd59ec06328566053207f897272d | 30.095238 | 87 | 0.668966 | 4.408784 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-casc/src/main/java/net/nemerosa/ontrack/extension/casc/expressions/CascExpressionPreprocessor.kt | 1 | 2143 | package net.nemerosa.ontrack.extension.casc.expressions
import net.nemerosa.ontrack.extension.casc.CascPreprocessor
import org.springframework.stereotype.Component
@Component
class CascExpressionPreprocessor(
expressionContexts: List<CascExpressionContext>,
) : CascPreprocessor {
private val contexts = expressionContexts.associateBy { it.name }
override fun process(yaml: String): String =
yaml.lines().joinToString("\n") { processLine(it) }
private fun processLine(line: String): String =
line.replace(pattern) { m ->
val expression = m.groupValues[1].trim()
val value = processExpression(expression)
// If the replacement is on multiple lines,
// we need to indent the result accordingly,
// by taking the same amount of white spaces
// as before the match
val valueLines = value.lines()
if (valueLines.size > 1) {
val prefix = line.substring(0, m.range.first)
if (prefix.isBlank()) {
// Indenting all lines but the first one
valueLines.mapIndexed { index, s ->
if (index > 0) {
prefix + s
} else {
s
}
}.joinToString("\n")
}
// Not empty in front of the expression, skipping any indentation
else {
value
}
}
// No multiline --> inline
else {
value
}
}
private fun processExpression(expression: String): String {
val name = expression.substringBefore(".")
val rest = expression.substringAfter(".")
if (name.isBlank()) {
throw CascExpressionMissingNameException()
}
val context = contexts[name] ?: throw CascExpressionUnknownException(name)
return context.evaluate(rest)
}
companion object {
private val pattern = "\\{\\{([^}]+)}}".toRegex()
}
} | mit | 98b16055dbecc1784cae8ee3e7f45de3 | 34.147541 | 82 | 0.540831 | 5.3575 | false | false | false | false |
drakeet/MultiType | library/src/test/kotlin/com/drakeet/multitype/MultiTypeAdapterTest.kt | 1 | 3893 | /*
* Copyright (c) 2016-present. Drakeet Xu
*
* 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.drakeet.multitype
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.*
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers.anyList
import org.mockito.ArgumentMatchers.anyString
import org.robolectric.RobolectricTestRunner
import java.util.*
/**
* @author Drakeet Xu
*/
@RunWith(RobolectricTestRunner::class)
class MultiTypeAdapterTest {
private val parent: ViewGroup = mock()
private val context: Context = mock()
private val mockedItemViewDelegate: TestItemViewDelegate = mock()
private val itemViewDelegate = TestItemViewDelegate()
@Before
@Throws(Exception::class)
fun setUp() {
whenever(parent.context).thenReturn(context)
}
@Test
fun shouldReturnOriginalItems() {
val list = ArrayList<Any>()
val adapter = MultiTypeAdapter(list)
assertEquals(list, adapter.items)
}
@Test
fun shouldReturnEmptyItemsWithDefaultConstructor() {
val adapter = MultiTypeAdapter()
assertThat(adapter.items).isEmpty()
}
@Test
fun shouldOverrideRegisteredDelegate() {
val adapter = MultiTypeAdapter()
adapter.register(TestItem::class, itemViewDelegate)
assertThat(adapter.types.size).isEqualTo(1)
assertThat(itemViewDelegate).isEqualTo(adapter.types.getType<Any>(0).delegate)
val newDelegate = TestItemViewDelegate()
adapter.register(TestItem::class, newDelegate)
assertThat(newDelegate).isEqualTo(adapter.types.getType<Any>(0).delegate)
}
@Test
fun shouldNotOverrideRegisteredDelegateWhenToMany() {
val adapter = MultiTypeAdapter()
val delegate2 = TestItemViewDelegate()
adapter.register(TestItem::class)
.to(itemViewDelegate, delegate2)
.withLinker { _, _ -> -1 }
assertThat(adapter.types.getType<Any>(0).clazz).isEqualTo(TestItem::class.java)
assertThat(adapter.types.getType<Any>(1).clazz).isEqualTo(TestItem::class.java)
assertThat(itemViewDelegate).isEqualTo(adapter.types.getType<Any>(0).delegate)
assertThat(delegate2).isEqualTo(adapter.types.getType<Any>(1).delegate)
}
@Test
fun testOnCreateViewHolder() {
val adapter = MultiTypeAdapter()
adapter.register(TestItem::class, mockedItemViewDelegate)
val item = TestItem("testOnCreateViewHolder")
adapter.items = listOf(item)
val type = adapter.getItemViewType(0)
adapter.onCreateViewHolder(parent, type)
verify(mockedItemViewDelegate).onCreateViewHolder(context, parent)
}
@Test
fun testOnBindViewHolder() {
val adapter = MultiTypeAdapter()
adapter.register(TestItem::class, mockedItemViewDelegate)
val item = TestItem("testOnCreateViewHolder")
adapter.items = listOf(item)
val holder: TestItemViewDelegate.ViewHolder = mock()
whenever(holder.itemViewType).thenReturn(adapter.getItemViewType(0))
adapter.onBindViewHolder(holder, 0)
verify(mockedItemViewDelegate).onBindViewHolder(eq(holder), eq(item), anyList())
val payloads = emptyList<Any>()
adapter.onBindViewHolder(holder, 0, payloads)
verify(mockedItemViewDelegate, times(2)).onBindViewHolder(holder, item, payloads)
}
}
| apache-2.0 | d0bbd914fbd3a6b7860cab4ce745cbf8 | 31.991525 | 85 | 0.752376 | 4.320755 | false | true | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/ui/UIEditableNumber.kt | 1 | 3422 | package com.soywiz.korge.ui
import com.soywiz.kmem.*
import com.soywiz.korge.annotations.*
import com.soywiz.korge.input.*
import com.soywiz.korge.view.*
import com.soywiz.korgw.*
import com.soywiz.korio.async.*
import com.soywiz.korio.util.*
import com.soywiz.korma.geom.*
import kotlin.math.*
@KorgeExperimental
inline fun Container.uiEditableNumber(
value: Double = 0.0, min: Double = 0.0, max: Double = 1.0, decimals: Int = 2, clamped: Boolean = true,
width: Double = 64.0,
height: Double = 18.0,
block: @ViewDslMarker UIEditableNumber.() -> Unit = {}
): UIEditableNumber = UIEditableNumber(value, min, max, decimals, clamped, width, height)
.addTo(this).also { block(it) }
// @TODO: lock cursor while dragging
@KorgeExperimental
class UIEditableNumber(value: Double = 0.0, min: Double = 0.0, max: Double = 1.0, var decimals: Int = 2, var clamped: Boolean = true, width: Double = 64.0, height: Double = 18.0) : UIView(width, height) {
private val textView = uiText("", width, height)
private val textInputView = uiTextInput("", width, height)
.also { it.visible = false }
.also { it.padding = Margin(0.0) }
var min: Double = min
var max: Double = max
override fun onSizeChanged() {
super.onSizeChanged()
textView.size(width, height)
textInputView.size(width, height)
}
private fun getValueText(value: Double = this.value): String {
return value.toStringDecimal(decimals)
}
val onSetValue = Signal<UIEditableNumber>()
var value: Double = Double.NaN
set(value) {
val clampedValue = if (clamped) value.clamp(min, max) else value
if (field != clampedValue || textView.text.isEmpty()) {
field = clampedValue
textView.text = getValueText()
onSetValue(this)
}
}
private var oldValue: Double = value
private fun setTextInputVisible(visible: Boolean, useValue: Boolean = true) {
textView.visible = !visible
textInputView.visible = visible
if (textInputView.visible) {
oldValue = value
textView.text = getValueText()
textInputView.text = getValueText()
textInputView.focus()
textInputView.selectAll()
} else {
value = if (useValue) textInputView.text.toDoubleOrNull() ?: oldValue else oldValue
}
}
init {
this.value = value
cursor = GameWindow.Cursor.RESIZE_EAST
var start = 0.0
textInputView.onReturnPressed { setTextInputVisible(false, useValue = true) }
textInputView.onEscPressed { setTextInputVisible(false, useValue = false) }
textInputView.onFocusLost { setTextInputVisible(false, useValue = true) }
mouse {
down {
//currentEvent?.requestLock?.invoke()
//views.gameWindow.lockMousePointer()
}
click {
setTextInputVisible(!textInputView.visible)
}
}
onMouseDrag {
if (textInputView.visible) return@onMouseDrag
if (it.start) {
start = [email protected]
}
val dist = (max - min).absoluteValue
[email protected] = (start + dist * (it.dx / (width * 2)))
it.mouseEvents.stopPropagation()
}
}
}
| apache-2.0 | 595a2e5449e826a13b421a38536d972a | 35.021053 | 204 | 0.613968 | 4.11793 | false | false | false | false |
Le-Chiffre/Yttrium | Router/src/com/rimmer/yttrium/router/Path.kt | 2 | 1270 | package com.rimmer.yttrium.router
import com.rimmer.yttrium.serialize.Reader
/**
* Represents one segment in the url of a route.
* @param name If this is a string segment, this is the parsed value.
* For a parameter segment, this is the parameter name.
* @param type If set, this is a parameter segment that should be parsed to this type.
*/
data class PathSegment(val name: String, val type: Class<*>?, val reader: Reader?)
/** Converts the provided segments into Swagger format. */
fun buildSwaggerPath(segments: List<Segment>): String {
val builder = StringBuilder()
for(segment in segments) {
builder.append('/')
if(segment.arg == null) {
builder.append(segment.name)
} else {
builder.append('{')
builder.append(segment.name)
builder.append('}')
}
}
return builder.toString()
}
/** Converts the provided segments into Swagger format. */
fun buildEquivalencePath(segments: List<Segment>): String {
val builder = StringBuilder()
for(segment in segments) {
builder.append('/')
if(segment.arg == null) {
builder.append(segment.name)
} else {
builder.append('*')
}
}
return builder.toString()
} | mit | 7c1603f63766e7b3dd07c1f005ee6aca | 30 | 86 | 0.633858 | 4.305085 | false | false | false | false |
Karumi/Shot | shot-consumer-compose/app/src/androidTest/java/com/karumi/shotconsumercompose/GreetingScreenshotTest.kt | 1 | 2037 | package com.karumi.shotconsumercompose
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.asAndroidBitmap
import androidx.compose.ui.test.captureToImage
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onRoot
import com.karumi.shot.ScreenshotTest
import com.karumi.shotconsumercompose.ui.ShotConsumerComposeTheme
import org.junit.Rule
import org.junit.Test
class GreetingScreenshotTest : ScreenshotTest {
@get:Rule
val composeRule = createComposeRule()
@Test
fun rendersTheDefaultComponent() {
renderComponent()
compareScreenshot(composeRule.onRoot())
}
@Test
fun rendersAGreetingWithAnEmptyText() {
renderComponent("")
compareScreenshot(composeRule)
}
@Test
fun rendersAGreetingWithATextFullOfWhitespaces() {
renderComponent(" ".repeat(200))
compareScreenshot(composeRule)
}
@Test
fun rendersAGreetingWithAShortText() {
renderComponent("Hello!")
compareScreenshot(composeRule)
}
@Test
fun rendersAGreetingWithALongText() {
renderComponent("Hello world from the compose!".repeat(20))
compareScreenshot(composeRule)
}
@Test
fun rendesAnyComponentUsingABitmapInsteadOfANode() {
renderComponent("Hello world from the compose!")
compareScreenshot(composeRule.onRoot().captureToImage().asAndroidBitmap())
}
@Composable
private fun greetingComponent(greeting: String) {
ShotConsumerComposeTheme {
Surface(color = MaterialTheme.colors.background) {
Greeting(greeting)
}
}
}
private fun renderComponent(greeting: String? = null) {
composeRule.setContent {
if (greeting == null) {
DefaultPreview()
} else {
greetingComponent(greeting)
}
}
}
} | apache-2.0 | 8343233ea1afc85ec60a8cca9e80d487 | 26.173333 | 82 | 0.684831 | 4.83848 | false | true | false | false |
HedvigInsurance/bot-service | src/main/java/com/hedvig/botService/chat/MemberSourceConversation.kt | 1 | 3141 | package com.hedvig.botService.chat
import com.hedvig.botService.enteties.UserContext
import com.hedvig.botService.enteties.message.Message
import com.hedvig.botService.enteties.message.MessageBodySingleSelect
import com.hedvig.botService.enteties.message.MessageBodyText
import com.hedvig.botService.enteties.message.SelectItem
import com.hedvig.botService.enteties.message.SelectLink
import com.hedvig.botService.enteties.message.SelectOption
import com.hedvig.libs.translations.Translations
import org.springframework.context.ApplicationEventPublisher
class MemberSourceConversation(
eventPublisher: ApplicationEventPublisher,
translations: Translations,
userContext: UserContext
) : Conversation(eventPublisher, translations, userContext) {
override fun getSelectItemsForAnswer(): List<SelectItem> {
return listOf()
}
override fun canAcceptAnswerToQuestion(): Boolean {
return false
}
override fun handleMessage(m: Message) {
}
override fun init() {
init("membersource.poll")
}
override fun init(startMessage: String) {
startConversation(startMessage)
}
override fun receiveEvent(e: EventTypes, value: String) {
if (e == Conversation.EventTypes.MESSAGE_FETCHED
) {
val relay = getRelay(value)
if (relay != null) {
completeRequest(relay)
}
}
}
init {
this.createChatMessage(
"membersource.poll",
WrappedMessage(
MessageBodySingleSelect(
"En sista fråga, hur hörde du om Hedvig? 🙂",
listOf(
SelectOption("Från en vän/familj/kollega", "friend"),
SelectOption("Google", "google"),
SelectOption("Facebook/Instagram", "facebook_instagram"),
SelectOption("Influencer/Podcast", "influencerPodcast"),
SelectOption("Nyheterna/TV", "news_tv"),
SelectOption("Reklam utomhus", "ad_outside"),
SelectOption("Annat", "other")
)
)
) { b, u, m ->
u.putUserData("MEMBER_SOURCE", b.selectedItem.value)
b.text = b.selectedItem.text
addToChat(m)
val nxtMsg = when (b.selectedItem.value) {
"other" -> "membersource.text"
else -> {
"membersource.thanks"
}
}
nxtMsg
}
)
this.createChatMessage("membersource.text",
WrappedMessage(MessageBodyText("Var hörde du om mig? ")) { b, u, m ->
addToChat(m)
u.putUserData("MEMBER_SOURCE_TEXT", b.text.trim())
"membersource.thanks"
}
)
this.createChatMessage(
"membersource.thanks",
MessageBodySingleSelect("Toppen, tack!", listOf(SelectLink.toDashboard("Börja utforska appen", "expore")))
)
}
}
| agpl-3.0 | 72ddd4f438cacbf288bf71b7cfab6205 | 33.043478 | 118 | 0.579821 | 4.81106 | false | false | false | false |
mibac138/ArgParser | core/src/main/kotlin/com/github/mibac138/argparser/syntax/SyntaxDSLComponentProperty.kt | 1 | 2945 | /*
* Copyright (c) 2017 Michał Bączkowski
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.mibac138.argparser.syntax
import com.github.mibac138.argparser.syntax.dsl.SyntaxElementDSL
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
open class SyntaxDSLComponentProperty<T, COMPONENT : SyntaxComponent>(
protected val componentType: Class<COMPONENT>,
protected var toComponent: T?.() -> COMPONENT?,
protected var toValue: COMPONENT?.() -> T?,
protected val allowReassigning: Boolean = false,
/**
* If false values must be unique across the parent syntax element or the parent element and it's [children][SyntaxContainer.content]
* if it's a [container][SyntaxContainer]
*/
protected val allowDuplicates: Boolean = true
) : ReadWriteProperty<SyntaxElementDSL, T?> {
@Suppress("UNCHECKED_CAST")
override fun getValue(thisRef: SyntaxElementDSL, property: KProperty<*>)
= (thisRef.components.firstOrNull { componentType.isInstance(it) } as COMPONENT?).toValue()
override fun setValue(thisRef: SyntaxElementDSL, property: KProperty<*>, value: T?) {
if (allowReassigning)
thisRef.components.removeIf { componentType.isInstance(it) }
else if (thisRef.components.firstOrNull { componentType.isInstance(it) } != null)
throw IllegalStateException("Can't reassign ${componentType.simpleName}'s value")
if (!allowDuplicates && value != null && thisRef.parent?.let { it.elements.any { it.index == value } } == true)
throw IllegalArgumentException(
"There can't be two elements with the same component ($componentType) value ($value)")
value.toComponent()?.let {
thisRef.components.add(it)
}
}
} | mit | a5d827e9271a6fbad94f35e9ae9d0002 | 48.066667 | 141 | 0.696228 | 4.864463 | false | false | false | false |
cashapp/sqldelight | dialects/postgresql/src/main/kotlin/app/cash/sqldelight/dialects/postgresql/grammar/mixins/JsonExpressionMixin.kt | 1 | 1139 | package app.cash.sqldelight.dialects.postgresql.grammar.mixins
import app.cash.sqldelight.dialects.postgresql.grammar.psi.PostgreSqlJsonExpression
import com.alecstrong.sql.psi.core.SqlAnnotationHolder
import com.alecstrong.sql.psi.core.psi.SqlColumnDef
import com.alecstrong.sql.psi.core.psi.SqlColumnName
import com.alecstrong.sql.psi.core.psi.SqlCompositeElementImpl
import com.intellij.lang.ASTNode
internal abstract class JsonExpressionMixin(node: ASTNode) :
SqlCompositeElementImpl(node),
PostgreSqlJsonExpression {
override fun annotate(annotationHolder: SqlAnnotationHolder) {
val columnType = ((firstChild.reference?.resolve() as? SqlColumnName)?.parent as? SqlColumnDef)?.columnType?.typeName?.text
if (columnType == null || columnType !in arrayOf("JSON", "JSONB")) {
annotationHolder.createErrorAnnotation(firstChild, "Left side of json expression must be a json column.")
}
if (jsonbBinaryOperator != null && columnType != "JSONB") {
annotationHolder.createErrorAnnotation(firstChild, "Left side of jsonb expression must be a jsonb column.")
}
super.annotate(annotationHolder)
}
}
| apache-2.0 | 4f1bc82950c893e8c4eef110ff4396bf | 48.521739 | 127 | 0.784021 | 4.380769 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/gallery/GalleryItem.kt | 1 | 1927 | package org.wikipedia.gallery
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.wikipedia.Constants.PREFERRED_GALLERY_IMAGE_SIZE
import org.wikipedia.dataclient.Service
import org.wikipedia.util.ImageUrlUtil
@Serializable
open class GalleryItem {
@SerialName("section_id")
val sectionId = 0
@SerialName("wb_entity_id")
val entityId: String = ""
@SerialName("audio_type")
val audioType: String = ""
@SerialName("structured")
var structuredData: StructuredData? = null
// return the base url of Wiki Commons for WikiSite() if the file_page is null.
@SerialName("file_page")
var filePage: String = Service.COMMONS_URL
val duration = 0.0
val isShowInGallery = false
var type: String = ""
var thumbnail = ImageInfo()
var original = ImageInfo()
var description = TextInfo()
val caption: TextInfo? = null
val sources: List<ImageInfo>? = null
var titles: Titles? = null
var artist: ArtistInfo? = null
var license: ImageLicense? = null
val thumbnailUrl get() = thumbnail.source
val preferredSizedImageUrl get() = ImageUrlUtil.getUrlForPreferredSize(thumbnailUrl, PREFERRED_GALLERY_IMAGE_SIZE)
// The getSources has different levels of source,
// should have an option that allows user to chose which quality to play
val originalVideoSource get() = sources?.lastOrNull()
var structuredCaptions
get() = structuredData?.captions ?: emptyMap()
set(captions) {
if (structuredData == null) {
structuredData = StructuredData()
}
structuredData?.captions = HashMap(captions)
}
@Serializable
class Titles constructor(val display: String = "", val canonical: String = "", val normalized: String = "")
@Serializable
class StructuredData(var captions: HashMap<String, String>? = null)
}
| apache-2.0 | 4bca970bffbb3cadd46ae43a1b37c4e4 | 30.080645 | 118 | 0.688116 | 4.523474 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/modules/universal/ScopedSecureStoreModule.kt | 2 | 1719 | package abi43_0_0.host.exp.exponent.modules.universal
import android.content.Context
import host.exp.exponent.utils.ScopedContext
import android.content.SharedPreferences
import android.util.Log
import abi43_0_0.expo.modules.securestore.SecureStoreModule
import host.exp.exponent.Constants
private const val SHARED_PREFERENCES_NAME = "SecureStore"
class ScopedSecureStoreModule(private val scopedContext: ScopedContext) :
SecureStoreModule(if (Constants.isStandaloneApp()) scopedContext.baseContext else scopedContext) {
// In standalone apps on SDK 41 and below, SecureStore was initiated with scoped context,
// so SharedPreferences was scoped to that particular experienceId. This meant you
// would lose data upon ejecting to bare. With this method, we can migrate apps' SecureStore
// data from the scoped SharedPreferences SecureStore file, to unscoped, so data will persist
// even after ejecting.
private fun maybeMigrateSharedPreferences() {
val prefs = super.getSharedPreferences()
val legacyPrefs = scopedSharedPreferences
val shouldMigratePreferencesData = Constants.isStandaloneApp() && prefs.all.isEmpty() && legacyPrefs.all.isNotEmpty()
if (shouldMigratePreferencesData) {
for ((key, value) in legacyPrefs.all) {
val success = prefs.edit().putString(key, value.toString()).commit()
if (!success) {
Log.e("E_SECURESTORE_WRITE_ERROR", "Could not transfer SecureStore data to new storage.")
}
}
}
}
private val scopedSharedPreferences: SharedPreferences
get() = scopedContext.getSharedPreferences(
SHARED_PREFERENCES_NAME,
Context.MODE_PRIVATE
)
init {
maybeMigrateSharedPreferences()
}
}
| bsd-3-clause | 9c76a7c4d2e1144be2cfd45deeeda0a2 | 38.976744 | 121 | 0.753345 | 4.464935 | false | false | false | false |
Undin/intellij-rust | debugger/src/main/kotlin/org/rust/debugger/lang/RsMSVCTypeNameDecoratorVisitor.kt | 2 | 4986 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.debugger.lang
import org.rust.debugger.lang.RsTypeNameParser.*
class RsMSVCTypeNameDecoratorVisitor : RsTypeNameBaseVisitor<Unit>() {
private var nestedGenericsLevel: Int = 0
private val builder: StringBuilder = StringBuilder()
fun getDecoratedTypeName(): String = builder.toString()
// str -> &str
override fun visitMsvcStr(ctx: MsvcStrContext) {
builder.append("&str")
}
// never$ -> !
override fun visitMsvcNever(ctx: MsvcNeverContext) {
builder.append("!")
}
// tuple$<MyType1, MyType2, ...> -> (MyType1, MyType2, ...)
override fun visitMsvcTuple(ctx: MsvcTupleContext) {
builder.append("(")
ctx.items?.accept(this)
builder.append(")")
}
// ptr_const$<MyType> -> *const MyType
override fun visitMsvcPtr_const(ctx: MsvcPtr_constContext) {
builder.append("*const ")
ctx.type.accept(this)
}
// ptr_mut$<MyType> -> *mut MyType
override fun visitMsvcPtr_mut(ctx: MsvcPtr_mutContext) {
builder.append("*mut ")
ctx.type.accept(this)
}
// ref$<MyType> -> &MyType
override fun visitMsvcRef(ctx: MsvcRefContext) {
builder.append("&")
ctx.type.accept(this)
}
// ref_mut$<MyType> -> &mut MyType
override fun visitMsvcRef_mut(ctx: MsvcRef_mutContext) {
builder.append("&mut ")
ctx.type.accept(this)
}
// array$<MyType, length> -> [MyType; length]
override fun visitMsvcArray(ctx: MsvcArrayContext) {
builder.append("[")
ctx.type.accept(this)
builder.append("; ")
builder.append(ctx.length.text)
builder.append("]")
}
// slice$<MyType> -> &[MyType]
override fun visitMsvcSlice(ctx: MsvcSliceContext) {
builder.append("&[")
ctx.type.accept(this)
builder.append("]")
}
// Enums before Rust 1.65
// enum$<MyEnum> -> MyEnum
// enum$<MyEnum, MyVariant> -> MyEnum::MyVariant
// enum$<MyEnum, _, _, MyVariant> -> MyEnum::MyVariant
override fun visitMsvcEnum(ctx: MsvcEnumContext) {
ctx.type.accept(this)
val variant = ctx.variant
if (variant != null) {
builder.append("::${variant.text}")
}
}
// enum2$<MyEnum> -> MyEnum
override fun visitMsvcEnum2(ctx: MsvcEnum2Context) {
ctx.type.accept(this)
}
// &str
override fun visitStr(ctx: StrContext) {
builder.append("&str")
}
// !
override fun visitNever(ctx: NeverContext) {
builder.append("!")
}
// (MyType1, ..., MyTypeN)
override fun visitTuple(ctx: TupleContext) {
builder.append("(")
ctx.items?.accept(this)
builder.append(")")
}
// *const MyType
override fun visitPtrConst(ctx: PtrConstContext) {
builder.append("*const ")
ctx.type.accept(this)
}
// *mut MyType
override fun visitPtrMut(ctx: PtrMutContext) {
builder.append("*mut ")
ctx.type.accept(this)
}
// &MyType
override fun visitRef(ctx: RefContext) {
builder.append("&")
ctx.type.accept(this)
}
// &mut MyType
override fun visitRefMut(ctx: RefMutContext) {
builder.append("&mut ")
ctx.type.accept(this)
}
// [MyType; length]
override fun visitArray(ctx: ArrayContext) {
builder.append("[")
ctx.type.accept(this)
builder.append("; ")
builder.append(ctx.length.text)
builder.append("]")
}
// &[MyType]
override fun visitSlice(ctx: SliceContext) {
builder.append("[")
ctx.type.accept(this)
builder.append("]")
}
// foo::bar::Foo<MyType>
override fun visitQualifiedName(ctx: QualifiedNameContext) {
val segments = ctx.namespaceSegments
for (segment in segments.dropLast(1)) {
segment.accept(this)
builder.append("::")
}
segments.last().accept(this)
}
// Foo<MyType>
override fun visitQualifiedNameSegment(ctx: QualifiedNameSegmentContext) {
builder.append(ctx.name.text)
val items = ctx.items
if (items != null) {
nestedGenericsLevel++
if (nestedGenericsLevel >= MAX_NESTED_GENERICS_LEVEL) {
builder.append("<…>")
return
}
builder.append('<')
items.accept(this)
builder.append('>')
nestedGenericsLevel--
}
}
override fun visitCommaSeparatedList(ctx: CommaSeparatedListContext) {
val items = ctx.items
for (child in items.dropLast(1)) {
child.accept(this)
builder.append(", ")
}
items.last().accept(this)
}
companion object {
private const val MAX_NESTED_GENERICS_LEVEL: Int = 2
}
}
| mit | a44136d0a1ba6eaad5529e3de274a5ce | 25.795699 | 78 | 0.580257 | 3.943038 | false | false | false | false |
noud02/Akatsuki | src/main/kotlin/moe/kyubey/akatsuki/commands/Stats.kt | 1 | 3981 | /*
* Copyright (c) 2017-2019 Yui
*
* 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 moe.kyubey.akatsuki.commands
import moe.kyubey.akatsuki.Akatsuki
import moe.kyubey.akatsuki.annotations.Load
import moe.kyubey.akatsuki.entities.Command
import moe.kyubey.akatsuki.entities.Context
import moe.kyubey.akatsuki.music.MusicManager
import net.dv8tion.jda.core.EmbedBuilder
import java.lang.management.ManagementFactory
import java.text.SimpleDateFormat
import java.time.temporal.ChronoUnit
import java.util.*
@Load
class Stats : Command() {
override val desc = "Get stats of the bot."
override fun run(ctx: Context) {
val rb = ManagementFactory.getRuntimeMXBean()
val rtime = Runtime.getRuntime()
val embed = EmbedBuilder().apply {
if (ctx.jda.shardInfo != null) {
setTitle("Shard [${ctx.jda.shardInfo.shardId + 1} / ${ctx.jda.shardInfo.shardTotal}]")
}
val millis = rb.uptime
val secs = (millis / 1000) % 60
val mins = (millis / 60000) % 60
val hours = (millis / 3600000) % 24
val uptime = "%02d:%02d:%02d".format(hours, mins, secs)
descriptionBuilder.append("**Uptime:** $uptime\n")
descriptionBuilder.append("**Memory Usage:** ${rtime.totalMemory() / (1024 * 1024)}MB\n")
if (Akatsuki.jda != null) {
descriptionBuilder.append("**Guilds:** ${ctx.jda.guilds.size}\n")
descriptionBuilder.append("**Users:** ${ctx.jda.users.size}\n")
descriptionBuilder.append("**Ping:** `${ctx.jda.ping}ms`\n")
descriptionBuilder.append("**Voice connections:** ${MusicManager.musicManagers.size}\n")
} else {
descriptionBuilder.append("**Total Guilds:** ${Akatsuki.shardManager.guilds.size}\n")
descriptionBuilder.append("**Total Users:** ${Akatsuki.shardManager.users.size}\n")
descriptionBuilder.append("**Total Voice Connections:** ${MusicManager.musicManagers.size}\n")
descriptionBuilder.append("**Average Ping:** `${Akatsuki.shardManager.averagePing}ms`\n")
for (shard in Akatsuki.shardManager.shards.sortedBy { it.shardInfo.shardId }) {
val voiceConns = MusicManager.musicManagers.filter { shard.guilds.any { g -> g.id == it.key } }.size
addField(
"Shard ${shard.shardInfo.shardId + 1}",
"**Guilds:** ${shard.guilds.size}\n" +
"**Users:** ${shard.users.size}\n" +
"**Voice Connections:** $voiceConns\n" +
"**Ping:** `${shard.ping}ms`",
true
)
}
}
}
ctx.send(embed.build())
}
} | mit | 93a4b64199f6888fb8a36892708f25aa | 43.244444 | 120 | 0.614921 | 4.403761 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/core/src/main/kotlin/com/teamwizardry/librarianlib/math/Matrix4dView.kt | 1 | 1006 | package com.teamwizardry.librarianlib.math
/**
* A read-only view into a potentially mutable matrix
*/
public class Matrix4dView(public var target: Matrix4d): Matrix4d() {
override val m00: Double get() = target.m00
override val m01: Double get() = target.m01
override val m02: Double get() = target.m02
override val m03: Double get() = target.m03
override val m10: Double get() = target.m10
override val m11: Double get() = target.m11
override val m12: Double get() = target.m12
override val m13: Double get() = target.m13
override val m20: Double get() = target.m20
override val m21: Double get() = target.m21
override val m22: Double get() = target.m22
override val m23: Double get() = target.m23
override val m30: Double get() = target.m30
override val m31: Double get() = target.m31
override val m32: Double get() = target.m32
override val m33: Double get() = target.m33
override fun toImmutable(): Matrix4d = Matrix4d(this)
} | lgpl-3.0 | cc3ddb733a136f09c69f2776fec1374f | 34.964286 | 68 | 0.683897 | 3.505226 | false | false | false | false |
MisumiRize/SoylentSystem | lib/src/main/java/org/soylentsystem/realm/Transaction.kt | 1 | 864 | package org.soylentsystem.realm
import android.content.Context
import dalvik.system.DexFile
class Transaction(context: Context) : Realm(context) {
override fun clean() {
val realmClass = realm.javaClass
val realmObjectClass = Class.forName("io.realm.RealmObject")
var packageName = context.getPackageName()
realmClass.getMethod("beginTransaction").invoke(realm)
DexFile(context.getPackageCodePath()).entries().asSequence().filter { klass ->
klass.contains(packageName) && realmObjectClass.isAssignableFrom(Class.forName(klass))
}.forEach { klass ->
realmClass.getMethods().first { m -> m.getName() == "clear" }.invoke(realm, Class.forName(klass))
}
realmClass.getMethod("commitTransaction").invoke(realm)
realmClass.getMethod("close").invoke(realm)
}
}
| mit | 4f35cb3b6366bc9698a45d0d386b12b9 | 33.56 | 109 | 0.681713 | 4.476684 | false | false | false | false |
deva666/anko | anko/library/static/commons/src/Custom.kt | 2 | 2233 | /*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused")
package org.jetbrains.anko.custom
import android.app.Activity
import android.content.Context
import android.view.View
import android.view.ViewManager
import org.jetbrains.anko.internals.AnkoInternals
inline fun <T : View> ViewManager.ankoView(factory: (ctx: Context) -> T, theme: Int, init: T.() -> Unit): T {
val ctx = AnkoInternals.wrapContextIfNeeded(AnkoInternals.getContext(this), theme)
val view = factory(ctx)
view.init()
AnkoInternals.addView(this, view)
return view
}
inline fun <T : View> Context.ankoView(factory: (ctx: Context) -> T, theme: Int, init: T.() -> Unit): T {
val ctx = AnkoInternals.wrapContextIfNeeded(this, theme)
val view = factory(ctx)
view.init()
AnkoInternals.addView(this, view)
return view
}
inline fun <T : View> Activity.ankoView(factory: (ctx: Context) -> T, theme: Int, init: T.() -> Unit): T {
val ctx = AnkoInternals.wrapContextIfNeeded(this, theme)
val view = factory(ctx)
view.init()
AnkoInternals.addView(this, view)
return view
}
inline fun <reified T : View> ViewManager.customView(theme: Int = 0, init: T.() -> Unit): T {
return ankoView({ ctx -> AnkoInternals.initiateView(ctx, T::class.java) }, theme) { init() }
}
inline fun <reified T : View> Context.customView(theme: Int = 0, init: T.() -> Unit): T {
return ankoView({ ctx -> AnkoInternals.initiateView(ctx, T::class.java) }, theme) { init() }
}
inline fun <reified T : View> Activity.customView(theme: Int = 0, init: T.() -> Unit): T {
return ankoView({ ctx -> AnkoInternals.initiateView(ctx, T::class.java) }, theme) { init() }
} | apache-2.0 | ed7aa6b666790045ee4c5c87be685f7f | 35.622951 | 109 | 0.695477 | 3.654664 | false | false | false | false |
androidx/androidx | room/room-compiler/src/test/test-data/kotlinCodeGen/pojoRowAdapter_customTypeConverter_upcast.kt | 3 | 3230 | import android.database.Cursor
import androidx.room.EntityInsertionAdapter
import androidx.room.RoomDatabase
import androidx.room.RoomSQLiteQuery
import androidx.room.RoomSQLiteQuery.Companion.acquire
import androidx.room.util.getColumnIndexOrThrow
import androidx.room.util.query
import androidx.sqlite.db.SupportSQLiteStatement
import java.lang.Class
import javax.`annotation`.processing.Generated
import kotlin.Int
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.collections.List
import kotlin.jvm.JvmStatic
@Generated(value = ["androidx.room.RoomProcessor"])
@Suppress(names = ["UNCHECKED_CAST", "DEPRECATION"])
public class MyDao_Impl(
__db: RoomDatabase,
) : MyDao {
private val __db: RoomDatabase
private val __insertionAdapterOfMyEntity: EntityInsertionAdapter<MyEntity>
init {
this.__db = __db
this.__insertionAdapterOfMyEntity = object : EntityInsertionAdapter<MyEntity>(__db) {
public override fun createQuery(): String =
"INSERT OR ABORT INTO `MyEntity` (`pk`,`foo`) VALUES (?,?)"
public override fun bind(statement: SupportSQLiteStatement, entity: MyEntity): Unit {
statement.bindLong(1, entity.pk.toLong())
val _tmp: String = FooConverter.nullableFooToString(entity.foo)
if (_tmp == null) {
statement.bindNull(2)
} else {
statement.bindString(2, _tmp)
}
}
}
}
public override fun addEntity(item: MyEntity): Unit {
__db.assertNotSuspendingTransaction()
__db.beginTransaction()
try {
__insertionAdapterOfMyEntity.insert(item)
__db.setTransactionSuccessful()
} finally {
__db.endTransaction()
}
}
public override fun getEntity(): MyEntity {
val _sql: String = "SELECT * FROM MyEntity"
val _statement: RoomSQLiteQuery = acquire(_sql, 0)
__db.assertNotSuspendingTransaction()
val _cursor: Cursor = query(__db, _statement, false, null)
try {
val _cursorIndexOfPk: Int = getColumnIndexOrThrow(_cursor, "pk")
val _cursorIndexOfFoo: Int = getColumnIndexOrThrow(_cursor, "foo")
val _result: MyEntity
if (_cursor.moveToFirst()) {
val _tmpPk: Int
_tmpPk = _cursor.getInt(_cursorIndexOfPk)
val _tmpFoo: Foo?
val _tmp: String?
if (_cursor.isNull(_cursorIndexOfFoo)) {
_tmp = null
} else {
_tmp = _cursor.getString(_cursorIndexOfFoo)
}
val _tmp_1: Foo = FooConverter.nullableStringToFoo(_tmp)
_tmpFoo = _tmp_1
_result = MyEntity(_tmpPk,_tmpFoo)
} else {
error("Cursor was empty, but expected a single item.")
}
return _result
} finally {
_cursor.close()
_statement.release()
}
}
public companion object {
@JvmStatic
public fun getRequiredConverters(): List<Class<*>> = emptyList()
}
} | apache-2.0 | 61fa0dad788ab78b029032318535427c | 34.505495 | 97 | 0.594427 | 4.785185 | false | false | false | false |
dkandalov/pomodoro-tm | src/pomodoro/model/time/Time.kt | 1 | 531 | package pomodoro.model.time
import java.time.Instant
data class Time(internal val instant: Instant = Instant.EPOCH) : Comparable<Time> {
val epochMilli: Long = instant.toEpochMilli()
constructor(epochMilli: Long) : this(Instant.ofEpochMilli(epochMilli))
override fun compareTo(other: Time) = instant.compareTo(other.instant)
operator fun plus(duration: Duration) = Time(instant + duration.delegate)
companion object {
val zero = Time(Instant.EPOCH)
fun now() = Time(Instant.now())
}
} | apache-2.0 | e42a36720e7ba94a7f0cd26700f0e663 | 27 | 83 | 0.708098 | 4.084615 | false | false | false | false |
mocovenwitch/heykotlin | app/src/main/java/com/mocoven/heykotlin/playground/Practice2.kt | 1 | 931 | package com.mocoven.heykotlin.playground
/**
* Created by Mocoven on 10/04/2017.
*/
/**
* Note that anonymous objects can be used as types only in local and private declarations. #1
*
* If you use an anonymous object as a return type of a public function #2 or the type of a public
* property, the actual type of that function or property will be the declared supertype of the
* anonymous object, or Any if you didn't declare any supertype.
*
* Members added in the #2 anonymous object will not be accessible.
*/
class C {
// #1 Private function, so the return type is the anonymous object type
private fun foo() = object {
val x: String = "x"
}
// #2 Public function, so the return type is Any
fun publicFoo() = object {
val x: String = "x"
}
fun bar() {
val x1 = foo().x // Works
//val x2 = publicFoo().x // ERROR: Unresolved reference 'x'
}
} | mit | 15613bb9296d80e4eb6ed31a958ff052 | 29.064516 | 98 | 0.646617 | 3.847107 | false | false | false | false |
lvtanxi/Study | SsoDemo/src/main/kotlin/com/lv/controller/LoginController.kt | 1 | 1622 | package com.lv.controller
import com.lv.util.SSOCheck
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import org.springframework.web.servlet.ModelAndView
import javax.servlet.http.Cookie
/**
* Date: 2017-04-07
* Time: 10:49
* Description:
*/
@RestController
class LoginController{
@GetMapping("login")
fun login()= ModelAndView("login")
@PostMapping("doLogin")
fun doLogin(@RequestParam("userName") userName: String?,@RequestParam("passWord") passWord: String?,@RequestParam("toToUrl") toToUrl: String?):String{
println(">>>>>>>>>>>"+toToUrl)
val checkLogin = SSOCheck.checkLogin(userName, passWord)
if (checkLogin) {
val cookie = Cookie("ssocookie","ss0")
//想多个域(同父域)共享cookie的话要这样做
cookie.domain="localhost"
cookie.path="/"
val response = (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes).response
val request = (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes).request
println(request.requestURL)
response.addCookie(cookie)
request.session.setAttribute("lvtanxi","lvtanxi")
return toToUrl.toString()
}
return "error"
}
}
| apache-2.0 | 4ffbe1d9efe58157b5a8595679cad6e6 | 35.181818 | 154 | 0.712312 | 4.302703 | false | false | false | false |
InsertKoinIO/koin | android/koin-android/src/main/java/org/koin/android/scope/ServiceExt.kt | 1 | 1066 | package org.koin.android.scope
import android.app.Service
import org.koin.android.ext.android.getKoin
import org.koin.core.annotation.KoinInternalApi
import org.koin.core.component.getScopeId
import org.koin.core.component.getScopeName
import org.koin.core.scope.Scope
fun Service.createServiceScope(): Scope {
if (this !is AndroidScopeComponent) {
error("Service should implement AndroidScopeComponent")
}
val koin = getKoin()
val scope =
koin.getScopeOrNull(getScopeId()) ?: koin.createScope(getScopeId(), getScopeName(), this)
return scope
}
fun Service.destroyServiceScope() {
if (this !is AndroidScopeComponent) {
error("Service should implement AndroidScopeComponent")
}
scope.close()
}
fun Service.serviceScope() = lazy { createServiceScope() }
/**
* Create new scope
*/
@KoinInternalApi
fun Service.createScope(source: Any? = null): Scope = getKoin().createScope(getScopeId(), getScopeName(), source)
@KoinInternalApi
fun Service.getScopeOrNull(): Scope? = getKoin().getScopeOrNull(getScopeId()) | apache-2.0 | 87f4424ba006a39e0e73ffb3ebe3a7a3 | 29.485714 | 113 | 0.741088 | 4.14786 | false | false | false | false |
WangDaYeeeeee/GeometricWeather | app/src/main/java/wangdaye/com/geometricweather/main/utils/MainThemeColorProvider.kt | 1 | 6097 | package wangdaye.com.geometricweather.main.utils
import android.annotation.SuppressLint
import android.content.Context
import android.os.Looper
import androidx.annotation.AttrRes
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import wangdaye.com.geometricweather.R
import wangdaye.com.geometricweather.common.basic.models.Location
import wangdaye.com.geometricweather.common.basic.models.options.DarkMode
import wangdaye.com.geometricweather.common.basic.models.weather.Weather
import wangdaye.com.geometricweather.common.utils.DisplayUtils
import wangdaye.com.geometricweather.main.MainActivity
import wangdaye.com.geometricweather.settings.SettingsManager
import wangdaye.com.geometricweather.theme.ThemeManager
import java.util.*
import kotlin.collections.HashMap
private val preloadAttrIds = intArrayOf(
R.attr.colorPrimary,
R.attr.colorOnPrimary,
R.attr.colorPrimaryContainer,
R.attr.colorOnPrimaryContainer,
R.attr.colorSecondary,
R.attr.colorOnSecondary,
R.attr.colorSecondaryContainer,
R.attr.colorOnSecondaryContainer,
R.attr.colorTertiary,
R.attr.colorOnTertiary,
R.attr.colorTertiaryContainer,
R.attr.colorOnTertiaryContainer,
R.attr.colorTertiary,
R.attr.colorErrorContainer,
R.attr.colorOnError,
R.attr.colorOnErrorContainer,
android.R.attr.colorBackground,
R.attr.colorOnBackground,
R.attr.colorSurface,
R.attr.colorOnSurface,
R.attr.colorSurfaceVariant,
R.attr.colorOnSurfaceVariant,
R.attr.colorOutline,
R.attr.colorTitleText,
R.attr.colorBodyText,
R.attr.colorCaptionText,
R.attr.colorMainCardBackground,
R.attr.colorPrecipitationProbability,
)
class MainThemeColorProvider(
private val host: MainActivity
): LifecycleEventObserver {
companion object {
@SuppressLint("StaticFieldLeak")
@Volatile
private var instance: MainThemeColorProvider? = null
@JvmStatic
fun bind(mainActivity: MainActivity) {
if (Looper.myLooper() != Looper.getMainLooper()) {
throw IllegalStateException("Cannot bind context provider on a background thread")
}
if (mainActivity.lifecycle.currentState == Lifecycle.State.DESTROYED) {
return
}
instance?.let {
if (it.host === mainActivity) {
return
}
unbind()
}
instance = MainThemeColorProvider(mainActivity)
mainActivity.lifecycle.addObserver(instance!!)
}
@JvmStatic
fun unbind() {
if (Looper.myLooper() != Looper.getMainLooper()) {
throw IllegalStateException("Cannot unbind context provider on a background thread")
}
instance?.let {
it.host.lifecycle.removeObserver(it)
}
instance = null
}
@JvmStatic
fun isLightTheme(
context: Context,
location: Location,
) = isLightTheme(
context = context,
daylight = location.isDaylight
)
@JvmStatic
fun isLightTheme(
context: Context,
weather: Weather,
timeZone: TimeZone,
) = isLightTheme(
context = context,
daylight = weather.isDaylight(timeZone)
)
@JvmStatic
private fun isLightTheme(
context: Context,
daylight: Boolean,
) = when (SettingsManager.getInstance(context).darkMode) {
DarkMode.AUTO -> instance?.host?.isDaylight ?: daylight
DarkMode.SYSTEM -> !DisplayUtils.isDarkMode(context)
DarkMode.LIGHT -> true
DarkMode.DARK -> false
}
@JvmStatic
fun getContext(
lightTheme: Boolean
) = if (lightTheme) {
instance!!.lightContext
} else {
instance!!.darkContext
}
@JvmStatic
fun getContext(
location: Location
) = getContext(
lightTheme = isLightTheme(instance!!.host, location)
)
@JvmStatic
fun getColor(
lightTheme: Boolean,
@AttrRes id: Int,
): Int {
val cache = if (lightTheme) {
instance!!.lightColorCache
} else {
instance!!.darkColorCache
}
cache[id]?.let {
return it
}
val color = ThemeManager.getInstance(instance!!.host).getThemeColor(
context = getContext(lightTheme),
id = id
)
cache[id] = color
return color
}
@JvmStatic
fun getColor(
location: Location,
@AttrRes id: Int,
) = getColor(
id = id,
lightTheme = isLightTheme(instance!!.host, location)
)
}
val lightContext = ThemeManager
.getInstance(host)
.generateThemeContext(context = host, lightTheme = true)
private val lightColorCache = HashMap<Int, Int>()
val darkContext = ThemeManager
.getInstance(host)
.generateThemeContext(context = host, lightTheme = false)
private val darkColorCache = HashMap<Int, Int>()
init {
preloadAttrIds.zip(
ThemeManager.getInstance(host).getThemeColors(lightContext, preloadAttrIds).zip(
ThemeManager.getInstance(host).getThemeColors(darkContext, preloadAttrIds)
)
).forEach { // attr id, <light color, dark color>
lightColorCache[it.first] = it.second.first
darkColorCache[it.first] = it.second.second
}
}
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
val currentState = host.lifecycle.currentState
if (currentState == Lifecycle.State.DESTROYED) {
unbind()
}
}
} | lgpl-3.0 | 3bfb647e063cae226320a6a3606092e3 | 28.601942 | 100 | 0.614893 | 4.973083 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChaptersController.kt | 1 | 19104 | package eu.kanade.tachiyomi.ui.manga.chapter
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.view.ActionMode
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.view.*
import com.bluelinelabs.conductor.RouterTransaction
import com.elvishew.xlog.XLog
import com.jakewharton.rxbinding.support.v4.widget.refreshes
import com.jakewharton.rxbinding.view.clicks
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.SelectableAdapter
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.ui.base.controller.NucleusController
import eu.kanade.tachiyomi.ui.base.controller.popControllerWithTag
import eu.kanade.tachiyomi.ui.manga.MangaController
import eu.kanade.tachiyomi.ui.reader.ReaderActivity
import eu.kanade.tachiyomi.util.getCoordinates
import eu.kanade.tachiyomi.util.snack
import eu.kanade.tachiyomi.util.toast
import exh.EH_SOURCE_ID
import exh.EXH_SOURCE_ID
import kotlinx.android.synthetic.main.chapters_controller.*
import rx.android.schedulers.AndroidSchedulers
import timber.log.Timber
class ChaptersController : NucleusController<ChaptersPresenter>(),
ActionMode.Callback,
FlexibleAdapter.OnItemClickListener,
FlexibleAdapter.OnItemLongClickListener,
ChaptersAdapter.OnMenuItemClickListener,
SetDisplayModeDialog.Listener,
SetSortingDialog.Listener,
DownloadChaptersDialog.Listener,
DownloadCustomChaptersDialog.Listener,
DeleteChaptersDialog.Listener {
/**
* Adapter containing a list of chapters.
*/
private var adapter: ChaptersAdapter? = null
/**
* Action mode for multiple selection.
*/
private var actionMode: ActionMode? = null
/**
* Selected items. Used to restore selections after a rotation.
*/
private val selectedItems = mutableSetOf<ChapterItem>()
init {
setHasOptionsMenu(true)
setOptionsMenuHidden(true)
}
override fun createPresenter(): ChaptersPresenter {
val ctrl = parentController as MangaController
return ChaptersPresenter(ctrl.manga!!, ctrl.source!!,
ctrl.chapterCountRelay, ctrl.lastUpdateRelay, ctrl.mangaFavoriteRelay)
}
override fun inflateView(inflater: LayoutInflater, container: ViewGroup): View {
return inflater.inflate(R.layout.chapters_controller, container, false)
}
override fun onViewCreated(view: View) {
super.onViewCreated(view)
// Init RecyclerView and adapter
adapter = ChaptersAdapter(this, view.context)
recycler.adapter = adapter
recycler.layoutManager = LinearLayoutManager(view.context)
recycler.addItemDecoration(DividerItemDecoration(view.context, DividerItemDecoration.VERTICAL))
recycler.setHasFixedSize(true)
adapter?.fastScroller = fast_scroller
swipe_refresh.refreshes().subscribeUntilDestroy { fetchChaptersFromSource() }
fab.clicks().subscribeUntilDestroy {
val item = presenter.getNextUnreadChapter()
if (item != null) {
// Create animation listener
val revealAnimationListener: Animator.AnimatorListener = object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator?) {
openChapter(item.chapter, true)
}
}
// Get coordinates and start animation
val coordinates = fab.getCoordinates()
if (!reveal_view.showRevealEffect(coordinates.x, coordinates.y, revealAnimationListener)) {
openChapter(item.chapter)
}
} else {
view.context.toast(R.string.no_next_chapter)
}
}
presenter.redirectUserRelay
.observeOn(AndroidSchedulers.mainThread())
.subscribeUntilDestroy { redirect ->
XLog.d("Redirecting to updated manga (manga.id: %s, manga.title: %s, update: %s)!", redirect.manga.id, redirect.manga.title, redirect.update)
// Replace self
parentController?.router?.replaceTopController(RouterTransaction.with(MangaController(redirect)))
}
}
override fun onDestroyView(view: View) {
adapter = null
actionMode = null
super.onDestroyView(view)
}
override fun onActivityResumed(activity: Activity) {
if (view == null) return
// Check if animation view is visible
if (reveal_view.visibility == View.VISIBLE) {
// Show the unReveal effect
val coordinates = fab.getCoordinates()
reveal_view.hideRevealEffect(coordinates.x, coordinates.y, 1920)
}
super.onActivityResumed(activity)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.chapters, menu)
}
override fun onPrepareOptionsMenu(menu: Menu) {
// Initialize menu items.
val menuFilterRead = menu.findItem(R.id.action_filter_read) ?: return
val menuFilterUnread = menu.findItem(R.id.action_filter_unread)
val menuFilterDownloaded = menu.findItem(R.id.action_filter_downloaded)
val menuFilterBookmarked = menu.findItem(R.id.action_filter_bookmarked)
// Set correct checkbox values.
menuFilterRead.isChecked = presenter.onlyRead()
menuFilterUnread.isChecked = presenter.onlyUnread()
menuFilterDownloaded.isChecked = presenter.onlyDownloaded()
menuFilterBookmarked.isChecked = presenter.onlyBookmarked()
if (presenter.onlyRead())
//Disable unread filter option if read filter is enabled.
menuFilterUnread.isEnabled = false
if (presenter.onlyUnread())
//Disable read filter option if unread filter is enabled.
menuFilterRead.isEnabled = false
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_display_mode -> showDisplayModeDialog()
R.id.manga_download -> showDownloadDialog()
R.id.action_sorting_mode -> showSortingDialog()
R.id.action_filter_unread -> {
item.isChecked = !item.isChecked
presenter.setUnreadFilter(item.isChecked)
activity?.invalidateOptionsMenu()
}
R.id.action_filter_read -> {
item.isChecked = !item.isChecked
presenter.setReadFilter(item.isChecked)
activity?.invalidateOptionsMenu()
}
R.id.action_filter_downloaded -> {
item.isChecked = !item.isChecked
presenter.setDownloadedFilter(item.isChecked)
}
R.id.action_filter_bookmarked -> {
item.isChecked = !item.isChecked
presenter.setBookmarkedFilter(item.isChecked)
}
R.id.action_filter_empty -> {
presenter.removeFilters()
activity?.invalidateOptionsMenu()
}
R.id.action_sort -> presenter.revertSortOrder()
else -> return super.onOptionsItemSelected(item)
}
return true
}
fun onNextChapters(chapters: List<ChapterItem>) {
// If the list is empty, fetch chapters from source if the conditions are met
// We use presenter chapters instead because they are always unfiltered
if (presenter.chapters.isEmpty())
initialFetchChapters()
val mangaController = parentController as MangaController
if (mangaController.update
// Auto-update old format galleries
|| ((presenter.manga.source == EH_SOURCE_ID || presenter.manga.source == EXH_SOURCE_ID)
&& chapters.size == 1 && chapters.first().date_upload == 0L)) {
mangaController.update = false
fetchChaptersFromSource()
}
val adapter = adapter ?: return
adapter.updateDataSet(chapters)
if (selectedItems.isNotEmpty()) {
adapter.clearSelection() // we need to start from a clean state, index may have changed
createActionModeIfNeeded()
selectedItems.forEach { item ->
val position = adapter.indexOf(item)
if (position != -1 && !adapter.isSelected(position)) {
adapter.toggleSelection(position)
}
}
actionMode?.invalidate()
}
}
private fun initialFetchChapters() {
// Only fetch if this view is from the catalog and it hasn't requested previously
if ((parentController as MangaController).fromCatalogue && !presenter.hasRequested) {
fetchChaptersFromSource()
}
}
private fun fetchChaptersFromSource() {
swipe_refresh?.isRefreshing = true
presenter.fetchChaptersFromSource()
}
fun onFetchChaptersDone() {
swipe_refresh?.isRefreshing = false
}
fun onFetchChaptersError(error: Throwable) {
swipe_refresh?.isRefreshing = false
activity?.toast(error.message)
// [EXH]
XLog.w("> Failed to fetch chapters!", error)
XLog.w("> (source.id: %s, source.name: %s, manga.id: %s, manga.url: %s)",
presenter.source.id,
presenter.source.name,
presenter.manga.id,
presenter.manga.url)
}
fun onChapterStatusChange(download: Download) {
getHolder(download.chapter)?.notifyStatus(download.status)
}
private fun getHolder(chapter: Chapter): ChapterHolder? {
return recycler?.findViewHolderForItemId(chapter.id!!) as? ChapterHolder
}
fun openChapter(chapter: Chapter, hasAnimation: Boolean = false) {
val activity = activity ?: return
val intent = ReaderActivity.newIntent(activity, presenter.manga, chapter)
if (hasAnimation) {
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
}
startActivity(intent)
}
override fun onItemClick(view: View, position: Int): Boolean {
val adapter = adapter ?: return false
val item = adapter.getItem(position) ?: return false
if (actionMode != null && adapter.mode == SelectableAdapter.Mode.MULTI) {
toggleSelection(position)
return true
} else {
openChapter(item.chapter)
return false
}
}
override fun onItemLongClick(position: Int) {
createActionModeIfNeeded()
toggleSelection(position)
}
// SELECTIONS & ACTION MODE
private fun toggleSelection(position: Int) {
val adapter = adapter ?: return
val item = adapter.getItem(position) ?: return
adapter.toggleSelection(position)
if (adapter.isSelected(position)) {
selectedItems.add(item)
} else {
selectedItems.remove(item)
}
actionMode?.invalidate()
}
private fun getSelectedChapters(): List<ChapterItem> {
val adapter = adapter ?: return emptyList()
return adapter.selectedPositions.mapNotNull { adapter.getItem(it) }
}
private fun createActionModeIfNeeded() {
if (actionMode == null) {
actionMode = (activity as? AppCompatActivity)?.startSupportActionMode(this)
}
}
private fun destroyActionModeIfNeeded() {
actionMode?.finish()
}
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.menuInflater.inflate(R.menu.chapter_selection, menu)
adapter?.mode = SelectableAdapter.Mode.MULTI
return true
}
@SuppressLint("StringFormatInvalid")
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
val count = adapter?.selectedItemCount ?: 0
if (count == 0) {
// Destroy action mode if there are no items selected.
destroyActionModeIfNeeded()
} else {
mode.title = resources?.getString(R.string.label_selected, count)
}
return false
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_select_all -> selectAll()
R.id.action_mark_as_read -> markAsRead(getSelectedChapters())
R.id.action_mark_as_unread -> markAsUnread(getSelectedChapters())
R.id.action_download -> downloadChapters(getSelectedChapters())
R.id.action_delete -> showDeleteChaptersConfirmationDialog()
else -> return false
}
return true
}
override fun onDestroyActionMode(mode: ActionMode) {
adapter?.mode = SelectableAdapter.Mode.SINGLE
adapter?.clearSelection()
selectedItems.clear()
actionMode = null
}
override fun onMenuItemClick(position: Int, item: MenuItem) {
val chapter = adapter?.getItem(position) ?: return
val chapters = listOf(chapter)
when (item.itemId) {
R.id.action_download -> downloadChapters(chapters)
R.id.action_bookmark -> bookmarkChapters(chapters, true)
R.id.action_remove_bookmark -> bookmarkChapters(chapters, false)
R.id.action_delete -> deleteChapters(chapters)
R.id.action_mark_as_read -> markAsRead(chapters)
R.id.action_mark_as_unread -> markAsUnread(chapters)
R.id.action_mark_previous_as_read -> markPreviousAsRead(chapter)
}
}
// SELECTION MODE ACTIONS
private fun selectAll() {
val adapter = adapter ?: return
adapter.selectAll()
selectedItems.addAll(adapter.items)
actionMode?.invalidate()
}
private fun markAsRead(chapters: List<ChapterItem>) {
presenter.markChaptersRead(chapters, true)
if (presenter.preferences.removeAfterMarkedAsRead()) {
deleteChapters(chapters)
}
}
private fun markAsUnread(chapters: List<ChapterItem>) {
presenter.markChaptersRead(chapters, false)
}
private fun downloadChapters(chapters: List<ChapterItem>) {
val view = view
destroyActionModeIfNeeded()
presenter.downloadChapters(chapters)
if (view != null && !presenter.manga.favorite) {
recycler?.snack(view.context.getString(R.string.snack_add_to_library), Snackbar.LENGTH_INDEFINITE) {
setAction(R.string.action_add) {
presenter.addToLibrary()
}
}
}
}
private fun showDeleteChaptersConfirmationDialog() {
DeleteChaptersDialog(this).showDialog(router)
}
override fun deleteChapters() {
deleteChapters(getSelectedChapters())
}
private fun markPreviousAsRead(chapter: ChapterItem) {
val adapter = adapter ?: return
val chapters = if (presenter.sortDescending()) adapter.items.reversed() else adapter.items
val chapterPos = chapters.indexOf(chapter)
if (chapterPos != -1) {
markAsRead(chapters.take(chapterPos))
}
}
private fun bookmarkChapters(chapters: List<ChapterItem>, bookmarked: Boolean) {
destroyActionModeIfNeeded()
presenter.bookmarkChapters(chapters, bookmarked)
}
fun deleteChapters(chapters: List<ChapterItem>) {
destroyActionModeIfNeeded()
if (chapters.isEmpty()) return
DeletingChaptersDialog().showDialog(router)
presenter.deleteChapters(chapters)
}
fun onChaptersDeleted() {
dismissDeletingDialog()
adapter?.notifyDataSetChanged()
}
fun onChaptersDeletedError(error: Throwable) {
dismissDeletingDialog()
Timber.e(error)
}
private fun dismissDeletingDialog() {
router.popControllerWithTag(DeletingChaptersDialog.TAG)
}
// OVERFLOW MENU DIALOGS
private fun showDisplayModeDialog() {
val preselected = if (presenter.manga.displayMode == Manga.DISPLAY_NAME) 0 else 1
SetDisplayModeDialog(this, preselected).showDialog(router)
}
override fun setDisplayMode(id: Int) {
presenter.setDisplayMode(id)
adapter?.notifyDataSetChanged()
}
private fun showSortingDialog() {
val preselected = if (presenter.manga.sorting == Manga.SORTING_SOURCE) 0 else 1
SetSortingDialog(this, preselected).showDialog(router)
}
override fun setSorting(id: Int) {
presenter.setSorting(id)
}
private fun showDownloadDialog() {
DownloadChaptersDialog(this).showDialog(router)
}
private fun getUnreadChaptersSorted() = presenter.chapters
.filter { !it.read && it.status == Download.NOT_DOWNLOADED }
.distinctBy { it.name }
.sortedByDescending { it.source_order }
override fun downloadCustomChapters(amount: Int) {
val chaptersToDownload = getUnreadChaptersSorted().take(amount)
if (chaptersToDownload.isNotEmpty()) {
downloadChapters(chaptersToDownload)
}
}
private fun showCustomDownloadDialog() {
DownloadCustomChaptersDialog(this, presenter.chapters.size).showDialog(router)
}
override fun downloadChapters(choice: Int) {
// i = 0: Download 1
// i = 1: Download 5
// i = 2: Download 10
// i = 3: Download x
// i = 4: Download unread
// i = 5: Download all
val chaptersToDownload = when (choice) {
0 -> getUnreadChaptersSorted().take(1)
1 -> getUnreadChaptersSorted().take(5)
2 -> getUnreadChaptersSorted().take(10)
3 -> {
showCustomDownloadDialog()
return
}
4 -> presenter.chapters.filter { !it.read }
5 -> presenter.chapters
else -> emptyList()
}
if (chaptersToDownload.isNotEmpty()) {
downloadChapters(chaptersToDownload)
}
}
}
| apache-2.0 | 16e8ee75fd58ade958be58eac0513624 | 35.095146 | 161 | 0.624738 | 5.070064 | false | false | false | false |
MrSugarCaney/DirtyArrows | src/main/kotlin/nl/sugcube/dirtyarrows/Broadcast.kt | 1 | 7627 | package nl.sugcube.dirtyarrows
import nl.sugcube.dirtyarrows.effect.HeadshotType
import org.bukkit.ChatColor
import org.bukkit.entity.Player
/**
* @author SugarCaney
*/
object Broadcast {
val TAG = "${Colour.SECONDARY}DA${Colour.TERTIARY}>${Colour.PRIMARY}"
val TAG_HELP = "${Colour.SECONDARY}DA-?${Colour.TERTIARY}>${Colour.PRIMARY}"
val TAG_ERROR = "${Colour.ERROR}!!>"
val TAG_MINIGAME = "${Colour.TERTIARY}[${Colour.SECONDARY}->${Colour.TERTIARY}]${Colour.PRIMARY}"
/**
* New version notification message.
*
* `%s` = New version number.
*/
val NEW_VERSION_AVAILABLE = "$TAG A new version of ${Colour.SECONDARY}DirtyArrows${Colour.PRIMARY} is available: ${Colour.SECONDARY}v%s${Colour.PRIMARY}"
/**
* Shows that the plugin.yml has been reloaded.
*/
val RELOADED_CONFIG = "$TAG Reloaded ${Colour.SECONDARY}config.yml"
/**
* DirtyArrows enable message.
*/
val ENABLED = "$TAG ${ChatColor.GREEN}Enabled!"
/**
* DirtyArrows disable message.
*/
val DISABLED = "$TAG ${ChatColor.RED}Disabled!"
/**
* Error when not enough xp levels are available.
*
* `%d` = Amount of levels required.
*/
val LEVELS_REQUIRED = "$TAG_ERROR You need ${Colour.ERROR_SECONDARY}%d${Colour.ERROR} levels to craft this bow!"
/**
* Confirmation message for giving a bow to someone.
*
* %s = Bow name.
* %s = Receiver name.
*/
val GAVE_BOW = "$TAG Gave ${Colour.SECONDARY}%s${Colour.PRIMARY} to ${Colour.SECONDARY}%s${Colour.PRIMARY}."
/**
* Set position # to coordinate.
*
* %d = Position number.
* %s = Set coordinate.
*/
val POSITION_SET = "$TAG Set position ${Colour.SECONDARY}%d${Colour.PRIMARY} to ${Colour.SECONDARY}%s${Colour.PRIMARY}."
/**
* List all region names.
*
* %d = Amount of regions.
* %s = List of region names.
*/
val REGIONS_LIST = "$TAG Regions [%d]: ${Colour.SECONDARY}%s${Colour.PRIMARY}."
/**
* Show in which region the player is.
*
* %s = Region name.
*/
val IN_REGION = "$TAG You are in region: ${Colour.SECONDARY}%s${Colour.PRIMARY}"
/**
* You are not in a region.
*/
val NOT_IN_REGION = "$TAG You are not in a DirtyArrows region."
/**
* Removed a region.
*
* %s = Removed region name.
*/
val REGION_REMOVED = "$TAG Removed region ${Colour.SECONDARY}%s${Colour.PRIMARY}."
/**
* Created a region.
*
* %s = Created region name.
*/
val REGION_CREATED = "$TAG Created region ${Colour.SECONDARY}%s${Colour.PRIMARY}."
/**
* Teleported to a certain region.
*
* %s = Region name.
*/
val REGION_TELEPORTED = "$TAG Teleported you to region ${Colour.SECONDARY}%s${Colour.PRIMARY}."
/**
* Got impacted by a headshot from a different player.
*
* %s = Name of player who made the headshot.
*/
val HEADSHOT_BY = "$TAG Headshot by ${Colour.SECONDARY}%s${Colour.PRIMARY}."
/**
* Made a headshot on a different player. For minigames see [MINIGAME_HEADSHOT_ON].
*
* %s = Name of player who was the target of the headshot.
*/
val HEADSHOT_ON = "$TAG You made a headshot on ${Colour.SECONDARY}%s${Colour.PRIMARY}."
/**
* Got impacted by a headshot from a different player (minigame).
*
* %s = Name of player who made the headshot.
*/
val MINIGAME_HEADSHOT_BY = "$TAG_MINIGAME Headshot by ${Colour.SECONDARY}%s${Colour.PRIMARY}."
/**
* Made a headshot on a different player (minigame).
*
* %s = Name of player who was the target of the headshot.
*/
val MINIGAME_HEADSHOT_ON = "$TAG_MINIGAME You made a headshot on ${Colour.SECONDARY}%s${Colour.PRIMARY}."
/**
* No permission to use the bow.
*
* %s = Name of the bow.
*/
val NO_BOW_PERMISSION = "$TAG_ERROR You don't have permission to use ${Colour.PRIMARY}%s{${Colour.ERROR}."
/**
* Cannot use the bow in a protected region.
*
* %s = Name of the bow.
*/
val DISABLED_IN_PROTECTED_REGION = "$TAG_ERROR ${Colour.PRIMARY}%s${Colour.ERROR} is disabled in protected regions."
/**
* Message to list all required resources.
*
* %s = List of required resources.
*/
val NOT_ENOUGH_RESOURCES = "$TAG_ERROR You don't have enough resources, required: ${Colour.PRIMARY}%s${Colour.ERROR}."
/**
* Message to let the player know they defrosted.
*/
val DEFROSTED = "$TAG You defrosted."
/**
* Message to let the player know they are frozen.
*/
val FROZEN = "$TAG You have been frozen."
/**
* Message to let the player know they were cursed.
*/
val CURSED = "$TAG You have been cursed."
/**
* Let know that the curse was lifted.
*/
val CURSE_LIFTED = "$TAG The curse has been lifted."
/**
* Lets know that the bow does not requires ammonution.
*
* %s = bow name.
*/
val NO_AMMO_REQUIRED = "$TAG ${Colour.SECONDARY}%s${Colour.PRIMARY} does not require ammunition."
/**
* Give ammo confirmation.
*
* %s = Item list.
* %s = Target player.
*/
val GAVE_AMMO = "$TAG Gave ${Colour.TERTIARY}%s${Colour.PRIMARY} to ${Colour.SECONDARY}%s${Colour.PRIMARY}."
/**
* You have to wait X seconds to use the bow again.
*
* %.1f = The amount of seconds left.
* %s = Bow name.
*/
val COOLDOWN = "$TAG_ERROR Wait ${Colour.PRIMARY}%.1fs${Colour.ERROR} before you can use ${Colour.SECONDARY}%s${Colour.ERROR} again."
/**
* Notifies that they player misses a music disc in their inventory.
*/
val NO_RECORD = "$TAG_ERROR You need a ${Colour.PRIMARY}music disc${Colour.ERROR} in your inventory to play music."
/**
* Get the message that shows whether DA is enabled or disabled.
*
* @param plugin
* The DirtyArrows plugin.
* @param enabled
* Whether DA is enabled (`true`) or disabled (`false`).
*/
fun enabledMessage(plugin: DirtyArrows, enabled: Boolean = true): String {
if (plugin.isMinigameVersion()) return ""
return if (enabled) ENABLED else DISABLED
}
/**
* Get the regular tag for messages.
*/
fun tag(plugin: DirtyArrows) = if (plugin.isMinigameVersion()) TAG_MINIGAME else TAG
/**
* Get the message to show when a player makes or receives a headshot.
*
* @param playerInMessage
* The applicable player.
* @param headshotType
* Whether the headshot was made by, or on `playerInMessage`.
* @param plugin
* The DirtyArrows plugin.
*/
fun headshot(playerInMessage: Player, headshotType: HeadshotType, plugin: DirtyArrows): String {
return if (plugin.isMinigameVersion()) {
headshotType.minigameMessage.format(playerInMessage.displayName)
}
else headshotType.message.format(playerInMessage.displayName)
}
/**
* @author SugarCaney
*/
object Colour {
val PRIMARY = ChatColor.YELLOW
val SECONDARY = ChatColor.GREEN
val TERTIARY = ChatColor.WHITE
val ERROR = ChatColor.RED
val ERROR_SECONDARY = ChatColor.GRAY
}
}
/**
* @see [Broadcast.tag]
*/
fun DirtyArrows.tag() = Broadcast.tag(this)
/**
* @see [Broadcast.headshot]
*/
fun DirtyArrows.headshot(playerInMessage: Player, headshotType: HeadshotType): String {
return Broadcast.headshot(playerInMessage, headshotType, this)
} | gpl-3.0 | b88af3f8feea9922cbe64f83f9c3955d | 28.451737 | 157 | 0.606267 | 3.777613 | false | false | false | false |
walleth/walleth | app/src/main/java/org/walleth/tokens/CreateTokenDefinitionActivity.kt | 1 | 3743 | package org.walleth.tokens
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
import androidx.lifecycle.lifecycleScope
import kotlinx.android.synthetic.main.activity_create_token.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.kethereum.model.Address
import org.koin.android.ext.android.inject
import org.ligi.kaxtui.alert
import org.walleth.R
import org.walleth.base_activities.BaseSubActivity
import org.walleth.chains.ChainInfoProvider
import org.walleth.data.AppDatabase
import org.walleth.data.tokens.Token
import org.walleth.qr.scan.getQRScanActivity
class CreateTokenDefinitionActivity : BaseSubActivity() {
val appDatabase: AppDatabase by inject()
val chainInfoProvider: ChainInfoProvider by inject()
private val scanQRForResult: ActivityResultLauncher<Intent> = registerForActivityResult(StartActivityForResult()) {
if (it.resultCode == Activity.RESULT_OK) {
token_address_input.setText(it.data?.getStringExtra("SCAN_RESULT"))
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_create_token)
supportActionBar?.subtitle = getString(R.string.create_token_activity_subtitle)
fab.setOnClickListener {
val newDecimals = token_decimals_input.text.toString().toIntOrNull()
val newTokenName = token_name_input.text.toString()
val newTokenAddress = token_address_input.text.toString()
if (newDecimals == null || newDecimals > 42) {
alert(R.string.create_token_activity_error_invalid_amount_of_decimals)
} else if (newTokenName.isBlank()) {
alert(R.string.create_token_activity_error_invalid_name)
} else if (newTokenAddress.isBlank()) {
alert(R.string.create_token_activity_error_invalid_address)
} else {
lifecycleScope.launch(Dispatchers.Main) {
chainInfoProvider.getFlow().collect { networkDefinition ->
lifecycleScope.launch(Dispatchers.Main) {
withContext(Dispatchers.Default) {
appDatabase.tokens.upsert(Token(
name = newTokenName,
symbol = newTokenName,
address = Address(newTokenAddress),
decimals = newDecimals,
chain = networkDefinition.chainId,
deleted = false,
starred = true,
fromUser = true,
order = 0
))
}
finish()
}
}
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_import, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.menu_scan -> true.also {
scanQRForResult.launch(getQRScanActivity())
}
else -> super.onOptionsItemSelected(item)
}
}
| gpl-3.0 | eaff964ed79ce78a3a541bfe0a402a70 | 39.247312 | 119 | 0.609404 | 5.234965 | false | false | false | false |
da1z/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/expressions/javaUCallExpressions.kt | 2 | 7343 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiTypesUtil
import org.jetbrains.uast.*
import org.jetbrains.uast.psi.UElementWithLocation
class JavaUCallExpression(
override val psi: PsiMethodCallExpression,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallExpression, UElementWithLocation {
override val kind: UastCallKind
get() = UastCallKind.METHOD_CALL
override val methodIdentifier by lz {
val methodExpression = psi.methodExpression
val nameElement = methodExpression.referenceNameElement ?: return@lz null
UIdentifier(nameElement, this)
}
override val classReference: UReferenceExpression?
get() = null
override val valueArgumentCount by lz { psi.argumentList.expressions.size }
override val valueArguments by lz { psi.argumentList.expressions.map { JavaConverter.convertOrEmpty(it, this) } }
override val typeArgumentCount by lz { psi.typeArguments.size }
override val typeArguments: List<PsiType>
get() = psi.typeArguments.toList()
override val returnType: PsiType?
get() = psi.type
override val methodName: String?
get() = psi.methodExpression.referenceName
override fun resolve() = psi.resolveMethod()
override fun getStartOffset(): Int =
psi.methodExpression.referenceNameElement?.textOffset ?: psi.methodExpression.textOffset
override fun getEndOffset() = psi.textRange.endOffset
override val receiver: UExpression?
get() {
uastParent.let { uastParent ->
return if (uastParent is UQualifiedReferenceExpression && uastParent.selector == this)
uastParent.receiver
else
null
}
}
override val receiverType: PsiType?
get() {
val qualifierType = psi.methodExpression.qualifierExpression?.type
if (qualifierType != null) {
return qualifierType
}
val method = resolve() ?: return null
if (method.hasModifierProperty(PsiModifier.STATIC)) return null
val psiManager = psi.manager
val containingClassForMethod = method.containingClass ?: return null
val containingClass = PsiTreeUtil.getParentOfType(psi, PsiClass::class.java)
val containingClassSequence = generateSequence(containingClass) {
if (it.hasModifierProperty(PsiModifier.STATIC))
null
else
PsiTreeUtil.getParentOfType(it, PsiClass::class.java)
}
val receiverClass = containingClassSequence.find { containingClassForExpression ->
psiManager.areElementsEquivalent(containingClassForMethod, containingClassForExpression) ||
containingClassForExpression.isInheritor(containingClassForMethod, true)
}
return receiverClass?.let { PsiTypesUtil.getClassType(it) }
}
}
class JavaConstructorUCallExpression(
override val psi: PsiNewExpression,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallExpression {
override val kind by lz {
when {
psi.arrayInitializer != null -> UastCallKind.NEW_ARRAY_WITH_INITIALIZER
psi.arrayDimensions.isNotEmpty() -> UastCallKind.NEW_ARRAY_WITH_DIMENSIONS
else -> UastCallKind.CONSTRUCTOR_CALL
}
}
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
override val methodIdentifier: UIdentifier?
get() = null
override val classReference by lz {
psi.classReference?.let { ref ->
JavaConverter.convertReference(ref, this, null) as? UReferenceExpression
}
}
override val valueArgumentCount: Int
get() {
val initializer = psi.arrayInitializer
return when {
initializer != null -> initializer.initializers.size
psi.arrayDimensions.isNotEmpty() -> psi.arrayDimensions.size
else -> psi.argumentList?.expressions?.size ?: 0
}
}
override val valueArguments by lz {
val initializer = psi.arrayInitializer
when {
initializer != null -> initializer.initializers.map { JavaConverter.convertOrEmpty(it, this) }
psi.arrayDimensions.isNotEmpty() -> psi.arrayDimensions.map { JavaConverter.convertOrEmpty(it, this) }
else -> psi.argumentList?.expressions?.map { JavaConverter.convertOrEmpty(it, this) } ?: emptyList()
}
}
override val typeArgumentCount by lz { psi.classReference?.typeParameters?.size ?: 0 }
override val typeArguments: List<PsiType>
get() = psi.classReference?.typeParameters?.toList() ?: emptyList()
override val returnType: PsiType?
get() = (psi.classReference?.resolve() as? PsiClass)?.let { PsiTypesUtil.getClassType(it) } ?: psi.type
override val methodName: String?
get() = null
override fun resolve() = psi.resolveMethod()
}
class JavaArrayInitializerUCallExpression(
override val psi: PsiArrayInitializerExpression,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallExpression {
override val methodIdentifier: UIdentifier?
get() = null
override val classReference: UReferenceExpression?
get() = null
override val methodName: String?
get() = null
override val valueArgumentCount by lz { psi.initializers.size }
override val valueArguments by lz { psi.initializers.map { JavaConverter.convertOrEmpty(it, this) } }
override val typeArgumentCount: Int
get() = 0
override val typeArguments: List<PsiType>
get() = emptyList()
override val returnType: PsiType?
get() = psi.type
override val kind: UastCallKind
get() = UastCallKind.NESTED_ARRAY_INITIALIZER
override fun resolve() = null
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
}
class JavaAnnotationArrayInitializerUCallExpression(
override val psi: PsiArrayInitializerMemberValue,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallExpression {
override val kind: UastCallKind
get() = UastCallKind.NESTED_ARRAY_INITIALIZER
override val methodIdentifier: UIdentifier?
get() = null
override val classReference: UReferenceExpression?
get() = null
override val methodName: String?
get() = null
override val valueArgumentCount by lz { psi.initializers.size }
override val valueArguments by lz {
psi.initializers.map {
JavaConverter.convertPsiElement(it, this) as? UExpression ?: UnknownJavaExpression(it, this)
}
}
override val typeArgumentCount: Int
get() = 0
override val typeArguments: List<PsiType>
get() = emptyList()
override val returnType: PsiType?
get() = null
override fun resolve() = null
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
} | apache-2.0 | ca3fd88ecfa0098b4577b4b499f2a49a | 29.857143 | 115 | 0.724227 | 4.978305 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.