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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
google/ksp | test-utils/src/main/kotlin/com/google/devtools/ksp/processor/JavaModifierProcessor.kt | 1 | 2833 | /*
* Copyright 2020 Google LLC
* Copyright 2010-2020 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.processor
import com.google.devtools.ksp.KspExperimental
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.symbol.*
import com.google.devtools.ksp.symbol.KSPropertyDeclaration
import com.google.devtools.ksp.visitor.KSTopDownVisitor
class JavaModifierProcessor : AbstractTestProcessor() {
val results = mutableListOf<String>()
override fun toResult(): List<String> {
return results
}
override fun process(resolver: Resolver): List<KSAnnotated> {
resolver.getSymbolsWithAnnotation("Test")
.map {
it as KSClassDeclaration
}
.forEach {
it.superTypes.single().resolve().declaration.accept(ModifierVisitor(resolver), Unit)
}
return emptyList()
}
inner class ModifierVisitor(val resolver: Resolver) : KSTopDownVisitor<Unit, Unit>() {
override fun defaultHandler(node: KSNode, data: Unit) {
}
override fun visitClassDeclaration(classDeclaration: KSClassDeclaration, data: Unit) {
results.add(classDeclaration.toSignature())
classDeclaration.declarations.forEach { it.accept(this, data) }
}
override fun visitPropertyDeclaration(property: KSPropertyDeclaration, data: Unit) {
results.add(property.toSignature())
}
override fun visitFunctionDeclaration(function: KSFunctionDeclaration, data: Unit) {
results.add(function.toSignature())
}
@OptIn(KspExperimental::class)
private fun KSDeclaration.toSignature(): String {
val parent = parentDeclaration
val id = if (parent == null) {
""
} else {
"${parent.simpleName.asString()}."
} + simpleName.asString()
val modifiersSignature = modifiers.map { it.toString() }.sorted().joinToString(" ")
val extras = resolver.effectiveJavaModifiers(this).map { it.toString() }.sorted().joinToString(" ").trim()
return "$id: $modifiersSignature".trim() + " : " + extras
}
}
}
| apache-2.0 | ec730eb39c81f3817b9dab58c59c38f6 | 37.283784 | 118 | 0.665372 | 4.753356 | false | false | false | false |
toastkidjp/Yobidashi_kt | todo/src/main/java/jp/toastkid/todo/model/TodoTask.kt | 2 | 960 | /*
* Copyright (c) 2019 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.todo.model
import android.graphics.Color
import androidx.annotation.ColorInt
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.io.Serializable
/**
* @author toastkidjp
*/
@Entity
class TodoTask(
@PrimaryKey(autoGenerate = true)
var id: Int
): Serializable {
var description: String = ""
var bigram: String = ""
var created: Long = 0L
var lastModified: Long = 0L
var dueDate: Long = 0L
var categoryId: Int = 0
var boardId: Int = 0
var x: Float = 0f
var y: Float = 0f
@ColorInt
var color: Int = Color.CYAN
var done: Boolean = false
} | epl-1.0 | f3cac1f9ee7dac4b5388dd880a7d56af | 19.891304 | 88 | 0.690625 | 3.950617 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/annotator/fixes/AddSelfFix.kt | 2 | 1402 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator.fixes
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.ext.valueParameters
class AddSelfFix(val function: RsFunction) : LocalQuickFixAndIntentionActionOnPsiElement(function) {
override fun getFamilyName() = "Add self to function"
override fun getText() = "Add self to function"
override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) {
val hasParameters = function.valueParameters.isNotEmpty()
val psiFactory = RsPsiFactory(project)
val valueParameterList = function.valueParameterList
val lparen = valueParameterList?.firstChild
val self = psiFactory.createSelf()
valueParameterList?.addAfter(self, lparen)
if (hasParameters) {
// IDE error if use addAfter(comma, self)
val parent = lparen?.parent
parent?.addAfter(psiFactory.createComma(), parent.firstChild.nextSibling)
}
}
}
| mit | 9ab4ce83d6b2fc001f47bab168633a17 | 35.894737 | 125 | 0.739658 | 4.657807 | false | false | false | false |
jtransc/jtransc | jtransc-utils/src/com/jtransc/sourcemaps/sourcemaps.kt | 1 | 3416 | package com.jtransc.sourcemaps
import com.jtransc.json.Json
import java.util.*
object Sourcemaps {
fun decodeRaw(str: String): List<List<List<Int>>> {
return str.split(";").map {
it.split(",").map { Base64Vlq.decode(it) }
}
}
fun encodeRaw(items: List<List<List<Int>>>): String {
return items.map {
it.map { Base64Vlq.encode(it) }.joinToString(",")
}.joinToString(";")
}
data class MappingItem(val sourceIndex: Int, val sourceLine: Int, val sourceColumn: Int, val targetColumn: Int)
data class MappingRow(val mappings: List<MappingItem>)
data class MappingFile(val rows: List<MappingRow>)
data class TargetMapping(val name: String, val line: Int, val column: Int)
data class SourceMap(
val version: Int = 3,
val file: String = "unknown.js",
val sourceRoot: String = "file:///",
val sources: List<String> = arrayListOf<String>(),
val names: List<String> = arrayListOf<String>(),
val mappings: String = ""
) {
val mappingFile = decode(mappings)
fun decodePos(line: Int, column: Int = 0): TargetMapping? {
for (item in mappingFile.rows.getOrNull(line)?.mappings ?: listOf()) {
if (item.targetColumn >= column) {
return TargetMapping(sourceRoot + sources[item.sourceIndex], item.sourceLine, item.sourceColumn)
}
}
return null
}
}
fun decodeFile(str: String) = Json.decodeTo<SourceMap>(str)
fun decode(str: String): MappingFile {
var sourceLine = 0
var sourceIndex = 0
var sourceColumn = 0
return MappingFile(decodeRaw(str).map { row ->
var targetColumn = 0
MappingRow(row.flatMap { info ->
if (info.size >= 4) {
targetColumn += info[0]
sourceIndex += info[1]
sourceLine += info[2]
sourceColumn += info[3]
listOf(MappingItem(sourceIndex, sourceLine, sourceColumn, targetColumn))
} else {
listOf()
}
})
})
}
fun encode(mapping: MappingFile): String {
var sourceLine = 0
var sourceIndex = 0
var sourceColumn = 0
val lists = mapping.rows.map { row ->
var targetColumn = 0
row.mappings.map {
listOf(
it.targetColumn - targetColumn,
it.sourceIndex - sourceIndex,
it.sourceLine - sourceLine,
it.sourceColumn - sourceColumn
).apply {
sourceIndex = it.sourceIndex
sourceLine = it.sourceLine
sourceColumn = it.sourceColumn
targetColumn = it.targetColumn
}
}
}
return encodeRaw(lists)
}
fun encodeFile(targetPath: String, targetContent: String, source: String, mappings: HashMap<Int, Int>): String {
//(0 until targetContent.count { it == '\n' }).map {}
val mapping = MappingFile((0 until (mappings.keys.maxOrNull() ?: 1)).map {
val targetLine = mappings[it]
MappingRow(if (targetLine == null) listOf() else listOf(MappingItem(0, targetLine, 0, 0)))
})
return Json.encode(mapOf(
"version" to 3,
"file" to targetPath,
"sources" to arrayListOf(source),
"names" to arrayListOf<String>(),
"mappings" to encode(mapping)
), prettify = true)
}
fun encodeFile(files: List<String>, mappings: Map<Int, MappingItem>): String {
val mapping = MappingFile((0 until (mappings.keys.maxOrNull() ?: 1)).map {
val item = mappings[it]
MappingRow(if (item == null) listOf() else listOf(item))
})
return Json.encode(mapOf(
"version" to 3,
"file" to "program.js",
"sources" to files,
"names" to arrayListOf<String>(),
"mappings" to encode(mapping)
), prettify = true)
}
} | apache-2.0 | 84dfae025774113b2e90dc428874a11b | 27.239669 | 113 | 0.665398 | 3.339198 | false | false | false | false |
empros-gmbh/kmap | data/src/main/kotlin/ch/empros/kmap/ResultSetExt.kt | 1 | 3542 | package ch.empros.kmap
import java.sql.ResultSet
import java.sql.Types
/**
* Extension function that maps this [ResultSet]'s JDBC-based metadata to a kMap metadata object.
*/
fun ResultSet.kMapMetaData(): MetaData =
MetaData(
IntRange(1, metaData.columnCount)
.map { i ->
with(metaData) {
val name = getColumnName(i)
val label = getColumnLabel(i)
when (val cType = getColumnType(i)) {
Types.BOOLEAN -> BooleanColumn(name, label)
Types.CLOB -> ClobColumn(name, label)
Types.DATE -> DateColumn(name, label)
Types.FLOAT, Types.REAL -> FloatColumn(name, label)
Types.DOUBLE -> DoubleColumn(name, label)
Types.INTEGER -> IntColumn(name, label)
Types.BIGINT -> LongColumn(name, label)
Types.NUMERIC, Types.DECIMAL -> BigDecimalColumn(name, label)
Types.TIMESTAMP -> DateTimeColumn(name, label)
Types.VARCHAR, Types.NCHAR, Types.NVARCHAR, Types.LONGNVARCHAR, Types.LONGVARCHAR -> StringColumn(name, label, getColumnDisplaySize(i))
else -> throw IllegalArgumentException("KMap ResultSet Mapping: Unsupported SQL-Type '$cType'")
}
}
}
)
/**
* Extension function that reads this [ResultSet]'s records and puts them into a [Page] object.
* Upon completion this [ResultSet] is closed.
* TODO This method is wrong! We may not close the ResultSet automatically, we need to iterate lazily.
*/
fun ResultSet.toPageThenClose(): Page {
if (isClosed) throw IllegalStateException("Unable to read data from closed resultSet")
val records = mutableListOf<Record>()
val metaData = kMapMetaData()
while (next()) {
records.add(currentRecord(metaData))
}
close()
return Page(metaData, records)
}
/**
* Extension function that creates a KMap [Record] for the current entry on this [ResultSet].
* Usually you do not need to call this method directly and rather use [toPageThenClose] to get this [ResultSet]'s data.
*
* But if you think you absolutely must use this method, read on:
* If you call this method repeatedly on the same [ResultSet] instance, you can prevent the repeated construction of a
* [kMapMetaData] object by calling [ResultSet.kMapMetaData()] beforehand and pass its result to this method,
* see [toPageThenClose] for an example.
*
* It is possible to call this method with a [MetaData] instance that was created on another [ResultSet] instance.
* The implementation does not take any measures to prevent you from doing such a stupid thing, and you will likely get an
* exception as a result. So heed your doctor's advice: if it hurts, don't do it.
*/
fun ResultSet.currentRecord(metaData: MetaData = kMapMetaData()): Record {
val values = IntRange(0, metaData.colCount - 1).map { index ->
val value: Any? = when (val kmColumn = metaData[index]) {
is BooleanColumn -> this.getBoolean(kmColumn.label)
is BigDecimalColumn -> this.getBigDecimal(kmColumn.label)
is DateColumn -> this.getDate(kmColumn.label)
is DateTimeColumn -> this.getTimestamp(kmColumn.label)
is DoubleColumn -> this.getDouble(kmColumn.label)
is FloatColumn -> this.getFloat(kmColumn.label)
is LongColumn -> this.getLong(kmColumn.label)
is IntColumn -> this.getInt(kmColumn.label)
is StringColumn -> this.getString(kmColumn.label)
is ClobColumn -> this.getClob(kmColumn.label).characterStream.readText()
}
value
}.toList()
return Record(metaData, values)
}
| mit | 2f0cae7c611b43d2b8421f79abeec96e | 42.728395 | 147 | 0.694241 | 4.104287 | false | false | false | false |
pnemonic78/RemoveDuplicates | duplicates-android/app/src/main/java/com/github/duplicates/contact/ContactViewHolder.kt | 1 | 5247 | /*
* Copyright 2016, Moshe Waisberg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.duplicates.contact
import android.content.Context
import android.view.ViewGroup
import com.github.android.removeduplicates.BuildConfig
import com.github.android.removeduplicates.R
import com.github.android.removeduplicates.databinding.SameContactBinding
import com.github.duplicates.DuplicateItemPair
import com.github.duplicates.DuplicateViewHolder
import com.github.duplicates.contact.ContactComparator.Companion.EMAIL
import com.github.duplicates.contact.ContactComparator.Companion.EVENT
import com.github.duplicates.contact.ContactComparator.Companion.IM
import com.github.duplicates.contact.ContactComparator.Companion.NAME
import com.github.duplicates.contact.ContactComparator.Companion.PHONE
import java.util.*
/**
* View holder of a duplicate contact.
*
* @author moshe.w
*/
class ContactViewHolder(
itemView: ViewGroup,
binding: SameContactBinding,
onCheckedChangeListener: OnItemCheckedChangeListener<ContactItem>? = null
) : DuplicateViewHolder<ContactItem>(itemView, onCheckedChangeListener) {
private val match = binding.match
private val checkbox1 = binding.item1.checkbox
private val icon1 = binding.item1.icon
private val account1 = binding.item1.account
private val name1 = binding.item1.name
private val email1 = binding.item1.email
private val event1 = binding.item1.event
private val im1 = binding.item1.im
private val phone1 = binding.item1.phone
private val checkbox2 = binding.item2.checkbox
private val icon2 = binding.item2.icon
private val account2 = binding.item2.account
private val name2 = binding.item2.name
private val email2 = binding.item2.email
private val event2 = binding.item2.event
private val im2 = binding.item2.im
private val phone2 = binding.item2.phone
init {
checkbox1.setOnClickListener {
onCheckedChangeListener?.onItemCheckedChangeListener(item1, checkbox1.isChecked)
}
checkbox2.setOnClickListener {
onCheckedChangeListener?.onItemCheckedChangeListener(item2, checkbox2.isChecked)
}
}
override fun bindHeader(context: Context, pair: DuplicateItemPair<ContactItem>) {
match.text =
context.getString(R.string.match, percentFormatter.format(pair.match.toDouble()))
}
override fun bindItem1(context: Context, item: ContactItem) {
checkbox1.isChecked = item.isChecked
checkbox1.text = if (BuildConfig.DEBUG) item.id.toString() else ""
if (item.photoThumbnailUri == null) {
icon1.setImageResource(R.drawable.ic_person_outline)
} else {
icon1.setImageURI(item.photoThumbnailUri)
}
account1.text =
context.getString(R.string.contacts_account, item.accountName, item.accountType)
name1.text = item.displayName
email1.text = formatData(item.emails)
event1.text = formatData(item.events)
im1.text = formatData(item.ims)
phone1.text = formatData(item.phones)
}
override fun bindItem2(context: Context, item: ContactItem) {
checkbox2.isChecked = item.isChecked
checkbox2.text = if (BuildConfig.DEBUG) item.id.toString() else ""
if (item.photoThumbnailUri == null) {
icon2.setImageResource(R.drawable.ic_person_outline)
} else {
icon2.setImageURI(item.photoThumbnailUri)
}
account2.text =
context.getString(R.string.contacts_account, item.accountName, item.accountType)
name2.text = item.displayName
email2.text = formatData(item.emails)
event2.text = formatData(item.events)
im2.text = formatData(item.ims)
phone2.text = formatData(item.phones)
}
override fun bindDifference(context: Context, pair: DuplicateItemPair<ContactItem>) {
val difference = pair.difference
bindDifference(email1, email2, difference[EMAIL])
bindDifference(event1, event2, difference[EVENT])
bindDifference(im1, im2, difference[IM])
bindDifference(name1, name2, difference[NAME])
bindDifference(phone1, phone2, difference[PHONE])
}
private fun formatData(data: Collection<ContactData>): CharSequence? {
if (data.isEmpty()) {
return null
}
val unique: MutableSet<String> = HashSet(data.size)
for (datum in data) {
unique.add(datum.toString())
}
val s = StringBuilder()
for (u in unique) {
if (s.isNotEmpty()) {
s.append("; ")
}
s.append(u)
}
return s
}
}
| apache-2.0 | bc5afbaf149dc895a06496e2382d94e0 | 37.021739 | 93 | 0.69716 | 4.224638 | false | false | false | false |
AdamMc331/SwipeDeck2 | swipedeck/src/main/java/com/daprlabs/aaron/swipedeck/SwipeDeck.kt | 1 | 15865 | package com.daprlabs.aaron.swipedeck
import android.content.Context
import android.database.DataSetObserver
import android.os.Build
import android.support.design.widget.CoordinatorLayout
import android.support.v4.view.ViewCompat
import android.util.AttributeSet
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Adapter
import android.widget.FrameLayout
import com.daprlabs.aaron.swipedeck.utility.Deck
import com.daprlabs.aaron.swipedeck.utility.SwipeCallback
import java.util.*
/**
* Maintains a deck of cards that can be swiped.
*
* @property[previewLayoutId] Preview layout when swipeCard is attached??
* @property[numberOfSimultaneousCards] The number of cards that will be seen in the stack at a time.
* @property[cardSpacing] The spacing between each swipeCard.
* @property[buffer] The cards to be displayed. TODO: Discover how this is different from deck.
* @property[deck] The cards to be displayed. TODO: Discover how this is different from buffer.
* @property[mHasStableIds] Whether [adapter] has stable IDs or not.
* @property[adapter] An adapter for all the cards to display.
* @property[observer] A watcher that handles changes to the dataset.
* @property[callback] The callback to use when cards are swiped. TODO: This exists in CardContainer.
* @property[leftImageResource] The image resource on the left of a swipeCard. TODO: This exists in CardContainer.
* @property[rightImageResource] The image resource on the right of a swipeCard. TODO: This exists in CardContainer.
* @property[endOpacity] The opacity of the swipeCard at the end of a swipe.
* @property[rotationDegrees] The degrees a swipeCard should rotate as its being swiped.
* @property[renderAbove] Whether the swipe deck should be rendered above everything else.
* @property[swipeEnabled] Whether or not the cards can be swiped.
* @property[adapterIndex] The current index of [adapter].
*/
open class SwipeDeck(context: Context, attrs: AttributeSet) : CoordinatorLayout(context, attrs) {
private val previewLayoutId: Int
private val numberOfSimultaneousCards: Int
private val cardSpacing: Float
private val buffer = ArrayList<SwipeCard>()
private lateinit var deck: Deck<SwipeCard>
private var mHasStableIds: Boolean = false
private var adapter: Adapter? = null
private var observer: DataSetObserver? = null
private var callback: SwipeDeckCallback? = null
var leftImageResource: Int = 0
var rightImageResource: Int = 0
var endOpacity: Float = 0F
var rotationDegrees: Float = 0F
var renderAbove: Boolean = false
var swipeEnabled: Boolean = false
var adapterIndex = 0
init {
val a = context.theme.obtainStyledAttributes(
attrs,
R.styleable.SwipeDeck2,
0, 0)
numberOfSimultaneousCards = a.getInt(R.styleable.SwipeDeck2_max_visible, 3)
endOpacity = a.getFloat(R.styleable.SwipeDeck2_opacity_end, 0.33f)
rotationDegrees = a.getFloat(R.styleable.SwipeDeck2_rotation_degrees, 15f)
cardSpacing = a.getDimension(R.styleable.SwipeDeck2_card_spacing, 15f)
renderAbove = a.getBoolean(R.styleable.SwipeDeck2_render_above, true)
swipeEnabled = a.getBoolean(R.styleable.SwipeDeck2_swipe_enabled, true)
previewLayoutId = a.getResourceId(R.styleable.SwipeDeck2_preview_layout, -1)
deck = Deck<SwipeCard>(object : Deck.DeckEventListener<SwipeCard> {
override fun itemAddedFront(item: SwipeCard) {
deck.first?.setSwipeEnabled(swipeEnabled)
// If our deck is too large now, remove the last item.
if (deck.size() > numberOfSimultaneousCards) {
deck.removeLast()
adapterIndex--
}
renderDeck()
}
//TODO: Figure out why this doesn't care about deck size? Why does it set the first enabled?
override fun itemAddedBack(item: SwipeCard) {
deck.first?.setSwipeEnabled(swipeEnabled)
renderDeck()
}
override fun itemRemovedFront(item: SwipeCard) {
buffer.add(item)
deck.first?.setSwipeEnabled(swipeEnabled)
item.cleanupAndRemoveView()
addNextView()
renderDeck()
}
override fun itemRemovedBack(item: SwipeCard) {
item.card
?.animate()
?.setDuration(100)
?.alpha(0f)
}
})
// Set clipping of view parent to false so cards can render outside their boundary.
// Make sure not to clip to padding.
clipToPadding = false
clipChildren = false
this.setWillNotDraw(false)
// If render above is set make sure everything in this view renders above other views.
if (renderAbove) {
ViewCompat.setTranslationZ(this, java.lang.Float.MAX_VALUE)
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (isInEditMode && previewLayoutId != -1) {
for (i in numberOfSimultaneousCards - 1 downTo 0) {
val view = LayoutInflater.from(context).inflate(previewLayoutId, this, false)
val params = view.layoutParams as FrameLayout.LayoutParams
val offset = (i * cardSpacing).toInt()
// All cards are placed in absolute coordinates, so disable gravity if we have any
params.gravity = Gravity.NO_GRAVITY
// We can't user translations here, for some reason it's not rendered properly in preview
params.topMargin = offset
view.layoutParams = params
addViewInLayout(view, -1, params, true)
}
setZTranslations()
}
}
fun setAdapter(adapter: Adapter) {
this.adapter?.unregisterDataSetObserver(observer)
mHasStableIds = adapter.hasStableIds()
this.adapter = adapter
observer = object : DataSetObserver() {
override fun onChanged() {
super.onChanged()
//handle data set changes
//if we need to add any cards at this point (ie. the amount of cards in the deck
//is less than the max number of cards to display) add the cards.
val deckSize = deck.size()
//only perform action if there are less cards on screen than NUMBER_OF_CARDS
if (deckSize < numberOfSimultaneousCards) {
for (i in deckSize..numberOfSimultaneousCards - 1) {
addNextView()
}
}
// If the adapter has been emptied empty the view and reset adapterIndex
if (adapter.count == 0) {
deck.clear()
adapterIndex = 0
}
}
override fun onInvalidated() {
// Reset state, remove views and request layout
deck.clear()
removeAllViews()
requestLayout()
}
}
adapter.registerDataSetObserver(observer)
requestLayout()
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
if (isInEditMode) return
// If we don't have an adapter, we don't need to do anything
if (adapter == null || adapter?.count == 0) {
removeAllViewsInLayout()
return
}
// Pull in views from the adapter at the position the top of the deck is set to
// stop when you get to for cards or the end of the adapter.
val deckSize = deck.size()
for (i in deckSize..numberOfSimultaneousCards - 1) {
addNextView()
}
}
/**
* TODO: Investigate the difference between this and addLastView and see if anything can be abstracted out.
*/
private fun addNextView() {
if (adapterIndex < (adapter?.count ?: 0)) {
val newBottomChild = adapter?.getView(adapterIndex, null, this)
newBottomChild?.setLayerType(View.LAYER_TYPE_HARDWARE, null)
//todo: i'm setting the swipeCard to invisible initially and making it visible when i animate
//later
newBottomChild?.alpha = 0f
newBottomChild?.y = paddingTop.toFloat()
val viewId = adapter?.getItemId(adapterIndex) ?: 0
val card = SwipeCard(newBottomChild, CardContainerCallback(viewId), this)
card.positionWithinAdapter = adapterIndex
if (leftImageResource != 0) {
card.setLeftImageResource(leftImageResource)
}
if (rightImageResource != 0) {
card.setRightImageResource(rightImageResource)
}
card.id = viewId
deck.addLast(card)
adapterIndex++
}
}
private fun addLastView() {
// Get the position of the swipeCard prior to the swipeCard atop the deck
val positionOfLastCard: Int
// If there's a swipeCard on the deck get the swipeCard before it, otherwise the last swipeCard is one
// before the adapter index.
if (deck.size() > 0) {
positionOfLastCard = deck.first?.positionWithinAdapter?.minus(1) ?: 0
} else {
positionOfLastCard = adapterIndex - 1
}
if (positionOfLastCard >= 0) {
val newBottomChild = adapter?.getView(positionOfLastCard, null, this)
newBottomChild?.setLayerType(View.LAYER_TYPE_HARDWARE, null)
//todo: i'm setting the swipeCard to invisible initially and making it visible when i animate
//later
newBottomChild?.alpha = 0f
newBottomChild?.y = paddingTop.toFloat()
val viewId = adapter?.getItemId(positionOfLastCard) ?: 0
val card = SwipeCard(newBottomChild, CardContainerCallback(viewId), this)
if (leftImageResource != 0) {
card.setLeftImageResource(leftImageResource)
}
if (rightImageResource != 0) {
card.setRightImageResource(rightImageResource)
}
card.id = viewId
deck.addFirst(card)
card.positionWithinAdapter = positionOfLastCard
}
}
private fun renderDeck() {
// We remove all the views and re add them so that the Z translation is correct
removeAllViews()
for (i in deck.size() - 1 downTo 0) {
val container = deck[i]
val card = container.card
val params = card?.layoutParams ?: ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT)
addViewInLayout(card, -1, params, true)
val itemWidth = width - (paddingLeft + paddingRight)
val itemHeight = height - (paddingTop + paddingBottom)
card?.measure(View.MeasureSpec.EXACTLY or itemWidth, View.MeasureSpec.EXACTLY or itemHeight)
}
// If there's still a swipeCard animating in the buffer, make sure it's re added after removing all views
// cards in buffer go from older ones to newer
// in our deck, newer cards are placed below older cards
// we need to start with new cards, so older cards would be above them
for (i in buffer.indices.reversed()) {
val card = buffer[i].card
val params= card?.layoutParams ?: ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT)
addViewInLayout(card, -1, params, true)
val itemWidth = width - (paddingLeft + paddingRight)
val itemHeight = height - (paddingTop + paddingBottom)
card?.measure(View.MeasureSpec.EXACTLY or itemWidth, View.MeasureSpec.EXACTLY or itemHeight)
}
positionCards()
}
private fun positionCards() {
setZTranslations()
for (i in 0..deck.size() - 1) {
animateCardPosition(deck[i].card, deck[i].positionWithinViewGroup)
}
}
protected open fun animateCardPosition(card: View?, position: Int) {
val offset = (position * cardSpacing).toInt().toFloat()
card?.animate()
?.setDuration(ANIMATION_DURATION)
?.y(paddingTop + offset)
?.alpha(1.0f)
}
fun setCallback(callback: SwipeDeckCallback) {
this.callback = callback
}
/**
* Swipe top swipeCard to the left side.
* TODO: This can be moved to the card and/or deck
*
* @param duration animation duration in milliseconds
*/
fun swipeTopCardLeft(duration: Long = ANIMATION_DURATION) {
if (deck.size() > 0) {
deck[0].swipeCardLeft(duration)
callback?.cardSwipedLeft(deck[0].id)
deck.removeFirst()
}
}
/**
* Swipe swipeCard to the right side.
* TODO: This can be moved to the card and/or deck
*
* @param duration animation duration in milliseconds
*/
fun swipeTopCardRight(duration: Long = ANIMATION_DURATION) {
if (deck.size() > 0) {
deck[0].swipeCardRight(duration)
callback?.cardSwipedRight(deck[0].id)
deck.removeFirst()
}
}
fun unSwipeCard() {
addLastView()
}
fun removeFromBuffer(container: SwipeCard) {
this.buffer.remove(container)
}
private fun setZTranslations() {
//this is only needed to add shadows to cardviews on > lollipop
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val count = childCount
for (i in 0..count - 1) {
getChildAt(i).translationZ = (i * 10).toFloat()
}
}
}
interface SwipeDeckCallback {
fun cardSwipedLeft(itemId: Long)
fun cardSwipedRight(itemId: Long)
/**
* Check whether we can start dragging view with provided id.
*
* @param itemId id of the swipeCard returned by adapter's [Adapter.getItemId]
* *
* @return true if we can start dragging view, false otherwise
*/
fun isDragEnabled(itemId: Long): Boolean
}
private inner class CardContainerCallback(private val viewId: Long) : SwipeCallback {
override fun cardSwipedLeft(card: View?) {
Log.d(TAG, "swipeCard swiped left")
if (!(deck.first?.card === card)) {
Log.e("SWIPE ERROR: ", "swipeCard on top of deck not equal to swipeCard swiped")
}
deck.removeFirst()
callback?.cardSwipedLeft(viewId)
}
override fun cardSwipedRight(card: View?) {
Log.d(TAG, "swipeCard swiped right")
if (!(deck.first?.card === card)) {
Log.e("SWIPE ERROR: ", "swipeCard on top of deck not equal to swipeCard swiped")
}
deck.removeFirst()
callback?.cardSwipedRight(viewId)
}
override // Enabled by default, drag would depend on swipeEnabled
val isDragEnabled: Boolean
get() {
return callback?.isDragEnabled(viewId) ?: true
}
override fun cardOffScreen(card: View?) {
}
override fun cardActionDown() {
}
override fun cardActionUp() {
}
}
companion object {
private val TAG = "SwipeDeck"
var ANIMATION_DURATION = 200L
}
}
| mit | 1bb16b4e96f0ac8499b37b37d48df598 | 36.50591 | 145 | 0.613615 | 4.678561 | false | false | false | false |
yamamotoj/workshop-jb | src/ii_conventions/_16_MultiAssignment.kt | 1 | 1625 | package ii_conventions
fun multiAssignPair(pair: Pair<Int, String>) {
val (first, second) = pair
}
class MyPair {
fun component1(): Int = 1
fun component2(): String = "a"
}
fun howItWorks() {
fun invocation() {
val (i, s) = MyPair()
}
//invocations of functions 'component1' and 'component2' are generated
fun generatedCode() {
val tmp = MyPair()
val i = tmp.component1()
val s = tmp.component2()
}
}
fun iterateOverCollectionWithIndex(collection: Collection<Int>) {
for ((index, element) in collection.withIndex()) {
println("$index: $element")
}
}
fun howWorksMultiAssignmentInForCycle() {
fun invocation(it: Iterator<MyPair>) {
for ((i, s) in it) {
}
}
fun generatedCode(it: Iterator<MyPair>) {
for (tmp in it) {
val i = tmp.component1()
val s = tmp.component2()
}
}
}
// with 'data' annotation 'component1', 'component2', etc. are generated automatically
// for constructor parameters
data class MyAnotherPair(val i: Int, val s: String)
//that's why we can multi-assign Date class:
fun multiAssignDate(date: MyDate) {
val (year, month, dayOfMonth) = date
}
fun todoTask16() = TODO("Again no special task. Just return 'true' if you are interested in Kotlin. =)")
data class FourBooleans(val b1: Boolean = true,
val b2: Boolean = true,
val b3: Boolean = true,
val b4: Boolean = true)
fun task16(): Boolean {
val (b1, b2, b3, b4) = FourBooleans()
return b1 && b2 && b3 && b4
} | mit | d2b2b1f735669331273a0119d8e7e525 | 24.40625 | 104 | 0.595077 | 3.611111 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/user/AbstractInfoFakeDialogFragment.kt | 1 | 6197 | package de.westnordost.streetcomplete.user
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.ViewPropertyAnimator
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
import android.view.animation.OvershootInterpolator
import androidx.fragment.app.Fragment
import de.westnordost.streetcomplete.util.Transforms
import de.westnordost.streetcomplete.util.animateFrom
import de.westnordost.streetcomplete.util.animateTo
import de.westnordost.streetcomplete.util.applyTransforms
/** It is not a real dialog because a real dialog has its own window, or in other words, has a
* different root view than the rest of the UI. However, for the calculation to animate the icon
* from another view to the position in the "dialog", there must be a common root view.*/
abstract class AbstractInfoFakeDialogFragment(layoutId: Int) : Fragment(layoutId) {
/** View from which the title image view is animated from (and back on dismissal)*/
private var sharedTitleView: View? = null
var isShowing: Boolean = false
private set
// need to keep the animators here to be able to clear them on cancel
private val currentAnimators: MutableList<ViewPropertyAnimator> = mutableListOf()
protected abstract val dialogAndBackgroundContainer: ViewGroup
protected abstract val dialogBackground: View
protected abstract val dialogContentContainer: ViewGroup
protected abstract val dialogBubbleBackground: View
protected abstract val titleView: View
/* ---------------------------------------- Lifecycle --------------------------------------- */
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
dialogAndBackgroundContainer.setOnClickListener { dismiss() }
}
override fun onDestroy() {
super.onDestroy()
sharedTitleView = null
clearAnimators()
}
/* ---------------------------------------- Interface --------------------------------------- */
open fun dismiss(): Boolean {
if (currentAnimators.isNotEmpty()) return false
isShowing = false
animateOut(sharedTitleView)
return true
}
protected fun show(sharedView: View): Boolean {
if (currentAnimators.isNotEmpty()) return false
isShowing = true
this.sharedTitleView = sharedView
animateIn(sharedView)
return true
}
/* ----------------------------------- Animating in and out --------------------------------- */
private fun animateIn(sharedView: View) {
dialogAndBackgroundContainer.visibility = View.VISIBLE
currentAnimators.addAll(
createDialogPopInAnimations() + listOf(
createTitleImageFlingInAnimation(sharedView),
createFadeInBackgroundAnimation()
)
)
currentAnimators.forEach { it.start() }
}
private fun animateOut(sharedView: View?) {
currentAnimators.addAll(createDialogPopOutAnimations())
if (sharedView != null) currentAnimators.add(createTitleImageFlingOutAnimation(sharedView))
currentAnimators.add(createFadeOutBackgroundAnimation())
currentAnimators.forEach { it.start() }
}
private fun createFadeInBackgroundAnimation(): ViewPropertyAnimator {
dialogBackground.alpha = 0f
return dialogBackground.animate()
.alpha(1f)
.setDuration(ANIMATION_TIME_IN_MS)
.setInterpolator(DecelerateInterpolator())
.withEndAction { currentAnimators.clear() }
}
private fun createFadeOutBackgroundAnimation(): ViewPropertyAnimator {
return dialogBackground.animate()
.alpha(0f)
.setDuration(ANIMATION_TIME_OUT_MS)
.setInterpolator(AccelerateInterpolator())
.withEndAction {
dialogAndBackgroundContainer.visibility = View.INVISIBLE
currentAnimators.clear()
}
}
private fun createTitleImageFlingInAnimation(sourceView: View): ViewPropertyAnimator {
sourceView.visibility = View.INVISIBLE
val root = sourceView.rootView as ViewGroup
titleView.applyTransforms(Transforms.IDENTITY)
return titleView.animateFrom(sourceView, root)
.setDuration(ANIMATION_TIME_IN_MS)
.setInterpolator(OvershootInterpolator())
}
private fun createTitleImageFlingOutAnimation(targetView: View): ViewPropertyAnimator {
val root = targetView.rootView as ViewGroup
return titleView.animateTo(targetView, root)
.setDuration(ANIMATION_TIME_OUT_MS)
.setInterpolator(AccelerateDecelerateInterpolator())
.withEndAction {
targetView.visibility = View.VISIBLE
sharedTitleView = null
}
}
private fun createDialogPopInAnimations(): List<ViewPropertyAnimator> {
return listOf(dialogContentContainer, dialogBubbleBackground).map {
it.alpha = 0f
it.scaleX = 0.5f
it.scaleY = 0.5f
it.translationY = 0f
it.animate()
.alpha(1f)
.scaleX(1f).scaleY(1f)
.setDuration(ANIMATION_TIME_IN_MS)
.setInterpolator(OvershootInterpolator())
}
}
private fun createDialogPopOutAnimations(): List<ViewPropertyAnimator> {
return listOf(dialogContentContainer, dialogBubbleBackground).map {
it.animate()
.alpha(0f)
.scaleX(0.5f).scaleY(0.5f)
.translationYBy(it.height * 0.2f)
.setDuration(ANIMATION_TIME_OUT_MS)
.setInterpolator(AccelerateInterpolator())
}
}
private fun clearAnimators() {
for (anim in currentAnimators) {
anim.cancel()
}
currentAnimators.clear()
}
companion object {
const val ANIMATION_TIME_IN_MS = 600L
const val ANIMATION_TIME_OUT_MS = 300L
}
}
| gpl-3.0 | 15efb439a79c29861ed0da5c47af8eb4 | 36.786585 | 100 | 0.650315 | 5.638763 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/manager/RecipientManager.kt | 1 | 7289 | package com.toshi.manager
import com.toshi.extensions.getQueryMap
import com.toshi.extensions.isGroupId
import com.toshi.manager.network.IdService
import com.toshi.manager.store.BlockedUserStore
import com.toshi.manager.store.GroupStore
import com.toshi.manager.store.UserStore
import com.toshi.model.local.BlockedUser
import com.toshi.model.local.Group
import com.toshi.model.local.Recipient
import com.toshi.model.local.Report
import com.toshi.model.local.User
import com.toshi.model.network.SearchResult
import com.toshi.model.network.ServerTime
import com.toshi.model.network.UserSection
import com.toshi.model.network.user.UserType
import com.toshi.util.logging.LogUtil
import com.toshi.view.BaseApplication
import rx.Completable
import rx.Observable
import rx.Scheduler
import rx.Single
import rx.schedulers.Schedulers
import java.io.IOException
class RecipientManager(
private val idService: IdService = IdService.get(),
private val groupStore: GroupStore = GroupStore(),
private val userStore: UserStore = UserStore(),
private val blockedUserStore: BlockedUserStore = BlockedUserStore(),
private val baseApplication: BaseApplication = BaseApplication.get(),
private val scheduler: Scheduler = Schedulers.io()
) {
fun getFromId(recipientId: String): Single<Recipient> {
return if (recipientId.isGroupId()) getGroupFromId(recipientId).map { Recipient(it) }
else getUserFromToshiId(recipientId).map { Recipient(it) }
}
fun getGroupFromId(id: String): Single<Group> {
return groupStore.loadForId(id)
.subscribeOn(scheduler)
.doOnError { LogUtil.exception("getGroupFromId", it) }
}
fun getUserFromUsername(username: String): Single<User> {
return Single
.concat(
userStore.loadForUsername(username),
fetchAndCacheFromNetworkByUsername(username))
.subscribeOn(scheduler)
.first { isUserFresh(it) }
.doOnError { LogUtil.exception("getUserFromUsername", it) }
.toSingle()
}
fun getUserFromToshiId(toshiId: String): Single<User> {
return Single
.concat(
userStore.loadForToshiId(toshiId),
fetchAndCacheFromNetworkByToshiId(toshiId))
.subscribeOn(scheduler)
.first { isUserFresh(it) }
.doOnError { LogUtil.exception("getUserFromToshiId", it) }
.toSingle()
}
private fun isUserFresh(user: User?): Boolean {
return when {
user == null -> false
baseApplication.isConnected -> true
else -> !user.needsRefresh()
}
}
fun getUserFromPaymentAddress(paymentAddress: String): Single<User> {
return Single
.concat(
userStore.loadForPaymentAddress(paymentAddress),
fetchAndCacheFromNetworkByPaymentAddress(paymentAddress).toSingle()
)
.subscribeOn(scheduler)
.first { isUserFresh(it) }
.doOnError { LogUtil.exception("getUserFromPaymentAddress", it) }
.toSingle()
}
private fun fetchAndCacheFromNetworkByUsername(username: String): Single<User> {
// It's the same endpoint
return fetchAndCacheFromNetworkByToshiId(username)
}
private fun fetchAndCacheFromNetworkByToshiId(userAddress: String): Single<User> {
return idService
.api
.getUser(userAddress)
.subscribeOn(scheduler)
.doOnSuccess { cacheUser(it) }
}
fun fetchUsersFromToshiIds(userIds: List<String>): Single<List<User>> {
return idService
.api
.getUsers(userIds)
.map { it.results }
.subscribeOn(scheduler)
}
private fun fetchAndCacheFromNetworkByPaymentAddress(paymentAddress: String): Observable<User> {
return idService
.api
.searchByPaymentAddress(paymentAddress)
.toObservable()
.filter { it.results.size > 0 }
.map { it.results[0] }
.subscribeOn(scheduler)
.doOnNext { cacheUser(it) }
.doOnError { LogUtil.exception("fetchAndCacheFromNetworkByPaymentAddress", it) }
}
fun cacheUser(user: User) {
userStore.save(user)
.subscribe(
{ },
{ LogUtil.exception("Error while saving user to db", it) }
)
}
fun searchOnlineUsers(query: String): Single<List<User>> {
return idService
.api
.searchBy(UserType.USER.name.toLowerCase(), query)
.subscribeOn(scheduler)
.map { it.results }
}
fun isUserBlocked(ownerAddress: String): Single<Boolean> {
return blockedUserStore
.isBlocked(ownerAddress)
.subscribeOn(scheduler)
}
fun blockUser(ownerAddress: String): Completable {
val blockedUser = BlockedUser()
.setOwnerAddress(ownerAddress)
return Completable
.fromAction { blockedUserStore.save(blockedUser) }
.subscribeOn(scheduler)
}
fun unblockUser(ownerAddress: String): Completable {
return Completable
.fromAction { blockedUserStore.delete(ownerAddress) }
.subscribeOn(scheduler)
}
fun reportUser(report: Report): Completable {
return getTimestamp()
.flatMapCompletable { idService.api.reportUser(report, it.get()) }
.subscribeOn(scheduler)
}
fun searchForUsersWithType(type: String, query: String? = null): Single<SearchResult<User>> {
return idService
.api
.search(type, query)
.doOnSuccess { cacheUsers(it.results) }
.subscribeOn(scheduler)
}
fun searchForUsersWithQuery(query: String): Single<SearchResult<User>> {
val queryMap = query.getQueryMap()
return idService
.api
.search(queryMap)
.doOnSuccess { cacheUsers(it.results) }
.subscribeOn(scheduler)
}
fun getPopularSearches(): Single<List<UserSection>> {
return idService
.api
.getPopularSearches()
.map { it.sections }
.doOnSuccess { it.forEach { cacheUsers(it.results) } }
.subscribeOn(scheduler)
}
private fun cacheUsers(users: List<User>) {
userStore.saveUsers(users)
.subscribe(
{ },
{ LogUtil.exception("Error while saving users to db", it) }
)
}
fun getTimestamp(): Single<ServerTime> = idService.api.timestamp
fun clear() = clearCache()
private fun clearCache() {
try {
idService.clearCache()
} catch (e: IOException) {
LogUtil.exception("Error while clearing network cache", e)
}
}
} | gpl-3.0 | 2f9dddfa8e5719e0ac7ec54dea2aa7fc | 33.880383 | 100 | 0.596378 | 4.823958 | false | false | false | false |
devulex/eventorage | frontend/src/com/devulex/eventorage/react/dom/ReactDOMBuilder.kt | 1 | 3330 | package com.devulex.eventorage.react.dom
import com.devulex.eventorage.react.RProps
import com.devulex.eventorage.react.ReactBuilder
import com.devulex.eventorage.react.ReactElement
import kotlinx.html.*
import org.w3c.dom.events.*
class InnerHTML (
val __html: String
)
class DOMProps: RProps() {
var dangerouslySetInnerHTML: InnerHTML? = null
}
class ReactDOMBuilder : ReactBuilder(), TagConsumer<ReactElement?> {
/*
inline operator fun <reified T: ReactComponent<P, S>, reified P : RProps, S: RState> ReactComponentSpec<T, P, S>.invoke(
noinline handler: P.() -> Unit = {}
) : ReactElement {
val props = instantiateProps<P>()
return node(props) { props.handler() }
}
inline operator fun <reified P : RProps> ReactExternalComponentSpec<P>.invoke(
noinline handler: P.() -> Unit = {}
) : ReactElement {
val props = instantiateProps<P>()
return node(props) { props.handler() }
}
*/
override fun <P: RProps> createReactNode(type: Any, props: P) = Node(type, props)
class DOMNode(val tagName: String) : Node<DOMProps>(tagName, DOMProps())
private fun currentDOMNode() = currentNodeOfType<DOMNode>()
var HTMLTag.key: String
get() {
return currentDOMNode().props.key ?: ""
}
set(value) {
currentDOMNode().props.key = value
}
var HTMLTag.ref: String
get() {
return currentDOMNode().props.ref ?: ""
}
set(value) {
currentDOMNode().props.ref = value
}
fun setProp(attribute: String, value: dynamic) {
val node = currentNode()
val key = fixAttributeName(attribute)
if (value == null) {
js("delete node.props[key]")
} else {
node.props.asDynamic()[key] = value
}
}
override fun onTagAttributeChange(tag: Tag, attribute: String, value: String?) {
setProp(attribute, value)
}
operator fun String.unaryPlus() {
onTagContent(this)
}
override fun onTagContent(content: CharSequence): Unit {
children.add(content)
}
override fun onTagContentEntity(entity: Entities): Unit {
children.add(entity.text)
}
override fun onTagContentUnsafe(block: Unsafe.() -> Unit) {
val sb = StringBuilder()
object : Unsafe {
override fun String.unaryPlus() {
sb.append(this)
}
}.block()
val node = currentDOMNode()
node.props.dangerouslySetInnerHTML = InnerHTML(sb.toString())
}
override fun onTagStart(tag: Tag) {
enterNode(DOMNode(tag.tagName))
tag.attributesEntries.forEach { setProp(it.key, it.value) }
}
override fun onTagEnd(tag: Tag) {
if (path.isEmpty() || currentDOMNode().tagName.toLowerCase() != tag.tagName.toLowerCase())
throw IllegalStateException("We haven't entered tag ${tag.tagName} but trying to leave")
exitCurrentNode()
}
override fun onTagEvent(tag: Tag, event: String, value: (Event) -> Unit) {
setProp(event, value)
}
override fun finalize(): ReactElement? {
return result()
}
}
fun buildElement(handler: ReactDOMBuilder.() -> Unit) = with(ReactDOMBuilder()) {
handler()
finalize()
}
| mit | e172c9b3516485c9b0a02a42899e02bc | 27.706897 | 124 | 0.614114 | 4.08589 | false | false | false | false |
scorsero/scorsero-client-android | app/src/main/java/io/github/dmi3coder/scorsero/score/ScoreCreationController.kt | 1 | 2133 | package io.github.dmi3coder.scorsero.score
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bluelinelabs.conductor.Controller
import io.github.dmi3coder.scorsero.MainApplication
import io.github.dmi3coder.scorsero.R
import io.github.dmi3coder.scorsero.data.Score
import io.github.dmi3coder.scorsero.score.ScoreCreationContract.Presenter
import io.github.dmi3coder.scorsero.score.ScoreCreationContract.ViewState.OPEN
import kotlinx.android.synthetic.main.controller_score_creation.view.creation_fab
import kotlinx.android.synthetic.main.controller_score_creation.view.field_list
/**
* Created by dim3coder on 10:28 PM 7/18/17.
*/
class ScoreCreationController(
var operationScore: Score = Score()) : Controller(), ScoreCreationContract.View {
internal lateinit var presenter: ScoreCreationContract.Presenter
internal lateinit var view: View
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View {
view = inflater.inflate(R.layout.controller_score_creation, container, false)
var scoreCreationPresenter = ScoreCreationPresenter(this)
MainApplication.mainComponent.inject(scoreCreationPresenter)
scoreCreationPresenter.start(operationScore)
return view
}
override fun setPresenter(presenter: Presenter) {
this.presenter = presenter
}
override fun setVisibility(visible: Boolean) {
TODO("Unsupported")
}
override fun setScore(scoreData: Score?) {
activity?.runOnUiThread {
if (scoreData?.id != null) {
view.creation_fab.setImageResource(R.drawable.ic_check)
activity?.title = "Edit Score"
} else {
activity?.title = "New Score"
}
operationScore = scoreData ?: Score()
view.field_list.layoutManager = LinearLayoutManager(activity)
view.field_list.adapter = ScoreFieldAdapter(operationScore)
view.creation_fab.setOnClickListener {
presenter.processScore(operationScore, OPEN)
router.handleBack()
}
}
}
override fun clear() {
setScore(null)
}
} | gpl-3.0 | 45027e6e768e9f303f0eabd22d0ab7ed | 33.983607 | 85 | 0.759025 | 4.223762 | false | false | false | false |
kaushikgopal/Android-RxJava | app/src/main/kotlin/com/morihacky/android/rxjava/fragments/UsingFragment.kt | 3 | 3126 | package com.morihacky.android.rxjava.fragments
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView
import com.morihacky.android.rxjava.R
import io.reactivex.Flowable
import io.reactivex.functions.Consumer
import io.reactivex.functions.Function
import org.reactivestreams.Publisher
import java.util.*
import java.util.concurrent.Callable
class UsingFragment : BaseFragment() {
private lateinit var _logs: MutableList<String>
private lateinit var _logsList: ListView
private lateinit var _adapter: UsingFragment.LogAdapter
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater?.inflate(R.layout.fragment_buffer, container, false)
_logsList = view?.findViewById(R.id.list_threading_log) as ListView
(view.findViewById(R.id.text_description) as TextView).setText(R.string.msg_demo_using)
_setupLogger()
view.findViewById(R.id.btn_start_operation).setOnClickListener { executeUsingOperation() }
return view
}
private fun executeUsingOperation() {
val resourceSupplier = Callable<Realm> { Realm() }
val sourceSupplier = Function<Realm, Publisher<Int>> { realm ->
Flowable.just(true)
.map {
realm.doSomething()
// i would use the copyFromRealm and change it to a POJO
Random().nextInt(50)
}
}
val disposer = Consumer<Realm> { realm ->
realm.clear()
}
Flowable.using(resourceSupplier, sourceSupplier, disposer)
.subscribe({ i ->
_log("got a value $i - (look at the logs)")
})
}
inner class Realm {
init {
_log("initializing Realm instance")
}
fun doSomething() {
_log("do something with Realm instance")
}
fun clear() {
// notice how this is called even before you manually "dispose"
_log("cleaning up the resources (happens before a manual 'dispose'")
}
}
// -----------------------------------------------------------------------------------
// Method that help wiring up the example (irrelevant to RxJava)
private fun _log(logMsg: String) {
_logs.add(0, logMsg)
// You can only do below stuff on main thread.
Handler(Looper.getMainLooper()).post {
_adapter.clear()
_adapter.addAll(_logs)
}
}
private fun _setupLogger() {
_logs = ArrayList<String>()
_adapter = LogAdapter(activity, ArrayList<String>())
_logsList.adapter = _adapter
}
private class LogAdapter(context: Context, logs: List<String>) : ArrayAdapter<String>(context, R.layout.item_log, R.id.item_log, logs)
} | apache-2.0 | c6d129577635748c4b67f4a459ad5d8f | 32.623656 | 138 | 0.620282 | 4.583578 | false | false | false | false |
RoverPlatform/rover-android | location/src/main/kotlin/io/rover/sdk/location/sync/BeaconsSyncParticipant.kt | 1 | 9770 | package io.rover.sdk.location.sync
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteException
import io.rover.sdk.core.data.domain.ID
import io.rover.sdk.core.data.graphql.getObjectIterable
import io.rover.sdk.core.data.graphql.getStringIterable
import io.rover.sdk.core.data.graphql.safeGetString
import io.rover.sdk.core.data.sync.GraphQLResponse
import io.rover.sdk.core.data.sync.PageInfo
import io.rover.sdk.core.data.sync.SqlSyncStorageInterface
import io.rover.sdk.core.data.sync.SyncCoordinatorInterface
import io.rover.sdk.core.data.sync.SyncDecoder
import io.rover.sdk.core.data.sync.SyncQuery
import io.rover.sdk.core.data.sync.SyncRequest
import io.rover.sdk.core.data.sync.SyncResource
import io.rover.sdk.core.data.sync.after
import io.rover.sdk.core.data.sync.decodeJson
import io.rover.sdk.core.data.sync.first
import io.rover.sdk.core.logging.log
import io.rover.sdk.core.streams.Publishers
import io.rover.sdk.core.streams.Scheduler
import io.rover.sdk.core.streams.map
import io.rover.sdk.core.streams.observeOn
import io.rover.sdk.core.streams.subscribeOn
import io.rover.sdk.location.domain.Beacon
import org.json.JSONArray
import org.json.JSONObject
import org.reactivestreams.Publisher
import java.util.HashMap
import java.util.UUID
class BeaconsRepository(
private val syncCoordinator: SyncCoordinatorInterface,
private val beaconsSqlStorage: BeaconsSqlStorage,
private val ioScheduler: Scheduler
) {
fun allBeacons(): Publisher<ClosableSequence<Beacon>> = syncCoordinator
.updates
.observeOn(ioScheduler)
.map {
beaconsSqlStorage.queryAllBeacons()
}
/**
* Look up a [Beacon] by its iBeacon UUID, major, and minor. Yields it if it exists.
*/
fun beaconByUuidMajorAndMinor(uuid: UUID, major: Short, minor: Short): Publisher<Beacon?> {
return Publishers.defer {
Publishers.just(beaconsSqlStorage.queryBeaconByUuidMajorAndMinor(uuid, major, minor))
}.subscribeOn(ioScheduler)
}
}
class BeaconsSqlStorage(
private val sqLiteDatabase: SQLiteDatabase
) : SqlSyncStorageInterface<Beacon> {
fun queryBeaconByUuidMajorAndMinor(uuid: UUID, major: Short, minor: Short): Beacon? {
val columnNames = Columns.values().sortedBy { it.ordinal }.map { it.columnName }
val cursor = sqLiteDatabase.query(
TABLE_NAME,
columnNames.toTypedArray(),
"uuid = ? AND major = ? AND minor = ?",
arrayOf(uuid.toString(), major.toString(), minor.toString()),
null,
null,
null
)
return try {
if (cursor.moveToFirst()) {
return Beacon.fromSqliteCursor(cursor)
} else {
null
}
} catch (e: SQLiteException) {
log.w("Unable to query DB for beacon: $e")
null
} finally {
cursor.close()
}
}
fun queryAllBeacons(): ClosableSequence<Beacon> {
val columnNames = Columns.values().sortedBy { it.ordinal }.map { it.columnName }
return object : ClosableSequence<Beacon> {
// Responsibility for Recycling is delegated to the caller through the
// [ClosableSequence].
override fun iterator(): CloseableIterator<Beacon> {
val cursor = sqLiteDatabase.query(
TABLE_NAME,
columnNames.toTypedArray(),
null,
null,
null,
null,
null
)
return object : AbstractIterator<Beacon>(), CloseableIterator<Beacon> {
override fun computeNext() {
if (!cursor.moveToNext()) {
done()
} else {
setNext(
Beacon.fromSqliteCursor(cursor)
)
}
}
override fun close() {
cursor.close()
}
}
}
}
}
// TODO: indicate failure. right now cursor will still be moved forward.
override fun upsertObjects(items: List<Beacon>) {
sqLiteDatabase.beginTransaction()
try {
items.forEach { item ->
val initialValues = ContentValues().apply {
put(Columns.Id.columnName, item.id.rawValue)
put(Columns.Name.columnName, item.name)
put(Columns.Uuid.columnName, item.uuid.toString())
put(Columns.Major.columnName, item.major)
put(Columns.Minor.columnName, item.minor)
put(Columns.Tags.columnName, JSONArray(item.tags).toString())
}
sqLiteDatabase.insertWithOnConflict(
TABLE_NAME,
null,
initialValues,
SQLiteDatabase.CONFLICT_REPLACE
)
}
sqLiteDatabase.setTransactionSuccessful()
} catch (e: SQLiteException) {
log.w("Problem upserting beacon into sync database: %s")
} finally {
sqLiteDatabase.endTransaction()
}
}
companion object {
private const val TABLE_NAME = "beacons"
fun initSchema(sqLiteDatabase: SQLiteDatabase) {
sqLiteDatabase.execSQL("""
CREATE TABLE $TABLE_NAME (
id TEXT PRIMARY KEY,
name TEXT,
uuid TEXT,
major INTEGER,
minor INTEGER,
tags TEXT
)
""".trimIndent())
}
fun dropSchema(sqLiteDatabase: SQLiteDatabase) {
try {
sqLiteDatabase.execSQL("""
DROP TABLE $TABLE_NAME
""".trimIndent())
} catch (e: SQLiteException) {
log.w("Unable to drop existing table, assuming it does not exist: $e")
}
}
}
enum class Columns(
val columnName: String
) {
Id("id"),
Name("name"),
Uuid("uuid"),
Major("major"),
Minor("minor"),
Tags("tags")
}
}
fun Beacon.Companion.fromSqliteCursor(cursor: Cursor): Beacon {
return Beacon(
id = ID(cursor.getString(BeaconsSqlStorage.Columns.Id.ordinal)),
name = cursor.getString(BeaconsSqlStorage.Columns.Name.ordinal),
uuid = UUID.fromString(cursor.getString(BeaconsSqlStorage.Columns.Uuid.ordinal)),
major = cursor.getInt(BeaconsSqlStorage.Columns.Major.ordinal),
minor = cursor.getInt(BeaconsSqlStorage.Columns.Minor.ordinal),
tags = JSONArray(cursor.getString(BeaconsSqlStorage.Columns.Tags.ordinal)).getStringIterable().toList()
)
}
class BeaconsSyncResource(
private val sqliteStorageInterface: SqlSyncStorageInterface<Beacon>
) : SyncResource<Beacon> {
override fun upsertObjects(nodes: List<Beacon>) {
sqliteStorageInterface.upsertObjects(nodes)
}
override fun nextRequest(cursor: String?): SyncRequest {
log.v("Being asked for next sync request for cursor: $cursor")
val values: HashMap<String, Any> = hashMapOf(
Pair(SyncQuery.Argument.first.name, 500),
Pair(SyncQuery.Argument.orderBy.name, hashMapOf(
Pair("field", "UPDATED_AT"),
Pair("direction", "ASC")
))
)
if (cursor != null) {
values[SyncQuery.Argument.after.name] = cursor
}
return SyncRequest(
SyncQuery.beacons,
values
)
}
}
class BeaconSyncDecoder : SyncDecoder<Beacon> {
override fun decode(json: JSONObject): GraphQLResponse<Beacon> {
return BeaconSyncResponseData.decodeJson(json.getJSONObject("data")).beacons
}
}
data class BeaconSyncResponseData(
val beacons: GraphQLResponse<Beacon>
) {
companion object
}
fun BeaconSyncResponseData.Companion.decodeJson(json: JSONObject): BeaconSyncResponseData {
return BeaconSyncResponseData(
beacons = GraphQLResponse.decodeBeaconPageJson(
json.getJSONObject("beacons")
)
)
}
fun GraphQLResponse.Companion.decodeBeaconPageJson(json: JSONObject): GraphQLResponse<Beacon> {
return GraphQLResponse(
nodes = json.getJSONArray("nodes").getObjectIterable().map { nodeJson ->
Beacon.decodeJson(nodeJson)
},
pageInfo = PageInfo.decodeJson(
json.getJSONObject("pageInfo")
)
)
}
fun Beacon.Companion.decodeJson(json: JSONObject): Beacon {
return Beacon(
ID(json.safeGetString("id")),
json.safeGetString("name"),
UUID.fromString(json.safeGetString("uuid")),
json.getInt("major"),
json.getInt("minor"),
json.getJSONArray("tags").getStringIterable().toList()
)
}
val SyncQuery.Companion.beacons: SyncQuery
get() = SyncQuery(
"beacons",
"""
nodes {
...beaconFields
}
pageInfo {
endCursor
hasNextPage
}
""".trimIndent(),
arguments = listOf(
SyncQuery.Argument.first, SyncQuery.Argument.after, SyncQuery.Argument.orderBy
),
fragments = listOf("beaconFields")
)
private val SyncQuery.Argument.Companion.orderBy
get() = SyncQuery.Argument("orderBy", "BeaconOrder") | apache-2.0 | 9858f9591b8cbb179be8b75d0d5f05a9 | 32.234694 | 111 | 0.595394 | 4.724371 | false | false | false | false |
RoverPlatform/rover-android | core/src/main/kotlin/io/rover/sdk/core/platform/MapExtensions.kt | 1 | 784 | package io.rover.sdk.core.platform
/**
* Merge two hashes together. In the event of the same key existing, [transform] is invoked to
* merge the two values.
*/
fun <TKey, TValue> Map<TKey, TValue>.merge(other: Map<TKey, TValue>, transform: (TValue, TValue) -> TValue): Map<TKey, TValue> {
val keysSet = this.keys + other.keys
return keysSet.map { key ->
val left = this[key]
val right = other[key]
val value = when {
left != null && right != null -> transform(left, right)
left != null -> left
right != null -> right
else -> throw RuntimeException("Value for $key unexpectedly disappeared from both hashes being merged by Map.merge().")
}
Pair(key, value)
}.associate { it }
}
| apache-2.0 | 379703193f0385d5be2bb4a5335659c7 | 33.086957 | 131 | 0.603316 | 3.900498 | false | false | false | false |
MaKToff/Codename_Ghost | core/src/com/cypress/GameObjects/Block.kt | 1 | 954 | package com.cypress.GameObjects
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.math.Vector2
/** Contains definition of block. */
public class Block(private val position : Vector2, private val width : Float, private val height : Float,
private val texture : TextureRegion ){
private val bounds = Rectangle(position.x, position.y, width, height)
/** Draws block. */
public fun draw(batcher : SpriteBatch){
batcher.begin()
batcher.draw(texture, position.x, position.y, width, height)
batcher.end()
}
/** Returns width. */
public fun getWidth() = width
/** Returns height. */
public fun getHeight() = height
/** Returns bounds of block. */
public fun getBounds() = bounds
/** Returns position of block. */
public fun getPosition() = position
} | apache-2.0 | 2963ddd91a2c53cbc022f8d97522f756 | 28.84375 | 105 | 0.675052 | 4.24 | false | false | false | false |
zhufucdev/PCtoPE | app/src/main/java/com/zhufucdev/pctope/utils/myContextWrapper.kt | 1 | 1365 | package com.zhufucdev.pctope.utils
import android.content.Context
import android.content.ContextWrapper
import android.os.Build
import android.preference.PreferenceManager
import java.util.*
/**
* Created by zhufu on 17-9-17.
*/
class myContextWrapper(base: Context?) : ContextWrapper(base) {
val base = base@this
var language : String? = null
init {
language = PreferenceManager.getDefaultSharedPreferences(base).getString("pref_language", "auto")
}
fun wrap() : ContextWrapper {
val resources = base.resources
val configuration = resources.configuration
val metrics = resources.displayMetrics
when (language) {
"en" -> configuration.setLocale(Locale.ENGLISH)
"ch" -> configuration.setLocale(Locale.SIMPLIFIED_CHINESE)
else -> configuration.setLocale(SystemLanguage())
}
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.N) {
return ContextWrapper(base.createConfigurationContext(configuration))
}
else
resources.updateConfiguration(configuration, metrics)
return base
}
private fun SystemLanguage(): Locale {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
resources.configuration.locales.get(0)
else
resources.configuration.locale
}
} | gpl-3.0 | 15a6cb9524f42e5a33e480f4ce0d08bf | 30.767442 | 105 | 0.668132 | 4.739583 | false | true | false | false |
PaulWoitaschek/Voice | app/src/main/kotlin/voice/app/features/bookmarks/list/BookmarkDiffUtilCallback.kt | 1 | 705 | package voice.app.features.bookmarks.list
import androidx.recyclerview.widget.DiffUtil
import voice.data.Bookmark
/**
* Calculates the diff between two bookmark lists.
*/
class BookmarkDiffUtilCallback(
private val oldItems: List<Bookmark>,
private val newItems: List<Bookmark>,
) : DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldItems[oldItemPosition] == newItems[newItemPosition]
}
override fun getOldListSize() = oldItems.size
override fun getNewListSize() = newItems.size
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
areItemsTheSame(oldItemPosition, newItemPosition)
}
| gpl-3.0 | e4e0f8027ec1aa3e8e85cc18498cc298 | 28.375 | 85 | 0.778723 | 4.93007 | false | false | false | false |
jamieadkins95/Roach | app/src/main/java/com/jamieadkins/gwent/deck/builder/DeckDetailsActivity.kt | 1 | 1488 | package com.jamieadkins.gwent.deck.builder
import android.os.Bundle
import com.jamieadkins.gwent.base.GwentApplication.Companion.coreComponent
import com.jamieadkins.gwent.deck.builder.di.DaggerDeckBuilderComponent
import com.jamieadkins.gwent.base.DaggerAndroidActivity
import com.jamieadkins.gwent.R
class DeckDetailsActivity : DaggerAndroidActivity() {
override fun onInject() {
DaggerDeckBuilderComponent.builder()
.core(coreComponent)
.build()
.inject(this)
}
lateinit var deckId: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_deck_detail)
deckId = savedInstanceState?.getString(DeckDetailsFragment.KEY_ID)
?: intent?.data?.getQueryParameter("deckId")
?: throw Exception("Deck ID not found")
if (savedInstanceState == null) {
val fragment = DeckDetailsFragment()
val bundle = Bundle()
bundle.putString(DeckDetailsFragment.KEY_ID, deckId)
fragment.arguments = bundle
supportFragmentManager
.beginTransaction()
.replace(R.id.contentContainer, fragment)
.commit()
}
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putString(DeckDetailsFragment.KEY_ID, deckId)
super.onSaveInstanceState(outState)
}
} | apache-2.0 | e29a1c5579ecc55b9c7f8fdaae300756 | 32.088889 | 74 | 0.662634 | 5.09589 | false | false | false | false |
hartwigmedical/hmftools | cider/src/main/java/com/hartwig/hmftools/cider/CiderParams.kt | 1 | 2758 | package com.hartwig.hmftools.cider
import com.beust.jcommander.Parameter
import com.hartwig.hmftools.common.ensemblcache.EnsemblDataCache
import com.hartwig.hmftools.common.genome.refgenome.RefGenomeSource
import com.hartwig.hmftools.common.genome.refgenome.RefGenomeVersion
import com.hartwig.hmftools.common.utils.config.RefGenomeVersionConverter
import htsjdk.samtools.ValidationStringency
class CiderParams
{
@Parameter(names = ["-sample"], description = "Name of sample")
lateinit var sampleId: String
@Parameter(names = ["-bam"], description = "Path to indexed bam/cram file")
lateinit var bamPath: String
@Parameter(
names = ["-" + RefGenomeSource.REF_GENOME],
description = "Path to the reference genome fasta file. Required only when using CRAM files."
)
var refGenomePath: String? = null
@Parameter(
names = ["-output_dir"],
required = true,
description = "Path to the output directory. "
+ "This directory will be created if it does not already exist."
)
lateinit var outputDir: String
@Parameter(names = ["-validation_stringency"], description = "SAM validation strategy")
var stringency = ValidationStringency.DEFAULT_STRINGENCY
@Parameter(names = ["-threads"], description = "Number of threads")
var threadCount = DEFAULT_THREADS
@Parameter(names = ["-max_fragment_length"], description = "Approximate maximum fragment length")
var approxMaxFragmentLength = DEFAULT_MAX_FRAGMENT_LENGTH
@Parameter(
names = ["-" + RefGenomeVersion.REF_GENOME_VERSION],
required = true,
description = RefGenomeVersion.REF_GENOME_VERSION_CFG_DESC,
converter = RefGenomeVersionConverter::class
)
lateinit var refGenomeVersion: RefGenomeVersion
@Parameter(names = ["-" + EnsemblDataCache.ENSEMBL_DATA_DIR],
required = true,
description = EnsemblDataCache.ENSEMBL_DATA_DIR_CFG)
lateinit var ensemblDataDir: String
@Parameter(names = ["-min_base_quality"], description = "Minimum quality for a base to be considered")
var minBaseQuality = 25
@Parameter(names = ["-write_filtered_bam"], description = "Write a output BAM file containing all CDR3 reads")
var writeFilteredBam = false
@Parameter(names = ["-report_partial_seq"], description = "Report partially rearranged sequences (V only or J only)")
var reportPartialSeq = false
@Parameter(names = ["-num_trim_bases"], description = "Number of bases to trim on each side of reads")
var numBasesToTrim = 0
val isValid: Boolean get() = true
companion object
{
const val DEFAULT_THREADS = 1
const val DEFAULT_MAX_FRAGMENT_LENGTH = 1000
}
} | gpl-3.0 | 80fa3db3c18cbd4231805c76c1d26634 | 36.794521 | 121 | 0.698695 | 4.217125 | false | false | false | false |
googlecodelabs/androidthings-surveybox | step3-firebase/android/app/src/main/java/com/example/surveybox/ButtonPress.kt | 3 | 1087 | /*
* Copyright 2018, 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.surveybox
import com.google.firebase.database.IgnoreExtraProperties
import com.google.firebase.database.ServerValue
import java.util.Date
/**
* Represents a button press event
*/
@IgnoreExtraProperties
data class ButtonPress(var deviceId: String = "", var roomId: String = "", var value: Int? = null,
var localtime: Long = Date().time,
var servertime: Map<String, String>? = ServerValue.TIMESTAMP)
| apache-2.0 | 22bf4eb1a2c910c44b1d30da65c0420d | 35.233333 | 98 | 0.718491 | 4.279528 | false | false | false | false |
andrei-heidelbacher/metanalysis | chronolens-core/src/test/kotlin/org/chronolens/core/versioning/VcsProxyFactoryMock.kt | 1 | 1448 | /*
* Copyright 2017-2021 Andrei Heidelbacher <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chronolens.core.versioning
import java.io.File
class VcsProxyFactoryMock : VcsProxyFactory() {
companion object {
private var isInitialized = false
private var revisions = emptyList<RevisionMock>()
fun resetRepository() {
isInitialized = false
revisions = emptyList()
}
fun setRepository(revisions: List<RevisionMock>) {
isInitialized = true
this.revisions = revisions
}
inline fun setRepository(init: HistoryBuilder.() -> Unit) {
setRepository(HistoryBuilder().apply(init).build())
}
}
override fun isSupported(): Boolean = true
override fun createProxy(directory: File): VcsProxy? =
if (isInitialized) VcsProxyMock(revisions) else null
}
| apache-2.0 | 6fe749a567a27bd939ea2701fcf57add | 31.177778 | 75 | 0.68232 | 4.611465 | false | false | false | false |
natanieljr/droidmate | project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/modelFeatures/misc/ClickFrequencyTable.kt | 1 | 2875 | // DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// 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/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.exploration.modelFeatures.misc
import com.google.common.collect.Table
import kotlinx.coroutines.runBlocking
import org.droidmate.exploration.ExplorationContext
import java.util.*
//TODO check if this is even still used
class ClickFrequencyTable private constructor(val table: Table<Int, String, Int>) : Table<Int, String, Int> by table {
constructor(data: ExplorationContext<*,*,*>) : this(build(data))
companion object {
const val headerNoOfClicks = "No_of_clicks"
const val headerViewsCount = "Views_count"
fun build(data: ExplorationContext<*,*,*>): Table<Int, String, Int> {
val countOfViewsHavingNoOfClicks: Map<Int, Int> = data.countOfViewsHavingNoOfClicks
return buildTable(
headers = listOf(headerNoOfClicks, headerViewsCount),
rowCount = countOfViewsHavingNoOfClicks.keys.size,
computeRow = { rowIndex ->
check(countOfViewsHavingNoOfClicks.containsKey(rowIndex))
val noOfClicks = rowIndex
listOf(
noOfClicks,
countOfViewsHavingNoOfClicks[noOfClicks]!!
)
}
)
}
/** computing how many new widgets become visible after each action (#actions -> #newWidgets) **/
private val ExplorationContext<*,*,*>.countOfViewsHavingNoOfClicks: Map<Int, Int>
get() = mutableMapOf<Int, Int>().also { res ->
with(mutableSetOf<UUID>()) {
// temporary set of widgets seen over the action trace
explorationTrace.getActions().forEachIndexed { idx, action ->
size.let { nSeenBefore -> runBlocking {
// the size of the set of widgets seen until step idx
getState(action.resState)?.widgets?.map { it.uid }?.let { addAll(it) } // update the unique ids of widgets seen in the new state
res.put(idx, size - nSeenBefore) // this is the number of newly explored widgets
} }
}
}
}
}
} | gpl-3.0 | 92a5af6e82b0b12dce5e4161d8ee4b7b | 37.346667 | 136 | 0.718261 | 3.90095 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/mixin/handlers/injectionPoint/NewInsnInjectionPoint.kt | 1 | 8372 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.handlers.injectionPoint
import com.demonwav.mcdev.platform.mixin.reference.MixinSelector
import com.demonwav.mcdev.platform.mixin.reference.MixinSelectorParser
import com.demonwav.mcdev.platform.mixin.reference.toMixinString
import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.AT
import com.demonwav.mcdev.platform.mixin.util.fakeResolve
import com.demonwav.mcdev.platform.mixin.util.findOrConstructSourceMethod
import com.demonwav.mcdev.platform.mixin.util.shortName
import com.demonwav.mcdev.util.MemberReference
import com.demonwav.mcdev.util.constantStringValue
import com.demonwav.mcdev.util.descriptor
import com.demonwav.mcdev.util.fullQualifiedName
import com.demonwav.mcdev.util.getQualifiedMemberReference
import com.demonwav.mcdev.util.internalName
import com.demonwav.mcdev.util.mapToArray
import com.demonwav.mcdev.util.shortName
import com.intellij.codeInsight.completion.JavaLookupElementBuilder
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiNewExpression
import com.intellij.psi.PsiSubstitutor
import com.intellij.psi.util.parentOfType
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type
import org.objectweb.asm.tree.AbstractInsnNode
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.MethodInsnNode
import org.objectweb.asm.tree.MethodNode
import org.objectweb.asm.tree.TypeInsnNode
class NewInsnInjectionPoint : InjectionPoint<PsiMember>() {
private fun getTarget(at: PsiAnnotation, target: MixinSelector?): MixinSelector? {
if (target != null) {
return target
}
val clazz = AtResolver.getArgs(at)["class"] ?: return null
return classToMemberReference(clazz)
}
override fun createNavigationVisitor(
at: PsiAnnotation,
target: MixinSelector?,
targetClass: PsiClass
): NavigationVisitor? {
return getTarget(at, target)?.let { MyNavigationVisitor(it) }
}
override fun doCreateCollectVisitor(
at: PsiAnnotation,
target: MixinSelector?,
targetClass: ClassNode,
mode: CollectVisitor.Mode
): CollectVisitor<PsiMember>? {
if (mode == CollectVisitor.Mode.COMPLETION) {
return MyCollectVisitor(mode, at.project, MemberReference(""))
}
return getTarget(at, target)?.let { MyCollectVisitor(mode, at.project, it) }
}
override fun createLookup(targetClass: ClassNode, result: CollectVisitor.Result<PsiMember>): LookupElementBuilder? {
when (val target = result.target) {
is PsiClass -> {
return JavaLookupElementBuilder.forClass(target, target.internalName)
.withPresentableText(target.shortName ?: return null)
}
is PsiMethod -> {
val ownerName = result.qualifier?.substringAfterLast('.')?.replace('$', '.') ?: targetClass.shortName
return JavaLookupElementBuilder.forMethod(
target,
target.getQualifiedMemberReference(result.qualifier).toMixinString(),
PsiSubstitutor.EMPTY,
null
)
.setBoldIfInClass(target, targetClass)
.withPresentableText(ownerName + "." + target.internalName)
.withLookupString(target.internalName)
}
else -> return null
}
}
private class MyNavigationVisitor(
private val selector: MixinSelector
) : NavigationVisitor() {
override fun visitNewExpression(expression: PsiNewExpression) {
val anonymousName = expression.anonymousClass?.fullQualifiedName?.replace('.', '/')
if (anonymousName != null) {
// guess descriptor
val hasThis = expression.parentOfType<PsiMethod>()?.hasModifierProperty(PsiModifier.STATIC) == false
val thisType = if (hasThis) expression.parentOfType<PsiClass>()?.internalName else null
val argTypes = expression.argumentList?.expressionTypes?.map { it.descriptor } ?: emptyList()
val bytecodeArgTypes = if (thisType != null) listOf(thisType) + argTypes else argTypes
val methodDesc = Type.getMethodDescriptor(
Type.VOID_TYPE,
*bytecodeArgTypes.mapToArray { Type.getType(it) }
)
if (selector.matchMethod(anonymousName, "<init>", methodDesc)) {
addResult(expression)
}
} else {
val ctor = expression.resolveConstructor()
val containingClass = ctor?.containingClass
if (ctor != null && containingClass != null) {
if (selector.matchMethod(ctor, containingClass)) {
addResult(expression)
}
}
}
super.visitNewExpression(expression)
}
}
private class MyCollectVisitor(
mode: Mode,
private val project: Project,
private val selector: MixinSelector
) : CollectVisitor<PsiMember>(mode) {
override fun accept(methodNode: MethodNode) {
val insns = methodNode.instructions ?: return
insns.iterator().forEachRemaining { insn ->
if (insn !is TypeInsnNode) return@forEachRemaining
if (insn.opcode != Opcodes.NEW) return@forEachRemaining
val initCall = findInitCall(insn) ?: return@forEachRemaining
if (mode != Mode.COMPLETION) {
if (!selector.matchMethod(initCall.owner, initCall.name, initCall.desc)) {
return@forEachRemaining
}
}
val targetMethod = initCall.fakeResolve()
addResult(
insn,
targetMethod.method.findOrConstructSourceMethod(
targetMethod.clazz,
project,
canDecompile = false
),
qualifier = insn.desc.replace('/', '.')
)
}
}
}
companion object {
fun findInitCall(newInsn: TypeInsnNode): MethodInsnNode? {
var newInsns = 0
var insn: AbstractInsnNode? = newInsn
while (insn != null) {
when (insn) {
is TypeInsnNode -> {
if (insn.opcode == Opcodes.NEW) {
newInsns++
}
}
is MethodInsnNode -> {
if (insn.opcode == Opcodes.INVOKESPECIAL && insn.name == "<init>") {
newInsns--
if (newInsns == 0) {
return insn
}
}
}
}
insn = insn.next
}
return null
}
}
}
class NewInsnSelectorParser : MixinSelectorParser {
override fun parse(value: String, context: PsiElement): MixinSelector? {
// check we're inside NEW
val at = context.parentOfType<PsiAnnotation>() ?: return null
if (!at.hasQualifiedName(AT)) return null
if (at.findAttributeValue("value")?.constantStringValue != "NEW") return null
return classToMemberReference(value)
}
}
private fun classToMemberReference(value: String): MemberReference? {
val fqn = value.replace('/', '.').replace('$', '.')
if (fqn.isNotEmpty() && !fqn.startsWith('.') && !fqn.endsWith('.') && !fqn.contains("..")) {
if (StringUtil.isJavaIdentifier(fqn.replace('.', '_'))) {
return MemberReference("<init>", owner = fqn)
}
}
return null
}
| mit | 58558e85f4ab964cc76f90f8bfd9a95b | 38.866667 | 120 | 0.607262 | 5.161529 | false | false | false | false |
bozaro/git-as-svn | src/test/kotlin/svnserver/server/SvnFilePropertyTest.kt | 1 | 21138 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.server
import org.testng.Assert
import org.testng.annotations.Test
import org.tmatesoft.svn.core.SVNException
import org.tmatesoft.svn.core.SVNLogEntry
import org.tmatesoft.svn.core.SVNProperty
import org.tmatesoft.svn.core.SVNPropertyValue
import org.tmatesoft.svn.core.internal.wc.SVNFileUtil
import org.tmatesoft.svn.core.io.SVNRepository
import svnserver.SvnTestHelper
import svnserver.SvnTestServer
/**
* Check file properties.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class SvnFilePropertyTest {
/**
* Check commit .gitattributes.
*/
@Test
fun executable() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
SvnTestHelper.createFile(repo, "/non-exec.txt", "", emptyMap())
SvnTestHelper.createFile(repo, "/exec.txt", "", propsExecutable)
SvnTestHelper.checkFileProp(repo, "/non-exec.txt", emptyMap())
SvnTestHelper.checkFileProp(repo, "/exec.txt", propsExecutable)
run {
val latestRevision = repo.latestRevision
val editor = repo.getCommitEditor("Create directory: /foo", null, false, null)
editor.openRoot(-1)
editor.openFile("/non-exec.txt", latestRevision)
editor.changeFileProperty("/non-exec.txt", SVNProperty.EXECUTABLE, SVNPropertyValue.create("*"))
editor.closeFile("/non-exec.txt", null)
editor.openFile("/exec.txt", latestRevision)
editor.changeFileProperty("/exec.txt", SVNProperty.EXECUTABLE, null)
editor.closeFile("/exec.txt", null)
editor.closeDir()
editor.closeEdit()
}
SvnTestHelper.checkFileProp(repo, "/non-exec.txt", propsExecutable)
SvnTestHelper.checkFileProp(repo, "/exec.txt", emptyMap())
}
}
/**
* Check commit .gitattributes.
*/
@Test
fun binary() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
SvnTestHelper.createFile(repo, "/data.txt", "Test file", emptyMap())
SvnTestHelper.createFile(repo, "/data.dat", "Test data\u0000", propsBinary)
SvnTestHelper.checkFileProp(repo, "/data.txt", emptyMap())
SvnTestHelper.checkFileProp(repo, "/data.dat", propsBinary)
run {
val latestRevision = repo.latestRevision
val editor = repo.getCommitEditor("Modify files", null, false, null)
editor.openRoot(-1)
editor.openFile("/data.txt", latestRevision)
editor.changeFileProperty("/data.txt", SVNProperty.MIME_TYPE, SVNPropertyValue.create(SVNFileUtil.BINARY_MIME_TYPE))
editor.changeFileProperty("/data.txt", SVNProperty.EOL_STYLE, null)
SvnTestHelper.sendDeltaAndClose(editor, "/data.txt", "Test file", "Test file\u0000")
editor.openFile("/data.dat", latestRevision)
editor.changeFileProperty("/data.dat", SVNProperty.MIME_TYPE, null)
SvnTestHelper.sendDeltaAndClose(editor, "/data.dat", "Test data\u0000", "Test data")
editor.closeDir()
editor.closeEdit()
}
SvnTestHelper.checkFileProp(repo, "/data.txt", propsBinary)
SvnTestHelper.checkFileProp(repo, "/data.dat", emptyMap())
}
}
/**
* Check commit .gitattributes.
*/
@Test
fun symlink() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
val content = "link foo/bar.txt"
SvnTestHelper.createFile(repo, "/non-link", content, emptyMap())
SvnTestHelper.createFile(repo, "/link", content, propsSymlink)
SvnTestHelper.checkFileProp(repo, "/non-link", emptyMap())
SvnTestHelper.checkFileProp(repo, "/link", propsSymlink)
SvnTestHelper.checkFileContent(repo, "/non-link", content)
SvnTestHelper.checkFileContent(repo, "/link", content)
val content2 = "link bar/foo.txt"
run {
val latestRevision = repo.latestRevision
val editor = repo.getCommitEditor("Change symlink property", null, false, null)
editor.openRoot(-1)
editor.openFile("/non-link", latestRevision)
editor.changeFileProperty("/non-link", SVNProperty.SPECIAL, SVNPropertyValue.create("*"))
SvnTestHelper.sendDeltaAndClose(editor, "/non-link", content, content2)
editor.openFile("/link", latestRevision)
editor.changeFileProperty("/link", SVNProperty.SPECIAL, null)
SvnTestHelper.sendDeltaAndClose(editor, "/link", content, content2)
editor.closeDir()
editor.closeEdit()
}
SvnTestHelper.checkFileProp(repo, "/non-link", propsSymlink)
SvnTestHelper.checkFileProp(repo, "/link", emptyMap())
SvnTestHelper.checkFileContent(repo, "/non-link", content2)
SvnTestHelper.checkFileContent(repo, "/link", content2)
run {
val latestRevision = repo.latestRevision
val editor = repo.getCommitEditor("Change symlink property", null, false, null)
editor.openRoot(-1)
editor.openFile("/non-link", latestRevision)
editor.changeFileProperty("/non-link", SVNProperty.SPECIAL, null)
editor.closeFile("/non-link", null)
editor.openFile("/link", latestRevision)
editor.changeFileProperty("/link", SVNProperty.SPECIAL, SVNPropertyValue.create("*"))
editor.closeFile("/link", null)
editor.closeDir()
editor.closeEdit()
}
SvnTestHelper.checkFileProp(repo, "/non-link", emptyMap())
SvnTestHelper.checkFileProp(repo, "/link", propsSymlink)
SvnTestHelper.checkFileContent(repo, "/non-link", content2)
SvnTestHelper.checkFileContent(repo, "/link", content2)
}
}
@Test
fun native() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
val content = "foo"
SvnTestHelper.createFile(repo, "/text.txt", content, emptyMap())
SvnTestHelper.createFile(repo, "/.gitattributes", "*.txt text", emptyMap())
SvnTestHelper.checkFileProp(repo, "/text.txt", propsEolNative)
}
}
@Test
fun crlf() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
val content = "foo"
SvnTestHelper.createFile(repo, "/text.txt", content, emptyMap())
SvnTestHelper.createFile(repo, "/.gitattributes", "*.txt eol=crlf", emptyMap())
SvnTestHelper.checkFileProp(repo, "/text.txt", propsEolCrLf)
}
}
@Test
fun symlinkBinary() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
val content = "link foo/bar.txt"
SvnTestHelper.createFile(repo, "/.gitattributes", "*.bin binary", emptyMap())
SvnTestHelper.createFile(repo, "/non-link.bin", content, propsBinary)
SvnTestHelper.createFile(repo, "/link.bin", content, propsSymlink)
SvnTestHelper.checkFileProp(repo, "/non-link.bin", propsBinary)
SvnTestHelper.checkFileProp(repo, "/link.bin", propsSymlink)
SvnTestHelper.checkFileContent(repo, "/non-link.bin", content)
SvnTestHelper.checkFileContent(repo, "/link.bin", content)
}
}
@Test
fun needsLock() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
val content = "link foo/bar.txt"
SvnTestHelper.createFile(repo, "/link.bin", content, emptyMap())
SvnTestHelper.createFile(repo, "/.gitattributes", "*.bin lockable", emptyMap())
SvnTestHelper.checkFileProp(repo, "/link.bin", propsNeedsLock)
}
}
/**
* Check commit .gitattributes.
*/
@Test
fun commitUpdatePropertiesRoot() {
//Map<String, String> props = new HashMap<>()["key":""];
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
SvnTestHelper.createFile(repo, "/sample.txt", "", emptyMap())
SvnTestHelper.checkFileProp(repo, "/sample.txt", emptyMap())
SvnTestHelper.createFile(repo, "/.gitattributes", "*.txt\t\t\ttext eol=lf\n", emptyMap())
// After commit .gitattributes file sample.txt must change property svn:eol-style automagically.
SvnTestHelper.checkFileProp(repo, "/sample.txt", propsEolLf)
// After commit .gitattributes directory with .gitattributes must change property svn:auto-props automagically.
SvnTestHelper.checkDirProp(repo, "/", propsAutoProps)
// After commit .gitattributes file sample.txt must change property svn:eol-style automagically.
run {
val changed = HashSet<String>()
repo.log(arrayOf(""), repo.latestRevision, repo.latestRevision, true, false) { logEntry: SVNLogEntry -> changed.addAll(logEntry.changedPaths.keys) }
Assert.assertTrue(changed.contains("/"))
Assert.assertTrue(changed.contains("/.gitattributes"))
Assert.assertTrue(changed.contains("/sample.txt"))
Assert.assertEquals(changed.size, 3)
}
}
}
/**
* Check commit .gitattributes.
*/
@Test
fun commitUpdatePropertiesSubdir() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
run {
val editor = repo.getCommitEditor("Create directory: /foo", null, false, null)
editor.openRoot(-1)
editor.addDir("/foo", null, -1)
// Empty file.
val emptyFile = "/foo/.keep"
editor.addFile(emptyFile, null, -1)
SvnTestHelper.sendDeltaAndClose(editor, emptyFile, null, "")
// Close dir
editor.closeDir()
editor.closeDir()
editor.closeEdit()
}
SvnTestHelper.createFile(repo, "/sample.txt", "", emptyMap())
SvnTestHelper.createFile(repo, "/foo/sample.txt", "", emptyMap())
SvnTestHelper.checkFileProp(repo, "/sample.txt", emptyMap())
SvnTestHelper.checkFileProp(repo, "/foo/sample.txt", emptyMap())
SvnTestHelper.createFile(repo, "/foo/.gitattributes", "*.txt\t\t\ttext eol=lf\n", emptyMap())
// After commit .gitattributes file sample.txt must change property svn:eol-style automagically.
SvnTestHelper.checkFileProp(repo, "/foo/sample.txt", propsEolLf)
SvnTestHelper.checkFileProp(repo, "/sample.txt", emptyMap())
// After commit .gitattributes directory with .gitattributes must change property svn:auto-props automagically.
SvnTestHelper.checkDirProp(repo, "/foo", propsAutoProps)
// After commit .gitattributes file sample.txt must change property svn:eol-style automagically.
run {
val changed = HashSet<String>()
repo.log(arrayOf(""), repo.latestRevision, repo.latestRevision, true, false) { logEntry: SVNLogEntry -> changed.addAll(logEntry.changedPaths.keys) }
Assert.assertTrue(changed.contains("/foo"))
Assert.assertTrue(changed.contains("/foo/.gitattributes"))
Assert.assertTrue(changed.contains("/foo/sample.txt"))
Assert.assertEquals(changed.size, 3)
}
}
}
/**
* Check commit .gitattributes.
*/
@Test
fun commitDirWithProperties() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
val latestRevision = repo.latestRevision
val editor = repo.getCommitEditor("Create directory: /foo", null, false, null)
editor.openRoot(-1)
editor.addDir("/foo", null, latestRevision)
editor.changeDirProperty(SVNProperty.INHERITABLE_AUTO_PROPS, SVNPropertyValue.create("*.txt = svn:eol-style=native\n"))
// Empty file.
val filePath = "/foo/.gitattributes"
editor.addFile(filePath, null, -1)
SvnTestHelper.sendDeltaAndClose(editor, filePath, null, "*.txt\t\t\ttext\n")
// Close dir
editor.closeDir()
editor.closeDir()
editor.closeEdit()
}
}
/**
* Check commit .gitattributes.
*/
@Test
fun commitDirWithoutProperties() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
try {
val latestRevision = repo.latestRevision
val editor = repo.getCommitEditor("Create directory: /foo", null, false, null)
editor.openRoot(-1)
editor.addDir("/foo", null, latestRevision)
// Empty file.
val filePath = "/foo/.gitattributes"
editor.addFile(filePath, null, -1)
SvnTestHelper.sendDeltaAndClose(editor, filePath, null, "*.txt\t\t\ttext\n")
// Close dir
editor.closeDir()
editor.closeDir()
editor.closeEdit()
Assert.fail()
} catch (e: SVNException) {
Assert.assertTrue(e.message!!.contains(SVNProperty.INHERITABLE_AUTO_PROPS))
}
}
}
/**
* Check commit .gitattributes.
*/
@Test
fun commitDirUpdateWithProperties() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
run {
val editor = repo.getCommitEditor("Create directory: /foo", null, false, null)
editor.openRoot(-1)
editor.addDir("/foo", null, -1)
// Empty file.
val filePath = "/foo/.gitattributes"
editor.addFile(filePath, null, -1)
SvnTestHelper.sendDeltaAndClose(editor, filePath, null, "")
// Close dir
editor.closeDir()
editor.closeDir()
editor.closeEdit()
}
run {
val latestRevision = repo.latestRevision
val editor = repo.getCommitEditor("Modify .gitattributes", null, false, null)
editor.openRoot(-1)
editor.openDir("/foo", latestRevision)
editor.changeDirProperty(SVNProperty.INHERITABLE_AUTO_PROPS, SVNPropertyValue.create("*.txt = svn:eol-style=native\n"))
// Empty file.
val filePath = "/foo/.gitattributes"
editor.openFile(filePath, latestRevision)
SvnTestHelper.sendDeltaAndClose(editor, filePath, "", "*.txt\t\t\ttext\n")
// Close dir
editor.closeDir()
editor.closeDir()
editor.closeEdit()
}
}
}
/**
* Check commit .gitattributes.
*/
@Test
fun commitDirUpdateWithoutProperties() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
run {
val editor = repo.getCommitEditor("Create directory: /foo", null, false, null)
editor.openRoot(-1)
editor.addDir("/foo", null, -1)
// Empty file.
val filePath = "/foo/.gitattributes"
editor.addFile(filePath, null, -1)
SvnTestHelper.sendDeltaAndClose(editor, filePath, null, "")
// Close dir
editor.closeDir()
editor.closeDir()
editor.closeEdit()
}
try {
val latestRevision = repo.latestRevision
val editor = repo.getCommitEditor("Modify .gitattributes", null, false, null)
editor.openRoot(-1)
editor.openDir("/foo", latestRevision)
// Empty file.
val filePath = "/foo/.gitattributes"
editor.openFile(filePath, latestRevision)
SvnTestHelper.sendDeltaAndClose(editor, filePath, "", "*.txt\t\t\ttext\n")
// Close dir
editor.closeDir()
editor.closeDir()
editor.closeEdit()
Assert.fail()
} catch (e: SVNException) {
Assert.assertTrue(e.message!!.contains(SVNProperty.INHERITABLE_AUTO_PROPS))
}
}
}
/**
* Check commit .gitattributes.
*/
@Test
fun commitRootWithProperties() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
SvnTestHelper.createFile(repo, "/.gitattributes", "", emptyMap())
run {
val latestRevision = repo.latestRevision
val editor = repo.getCommitEditor("Modify .gitattributes", null, false, null)
editor.openRoot(latestRevision)
editor.changeDirProperty(SVNProperty.INHERITABLE_AUTO_PROPS, SVNPropertyValue.create("*.txt = svn:eol-style=native\n"))
// Empty file.
val filePath = "/.gitattributes"
editor.openFile(filePath, latestRevision)
SvnTestHelper.sendDeltaAndClose(editor, filePath, "", "*.txt\t\t\ttext\n")
// Close dir
editor.closeDir()
editor.closeEdit()
}
}
}
/**
* Check commit .gitattributes.
*/
@Test
fun commitRootWithoutProperties() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
SvnTestHelper.createFile(repo, "/.gitattributes", "", emptyMap())
try {
val latestRevision = repo.latestRevision
val editor = repo.getCommitEditor("Modify .gitattributes", null, false, null)
editor.openRoot(latestRevision)
// Empty file.
val filePath = "/.gitattributes"
editor.openFile(filePath, latestRevision)
SvnTestHelper.sendDeltaAndClose(editor, filePath, "", "*.txt\t\t\ttext\n")
// Close dir
editor.closeDir()
editor.closeEdit()
Assert.fail()
} catch (e: SVNException) {
Assert.assertTrue(e.message!!.contains(SVNProperty.INHERITABLE_AUTO_PROPS))
}
}
}
/**
* Check commit .gitattributes.
*/
@Test
fun commitFileWithProperties() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
SvnTestHelper.createFile(repo, "sample.txt", "", emptyMap())
SvnTestHelper.checkFileProp(repo, "/sample.txt", emptyMap())
SvnTestHelper.createFile(repo, ".gitattributes", "*.txt\t\t\ttext eol=lf\n", emptyMap())
SvnTestHelper.createFile(repo, "with-props.txt", "", propsEolLf)
try {
SvnTestHelper.createFile(repo, "none-props.txt", "", emptyMap())
} catch (e: SVNException) {
Assert.assertTrue(e.message!!.contains(SVNProperty.EOL_STYLE))
}
}
}
companion object {
val propsBinary = mapOf(SVNProperty.MIME_TYPE to SVNFileUtil.BINARY_MIME_TYPE)
val propsEolNative = mapOf(SVNProperty.EOL_STYLE to SVNProperty.EOL_STYLE_NATIVE)
val propsEolLf = mapOf(SVNProperty.EOL_STYLE to SVNProperty.EOL_STYLE_LF)
val propsEolCrLf = mapOf(SVNProperty.EOL_STYLE to SVNProperty.EOL_STYLE_CRLF)
val propsExecutable = mapOf(SVNProperty.EXECUTABLE to "*")
val propsSymlink = mapOf(SVNProperty.SPECIAL to "*")
val propsAutoProps = mapOf(SVNProperty.INHERITABLE_AUTO_PROPS to "*.txt = svn:eol-style=LF\n")
val propsNeedsLock = mapOf(SVNProperty.NEEDS_LOCK to "*")
}
}
| gpl-2.0 | 23de80985c8c130cce388efe54309155 | 44.753247 | 164 | 0.587946 | 4.649802 | false | true | false | false |
pennlabs/penn-mobile-android | PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/PhoneSaveAdapter.kt | 1 | 2214 | package com.pennapps.labs.pennmobile.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import com.pennapps.labs.pennmobile.R
import com.pennapps.labs.pennmobile.classes.Contact
import kotlinx.android.synthetic.main.phone_save_list_item.view.*
class PhoneSaveAdapter(context: Context, contacts: List<Contact?>, s: MutableList<Contact>, size: Int) : ArrayAdapter<Contact?>(context, R.layout.phone_save_list_item, contacts) {
private val inflater: LayoutInflater = LayoutInflater.from(context)
private val selections: MutableList<Contact> = s
private val state: BooleanArray = BooleanArray(size)
override fun getView(pos: Int, view: View?, parent: ViewGroup): View {
//var view = view
val currentPerson = getItem(pos)
val view = view ?: inflater.inflate(R.layout.phone_save_list_item, parent, false)
val nameTv = view.support_name
val supportPhoneTv = view.support_phone
val checkbox = view.phone_save_checkbox
nameTv?.text = currentPerson?.name
supportPhoneTv?.text = currentPerson?.phone
view.support_phone_icon?.visibility = if (currentPerson?.isURL == true) View.GONE else View.VISIBLE
checkbox?.setOnCheckedChangeListener(null)
checkbox?.isChecked = state[pos]
checkbox?.setOnCheckedChangeListener { buttonView, isChecked ->
if (!state[pos]) {
checkbox.isChecked = true
selections.add(Contact(nameTv?.text.toString(), supportPhoneTv.text.toString()))
state[pos] = true
} else {
view.phone_save_checkbox?.isChecked = false
for (p in selections) {
if (p.name == nameTv?.text.toString()) {
selections.remove(p)
break
}
}
state[pos] = false
}
}
view.setOnClickListener { checkbox.isChecked = !checkbox.isChecked }
return view
}
init {
for (i in state.indices) {
state[i] = true
}
}
} | mit | 3fe7d6931003396dde65625d676d5e9d | 38.553571 | 179 | 0.631436 | 4.509165 | false | false | false | false |
plombardi89/kbaseball | user-service/service/src/main/kotlin/kbaseball/user/UserApplication.kt | 1 | 3806 | /*
Copyright (C) 2015 Philip Lombardi <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package kbaseball.user
import com.github.toastshaman.dropwizard.auth.jwt.hmac.HmacSHA512Signer
import com.github.toastshaman.dropwizard.auth.jwt.model.JsonWebTokenHeader
import com.loginbox.dropwizard.mybatis.MybatisBundle
import io.dropwizard.Application
import io.dropwizard.db.PooledDataSourceFactory
import io.dropwizard.migrations.MigrationsBundle
import io.dropwizard.setup.Bootstrap
import io.dropwizard.setup.Environment
import kbaseball.email.EmailContentTemplate
import kbaseball.service.auth.JwtJerseyConfigurator
import kbaseball.user.exception.mapper.UserExistsAlreadyExceptionMapper
import kbaseball.user.exception.mapper.UserNotFoundExceptionMapper
import kbaseball.user.resource.LoginResource
import kbaseball.user.resource.UserResource
import org.apache.ibatis.session.Configuration
import org.passay.*
class UserApplication : Application<UserApplicationConfiguration>() {
companion object {
@JvmStatic fun main(args: Array<String>) {
UserApplication().run(*args)
}
}
private val mybatisBundle = object : MybatisBundle<UserApplicationConfiguration>() {
override fun getDataSourceFactory(configuration: UserApplicationConfiguration?): PooledDataSourceFactory? {
return configuration!!.dataSourceFactory
}
override fun configureMybatis(configuration: Configuration?) {
configuration?.typeHandlerRegistry?.register("com.github.javaplugs.mybatis")
configuration?.mapperRegistry?.addMappers("kbaseball.user.db.mapper")
}
}
override fun initialize(bootstrap: Bootstrap<UserApplicationConfiguration>?) {
bootstrap!!
bootstrap.addBundle(object : MigrationsBundle<UserApplicationConfiguration>() {
override fun getDataSourceFactory(configuration: UserApplicationConfiguration?): PooledDataSourceFactory? {
return configuration!!.dataSourceFactory
}
})
bootstrap.addBundle(mybatisBundle)
}
override fun run(config: UserApplicationConfiguration, environment: Environment?) {
environment!!
val emailer = config.email.buildEmailer()
val welcomeEmail = EmailContentTemplate.Factory.newTemplate("email/welcome.html", "email/welcome.txt")
.withVariable("kbaseballUrl", "https://example.org/kbaseball")
val userResource = UserResource(buildPasswordValidator(), emailer, welcomeEmail)
// configure jersey to work with JSON Web Tokens
JwtJerseyConfigurator().configureJersey(environment.jersey(), config.getJwtTokenSecret())
val loginResource = LoginResource(
JsonWebTokenHeader.HS512(),
HmacSHA512Signer(config.getJwtTokenSecret()))
environment.jersey().register(loginResource)
environment.jersey().register(userResource)
environment.jersey().register(UserExistsAlreadyExceptionMapper::class.java)
environment.jersey().register(UserNotFoundExceptionMapper::class.java)
}
private fun buildPasswordValidator(): PasswordValidator {
return PasswordValidator(listOf(
LengthRule(8, 100),
CharacterRule(EnglishCharacterData.Digit, 1),
CharacterRule(EnglishCharacterData.LowerCase, 1)
))
}
} | agpl-3.0 | db833ca14f968e5358ec4520b16d7885 | 36.693069 | 113 | 0.783762 | 4.563549 | false | true | false | false |
vondear/RxTools | RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityCobweb.kt | 1 | 2918 | package com.tamsiree.rxdemo.activity
import android.os.Bundle
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import com.tamsiree.rxdemo.R
import com.tamsiree.rxkit.RxDeviceTool.setPortrait
import com.tamsiree.rxkit.model.ModelSpider
import com.tamsiree.rxui.activity.ActivityBase
import com.tamsiree.rxui.view.colorpicker.OnColorChangedListener
import com.tamsiree.rxui.view.colorpicker.OnColorSelectedListener
import kotlinx.android.synthetic.main.activity_cobweb.*
import java.util.*
/**
* @author tamsiree
*/
class ActivityCobweb : ActivityBase(), OnSeekBarChangeListener {
private val nameStrs = arrayOf(
"金钱", "能力", "美貌", "智慧", "交际",
"口才", "力量", "智力", "体力", "体质",
"敏捷", "精神", "耐力", "精通", "急速",
"暴击", "回避", "命中", "跳跃", "反应",
"幸运", "魅力", "感知", "活力", "意志"
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//RxBarTool.setTransparentStatusBar(mContext);
setContentView(R.layout.activity_cobweb)
setPortrait(this)
}
override fun initView() {
rx_title.setLeftFinish(mContext)
seekbar_level.setOnSeekBarChangeListener(this)
seekbar_spider_number.setOnSeekBarChangeListener(this)
color_picker_view.addOnColorChangedListener(object : OnColorChangedListener {
override fun onColorChanged(selectedColor: Int) {
cobweb_view.spiderColor = selectedColor
}
})
color_picker_view.addOnColorSelectedListener(object : OnColorSelectedListener {
override fun onColorSelected(selectedColor: Int) {
}
})
color_picker_view_level.addOnColorChangedListener(object : OnColorChangedListener {
override fun onColorChanged(selectedColor: Int) {
cobweb_view.spiderLevelColor = selectedColor
}
})
}
override fun initData() {
}
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
when (seekBar.id) {
R.id.seekbar_level -> cobweb_view.spiderMaxLevel = progress + 1
R.id.seekbar_spider_number -> {
val number = progress + 1
val modelSpiders: MutableList<ModelSpider> = ArrayList()
var i = 0
while (i < number) {
modelSpiders.add(ModelSpider(nameStrs[i], (1 + Random().nextInt(cobweb_view.spiderMaxLevel)).toFloat()))
i++
}
cobweb_view.setSpiderList(modelSpiders)
}
else -> {
}
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
} | apache-2.0 | df3eca883b03462839a5eb099d8c8955 | 31.402299 | 124 | 0.62704 | 4.224888 | false | false | false | false |
stripe/stripe-android | paymentsheet/src/main/java/com/stripe/android/paymentsheet/ui/AddressOptionsAppBar.kt | 1 | 1567 | package com.stripe.android.paymentsheet.ui
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.stripe.android.paymentsheet.R
import com.stripe.android.ui.core.paymentsColors
@Composable
internal fun AddressOptionsAppBar(
isRootScreen: Boolean,
onButtonClick: () -> Unit
) {
TopAppBar(
modifier = Modifier.fillMaxWidth(),
elevation = 0.dp,
backgroundColor = MaterialTheme.colors.surface
) {
IconButton(
onClick = onButtonClick
) {
Icon(
painter = painterResource(
id = if (isRootScreen) {
R.drawable.stripe_ic_paymentsheet_close_enabled
} else {
R.drawable.stripe_ic_paymentsheet_back_enabled
}
),
contentDescription = stringResource(
if (isRootScreen) {
R.string.stripe_paymentsheet_close
} else {
R.string.back
}
),
tint = MaterialTheme.paymentsColors.appBarIcon
)
}
}
}
| mit | 883d4b5879a511ead3c5e4ac7e4ac212 | 31.645833 | 71 | 0.606254 | 5.120915 | false | false | false | false |
syrop/Victor-Events | events/src/main/kotlin/pl/org/seva/events/login/Login.kt | 1 | 1263 | /*
* Copyright (C) 2017 Wiktor Nizio
*
* 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/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.events.login
import com.google.firebase.auth.FirebaseUser
class Login {
var isLoggedIn: Boolean = false
var email: String = ""
var displayName: String = ""
fun setCurrentUser(user: FirebaseUser?) = if (user != null) {
isLoggedIn = true
email = checkNotNull(user.email)
displayName = checkNotNull(user.displayName)
} else {
isLoggedIn = false
email = ""
displayName = ""
}
}
| gpl-3.0 | 3cbb63fe019490867db5dd0100fd5cd1 | 32.236842 | 98 | 0.702296 | 4.074194 | false | false | false | false |
stripe/stripe-android | paymentsheet/src/main/java/com/stripe/android/paymentsheet/ui/GooglePayDivider.kt | 1 | 1821 | package com.stripe.android.paymentsheet.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.stripe.android.paymentsheet.R
import com.stripe.android.ui.core.paymentsColors
import com.stripe.android.ui.core.paymentsShapes
import com.stripe.android.ui.core.shouldUseDarkDynamicColor
@Composable
internal fun GooglePayDividerUi(
text: String = stringResource(R.string.stripe_paymentsheet_or_pay_with_card)
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxWidth()
.padding(top = 18.dp)
) {
GooglePayDividerLine()
Text(
text = text,
style = MaterialTheme.typography.body1,
color = MaterialTheme.paymentsColors.subtitle,
modifier = Modifier
.background(MaterialTheme.colors.surface)
.padding(horizontal = 8.dp)
)
}
}
@Composable
internal fun GooglePayDividerLine() {
val color = if (MaterialTheme.colors.surface.shouldUseDarkDynamicColor()) {
Color.Black.copy(alpha = .20f)
} else {
Color.White.copy(alpha = .20f)
}
Box(
Modifier
.background(color)
.height(MaterialTheme.paymentsShapes.borderStrokeWidth.dp)
.fillMaxWidth()
)
}
| mit | 40aeb635be26b2eabf9a102111cce350 | 31.517857 | 80 | 0.714443 | 4.325416 | false | false | false | false |
afollestad/photo-affix | app/src/main/java/com/afollestad/photoaffix/views/ActivityExt.kt | 1 | 2474 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.photoaffix.views
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.Intent.ACTION_VIEW
import android.content.pm.ActivityInfo
import android.net.Uri
import android.view.Surface
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.photoaffix.R
import com.afollestad.photoaffix.utilities.ext.hide
import kotlinx.android.synthetic.main.activity_main.content_loading_progress_frame
fun Activity.lockOrientation() {
val orientation: Int
val rotation = (getSystemService(AppCompatActivity.WINDOW_SERVICE) as WindowManager)
.defaultDisplay
.rotation
orientation = when (rotation) {
Surface.ROTATION_0 -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
Surface.ROTATION_90 -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
Surface.ROTATION_180 -> ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT
else -> ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
}
requestedOrientation = orientation
}
fun Activity.unlockOrientation() {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
}
fun Activity.viewUri(
uri: Uri,
onNoResolve: (() -> Unit)? = null
) {
try {
startActivity(
Intent(ACTION_VIEW)
.setDataAndType(uri, "image/*")
)
} catch (_: ActivityNotFoundException) {
onNoResolve?.invoke()
}
}
fun Activity.showErrorDialog(e: Exception) {
unlockOrientation()
content_loading_progress_frame.hide()
e.printStackTrace()
val message = if (e is OutOfMemoryError) {
"Your device is low on RAM!"
} else {
e.message
}
MaterialDialog(this).show {
title(R.string.error)
message(text = message)
positiveButton(android.R.string.ok)
}
}
| apache-2.0 | 853d6272450d850aa00461c0f45593ac | 30.316456 | 86 | 0.75384 | 4.302609 | false | false | false | false |
Undin/intellij-rust | toml/src/main/kotlin/org/rust/toml/inspections/CrateVersionInvalidInspection.kt | 3 | 1625 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.toml.inspections
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import org.rust.toml.crates.local.CargoRegistryCrate
import org.rust.toml.crates.local.CrateVersionRequirement
import org.rust.toml.stringValue
import org.toml.lang.psi.TomlValue
class CrateVersionInvalidInspection : CrateVersionInspection() {
override fun handleCrateVersion(
dependency: DependencyCrate,
crate: CargoRegistryCrate,
versionElement: TomlValue,
holder: ProblemsHolder
) {
val versionText = versionElement.stringValue ?: return
val versionReq = CrateVersionRequirement.build(versionText)
if (versionReq == null) {
holder.registerProblem(
versionElement,
"Invalid version requirement $versionText",
ProblemHighlightType.WEAK_WARNING
)
return
}
val compatibleVersions = crate.versions.filter {
val version = it.semanticVersion ?: return@filter false
versionReq.matches(version)
}
if (compatibleVersions.isEmpty()) {
holder.registerProblem(versionElement, "No version matching $versionText found for crate ${dependency.crateName}")
} else if (compatibleVersions.all { it.isYanked }) {
holder.registerProblem(versionElement, "All versions matching $versionText for crate ${dependency.crateName} are yanked")
}
}
}
| mit | f3965fe2fd9eaf4cf0040311b80c6afb | 35.111111 | 133 | 0.688 | 4.83631 | false | false | false | false |
Dr-Horv/Advent-of-Code-2017 | src/main/kotlin/solutions/day11/Day11.kt | 1 | 1457 |
package solutions.day11
import solutions.Solver
data class Position(val x: Int, val y: Int)
enum class Direction {
N,
NE,
SE,
S,
SW,
NW
}
fun String.toDirection(): Direction = when(this) {
"n" -> Direction.N
"ne" -> Direction.NE
"se" -> Direction.SE
"s" -> Direction.S
"sw" -> Direction.SW
"nw" -> Direction.NW
else -> throw RuntimeException("Unparsable direction")
}
fun Position.go(dir: Direction) : Position = when(dir){
Direction.N -> Position(x, y + 2)
Direction.NE -> Position(x+1, y+1)
Direction.SE -> Position(x+1, y-1)
Direction.S -> Position(x, y-2)
Direction.SW -> Position(x-1, y-1)
Direction.NW -> Position(x-1, y+1)
}
fun Position.distance(): Int {
val xPos = Math.abs(x)
val yPos = Math.abs(y)
return (yPos + xPos)/2
}
class Day11: Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val map = input.first()
.split(",")
.map(String::trim)
.map(String::toDirection)
var curr = Position(0,0)
var furthest = curr
map.forEach {
curr = curr.go(it)
if(partTwo && curr.distance() > furthest.distance()) {
furthest = curr
}
}
return if(!partTwo) {
(curr.distance()).toString()
} else {
(furthest.distance()).toString()
}
}
}
| mit | 5e16783bebb4a642de516d52ec0b4705 | 19.814286 | 71 | 0.538092 | 3.428235 | false | false | false | false |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/ui/WorkItemsListCellRenderer.kt | 1 | 8611 | package com.github.jk1.ytplugin.ui
import com.github.jk1.ytplugin.issues.model.IssueWorkItem
import com.intellij.icons.AllIcons
import com.intellij.tasks.youtrack.YouTrackRepository
import com.intellij.ui.Gray
import com.intellij.ui.JBColor
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.border.CustomLineBorder
import com.intellij.util.ui.UIUtil
import java.awt.*
import java.lang.Integer.max
import java.lang.Math.min
import javax.swing.JList
import javax.swing.JPanel
import javax.swing.ListCellRenderer
class WorkItemsListCellRenderer(
private val viewportWidthProvider: () -> Int, repo: YouTrackRepository
) : JPanel(BorderLayout()), ListCellRenderer<IssueWorkItem> {
private val myRepository = repo
private val topPanel = JPanel(BorderLayout())
private val summaryPanel = JPanel(BorderLayout())
lateinit var trackingComments: SimpleColoredComponent
private lateinit var issueLink: HyperlinkLabel
lateinit var datePanel: JPanel
lateinit var valuePanel: JPanel
lateinit var issueLinkPanel: JPanel
private fun getValuePanelPosition() = valuePanel.preferredSize.getWidth()
private fun getDatePanelPosition() = datePanel.preferredSize.getWidth()
private var PREFFERED_COMMENT_WIDTH = 0.484
private val PREFFERED_ATTRIBUTE_WIDTH = 0.080
private val PREFFERED_DATE_TYPE_WIDTH = 0.116
private val PREFFERED_ISSUE_ID_WIDTH = 0.078
private val PREFFERED_VALUE_WIDTH = 0.113
private val OFFSET_COMMENT = 100
private val OFFSET = 10
private val LARGE_SCREEN_SIZE = 1000
private val SMALL_SCREEN_SIZE = 450
private val PREFFERED_PANEL_HEIGHT = 32
private var maxAttributes = 0
private var maxIssueIdWidth = 0
fun getIssuePosition(): List<Int> {
val panelWidth = viewportWidthProvider.invoke()
//returns start of the x-position of issueId and its length
return listOf((getDatePanelPosition() + getValuePanelPosition()).toInt(), (0.2 * panelWidth).toInt())
}
init {
summaryPanel.isOpaque = false
border = CustomLineBorder(JBColor(Gray._220, Gray._85), 0, 0, 1, 0)
topPanel.isOpaque = false
topPanel.add(summaryPanel, BorderLayout.WEST)
add(topPanel, BorderLayout.NORTH)
topPanel.revalidate()
}
override fun getListCellRendererComponent(
list: JList<out IssueWorkItem>,
issueWorkItem: IssueWorkItem, index: Int,
isSelected: Boolean, cellHasFocus: Boolean
): Component {
background = UIUtil.getListBackground(false, false)
fillTrackingInfoLine(issueWorkItem)
return this
}
fun setCustomAttributesNum(num: Int) {
maxAttributes = num
}
private fun fillTrackingInfoLine(issueWorkItem: IssueWorkItem) {
summaryPanel.removeAll()
summaryPanel.isOpaque = false
val renderer = WorkItemCellRenderer(issueWorkItem)
val date = renderer.fillDateComponent()
val value = renderer.fillIssueComponent()
val type = renderer.fillTypeComponent()
val attributes = renderer.fillAttributesComponents()
if (issueWorkItem.attributes.size > maxAttributes) {
maxAttributes = issueWorkItem.attributes.size
PREFFERED_COMMENT_WIDTH = 0.484 - maxAttributes * PREFFERED_ATTRIBUTE_WIDTH
updateUI()
}
issueLink = HyperlinkLabel(
issueWorkItem.issueId,
"${myRepository.url}/issue/${issueWorkItem.issueId}", AllIcons.Actions.MoveTo2
)
issueLink.isOpaque = false
if (issueWorkItem.issueId.length > maxIssueIdWidth) {
maxIssueIdWidth = issueWorkItem.issueId.length
}
trackingComments = renderer.fillCommentComponent((PREFFERED_COMMENT_WIDTH *
viewportWidthProvider.invoke()).toInt() - OFFSET_COMMENT)
val layout = FlowLayout(FlowLayout.LEFT)
layout.hgap = 0
layout.vgap = 0
val panel = JPanel(layout)
panel.isOpaque = false
val panelWidth = viewportWidthProvider.invoke()
panel.preferredSize = Dimension(panelWidth, PREFFERED_PANEL_HEIGHT)
datePanel = createPanel()
issueLinkPanel = createPanel()
valuePanel = createPanel()
value.alignmentX = Component.RIGHT_ALIGNMENT
valuePanel.alignmentX = Component.RIGHT_ALIGNMENT
if (panelWidth > LARGE_SCREEN_SIZE) {
adaptSizeForTheLargeScreen(panelWidth)
} else {
adaptSizeForTheSmallScreen(panelWidth)
}
datePanel.add(date)
valuePanel.add(value)
issueLinkPanel.add(issueLink)
panel.add(datePanel)
panel.add(valuePanel)
if (panelWidth > SMALL_SCREEN_SIZE) {
panel.add(issueLinkPanel)
if (panelWidth > LARGE_SCREEN_SIZE) {
addType(type, panel, panelWidth)
addAttributes(attributes, panel, panelWidth)
addComment(panel, panelWidth)
}
}
summaryPanel.add(panel, BorderLayout.CENTER)
}
private fun createPanel(): JPanel {
val panel = JPanel(FlowLayout(FlowLayout.LEFT))
panel.isOpaque = false
return panel
}
private fun adaptSizeForTheLargeScreen(panelWidth: Int) {
val minIssueIdWidth = (PREFFERED_ISSUE_ID_WIDTH * panelWidth).toInt()
val unitWidth = PREFFERED_ISSUE_ID_WIDTH * panelWidth / 6
datePanel.preferredSize = Dimension(
(PREFFERED_DATE_TYPE_WIDTH * panelWidth).toInt(),
PREFFERED_PANEL_HEIGHT + OFFSET
)
valuePanel.preferredSize = Dimension(
(PREFFERED_VALUE_WIDTH * panelWidth).toInt(),
PREFFERED_PANEL_HEIGHT + OFFSET
)
issueLinkPanel.preferredSize = Dimension(
max((unitWidth * maxIssueIdWidth).toInt(), minIssueIdWidth),
PREFFERED_PANEL_HEIGHT + OFFSET
)
}
private fun adaptSizeForTheSmallScreen(panelWidth: Int) {
datePanel.preferredSize = Dimension((0.3 * panelWidth).toInt(), PREFFERED_PANEL_HEIGHT)
valuePanel.preferredSize = Dimension((0.4 * panelWidth).toInt(), PREFFERED_PANEL_HEIGHT)
issueLinkPanel.preferredSize = Dimension((0.2 * panelWidth).toInt(), PREFFERED_PANEL_HEIGHT)
}
private fun addAttributes(attributes: List<SimpleColoredComponent>, panel: JPanel, panelWidth: Int) {
attributes.forEach {
val attributePanel = JPanel(FlowLayout(FlowLayout.LEFT))
attributePanel.add(it)
attributePanel.preferredSize = Dimension(
(PREFFERED_ATTRIBUTE_WIDTH * panelWidth).toInt(),
PREFFERED_PANEL_HEIGHT + OFFSET
)
attributePanel.isOpaque = false
panel.add(attributePanel)
}
// added space to be equal with the max number of attributes
if (attributes.size < maxAttributes) {
val attributePanel = JPanel(FlowLayout(FlowLayout.LEFT))
attributePanel.add(SimpleColoredComponent())
attributePanel.preferredSize = Dimension(
((maxAttributes - attributes.size) *
PREFFERED_ATTRIBUTE_WIDTH * panelWidth).toInt(), PREFFERED_PANEL_HEIGHT + OFFSET
)
attributePanel.isOpaque = false
panel.add(attributePanel)
}
}
private fun addType(type: SimpleColoredComponent, panel: JPanel, panelWidth: Int) {
val typePanel = JPanel(FlowLayout(FlowLayout.LEFT))
typePanel.add(type)
typePanel.preferredSize = Dimension(
(PREFFERED_DATE_TYPE_WIDTH * panelWidth).toInt(),
PREFFERED_PANEL_HEIGHT + OFFSET
)
typePanel.isOpaque = false
panel.add(typePanel)
}
private fun addComment(panel: JPanel, panelWidth: Int) {
val minIssueIdWidth = (PREFFERED_ISSUE_ID_WIDTH * panelWidth).toInt()
val unitWidth = PREFFERED_ISSUE_ID_WIDTH * panelWidth / 6
val trackingCommentsPanel = JPanel(FlowLayout(FlowLayout.LEFT))
trackingCommentsPanel.add(trackingComments)
val commentsWidth = (PREFFERED_COMMENT_WIDTH * panelWidth).toInt() +
minIssueIdWidth - (unitWidth * maxIssueIdWidth).toInt()
trackingCommentsPanel.preferredSize = Dimension(
min(
commentsWidth,
(PREFFERED_COMMENT_WIDTH * panelWidth).toInt()
), PREFFERED_PANEL_HEIGHT + OFFSET
)
trackingCommentsPanel.isOpaque = false
panel.add(trackingCommentsPanel)
}
}
| apache-2.0 | c7230c5e0671f07aae0ffde04c44b5ca | 35.180672 | 109 | 0.662641 | 4.592533 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mixin/inspection/MixinAnnotationAttributeInspection.kt | 1 | 1681 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.inspection
import com.demonwav.mcdev.util.annotationFromNameValuePair
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.JavaElementVisitor
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiAnnotationMemberValue
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiNameValuePair
abstract class MixinAnnotationAttributeInspection(
private val annotation: String?,
private val attribute: String?
) : MixinInspection() {
constructor(attribute: String?) : this(null, attribute)
protected abstract fun visitAnnotationAttribute(
annotation: PsiAnnotation,
value: PsiAnnotationMemberValue,
holder: ProblemsHolder
)
final override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder)
private inner class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() {
override fun visitNameValuePair(pair: PsiNameValuePair) {
if (
pair.name != attribute &&
(attribute != null || pair.name != PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME)
) {
return
}
val psiAnnotation = pair.annotationFromNameValuePair ?: return
if (annotation != null && !psiAnnotation.hasQualifiedName(annotation)) {
return
}
val value = pair.value ?: return
visitAnnotationAttribute(psiAnnotation, value, this.holder)
}
}
}
| mit | f83400109a779d7a9b9b82b6f5be0eda | 29.017857 | 96 | 0.688281 | 5.188272 | false | false | false | false |
qikh/kong-lang | src/main/kotlin/antlr/Main.kt | 1 | 898 | package antlr
import org.antlr.v4.runtime.ANTLRInputStream
import org.antlr.v4.runtime.CommonTokenStream
import java.util.*
fun main(args: Array<String>) {
try {
val input = "def add(a,b) = a + b \n" +
"let c = add(10,15) \n" +
"println(c)"
val lexer = KongLexer(ANTLRInputStream(input))
val parser = KongParser(CommonTokenStream(lexer))
parser.buildParseTree = true
val tree = parser.prog()
val scope = Scope()
val functions = HashMap<String, Function>()
val symbolVisitor = SymbolVisitor(functions)
symbolVisitor.visit(tree)
val visitor = EvalVisitor(scope, functions)
visitor.visit(tree)
} catch (e: Exception) {
if (e.message != null) {
System.err.println(e.message)
} else {
e.printStackTrace()
}
}
}
| apache-2.0 | c43f591764321498b4e097a94dde153e | 27.967742 | 57 | 0.577951 | 3.821277 | false | false | false | false |
cy6erGn0m/klaxon | src/main/kotlin/com/beust/klaxon/Lexer.kt | 2 | 5408 | package com.beust.klaxon
import java.util.regex.Pattern
import java.io.InputStream
public enum class Type {
VALUE,
LEFT_BRACE,
RIGHT_BRACE,
LEFT_BRACKET,
RIGHT_BRACKET,
COMMA,
COLON,
EOF
}
class Token(val tokenType: Type, val value: Any?) {
override fun toString() : String {
val v = if (value != null) { " (" + value + ")" } else {""}
val result = tokenType.toString() + v
return result
}
}
public class Lexer(val inputStream : InputStream) {
val bytes = inputStream.readBytes()
val EOF = Token(Type.EOF, null)
var index = 0
val NUMERIC = Pattern.compile("[-]?[0-9]+")
val DOUBLE = Pattern.compile(NUMERIC.toString() + "((\\.[0-9]+)?([eE][-+]?[0-9]+)?)")
fun isSpace(c: Char): Boolean {
return c == ' ' || c == '\r' || c == '\n' || c == '\t'
}
private fun nextChar() : Char {
return bytes[index++].toChar()
}
private fun peekChar() : Char {
return bytes[index].toChar()
}
private fun isDone() : Boolean {
return index >= bytes.size
}
val BOOLEAN_LETTERS = "falsetrue".toSet()
private fun isBooleanLetter(c: Char) : Boolean {
return BOOLEAN_LETTERS.contains(Character.toLowerCase(c))
}
val NULL_LETTERS = "null".toSet()
fun isValueLetter(c: Char) : Boolean {
return c == '-' || c == '+' || c == '.' || c.isDigit() || isBooleanLetter(c)
|| c in NULL_LETTERS
}
fun nextToken() : Token {
if (isDone()) {
return EOF
}
var tokenType: Type
var c = nextChar()
val currentValue = StringBuilder()
var jsonValue: Any? = null
while (! isDone() && isSpace(c)) {
c = nextChar()
}
if ('"' == c) {
tokenType = Type.VALUE
loop@
do {
if (isDone()) {
throw RuntimeException("Unterminated string")
}
c = nextChar()
when (c) {
'\\' -> {
if (isDone()) {
throw RuntimeException("Unterminated string")
}
c = nextChar()
when (c) {
'\\' -> currentValue.append("\\")
'/' -> currentValue.append("/")
'b' -> currentValue.append("\b")
'f' -> currentValue.append("\u000c")
'n' -> currentValue.append("\n")
'r' -> currentValue.append("\r")
't' -> currentValue.append("\t")
'u' -> {
val unicodeChar = StringBuilder(4)
.append(nextChar())
.append(nextChar())
.append(nextChar())
.append(nextChar())
val intValue = java.lang.Integer.parseInt(unicodeChar.toString(), 16);
currentValue.append(intValue.toChar())
}
else -> currentValue.append(c)
}
}
'"' -> break@loop
else -> currentValue.append(c)
}
} while (true)
jsonValue = currentValue.toString()
} else if ('{' == c) {
tokenType = Type.LEFT_BRACE
} else if ('}' == c) {
tokenType = Type.RIGHT_BRACE
} else if ('[' == c) {
tokenType = Type.LEFT_BRACKET
} else if (']' == c) {
tokenType = Type.RIGHT_BRACKET
} else if (':' == c) {
tokenType = Type.COLON
} else if (',' == c) {
tokenType = Type.COMMA
} else if (! isDone()) {
while (isValueLetter(c)) {
currentValue.append(c)
if (! isValueLetter(peekChar())) {
break;
} else {
c = nextChar()
}
}
val v = currentValue.toString()
if (NUMERIC.matcher(v).matches()) {
try {
jsonValue = java.lang.Integer.parseInt(v);
} catch (e: NumberFormatException){
try {
jsonValue = java.lang.Long.parseLong(v)
} catch(e: NumberFormatException) {
jsonValue = java.math.BigInteger(v)
}
}
} else if (DOUBLE.matcher(v).matches()) {
jsonValue = java.lang.Double.parseDouble(v)
} else if ("true".equals(v.toLowerCase())) {
jsonValue = true
} else if ("false".equals(v.toLowerCase())) {
jsonValue = false
} else if (v == "null") {
jsonValue = null
} else {
throw RuntimeException("Unexpected character at position ${index}"
+ ": '${c} (${c.toInt()})'")
}
tokenType = Type.VALUE
} else {
tokenType = Type.EOF
}
return Token(tokenType, jsonValue)
}
}
| apache-2.0 | cf613a965dc4346ab65e975af378e635 | 30.625731 | 102 | 0.421967 | 4.943327 | false | false | false | false |
ligee/kotlin-jupyter | build-plugin/src/build/util/versionCatalog.kt | 1 | 2379 | package build.util
import org.gradle.api.Project
import org.gradle.api.artifacts.MinimalExternalModuleDependency
import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.api.provider.Provider
import org.gradle.kotlin.dsl.getByType
private const val DEFAULT_VERSION_CATALOG = "libs"
private const val VERSION_CATALOG_EXTENSION_PREFIX = "versionCatalogExtFor"
@Suppress("UnstableApiUsage")
class NamedVersionCatalogsExtension(
private val project: Project,
private val catalogName: String,
) {
private val catalog = run {
val catalogs = project.extensions.getByType<VersionCatalogsExtension>()
catalogs.named(catalogName)
}
val versions = Versions()
inner class Versions {
fun get(ref: String): String {
return catalog.findVersion(ref).get().requiredVersion
}
fun getOrNull(ref: String): String? {
return catalog.findVersion(ref).getOrNull()?.requiredVersion
}
}
val dependencies = Dependencies()
inner class Dependencies {
fun get(name: String): Provider<MinimalExternalModuleDependency> {
return catalog.findDependency(name).get()
}
}
}
private fun versionCatalogExtensionName(name: String) = VERSION_CATALOG_EXTENSION_PREFIX + name.capitalize()
fun Project.versionCatalog(name: String): NamedVersionCatalogsExtension = extensions.getOrCreate(versionCatalogExtensionName(name)) { NamedVersionCatalogsExtension(this, name) }
val Project.defaultVersionCatalog get(): NamedVersionCatalogsExtension = versionCatalog(DEFAULT_VERSION_CATALOG)
val NamedVersionCatalogsExtension.Versions.devKotlin get() = get("kotlin")
val NamedVersionCatalogsExtension.Versions.stableKotlin get() = get("stableKotlin")
val NamedVersionCatalogsExtension.Versions.gradleKotlin get() = get("gradleKotlin")
val NamedVersionCatalogsExtension.Versions.ktlint get() = get("ktlint")
val NamedVersionCatalogsExtension.Versions.jvmTarget get() = get("jvmTarget")
val NamedVersionCatalogsExtension.Dependencies.junitApi get() = get("test.junit.api")
val NamedVersionCatalogsExtension.Dependencies.junitEngine get() = get("test.junit.engine")
val NamedVersionCatalogsExtension.Dependencies.kotlinTest get() = get("kotlin.stable.test")
val NamedVersionCatalogsExtension.Dependencies.kotlintestAssertions get() = get("test.kotlintest.assertions")
| apache-2.0 | 1e39125d2d8e7093084ad744949eb21f | 41.482143 | 177 | 0.770492 | 4.777108 | false | true | false | false |
caot/intellij-community | platform/configuration-store-impl/src/XmlElementStorage.kt | 2 | 10803 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.TrackingPathMacroSubstitutor
import com.intellij.openapi.components.impl.stores.*
import com.intellij.openapi.util.JDOMUtil
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.SmartHashSet
import gnu.trove.THashMap
import org.jdom.Attribute
import org.jdom.Element
import java.io.IOException
abstract class XmlElementStorage protected constructor(protected val fileSpec: String,
protected val rootElementName: String,
protected val pathMacroSubstitutor: TrackingPathMacroSubstitutor?,
roamingType: RoamingType?,
provider: StreamProvider?) : StateStorageBase<StateMap>() {
protected val roamingType: RoamingType = roamingType ?: RoamingType.PER_USER
private val provider: StreamProvider? = if (provider == null || roamingType == RoamingType.DISABLED || !provider.isApplicable(fileSpec, this.roamingType)) null else provider
protected abstract fun loadLocalData(): Element?
override fun getStateAndArchive(storageData: StateMap, component: Any, componentName: String) = storageData.getStateAndArchive(componentName)
override fun hasState(storageData: StateMap, componentName: String) = storageData.hasState(componentName)
override fun loadData(): StateMap {
val element: Element?
// we don't use local data if has stream provider
if (provider != null && provider.enabled) {
try {
element = loadDataFromProvider()
dataLoadedFromProvider(element)
}
catch (e: Exception) {
LOG.error(e)
element = null
}
}
else {
element = loadLocalData()
}
return if (element == null) StateMap.EMPTY else loadState(element)
}
protected open fun dataLoadedFromProvider(element: Element?) {
}
private fun loadDataFromProvider() = JDOMUtil.load(provider!!.loadContent(fileSpec, roamingType))
private fun loadState(element: Element): StateMap {
beforeElementLoaded(element)
return StateMap.fromMap(FileStorageCoreUtil.load(element, pathMacroSubstitutor, true))
}
fun setDefaultState(element: Element) {
element.setName(rootElementName)
storageDataRef.set(loadState(element))
}
override fun startExternalization() = if (checkIsSavingDisabled()) null else createSaveSession(getStorageData())
protected abstract fun createSaveSession(states: StateMap): StateStorage.ExternalizationSession
override fun analyzeExternalChangesAndUpdateIfNeed(componentNames: MutableSet<String>) {
val oldData = storageDataRef.get()
val newData = getStorageData(true)
if (oldData == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("analyzeExternalChangesAndUpdateIfNeed: old data null, load new for ${toString()}")
}
componentNames.addAll(newData.keys())
}
else {
val changedComponentNames = oldData.getChangedComponentNames(newData)
if (LOG.isDebugEnabled()) {
LOG.debug("analyzeExternalChangesAndUpdateIfNeed: changedComponentNames $changedComponentNames for ${toString()}")
}
if (!ContainerUtil.isEmpty(changedComponentNames)) {
componentNames.addAll(changedComponentNames)
}
}
}
private fun setStates(oldStorageData: StateMap, newStorageData: StateMap?) {
if (oldStorageData !== newStorageData && storageDataRef.getAndSet(newStorageData) !== oldStorageData) {
LOG.warn("Old storage data is not equal to current, new storage data was set anyway")
}
}
abstract class XmlElementStorageSaveSession<T : XmlElementStorage>(private val originalStates: StateMap, protected val storage: T) : SaveSessionBase() {
private var copiedStates: MutableMap<String, Any>? = null
private val newLiveStates = THashMap<String, Element>()
override fun createSaveSession() = if (storage.checkIsSavingDisabled() || copiedStates == null) null else this
override fun setSerializedState(component: Any, componentName: String, element: Element?) {
if (copiedStates == null) {
copiedStates = setStateAndCloneIfNeed(componentName, element, originalStates, newLiveStates)
}
else {
updateState(copiedStates!!, componentName, element, newLiveStates)
}
}
override fun save() {
val stateMap = StateMap.fromMap(copiedStates!!)
var element = save(stateMap, newLiveStates, storage.rootElementName)
if (element == null || JDOMUtil.isEmpty(element)) {
element = null
}
else {
storage.beforeElementSaved(element)
}
val provider = storage.provider
if (provider != null && provider.enabled) {
if (element == null) {
provider.delete(storage.fileSpec, storage.roamingType)
}
else {
// we should use standard line-separator (\n) - stream provider can share file content on any OS
val content = StorageUtil.writeToBytes(element, "\n")
provider.saveContent(storage.fileSpec, content.getInternalBuffer(), content.size(), storage.roamingType)
}
}
else {
saveLocally(element)
}
storage.setStates(originalStates, stateMap)
}
throws(IOException::class)
protected abstract fun saveLocally(element: Element?)
}
protected open fun beforeElementLoaded(element: Element) {
}
protected open fun beforeElementSaved(element: Element) {
if (pathMacroSubstitutor != null) {
try {
pathMacroSubstitutor.collapsePaths(element)
}
finally {
pathMacroSubstitutor.reset()
}
}
}
public fun updatedFromStreamProvider(changedComponentNames: MutableSet<String>, deleted: Boolean) {
if (roamingType == RoamingType.DISABLED) {
// storage roaming was changed to DISABLED, but settings repository has old state
return
}
try {
val newElement = if (deleted) null else loadDataFromProvider()
val states = storageDataRef.get()
if (newElement == null) {
// if data was loaded, mark as changed all loaded components
if (states != null) {
changedComponentNames.addAll(states.keys())
setStates(states, null)
}
}
else if (states != null) {
val newStates = loadState(newElement)
changedComponentNames.addAll(states.getChangedComponentNames(newStates))
setStates(states, newStates)
}
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
private fun save(states: StateMap, newLiveStates: Map<String, Element>, rootElementName: String): Element? {
if (states.isEmpty()) {
return null
}
val rootElement = Element(rootElementName)
for (componentName in states.keys()) {
val element = states.getElement(componentName, newLiveStates)
// name attribute should be first
val elementAttributes = element.getAttributes()
if (elementAttributes.isEmpty()) {
element.setAttribute(FileStorageCoreUtil.NAME, componentName)
}
else {
var nameAttribute: Attribute? = element.getAttribute(FileStorageCoreUtil.NAME)
if (nameAttribute == null) {
nameAttribute = Attribute(FileStorageCoreUtil.NAME, componentName)
elementAttributes.add(0, nameAttribute)
}
else {
nameAttribute.setValue(componentName)
if (elementAttributes.get(0) != nameAttribute) {
elementAttributes.remove(nameAttribute)
elementAttributes.add(0, nameAttribute)
}
}
}
rootElement.addContent(element)
}
return rootElement
}
fun setStateAndCloneIfNeed(componentName: String, newState: Element?, oldStates: StateMap, newLiveStates: MutableMap<String, Element>): MutableMap<String, Any>? {
val oldState = oldStates.get(componentName)
if (newState == null || JDOMUtil.isEmpty(newState)) {
if (oldState == null) {
return null
}
val newStates = oldStates.toMutableMap()
newStates.remove(componentName)
return newStates
}
prepareElement(newState)
newLiveStates.put(componentName, newState)
var newBytes: ByteArray? = null
if (oldState is Element) {
if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) {
return null
}
}
else if (oldState != null) {
newBytes = StateMap.getNewByteIfDiffers(componentName, newState, oldState as ByteArray)
if (newBytes == null) {
return null
}
}
val newStates = oldStates.toMutableMap()
newStates.put(componentName, newBytes ?: newState)
return newStates
}
fun prepareElement(state: Element) {
if (state.getParent() != null) {
LOG.warn("State element must not have parent ${JDOMUtil.writeElement(state)}")
state.detach()
}
state.setName(FileStorageCoreUtil.COMPONENT)
}
private fun updateState(states: MutableMap<String, Any>, componentName: String, newState: Element?, newLiveStates: MutableMap<String, Element>) {
if (newState == null || JDOMUtil.isEmpty(newState)) {
states.remove(componentName)
return
}
prepareElement(newState)
newLiveStates.put(componentName, newState)
val oldState = states.get(componentName)
var newBytes: ByteArray? = null
if (oldState is Element) {
if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) {
return
}
}
else if (oldState != null) {
newBytes = StateMap.getNewByteIfDiffers(componentName, newState, oldState as ByteArray) ?: return
}
states.put(componentName, newBytes ?: newState)
}
// newStorageData - myStates contains only live (unarchived) states
private fun StateMap.getChangedComponentNames(newStates: StateMap): Set<String> {
val bothStates = keys().toMutableSet()
bothStates.retainAll(newStates.keys())
val diffs = SmartHashSet<String>()
diffs.addAll(newStates.keys())
diffs.addAll(keys())
diffs.removeAll(bothStates)
for (componentName in bothStates) {
compare(componentName, newStates, diffs)
}
return diffs
} | apache-2.0 | 48fba509fdcadaa5d6e8ce2bbfe48fa7 | 33.73955 | 175 | 0.695455 | 4.879404 | false | false | false | false |
moallemi/gradle-advanced-build-version | src/main/kotlin/me/moallemi/gradle/advancedbuildversion/gradleextensions/VersionNameConfig.kt | 1 | 2559 | /*
* Copyright 2020 Reza Moallemi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.moallemi.gradle.advancedbuildversion.gradleextensions
import org.gradle.api.GradleException
class VersionNameConfig {
private var versionMajor: Int? = null
private var versionMinor: Int? = null
private var versionPatch: Int? = null
private var versionBuild: Int? = null
val versionName: String
get() {
val patch = getPatchVersion()
val minor = getMinorVersion()
val build = getBuildVersion()
val major = getMajorVersion()
return major + minor + patch + build
}
fun versionMajor(major: Int) {
versionMajor = major
}
fun versionMinor(minor: Int) {
versionMinor = minor
}
fun versionPatch(patch: Int) {
versionPatch = patch
}
fun versionBuild(build: Int) {
versionBuild = build
}
private fun getMajorVersion() =
versionMajor
?.takeUnless { it < 0 }
?.toString()
?: throw GradleException("nameOptions.versionMajor could not be null or less than 0")
private fun getBuildVersion() =
versionBuild?.let {
it.takeUnless {
it < 0
}?.let {
".$versionBuild"
} ?: throw GradleException("nameOptions.versionBuild could not be less than 0")
} ?: ""
private fun getMinorVersion() =
versionMinor?.let {
it.takeUnless {
it < 0
}?.let {
".$versionMinor"
} ?: throw GradleException("nameOptions.versionMinor could not be less than 0")
} ?: ".0"
private fun getPatchVersion() =
versionPatch?.let {
it.takeUnless {
it < 0
}?.let {
".$versionPatch"
} ?: throw GradleException("nameOptions.versionPatch could not be less than 0")
} ?: versionBuild?.let {
".0"
} ?: ""
}
| apache-2.0 | 38396589836b4b52ae02704c6366ef90 | 28.413793 | 97 | 0.590465 | 4.644283 | false | false | false | false |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/view/ImageSelectAdapter.kt | 1 | 2781 | package de.westnordost.streetcomplete.view
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import de.westnordost.streetcomplete.R
/** Select a number of items from a list of items */
class ImageSelectAdapter<T>(private val maxSelectableIndices: Int = -1) :
RecyclerView.Adapter<ItemViewHolder>() {
var items = listOf<Item<T>>()
set(value) {
field = value
notifyDataSetChanged()
}
private val _selectedIndices = mutableSetOf<Int>()
val selectedIndices get() = _selectedIndices.toList()
var cellLayoutId = R.layout.cell_labeled_image_select
val listeners = mutableListOf<ImageSelectAdapter.OnItemSelectionListener>()
val selectedItems get() = _selectedIndices.map { i -> items[i].value!! }
interface OnItemSelectionListener {
fun onIndexSelected(index: Int)
fun onIndexDeselected(index: Int)
}
fun select(indices: List<Int>) {
for (index in indices) {
select(index)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
val view = LayoutInflater.from(parent.context).inflate(cellLayoutId, parent, false)
val holder = ItemViewHolder(view)
holder.onClickListener = ::toggle
return holder
}
fun isSelected(index: Int) = _selectedIndices.contains(index)
fun select(index: Int) {
checkIndexRange(index)
// special case: toggle-behavior if only one index can be selected
if (maxSelectableIndices == 1 && _selectedIndices.size == 1) {
deselect(_selectedIndices.first())
} else if (maxSelectableIndices > -1 && maxSelectableIndices <= _selectedIndices.size) {
return
}
if (!_selectedIndices.add(index)) return
notifyItemChanged(index)
for (listener in listeners) {
listener.onIndexSelected(index)
}
}
fun deselect(index: Int) {
checkIndexRange(index)
if (!_selectedIndices.remove(index)) return
notifyItemChanged(index)
for (listener in listeners) {
listener.onIndexDeselected(index)
}
}
fun toggle(index: Int) {
checkIndexRange(index)
if (!isSelected(index)) {
select(index)
} else {
deselect(index)
}
}
private fun checkIndexRange(index: Int) {
if (index < 0 || index >= items.size)
throw ArrayIndexOutOfBoundsException(index)
}
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
holder.bind(items[position])
holder.isSelected = isSelected(position)
}
override fun getItemCount() = items.size
}
| gpl-3.0 | ebda2876534b708fc6662b2bfbe58559 | 28.273684 | 96 | 0.644732 | 4.681818 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/base/App.kt | 1 | 4439 | package org.stepic.droid.base
import android.content.Context
import android.os.Build
import android.webkit.WebView
import androidx.appcompat.app.AppCompatDelegate
import androidx.multidex.MultiDexApplication
import com.facebook.appevents.AppEventsLogger
import com.google.android.gms.security.ProviderInstaller
import com.squareup.leakcanary.LeakCanary
import com.squareup.leakcanary.RefWatcher
import com.vk.api.sdk.VK
import com.yandex.metrica.YandexMetrica
import com.yandex.metrica.YandexMetricaConfig
import io.branch.referral.Branch
import org.stepic.droid.BuildConfig
import org.stepic.droid.R
import org.stepic.droid.analytic.experiments.SplitTestsHolder
import org.stepic.droid.code.highlight.ParserContainer
import org.stepic.droid.core.ComponentManager
import org.stepic.droid.core.ComponentManagerImpl
import org.stepic.droid.di.AppCoreComponent
import org.stepic.droid.di.DaggerAppCoreComponent
import org.stepic.droid.di.storage.DaggerStorageComponent
import org.stepic.droid.persistence.downloads.DownloadsSyncronizer
import org.stepic.droid.preferences.SharedPreferenceHelper
import org.stepic.droid.util.DebugToolsHelper
import org.stepic.droid.util.NotificationChannelInitializer
import org.stepik.android.domain.view_assignment.service.DeferrableViewAssignmentReportServiceContainer
import ru.nobird.android.view.base.ui.extension.isMainProcess
import timber.log.Timber
import javax.inject.Inject
import javax.net.ssl.SSLContext
class App : MultiDexApplication() {
companion object {
lateinit var application: App
lateinit var refWatcher: RefWatcher
private set
fun component(): AppCoreComponent =
application.component
fun getAppContext(): Context =
application.applicationContext
fun componentManager(): ComponentManager =
application.componentManager
}
private lateinit var component: AppCoreComponent
private lateinit var componentManager: ComponentManager
@Inject
internal lateinit var downloadsSyncronizer: DownloadsSyncronizer
/**
* Init split tests on app start
*/
@Inject
internal lateinit var splitTestsHolder: SplitTestsHolder
/**
* Init step view publisher service on startup
*/
@Inject
internal lateinit var stepDeferrableViewReportService: DeferrableViewAssignmentReportServiceContainer
//don't use this field, it is just for init ASAP in background thread
@Inject
internal lateinit var codeParserContainer: ParserContainer
@Inject
internal lateinit var sharedPreferenceHelper: SharedPreferenceHelper
override fun onCreate() {
super.onCreate()
if (!isMainProcess) return
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return
}
refWatcher = LeakCanary.install(this)
setTheme(R.style.AppTheme)
init()
}
private fun init() {
application = this
DebugToolsHelper.initDebugTools(this)
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
WebView.setDataDirectorySuffix("web")
}
WebView.setWebContentsDebuggingEnabled(true)
}
AppEventsLogger.activateApp(this)
VK.initialize(this)
// init AppMetrica SDK
YandexMetrica.activate(applicationContext, YandexMetricaConfig.newConfigBuilder("fd479031-bdf4-419e-8d8f-6895aab23502").build())
YandexMetrica.enableActivityAutoTracking(this)
component = DaggerAppCoreComponent.builder()
.context(application)
.setStorageComponent(DaggerStorageComponent
.builder()
.context(application)
.build())
.build()
component.inject(this)
componentManager = ComponentManagerImpl(component)
Branch.getAutoInstance(this)
initChannels()
initNightMode()
}
private fun initChannels() {
NotificationChannelInitializer.initNotificationChannels(this)
}
private fun initNightMode() {
AppCompatDelegate.setDefaultNightMode(sharedPreferenceHelper.nightMode)
}
}
| apache-2.0 | 77dd32ee8323a675e7ebc39fd0873e6c | 30.935252 | 136 | 0.717279 | 4.867325 | false | false | false | false |
WangDaYeeeeee/GeometricWeather | app/src/main/java/wangdaye/com/geometricweather/common/ui/widgets/Material3Widgets.kt | 1 | 3264 | package wangdaye.com.geometricweather.common.ui.widgets
import android.content.Context
import androidx.compose.animation.rememberSplineBasedDecay
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import wangdaye.com.geometricweather.R
import kotlin.math.ln
// helper.
@Composable
fun getWidgetSurfaceColor(elevation: Dp): Color {
val surface = MaterialTheme.colorScheme.surface
if (elevation == 0.dp) {
return surface
}
return MaterialTheme
.colorScheme
.surfaceTint
.copy(alpha = ((4.5f * ln(elevation.value + 1)) + 2f) / 100f)
.compositeOver(surface)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun generateCollapsedScrollBehavior(): TopAppBarScrollBehavior {
val decayAnimationSpec = rememberSplineBasedDecay<Float>()
return remember(decayAnimationSpec) {
TopAppBarDefaults.exitUntilCollapsedScrollBehavior(decayAnimationSpec)
}
}
// scaffold.
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Material3Scaffold(
modifier: Modifier = Modifier,
topBar: @Composable () -> Unit = {},
bottomBar: @Composable () -> Unit = {},
snackbarHost: @Composable () -> Unit = {},
floatingActionButton: @Composable () -> Unit = {},
floatingActionButtonPosition: FabPosition = FabPosition.End,
containerColor: Color = MaterialTheme.colorScheme.surface,
contentColor: Color = MaterialTheme.colorScheme.onSurface,
content: @Composable (PaddingValues) -> Unit
) {
Scaffold(
modifier = modifier,
topBar = topBar,
bottomBar = bottomBar,
snackbarHost = snackbarHost,
floatingActionButton = floatingActionButton,
floatingActionButtonPosition = floatingActionButtonPosition,
containerColor = containerColor,
contentColor = contentColor,
content = content,
)
}
// list items.
val defaultCardListItemElevation = 2.dp
fun getCardListItemMarginDp(context: Context) = context
.resources
.getDimension(R.dimen.little_margin)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Material3CardListItem(
elevation: Dp = defaultCardListItemElevation,
content: @Composable ColumnScope.() -> Unit,
) = Card(
modifier = Modifier
.padding(
start = dimensionResource(R.dimen.little_margin),
end = dimensionResource(R.dimen.little_margin),
top = dimensionResource(R.dimen.little_margin),
bottom = 0.dp
),
shape = RoundedCornerShape(
size = dimensionResource(R.dimen.material3_card_list_item_corner_radius)
),
containerColor = getWidgetSurfaceColor(elevation),
contentColor = MaterialTheme.colorScheme.onSurface,
content = content
) | lgpl-3.0 | b7e2c5e6f5102904b1c5febc19c647d9 | 31.009804 | 80 | 0.734069 | 4.629787 | false | false | false | false |
Tait4198/hi_pixiv | app/src/main/java/info/hzvtc/hipixiv/vm/fragment/UserViewModel.kt | 1 | 8306 | package info.hzvtc.hipixiv.vm.fragment
import android.content.Intent
import android.support.design.widget.Snackbar
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import com.google.gson.Gson
import com.like.LikeButton
import info.hzvtc.hipixiv.R
import info.hzvtc.hipixiv.adapter.events.ItemLike
import info.hzvtc.hipixiv.adapter.events.OnScrollListener
import info.hzvtc.hipixiv.adapter.UserAdapter
import info.hzvtc.hipixiv.adapter.events.ItemClick
import info.hzvtc.hipixiv.adapter.events.UserClick
import info.hzvtc.hipixiv.data.Account
import info.hzvtc.hipixiv.databinding.FragmentListBinding
import info.hzvtc.hipixiv.net.ApiService
import info.hzvtc.hipixiv.pojo.illust.Illust
import info.hzvtc.hipixiv.pojo.user.UserResponse
import info.hzvtc.hipixiv.util.AppMessage
import info.hzvtc.hipixiv.util.AppUtil
import info.hzvtc.hipixiv.view.fragment.BaseFragment
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.net.SocketTimeoutException
import javax.inject.Inject
class UserViewModel @Inject constructor(val apiService : ApiService,val gson: Gson) :
BaseFragmentViewModel<BaseFragment<FragmentListBinding>, FragmentListBinding>(),ViewModelData<UserResponse> {
var obsNewData : Observable<UserResponse>? = null
lateinit var account: Account
private var allowLoadMore = true
private var errorIndex = 0
private lateinit var adapter : UserAdapter
override fun runView() {
getData(obsNewData)
}
override fun initViewModel() {
adapter = UserAdapter(getContext())
adapter.setPreviewClick(object : ItemClick{
override fun itemClick(illust: Illust) {
val intent = Intent(getString(R.string.activity_content))
intent.putExtra(getString(R.string.extra_json),gson.toJson(illust))
intent.putExtra(getString(R.string.extra_type),getString(R.string.extra_type_illust))
ActivityCompat.startActivity(getContext(), intent, null)
}
})
adapter.setUserFollow(userFollow = object : ItemLike {
override fun like(id: Int, itemIndex: Int, isRank: Boolean, likeButton: LikeButton) {
postFollowOrUnfollow(id,itemIndex,true,likeButton)
}
override fun unlike(id: Int, itemIndex: Int, isRank: Boolean, likeButton: LikeButton) {
postFollowOrUnfollow(id,itemIndex,false,likeButton)
}
})
adapter.setUserClick(object : UserClick{
override fun click(userId: Int) {
val intent = Intent(mView.getString(R.string.activity_content))
intent.putExtra(getString(R.string.extra_type),mView.getString(R.string.extra_type_user))
intent.putExtra(getString(R.string.extra_int),userId)
ActivityCompat.startActivity(mView.context, intent, null)
}
})
mBind.recyclerView.layoutManager = GridLayoutManager(getContext(),1)
mBind.srLayout.setColorSchemeColors(ContextCompat.getColor(getContext(), R.color.primary))
mBind.srLayout.setOnRefreshListener({ getData(obsNewData) })
mBind.recyclerView.addOnScrollListener(object : OnScrollListener() {
override fun onBottom() {
if(allowLoadMore){
getMoreData()
}
}
override fun scrollUp(dy: Int) {
getParent()?.showFab(false)
}
override fun scrollDown(dy: Int) {
getParent()?.showFab(true)
}
})
mBind.recyclerView.adapter = adapter
}
override fun getData(obs: Observable<UserResponse>?) {
if(obs != null){
Observable.just(obs)
.doOnNext({ errorIndex = 0 })
.doOnNext({ if(obs != obsNewData) obsNewData = obs })
.doOnNext({ mBind.srLayout.isRefreshing = true })
.observeOn(Schedulers.io())
.flatMap({ observable -> observable })
.doOnNext({ userResponse -> adapter.setNewData(userResponse) })
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
_ -> adapter.updateUI(true)
},{
error ->
mBind.srLayout.isRefreshing = false
adapter.loadError()
processError(error)
},{
mBind.srLayout.isRefreshing = false
})
}
}
override fun getMoreData() {
Observable.just(adapter.nextUrl?:"")
.doOnNext({ errorIndex = 1 })
.doOnNext({ allowLoadMore = false })
.filter({ url -> !url.isNullOrEmpty() })
.observeOn(AndroidSchedulers.mainThread())
.doOnNext({ adapter.setProgress(true) })
.observeOn(Schedulers.io())
.flatMap({ account.obsToken(getContext()) })
.flatMap({ token -> apiService.getUserNext(token,adapter.nextUrl?:"")})
.doOnNext({ userResponse -> adapter.addMoreData(userResponse) })
.observeOn(AndroidSchedulers.mainThread())
.doOnNext({ (userPreviews) ->
if (userPreviews.size == 0){
AppMessage.toastMessageLong(getString(R.string.no_more_data), getContext())
}
})
.doOnNext({ userResponse ->
if(userResponse.nextUrl.isNullOrEmpty()){
AppMessage.toastMessageLong(getString(R.string.is_last_data), getContext())
}
})
.subscribe({
_ ->
adapter.setProgress(false)
adapter.updateUI(false)
},{
error->
adapter.setProgress(false)
allowLoadMore = true
processError(error)
},{
allowLoadMore = true
})
}
private fun postFollowOrUnfollow(userId : Int,position : Int,isLike : Boolean,likeButton: LikeButton){
account.obsToken(getContext())
.filter({ AppUtil.isNetworkConnected(getContext()) })
.flatMap({
token ->
if(isLike){
return@flatMap apiService.postFollowUser(token,userId,"public")
}else{
return@flatMap apiService.postUnfollowUser(token,userId)
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
adapter.updateFollowed(position,isLike)
},{
error -> processError(error)
adapter.updateFollowed(position,false)
likeButton.isLiked = false
},{
if(!AppUtil.isNetworkConnected(getContext())){
adapter.updateFollowed(position,false)
likeButton.isLiked = false
}
})
}
private fun processError(error : Throwable){
Log.e("Error",error.printStackTrace().toString())
if(AppUtil.isNetworkConnected(getContext())){
val msg = if(error is SocketTimeoutException)
getString(R.string.load_data_timeout)
else
getString(R.string.load_data_failed)
Snackbar.make(getParent()?.getRootView()?:mBind.root.rootView, msg, Snackbar.LENGTH_LONG)
.setAction(getString(R.string.app_dialog_ok),{
if(errorIndex == 0){
getData(obsNewData)
}else if(errorIndex == 1){
getMoreData()
}
}).show()
}
}
} | mit | 06721f3367db5827bfc3b261f828ad3f | 40.954545 | 117 | 0.572719 | 5.175078 | false | false | false | false |
googlecodelabs/android-people | app/src/main/java/com/example/android/people/AssetFileProvider.kt | 3 | 2650 | /*
* Copyright (C) 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 com.example.android.people
import android.content.ContentProvider
import android.content.ContentValues
import android.content.res.AssetFileDescriptor
import android.database.Cursor
import android.net.Uri
import android.webkit.MimeTypeMap
import com.example.android.people.data.Contact
class AssetFileProvider : ContentProvider() {
override fun onCreate(): Boolean {
return true
}
override fun getType(uri: Uri): String? {
val segments = uri.pathSegments
return when (segments[0]) {
"icon" -> MimeTypeMap.getSingleton().getMimeTypeFromExtension("jpg")
else -> "application/octet-stream"
}
}
override fun openAssetFile(uri: Uri, mode: String): AssetFileDescriptor? {
val segments = uri.pathSegments
return when (segments[0]) {
"icon" -> {
val id = segments[1].toLong()
Contact.CONTACTS.find { it.id == id }?.let { contact ->
context?.resources?.assets?.openFd(contact.icon)
}
}
"photo" -> {
val filename = segments[1]
context?.resources?.assets?.openFd(filename)
}
else -> null
}
}
override fun query(
uri: Uri,
projection: Array<out String>?,
selection: String?,
selectionArgs: Array<out String>?,
sortOrder: String?
): Cursor? {
throw UnsupportedOperationException("No query")
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
throw UnsupportedOperationException("No insert")
}
override fun update(
uri: Uri,
values: ContentValues?,
selection: String?,
selectionArgs: Array<out String>?
): Int {
throw UnsupportedOperationException("No update")
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
throw UnsupportedOperationException("No delete")
}
}
| apache-2.0 | cec23e9ce1fe4fed03442d8af982d8cb | 30.927711 | 95 | 0.636981 | 4.715302 | false | false | false | false |
I60R/ActivityRx | example/src/main/java/i60r/activityrxexample/TestApplication.kt | 1 | 1553 | package i60r.activityrxexample
import android.app.Application
import android.util.Log
import i60r.activityrx.Activities
import i60r.activityrx.ActivityRx
import i60r.activityrx.On
/***
* Created by 160R on 08.05.17.
*/
class TestApplication : Application() {
override fun onCreate() {
super.onCreate()
ActivityRx.init(this)
Activities.events()
.subscribe {
Log.d("~~~ ~~~ ~>", "${it.id} ~> ${it.on}")
if (it.on == On.RESUME) {
Log.d("==>", "*\n*\n*\n*")
}
}
Activities.observe(Activity1::class.java)
.filter { it.on.visible }
.flatMap {
it.ui.finish()
Activities.start(Activity2::class.java)
.filter { it.on.visible }
}
.flatMap {
it.ui.finish()
Activities.start(Activity3::class.java)
.filter { it.on.visible }
.takeUntil { it.on.visible }
}
.flatMap {
Activities.current()
.subscribe {
Log.d("--- --- ->", "${it.id} -> ${it.on}")
}
Activities.observe(it.ui)
}
.subscribe {
Log.d("=== === =>", "${it.id} => ${it.on.name}")
}
}
}
| mit | 93688dc8888d71e9ba7e2624fea9fb8b | 27.759259 | 75 | 0.395364 | 4.581121 | false | false | false | false |
jainsahab/AndroidSnooper | Snooper/src/main/java/com/prateekj/snooper/networksnooper/activity/HttpCallListActivity.kt | 1 | 4896 | package com.prateekj.snooper.networksnooper.activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View.GONE
import android.view.View.VISIBLE
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.prateekj.snooper.R
import com.prateekj.snooper.customviews.DividerItemDecoration
import com.prateekj.snooper.customviews.NextPageRequestListener
import com.prateekj.snooper.networksnooper.activity.HttpCallActivity.Companion.HTTP_CALL_ID
import com.prateekj.snooper.networksnooper.adapter.HttpCallListAdapter
import com.prateekj.snooper.networksnooper.database.SnooperRepo
import com.prateekj.snooper.networksnooper.model.HttpCallRecord
import com.prateekj.snooper.networksnooper.presenter.HttpCallListPresenter
import com.prateekj.snooper.networksnooper.presenter.HttpCallListPresenter.Companion.PAGE_SIZE
import com.prateekj.snooper.networksnooper.views.HttpListView
import kotlinx.android.synthetic.main.activity_http_call_list.*
class HttpCallListActivity : SnooperBaseActivity(), HttpListView, NextPageRequestListener {
private lateinit var presenter: HttpCallListPresenter
private lateinit var httpCallListAdapter: HttpCallListAdapter
private lateinit var repo: SnooperRepo
private var areAllPagesLoaded: Boolean = false
private var noCallsFound: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_http_call_list)
setSupportActionBar(toolbar)
repo = SnooperRepo(this)
presenter = HttpCallListPresenter(this, repo)
list.layoutManager = LinearLayoutManager(this)
val itemDecoration =
DividerItemDecoration(this, DividerItemDecoration.VERTICAL, R.drawable.grey_divider)
list.addItemDecoration(itemDecoration)
list.itemAnimator = DefaultItemAnimator()
list.setNextPageListener(this)
presenter.init()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.http_call_list_menu, menu)
if (noCallsFound) {
menu.findItem(R.id.delete_records_menu).isVisible = false
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.done_menu -> {
presenter.onDoneClick()
return true
}
R.id.delete_records_menu -> presenter.onDeleteRecordsClicked()
R.id.search -> openSearchActivity()
}
return super.onOptionsItemSelected(item)
}
private fun openSearchActivity() {
startActivity(Intent(this, HttpCallSearchActivity::class.java))
}
override fun navigateToResponseBody(httpCallId: Long) {
val intent = Intent(this, HttpCallActivity::class.java)
intent.putExtra(HTTP_CALL_ID, httpCallId)
startActivity(intent)
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left)
}
override fun finishView() {
finish()
}
override fun showDeleteConfirmationDialog() {
val dialogClickListener = DialogInterface.OnClickListener { dialog, which ->
when (which) {
DialogInterface.BUTTON_POSITIVE -> presenter.confirmDeleteRecords()
DialogInterface.BUTTON_NEGATIVE -> dialog.dismiss()
}
}
val builder = AlertDialog.Builder(this)
builder.setMessage(R.string.delete_records_dialog_text).setPositiveButton(
getString(R.string.delete_records_dialog_confirmation),
dialogClickListener
)
.setNegativeButton(
getString(R.string.delete_records_dialog_cancellation),
dialogClickListener
).show()
}
override fun updateListViewAfterDelete() {
httpCallListAdapter.refreshData(repo.findAllSortByDateAfter(-1, 20))
httpCallListAdapter.notifyDataSetChanged()
}
override fun initHttpCallRecordList(httpCallRecords: List<HttpCallRecord>) {
httpCallListAdapter = HttpCallListAdapter(httpCallRecords.toMutableList(), presenter)
checkIfAllPagesAreLoaded(httpCallRecords)
list.adapter = httpCallListAdapter
}
override fun appendRecordList(httpCallRecords: List<HttpCallRecord>) {
httpCallListAdapter.appendData(httpCallRecords)
checkIfAllPagesAreLoaded(httpCallRecords)
list.post { httpCallListAdapter.notifyDataSetChanged() }
}
override fun renderNoCallsFoundView() {
noCallsFound = true
http_call_list_container.visibility = GONE
no_calls_found_container.visibility = VISIBLE
}
override fun requestNextPage() {
presenter.onNextPageCall()
}
override fun areAllPagesLoaded(): Boolean {
return areAllPagesLoaded
}
private fun checkIfAllPagesAreLoaded(httpCallRecords: List<HttpCallRecord>) {
if (httpCallRecords.size < PAGE_SIZE) {
areAllPagesLoaded = true
}
}
}
| apache-2.0 | 3e9ff36cd8ba8846972dec6b798cd0f9 | 34.223022 | 94 | 0.770221 | 4.588566 | false | false | false | false |
sjnyag/stamp | app/src/main/java/com/sjn/stamp/ui/observer/StampEditStateObserver.kt | 1 | 1861 | package com.sjn.stamp.ui.observer
import com.sjn.stamp.utils.LogHelper
import java.util.*
object StampEditStateObserver {
private val TAG = LogHelper.makeLogTag(StampEditStateObserver::class.java)
private var state = State.NO_EDIT
var selectedStampList: List<String> = ArrayList()
internal set
private val listenerList = Collections.synchronizedList(ArrayList<Listener>())
val isStampMode: Boolean
get() = state == State.EDITING || state == State.STAMPING
enum class State {
EDITING,
NO_EDIT,
STAMPING
}
fun notifyAllStampChange(stamp: String) {
LogHelper.i(TAG, "notifyAllStampChange ", listenerList!!.size)
for (listener in ArrayList(listenerList)) {
listener.onNewStampCreated(stamp)
}
}
fun notifySelectedStampListChange(stampList: List<String>) {
LogHelper.i(TAG, "notifySelectedStampListChange ", listenerList!!.size)
selectedStampList = stampList
for (listener in ArrayList(listenerList)) {
listener.onSelectedStampChange(selectedStampList)
}
}
fun notifyStateChange(state: State) {
LogHelper.i(TAG, "notifyStateChange ", state)
this.state = state
for (listener in ArrayList(listenerList)) {
listener.onStampStateChange(this.state)
}
}
interface Listener {
fun onSelectedStampChange(selectedStampList: List<String>)
fun onNewStampCreated(stamp: String)
fun onStampStateChange(state: State)
}
fun addListener(listener: Listener) {
if (!listenerList.contains(listener)) {
listenerList.add(listener)
}
}
fun removeListener(listener: Listener) {
if (listenerList.contains(listener)) {
listenerList.remove(listener)
}
}
}
| apache-2.0 | 3c3e488791c5a09f2633458c61965839 | 25.971014 | 82 | 0.651263 | 4.583744 | false | false | false | false |
laminr/aeroknow | app/src/main/java/biz/eventually/atpl/data/db/Question.kt | 1 | 2250 | package biz.eventually.atpl.data.db
import android.arch.persistence.room.*
import android.os.Parcel
import android.os.Parcelable
/**
* Created by Thibault de Lambilly on 20/03/17.
*
*/
@Entity(
tableName = "question",
indices = [Index(value = ["topic_id"], name = "idx_question_topic_id")],
foreignKeys = [ForeignKey(
entity = Topic::class,
parentColumns = ["idWeb"],
childColumns = ["topic_id"],
onUpdate = ForeignKey.CASCADE,
onDelete = ForeignKey.CASCADE
)]
)
class Question(@PrimaryKey
var idWeb: Long,
@ColumnInfo(name = "topic_id")
var topicId: Long,
var label: String,
var img: String = "",
var focus: Boolean? = null,
var good: Int = 0,
var wrong: Int = 0
) : Comparable<Question>, Parcelable {
@Ignore
val imgList: List<String> = explodeImgRaw(img)
@Ignore
var answers: List<Answer> = listOf()
override fun compareTo(other: Question) = compareValuesBy(this, other, { it.label })
private fun explodeImgRaw(raw: String?): List<String> = raw?.split("|")?.toList() ?: listOf()
constructor(parcel: Parcel) : this(
parcel.readLong(),
parcel.readLong(),
parcel.readString(),
parcel.readString(),
parcel.readValue(Boolean::class.java.classLoader) as? Boolean,
parcel.readInt(),
parcel.readInt()) {
answers = parcel.createTypedArrayList(Answer)
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeLong(idWeb)
parcel.writeLong(topicId)
parcel.writeString(label)
parcel.writeString(img)
parcel.writeValue(focus)
parcel.writeInt(good)
parcel.writeInt(wrong)
parcel.writeTypedList(answers)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Question> {
override fun createFromParcel(parcel: Parcel): Question = Question(parcel)
override fun newArray(size: Int): Array<Question?> = arrayOfNulls(size)
}
} | mit | 06bae388dac4ff20c12263bb35b6b01b | 28.233766 | 97 | 0.585778 | 4.573171 | false | false | false | false |
pftbest/zoom-example | src/main/java/org/tmpfs/zoomtest/ZoomFrame.kt | 1 | 2482 | package org.tmpfs.zoomtest
import android.content.Context
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.View
import android.widget.FrameLayout
class ZoomFrame @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
FrameLayout(context, attrs, defStyleAttr) {
private val gestureDetector = GestureDetector(context, GestureListener())
private val scaleDetector = ScaleGestureDetector(context, ScaleListener())
private val firstChild: View
get() = getChildAt(0)
override fun onTouchEvent(event: MotionEvent?): Boolean {
var result = scaleDetector.onTouchEvent(event)
if (!scaleDetector.isInProgress) {
result = result or gestureDetector.onTouchEvent(event)
}
return result
}
private inner class GestureListener : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: MotionEvent?): Boolean = true
override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean {
firstChild.translationX -= distanceX
firstChild.translationY -= distanceY
return true
}
}
private inner class ScaleListener : ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
firstChild.setPivotFromParent(detector.focusX, detector.focusY)
return true
}
override fun onScale(detector: ScaleGestureDetector): Boolean {
val factor = detector.scaleFactor
firstChild.scaleX *= factor
firstChild.scaleY *= factor
return true
}
}
}
private fun View.setPivot(pX: Float, pY: Float) {
// calculate the offset that new pivot value would cause
val offsetX = (pX - pivotX) * (1 - scaleX)
val offsetY = (pY - pivotY) * (1 - scaleY)
// move the view
translationX -= offsetX
translationY -= offsetY
// apply the pivot
pivotX = pX
pivotY = pY
}
private fun View.setPivotFromParent(pX: Float, pY: Float) {
// translate pivot point from parent coordinates to child coordinates
val cX = (pX - left + pivotX * (scaleX - 1) - translationX) / scaleX
val cY = (pY - top + pivotY * (scaleY - 1) - translationY) / scaleY
setPivot(cX, cY)
}
| mit | d4661c2396482a609edade42ac24bfe1 | 33.957746 | 113 | 0.680902 | 4.773077 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/renderer/DefaultComponentRenderingStrategy.kt | 1 | 3314 | package org.hexworks.zircon.internal.component.renderer
import org.hexworks.zircon.api.component.Component
import org.hexworks.zircon.api.component.renderer.ComponentDecorationRenderContext
import org.hexworks.zircon.api.component.renderer.ComponentDecorationRenderer
import org.hexworks.zircon.api.component.renderer.ComponentPostProcessor
import org.hexworks.zircon.api.component.renderer.ComponentPostProcessorContext
import org.hexworks.zircon.api.component.renderer.ComponentRenderContext
import org.hexworks.zircon.api.component.renderer.ComponentRenderer
import org.hexworks.zircon.api.component.renderer.ComponentRenderingStrategy
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Rect
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.graphics.TileGraphics
class DefaultComponentRenderingStrategy<T : Component>(
/**
* The [ComponentRenderer] which will be used to render
* the *content* of this [Component].
*/
val componentRenderer: ComponentRenderer<in T>,
/**
* The [ComponentDecorationRenderer]s this [Component] has.
*/
val decorationRenderers: List<ComponentDecorationRenderer> = listOf(),
/**
* The [ComponentPostProcessor]s this [Component] has.
*/
val componentPostProcessors: List<ComponentPostProcessor<T>> = listOf()
) : ComponentRenderingStrategy<T> {
override val contentPosition: Position = decorationRenderers.asSequence()
.map {
it.offset
}.fold(Position.defaultPosition(), Position::plus)
override fun render(component: T, graphics: TileGraphics) {
if (component.isHidden.not()) {
var currentOffset = Position.defaultPosition()
var currentSize = graphics.size
val graphicsCopy = graphics.createCopy()
val componentArea = graphicsCopy.toSubTileGraphics(
Rect.create(
position = decorationRenderers
.map { it.offset }.fold(Position.zero(), Position::plus),
size = graphicsCopy.size - decorationRenderers
.map { it.occupiedSize }.fold(Size.zero(), Size::plus)
)
)
componentRenderer.render(
tileGraphics = componentArea,
context = ComponentRenderContext(component)
)
decorationRenderers.forEach { renderer ->
val bounds = Rect.create(currentOffset, currentSize)
renderer.render(graphicsCopy.toSubTileGraphics(bounds), ComponentDecorationRenderContext(component))
currentOffset += renderer.offset
currentSize -= renderer.occupiedSize
}
componentPostProcessors.forEach { renderer ->
renderer.render(componentArea, ComponentPostProcessorContext(component))
}
graphics.transform { position, _ ->
graphicsCopy.getTileAtOrNull(position) ?: Tile.empty()
}
}
}
override fun calculateContentSize(componentSize: Size): Size = componentSize -
decorationRenderers.asSequence().map {
it.occupiedSize
}.fold(Size.zero(), Size::plus)
}
| apache-2.0 | af594d3ab5fcabef61f7e0feac411d85 | 39.91358 | 116 | 0.674713 | 5.036474 | false | false | false | false |
AcornUI/Acorn | acornui-core/src/main/kotlin/com/acornui/graphic/Scaling.kt | 1 | 3494 | /*
* Copyright 2019 Poly Forest, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui.graphic
import com.acornui.math.*
/**
* Describes the different scaling strategies.
* @author nbilyk
*/
enum class Scaling {
/**
* Scales the source to fit the target while keeping the same aspect ratio. This may cause the source to be smaller
* than the target in one direction.
*/
FIT,
/**
* Scales the source to fill the target while keeping the same aspect ratio. This may cause the source to be larger
* than the target in one direction.
*/
FILL,
/**
* Scales the source to fill the target in the x direction while keeping the same aspect ratio. This may cause the
* source to be smaller or larger than the target in the y direction.
*/
FILL_X,
/**
* Scales the source to fill the target in the y direction while keeping the same aspect ratio. This may cause the
* source to be smaller or larger than the target in the x direction.
*/
FILL_Y,
/**
* Scales the source to fill the target. This may cause the source to not keep the same aspect ratio.
*/
STRETCH,
/**
* Scales the source to fill the target in the x direction, without changing the y direction. This may cause the
* source to not keep the same aspect ratio.
*/
STRETCH_X,
/**
* Scales the source to fill the target in the y direction, without changing the x direction. This may cause the
* source to not keep the same aspect ratio.
*/
STRETCH_Y,
/**
* The source is not scaled.
*/
NONE;
/**
* Applies the scaling strategy to the provided source and target dimensions.
*/
fun apply(
sourceWidth: Double,
sourceHeight: Double,
targetWidth: Double,
targetHeight: Double
): Vector2 {
return when (this) {
FIT -> {
val targetRatio = targetHeight / targetWidth
val sourceRatio = sourceHeight / sourceWidth
val scale = if (targetRatio > sourceRatio) targetWidth / sourceWidth else targetHeight / sourceHeight
vec2(sourceWidth * scale, sourceHeight * scale)
}
FILL -> {
val targetRatio = targetHeight / targetWidth
val sourceRatio = sourceHeight / sourceWidth
val scale = if (targetRatio < sourceRatio) targetWidth / sourceWidth else targetHeight / sourceHeight
vec2(sourceWidth * scale, sourceHeight * scale)
}
FILL_X -> {
val scale = targetWidth / sourceWidth
vec2(sourceWidth * scale, sourceHeight * scale)
}
FILL_Y -> {
val scale = targetHeight / sourceHeight
vec2(sourceWidth * scale, sourceHeight * scale)
}
STRETCH -> {
vec2(targetWidth, targetHeight)
}
STRETCH_X -> {
vec2(targetWidth, sourceHeight)
}
STRETCH_Y -> {
vec2(sourceWidth, targetHeight)
}
NONE -> {
vec2(sourceWidth, sourceHeight)
}
}
}
}
/**
* Applies the scaling strategy to the provided source and target dimensions.
*/
fun Scaling.apply(
source: Vector2,
target: Vector2
): Vector2 = apply(source.x, source.y, target.x, target.y) | apache-2.0 | 2efcc74465c5d34f404c56291e311fb5 | 26.96 | 116 | 0.697768 | 3.886541 | false | false | false | false |
KotlinNLP/SimpleDNN | src/test/kotlin/deeplearning/birnn/utils/BiRNNEncoderUtils.kt | 1 | 3120 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package deeplearning.birnn.utils
import com.kotlinnlp.simplednn.core.functionalities.activations.Tanh
import com.kotlinnlp.simplednn.core.layers.LayerType
import com.kotlinnlp.simplednn.core.layers.models.recurrent.simple.SimpleRecurrentLayerParameters
import com.kotlinnlp.simplednn.deeplearning.birnn.BiRNN
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
/**
*
*/
object BiRNNEncoderUtils {
/**
*
*/
fun buildInputSequence(): List<DenseNDArray> = listOf(
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.5, 0.6)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.7, -0.4)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, -0.7))
)
/**
*
*/
fun buildOutputErrorsSequence(): List<DenseNDArray> = listOf(
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.4, -0.8, 0.1, 0.4, 0.6, -0.4)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.6, 0.6, 0.7, 0.7, -0.6, 0.3)),
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.1, -0.1, 0.1, -0.8, 0.4, -0.5))
)
/**
*
*/
fun buildBiRNN(): BiRNN {
val birnn = BiRNN(
inputSize = 2,
inputType = LayerType.Input.Dense,
hiddenSize = 3,
hiddenActivation = Tanh,
recurrentConnectionType = LayerType.Connection.SimpleRecurrent
)
this.initL2RParameters(params = birnn.leftToRightNetwork.paramsPerLayer[0] as SimpleRecurrentLayerParameters)
this.initR2LParameters(params = birnn.rightToLeftNetwork.paramsPerLayer[0] as SimpleRecurrentLayerParameters)
return birnn
}
/**
*
*/
private fun initL2RParameters(params: SimpleRecurrentLayerParameters) {
params.unit.weights.values.assignValues(DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(-0.9, 0.4),
doubleArrayOf(0.7, -1.0),
doubleArrayOf(-0.9, -0.4)
)))
params.unit.biases.values.assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(0.4, -0.3, 0.8)))
params.unit.recurrentWeights.values.assignValues(DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.1, 0.9, -0.5),
doubleArrayOf(-0.6, 0.7, 0.7),
doubleArrayOf(0.3, 0.9, 0.0)
)))
}
/**
*
*/
private fun initR2LParameters(params: SimpleRecurrentLayerParameters) {
params.unit.weights.values.assignValues(DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.3, 0.1),
doubleArrayOf(0.6, 0.0),
doubleArrayOf(-0.7, 0.1)
)))
params.unit.biases.values.assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(0.2, -0.9, -0.2)))
params.unit.recurrentWeights.values.assignValues(DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(-0.2, 0.7, 0.7),
doubleArrayOf(-0.2, 0.0, -1.0),
doubleArrayOf(0.5, -0.4, 0.4)
)))
}
}
| mpl-2.0 | abd635ea19d228ad86416609cc8879d0 | 30.836735 | 113 | 0.688782 | 3.627907 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/notifications/NotificationsListFragment.kt | 1 | 15614 | @file:Suppress("DEPRECATION")
package org.wordpress.android.ui.notifications
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.text.TextUtils
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.text.HtmlCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.appbar.AppBarLayout.LayoutParams
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.google.android.material.tabs.TabLayout.Tab
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.EventBus
import org.wordpress.android.R
import org.wordpress.android.analytics.AnalyticsTracker
import org.wordpress.android.analytics.AnalyticsTracker.NOTIFICATIONS_SELECTED_FILTER
import org.wordpress.android.analytics.AnalyticsTracker.Stat.NOTIFICATION_TAPPED_SEGMENTED_CONTROL
import org.wordpress.android.databinding.NotificationsListFragmentBinding
import org.wordpress.android.fluxc.store.AccountStore
import org.wordpress.android.ui.ActivityLauncher
import org.wordpress.android.ui.JetpackConnectionSource.NOTIFICATIONS
import org.wordpress.android.ui.JetpackConnectionWebViewActivity
import org.wordpress.android.ui.RequestCodes
import org.wordpress.android.ui.ScrollableViewInitializedListener
import org.wordpress.android.ui.WPWebViewActivity
import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureFullScreenOverlayFragment
import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureRemovalOverlayUtil.JetpackFeatureOverlayScreenType
import org.wordpress.android.ui.main.WPMainActivity
import org.wordpress.android.ui.main.WPMainNavigationView.PageType
import org.wordpress.android.ui.mysite.jetpackbadge.JetpackPoweredBottomSheetFragment
import org.wordpress.android.ui.notifications.NotificationEvents.NotificationsUnseenStatus
import org.wordpress.android.ui.notifications.adapters.NotesAdapter.FILTERS
import org.wordpress.android.ui.notifications.adapters.NotesAdapter.FILTERS.FILTER_ALL
import org.wordpress.android.ui.notifications.adapters.NotesAdapter.FILTERS.FILTER_COMMENT
import org.wordpress.android.ui.notifications.adapters.NotesAdapter.FILTERS.FILTER_FOLLOW
import org.wordpress.android.ui.notifications.adapters.NotesAdapter.FILTERS.FILTER_LIKE
import org.wordpress.android.ui.notifications.adapters.NotesAdapter.FILTERS.FILTER_UNREAD
import org.wordpress.android.ui.notifications.services.NotificationsUpdateServiceStarter
import org.wordpress.android.ui.notifications.services.NotificationsUpdateServiceStarter.IS_TAPPED_ON_NOTIFICATION
import org.wordpress.android.ui.stats.StatsConnectJetpackActivity
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T.NOTIFS
import org.wordpress.android.util.JetpackBrandingUtils
import org.wordpress.android.util.JetpackBrandingUtils.Screen
import org.wordpress.android.util.NetworkUtils
import org.wordpress.android.util.WPUrlUtils
import org.wordpress.android.util.extensions.setLiftOnScrollTargetViewIdAndRequestLayout
import org.wordpress.android.viewmodel.observeEvent
import javax.inject.Inject
@AndroidEntryPoint
class NotificationsListFragment : Fragment(R.layout.notifications_list_fragment), ScrollableViewInitializedListener {
@Inject lateinit var accountStore: AccountStore
@Inject lateinit var jetpackBrandingUtils: JetpackBrandingUtils
private val viewModel: NotificationsListViewModel by viewModels()
private var shouldRefreshNotifications = false
private var lastTabPosition = 0
private var binding: NotificationsListFragmentBinding? = null
@Suppress("DEPRECATION")
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
if (savedInstanceState != null) {
binding?.setSelectedTab(savedInstanceState.getInt(KEY_LAST_TAB_POSITION, TAB_POSITION_ALL))
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
shouldRefreshNotifications = true
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setHasOptionsMenu(true)
binding = NotificationsListFragmentBinding.bind(view).apply {
toolbarMain.setTitle(R.string.notifications_screen_title)
(requireActivity() as AppCompatActivity).setSupportActionBar(toolbarMain)
tabLayout.addOnTabSelectedListener(object : OnTabSelectedListener {
override fun onTabSelected(tab: Tab) {
val properties: MutableMap<String, String?> = HashMap(1)
when (tab.position) {
TAB_POSITION_ALL -> properties[NOTIFICATIONS_SELECTED_FILTER] = FILTER_ALL.toString()
TAB_POSITION_COMMENT -> properties[NOTIFICATIONS_SELECTED_FILTER] = FILTER_COMMENT.toString()
TAB_POSITION_FOLLOW -> properties[NOTIFICATIONS_SELECTED_FILTER] = FILTER_FOLLOW.toString()
TAB_POSITION_LIKE -> properties[NOTIFICATIONS_SELECTED_FILTER] = FILTER_LIKE.toString()
TAB_POSITION_UNREAD -> properties[NOTIFICATIONS_SELECTED_FILTER] = FILTER_UNREAD.toString()
else -> properties[NOTIFICATIONS_SELECTED_FILTER] = FILTER_ALL.toString()
}
AnalyticsTracker.track(NOTIFICATION_TAPPED_SEGMENTED_CONTROL, properties)
lastTabPosition = tab.position
}
override fun onTabUnselected(tab: Tab) {}
override fun onTabReselected(tab: Tab) {}
})
viewPager.adapter = NotificationsFragmentAdapter(childFragmentManager, buildTitles())
viewPager.pageMargin = resources.getDimensionPixelSize(R.dimen.margin_extra_large)
tabLayout.setupWithViewPager(viewPager)
jetpackTermsAndConditions.text = HtmlCompat.fromHtml(
String.format(resources.getString(R.string.jetpack_connection_terms_and_conditions), "<u>", "</u>"),
HtmlCompat.FROM_HTML_MODE_LEGACY
)
jetpackTermsAndConditions.setOnClickListener {
WPWebViewActivity.openURL(requireContext(), WPUrlUtils.buildTermsOfServiceUrl(context))
}
jetpackFaq.setOnClickListener {
WPWebViewActivity.openURL(requireContext(), StatsConnectJetpackActivity.FAQ_URL)
}
}
viewModel.showJetpackPoweredBottomSheet.observeEvent(viewLifecycleOwner) {
JetpackPoweredBottomSheetFragment
.newInstance(it, PageType.NOTIFS)
.show(childFragmentManager, JetpackPoweredBottomSheetFragment.TAG)
}
viewModel.showJetpackOverlay.observeEvent(viewLifecycleOwner) {
if (savedInstanceState == null)
JetpackFeatureFullScreenOverlayFragment
.newInstance(JetpackFeatureOverlayScreenType.NOTIFICATIONS)
.show(childFragmentManager, JetpackFeatureFullScreenOverlayFragment.TAG)
}
}
private fun buildTitles(): List<String> {
val result: ArrayList<String> = ArrayList(TAB_COUNT)
result.add(TAB_POSITION_ALL, getString(R.string.notifications_tab_title_all))
result.add(TAB_POSITION_UNREAD, getString(R.string.notifications_tab_title_unread_notifications))
result.add(TAB_POSITION_COMMENT, getString(R.string.notifications_tab_title_comments))
result.add(TAB_POSITION_FOLLOW, getString(R.string.notifications_tab_title_follows))
result.add(TAB_POSITION_LIKE, getString(R.string.notifications_tab_title_likes))
return result
}
override fun onPause() {
super.onPause()
shouldRefreshNotifications = true
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
override fun onResume() {
super.onResume()
EventBus.getDefault().post(NotificationsUnseenStatus(false))
binding?.apply {
if (!accountStore.hasAccessToken()) {
showConnectJetpackView()
connectJetpack.visibility = View.VISIBLE
tabLayout.visibility = View.GONE
viewPager.visibility = View.GONE
} else {
connectJetpack.visibility = View.GONE
tabLayout.visibility = View.VISIBLE
viewPager.visibility = View.VISIBLE
if (shouldRefreshNotifications) {
fetchNotesFromRemote()
}
}
setSelectedTab(lastTabPosition)
}
viewModel.onResume()
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putInt(KEY_LAST_TAB_POSITION, lastTabPosition)
super.onSaveInstanceState(outState)
}
private fun NotificationsListFragmentBinding.clearToolbarScrollFlags() {
if (toolbarMain.layoutParams is LayoutParams) {
val params = toolbarMain.layoutParams as LayoutParams
params.scrollFlags = 0
}
}
private fun fetchNotesFromRemote() {
if (!isAdded || !NetworkUtils.isNetworkAvailable(activity)) {
return
}
NotificationsUpdateServiceStarter.startService(activity)
}
private fun NotificationsListFragmentBinding.setSelectedTab(position: Int) {
lastTabPosition = position
tabLayout.getTabAt(lastTabPosition)?.select()
}
private fun NotificationsListFragmentBinding.showConnectJetpackView() {
clearToolbarScrollFlags()
jetpackSetup.setOnClickListener {
val selectedSite = (requireActivity() as? WPMainActivity)?.selectedSite
JetpackConnectionWebViewActivity.startJetpackConnectionFlow(activity, NOTIFICATIONS, selectedSite, false)
}
}
@Suppress("DEPRECATION")
private class NotificationsFragmentAdapter(
fragmentManager: FragmentManager,
private val titles: List<String>
) : FragmentPagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
override fun getCount(): Int {
return TAB_COUNT
}
override fun getItem(position: Int): Fragment {
return NotificationsListFragmentPage.newInstance(position)
}
override fun getPageTitle(position: Int): CharSequence? {
if (titles.size > position && position >= 0) {
return titles[position]
}
return super.getPageTitle(position)
}
override fun restoreState(state: Parcelable?, loader: ClassLoader?) {
try {
super.restoreState(state, loader)
} catch (exception: IllegalStateException) {
AppLog.e(NOTIFS, exception)
}
}
}
override fun onPrepareOptionsMenu(menu: Menu) {
val notificationSettings = menu.findItem(R.id.notifications_settings)
notificationSettings.isVisible = accountStore.hasAccessToken()
super.onPrepareOptionsMenu(menu)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.notifications_list_menu, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.notifications_settings) {
ActivityLauncher.viewNotificationsSettings(activity)
return true
}
return super.onOptionsItemSelected(item)
}
companion object {
const val NOTE_ID_EXTRA = "noteId"
const val NOTE_INSTANT_REPLY_EXTRA = "instantReply"
const val NOTE_PREFILLED_REPLY_EXTRA = "prefilledReplyText"
const val NOTE_MODERATE_ID_EXTRA = "moderateNoteId"
const val NOTE_MODERATE_STATUS_EXTRA = "moderateNoteStatus"
const val NOTE_CURRENT_LIST_FILTER_EXTRA = "currentFilter"
private const val TAB_COUNT = 5
const val TAB_POSITION_ALL = 0
const val TAB_POSITION_UNREAD = 1
const val TAB_POSITION_COMMENT = 2
const val TAB_POSITION_FOLLOW = 3
const val TAB_POSITION_LIKE = 4
private const val KEY_LAST_TAB_POSITION = "lastTabPosition"
fun newInstance(): NotificationsListFragment {
return NotificationsListFragment()
}
private fun getOpenNoteIntent(activity: Activity, noteId: String): Intent {
val detailIntent = Intent(activity, NotificationsDetailActivity::class.java)
detailIntent.putExtra(NOTE_ID_EXTRA, noteId)
return detailIntent
}
@JvmStatic
@Suppress("LongParameterList")
fun openNoteForReply(
activity: Activity?,
noteId: String?,
shouldShowKeyboard: Boolean,
replyText: String?,
filter: FILTERS?,
isTappedFromPushNotification: Boolean
) {
if (noteId == null || activity == null) {
return
}
if (activity.isFinishing) {
return
}
val detailIntent = getOpenNoteIntent(activity, noteId)
detailIntent.putExtra(NOTE_INSTANT_REPLY_EXTRA, shouldShowKeyboard)
if (!TextUtils.isEmpty(replyText)) {
detailIntent.putExtra(NOTE_PREFILLED_REPLY_EXTRA, replyText)
}
detailIntent.putExtra(NOTE_CURRENT_LIST_FILTER_EXTRA, filter)
detailIntent.putExtra(IS_TAPPED_ON_NOTIFICATION, isTappedFromPushNotification)
openNoteForReplyWithParams(detailIntent, activity)
}
private fun openNoteForReplyWithParams(detailIntent: Intent, activity: Activity) {
activity.startActivityForResult(detailIntent, RequestCodes.NOTE_DETAIL)
}
}
override fun onScrollableViewInitialized(containerId: Int) {
binding?.appBar?.setLiftOnScrollTargetViewIdAndRequestLayout(containerId)
if (jetpackBrandingUtils.shouldShowJetpackBranding()) {
binding?.root?.post {
// post is used to create a minimal delay here. containerId changes just before
// onScrollableViewInitialized is called, and findViewById can't find the new id before the delay.
val jetpackBannerView = binding?.jetpackBanner?.root ?: return@post
val scrollableView = binding?.root?.findViewById<View>(containerId) as? RecyclerView ?: return@post
jetpackBrandingUtils.showJetpackBannerIfScrolledToTop(jetpackBannerView, scrollableView)
jetpackBrandingUtils.initJetpackBannerAnimation(jetpackBannerView, scrollableView)
if (jetpackBrandingUtils.shouldShowJetpackPoweredBottomSheet()) {
jetpackBannerView.setOnClickListener {
jetpackBrandingUtils.trackBannerTapped(Screen.NOTIFICATIONS)
JetpackPoweredBottomSheetFragment
.newInstance()
.show(childFragmentManager, JetpackPoweredBottomSheetFragment.TAG)
}
}
}
}
}
}
| gpl-2.0 | f67cc938f90506b8b5d2552b00fcc33c | 44.788856 | 120 | 0.698156 | 5.183931 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/deeplearning/birnn/deepbirnn/DeepBiRNNEncoder.kt | 1 | 5345 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.deeplearning.birnn.deepbirnn
import com.kotlinnlp.simplednn.core.neuralprocessor.NeuralProcessor
import com.kotlinnlp.simplednn.deeplearning.birnn.BiRNN
import com.kotlinnlp.simplednn.deeplearning.birnn.BiRNNEncoder
import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
/**
* Deep Bidirectional Recursive Neural Network Encoder.
*
* For convenience, this class exposes methods as if there was a single [BiRNN].
* In this way, it is possible to use a [BiRNNEncoder] and a [DeepBiRNNEncoder] almost interchangeably.
*
* @property network the [DeepBiRNN] of this encoder
* @param rnnDropout the probability of RNNs dropout
* @param mergeDropout the probability of output merge dropout
* @property propagateToInput whether to propagate the errors to the input during the [backward]
* @property id an identification number useful to track a specific [DeepBiRNNEncoder]
*/
class DeepBiRNNEncoder<InputNDArrayType: NDArray<InputNDArrayType>>(
val network: DeepBiRNN,
rnnDropout: Double,
mergeDropout: Double,
override val propagateToInput: Boolean,
override val id: Int = 0
): NeuralProcessor<
List<InputNDArrayType>, // InputType
List<DenseNDArray>, // OutputType
List<DenseNDArray>, // ErrorsType
List<DenseNDArray> // InputErrorsType
> {
/**
* Deep Bidirectional Recursive Neural Network Encoder.
*
* For convenience, this class exposes methods as if there was a single [BiRNN].
* In this way, it is possible to use a [BiRNNEncoder] and a [DeepBiRNNEncoder] almost interchangeably.
*
* @param network the [DeepBiRNN] of this encoder
* @param dropout the probability of dropout, the same for the RNNs and the output merge (default 0.0)
* @param propagateToInput whether to propagate the errors to the input during the [backward]
* @param id an identification number useful to track a specific [DeepBiRNNEncoder]
*/
constructor(
network: DeepBiRNN,
propagateToInput: Boolean,
dropout: Double = 0.0,
id: Int = 0
): this(
network = network,
rnnDropout = dropout,
mergeDropout = dropout,
propagateToInput = propagateToInput,
id = id
)
/**
* List of encoders for all the stacked [BiRNN] layers.
*/
private val encoders = this.network.levels.mapIndexed { i, biRNN ->
if (i == 0)
BiRNNEncoder<InputNDArrayType>(
network = biRNN,
rnnDropout = rnnDropout,
mergeDropout = mergeDropout,
propagateToInput = this.propagateToInput)
else
BiRNNEncoder<DenseNDArray>(
network = biRNN,
rnnDropout = rnnDropout,
mergeDropout = mergeDropout,
propagateToInput = true)
}
/**
* The Forward.
*
* @param input the input sequence
*
* @return the result of the forward
*/
override fun forward(input: List<InputNDArrayType>): List<DenseNDArray> {
var output: List<DenseNDArray>
@Suppress("UNCHECKED_CAST")
output = (this.encoders[0] as BiRNNEncoder<InputNDArrayType>).forward(input)
for (i in 1 until this.encoders.size) {
@Suppress("UNCHECKED_CAST")
output = (this.encoders[i] as BiRNNEncoder<DenseNDArray>).forward(output)
}
return output
}
/**
* Propagate the errors of the entire sequence.
*
* @param outputErrors the errors to propagate
*/
override fun backward(outputErrors: List<DenseNDArray>) {
var errors: List<DenseNDArray> = outputErrors
this.encoders.reversed().forEach { encoder ->
encoder.backward(errors)
errors = encoder.getInputErrors(copy = false)
}
}
/**
* @param copy a Boolean indicating whether the returned errors must be a copy or a reference
*
* @return the errors of the input sequence
*/
override fun getInputErrors(copy: Boolean): List<DenseNDArray> =
this.encoders.first().getInputErrors(copy = copy)
/**
* @param copy a Boolean indicating whether the returned errors must be a copy or a reference
*
* @return the errors of the DeepBiRNN parameters
*/
override fun getParamsErrors(copy: Boolean) = this.encoders.flatMap { it.getParamsErrors(copy = copy) }
/**
* @param copy whether to return a copy of the arrays
*
* @return a pair containing the last output of the two RNNs (left-to-right, right-to-left).
*/
fun getLastOutput(copy: Boolean): Pair<DenseNDArray, DenseNDArray> = this.encoders.last().getLastOutput(copy)
/**
* Propagate the errors of the last output of the two RNNs (left-to-right, right-to-left).
*
* @param leftToRightErrors the last output errors of the left-to-right network
* @param rightToLeftErrors the last output errors of the right-to-left network
*/
fun backwardLastOutput(leftToRightErrors: DenseNDArray, rightToLeftErrors: DenseNDArray) =
this.encoders.last().backwardLastOutput(
leftToRightErrors = leftToRightErrors,
rightToLeftErrors = rightToLeftErrors)
}
| mpl-2.0 | ac92ff585da7a6271db8031beb31f917 | 33.934641 | 111 | 0.706829 | 4.182316 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/model/annotation/AnnotationBasedPluginModelBuilderService.kt | 1 | 3597 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.gradleTooling.model.annotation
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder
import org.jetbrains.plugins.gradle.tooling.ErrorMessageBuilder
import java.io.Serializable
import java.lang.Exception
interface DumpedPluginModel {
val className: String
// May contain primitives, Strings and collections of primitives/Strings
val args: Array<*>
operator fun component1() = className
operator fun component2() = args
}
class DumpedPluginModelImpl(
override val className: String,
override val args: Array<*>
) : DumpedPluginModel, Serializable {
constructor(clazz: Class<*>, vararg args: Any?) : this(clazz.canonicalName, args)
}
interface AnnotationBasedPluginModel : Serializable {
val annotations: List<String>
val presets: List<String>
/*
Objects returned from Gradle importer are implicitly wrapped in a proxy that can potentially leak internal Gradle structures.
So we need a way to safely serialize the arbitrary annotation plugin model.
*/
fun dump(): DumpedPluginModel
val isEnabled get() = annotations.isNotEmpty() || presets.isNotEmpty()
}
abstract class AnnotationBasedPluginModelBuilderService<T : AnnotationBasedPluginModel> : AbstractKotlinGradleModelBuilder() {
abstract val gradlePluginNames: List<String>
abstract val extensionName: String
abstract val modelClass: Class<T>
abstract fun createModel(annotations: List<String>, presets: List<String>, extension: Any?): T
override fun getErrorMessageBuilder(project: Project, e: Exception): ErrorMessageBuilder {
return ErrorMessageBuilder.create(project, e, "Gradle import errors")
.withDescription("Unable to build $gradlePluginNames plugin configuration")
}
override fun canBuild(modelName: String?): Boolean = modelName == modelClass.name
override fun buildAll(modelName: String?, project: Project): Any {
val plugin: Plugin<*>? = project.findPlugin(gradlePluginNames)
val extension: Any? = project.extensions.findByName(extensionName)
val annotations = mutableListOf<String>()
val presets = mutableListOf<String>()
if (plugin != null && extension != null) {
annotations += extension.getList("myAnnotations")
presets += extension.getList("myPresets")
return createModel(annotations, presets, extension)
}
return createModel(emptyList(), emptyList(), null)
}
private fun Project.findPlugin(names: List<String>): Plugin<*>? {
for (name in names) {
plugins.findPlugin(name)?.let { return it }
}
return null
}
private fun Any.getList(fieldName: String): List<String> {
@Suppress("UNCHECKED_CAST")
return getFieldValue(fieldName) as? List<String> ?: emptyList()
}
protected fun Any.getFieldValue(fieldName: String, clazz: Class<*> = this.javaClass): Any? {
val field = clazz.declaredFields.firstOrNull { it.name == fieldName }
?: return getFieldValue(fieldName, clazz.superclass ?: return null)
val oldIsAccessible = field.isAccessible
try {
field.isAccessible = true
return field.get(this)
} finally {
field.isAccessible = oldIsAccessible
}
}
} | apache-2.0 | db003f47113acb8585f9a282e0f011c5 | 36.092784 | 158 | 0.701418 | 4.867388 | false | false | false | false |
WhisperSystems/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/notifications/v2/NotificationConversation.kt | 1 | 7904 | package org.thoughtcrime.securesms.notifications.v2
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.net.Uri
import android.text.SpannableStringBuilder
import androidx.core.app.TaskStackBuilder
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.contacts.TurnOffContactJoinedNotificationsActivity
import org.thoughtcrime.securesms.contacts.avatars.GeneratedContactPhoto
import org.thoughtcrime.securesms.conversation.ConversationIntents
import org.thoughtcrime.securesms.conversation.colors.AvatarColor
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.notifications.DeleteNotificationReceiver
import org.thoughtcrime.securesms.notifications.MarkReadReceiver
import org.thoughtcrime.securesms.notifications.NotificationChannels
import org.thoughtcrime.securesms.notifications.NotificationIds
import org.thoughtcrime.securesms.notifications.RemoteReplyReceiver
import org.thoughtcrime.securesms.notifications.ReplyMethod
import org.thoughtcrime.securesms.preferences.widgets.NotificationPrivacyPreference
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.service.KeyCachingService
import org.thoughtcrime.securesms.util.Util
/**
* Encapsulate all the notifications for a given conversation (thread) and the top
* level information about said conversation.
*/
data class NotificationConversation(
val recipient: Recipient,
val threadId: Long,
val notificationItems: List<NotificationItemV2>
) {
val mostRecentNotification: NotificationItemV2 = notificationItems.last()
val notificationId: Int = NotificationIds.getNotificationIdForThread(threadId)
val sortKey: Long = Long.MAX_VALUE - mostRecentNotification.timestamp
val messageCount: Int = notificationItems.size
val isGroup: Boolean = recipient.isGroup
val isOnlyContactJoinedEvent: Boolean = messageCount == 1 && mostRecentNotification.isJoined
fun getContentTitle(context: Context): CharSequence {
return if (SignalStore.settings().messageNotificationsPrivacy.isDisplayContact) {
recipient.getDisplayName(context)
} else {
context.getString(R.string.SingleRecipientNotificationBuilder_signal)
}
}
fun getContactLargeIcon(context: Context): Drawable? {
return if (SignalStore.settings().messageNotificationsPrivacy.isDisplayContact) {
recipient.getContactDrawable(context)
} else {
GeneratedContactPhoto("Unknown", R.drawable.ic_profile_outline_40).asDrawable(context, AvatarColor.UNKNOWN)
}
}
fun getContactUri(context: Context): String? {
return if (SignalStore.settings().messageNotificationsPrivacy.isDisplayContact) {
recipient.contactUri?.toString()
} else {
null
}
}
fun getSlideBigPictureUri(context: Context): Uri? {
return if (notificationItems.size == 1 && SignalStore.settings().messageNotificationsPrivacy.isDisplayMessage && !KeyCachingService.isLocked(context)) {
mostRecentNotification.getBigPictureUri()
} else {
null
}
}
fun getContentText(context: Context): CharSequence? {
val privacy: NotificationPrivacyPreference = SignalStore.settings().messageNotificationsPrivacy
val stringBuilder = SpannableStringBuilder()
if (privacy.isDisplayContact && recipient.isGroup) {
stringBuilder.append(Util.getBoldedString(mostRecentNotification.individualRecipient.getDisplayName(context) + ": "))
}
return if (privacy.isDisplayMessage) {
stringBuilder.append(mostRecentNotification.getPrimaryText(context))
} else {
stringBuilder.append(context.getString(R.string.SingleRecipientNotificationBuilder_new_message))
}
}
fun getConversationTitle(context: Context): CharSequence? {
if (SignalStore.settings().messageNotificationsPrivacy.isDisplayContact) {
return if (isGroup) recipient.getDisplayName(context) else null
}
return context.getString(R.string.SingleRecipientNotificationBuilder_signal)
}
fun getWhen(): Long {
return mostRecentNotification.timestamp
}
fun hasNewNotifications(): Boolean {
return notificationItems.any { it.isNewNotification }
}
fun getChannelId(context: Context): String {
return if (isOnlyContactJoinedEvent) {
NotificationChannels.JOIN_EVENTS
} else {
recipient.notificationChannel ?: NotificationChannels.getMessagesChannel(context)
}
}
fun hasSameContent(other: NotificationConversation?): Boolean {
if (other == null) {
return false
}
return messageCount == other.messageCount && notificationItems.zip(other.notificationItems).all { (item, otherItem) -> item.hasSameContent(otherItem) }
}
fun getPendingIntent(context: Context): PendingIntent {
val intent: Intent = ConversationIntents.createBuilder(context, recipient.id, threadId)
.withStartingPosition(mostRecentNotification.getStartingPosition(context))
.build()
.makeUniqueToPreventMerging()
return TaskStackBuilder.create(context)
.addNextIntentWithParentStack(intent)
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)!!
}
fun getDeleteIntent(context: Context): PendingIntent? {
val ids = LongArray(notificationItems.size)
val mms = BooleanArray(ids.size)
notificationItems.forEachIndexed { index, notificationItem ->
ids[index] = notificationItem.id
mms[index] = notificationItem.isMms
}
val intent = Intent(context, DeleteNotificationReceiver::class.java)
.setAction(DeleteNotificationReceiver.DELETE_NOTIFICATION_ACTION)
.putExtra(DeleteNotificationReceiver.EXTRA_IDS, ids)
.putExtra(DeleteNotificationReceiver.EXTRA_MMS, mms)
.putExtra(DeleteNotificationReceiver.EXTRA_THREAD_IDS, longArrayOf(threadId))
.makeUniqueToPreventMerging()
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
fun getMarkAsReadIntent(context: Context): PendingIntent {
val intent = Intent(context, MarkReadReceiver::class.java)
.setAction(MarkReadReceiver.CLEAR_ACTION)
.putExtra(MarkReadReceiver.THREAD_IDS_EXTRA, longArrayOf(mostRecentNotification.threadId))
.putExtra(MarkReadReceiver.NOTIFICATION_ID_EXTRA, notificationId)
.makeUniqueToPreventMerging()
return PendingIntent.getBroadcast(context, (threadId * 2).toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
fun getQuickReplyIntent(context: Context): PendingIntent {
val intent: Intent = ConversationIntents.createPopUpBuilder(context, recipient.id, mostRecentNotification.threadId)
.build()
.makeUniqueToPreventMerging()
return PendingIntent.getActivity(context, (threadId * 2).toInt() + 1, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
fun getRemoteReplyIntent(context: Context, replyMethod: ReplyMethod): PendingIntent {
val intent = Intent(context, RemoteReplyReceiver::class.java)
.setAction(RemoteReplyReceiver.REPLY_ACTION)
.putExtra(RemoteReplyReceiver.RECIPIENT_EXTRA, recipient.id)
.putExtra(RemoteReplyReceiver.REPLY_METHOD, replyMethod)
.putExtra(RemoteReplyReceiver.EARLIEST_TIMESTAMP, notificationItems.first().timestamp)
.makeUniqueToPreventMerging()
return PendingIntent.getBroadcast(context, (threadId * 2).toInt() + 1, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
fun getTurnOffJoinedNotificationsIntent(context: Context): PendingIntent {
return PendingIntent.getActivity(
context,
0,
TurnOffContactJoinedNotificationsActivity.newIntent(context, threadId),
PendingIntent.FLAG_UPDATE_CURRENT
)
}
override fun toString(): String {
return "NotificationConversation(threadId=$threadId, notificationItems=$notificationItems, messageCount=$messageCount, hasNewNotifications=${hasNewNotifications()})"
}
}
| gpl-3.0 | a1d69c219bcd086a8c0ed025c558fc8f | 40.382199 | 169 | 0.778467 | 4.793208 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/pet/usecase/ApplyDamageToPlayerUseCase.kt | 1 | 4312 | package io.ipoli.android.pet.usecase
import io.ipoli.android.common.UseCase
import io.ipoli.android.dailychallenge.data.persistence.DailyChallengeRepository
import io.ipoli.android.habit.data.Habit
import io.ipoli.android.habit.usecase.CalculateHabitStreakUseCase
import io.ipoli.android.player.data.Player
import io.ipoli.android.player.persistence.PlayerRepository
import io.ipoli.android.quest.Quest
import org.threeten.bp.LocalDate
import java.util.*
/**
* Created by Venelin Valkov <[email protected]>
* on 11/30/17.
*/
class ApplyDamageToPlayerUseCase(
private val playerRepository: PlayerRepository,
private val dailyChallengeRepository: DailyChallengeRepository,
private val calculateHabitStreakUseCase: CalculateHabitStreakUseCase,
private val randomSeed: Long = System.currentTimeMillis()
) : UseCase<ApplyDamageToPlayerUseCase.Params, ApplyDamageToPlayerUseCase.Result> {
override fun execute(parameters: Params): ApplyDamageToPlayerUseCase.Result {
val p = playerRepository.find()
requireNotNull(p)
val player = p!!
if (player.isDead) {
return Result(player, 0, 0, 0)
}
val dcQuestIds =
dailyChallengeRepository.findForDate(parameters.date)?.questIds?.toSet() ?: emptySet()
val isPlanDay = player.preferences.planDays.contains(parameters.date.dayOfWeek)
val questDamage = parameters.quests.sumBy {
var dmg = QUEST_BASE_DAMAGE
if (isPlanDay)
dmg += PRODUCTIVE_DAY_DAMAGE
if (it.isFromRepeatingQuest)
dmg += REPEATING_QUEST_DAMAGE
if (it.isFromChallenge)
dmg += CHALLENGE_DAMAGE
if (dcQuestIds.contains(it.id))
dmg += DAILY_CHALLENGE_DAMAGE
dmg
}
val habitDamage = parameters.habits
.filter { !it.isCompletedForDate(parameters.date) }
.sumBy {
var dmg = HABIT_BASE_DAMAGE
if (isPlanDay)
dmg += PRODUCTIVE_DAY_DAMAGE
if (it.isFromChallenge)
dmg += CHALLENGE_DAMAGE
val streak = calculateHabitStreakUseCase.execute(
CalculateHabitStreakUseCase.Params(
it,
parameters.date
)
)
dmg += if (streak.current > 66)
HABIT_HIGH_STREAK_DAMAGE
else
HABIT_LOW_STREAK_DAMAGE
dmg
}
val totalDamage = questDamage + habitDamage
val r = createRandom()
val newPlayer = savePlayer(
player = player,
healthPenalty = totalDamage,
petHealthPenalty = totalDamage +
RANDOM_PET_DAMAGE[r.nextInt(RANDOM_PET_DAMAGE.size)],
petMoodPenalty = totalDamage +
RANDOM_PET_DAMAGE[r.nextInt(RANDOM_PET_DAMAGE.size)]
)
return ApplyDamageToPlayerUseCase.Result(newPlayer, questDamage, habitDamage, totalDamage)
}
private fun savePlayer(
player: Player,
healthPenalty: Int,
petHealthPenalty: Int,
petMoodPenalty: Int
) =
playerRepository.save(
player
.removeHealthPoints(healthPenalty)
.copy(
pet = if (player.pet.isDead) player.pet
else player.pet.removeHealthAndMoodPoints(petHealthPenalty, petMoodPenalty)
)
)
companion object {
const val QUEST_BASE_DAMAGE = 3
const val HABIT_BASE_DAMAGE = 1
const val PRODUCTIVE_DAY_DAMAGE = 2
const val CHALLENGE_DAMAGE = 2
const val REPEATING_QUEST_DAMAGE = 2
const val DAILY_CHALLENGE_DAMAGE = 2
const val HABIT_HIGH_STREAK_DAMAGE = 1
const val HABIT_LOW_STREAK_DAMAGE = 3
val RANDOM_PET_DAMAGE = intArrayOf(1, 2, 3, 4, 5)
}
private fun createRandom() = Random(randomSeed)
data class Params(val quests: List<Quest>, val habits: List<Habit>, val date: LocalDate)
data class Result(
val player: Player,
val questDamage: Int,
val habitDamage: Int,
val totalDamage: Int
)
} | gpl-3.0 | f6d08ae651190a6c1135477e628ee1f2 | 30.481752 | 98 | 0.607375 | 4.529412 | false | false | false | false |
jk1/intellij-community | platform/platform-impl/src/com/intellij/ui/components/components.kt | 3 | 8751 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("FunctionName")
package com.intellij.ui.components
import com.intellij.BundleBase
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.fileChooser.FileChooserFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComponentWithBrowseButton
import com.intellij.openapi.ui.ComponentWithBrowseButton.BrowseFolderActionListener
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.DialogWrapper.IdeModalityType
import com.intellij.openapi.ui.TextComponentAccessor
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.ui.ex.MultiLineLabel
import com.intellij.openapi.vcs.changes.issueLinks.LinkMouseListenerBase
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.*
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.util.FontUtil
import com.intellij.util.ui.SwingHelper
import com.intellij.util.ui.SwingHelper.addHistoryOnExpansion
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import java.awt.*
import java.util.regex.Pattern
import javax.swing.*
import javax.swing.text.BadLocationException
import javax.swing.text.Segment
private val HREF_PATTERN = Pattern.compile("<a(?:\\s+href\\s*=\\s*[\"']([^\"']*)[\"'])?\\s*>([^<]*)</a>")
private val LINK_TEXT_ATTRIBUTES: SimpleTextAttributes
get() = SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, JBColor.link())
fun Label(text: String, style: UIUtil.ComponentStyle? = null, fontColor: UIUtil.FontColor? = null, bold: Boolean = false): JLabel {
val finalText = BundleBase.replaceMnemonicAmpersand(text)
val label: JLabel
if (fontColor == null) {
label = if (finalText.contains('\n')) MultiLineLabel(finalText) else JLabel(finalText)
style?.let { UIUtil.applyStyle(it, label) }
}
else {
label = JBLabel(finalText, style ?: UIUtil.ComponentStyle.REGULAR, fontColor)
}
if (bold) {
label.font = label.font.deriveFont(Font.BOLD)
}
// surrounded by space to avoid false match
if (text.contains(" -> ")) {
label.text = text.replace(" -> ", " ${FontUtil.rightArrow(label.font)} ")
}
return label
}
fun Link(text: String, style: UIUtil.ComponentStyle? = null, action: () -> Unit): JComponent {
val result = LinkLabel.create(text, action)
style?.let { UIUtil.applyStyle(it, result) }
return result
}
@JvmOverloads
fun noteComponent(note: String, linkHandler: ((url: String) -> Unit)? = null): JComponent {
val matcher = HREF_PATTERN.matcher(note)
if (!matcher.find()) {
return Label(note)
}
val noteComponent = SimpleColoredComponent()
var prev = 0
do {
if (matcher.start() != prev) {
noteComponent.append(note.substring(prev, matcher.start()))
}
val linkUrl = matcher.group(1)
noteComponent.append(matcher.group(2), LINK_TEXT_ATTRIBUTES, if (linkHandler == null) SimpleColoredComponent.BrowserLauncherTag(linkUrl) else Runnable { linkHandler(linkUrl) })
prev = matcher.end()
}
while (matcher.find())
LinkMouseListenerBase.installSingleTagOn(noteComponent)
if (prev < note.length) {
noteComponent.append(note.substring(prev))
}
return noteComponent
}
@JvmOverloads
fun htmlComponent(text: String = "", font: Font = UIUtil.getLabelFont(), background: Color? = null, foreground: Color? = null, lineWrap: Boolean = false): JEditorPane {
val pane = SwingHelper.createHtmlViewer(lineWrap, font, background, foreground)
if (!text.isEmpty()) {
pane.text = "<html><head>${UIUtil.getCssFontDeclaration(font, UIUtil.getLabelForeground(), null, null)}</head><body>$text</body></html>"
}
pane.border = null
pane.disabledTextColor = UIUtil.getLabelDisabledForeground()
pane.addHyperlinkListener(BrowserHyperlinkListener.INSTANCE)
return pane
}
fun RadioButton(text: String): JRadioButton = JRadioButton(BundleBase.replaceMnemonicAmpersand(text))
fun CheckBox(text: String, selected: Boolean = false, toolTip: String? = null): JCheckBox {
val component = JCheckBox(BundleBase.replaceMnemonicAmpersand(text), selected)
toolTip?.let { component.toolTipText = it }
return component
}
@JvmOverloads
fun Panel(title: String? = null, layout: LayoutManager2? = BorderLayout()): JPanel {
val panel = JPanel(layout)
title?.let { setTitledBorder(it, panel) }
return panel
}
private fun setTitledBorder(title: String, panel: JPanel) {
val border = IdeBorderFactory.createTitledBorder(title, false)
panel.border = border
border.acceptMinimumSize(panel)
}
/**
* Consider using [UI DSL](https://github.com/JetBrains/intellij-community/tree/master/platform/platform-impl/src/com/intellij/ui/layout#readme) to create panel.
*/
fun dialog(title: String,
panel: JComponent,
resizable: Boolean = false,
focusedComponent: JComponent? = null,
okActionEnabled: Boolean = true,
project: Project? = null,
parent: Component? = null,
errorText: String? = null,
modality: IdeModalityType = IdeModalityType.IDE,
ok: (() -> List<ValidationInfo>?)? = null): DialogWrapper {
return object: DialogWrapper(project, parent, true, modality) {
init {
setTitle(title)
setResizable(resizable)
if (!okActionEnabled) {
this.okAction.isEnabled = false
}
setErrorText(errorText)
init()
}
override fun createCenterPanel() = panel
override fun getPreferredFocusedComponent() = focusedComponent
override fun doOKAction() {
if (!okAction.isEnabled) {
return
}
val validationInfoList = ok?.invoke()
if (validationInfoList == null || validationInfoList.isEmpty()) {
super.doOKAction()
}
else {
setErrorInfoAll(validationInfoList)
}
}
}
}
@JvmOverloads
fun <T : JComponent> installFileCompletionAndBrowseDialog(project: Project?,
component: ComponentWithBrowseButton<T>,
textField: JTextField,
@Nls(capitalization = Nls.Capitalization.Title) browseDialogTitle: String,
fileChooserDescriptor: FileChooserDescriptor,
textComponentAccessor: TextComponentAccessor<T>,
fileChosen: ((chosenFile: VirtualFile) -> String)? = null) {
if (ApplicationManager.getApplication() == null) {
// tests
return
}
component.addActionListener(
object : BrowseFolderActionListener<T>(browseDialogTitle, null, component, project, fileChooserDescriptor, textComponentAccessor) {
override fun onFileChosen(chosenFile: VirtualFile) {
if (fileChosen == null) {
super.onFileChosen(chosenFile)
}
else {
textComponentAccessor.setText(myTextComponent.childComponent, fileChosen(chosenFile))
}
}
})
FileChooserFactory.getInstance().installFileCompletion(textField, fileChooserDescriptor, true, project)
}
@JvmOverloads
fun textFieldWithHistoryWithBrowseButton(project: Project?,
browseDialogTitle: String,
fileChooserDescriptor: FileChooserDescriptor,
historyProvider: (() -> List<String>)? = null,
fileChosen: ((chosenFile: VirtualFile) -> String)? = null): TextFieldWithHistoryWithBrowseButton {
val component = TextFieldWithHistoryWithBrowseButton()
val textFieldWithHistory = component.childComponent
textFieldWithHistory.setHistorySize(-1)
textFieldWithHistory.setMinimumAndPreferredWidth(0)
if (historyProvider != null) {
addHistoryOnExpansion(textFieldWithHistory, historyProvider)
}
installFileCompletionAndBrowseDialog(
project,
component,
component.childComponent.textEditor,
browseDialogTitle,
fileChooserDescriptor,
TextComponentAccessor.TEXT_FIELD_WITH_HISTORY_WHOLE_TEXT,
fileChosen = fileChosen
)
return component
}
val JPasswordField.chars: CharSequence?
get() {
val doc = document
if (doc.length == 0) {
return ""
}
val segment = Segment()
try {
doc.getText(0, doc.length, segment)
}
catch (e: BadLocationException) {
return null
}
return segment
} | apache-2.0 | 7576f07d9bc15173242a36e22d4e7f2d | 35.165289 | 180 | 0.683008 | 4.639979 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/settings/models/OutlinedSwitch.kt | 2 | 1746 | package org.thoughtcrime.securesms.components.settings.models
import android.view.View
import android.widget.TextView
import com.google.android.material.switchmaterial.SwitchMaterial
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.settings.DSLSettingsText
import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.adapter.mapping.MappingModel
import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder
object OutlinedSwitch {
fun register(mappingAdapter: MappingAdapter) {
mappingAdapter.registerFactory(Model::class.java, LayoutFactory(::ViewHolder, R.layout.outlined_switch))
}
class Model(
val key: String = "OutlinedSwitch",
val text: DSLSettingsText,
val isChecked: Boolean,
val isEnabled: Boolean,
val onClick: (Model) -> Unit
) : MappingModel<Model> {
override fun areItemsTheSame(newItem: Model): Boolean = newItem.key == key
override fun areContentsTheSame(newItem: Model): Boolean {
return areItemsTheSame(newItem) &&
text == newItem.text &&
isChecked == newItem.isChecked &&
isEnabled == newItem.isEnabled
}
}
class ViewHolder(itemView: View) : MappingViewHolder<Model>(itemView) {
private val text: TextView = findViewById(R.id.outlined_switch_control_text)
private val switch: SwitchMaterial = findViewById(R.id.outlined_switch_switch)
override fun bind(model: Model) {
text.text = model.text.resolve(context)
switch.isChecked = model.isChecked
switch.setOnClickListener { model.onClick(model) }
itemView.isEnabled = model.isEnabled
}
}
}
| gpl-3.0 | 836cd634fcfc1b54ed7f4998867f434f | 36.148936 | 108 | 0.756586 | 4.476923 | false | false | false | false |
seirion/code | kotlin/next_permutation.kt | 1 | 584 | // https://leetcode.com/problems/next-permutation
fun nextPermutation(nums: IntArray): Unit {
nums.reverse()
var to = nums.zip(nums.drop(1))
.indexOfFirst { it.first > it.second }
.let { if (it == -1) nums.lastIndex else it }
if (to < nums.lastIndex) {
val s = nums.indexOfFirst { nums[to + 1] < it }
nums.swap(s, to + 1)
}
var from = 0
while (from < to) {
nums.swap(from++, to--)
}
nums.reverse()
}
fun IntArray.swap(a: Int, b: Int) {
val temp = this[a]
this[a] = this[b]
this[b] = temp
}
| apache-2.0 | 990f05d2430e024649afecbea6a36724 | 24.391304 | 57 | 0.539384 | 3.106383 | false | false | false | false |
jonathanlermitage/tikione-c2e | src/main/kotlin/fr/tikione/c2e/core/service/web/AbstractReader.kt | 1 | 3693 | package fr.tikione.c2e.core.service.web
import fr.tikione.c2e.core.model.web.Auth
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.safety.Whitelist
import org.jsoup.select.Elements
import java.io.IOException
abstract class AbstractReader {
/** Replace unbreakable spaces by regular spaces, and apply trim. */
fun clean(strToClean: String): String {
var str = strToClean
while (str.contains(160.toChar().toString())) {
str = str.replace(160.toChar().toString(), " ")
}
var res = Jsoup.clean(str.trim { it <= ' ' }, Whitelist.none())
if (res.toUpperCase().endsWith("TWITTER FACEBOOK EMAIL")) {
res = res.substring(0, res.toUpperCase().lastIndexOf("TWITTER FACEBOOK EMAIL")) // remove social buttons
}
return res.trim { it <= ' ' }
}
/** Get a remote document. */
@Throws(IOException::class)
fun queryUrl(auth: Auth, url: String): Document = Jsoup.connect(url)
.cookies(auth.cookies)
.userAgent(UA)
.execute().parse()
fun text(elt: Element?): String? = if (elt == null) null else clean(elt.text())
/** Get text and keep some HTML styling tags: `em` and `strong`. */
fun richText(elt: Element?): String? {
if (elt == null) {
return null
}
var text = elt.html()
var idx = 0
while (text.indexOf(EM_START, idx) >= 0) {
idx = text.indexOf(EM_START, idx) + EM_START.length
val idxEnd = text.indexOf(EM_END, idx) + EM_END.length
if (idx < idxEnd) {
text = text.substring(0, idx) + CUSTOMTAG_EM_START + text.substring(idx, idxEnd) + CUSTOMTAG_EM_END + text.substring(idxEnd)
}
}
idx = 0
while (text.indexOf(STRONG_START, idx) >= 0) {
idx = text.indexOf(STRONG_START, idx) + STRONG_START.length
val idxEnd = text.indexOf(STRONG_END, idx) + STRONG_END.length
if (idx < idxEnd) {
text = text.substring(0, idx) + CUSTOMTAG_STRONG_START + text.substring(idx, idxEnd) + CUSTOMTAG_STRONG_END + text.substring(idxEnd)
}
}
return clean(text)
}
fun text(vararg elt: Elements): String? {
if (elt.isEmpty()) {
return null
}
val buff = StringBuilder()
elt.iterator().forEach { elements -> buff.append(clean(elements.text())) }
return buff.toString()
}
fun attr(elt: Element?, attr: String): String? = elt?.attr(attr)
fun attr(elt: Elements?, attr: String): String? = elt?.attr(attr)
fun attr(baseUrl: String, elt: Elements?, attr: String): String? =
if (elt?.attr(attr) == null || elt.attr(attr).trim { it <= ' ' }.isEmpty()) null else baseUrl + elt.attr(attr)
companion object {
const val CPC_BASE_URL = "https://www.canardpc.com"
const val CPC_LOGIN_FORM_POST_URL = "$CPC_BASE_URL/user/login"
const val CPC_MAG_NUMBER_BASE_URL = "$CPC_BASE_URL/numero/_NUM_"
const val CUSTOMTAG_EM_START = "__c2e_emStart__"
const val CUSTOMTAG_EM_END = "__c2e_emEnd__"
const val CUSTOMTAG_STRONG_START = "__c2e_strongStart__"
const val CUSTOMTAG_STRONG_END = "__c2e_strongEnd__"
private const val EM_START = "<em>"
private const val EM_END = "</em>"
private const val STRONG_START = "<span class=\"title\">"
private const val STRONG_END = "</span>"
/** UserAgent to include when scrapping CanardPC website. This is not mandatory, but a good practice. */
const val UA = "fr.tikione.c2e"
}
}
| mit | 392a0279b13ba67c698c55d8cb3ac9eb | 39.141304 | 148 | 0.592201 | 3.645607 | false | false | false | false |
google/ground-android | ground/src/main/java/com/google/android/ground/MainViewModel.kt | 1 | 5767 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.MutableLiveData
import androidx.navigation.NavDirections
import com.google.android.ground.model.Survey
import com.google.android.ground.model.User
import com.google.android.ground.repository.LocationOfInterestRepository
import com.google.android.ground.repository.SurveyRepository
import com.google.android.ground.repository.TermsOfServiceRepository
import com.google.android.ground.repository.UserRepository
import com.google.android.ground.rx.Schedulers
import com.google.android.ground.rx.annotations.Cold
import com.google.android.ground.system.auth.AuthenticationManager
import com.google.android.ground.system.auth.SignInState
import com.google.android.ground.ui.common.AbstractViewModel
import com.google.android.ground.ui.common.EphemeralPopups
import com.google.android.ground.ui.common.Navigator
import com.google.android.ground.ui.common.SharedViewModel
import com.google.android.ground.ui.home.HomeScreenFragmentDirections
import com.google.android.ground.ui.signin.SignInFragmentDirections
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import java8.util.Optional
import javax.inject.Inject
import timber.log.Timber
/** Top-level view model representing state of the [MainActivity] shared by all fragments. */
@SharedViewModel
class MainViewModel
@Inject
constructor(
private val surveyRepository: SurveyRepository,
private val locationOfInterestRepository: LocationOfInterestRepository,
private val userRepository: UserRepository,
private val termsOfServiceRepository: TermsOfServiceRepository,
private val popups: EphemeralPopups,
navigator: Navigator,
authenticationManager: AuthenticationManager,
private val schedulers: Schedulers
) : AbstractViewModel() {
private var surveySyncSubscription: Disposable? = null
/** The window insets determined by the activity. */
val windowInsets: MutableLiveData<WindowInsetsCompat> = MutableLiveData()
/** The state of sign in progress dialog visibility. */
val signInProgressDialogVisibility: MutableLiveData<Boolean> = MutableLiveData()
init {
disposeOnClear(
authenticationManager.signInState
.observeOn(schedulers.ui())
.switchMap { signInState: SignInState -> onSignInStateChange(signInState) }
.subscribe { directions: NavDirections -> navigator.navigate(directions) }
)
}
/**
* Keeps local locations o interest in sync with remote when a survey is active, does nothing when
* no survey is active. The stream never completes; syncing stops when subscriptions are disposed
* of.
*
* @param survey the currently active survey.
*/
private fun syncLocationsOfInterest(
survey: Optional<Survey>
): @Cold(terminates = false) Completable {
return survey
.map { locationOfInterestRepository.syncLocationsOfInterest(it) }
.orElse(Completable.never())
}
private fun onSignInStateChange(signInState: SignInState): Observable<NavDirections> {
// Display progress only when signing in.
signInProgressDialogVisibility.postValue(signInState.state == SignInState.State.SIGNING_IN)
// TODO: Check auth status whenever fragments resumes
return signInState.result.fold(
{
when (signInState.state) {
SignInState.State.SIGNED_IN -> onUserSignedIn(it!!)
SignInState.State.SIGNED_OUT -> onUserSignedOut()
else -> Observable.never()
}
},
{ onUserSignInError(it) }
)
}
private fun onUserSignInError(error: Throwable): Observable<NavDirections> {
Timber.e("Authentication error: $error")
popups.showError(R.string.sign_in_unsuccessful)
return onUserSignedOut()
}
private fun onUserSignedOut(): Observable<NavDirections> {
// Scope of subscription is until view model is cleared. Dispose it manually otherwise, firebase
// attempts to maintain a connection even after user has logged out and throws an error.
surveySyncSubscription?.dispose()
surveyRepository.clearActiveSurvey()
userRepository.clearUserPreferences()
return Observable.just(SignInFragmentDirections.showSignInScreen())
}
private fun onUserSignedIn(user: User): Observable<NavDirections> {
// TODO: Move to background service.
surveySyncSubscription =
surveyRepository.activeSurvey
.observeOn(schedulers.io())
.switchMapCompletable { syncLocationsOfInterest(it) }
.subscribe()
surveySyncSubscription?.let { disposeOnClear(it) }
return userRepository
.saveUser(user)
.andThen(
if (termsOfServiceRepository.isTermsOfServiceAccepted) {
Observable.just(HomeScreenFragmentDirections.showHomeScreen())
} else {
termsOfServiceRepository.termsOfService
.map { SignInFragmentDirections.showTermsOfService().setTermsOfServiceText(it.text) }
.cast(NavDirections::class.java)
.switchIfEmpty(Maybe.just(HomeScreenFragmentDirections.showHomeScreen()))
.toObservable()
}
)
}
}
| apache-2.0 | 81b7434262b9766654f1707eddfa8ccd | 37.966216 | 100 | 0.75932 | 4.734811 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/readinglist/AddToReadingListDialog.kt | 1 | 10287 | package org.wikipedia.readinglist
import android.content.DialogInterface
import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetBehavior
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.Constants
import org.wikipedia.Constants.InvokeSource
import org.wikipedia.R
import org.wikipedia.analytics.ReadingListsFunnel
import org.wikipedia.databinding.DialogAddToReadingListBinding
import org.wikipedia.page.ExtendedBottomSheetDialogFragment
import org.wikipedia.page.PageTitle
import org.wikipedia.readinglist.ReadingListTitleDialog.readingListTitleDialog
import org.wikipedia.readinglist.database.ReadingList
import org.wikipedia.readinglist.database.ReadingListDbHelper
import org.wikipedia.settings.Prefs
import org.wikipedia.settings.SiteInfoClient
import org.wikipedia.util.DimenUtil.getDimension
import org.wikipedia.util.DimenUtil.roundedDpToPx
import org.wikipedia.util.FeedbackUtil
import org.wikipedia.util.FeedbackUtil.makeSnackbar
import org.wikipedia.util.log.L
import java.util.*
open class AddToReadingListDialog : ExtendedBottomSheetDialogFragment() {
private var _binding: DialogAddToReadingListBinding? = null
private val binding get() = _binding!!
private lateinit var titles: List<PageTitle>
private lateinit var adapter: ReadingListAdapter
private val createClickListener = CreateButtonClickListener()
private var showDefaultList = false
private val displayedLists = mutableListOf<ReadingList>()
private val listItemCallback = ReadingListItemCallback()
lateinit var invokeSource: InvokeSource
var readingLists = listOf<ReadingList>()
var disposables = CompositeDisposable()
var dismissListener: DialogInterface.OnDismissListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
titles = requireArguments().getParcelableArrayList(PAGE_TITLE_LIST)!!
invokeSource = requireArguments().getSerializable(Constants.INTENT_EXTRA_INVOKE_SOURCE) as InvokeSource
showDefaultList = requireArguments().getBoolean(SHOW_DEFAULT_LIST)
adapter = ReadingListAdapter()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
_binding = DialogAddToReadingListBinding.inflate(inflater, container, false)
binding.listOfLists.layoutManager = LinearLayoutManager(requireActivity())
binding.listOfLists.adapter = adapter
binding.createButton.setOnClickListener(createClickListener)
// Log a click event, but only the first time the dialog is shown.
logClick(savedInstanceState)
updateLists()
return binding.root
}
override fun onStart() {
super.onStart()
BottomSheetBehavior.from(binding.root.parent as View).peekHeight = roundedDpToPx(getDimension(R.dimen.readingListSheetPeekHeight))
}
override fun onDestroyView() {
disposables.clear()
_binding = null
super.onDestroyView()
}
override fun dismiss() {
super.dismiss()
dismissListener?.onDismiss(null)
}
private fun updateLists() {
disposables.add(Observable.fromCallable { ReadingListDbHelper.allLists }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ lists ->
readingLists = lists
displayedLists.clear()
displayedLists.addAll(readingLists)
if (!showDefaultList && displayedLists.isNotEmpty()) {
displayedLists.removeAt(0)
}
ReadingList.sort(displayedLists, Prefs.getReadingListSortMode(ReadingList.SORT_BY_NAME_ASC))
adapter.notifyDataSetChanged()
if (displayedLists.isEmpty()) {
showCreateListDialog()
}
}) { obj -> L.w(obj) })
}
private inner class CreateButtonClickListener : View.OnClickListener {
override fun onClick(v: View) {
if (readingLists.size >= Constants.MAX_READING_LISTS_LIMIT) {
val message = getString(R.string.reading_lists_limit_message)
dismiss()
makeSnackbar(requireActivity(), message, FeedbackUtil.LENGTH_DEFAULT).show()
} else {
showCreateListDialog()
}
}
}
private fun showCreateListDialog() {
readingListTitleDialog(requireActivity(), "", "", readingLists.map { it.title }) { text, description ->
addAndDismiss(ReadingListDbHelper.createList(text, description), titles)
}.show()
}
private fun addAndDismiss(readingList: ReadingList, titles: List<PageTitle>?) {
if (readingList.pages.size + titles!!.size > SiteInfoClient.maxPagesPerReadingList) {
val message = getString(R.string.reading_list_article_limit_message, readingList.title, SiteInfoClient.maxPagesPerReadingList)
makeSnackbar(requireActivity(), message, FeedbackUtil.LENGTH_DEFAULT).show()
dismiss()
return
}
commitChanges(readingList, titles)
}
open fun logClick(savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
ReadingListsFunnel().logAddClick(invokeSource)
}
}
open fun commitChanges(readingList: ReadingList, titles: List<PageTitle>) {
disposables.add(Observable.fromCallable { ReadingListDbHelper.addPagesToListIfNotExist(readingList, titles) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ addedTitlesList ->
val message: String
if (addedTitlesList.isEmpty()) {
message = if (titles.size == 1) getString(R.string.reading_list_article_already_exists_message, readingList.title, titles[0].displayText) else getString(R.string.reading_list_articles_already_exist_message, readingList.title)
} else {
message = if (addedTitlesList.size == 1) getString(R.string.reading_list_article_added_to_named, addedTitlesList[0], readingList.title) else getString(R.string.reading_list_articles_added_to_named, addedTitlesList.size, readingList.title)
ReadingListsFunnel().logAddToList(readingList, readingLists.size, invokeSource)
}
showViewListSnackBar(readingList, message)
dismiss()
}) { obj -> L.w(obj) })
}
fun showViewListSnackBar(list: ReadingList, message: String) {
makeSnackbar(requireActivity(), message, FeedbackUtil.LENGTH_DEFAULT)
.setAction(R.string.reading_list_added_view_button) { v -> v.context.startActivity(ReadingListActivity.newIntent(v.context, list)) }.show()
}
private inner class ReadingListItemCallback : ReadingListItemView.Callback {
override fun onClick(readingList: ReadingList) {
addAndDismiss(readingList, titles)
}
override fun onRename(readingList: ReadingList) {}
override fun onDelete(readingList: ReadingList) {}
override fun onSaveAllOffline(readingList: ReadingList) {}
override fun onRemoveAllOffline(readingList: ReadingList) {}
}
private class ReadingListItemHolder constructor(itemView: ReadingListItemView) : RecyclerView.ViewHolder(itemView) {
fun bindItem(readingList: ReadingList) {
(itemView as ReadingListItemView).setReadingList(readingList, ReadingListItemView.Description.SUMMARY)
}
val view get() = itemView as ReadingListItemView
init {
itemView.isLongClickable = false
}
}
private inner class ReadingListAdapter : RecyclerView.Adapter<ReadingListItemHolder>() {
override fun getItemCount(): Int {
return displayedLists.size
}
override fun onCreateViewHolder(parent: ViewGroup, pos: Int): ReadingListItemHolder {
val view = ReadingListItemView(requireContext())
return ReadingListItemHolder(view)
}
override fun onBindViewHolder(holder: ReadingListItemHolder, pos: Int) {
holder.bindItem(displayedLists[pos])
}
override fun onViewAttachedToWindow(holder: ReadingListItemHolder) {
super.onViewAttachedToWindow(holder)
holder.view.callback = listItemCallback
}
override fun onViewDetachedFromWindow(holder: ReadingListItemHolder) {
holder.view.callback = null
super.onViewDetachedFromWindow(holder)
}
}
companion object {
const val PAGE_TITLE_LIST = "pageTitleList"
const val SHOW_DEFAULT_LIST = "showDefaultList"
@JvmStatic
@JvmOverloads
fun newInstance(title: PageTitle,
source: InvokeSource,
listener: DialogInterface.OnDismissListener? = null): AddToReadingListDialog {
return newInstance(listOf(title), source, listener)
}
@JvmStatic
@JvmOverloads
fun newInstance(titles: List<PageTitle>,
source: InvokeSource,
listener: DialogInterface.OnDismissListener? = null): AddToReadingListDialog {
return AddToReadingListDialog().apply {
arguments = bundleOf(PAGE_TITLE_LIST to ArrayList<Parcelable>(titles),
Constants.INTENT_EXTRA_INVOKE_SOURCE to source,
SHOW_DEFAULT_LIST to true)
dismissListener = listener
}
}
}
}
| apache-2.0 | 8c074608ef11bf33b81610152543009a | 42.588983 | 262 | 0.677457 | 5.259202 | false | false | false | false |
google/ground-android | ground/src/main/java/com/google/android/ground/persistence/remote/firestore/schema/SubmissionDocument.kt | 1 | 1026 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.persistence.remote.firestore.schema
import com.google.firebase.firestore.IgnoreExtraProperties
/** Submission entity stored in Firestore. */
@IgnoreExtraProperties
data class SubmissionDocument(
val loiId: String? = null,
val jobId: String? = null,
val created: AuditInfoNestedObject? = null,
val lastModified: AuditInfoNestedObject? = null,
val responses: Map<String, Any>? = null
)
| apache-2.0 | 3e3f8cec3ba21711c33439a7e8268303 | 34.37931 | 75 | 0.753411 | 4.187755 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineTypeAliasHandler.kt | 4 | 1605 | // 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.inline
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.refactoring.HelpID
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtTypeAlias
class KotlinInlineTypeAliasHandler : KotlinInlineActionHandler() {
override val helpId: String get() = HelpID.INLINE_VARIABLE
override val refactoringName: String get() = KotlinBundle.message("title.inline.type.alias")
override fun canInlineKotlinElement(element: KtElement): Boolean = element is KtTypeAlias
override fun inlineKotlinElement(project: Project, editor: Editor?, element: KtElement) {
val typeAlias = element as? KtTypeAlias ?: return
if (!checkSources(project, editor, element)) return
typeAlias.name ?: return
typeAlias.getTypeReference() ?: return
val dialog = KotlinInlineTypeAliasDialog(
element,
editor?.findSimpleNameReference(),
editor = editor,
)
if (!isUnitTestMode()) {
dialog.show()
} else {
try {
dialog.doAction()
} finally {
dialog.close(DialogWrapper.OK_EXIT_CODE, true)
}
}
}
}
| apache-2.0 | fecc1745ca0caf411a0bbab6e0eddb5d | 35.477273 | 158 | 0.69595 | 4.706745 | false | false | false | false |
phrase/Phrase-AndroidStudio | src/main/kotlin/com/phrase/intellij/PhraseActions.kt | 1 | 5107 | package com.phrase.intellij
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.wm.ToolWindowManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.swing.Swing
import com.phrase.intellij.api.Api
import com.phrase.intellij.api.ApiCallback
import com.phrase.intellij.ui.projectconfig.ProjectConfigDialog
import com.phrase.intellij.ui.toolwindow.PhraseToolWindowPanel
enum class PhraseButton(val title:String, val desc:String, val icon:String) {
PUSH(PhraseBundle.message("buttonPush"), PhraseBundle.message("buttonPushDesc"), "/icons/cloud-upload.png"),
PULL(PhraseBundle.message("buttonPull"), PhraseBundle.message("buttonPullDesc"), "/icons/cloud-download.png"),
CONFIG(PhraseBundle.message("buttonConfig"), PhraseBundle.message("buttonConfigDesc"), "/icons/cog.png"),
TRANSLATION_CENTER(PhraseBundle.message("buttonTranslationCenter"), PhraseBundle.message("buttonTranslationCenterDesc"), "/icons/home.png"),
HELP(PhraseBundle.message("buttonHelp"), PhraseBundle.message("buttonHelpDesc"), "/icons/question.png");
}
abstract class PhraseAction(button: PhraseButton):AnAction(button.title, button.desc, IconLoader.getIcon(button.icon, PhraseAction::class.java)){
final override fun actionPerformed(e: AnActionEvent) {
e.project?.let { act(it) }
}
abstract fun act(project:Project)
}
abstract class PhraseActionToolWindow(button: PhraseButton):PhraseAction(button){
final override fun act(project: Project) {
ToolWindowManager.getInstance(project).getToolWindow("Phrase")?.let{
if (!it.isActive) it.activate(null)
val panel = it.contentManager.contents[0].component as PhraseToolWindowPanel
act(project, panel)
}
}
abstract fun act(project: Project, panel: PhraseToolWindowPanel)
}
class ActionPush: PhraseActionToolWindow(PhraseButton.PUSH) {
override fun act(project: Project, panel: PhraseToolWindowPanel) = onPushPull(Api.Command.PUSH, project, panel)
}
class ActionPull: PhraseActionToolWindow(PhraseButton.PULL) {
override fun act(project: Project, panel: PhraseToolWindowPanel) = onPushPull(Api.Command.PULL, project, panel)
}
class ActionConfig: PhraseAction(PhraseButton.CONFIG) {
override fun act(project: Project) = onConfig(project)
}
class ActionTranslationCenter: PhraseAction(PhraseButton.TRANSLATION_CENTER) {
override fun act(project: Project) = Utils.openLink(PhraseUrls.TRANSLATION_CENTER, project)
}
class ActionHelp: PhraseAction(PhraseButton.HELP) {
override fun act(project: Project) = Utils.openLink(PhraseUrls.HELP, project)
}
private fun onConfig(project: Project){
try {
Api.ensureClientExists()
val dialog = ProjectConfigDialog(project)
val isOK = dialog.showAndGet()
if(isOK) {
dialog.save()
project.guessProjectDir()?.refresh(false, false)
YamlParser.yamlVirtualFile(project)?.let {
FileEditorManager.getInstance(project).openTextEditor(OpenFileDescriptor(project, it), true)
}
}
}catch (e:Throwable){
showErrorNotification(e, project)
}
}
private fun onPushPull(command:Api.Command, project: Project, panel: PhraseToolWindowPanel){
val yamlModel:YamlModel = try {
YamlParser.read(project)
}catch (e:PhraseConfigurationNotFoundException){
onConfig(project); return
}catch (e:Throwable){
showErrorNotification(e, project); return
}
val api = Api(project, yamlModel.phrase.access_token)
GlobalScope.launch(Dispatchers.Swing) {
panel.clearLog()
val callback = object : ApiCallback{
override fun onMessage(message: String) { panel.append(message) }
override fun onFinish() { panel.append(PhraseBundle.message("done")) }
}
try {
api.runWithCallback(command, callback)
}catch (e:Throwable){
showErrorNotification(e, project)
}
}
}
private fun showErrorNotification(e:Throwable, project: Project){
when(e) {
is PhraseClientNotFoundException -> {
Notify.error(PhraseBundle.message("errorClientNotSpecified"), project) {
Utils.openConfigurable()
}
}
is PhraseConfigurationNotFoundException -> Notify.error(PhraseBundle.message("errorConfigurationNotFound"), project)
is PhraseLoadConfigurationException -> Notify.error(PhraseBundle.message("errorParsingConfiguration"), project)
is PhraseSaveConfigurationException -> Notify.error(PhraseBundle.message("errorSavingConfiguration"), project)
else -> Notify.error(PhraseBundle.message("errorUnknown"), project)
}
}
| bsd-3-clause | 73ff9f00a203771ddbab5db41c70a7cf | 43.408696 | 145 | 0.733111 | 4.383691 | false | true | false | false |
DevCharly/kobalt-ant | src/main/kotlin/com/devcharly/kobalt/plugin/ant/AntTaskPlugin.kt | 1 | 6779 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kobalt.plugin.ant
import com.beust.kobalt.IncrementalTaskInfo
import com.beust.kobalt.TaskResult
import com.beust.kobalt.api.*
import com.beust.kobalt.api.annotation.AnnotationDefault
import com.beust.kobalt.api.annotation.Directive
import com.beust.kobalt.maven.Md5
import com.beust.kobalt.misc.KobaltLogger
import com.beust.kobalt.misc.error
import com.devcharly.kotlin.ant.Ant
import com.devcharly.kotlin.ant.AntContext
import com.devcharly.kotlin.ant.LogLevel
import org.apache.tools.ant.BuildException
import org.apache.tools.ant.Task
import java.io.File
import java.util.*
/**
* antTask plugin for Kobalt
*
* Supports definition of per-project Kobalt tasks (similar to Ant targets)
* and execution of Ant tasks.
*
* val project = project {
* antTask("hello") {
* echo("Hello World")
* }
* }
*/
class AntTaskPlugin : BasePlugin(), ITaskContributor, IIncrementalTaskContributor {
override val name = PLUGIN_NAME
companion object {
const val PLUGIN_NAME = "AntTask"
const val ANT_TASKS = "antTasks"
}
override fun accept(project: Project): Boolean {
// enable plugin only for project with ant tasks
return project.projectProperties.get(ANT_TASKS) != null
}
// ITaskContributor
override fun tasksFor(project: Project, context: KobaltContext): List<DynamicTask> {
@Suppress("UNCHECKED_CAST")
val antTasks = project.projectProperties.get(AntTaskPlugin.ANT_TASKS) as ArrayList<AntTask>?
?: return emptyList()
// add new tasks for project
val dynamicTasks = ArrayList<DynamicTask>()
antTasks.filter { !it.isIncremental() }.forEach {
dynamicTasks.add(DynamicTask(this, it.taskName, it.description, it.group, project,
it.dependsOn.toList(), it.reverseDependsOn.toList(),
it.runBefore.toList(), it.runAfter.toList(), it.alwaysRunAfter.toList(),
closure = { project ->
it.executeTasks()
}))
}
return dynamicTasks
}
// IIncrementalTaskContributor
override fun incrementalTasksFor(project: Project, context: KobaltContext): List<IncrementalDynamicTask> {
@Suppress("UNCHECKED_CAST")
val antTasks = project.projectProperties.get(AntTaskPlugin.ANT_TASKS) as ArrayList<AntTask>?
?: return emptyList()
// add new tasks for project
val dynamicTasks = ArrayList<IncrementalDynamicTask>()
antTasks.filter { it.isIncremental() }.forEach {
dynamicTasks.add(IncrementalDynamicTask(context, this, it.taskName, it.description, it.group, project,
it.dependsOn.toList(), it.reverseDependsOn.toList(),
it.runBefore.toList(), it.runAfter.toList(), it.alwaysRunAfter.toList(),
incrementalClosure = { project ->
IncrementalTaskInfo(
inputChecksum = {
if (it.inputChecksum != null)
it.inputChecksum!!()
else if (it.inputFiles != null)
Md5.toMd5Directories(it.inputFiles.map { File(it) })
else
null
},
outputChecksum = {
if (it.outputChecksum != null)
it.outputChecksum!!()
else if (it.outputFiles != null)
Md5.toMd5Directories(it.outputFiles.map { File(it) })
else
null
},
task = { project ->
it.executeTasks()
},
context = context
)
}))
}
return dynamicTasks
}
}
class AntTask(val taskName: String,
val description: String = "", val group: String = AnnotationDefault.GROUP,
val dependsOn: Array<String> = arrayOf(), val reverseDependsOn: Array<String> = arrayOf(),
val runBefore: Array<String> = arrayOf(), val runAfter: Array<String> = arrayOf(),
val alwaysRunAfter: Array<String> = arrayOf(),
val inputFiles: Array<String>? = null, val outputFiles: Array<String>? = null,
val inputChecksum: (() -> String?)? = null, val outputChecksum: (() -> String?)? = null,
basedir: String = "", logLevel: LogLevel? = null,
context: AntContext? = null,
tasks: AntTask.() -> Unit)
: Ant(context ?: AntContext(basedir, logLevel ?: kobalt2antLogLevel()), execute = false, tasks = tasks as Ant.() -> Unit)
{
fun isIncremental() = inputFiles != null || inputChecksum != null || outputFiles != null || outputChecksum != null
fun executeTasks(): TaskResult {
// create basedir
if (context.basedir != "")
File(context.basedir).mkdirs()
// execute Ant tasks
try {
execute()
return TaskResult()
} catch (e: BuildException) {
return TaskResult(false, null, e.message)
}
}
override fun executeTask(task: Task) {
try {
super.executeTask(task)
} catch (e: BuildException) {
// always print stack trace
// if running from an IDE, clicking on
// BuildKt$project.invoke(Build.kt:123)
// in stack trace jump directly to the line in Build.kt
e.printStackTrace()
error("Ant task [${task.taskName}] failed: ${e.message}")
throw e
}
}
}
// use Kobalt log level
private fun kobalt2antLogLevel() =
when (KobaltLogger.LOG_LEVEL) {
0 -> LogLevel.WARN
1 -> LogLevel.INFO
2 -> LogLevel.VERBOSE
3 -> LogLevel.DEBUG
else -> LogLevel.INFO
}
@Directive
fun Project.antTask(taskName: String,
description: String = "", group: String = AnnotationDefault.GROUP,
dependsOn: Array<String> = arrayOf(), reverseDependsOn: Array<String> = arrayOf(),
runBefore: Array<String> = arrayOf(), runAfter: Array<String> = arrayOf(),
alwaysRunAfter: Array<String> = arrayOf(),
inputFiles: Array<String>? = null, outputFiles: Array<String>? = null,
inputChecksum: (() -> String?)? = null, outputChecksum: (() -> String?)? = null,
basedir: String = "", logLevel: LogLevel? = null,
context: AntContext? = null,
tasks: AntTask.() -> Unit)
= AntTask(taskName, description, group,
dependsOn, reverseDependsOn, runBefore, runAfter, alwaysRunAfter,
inputFiles, outputFiles,
inputChecksum, outputChecksum,
basedir, logLevel, context, tasks).apply {
@Suppress("UNCHECKED_CAST")
val antTasks = projectProperties.get(AntTaskPlugin.ANT_TASKS) as ArrayList<AntTask>?
?: ArrayList<AntTask>().apply { projectProperties.put(AntTaskPlugin.ANT_TASKS, this) }
antTasks.forEach {
if( it.taskName == taskName )
throw AssertionError("Duplicate antTask '$taskName' in project '$projectName'")
}
antTasks.add(this)
}
| apache-2.0 | 9fea65095c5fbe7481c0ae86477286d7 | 33.237374 | 122 | 0.697448 | 3.684239 | false | false | false | false |
google/intellij-community | build/tasks/src/org/jetbrains/intellij/build/tasks/reorderJars.kt | 1 | 7867 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet", "BlockingMethodInNonBlockingContext")
package org.jetbrains.intellij.build.tasks
import com.intellij.diagnostic.telemetry.use
import io.opentelemetry.api.common.AttributeKey
import it.unimi.dsi.fastutil.longs.LongSet
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.toPersistentList
import org.jetbrains.intellij.build.io.*
import org.jetbrains.intellij.build.tracer
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.util.*
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
private val excludedLibJars = java.util.Set.of("testFramework.core.jar", "testFramework.jar", "testFramework-java.jar")
private fun getClassLoadingLog(): InputStream {
val osName = System.getProperty("os.name")
val classifier = when {
osName.startsWith("windows", ignoreCase = true) -> "windows"
osName.startsWith("mac", ignoreCase = true) -> "mac"
else -> "linux"
}
return PackageIndexBuilder::class.java.classLoader.getResourceAsStream("$classifier/class-report.txt")!!
}
private val sourceToNames: Map<String, MutableList<String>> by lazy {
val sourceToNames = LinkedHashMap<String, MutableList<String>>()
getClassLoadingLog().bufferedReader().forEachLine {
val data = it.split(':', limit = 2)
val sourcePath = data[1]
// main jar is scrambled - doesn't make sense to reorder it
if (sourcePath != "lib/idea.jar") {
sourceToNames.computeIfAbsent(sourcePath) { mutableListOf() }.add(data[0])
}
}
sourceToNames
}
internal fun reorderJar(relativePath: String, file: Path) {
val orderedNames = sourceToNames.get(relativePath) ?: return
tracer.spanBuilder("reorder jar")
.setAttribute("relativePath", relativePath)
.setAttribute("file", file.toString())
.use {
reorderJar(jarFile = file, orderedNames = orderedNames, resultJarFile = file)
}
}
fun generateClasspath(homeDir: Path, mainJarName: String, antTargetFile: Path?): PersistentList<String> {
val libDir = homeDir.resolve("lib")
val appFile = libDir.resolve("app.jar")
tracer.spanBuilder("generate app.jar")
.setAttribute("dir", homeDir.toString())
.setAttribute("mainJarName", mainJarName)
.use {
transformFile(appFile) { target ->
writeNewZip(target) { zipCreator ->
val packageIndexBuilder = PackageIndexBuilder()
copyZipRaw(appFile, packageIndexBuilder, zipCreator) { entryName ->
entryName != "module-info.class"
}
val mainJar = libDir.resolve(mainJarName)
if (Files.exists(mainJar)) {
// no such file in community (no closed sources)
copyZipRaw(mainJar, packageIndexBuilder, zipCreator) { entryName ->
entryName != "module-info.class"
}
Files.delete(mainJar)
}
// packing to product.jar maybe disabled
val productJar = libDir.resolve("product.jar")
if (Files.exists(productJar)) {
copyZipRaw(productJar, packageIndexBuilder, zipCreator) { entryName ->
entryName != "module-info.class"
}
Files.delete(productJar)
}
packageIndexBuilder.writePackageIndex(zipCreator)
}
}
}
reorderJar("lib/app.jar", appFile)
tracer.spanBuilder("generate classpath")
.setAttribute("dir", homeDir.toString())
.use { span ->
val osName = System.getProperty("os.name")
val classifier = when {
osName.startsWith("windows", ignoreCase = true) -> "windows"
osName.startsWith("mac", ignoreCase = true) -> "mac"
else -> "linux"
}
val sourceToNames = readClassLoadingLog(
classLoadingLog = PackageIndexBuilder::class.java.classLoader.getResourceAsStream("$classifier/class-report.txt")!!,
rootDir = homeDir,
mainJarName = mainJarName
)
val files = computeAppClassPath(sourceToNames, libDir)
if (antTargetFile != null) {
files.add(antTargetFile)
}
val result = files.map { libDir.relativize(it).toString() }
span.setAttribute(AttributeKey.stringArrayKey("result"), result)
return result.toPersistentList()
}
}
private fun computeAppClassPath(sourceToNames: Map<Path, List<String>>, libDir: Path): LinkedHashSet<Path> {
// sorted to ensure stable performance results
val existing = TreeSet<Path>()
addJarsFromDir(libDir) { paths ->
paths.filterTo(existing) { !excludedLibJars.contains(it.fileName.toString()) }
}
val result = LinkedHashSet<Path>()
// add first - should be listed first
sourceToNames.keys.filterTo(result) { it.parent == libDir && existing.contains(it) }
result.addAll(existing)
return result
}
private inline fun addJarsFromDir(dir: Path, consumer: (Sequence<Path>) -> Unit) {
Files.newDirectoryStream(dir).use { stream ->
consumer(stream.asSequence().filter { it.toString().endsWith(".jar") })
}
}
internal fun readClassLoadingLog(classLoadingLog: InputStream, rootDir: Path, mainJarName: String): Map<Path, List<String>> {
val sourceToNames = LinkedHashMap<Path, MutableList<String>>()
classLoadingLog.bufferedReader().forEachLine {
val data = it.split(':', limit = 2)
var sourcePath = data[1]
if (sourcePath == "lib/idea.jar") {
sourcePath = "lib/$mainJarName"
}
sourceToNames.computeIfAbsent(rootDir.resolve(sourcePath)) { mutableListOf() }.add(data[0])
}
return sourceToNames
}
data class PackageIndexEntry(val path: Path, val classPackageIndex: LongSet, val resourcePackageIndex: LongSet)
private class EntryData(@JvmField val name: String, @JvmField val entry: ZipEntry)
fun reorderJar(jarFile: Path, orderedNames: List<String>, resultJarFile: Path): PackageIndexEntry {
val orderedNameToIndex = Object2IntOpenHashMap<String>(orderedNames.size)
orderedNameToIndex.defaultReturnValue(-1)
for ((index, orderedName) in orderedNames.withIndex()) {
orderedNameToIndex.put(orderedName, index)
}
val tempJarFile = resultJarFile.resolveSibling("${resultJarFile.fileName}_reorder")
val packageIndexBuilder = PackageIndexBuilder()
mapFileAndUse(jarFile) { sourceBuffer, fileSize ->
val entries = mutableListOf<EntryData>()
readZipEntries(sourceBuffer, fileSize) { name, entry ->
entries.add(EntryData(name, entry))
}
// ignore existing package index on reorder - a new one will be computed even if it is the same, do not optimize for simplicity
entries.sortWith(Comparator { o1, o2 ->
val o2p = o2.name
if ("META-INF/plugin.xml" == o2p) {
return@Comparator Int.MAX_VALUE
}
val o1p = o1.name
if ("META-INF/plugin.xml" == o1p) {
-Int.MAX_VALUE
}
else {
val i1 = orderedNameToIndex.getInt(o1p)
if (i1 == -1) {
if (orderedNameToIndex.containsKey(o2p)) 1 else 0
}
else {
val i2 = orderedNameToIndex.getInt(o2p)
if (i2 == -1) -1 else (i1 - i2)
}
}
})
writeNewZip(tempJarFile) { zipCreator ->
for (item in entries) {
packageIndexBuilder.addFile(item.name)
zipCreator.uncompressedData(item.name, item.entry.getByteBuffer())
}
packageIndexBuilder.writePackageIndex(zipCreator)
}
}
try {
Files.move(tempJarFile, resultJarFile, StandardCopyOption.REPLACE_EXISTING)
}
catch (e: Exception) {
throw e
}
finally {
Files.deleteIfExists(tempJarFile)
}
return PackageIndexEntry(path = resultJarFile, packageIndexBuilder.classPackageHashSet, packageIndexBuilder.resourcePackageHashSet)
} | apache-2.0 | 0a61fb7dbacc0df386515cea53dcf2b4 | 35.425926 | 133 | 0.691242 | 4.193497 | false | false | false | false |
Iterable/iterable-android-sdk | sample-apps/inbox-customization/app/src/main/java/com/iterable/inbox_customization/util/SingleFragmentActivity.kt | 1 | 1393 | package com.iterable.inbox_customization.util
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
class SingleFragmentActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val fragmentName = intent.getStringExtra(FRAGMENT_NAME)
val fragment: Fragment? = fragmentName?.let { Fragment.instantiate(this, it) }
val fragmentArguments = intent.getBundleExtra(FRAGMENT_ARGUMENTS)
fragment?.arguments = fragmentArguments
fragment?.let {
supportFragmentManager.beginTransaction()
.replace(android.R.id.content, it, "fragment").commit()
}
}
companion object {
const val FRAGMENT_NAME = "fragmentName"
const val FRAGMENT_ARGUMENTS = "fragmentArguments"
fun <T> createIntentWithFragment(activity: FragmentActivity, fragmentClass: Class<T>, arguments: Bundle? = null): Intent {
val intent = Intent(activity, SingleFragmentActivity::class.java)
intent.putExtra(FRAGMENT_NAME, fragmentClass.name)
intent.putExtra(FRAGMENT_ARGUMENTS, arguments)
return intent
}
}
} | mit | b3ff849ed7765360d089f529d338a7f1 | 38.828571 | 130 | 0.71285 | 5.065455 | false | false | false | false |
google/intellij-community | tools/ideTestingFramework/intellij.tools.ide.starter/src/com/intellij/ide/starter/runner/TestContainer.kt | 1 | 4101 | package com.intellij.ide.starter.runner
import com.intellij.ide.starter.bus.EventState
import com.intellij.ide.starter.bus.StarterBus
import com.intellij.ide.starter.ci.CIServer
import com.intellij.ide.starter.di.di
import com.intellij.ide.starter.ide.*
import com.intellij.ide.starter.models.IdeInfo
import com.intellij.ide.starter.models.TestCase
import com.intellij.ide.starter.path.GlobalPaths
import com.intellij.ide.starter.path.IDEDataPaths
import com.intellij.ide.starter.plugins.PluginInstalledState
import com.intellij.ide.starter.utils.catchAll
import com.intellij.ide.starter.utils.logOutput
import org.kodein.di.direct
import org.kodein.di.factory
import org.kodein.di.instance
import java.io.Closeable
import kotlin.io.path.div
/**
* [ciServer] - use [NoCIServer] for only local run. Otherwise - pass implementation of CIServer
*/
interface TestContainer<T> : Closeable {
val ciServer: CIServer
var useLatestDownloadedIdeBuild: Boolean
var testContext: IDETestContext
val setupHooks: MutableList<IDETestContext.() -> IDETestContext>
override fun close() {
catchAll { testContext.paths.close() }
logOutput("TestContainer $this disposed")
}
/**
* Allows to apply the common configuration to all created IDETestContext instances
*/
fun withSetupHook(hook: IDETestContext.() -> IDETestContext): T = apply {
setupHooks += hook
} as T
/**
* Makes the test use the latest available locally IDE build for testing.
*/
fun useLatestDownloadedIdeBuild(): T = apply {
assert(!ciServer.isBuildRunningOnCI)
useLatestDownloadedIdeBuild = true
} as T
/**
* @return <Build Number, InstalledIde>
*/
fun resolveIDE(ideInfo: IdeInfo): Pair<String, InstalledIde> {
return di.direct.factory<IdeInfo, IdeInstallator>().invoke(ideInfo).install(ideInfo)
}
fun installPerformanceTestingPluginIfMissing(context: IDETestContext) {
val performancePluginId = "com.jetbrains.performancePlugin"
context.pluginConfigurator.apply {
val pluginState = getPluginInstalledState(performancePluginId)
if (pluginState != PluginInstalledState.INSTALLED && pluginState != PluginInstalledState.BUNDLED_TO_IDE)
setupPluginFromPluginManager(performancePluginId, ide = context.ide)
}
}
/** Starting point to run your test */
fun initializeTestContext(testName: String, testCase: TestCase): IDETestContext {
logOutput("Resolving IDE build for $testName...")
val (buildNumber, ide) = resolveIDE(testCase.ideInfo)
require(ide.productCode == testCase.ideInfo.productCode) { "Product code of $ide must be the same as for $testCase" }
val testDirectory = (di.direct.instance<GlobalPaths>().testsDirectory / "${testCase.ideInfo.productCode}-$buildNumber") / testName
val paths = IDEDataPaths.createPaths(testName, testDirectory, testCase.useInMemoryFileSystem)
logOutput("Using IDE paths for $testName: $paths")
logOutput("IDE to run for $testName: $ide")
val projectHome = testCase.projectInfo?.downloadAndUnpackProject()
testContext = IDETestContext(paths, ide, testCase, testName, projectHome, patchVMOptions = { this }, ciServer = ciServer)
testContext = when (testCase.ideInfo == IdeProductProvider.AI) {
true -> testContext
.addVMOptionsPatch {
overrideDirectories(paths)
.withEnv("STUDIO_VM_OPTIONS", ide.patchedVMOptionsFile.toString())
}
false -> testContext
.disableInstantIdeShutdown()
.disableFusSendingOnIdeClose()
.disableLinuxNativeMenuForce()
.withGtk2OnLinux()
.disableGitLogIndexing()
.enableSlowOperationsInEdtInTests()
.collectOpenTelemetry()
.addVMOptionsPatch {
overrideDirectories(paths)
}
}
val contextWithAppliedHooks = setupHooks
.fold(testContext.updateGeneralSettings()) { acc, hook -> acc.hook() }
.apply { installPerformanceTestingPluginIfMissing(this) }
StarterBus.post(TestContextInitializedEvent(EventState.AFTER, contextWithAppliedHooks))
return contextWithAppliedHooks
}
} | apache-2.0 | 7e714ed73a4da828b35b83026cc36734 | 35.954955 | 134 | 0.739332 | 4.409677 | false | true | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/presentation/catalog/reducer/CatalogReducer.kt | 1 | 16632 | package org.stepik.android.presentation.catalog.reducer
import org.stepik.android.domain.banner.model.Banner
import org.stepik.android.domain.catalog.model.CatalogBlock
import org.stepik.android.domain.catalog.model.CatalogBlockContent
import org.stepik.android.domain.course.analytic.CourseViewSource
import org.stepik.android.presentation.banner.BannerFeature
import org.stepik.android.presentation.banner.reducer.BannerReducer
import org.stepik.android.presentation.catalog.CatalogFeature
import org.stepik.android.presentation.catalog.CatalogFeature.State
import org.stepik.android.presentation.catalog.CatalogFeature.Message
import org.stepik.android.presentation.catalog.CatalogFeature.Action
import org.stepik.android.presentation.course_continue_redux.CourseContinueFeature
import org.stepik.android.presentation.course_continue_redux.reducer.CourseContinueReducer
import org.stepik.android.presentation.course_list_redux.CourseListFeature
import org.stepik.android.presentation.course_list_redux.mapper.CourseListStateMapper
import org.stepik.android.presentation.course_list_redux.model.CatalogBlockStateWrapper
import org.stepik.android.presentation.course_list_redux.reducer.CourseListReducer
import org.stepik.android.presentation.enrollment.EnrollmentFeature
import org.stepik.android.presentation.filter.FiltersFeature
import org.stepik.android.presentation.filter.reducer.FiltersReducer
import org.stepik.android.presentation.progress.ProgressFeature
import org.stepik.android.presentation.stories.StoriesFeature
import org.stepik.android.presentation.stories.reducer.StoriesReducer
import org.stepik.android.presentation.user_courses.UserCoursesFeature
import org.stepik.android.presentation.wishlist.WishlistFeature
import ru.nobird.app.core.model.safeCast
import ru.nobird.app.presentation.redux.reducer.StateReducer
import javax.inject.Inject
class CatalogReducer
@Inject
constructor(
private val storiesReducer: StoriesReducer,
private val filtersReducer: FiltersReducer,
private val courseListReducer: CourseListReducer,
private val courseContinueReducer: CourseContinueReducer,
private val bannerReducer: BannerReducer,
private val courseListStateMapper: CourseListStateMapper
) : StateReducer<State, Message, Action> {
override fun reduce(state: State, message: Message): Pair<State, Set<Action>> =
when (message) {
// <editor-fold desc="Blocks Messages">
is Message.InitMessage -> {
if (state.blocksState is CatalogFeature.BlocksState.Idle ||
state.blocksState is CatalogFeature.BlocksState.Error && message.forceUpdate
) {
state.copy(blocksState = CatalogFeature.BlocksState.Loading) to setOf(Action.FetchCatalogBlocks)
} else {
null
}
}
is Message.FetchCatalogBlocksSuccess -> {
if (state.blocksState is CatalogFeature.BlocksState.Loading) {
val collections = message.collections
.sortedBy(CatalogBlock::position)
.mapNotNull { catalogBlockItem ->
when (catalogBlockItem.content) {
is CatalogBlockContent.FullCourseList ->
CatalogBlockStateWrapper.FullCourseList(catalogBlock = catalogBlockItem, state = CourseListFeature.State.Idle)
is CatalogBlockContent.SimpleCourseLists -> {
if (catalogBlockItem.appearance == CatalogBlockContent.APPEARANCE_SIMPLE_COURSE_LISTS_GRID) {
CatalogBlockStateWrapper.SimpleCourseListsGrid(catalogBlockItem, catalogBlockItem.content)
} else {
CatalogBlockStateWrapper.SimpleCourseListsDefault(catalogBlockItem, catalogBlockItem.content)
}
}
is CatalogBlockContent.AuthorsList ->
CatalogBlockStateWrapper.AuthorList(catalogBlockItem, catalogBlockItem.content)
is CatalogBlockContent.RecommendedCourses ->
CatalogBlockStateWrapper.RecommendedCourseList(catalogBlockItem, CourseListFeature.State.Idle)
is CatalogBlockContent.SpecializationsList ->
CatalogBlockStateWrapper.SpecializationList(catalogBlockItem, catalogBlockItem.content)
else ->
null
}
}
state.copy(blocksState = CatalogFeature.BlocksState.Content(collections)) to emptySet()
} else {
null
}
}
is Message.FetchCatalogBlocksError -> {
if (state.blocksState is CatalogFeature.BlocksState.Loading) {
state.copy(blocksState = CatalogFeature.BlocksState.Error) to emptySet()
} else {
null
}
}
// </editor-fold>
is Message.StoriesMessage -> {
val (storiesState, storiesActions) = storiesReducer.reduce(state.storiesState, message.message)
state.copy(storiesState = storiesState) to storiesActions.map(Action::StoriesAction).toSet()
}
is Message.FiltersMessage -> {
val (storiesState, collectionsState, bannerState) =
if (message.message is FiltersFeature.Message.LoadFiltersSuccess) {
Triple(
StoriesFeature.State.Loading,
CatalogFeature.BlocksState.Loading,
BannerFeature.State.Loading
)
} else {
Triple(
state.storiesState,
state.blocksState,
state.bannerState
)
}
val refreshAction =
if (message.message is FiltersFeature.Message.LoadFiltersSuccess) {
setOf(Action.StoriesAction(StoriesFeature.Action.FetchStories), Action.FetchCatalogBlocks, Action.BannerAction(BannerFeature.Action.LoadBanners(Banner.Screen.CATALOG)))
} else {
emptySet()
}
val (filtersState, filtersActions) = filtersReducer.reduce(state.filtersState, message.message)
state.copy(storiesState = storiesState, blocksState = collectionsState, filtersState = filtersState, bannerState = bannerState) to filtersActions.map(Action::FiltersAction).toSet() + refreshAction
}
is Message.CourseListMessage -> {
if (state.blocksState is CatalogFeature.BlocksState.Content) {
val courseListActionsSet = mutableSetOf<CourseListFeature.Action>()
val blocks = state.blocksState
.blocks
.map { collection ->
if (collection.id == message.id) {
when (collection) {
is CatalogBlockStateWrapper.FullCourseList -> {
val (courseListState, courseListActions) =
courseListReducer.reduce(collection.state, message.message)
courseListActionsSet += courseListActions
collection.copy(state = courseListState)
}
is CatalogBlockStateWrapper.RecommendedCourseList -> {
val (courseListState, courseListActions) =
courseListReducer.reduce(collection.state, message.message)
courseListActionsSet += courseListActions
collection.copy(state = courseListState)
}
else ->
collection
}
} else {
collection
}
}
val actions = courseListActionsSet.map(Action::CourseListAction).toSet()
state.copy(blocksState = CatalogFeature.BlocksState.Content(blocks)) to actions
} else {
null
}
}
is Message.CourseContinueMessage -> {
val (courseContinueState, courseContinueActions) = courseContinueReducer.reduce(state.courseContinueState, message.message)
val actions = courseContinueActions
.map {
if (it is CourseContinueFeature.Action.ViewAction) {
Action.ViewAction.CourseContinueViewAction(it)
} else {
Action.CourseContinueAction(it)
}
}
.toSet()
state.copy(courseContinueState = courseContinueState) to actions
}
is Message.UserCourseMessage -> {
if (state.blocksState is CatalogFeature.BlocksState.Content &&
message.message is UserCoursesFeature.Message.UserCourseOperationUpdate
) {
val updatedCollection = updateCourseLists(state.blocksState.blocks) { item ->
when (item) {
is CatalogBlockStateWrapper.FullCourseList ->
item.copy(state = mapUserCourseMessageToCourseListState(item.state, message.message))
is CatalogBlockStateWrapper.RecommendedCourseList ->
item.copy(state = mapUserCourseMessageToCourseListState(item.state, message.message))
else ->
return@updateCourseLists null
}
}
state.copy(blocksState = state.blocksState.copy(blocks = updatedCollection)) to emptySet()
} else {
null
}
}
is Message.ProgressMessage -> {
if (state.blocksState is CatalogFeature.BlocksState.Content &&
message.message is ProgressFeature.Message.ProgressUpdate
) {
val updatedCollection = updateCourseLists(state.blocksState.blocks) { item ->
when (item) {
is CatalogBlockStateWrapper.FullCourseList ->
item.copy(state = mapProgressMessageToCourseListState(item.state, message.message))
is CatalogBlockStateWrapper.RecommendedCourseList ->
item.copy(state = mapProgressMessageToCourseListState(item.state, message.message))
else ->
return@updateCourseLists null
}
}
state.copy(blocksState = state.blocksState.copy(blocks = updatedCollection)) to emptySet()
} else {
null
}
}
is Message.EnrollmentMessage -> {
if (state.blocksState is CatalogFeature.BlocksState.Content && message.message is EnrollmentFeature.Message.EnrollmentMessage) {
val courseListActions = mutableSetOf<CourseListFeature.Action>()
val updatedCollection = updateCourseLists(state.blocksState.blocks) { item ->
when (item) {
is CatalogBlockStateWrapper.FullCourseList -> {
val courseListId = item.catalogBlock.content.safeCast<CatalogBlockContent.FullCourseList>()?.courseList?.id ?: -1
courseListActions +=
CourseListFeature.Action.FetchCourseAfterEnrollment(item.id, message.message.enrolledCourse.id, CourseViewSource.Collection(courseListId))
item.copy(state = mapEnrollmentMessageToCourseListState(item.state, message.message))
}
is CatalogBlockStateWrapper.RecommendedCourseList -> {
courseListActions +=
CourseListFeature.Action.FetchCourseAfterEnrollment(item.id, message.message.enrolledCourse.id, CourseViewSource.Recommendation)
item.copy(state = mapEnrollmentMessageToCourseListState(item.state, message.message))
}
else ->
return@updateCourseLists null
}
}
state.copy(blocksState = state.blocksState.copy(blocks = updatedCollection)) to courseListActions.map(Action::CourseListAction).toSet()
} else {
null
}
}
is Message.WishlistMessage -> {
if (state.blocksState is CatalogFeature.BlocksState.Content &&
message.message is WishlistFeature.Message.WishlistOperationUpdate
) {
val updatedCollection = updateCourseLists(state.blocksState.blocks) { item ->
when (item) {
is CatalogBlockStateWrapper.FullCourseList ->
item.copy(state = mapWishlistMessageToCourseListState(item.state, message.message))
is CatalogBlockStateWrapper.RecommendedCourseList ->
item.copy(state = mapWishlistMessageToCourseListState(item.state, message.message))
else ->
return@updateCourseLists null
}
}
state.copy(blocksState = state.blocksState.copy(blocks = updatedCollection)) to emptySet()
} else {
null
}
}
is Message.BannerMessage -> {
val (bannerState, bannerActions) = bannerReducer.reduce(state.bannerState, message.message)
state.copy(bannerState = bannerState) to bannerActions.map(Action::BannerAction).toSet()
}
} ?: state to emptySet()
private fun updateCourseLists(
blocks: List<CatalogBlockStateWrapper>,
mapper: (CatalogBlockStateWrapper) -> CatalogBlockStateWrapper?
): List<CatalogBlockStateWrapper> =
blocks.mapNotNull { item ->
if (item is CatalogBlockStateWrapper.FullCourseList || item is CatalogBlockStateWrapper.RecommendedCourseList) {
mapper(item)
} else {
item
}
}
private fun mapUserCourseMessageToCourseListState(courseListState: CourseListFeature.State, message: UserCoursesFeature.Message.UserCourseOperationUpdate): CourseListFeature.State =
courseListStateMapper.mapToUserCourseUpdate(courseListState, message.userCourse)
private fun mapProgressMessageToCourseListState(courseListState: CourseListFeature.State, message: ProgressFeature.Message.ProgressUpdate): CourseListFeature.State =
courseListStateMapper.mergeWithCourseProgress(courseListState, message.progress)
private fun mapEnrollmentMessageToCourseListState(courseListState: CourseListFeature.State, message: EnrollmentFeature.Message.EnrollmentMessage): CourseListFeature.State =
courseListStateMapper.mapToEnrollmentUpdateState(courseListState, message.enrolledCourse)
private fun mapWishlistMessageToCourseListState(courseListState: CourseListFeature.State, message: WishlistFeature.Message.WishlistOperationUpdate): CourseListFeature.State =
courseListStateMapper.mapToWishlistUpdate(courseListState, message.wishlistOperationData)
} | apache-2.0 | b4f7203cbcf81d5435ff79ca2f4d53b7 | 54.443333 | 212 | 0.578884 | 6.043605 | false | false | false | false |
allotria/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/framework/Timeouts.kt | 6 | 1430 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testGuiFramework.framework
import org.fest.swing.timing.Pause
import org.fest.swing.timing.Timeout
import java.util.concurrent.TimeUnit
object Timeouts {
val defaultTimeout = Timeout.timeout(2, TimeUnit.MINUTES)
val noTimeout = Timeout.timeout(0, TimeUnit.SECONDS)
val seconds01 = Timeout.timeout(1, TimeUnit.SECONDS)
val seconds02 = Timeout.timeout(2, TimeUnit.SECONDS)
val seconds03 = Timeout.timeout(3, TimeUnit.SECONDS)
val seconds05 = Timeout.timeout(5, TimeUnit.SECONDS)
val seconds10 = Timeout.timeout(10, TimeUnit.SECONDS)
val seconds30 = Timeout.timeout(30, TimeUnit.SECONDS)
val minutes01 = Timeout.timeout(1, TimeUnit.MINUTES)
val minutes02 = Timeout.timeout(2, TimeUnit.MINUTES)
val minutes05 = Timeout.timeout(5, TimeUnit.MINUTES)
val minutes10 = Timeout.timeout(10, TimeUnit.MINUTES)
val minutes15 = Timeout.timeout(15, TimeUnit.MINUTES)
val minutes20 = Timeout.timeout(20, TimeUnit.MINUTES)
val hours01 = Timeout.timeout(1, TimeUnit.HOURS)
}
fun Timeout.wait() {
Pause.pause(this.duration())
}
fun Timeout.toPrintable(): String {
return when {
this.duration() >= 60000 -> "${this.duration() / 60000}(m)"
this.duration() >= 1000 -> "${this.duration() / 1000}(s)"
else -> "${this.duration()}(ms)"
}
}
| apache-2.0 | 4035e7b1d26beaca5db8e05e694cbaba | 36.631579 | 140 | 0.735664 | 3.638677 | false | false | false | false |
mtransitapps/mtransit-for-android | src/main/java/org/mtransit/android/ui/favorites/FavoritesViewModel.kt | 1 | 6636 | package org.mtransit.android.ui.favorites
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.liveData
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import org.mtransit.android.commons.ComparatorUtils
import org.mtransit.android.commons.MTLog
import org.mtransit.android.commons.StringUtils
import org.mtransit.android.commons.data.POI
import org.mtransit.android.commons.provider.POIProviderContract
import org.mtransit.android.data.DataSourceType.POIManagerTypeShortNameComparator
import org.mtransit.android.data.Favorite
import org.mtransit.android.data.IAgencyProperties
import org.mtransit.android.data.POIManager
import org.mtransit.android.datasource.DataSourcesRepository
import org.mtransit.android.datasource.POIRepository
import org.mtransit.android.provider.FavoriteRepository
import org.mtransit.android.ui.MTViewModelWithLocation
import org.mtransit.android.ui.view.common.PairMediatorLiveData
import org.mtransit.android.util.UITimeUtils
import javax.inject.Inject
@HiltViewModel
class FavoritesViewModel @Inject constructor(
private val dataSourcesRepository: DataSourcesRepository,
private val poiRepository: POIRepository,
private val favoriteRepository: FavoriteRepository,
private val poiTypeShortNameComparator: POIManagerTypeShortNameComparator,
) : MTViewModelWithLocation() {
companion object {
private val LOG_TAG = FavoritesViewModel::class.java.simpleName
private val POI_ALPHA_COMPARATOR = POIAlphaComparator()
}
override fun getLogTag(): String = LOG_TAG
fun onFavoriteUpdated() {
_favoriteUpdatedTrigger.value = (_favoriteUpdatedTrigger.value ?: 0) + 1
}
private val _favoriteUpdatedTrigger = MutableLiveData(0)
private val _agencies = this.dataSourcesRepository.readingAllAgenciesBase() // #onModuleChanged
val favoritePOIs: LiveData<List<POIManager>?> =
PairMediatorLiveData(_favoriteUpdatedTrigger, _agencies).switchMap { (_, agencies) ->
liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) {
emit(getFavorites(agencies))
}
}
private fun getFavorites(agencies: List<IAgencyProperties>?): List<POIManager>? {
if (agencies.isNullOrEmpty()) {
MTLog.d(this, "getFavorites() > SKIP (no agencies)")
return null // loading
}
val favorites = this.favoriteRepository.findFavorites()
if (favorites.isEmpty()) {
MTLog.d(this, "getFavorites() > SKIP (no favorites)")
return emptyList() // empty (no favorites)
}
val pois = mutableListOf<POIManager>()
val authorityToUUIDs = favorites.groupBy({ POI.POIUtils.extractAuthorityFromUUID(it.fkId).orEmpty() }, { it.fkId })
authorityToUUIDs
.filterKeys { it.isNotEmpty() }
.filterValues { it.isNotEmpty() }
.forEach { (authority, authorityUUIDs) ->
this.poiRepository.findPOIMs(authority, POIProviderContract.Filter.getNewUUIDsFilter(authorityUUIDs))
.takeIf { !it.isNullOrEmpty() }
?.let { agencyPOIs ->
agencyPOIs.sortedWith(POI_ALPHA_COMPARATOR)
pois.addAll(agencyPOIs)
}
}
if (pois.isNotEmpty()) {
pois.sortWith(poiTypeShortNameComparator)
}
val uuidToFavoriteFolderId = favorites.associateBy({ it.fkId }, { it.folderId })
val favFolderIds = mutableSetOf<Int>()
pois.forEach { favPOIM ->
val favFolderId = uuidToFavoriteFolderId[favPOIM.poi.uuid]
if (favFolderId != null && favFolderId > FavoriteRepository.DEFAULT_FOLDER_ID) {
favPOIM.poi.dataSourceTypeId = this.favoriteRepository.generateFavoriteFolderId(favFolderId)
favFolderIds.add(favFolderId)
}
}
var textMessageId = UITimeUtils.currentTimeMillis()
val favFolders = this.favoriteRepository.findFoldersList()
favFolders
.filter { favFolder -> favFolder.id > FavoriteRepository.DEFAULT_FOLDER_ID && !favFolderIds.contains(favFolder.id) }
.forEach { favoriteFolder ->
pois.add(getNewEmptyFolder(textMessageId++, favoriteFolder.id))
}
if (pois.isNotEmpty()) {
pois.sortWith(FavoriteFolderNameComparator(this.favoriteRepository, favFolders))
}
return pois
}
private fun getNewEmptyFolder(textMessageId: Long, favoriteFolderId: Int): POIManager {
return POIManager(this.favoriteRepository.generateFavEmptyFavPOI(textMessageId).also {
it.dataSourceTypeId = this.favoriteRepository.generateFavoriteFolderId(favoriteFolderId)
})
}
class POIAlphaComparator : Comparator<POIManager?> {
override fun compare(lhs: POIManager?, rhs: POIManager?): Int {
val lhsPoi = lhs?.poi
val rhsPoi = rhs?.poi
if (lhsPoi == null && rhsPoi == null) {
return ComparatorUtils.SAME
}
if (lhsPoi == null) {
return ComparatorUtils.BEFORE
} else if (rhsPoi == null) {
return ComparatorUtils.AFTER
}
return lhsPoi.compareToAlpha(null, rhsPoi)
}
}
class FavoriteFolderNameComparator(
private val favoriteRepository: FavoriteRepository,
private val favFolders: Collection<Favorite.Folder>
) : Comparator<POIManager?> {
override fun compare(lhs: POIManager?, rhs: POIManager?): Int {
val lhsPoi = lhs?.poi
val rhsPoi = rhs?.poi
if (lhsPoi == null && rhsPoi == null) {
return ComparatorUtils.SAME
}
if (lhsPoi == null) {
return ComparatorUtils.BEFORE
} else if (rhsPoi == null) {
return ComparatorUtils.AFTER
}
val lFavFolderId = favoriteRepository.getFavoriteDataSourceIdOrNull(lhsPoi.dataSourceTypeId)
val lFavFolderName = favFolders.singleOrNull { it.id == lFavFolderId }?.name ?: StringUtils.EMPTY
val rFavFolderId = favoriteRepository.getFavoriteDataSourceIdOrNull(rhsPoi.dataSourceTypeId)
val rFavFolderName = favFolders.singleOrNull { it.id == rFavFolderId }?.name ?: StringUtils.EMPTY
return lFavFolderName.compareTo(rFavFolderName)
}
}
} | apache-2.0 | 46e369f37addd615940704b8a72459f0 | 42.953642 | 128 | 0.6739 | 4.743388 | false | false | false | false |
googlecodelabs/android-performance | benchmarking/app/src/main/java/com/example/macrobenchmark_codelab/ui/components/GradientTintedIconButton.kt | 1 | 3883 | /*
* 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.macrobenchmark_codelab.ui.components
import android.content.res.Configuration
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Icon
import androidx.compose.material.Surface
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.macrobenchmark_codelab.ui.theme.JetsnackTheme
@Composable
fun JetsnackGradientTintedIconButton(
imageVector: ImageVector,
onClick: () -> Unit,
contentDescription: String?,
modifier: Modifier = Modifier,
colors: List<Color> = JetsnackTheme.colors.interactiveSecondary
) {
val interactionSource = remember { MutableInteractionSource() }
// This should use a layer + srcIn but needs investigation
val border = Modifier.fadeInDiagonalGradientBorder(
showBorder = true,
colors = JetsnackTheme.colors.interactiveSecondary,
shape = CircleShape
)
val pressed by interactionSource.collectIsPressedAsState()
val background = if (pressed) {
Modifier.offsetGradientBackground(colors, 200f, 0f)
} else {
Modifier.background(JetsnackTheme.colors.uiBackground)
}
val blendMode = if (JetsnackTheme.colors.isDark) BlendMode.Darken else BlendMode.Plus
val modifierColor = if (pressed) {
Modifier.diagonalGradientTint(
colors = listOf(
JetsnackTheme.colors.textSecondary,
JetsnackTheme.colors.textSecondary
),
blendMode = blendMode
)
} else {
Modifier.diagonalGradientTint(
colors = colors,
blendMode = blendMode
)
}
Surface(
modifier = modifier
.clickable(
onClick = onClick,
interactionSource = interactionSource,
indication = null
)
.clip(CircleShape)
.then(border)
.then(background),
color = Color.Transparent
) {
Icon(
imageVector = imageVector,
contentDescription = contentDescription,
modifier = modifierColor
)
}
}
@Preview("default")
@Preview("dark theme", uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun GradientTintedIconButtonPreview() {
JetsnackTheme {
JetsnackGradientTintedIconButton(
imageVector = Icons.Default.Add,
onClick = {},
contentDescription = "Demo",
modifier = Modifier.padding(4.dp)
)
}
}
| apache-2.0 | a408f073c10026d7580cd8b3631bf7a9 | 33.981982 | 89 | 0.7077 | 4.78202 | false | false | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/refactoring/suggested/NewIdentifierWatcher.kt | 1 | 3221 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.suggested
import com.intellij.lang.Language
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.util.TextRange
import java.util.*
class NewIdentifierWatcher(private val maxIdentifiers: Int) {
init {
require(maxIdentifiers > 0)
}
private class Ref(var marker: RangeMarker)
private val newIdentifierMarkers = ArrayDeque<Ref>()
val lastDocument: Document?
get() = newIdentifierMarkers.firstOrNull()?.marker?.takeIf { it.isValid }?.document
fun lastNewIdentifierRanges(): List<TextRange> {
return newIdentifierMarkers.map { it.marker.range!! }
}
fun documentChanged(event: DocumentEvent, language: Language) {
val document = event.document
val chars = document.charsSequence
if (document != lastDocument) {
reset()
}
val refactoringSupport = SuggestedRefactoringSupport.forLanguage(language) ?: return
val iterator = newIdentifierMarkers.iterator()
while (iterator.hasNext()) {
val ref = iterator.next()
val range = ref.marker.range
if (range == null) {
iterator.remove()
continue
}
var start = range.startOffset
while (start > 0 && refactoringSupport.isIdentifierPart(chars[start - 1])) {
start--
}
var end = range.endOffset
while (end < document.textLength && refactoringSupport.isIdentifierPart(chars[end])) {
end++
}
if (start != range.startOffset || end != range.endOffset) {
ref.marker.dispose()
ref.marker = document.createRangeMarker(start, end)
}
}
if (isNewIdentifierInserted(event, refactoringSupport)) {
if (newIdentifierMarkers.size == maxIdentifiers) {
val marker = newIdentifierMarkers.removeFirst().marker
marker.dispose()
}
val marker = document.createRangeMarker(event.newRange)
newIdentifierMarkers.addLast(Ref(marker))
}
else {
if (newIdentifierMarkers.any { it.marker.range!!.contains(event.newRange) }) return
if (event.newFragment.any { refactoringSupport.isIdentifierStart(it) }) {
reset()
}
}
}
private fun reset() {
newIdentifierMarkers.forEach { it.marker.dispose() }
newIdentifierMarkers.clear()
}
private fun isNewIdentifierInserted(event: DocumentEvent, refactoringSupport: SuggestedRefactoringSupport): Boolean {
if (!refactoringSupport.isIdentifierLike(event.newFragment)) return false
val chars = event.document.charsSequence
val start = event.offset
val end = event.offset + event.newLength
if (start > 0 && refactoringSupport.isIdentifierPart(chars[start - 1])) return false
if (end < event.document.textLength && refactoringSupport.isIdentifierPart(chars[end])) return false
return true
}
private fun SuggestedRefactoringSupport.isIdentifierLike(text: CharSequence) =
text.isNotEmpty() && isIdentifierStart(text[0]) && text.all { isIdentifierPart(it) }
}
| apache-2.0 | d5b5f54175daea8d06e6f4320f615d21 | 32.552083 | 140 | 0.703508 | 4.473611 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/test/kotlin/com/vrem/wifianalyzer/wifi/model/WiFiVirtualTest.kt | 1 | 2619 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.wifi.model
import com.vrem.util.EMPTY
import org.junit.Assert.assertEquals
import org.junit.Test
class WiFiVirtualTest {
@Test
fun testWiFiVirtualWithVirtualBSSID() {
// setup
val wiFiDetail = WiFiDetail(
WiFiIdentifier("SSID1", "20:cf:30:ce:1d:71"),
String.EMPTY,
WiFiSignal(2432, 2432, WiFiWidth.MHZ_20, -50, true),
WiFiAdditional.EMPTY)
// execute
val actual = wiFiDetail.wiFiVirtual
// validate
assertEquals(":cf:30:ce:1d:7", actual.bssid)
assertEquals(2432, actual.frequency)
assertEquals(":cf:30:ce:1d:7-" + 2432, actual.key)
}
@Test
fun testWiFiVirtualWithRegularBSSIDWhenBSSIDShort() {
// setup
val wiFiDetail = WiFiDetail(
WiFiIdentifier("SSID1", "20:cf:30:ce:1d:7"),
String.EMPTY,
WiFiSignal(2432, 2432, WiFiWidth.MHZ_20, -50, true),
WiFiAdditional.EMPTY)
// execute
val actual = wiFiDetail.wiFiVirtual
// validate
assertEquals("20:cf:30:ce:1d:7", actual.bssid)
assertEquals(2432, actual.frequency)
assertEquals("20:cf:30:ce:1d:7-" + 2432, actual.key)
}
@Test
fun testWiFiVirtualWithRegularBSSIDWhenBSSIDLong() {
// setup
val wiFiDetail = WiFiDetail(
WiFiIdentifier("SSID1", "20:cf:30:ce:1d:71:"),
String.EMPTY,
WiFiSignal(2432, 2432, WiFiWidth.MHZ_20, -50, true),
WiFiAdditional.EMPTY)
// execute
val actual = wiFiDetail.wiFiVirtual
// validate
assertEquals("20:cf:30:ce:1d:71:", actual.bssid)
assertEquals(2432, actual.frequency)
assertEquals("20:cf:30:ce:1d:71:-" + 2432, actual.key)
}
} | gpl-3.0 | 12de89d403f29f6f140218c7d808f143 | 33.933333 | 90 | 0.631539 | 3.823358 | false | true | false | false |
blokadaorg/blokada | android5/app/src/main/java/ui/advanced/packs/PacksFragment.kt | 1 | 3315 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package ui.advanced.packs
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.tabs.TabLayout
import model.Pack
import org.blokada.R
import ui.PacksViewModel
import ui.app
class PacksFragment : Fragment() {
private lateinit var vm: PacksViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
activity?.let {
vm = ViewModelProvider(it.app()).get(PacksViewModel::class.java)
}
val root = inflater.inflate(R.layout.fragment_packs, container, false)
val recycler: RecyclerView = root.findViewById(R.id.pack_recyclerview)
val tabs: TabLayout = root.findViewById(R.id.pack_tabs)
val adapter = PacksAdapter(interaction = object : PacksAdapter.Interaction {
override fun onClick(pack: Pack) {
val nav = findNavController()
nav.navigate(PacksFragmentDirections.actionNavigationPacksToPackDetailFragment(pack.id))
}
override fun onSwitch(pack: Pack, on: Boolean) {
if (on) {
vm.install(pack)
} else {
vm.uninstall(pack)
}
}
})
recycler.adapter = adapter
recycler.layoutManager = LinearLayoutManager(context)
vm.packs.observe(viewLifecycleOwner, Observer {
adapter.swapData(it)
})
// Needed for dynamic translation
tabs.getTabAt(0)?.text = getString(R.string.pack_category_highlights)
tabs.getTabAt(1)?.text = getString(R.string.pack_category_active)
tabs.getTabAt(2)?.text = getString(R.string.pack_category_all)
when(vm.getFilter()) {
PacksViewModel.Filter.ACTIVE -> tabs.selectTab(tabs.getTabAt(1))
PacksViewModel.Filter.ALL -> tabs.selectTab(tabs.getTabAt(2))
else -> tabs.selectTab(tabs.getTabAt(0))
}
tabs.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabReselected(tab: TabLayout.Tab?) {}
override fun onTabUnselected(tab: TabLayout.Tab?) {}
override fun onTabSelected(tab: TabLayout.Tab) {
val filtering = when(tab.position) {
0 -> PacksViewModel.Filter.HIGHLIGHTS
1 -> PacksViewModel.Filter.ACTIVE
else -> PacksViewModel.Filter.ALL
}
vm.filter(filtering)
}
})
return root
}
} | mpl-2.0 | bb115ae1bba3050a377107bb3566e51f | 31.821782 | 104 | 0.640917 | 4.596394 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/delegatedProperty/genericDelegateUncheckedCast2.kt | 1 | 839 | // IGNORE_BACKEND: JVM, JS, NATIVE
import kotlin.reflect.KProperty
class Delegate<T>(var inner: T) {
operator fun getValue(t: Any?, p: KProperty<*>): T = inner
operator fun setValue(t: Any?, p: KProperty<*>, i: T) { inner = i }
}
val del = Delegate("zzz")
class A {
inner class B {
var prop: String by del
}
}
inline fun asFailsWithCCE(block: () -> Unit) {
try {
block()
}
catch (e: ClassCastException) {
return
}
catch (e: Throwable) {
throw AssertionError("Should throw ClassCastException, got $e")
}
throw AssertionError("Should throw ClassCastException, no exception thrown")
}
fun box(): String {
val c = A().B()
(del as Delegate<String?>).inner = null
asFailsWithCCE { c.prop } // does not fail in JVM, JS due KT-8135.
return "OK"
} | apache-2.0 | aee98762aafa5c2b808dae800d4d8c27 | 21.105263 | 80 | 0.606675 | 3.696035 | false | false | false | false |
exponent/exponent | android/expoview/src/main/java/host/exp/exponent/experience/ErrorConsoleFragment.kt | 2 | 1945 | package host.exp.exponent.experience
import android.widget.ArrayAdapter
import android.app.Activity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import host.exp.exponent.Constants
import host.exp.exponent.kernel.ExponentError
import host.exp.expoview.databinding.ErrorConsoleFragmentBinding
class ErrorConsoleFragment : Fragment() {
private var _binding: ErrorConsoleFragmentBinding? = null
private val binding get() = _binding!!
lateinit var adapter: ArrayAdapter<ExponentError>
private fun onClickHome() {
val activity: Activity? = activity
if (activity is ErrorActivity) {
activity.onClickHome()
}
}
private fun onClickReload() {
val activity: Activity? = activity
if (activity is ErrorActivity) {
activity.onClickReload()
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = ErrorConsoleFragmentBinding.inflate(inflater, container, false)
binding.consoleHomeButton.setOnClickListener { onClickHome() }
binding.consoleReloadButton.setOnClickListener { onClickReload() }
val bundle = arguments
val manifestUrl = bundle!!.getString(ErrorActivity.MANIFEST_URL_KEY)
val isHomeError = bundle.getBoolean(ErrorActivity.IS_HOME_KEY, false)
if (isHomeError || manifestUrl == null || manifestUrl == Constants.INITIAL_URL) {
// Cannot go home in any of these cases
binding.consoleHomeButton.visibility = View.GONE
}
val errorQueue = ErrorActivity.errorList
synchronized(errorQueue) {
val adapter = ErrorQueueAdapter(requireContext(), errorQueue)
binding.listView.adapter = adapter
this.adapter = adapter
}
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| bsd-3-clause | 4a808f2f86893fa078d1038450fa9a94 | 28.923077 | 85 | 0.738303 | 4.587264 | false | false | false | false |
smmribeiro/intellij-community | platform/vcs-api/src/com/intellij/openapi/vcs/merge/MergeDialogCustomizer.kt | 12 | 4127 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.merge
import com.intellij.diff.DiffEditorTitleCustomizer
import com.intellij.openapi.diff.DiffBundle
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.history.VcsRevisionNumber
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.annotations.ApiStatus
/**
* Provides custom titles and messages used in the MultipleFileMergeDialog and DiffTools invoked from it.
*/
@ApiStatus.OverrideOnly
open class MergeDialogCustomizer {
companion object {
val DEFAULT_CUSTOMIZER_LIST = DiffEditorTitleCustomizerList(null, null, null)
}
/**
* Returns the description that is shown above the list of conflicted files.
*
* @param files the files that have conflicted changes and are shown in the dialog.
*/
open fun getMultipleFileMergeDescription(files: MutableCollection<VirtualFile>): @NlsContexts.Label String = ""
/**
* Returns the title of the merge dialog invoked for a 3-way merge of a file (after pressing the "Merge" button).
*
* @param file the file that is being merged.
*/
open fun getMergeWindowTitle(file: VirtualFile): @NlsContexts.DialogTitle String =
VcsBundle.message("multiple.file.merge.request.title", FileUtil.toSystemDependentName(file.presentableUrl))
/**
* Returns the title that is shown above the left panel in the 3-way merge dialog.
*
* @param file the file that is being merged.
* @see getTitleCustomizerList
*/
open fun getLeftPanelTitle(file: VirtualFile): @NlsContexts.Label String = DiffBundle.message("merge.version.title.our")
/**
* Returns the title that is shown above the center panel in the 3-way merge dialog.
*
* @param file the file that is being merged.
* @see getTitleCustomizerList
*/
open fun getCenterPanelTitle(file: VirtualFile): @NlsContexts.Label String = DiffBundle.message("merge.version.title.base")
/**
* Returns the title that is shown above the right panel in the 3-way merge dialog.
*
* @param file the file that is being merged.
* @param revisionNumber the revision number of the file at the right. Can be null if unknown.
* @see getTitleCustomizerList
*/
open fun getRightPanelTitle(file: VirtualFile, revisionNumber: VcsRevisionNumber?): @NlsContexts.Label String =
if (revisionNumber != null) {
DiffBundle.message("merge.version.title.their.with.revision", revisionNumber.asString())
}
else {
DiffBundle.message("merge.version.title.their")
}
/**
* Returns the title of the multiple files merge dialog.
*
* Don't mix with [getMergeWindowTitle] which is the title of the 3-way merge dialog displayed for a single file.
*/
open fun getMultipleFileDialogTitle(): @NlsContexts.DialogTitle String = VcsBundle.message("multiple.file.merge.title")
/**
* Allows to override the names of the columns of the multiple files merge dialog, defined in [MergeSession.getMergeInfoColumns].
*
* Return the column names, matching the order of columns defined in the MergeSession.
* Return `null` to use names from [MergeSession.getMergeInfoColumns].
*/
open fun getColumnNames(): List<@NlsContexts.ColumnName String>? = null
/**
* Allows to customize diff editor titles in the 3-way merge dialog using [DiffEditorTitleCustomizer] for each editor.
* This method takes precedence over methods like [getLeftPanelTitle].
* If [DiffEditorTitleCustomizer] is null for the side, get(side)PanelTitle will be used as a fallback.
*/
open fun getTitleCustomizerList(file: FilePath): DiffEditorTitleCustomizerList = DEFAULT_CUSTOMIZER_LIST
data class DiffEditorTitleCustomizerList(
val leftTitleCustomizer: DiffEditorTitleCustomizer?,
val centerTitleCustomizer: DiffEditorTitleCustomizer?,
val rightTitleCustomizer: DiffEditorTitleCustomizer?
)
}
| apache-2.0 | 37f71c53129b4a6fb5df7efd1e3a78cf | 41.989583 | 140 | 0.752847 | 4.510383 | false | false | false | false |
Unic8/retroauth | retroauth-android/src/main/java/com/andretietz/retroauth/AndroidCredentialStorage.kt | 1 | 3894 | /*
* Copyright (c) 2016 Andre Tietz
*
* 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.andretietz.retroauth
import android.accounts.Account
import android.accounts.AccountManager
import android.app.Application
import android.os.Looper
import java.util.concurrent.Callable
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.FutureTask
/**
* This is the implementation of a [CredentialStorage] in Android using the Android [AccountManager]
*/
class AndroidCredentialStorage constructor(
private val application: Application
) : CredentialStorage<Account, AndroidCredentialType, AndroidCredentials> {
private val executor by lazy { Executors.newSingleThreadExecutor() }
private val accountManager by lazy { AccountManager.get(application) }
companion object {
@JvmStatic
private fun createDataKey(type: AndroidCredentialType, key: String) =
"%s_%s".format(type.type, key)
}
override fun getCredentials(
owner: Account,
type: AndroidCredentialType,
callback: Callback<AndroidCredentials>?
): Future<AndroidCredentials> {
val task = GetTokenTask(application, accountManager, owner, type, callback)
return if (Looper.myLooper() == Looper.getMainLooper())
executor.submit(task)
else
FutureTask(task).also { it.run() }
}
override fun removeCredentials(owner: Account, type: AndroidCredentialType, credentials: AndroidCredentials) {
accountManager.invalidateAuthToken(owner.type, credentials.token)
type.dataKeys?.forEach { accountManager.setUserData(owner, createDataKey(type, it), null) }
}
override fun storeCredentials(owner: Account, type: AndroidCredentialType, credentials: AndroidCredentials) {
accountManager.setAuthToken(owner, type.type, credentials.token)
if (type.dataKeys != null && credentials.data != null) {
type.dataKeys.forEach {
require(credentials.data.containsKey(it)) {
throw IllegalArgumentException(
"The credentials you want to store, needs to contain credentials-data with the keys: %s"
.format(type.dataKeys.toString())
)
}
accountManager.setUserData(owner, createDataKey(type, it), credentials.data[it])
}
}
}
private class GetTokenTask(
application: Application,
private val accountManager: AccountManager,
private val owner: Account,
private val type: AndroidCredentialType,
private val callback: Callback<AndroidCredentials>?
) : Callable<AndroidCredentials> {
private val activityManager = ActivityManager[application]
override fun call(): AndroidCredentials {
val future = accountManager.getAuthToken(
owner,
type.type,
null,
activityManager.activity,
null,
null)
var token = future.result.getString(AccountManager.KEY_AUTHTOKEN)
if (token == null) token = accountManager.peekAuthToken(owner, type.type)
if (token == null) {
val error = AuthenticationCanceledException()
callback?.onError(error)
throw error
}
return AndroidCredentials(
token,
type.dataKeys
?.associateTo(HashMap()) {
it to accountManager.getUserData(owner, createDataKey(type, it))
}
).apply {
callback?.onResult(this)
}
}
}
}
| apache-2.0 | c4db2c9e53c9fd0fc7ce5e088d8feda9 | 33.460177 | 112 | 0.710067 | 4.619217 | false | false | false | false |
smmribeiro/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/RawPluginDescriptor.kt | 1 | 2523 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.plugins
import com.intellij.openapi.extensions.ExtensionDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.NlsSafe
import com.intellij.util.XmlElement
import org.jetbrains.annotations.ApiStatus
import java.time.LocalDate
@ApiStatus.Internal
class RawPluginDescriptor {
@JvmField var id: String? = null
@JvmField internal var name: String? = null
@JvmField internal var description: @NlsSafe String? = null
@JvmField internal var category: String? = null
@JvmField internal var changeNotes: String? = null
@JvmField internal var version: String? = null
@JvmField internal var sinceBuild: String? = null
@JvmField internal var untilBuild: String? = null
@JvmField internal var `package`: String? = null
@JvmField internal var url: String? = null
@JvmField internal var vendor: String? = null
@JvmField internal var vendorEmail: String? = null
@JvmField internal var vendorUrl: String? = null
@JvmField internal var resourceBundleBaseName: String? = null
@JvmField internal var isUseIdeaClassLoader = false
@JvmField internal var isBundledUpdateAllowed = false
@JvmField internal var implementationDetail = false
@JvmField internal var isRestartRequired = false
@JvmField internal var isLicenseOptional = false
@JvmField internal var productCode: String? = null
@JvmField internal var releaseDate: LocalDate? = null
@JvmField internal var releaseVersion = 0
@JvmField internal var modules: MutableList<PluginId>? = null
@JvmField internal var depends: MutableList<PluginDependency>? = null
@JvmField internal var actions: MutableList<ActionDescriptor>? = null
@JvmField var incompatibilities: MutableList<PluginId>? = null
@JvmField val appContainerDescriptor = ContainerDescriptor()
@JvmField val projectContainerDescriptor = ContainerDescriptor()
@JvmField val moduleContainerDescriptor = ContainerDescriptor()
@JvmField var epNameToExtensions: MutableMap<String, MutableList<ExtensionDescriptor>>? = null
@JvmField internal var contentModules: MutableList<PluginContentDescriptor.ModuleItem>? = null
@JvmField internal var dependencies = ModuleDependenciesDescriptor.EMPTY
class ActionDescriptor(
@JvmField val name: String,
@JvmField val element: XmlElement,
@JvmField val resourceBundle: String?,
)
}
| apache-2.0 | ee63a693ad093b66d1c5736abe07824f | 39.047619 | 158 | 0.782798 | 4.880077 | false | false | false | false |
fabmax/kool | kool-core/src/jvmMain/kotlin/de/fabmax/kool/platform/gl/LoadedTextureGl.kt | 1 | 3027 | package de.fabmax.kool.platform.gl
import de.fabmax.kool.pipeline.AddressMode
import de.fabmax.kool.pipeline.FilterMethod
import de.fabmax.kool.pipeline.LoadedTexture
import de.fabmax.kool.pipeline.TextureProps
import de.fabmax.kool.platform.Lwjgl3Context
import de.fabmax.kool.util.logW
import org.lwjgl.opengl.GL12.*
import org.lwjgl.opengl.GL14.GL_MIRRORED_REPEAT
import kotlin.math.min
class LoadedTextureGl(val ctx: Lwjgl3Context, val target: Int, val texture: Int, estimatedSize: Int) : LoadedTexture {
val texId = nextTexId++
var isDestroyed = false
private set
override var width = 0
override var height = 0
override var depth = 0
init {
ctx.engineStats.textureAllocated(texId, estimatedSize)
}
fun setSize(width: Int, height: Int, depth: Int) {
this.width = width
this.height = height
this.depth = depth
}
fun applySamplerProps(props: TextureProps) {
glBindTexture(target, texture)
glTexParameteri(target, GL_TEXTURE_MIN_FILTER, props.minFilter.glMinFilterMethod(props.mipMapping))
glTexParameteri(target, GL_TEXTURE_MAG_FILTER, props.magFilter.glMagFilterMethod())
glTexParameteri(target, GL_TEXTURE_WRAP_S, props.addressModeU.glAddressMode())
glTexParameteri(target, GL_TEXTURE_WRAP_T, props.addressModeV.glAddressMode())
if (target == GL_TEXTURE_3D) {
glTexParameteri(target, GL_TEXTURE_WRAP_R, props.addressModeW.glAddressMode())
}
val backend = ctx.renderBackend as GlRenderBackend
val anisotropy = min(props.maxAnisotropy, backend.glCapabilities.maxAnisotropy)
if (anisotropy > 1) {
glTexParameteri(target, backend.glCapabilities.glTextureMaxAnisotropyExt, anisotropy)
}
if (anisotropy > 1 && (props.minFilter == FilterMethod.NEAREST || props.magFilter == FilterMethod.NEAREST)) {
logW { "Texture filtering is NEAREST but anisotropy is $anisotropy (> 1)" }
}
}
override fun dispose() {
if (!isDestroyed) {
isDestroyed = true
glDeleteTextures(texture)
ctx.engineStats.textureDeleted(texId)
}
}
private fun FilterMethod.glMinFilterMethod(mipMapping: Boolean): Int {
return when(this) {
FilterMethod.NEAREST -> if (mipMapping) GL_NEAREST_MIPMAP_NEAREST else GL_NEAREST
FilterMethod.LINEAR -> if (mipMapping) GL_LINEAR_MIPMAP_LINEAR else GL_LINEAR
}
}
private fun FilterMethod.glMagFilterMethod(): Int {
return when (this) {
FilterMethod.NEAREST -> GL_NEAREST
FilterMethod.LINEAR -> GL_LINEAR
}
}
private fun AddressMode.glAddressMode(): Int {
return when(this) {
AddressMode.CLAMP_TO_EDGE -> GL_CLAMP_TO_EDGE
AddressMode.MIRRORED_REPEAT -> GL_MIRRORED_REPEAT
AddressMode.REPEAT -> GL_REPEAT
}
}
companion object {
private var nextTexId = 1L
}
} | apache-2.0 | ade01308c76627d1cb55251e10082b9f | 33.409091 | 118 | 0.666997 | 4.046791 | false | false | false | false |
kohesive/kohesive-iac | model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/clients/DeferredAWSCloudHSM.kt | 1 | 2064 | package uy.kohesive.iac.model.aws.clients
import com.amazonaws.services.cloudhsm.AbstractAWSCloudHSM
import com.amazonaws.services.cloudhsm.AWSCloudHSM
import com.amazonaws.services.cloudhsm.model.*
import uy.kohesive.iac.model.aws.IacContext
import uy.kohesive.iac.model.aws.proxy.makeProxy
open class BaseDeferredAWSCloudHSM(val context: IacContext) : AbstractAWSCloudHSM(), AWSCloudHSM {
override fun addTagsToResource(request: AddTagsToResourceRequest): AddTagsToResourceResult {
return with (context) {
request.registerWithAutoName()
makeProxy<AddTagsToResourceRequest, AddTagsToResourceResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
override fun createHapg(request: CreateHapgRequest): CreateHapgResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateHapgRequest, CreateHapgResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
override fun createHsm(request: CreateHsmRequest): CreateHsmResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateHsmRequest, CreateHsmResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
override fun createLunaClient(request: CreateLunaClientRequest): CreateLunaClientResult {
return with (context) {
request.registerWithAutoName()
makeProxy<CreateLunaClientRequest, CreateLunaClientResult>(
context = this@with,
sourceName = getNameStrict(request),
requestObject = request
)
}
}
}
class DeferredAWSCloudHSM(context: IacContext) : BaseDeferredAWSCloudHSM(context)
| mit | a8a29b5990efe469f8e018235bd8d02c | 34.586207 | 98 | 0.635174 | 4.82243 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/skills/SkillsFragment.kt | 1 | 6796 | package com.habitrpg.android.habitica.ui.fragments.skills
import android.app.Activity
import android.app.ProgressDialog
import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.extensions.subscribeWithErrorHandler
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.Skill
import com.habitrpg.android.habitica.models.responses.SkillResponse
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.ui.activities.SkillMemberActivity
import com.habitrpg.android.habitica.ui.activities.SkillTasksActivity
import com.habitrpg.android.habitica.ui.adapter.SkillsRecyclerViewAdapter
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import com.habitrpg.android.habitica.ui.helpers.SafeDefaultItemAnimator
import com.habitrpg.android.habitica.ui.helpers.resetViews
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar
import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar.Companion.showSnackbar
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.fragment_skills.*
class SkillsFragment : BaseMainFragment() {
private val TASK_SELECTION_ACTIVITY = 10
private val MEMBER_SELECTION_ACTIVITY = 11
internal var adapter: SkillsRecyclerViewAdapter? = null
private var selectedSkill: Skill? = null
@Suppress("DEPRECATION")
private var progressDialog: ProgressDialog? = null
override var user: User? = null
set(value) {
field = value
checkUserLoadSkills()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
adapter = SkillsRecyclerViewAdapter()
adapter?.useSkillEvents?.subscribeWithErrorHandler(Consumer { onSkillSelected(it) })?.let { compositeSubscription.add(it) }
checkUserLoadSkills()
this.tutorialStepIdentifier = "skills"
this.tutorialText = getString(R.string.tutorial_skills)
return inflater.inflate(R.layout.fragment_skills, container, false)
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
resetViews()
recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(activity)
recyclerView.adapter = adapter
recyclerView.itemAnimator = SafeDefaultItemAnimator()
}
private fun checkUserLoadSkills() {
if (user == null || adapter == null) {
return
}
adapter?.mana = this.user?.stats?.mp ?: 0.0
adapter?.level = this.user?.stats?.lvl ?: 0
adapter?.specialItems = this.user?.items?.special
user?.let { user ->
Observable.concat(userRepository.getSkills(user).firstElement().toObservable().flatMap { Observable.fromIterable(it) },
userRepository.getSpecialItems(user).firstElement().toObservable().flatMap { Observable.fromIterable(it) })
.toList()
.subscribe(Consumer { skills -> adapter?.setSkillList(skills) }, RxErrorHandler.handleEmptyError())
}
}
private fun onSkillSelected(skill: Skill) {
when {
"special" == skill.habitClass -> {
selectedSkill = skill
val intent = Intent(activity, SkillMemberActivity::class.java)
startActivityForResult(intent, MEMBER_SELECTION_ACTIVITY)
}
skill.target == "task" -> {
selectedSkill = skill
val intent = Intent(activity, SkillTasksActivity::class.java)
startActivityForResult(intent, TASK_SELECTION_ACTIVITY)
}
else -> useSkill(skill)
}
}
private fun displaySkillResult(usedSkill: Skill?, response: SkillResponse) {
adapter?.mana = response.user.stats?.mp ?: 0.0
val activity = activity ?: return
if ("special" == usedSkill?.habitClass) {
showSnackbar(activity.snackbarContainer, context?.getString(R.string.used_skill_without_mana, usedSkill.text), HabiticaSnackbar.SnackbarDisplayType.BLUE)
} else {
context?.let {
showSnackbar(activity.snackbarContainer, null,
context?.getString(R.string.used_skill_without_mana, usedSkill?.text),
BitmapDrawable(resources, HabiticaIconsHelper.imageOfMagic()),
ContextCompat.getColor(it, R.color.blue_10), "-" + usedSkill?.mana,
HabiticaSnackbar.SnackbarDisplayType.BLUE)
}
}
compositeSubscription.add(userRepository.retrieveUser(false).subscribe(Consumer { }, RxErrorHandler.handleEmptyError()))
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (data != null) {
when (requestCode) {
TASK_SELECTION_ACTIVITY -> {
if (resultCode == Activity.RESULT_OK) {
useSkill(selectedSkill, data.getStringExtra("taskID"))
}
}
MEMBER_SELECTION_ACTIVITY -> {
if (resultCode == Activity.RESULT_OK) {
useSkill(selectedSkill, data.getStringExtra("member_id"))
}
}
}
}
}
private fun useSkill(skill: Skill?, taskId: String? = null) {
if (skill == null) {
return
}
val observable: Flowable<SkillResponse> = if (taskId != null) {
userRepository.useSkill(user, skill.key, skill.target, taskId)
} else {
userRepository.useSkill(user, skill.key, skill.target)
}
compositeSubscription.add(observable.subscribe(Consumer { skillResponse -> this.displaySkillResult(skill, skillResponse) },
RxErrorHandler.handleEmptyError()))
}
}
| gpl-3.0 | 78671db2e0e30871bcc61ca30262bd31 | 42.12987 | 165 | 0.658181 | 4.989721 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt | 1 | 1998 | package info.nightscout.androidaps.queue.commands
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import javax.inject.Inject
class CommandSMBBolus(
injector: HasAndroidInjector,
private val detailedBolusInfo: DetailedBolusInfo,
callback: Callback?
) : Command(injector, CommandType.SMB_BOLUS, callback) {
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var activePlugin: ActivePluginProvider
override fun execute() {
val r: PumpEnactResult
val lastBolusTime = activePlugin.activeTreatments.lastBolusTime
if (lastBolusTime != 0L && lastBolusTime + T.mins(3).msecs() > DateUtil.now()) {
aapsLogger.debug(LTag.PUMPQUEUE, "SMB requested but still in 3 min interval")
r = PumpEnactResult(injector).enacted(false).success(false).comment("SMB requested but still in 3 min interval")
} else if (detailedBolusInfo.deliverAt != 0L && detailedBolusInfo.deliverAt + T.mins(1).msecs() > System.currentTimeMillis()) {
r = activePlugin.activePump.deliverTreatment(detailedBolusInfo)
} else {
r = PumpEnactResult(injector).enacted(false).success(false).comment("SMB request too old")
aapsLogger.debug(LTag.PUMPQUEUE, "SMB bolus canceled. deliverAt: " + dateUtil.dateAndTimeString(detailedBolusInfo.deliverAt))
}
aapsLogger.debug(LTag.PUMPQUEUE, "Result success: ${r.success} enacted: ${r.enacted}")
callback?.result(r)?.run()
}
override fun status(): String = "SMB BOLUS ${resourceHelper.gs(R.string.formatinsulinunits, detailedBolusInfo.insulin)}"
} | agpl-3.0 | c6777100bcbb842f6d029ae65d75ba5f | 48.975 | 137 | 0.746747 | 4.646512 | false | false | false | false |
fabmax/kool | kool-physics/src/jsMain/kotlin/de/fabmax/kool/physics/RigidDynamic.kt | 1 | 985 | package de.fabmax.kool.physics
import de.fabmax.kool.math.Mat4f
import physx.PxRigidActor
import physx.PxRigidDynamic
actual open class RigidDynamic internal constructor(mass: Float, pose: Mat4f, pxActor: PxRigidActor?) : RigidBody() {
actual constructor(mass: Float, pose: Mat4f) : this(mass, pose, null)
@Suppress("UNCHECKED_CAST_TO_EXTERNAL_INTERFACE")
protected val pxRigidDynamic: PxRigidDynamic
get() = pxRigidActor as PxRigidDynamic
init {
if (pxActor == null) {
MemoryStack.stackPush().use { mem ->
val pxPose = pose.toPxTransform(mem.createPxTransform())
pxRigidActor = Physics.physics.createRigidDynamic(pxPose)
this.mass = mass
}
} else {
pxRigidActor = pxActor
}
transform.set(pose)
}
actual fun wakeUp() {
pxRigidDynamic.wakeUp()
}
actual fun putToSleep() {
pxRigidDynamic.putToSleep()
}
} | apache-2.0 | 3ab1c05cbeff725f5152283322a76ffc | 27.171429 | 117 | 0.632487 | 4.104167 | false | false | false | false |
DanielGrech/anko | dsl/testData/compile/AndroidSimpleTest.kt | 7 | 1083 | package com.example.android_test
import android.app.Activity
import android.os.Bundle
import org.jetbrains.anko.*
import android.widget.LinearLayout
public open class MyActivity() : Activity() {
public override fun onCreate(savedInstanceState: Bundle?): Unit {
super.onCreate(savedInstanceState)
UI {
linearLayout {
orientation = LinearLayout.VERTICAL
val tv1 = textView {
text = "9287y4r3"
}
val b1 = button {
text = "Buttons1231"
onClick {
}
setOnClickListener {
tv1.text = text
}
}
linearLayout {
orientation = LinearLayout.HORIZONTAL
checkBox {
text = "34563456"
}
val b2 = button {
text = "9auhdfg9a"
}
}
}
}
}
}
| apache-2.0 | 78793fd7b0a748a1f1361b71dc61896e | 26.075 | 69 | 0.429363 | 5.760638 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/KotlinTypeArgumentInfoHandler.kt | 1 | 9590 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.parameterInfo
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.lang.parameterInfo.*
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.core.resolveCandidates
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.calls.callUtil.getCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.typeUtil.TypeNullability
import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny
import org.jetbrains.kotlin.types.typeUtil.nullability
class KotlinClassConstructorInfoHandler : KotlinTypeArgumentInfoHandlerBase<ClassConstructorDescriptor>() {
override fun fetchTypeParameters(descriptor: ClassConstructorDescriptor): List<TypeParameterDescriptor> = descriptor.typeParameters
override fun findParameterOwners(argumentList: KtTypeArgumentList): Collection<ClassConstructorDescriptor>? {
val userType = argumentList.parent as? KtUserType ?: return null
val descriptors = userType.referenceExpression?.resolveMainReferenceToDescriptors()?.mapNotNull { it as? ClassConstructorDescriptor }
return descriptors?.takeIf { it.isNotEmpty() }
}
override fun getArgumentListAllowedParentClasses() = setOf(KtUserType::class.java)
}
class KotlinClassTypeArgumentInfoHandler : KotlinTypeArgumentInfoHandlerBase<ClassDescriptor>() {
override fun fetchTypeParameters(descriptor: ClassDescriptor) = descriptor.typeConstructor.parameters
override fun findParameterOwners(argumentList: KtTypeArgumentList): Collection<ClassDescriptor>? {
val userType = argumentList.parent as? KtUserType ?: return null
val descriptors = userType.referenceExpression?.resolveMainReferenceToDescriptors()?.mapNotNull { it as? ClassDescriptor }
return descriptors?.takeIf { it.isNotEmpty() }
}
override fun getArgumentListAllowedParentClasses() = setOf(KtUserType::class.java)
}
class KotlinFunctionTypeArgumentInfoHandler : KotlinTypeArgumentInfoHandlerBase<FunctionDescriptor>() {
override fun fetchTypeParameters(descriptor: FunctionDescriptor) = descriptor.typeParameters
override fun findParameterOwners(argumentList: KtTypeArgumentList): Collection<FunctionDescriptor>? {
val callElement = argumentList.parent as? KtCallElement ?: return null
val bindingContext = argumentList.analyze(BodyResolveMode.PARTIAL)
val call = callElement.getCall(bindingContext) ?: return null
val candidates = call.resolveCandidates(bindingContext, callElement.getResolutionFacade())
return candidates
.map { it.resultingDescriptor }
.distinctBy { buildPresentation(it.typeParameters, -1).first }
}
override fun getArgumentListAllowedParentClasses() = setOf(KtCallElement::class.java)
}
abstract class KotlinTypeArgumentInfoHandlerBase<TParameterOwner : DeclarationDescriptor> :
ParameterInfoHandlerWithTabActionSupport<KtTypeArgumentList, TParameterOwner, KtTypeProjection> {
protected abstract fun fetchTypeParameters(descriptor: TParameterOwner): List<TypeParameterDescriptor>
protected abstract fun findParameterOwners(argumentList: KtTypeArgumentList): Collection<TParameterOwner>?
override fun getActualParameterDelimiterType() = KtTokens.COMMA
override fun getActualParametersRBraceType() = KtTokens.GT
override fun getArgumentListClass() = KtTypeArgumentList::class.java
override fun getActualParameters(o: KtTypeArgumentList) = o.arguments.toTypedArray()
override fun getArgListStopSearchClasses() =
setOf(KtNamedFunction::class.java, KtVariableDeclaration::class.java, KtClassOrObject::class.java)
override fun showParameterInfo(element: KtTypeArgumentList, context: CreateParameterInfoContext) {
context.showHint(element, element.textRange.startOffset, this)
}
override fun findElementForUpdatingParameterInfo(context: UpdateParameterInfoContext): KtTypeArgumentList? {
val element = context.file.findElementAt(context.offset) ?: return null
val argumentList = element.getParentOfType<KtTypeArgumentList>(true) ?: return null
val argument = element.parents.takeWhile { it != argumentList }.lastOrNull() as? KtTypeProjection
if (argument != null) {
val arguments = getActualParameters(argumentList)
val index = arguments.indexOf(element)
context.setCurrentParameter(index)
context.setHighlightedParameter(element)
}
return argumentList
}
override fun findElementForParameterInfo(context: CreateParameterInfoContext): KtTypeArgumentList? {
val file = context.file as? KtFile ?: return null
val token = file.findElementAt(context.offset) ?: return null
val argumentList = token.getParentOfType<KtTypeArgumentList>(true) ?: return null
val parameterOwners = findParameterOwners(argumentList) ?: return null
context.itemsToShow = parameterOwners.toTypedArray<Any>()
return argumentList
}
override fun updateParameterInfo(argumentList: KtTypeArgumentList, context: UpdateParameterInfoContext) {
if (context.parameterOwner !== argumentList) {
context.removeHint()
}
val offset = context.offset
val parameterIndex = argumentList.allChildren
.takeWhile { it.startOffset < offset }
.count { it.node.elementType == KtTokens.COMMA }
context.setCurrentParameter(parameterIndex)
}
override fun updateUI(itemToShow: TParameterOwner, context: ParameterInfoUIContext) {
if (!updateUIOrFail(itemToShow, context)) {
context.isUIComponentEnabled = false
return
}
}
private fun updateUIOrFail(itemToShow: TParameterOwner, context: ParameterInfoUIContext): Boolean {
val currentIndex = context.currentParameterIndex
if (currentIndex < 0) return false // by some strange reason we are invoked with currentParameterIndex == -1 during initialization
val parameters = fetchTypeParameters(itemToShow)
val (text, currentParameterStart, currentParameterEnd) = buildPresentation(parameters, currentIndex)
context.setupUIComponentPresentation(
text, currentParameterStart, currentParameterEnd,
false/*isDisabled*/, false/*strikeout*/, false/*isDisabledBeforeHighlight*/,
context.defaultParameterColor
)
return true
}
protected fun buildPresentation(
parameters: List<TypeParameterDescriptor>,
currentIndex: Int
): Triple<String, Int, Int> {
var currentParameterStart = -1
var currentParameterEnd = -1
val text = buildString {
var needWhere = false
for ((index, parameter) in parameters.withIndex()) {
if (index > 0) append(", ")
if (index == currentIndex) {
currentParameterStart = length
}
if (parameter.isReified) {
append("reified ")
}
when (parameter.variance) {
Variance.INVARIANT -> {
}
Variance.IN_VARIANCE -> append("in ")
Variance.OUT_VARIANCE -> append("out ")
}
append(parameter.name.asString())
val upperBounds = parameter.upperBounds
if (upperBounds.size == 1) {
val upperBound = upperBounds.single()
if (!upperBound.isAnyOrNullableAny() || upperBound.nullability() == TypeNullability.NOT_NULL) { // skip Any? or Any!
append(" : ").append(DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(upperBound))
}
} else if (upperBounds.size > 1) {
needWhere = true
}
if (index == currentIndex) {
currentParameterEnd = length
}
}
if (needWhere) {
append(" where ")
var needComma = false
for (parameter in parameters) {
val upperBounds = parameter.upperBounds
if (upperBounds.size > 1) {
for (upperBound in upperBounds) {
if (needComma) append(", ")
needComma = true
append(parameter.name.asString())
append(" : ")
append(DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(upperBound))
}
}
}
}
}
return Triple(text, currentParameterStart, currentParameterEnd)
}
} | apache-2.0 | 5d9f0d77149d631a442d7505d5f5e8ab | 44.454976 | 158 | 0.688947 | 5.578825 | false | false | false | false |
androidx/androidx | compose/material3/material3/samples/src/main/java/androidx/compose/material3/samples/ScaffoldSamples.kt | 3 | 11288 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material3.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.consumedWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.FabPosition
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Snackbar
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.material3.SnackbarVisuals
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Preview
@Sampled
@Composable
fun SimpleScaffoldWithTopBar() {
val colors = listOf(
Color(0xFFffd7d7.toInt()),
Color(0xFFffe9d6.toInt()),
Color(0xFFfffbd0.toInt()),
Color(0xFFe3ffd9.toInt()),
Color(0xFFd0fff8.toInt())
)
Scaffold(
topBar = {
TopAppBar(
title = { Text("Simple Scaffold Screen") },
navigationIcon = {
IconButton(
onClick = { /* "Open nav drawer" */ }
) {
Icon(Icons.Filled.Menu, contentDescription = "Localized description")
}
}
)
},
floatingActionButtonPosition = FabPosition.End,
floatingActionButton = {
ExtendedFloatingActionButton(
onClick = { /* fab click handler */ }
) {
Text("Inc")
}
},
content = { innerPadding ->
LazyColumn(
// consume insets as scaffold doesn't do it by default
modifier = Modifier.consumedWindowInsets(innerPadding),
contentPadding = innerPadding
) {
items(count = 100) {
Box(
Modifier
.fillMaxWidth()
.height(50.dp)
.background(colors[it % colors.size])
)
}
}
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun ScaffoldWithSimpleSnackbar() {
val snackbarHostState = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
Scaffold(
snackbarHost = { SnackbarHost(snackbarHostState) },
floatingActionButton = {
var clickCount by remember { mutableStateOf(0) }
ExtendedFloatingActionButton(
onClick = {
// show snackbar as a suspend function
scope.launch {
snackbarHostState.showSnackbar(
"Snackbar # ${++clickCount}"
)
}
}
) { Text("Show snackbar") }
},
content = { innerPadding ->
Text(
text = "Body content",
modifier = Modifier
.padding(innerPadding)
.fillMaxSize()
.wrapContentSize()
)
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun ScaffoldWithIndefiniteSnackbar() {
val snackbarHostState = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
Scaffold(
snackbarHost = { SnackbarHost(snackbarHostState) },
floatingActionButton = {
var clickCount by remember { mutableStateOf(0) }
ExtendedFloatingActionButton(
onClick = {
// show snackbar as a suspend function
scope.launch {
snackbarHostState.showSnackbar(
message = "Snackbar # ${++clickCount}",
actionLabel = "Action",
withDismissAction = true,
duration = SnackbarDuration.Indefinite
)
}
}
) { Text("Show snackbar") }
},
content = { innerPadding ->
Text(
text = "Body content",
modifier = Modifier
.padding(innerPadding)
.fillMaxSize()
.wrapContentSize()
)
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun ScaffoldWithCustomSnackbar() {
class SnackbarVisualsWithError(
override val message: String,
val isError: Boolean
) : SnackbarVisuals {
override val actionLabel: String
get() = if (isError) "Error" else "OK"
override val withDismissAction: Boolean
get() = false
override val duration: SnackbarDuration
get() = SnackbarDuration.Indefinite
}
val snackbarHostState = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
Scaffold(
snackbarHost = {
// reuse default SnackbarHost to have default animation and timing handling
SnackbarHost(snackbarHostState) { data ->
// custom snackbar with the custom action button color and border
val isError = (data.visuals as? SnackbarVisualsWithError)?.isError ?: false
val buttonColor = if (isError) {
ButtonDefaults.textButtonColors(
containerColor = MaterialTheme.colorScheme.errorContainer,
contentColor = MaterialTheme.colorScheme.error
)
} else {
ButtonDefaults.textButtonColors(
contentColor = MaterialTheme.colorScheme.inversePrimary
)
}
Snackbar(
modifier = Modifier
.border(2.dp, MaterialTheme.colorScheme.secondary)
.padding(12.dp),
action = {
TextButton(
onClick = { if (isError) data.dismiss() else data.performAction() },
colors = buttonColor
) { Text(data.visuals.actionLabel ?: "") }
}
) {
Text(data.visuals.message)
}
}
},
floatingActionButton = {
var clickCount by remember { mutableStateOf(0) }
ExtendedFloatingActionButton(
onClick = {
scope.launch {
snackbarHostState.showSnackbar(
SnackbarVisualsWithError(
"Snackbar # ${++clickCount}",
isError = clickCount % 2 != 0
)
)
}
}
) { Text("Show snackbar") }
},
content = { innerPadding ->
Text(
text = "Custom Snackbar Demo",
modifier = Modifier
.padding(innerPadding)
.fillMaxSize()
.wrapContentSize()
)
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun ScaffoldWithCoroutinesSnackbar() {
// decouple snackbar host state from scaffold state for demo purposes
// this state, channel and flow is for demo purposes to demonstrate business logic layer
val snackbarHostState = remember { SnackbarHostState() }
// we allow only one snackbar to be in the queue here, hence conflated
val channel = remember { Channel<Int>(Channel.CONFLATED) }
LaunchedEffect(channel) {
channel.receiveAsFlow().collect { index ->
val result = snackbarHostState.showSnackbar(
message = "Snackbar # $index",
actionLabel = "Action on $index"
)
when (result) {
SnackbarResult.ActionPerformed -> {
/* action has been performed */
}
SnackbarResult.Dismissed -> {
/* dismissed, no action needed */
}
}
}
}
Scaffold(
snackbarHost = { SnackbarHost(snackbarHostState) },
floatingActionButton = {
var clickCount by remember { mutableStateOf(0) }
ExtendedFloatingActionButton(
onClick = {
// offset snackbar data to the business logic
channel.trySend(++clickCount)
}
) { Text("Show snackbar") }
},
content = { innerPadding ->
Text(
"Snackbar demo",
modifier = Modifier
.padding(innerPadding)
.fillMaxSize()
.wrapContentSize()
)
}
)
}
| apache-2.0 | 68b5d04c262d8e1013b777e7584b94b3 | 34.949045 | 96 | 0.575213 | 5.61592 | false | false | false | false |
androidx/androidx | room/room-compiler-processing-testing/src/main/java/androidx/room/compiler/processing/util/CompilationTestCapabilities.kt | 3 | 2987 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.processing.util
import org.junit.AssumptionViolatedException
import java.util.Properties
/**
* Provides the information about compilation test capabilities.
* see: b/178725084
*/
object CompilationTestCapabilities {
/**
* `true` if we can run KSP tests.
*/
val canTestWithKsp: Boolean
init {
val config = Config.load()
canTestWithKsp = config.canEnableKsp()
}
/**
* Checks if KSP tests can be run and if not, throws an [AssumptionViolatedException] to skip
* the test.
*/
fun assumeKspIsEnabled() {
if (!canTestWithKsp) {
throw AssumptionViolatedException("KSP tests are not enabled")
}
}
internal data class Config(
val kotlinVersion: String,
val kspVersion: String
) {
fun canEnableKsp(): Boolean {
val reducedKotlin = reduceVersions(kotlinVersion)
val reducedKsp = reduceVersions(kspVersion)
return reducedKotlin.contentEquals(reducedKsp)
}
/**
* Reduces the version to some approximation by taking major and minor versions.
* We use this to check if ksp and kotlin are compatible, feel free to change it if it
* does not work as it is only an approximation
* e.g. 1.4.20 becomes 1.4, 1.40.210-foobar becomes 1.4
*/
private fun reduceVersions(version: String): Array<String?> {
val sections = version.split('.')
return arrayOf(
sections.getOrNull(0),
sections.getOrNull(1)
)
}
companion object {
/**
* Load the test configuration from resources.
*/
fun load(): Config {
val props = Properties()
val resourceName = "/${Config::class.java.canonicalName}.properties"
CompilationTestCapabilities::class.java
.getResource(resourceName)
.openStream()
.use {
props.load(it)
}
return Config(
kotlinVersion = props.getProperty("kotlinVersion") as String,
kspVersion = props.getProperty("kspVersion") as String
)
}
}
}
} | apache-2.0 | 09ca8d89bc1ece55b4b1eae007a18c75 | 31.835165 | 97 | 0.598594 | 4.904762 | false | true | false | false |
yschimke/okhttp | native-image-tests/src/main/kotlin/okhttp3/TestRegistration.kt | 2 | 3796 | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import com.oracle.svm.core.annotate.AutomaticFeature
import org.graalvm.nativeimage.hosted.Feature
import org.graalvm.nativeimage.hosted.RuntimeClassInitialization
import org.graalvm.nativeimage.hosted.RuntimeReflection
import java.io.File
@AutomaticFeature
class TestRegistration : Feature {
override fun beforeAnalysis(access: Feature.BeforeAnalysisAccess) {
// Presumably needed for parsing the testlist.txt file.
RuntimeClassInitialization.initializeAtBuildTime(access.findClassByName("kotlin.text.Charsets"))
registerKnownTests(access)
registerJupiterClasses(access)
registerParamProvider(access, "okhttp3.SampleTestProvider")
registerParamProvider(access, "okhttp3.internal.http.CancelModelParamProvider")
registerParamProvider(access, "okhttp3.internal.cache.FileSystemParamProvider")
registerParamProvider(access, "okhttp3.internal.http2.HttpOverHttp2Test\$ProtocolParamProvider")
registerParamProvider(access, "okhttp3.internal.cache.FileSystemParamProvider")
registerParamProvider(access, "okhttp3.WebPlatformUrlTest\$TestDataParamProvider")
}
private fun registerParamProvider(access: Feature.BeforeAnalysisAccess, provider: String) {
val providerClass = access.findClassByName(provider)
if (providerClass != null) {
registerTest(access, providerClass)
} else {
println("Missing $provider")
}
}
private fun registerJupiterClasses(access: Feature.BeforeAnalysisAccess) {
registerStandardClass(access, "org.junit.jupiter.params.ParameterizedTestExtension")
registerStandardClass(access, "org.junit.platform.console.tasks.TreePrintingListener")
registerStandardClass(access,
"org.junit.jupiter.engine.extension.TimeoutExtension\$ExecutorResource")
}
private fun registerStandardClass(access: Feature.BeforeAnalysisAccess, name: String) {
val listener = access.findClassByName(name)
RuntimeReflection.register(listener)
listener.declaredConstructors.forEach {
RuntimeReflection.register(it)
}
}
private fun registerKnownTests(access: Feature.BeforeAnalysisAccess) {
val knownTestFile = File("src/main/resources/testlist.txt").absoluteFile
knownTestFile.readLines().forEach {
try {
val testClass = access.findClassByName(it)
if (testClass != null) {
access.registerAsUsed(testClass)
registerTest(access, testClass)
}
} catch (e: Exception) {
// If you throw an exception here then native image building fails half way through
// silently without rewriting the binary. So we report noisily, but keep going and prefer
// running most tests still.
e.printStackTrace()
}
}
}
private fun registerTest(access: Feature.BeforeAnalysisAccess, java: Class<*>) {
access.registerAsUsed(java)
RuntimeReflection.register(java)
java.constructors.forEach {
RuntimeReflection.register(it)
}
java.declaredMethods.forEach {
RuntimeReflection.register(it)
}
java.declaredFields.forEach {
RuntimeReflection.register(it)
}
java.methods.forEach {
RuntimeReflection.register(it)
}
}
} | apache-2.0 | b3bf77297a350a3437a5427d0e7e605b | 36.594059 | 100 | 0.748156 | 4.298981 | false | true | false | false |
androidx/androidx | bluetooth/bluetooth-core/src/main/java/androidx/bluetooth/core/ScanSettings.kt | 3 | 5543 | /*
* 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.bluetooth.core
// TODO(ofy) Implement Bundleable instead of Parcelable
/**
* Bluetooth LE scan settings are passed to {@link BluetoothLeScanner#startScan} to define the
* parameters for the scan.
* @hide
*/
class ScanSettings {
companion object {
/**
* A special Bluetooth LE scan mode. Applications using this scan mode will passively
* listen for other scan results without starting BLE scans themselves.
*/
const val SCAN_MODE_OPPORTUNISTIC = -1
/**
* Perform Bluetooth LE scan in low power mode. This is the default scan mode as it
* consumes the least power. This mode is enforced if the scanning application is not in
* foreground.
*/
const val SCAN_MODE_LOW_POWER = 0
/**
* Perform Bluetooth LE scan in balanced power mode. Scan results are returned at a rate
* that provides a good trade-off between scan frequency and power consumption.
*/
const val SCAN_MODE_BALANCED = 1
/**
* Scan using highest duty cycle. It's recommended to only use this mode when the
* application is running in the foreground.
*/
const val SCAN_MODE_LOW_LATENCY = 2
/**
* Perform Bluetooth LE scan in ambient discovery mode. This mode has lower duty cycle
* and more aggressive scan interval than balanced mode that provides a good trade-off
* between scan latency and power consumption.
*
* @hide
*/
val SCAN_MODE_AMBIENT_DISCOVERY = 3
/**
* Default Bluetooth LE scan mode when the screen is off.
* This mode has the low duty cycle and long scan interval which results in the lowest
* power consumption among all modes. It is for the framework internal use only.
*
* @hide
*/
const val SCAN_MODE_SCREEN_OFF = 4
/**
* Balanced Bluetooth LE scan mode for foreground service when the screen is off.
* It is for the framework internal use only.
*
* @hide
*/
const val SCAN_MODE_SCREEN_OFF_BALANCED = 5
/**
* Trigger a callback for every Bluetooth advertisement found that matches the filter
* criteria. If no filter is active, all advertisement packets are reported.
*/
const val CALLBACK_TYPE_ALL_MATCHES = 1
/**
* A result callback is only triggered for the first advertisement packet received that
* matches the filter criteria.
*/
const val CALLBACK_TYPE_FIRST_MATCH = 2
/**
* Receive a callback when advertisements are no longer received from a device that has
* been previously reported by a first match callback.
*/
const val CALLBACK_TYPE_MATCH_LOST = 4
/**
* Determines how many advertisements to match per filter, as this is scarce hw resource
*/
/**
* Match one advertisement per filter
*/
const val MATCH_NUM_ONE_ADVERTISEMENT = 1
/**
* Match few advertisement per filter, depends on current capability and availability of
* the resources in hw
*/
const val MATCH_NUM_FEW_ADVERTISEMENT = 2
/**
* Match as many advertisement per filter as hw could allow, depends on current
* capability and availability of the resources in hw
*/
const val MATCH_NUM_MAX_ADVERTISEMENT = 3
/**
* In Aggressive mode, hw will determine a match sooner even with feeble signal strength
* and few number of sightings/match in a duration.
*/
const val MATCH_MODE_AGGRESSIVE = 1
/**
* For sticky mode, higher threshold of signal strength and sightings is required
* before reporting by hw
*/
const val MATCH_MODE_STICKY = 2
/**
* Request full scan results which contain the device, rssi, advertising data, scan
* response as well as the scan timestamp.
*
* @hide
*/
val SCAN_RESULT_TYPE_FULL = 0
/**
* Request abbreviated scan results which contain the device, rssi and scan timestamp.
*
*
* **Note:** It is possible for an application to get more scan results than it asked
* for, if there are multiple apps using this type.
*
* @hide
*/
val SCAN_RESULT_TYPE_ABBREVIATED = 1
/**
* Use all supported PHYs for scanning.
* This will check the controller capabilities, and start
* the scan on 1Mbit and LE Coded PHYs if supported, or on
* the 1Mbit PHY only.
*/
const val PHY_LE_ALL_SUPPORTED = 255
}
// TODO(ofy) Add remainder of ScanSettings
// ...
}
| apache-2.0 | 26e388cf50e9804a66e36827fb1c3b9f | 34.082278 | 96 | 0.616814 | 4.803293 | false | false | false | false |
androidx/androidx | navigation/navigation-safe-args-generator/src/main/kotlin/androidx/navigation/safe/args/generator/java/JavaNavWriter.kt | 3 | 27548 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation.safe.args.generator.java
import androidx.navigation.safe.args.generator.BoolArrayType
import androidx.navigation.safe.args.generator.BoolType
import androidx.navigation.safe.args.generator.FloatArrayType
import androidx.navigation.safe.args.generator.FloatType
import androidx.navigation.safe.args.generator.IntArrayType
import androidx.navigation.safe.args.generator.IntType
import androidx.navigation.safe.args.generator.LongArrayType
import androidx.navigation.safe.args.generator.LongType
import androidx.navigation.safe.args.generator.NavWriter
import androidx.navigation.safe.args.generator.ObjectArrayType
import androidx.navigation.safe.args.generator.ObjectType
import androidx.navigation.safe.args.generator.ReferenceArrayType
import androidx.navigation.safe.args.generator.ReferenceType
import androidx.navigation.safe.args.generator.StringArrayType
import androidx.navigation.safe.args.generator.StringType
import androidx.navigation.safe.args.generator.ext.capitalize
import androidx.navigation.safe.args.generator.ext.toCamelCase
import androidx.navigation.safe.args.generator.ext.toCamelCaseAsVar
import androidx.navigation.safe.args.generator.models.Action
import androidx.navigation.safe.args.generator.models.Argument
import androidx.navigation.safe.args.generator.models.Destination
import com.squareup.javapoet.AnnotationSpec
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.CodeBlock
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.JavaFile
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.ParameterSpec
import com.squareup.javapoet.TypeName
import com.squareup.javapoet.TypeSpec
import java.util.Locale
import javax.lang.model.element.Modifier
const val L = "\$L"
const val N = "\$N"
const val T = "\$T"
const val S = "\$S"
const val BEGIN_STMT = "\$["
const val END_STMT = "\$]"
class JavaNavWriter(private val useAndroidX: Boolean = true) : NavWriter<JavaCodeFile> {
override fun generateDirectionsCodeFile(
destination: Destination,
parentDirectionsFileList: List<JavaCodeFile>
): JavaCodeFile {
val className = destination.toClassName()
val typeSpec =
generateDestinationDirectionsTypeSpec(className, destination, parentDirectionsFileList)
return JavaFile.builder(className.packageName(), typeSpec).build().toCodeFile()
}
private fun generateDestinationDirectionsTypeSpec(
className: ClassName,
destination: Destination,
parentDirectionsFileList: List<JavaCodeFile>
): TypeSpec {
val constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build()
val actionTypes = destination.actions.map { action ->
action to generateDirectionsTypeSpec(action)
}
@Suppress("NAME_SHADOWING")
val getters = actionTypes
.map { (action, actionType) ->
val annotations = Annotations.getInstance(useAndroidX)
val methodName = action.id.javaIdentifier.toCamelCaseAsVar()
if (action.args.isEmpty()) {
MethodSpec.methodBuilder(methodName)
.addAnnotation(annotations.NONNULL_CLASSNAME)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(NAV_DIRECTION_CLASSNAME)
.addStatement(
"return new $T($L)",
ACTION_ONLY_NAV_DIRECTION_CLASSNAME, action.id.accessor()
)
.build()
} else {
val constructor = actionType.methodSpecs.find(MethodSpec::isConstructor)!!
val params = constructor.parameters.joinToString(", ") { param -> param.name }
val actionTypeName = ClassName.get(
className.packageName(),
className.simpleName(),
actionType.name
)
MethodSpec.methodBuilder(methodName)
.addAnnotation(annotations.NONNULL_CLASSNAME)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addParameters(constructor.parameters)
.returns(actionTypeName)
.addStatement("return new $T($params)", actionTypeName)
.build()
}
}
// The parent destination list is ordered from the closest to the farthest parent of the
// processing destination in the graph hierarchy.
val parentGetters = mutableListOf<MethodSpec>()
parentDirectionsFileList.forEach {
val parentPackageName = it.wrapped.packageName
val parentTypeSpec = it.wrapped.typeSpec
parentTypeSpec.methodSpecs.filter { method ->
method.hasModifier(Modifier.STATIC) &&
getters.none { it.name == method.name } && // de-dupe local actions
parentGetters.none { it.name == method.name } // de-dupe parent actions
}.forEach { actionMethod ->
val params = actionMethod.parameters.joinToString(", ") { param -> param.name }
val methodSpec = MethodSpec.methodBuilder(actionMethod.name)
.addAnnotations(actionMethod.annotations)
.addModifiers(actionMethod.modifiers)
.addParameters(actionMethod.parameters)
.returns(actionMethod.returnType)
.addStatement(
"return $T.$L($params)",
ClassName.get(parentPackageName, parentTypeSpec.name), actionMethod.name
)
.build()
parentGetters.add(methodSpec)
}
}
return TypeSpec.classBuilder(className)
.addModifiers(Modifier.PUBLIC)
.addTypes(
actionTypes
.filter { (action, _) -> action.args.isNotEmpty() }
.map { (_, actionType) -> actionType }
)
.addMethod(constructor)
.addMethods(getters + parentGetters)
.build()
}
internal fun generateDirectionsTypeSpec(action: Action): TypeSpec {
val annotations = Annotations.getInstance(useAndroidX)
val specs = ClassWithArgsSpecs(action.args, annotations, privateConstructor = true)
val className = ClassName.get("", action.id.javaIdentifier.toCamelCase())
val getDestIdMethod = MethodSpec.methodBuilder("getActionId")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC)
.returns(Int::class.java)
.addStatement("return $L", action.id.accessor())
.build()
val additionalEqualsBlock = CodeBlock.builder().apply {
beginControlFlow("if ($N() != that.$N())", getDestIdMethod, getDestIdMethod).apply {
addStatement("return false")
}
endControlFlow()
}.build()
val additionalHashCodeBlock = CodeBlock.builder().apply {
addStatement("result = 31 * result + $N()", getDestIdMethod)
}.build()
val toStringHeaderBlock = CodeBlock.builder().apply {
add("$S + $L() + $S", "${className.simpleName()}(actionId=", getDestIdMethod.name, "){")
}.build()
return TypeSpec.classBuilder(className)
.addSuperinterface(NAV_DIRECTION_CLASSNAME)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addField(specs.hashMapFieldSpec)
.addMethod(specs.constructor())
.addMethods(specs.setters(className))
.addMethod(specs.toBundleMethod("getArguments", true))
.addMethod(getDestIdMethod)
.addMethods(specs.getters())
.addMethod(specs.equalsMethod(className, additionalEqualsBlock))
.addMethod(specs.hashCodeMethod(additionalHashCodeBlock))
.addMethod(specs.toStringMethod(className, toStringHeaderBlock))
.build()
}
override fun generateArgsCodeFile(
destination: Destination
): JavaCodeFile {
val annotations = Annotations.getInstance(useAndroidX)
val destName = destination.name
?: throw IllegalStateException("Destination with arguments must have name")
val className = ClassName.get(destName.packageName(), "${destName.simpleName()}Args")
val args = destination.args
val specs = ClassWithArgsSpecs(args, annotations)
val fromBundleMethod = MethodSpec.methodBuilder("fromBundle").apply {
addAnnotation(annotations.NONNULL_CLASSNAME)
addModifiers(Modifier.PUBLIC, Modifier.STATIC)
if (args.any { it.type is ObjectArrayType || it.type is ObjectType }) {
addAnnotation(
specs.suppressAnnotationSpec.toBuilder()
.addMember("value", "$S", "deprecation")
.build()
)
} else {
addAnnotation(specs.suppressAnnotationSpec)
}
val bundle = "bundle"
addParameter(
ParameterSpec.builder(BUNDLE_CLASSNAME, bundle)
.addAnnotation(specs.androidAnnotations.NONNULL_CLASSNAME)
.build()
)
returns(className)
val result = "__result"
addStatement("$T $N = new $T()", className, result, className)
addStatement("$N.setClassLoader($T.class.getClassLoader())", bundle, className)
args.forEach { arg ->
addReadSingleArgBlock("containsKey", bundle, result, arg, specs) {
arg.type.addBundleGetStatement(this, arg, arg.sanitizedName, bundle)
}
}
addStatement("return $N", result)
}.build()
val fromSavedStateHandleMethod = MethodSpec.methodBuilder("fromSavedStateHandle").apply {
addAnnotation(annotations.NONNULL_CLASSNAME)
addModifiers(Modifier.PUBLIC, Modifier.STATIC)
addAnnotation(specs.suppressAnnotationSpec)
val savedStateHandle = "savedStateHandle"
addParameter(
ParameterSpec.builder(SAVED_STATE_HANDLE_CLASSNAME, savedStateHandle)
.addAnnotation(specs.androidAnnotations.NONNULL_CLASSNAME)
.build()
)
returns(className)
val result = "__result"
addStatement("$T $N = new $T()", className, result, className)
args.forEach { arg ->
addReadSingleArgBlock("contains", savedStateHandle, result, arg, specs) {
addStatement("$N = $N.get($S)", arg.sanitizedName, savedStateHandle, arg.name)
}
}
addStatement("return $N", result)
}.build()
val constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build()
val copyConstructor = MethodSpec.constructorBuilder()
.addAnnotation(specs.suppressAnnotationSpec)
.addModifiers(Modifier.PUBLIC)
.addParameter(
ParameterSpec.builder(className, "original")
.addAnnotation(specs.androidAnnotations.NONNULL_CLASSNAME)
.build()
)
.addCode(specs.copyMapContents("this", "original"))
.build()
val fromMapConstructor = MethodSpec.constructorBuilder()
.addAnnotation(specs.suppressAnnotationSpec)
.addModifiers(Modifier.PRIVATE)
.addParameter(HASHMAP_CLASSNAME, "argumentsMap")
.addStatement(
"$N.$N.putAll($N)",
"this",
specs.hashMapFieldSpec.name,
"argumentsMap"
)
.build()
val buildMethod = MethodSpec.methodBuilder("build")
.addAnnotation(annotations.NONNULL_CLASSNAME)
.addModifiers(Modifier.PUBLIC)
.returns(className)
.addStatement(
"$T result = new $T($N)",
className,
className,
specs.hashMapFieldSpec.name
)
.addStatement("return result")
.build()
val builderClassName = ClassName.get("", "Builder")
val builderTypeSpec = TypeSpec.classBuilder("Builder")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.addField(specs.hashMapFieldSpec)
.addMethod(copyConstructor)
.addMethod(specs.constructor())
.addMethod(buildMethod)
.addMethods(specs.setters(builderClassName))
.addMethods(specs.getters(true))
.build()
val typeSpec = TypeSpec.classBuilder(className)
.addSuperinterface(NAV_ARGS_CLASSNAME)
.addModifiers(Modifier.PUBLIC)
.addField(specs.hashMapFieldSpec)
.addMethod(constructor)
.addMethod(fromMapConstructor)
.addMethod(fromBundleMethod)
.addMethod(fromSavedStateHandleMethod)
.addMethods(specs.getters())
.addMethod(specs.toBundleMethod("toBundle"))
.addMethod(specs.toSavedStateHandleMethod())
.addMethod(specs.equalsMethod(className))
.addMethod(specs.hashCodeMethod())
.addMethod(specs.toStringMethod(className))
.addType(builderTypeSpec)
.build()
return JavaFile.builder(className.packageName(), typeSpec).build().toCodeFile()
}
private fun MethodSpec.Builder.addReadSingleArgBlock(
containsMethodName: String,
sourceVariableName: String,
targetVariableName: String,
arg: Argument,
specs: ClassWithArgsSpecs,
addGetStatement: MethodSpec.Builder.() -> Unit
) {
beginControlFlow("if ($N.$containsMethodName($S))", sourceVariableName, arg.name)
addStatement("$T $N", arg.type.typeName(), arg.sanitizedName)
addGetStatement()
addNullCheck(arg, arg.sanitizedName)
addStatement(
"$targetVariableName.$N.put($S, $N)",
specs.hashMapFieldSpec,
arg.name,
arg.sanitizedName
)
nextControlFlow("else")
if (arg.defaultValue == null) {
addStatement(
"throw new $T($S)", IllegalArgumentException::class.java,
"Required argument \"${arg.name}\" is missing and does not have an " +
"android:defaultValue"
)
} else {
addStatement(
"$targetVariableName.$N.put($S, $L)",
specs.hashMapFieldSpec,
arg.name,
arg.defaultValue.write()
)
}
endControlFlow()
}
}
private class ClassWithArgsSpecs(
val args: List<Argument>,
val androidAnnotations: Annotations,
val privateConstructor: Boolean = false
) {
val suppressAnnotationSpec = AnnotationSpec.builder(SuppressWarnings::class.java)
.addMember("value", "$S", "unchecked")
.build()
val hashMapFieldSpec = FieldSpec.builder(
HASHMAP_CLASSNAME,
"arguments",
Modifier.PRIVATE,
Modifier.FINAL
).initializer("new $T()", HASHMAP_CLASSNAME).build()
fun setters(thisClassName: ClassName) = args.map { arg ->
val capitalizedName = arg.sanitizedName.capitalize(Locale.US)
MethodSpec.methodBuilder("set$capitalizedName").apply {
addAnnotation(androidAnnotations.NONNULL_CLASSNAME)
addAnnotation(suppressAnnotationSpec)
addModifiers(Modifier.PUBLIC)
addParameter(generateParameterSpec(arg))
addNullCheck(arg, arg.sanitizedName)
addStatement(
"this.$N.put($S, $N)",
hashMapFieldSpec.name,
arg.name,
arg.sanitizedName
)
addStatement("return this")
returns(thisClassName)
}.build()
}
fun constructor() = MethodSpec.constructorBuilder().apply {
if (args.filterNot(Argument::isOptional).isNotEmpty()) {
addAnnotation(suppressAnnotationSpec)
}
addModifiers(if (privateConstructor) Modifier.PRIVATE else Modifier.PUBLIC)
args.filterNot(Argument::isOptional).forEach { arg ->
addParameter(generateParameterSpec(arg))
addNullCheck(arg, arg.sanitizedName)
addStatement(
"this.$N.put($S, $N)",
hashMapFieldSpec.name,
arg.name,
arg.sanitizedName
)
}
}.build()
fun toBundleMethod(
name: String,
addOverrideAnnotation: Boolean = false
) = MethodSpec.methodBuilder(name).apply {
if (addOverrideAnnotation) {
addAnnotation(Override::class.java)
}
addAnnotation(suppressAnnotationSpec)
addAnnotation(androidAnnotations.NONNULL_CLASSNAME)
addModifiers(Modifier.PUBLIC)
returns(BUNDLE_CLASSNAME)
val result = "__result"
addStatement("$T $N = new $T()", BUNDLE_CLASSNAME, result, BUNDLE_CLASSNAME)
args.forEach { arg ->
beginControlFlow("if ($N.containsKey($S))", hashMapFieldSpec.name, arg.name).apply {
addStatement(
"$T $N = ($T) $N.get($S)",
arg.type.typeName(),
arg.sanitizedName,
arg.type.typeName(),
hashMapFieldSpec.name,
arg.name
)
arg.type.addBundlePutStatement(this, arg, result, arg.sanitizedName)
}
if (arg.defaultValue != null) {
nextControlFlow("else").apply {
arg.type.addBundlePutStatement(this, arg, result, arg.defaultValue.write())
}
}
endControlFlow()
}
addStatement("return $N", result)
}.build()
fun toSavedStateHandleMethod(
addOverrideAnnotation: Boolean = false
) = MethodSpec.methodBuilder("toSavedStateHandle").apply {
if (addOverrideAnnotation) {
addAnnotation(Override::class.java)
}
addAnnotation(suppressAnnotationSpec)
addAnnotation(androidAnnotations.NONNULL_CLASSNAME)
addModifiers(Modifier.PUBLIC)
returns(SAVED_STATE_HANDLE_CLASSNAME)
val result = "__result"
addStatement(
"$T $N = new $T()", SAVED_STATE_HANDLE_CLASSNAME, result, SAVED_STATE_HANDLE_CLASSNAME
)
args.forEach { arg ->
beginControlFlow("if ($N.containsKey($S))", hashMapFieldSpec.name, arg.name).apply {
addStatement(
"$T $N = ($T) $N.get($S)",
arg.type.typeName(),
arg.sanitizedName,
arg.type.typeName(),
hashMapFieldSpec.name,
arg.name
)
arg.type.addSavedStateHandleSetStatement(this, arg, result, arg.sanitizedName)
}
if (arg.defaultValue != null) {
nextControlFlow("else").apply {
arg.type.addSavedStateHandleSetStatement(
this, arg, result, arg.defaultValue.write()
)
}
}
endControlFlow()
}
addStatement("return $N", result)
}.build()
fun copyMapContents(to: String, from: String) = CodeBlock.builder()
.addStatement(
"$N.$N.putAll($N.$N)",
to,
hashMapFieldSpec.name,
from,
hashMapFieldSpec.name
).build()
fun getters(isBuilder: Boolean = false) = args.map { arg ->
MethodSpec.methodBuilder(getterFromArgName(arg.sanitizedName)).apply {
addModifiers(Modifier.PUBLIC)
if (!isBuilder) {
addAnnotation(suppressAnnotationSpec)
} else {
addAnnotation(
AnnotationSpec.builder(SuppressWarnings::class.java)
.addMember("value", "{$S,$S}", "unchecked", "GetterOnBuilder")
.build()
)
}
if (arg.type.allowsNullable()) {
if (arg.isNullable) {
addAnnotation(androidAnnotations.NULLABLE_CLASSNAME)
} else {
addAnnotation(androidAnnotations.NONNULL_CLASSNAME)
}
}
addStatement(
"return ($T) $N.get($S)",
arg.type.typeName(),
hashMapFieldSpec.name,
arg.name
)
returns(arg.type.typeName())
}.build()
}
fun equalsMethod(
className: ClassName,
additionalCode: CodeBlock? = null
) = MethodSpec.methodBuilder("equals").apply {
addAnnotation(Override::class.java)
addModifiers(Modifier.PUBLIC)
addParameter(TypeName.OBJECT, "object")
addCode(
"""
if (this == object) {
return true;
}
if (object == null || getClass() != object.getClass()) {
return false;
}
""".trimIndent()
)
addStatement("$T that = ($T) object", className, className)
args.forEach { (name, type, _, _, sanitizedName) ->
beginControlFlow(
"if ($N.containsKey($S) != that.$N.containsKey($S))",
hashMapFieldSpec,
name,
hashMapFieldSpec,
name
).apply {
addStatement("return false")
}.endControlFlow()
val getterName = getterFromArgName(sanitizedName, "()")
val compareExpression = when (type) {
IntType,
BoolType,
ReferenceType,
LongType -> "$getterName != that.$getterName"
FloatType -> "Float.compare(that.$getterName, $getterName) != 0"
StringType, IntArrayType, LongArrayType, FloatArrayType, StringArrayType,
BoolArrayType, ReferenceArrayType, is ObjectArrayType, is ObjectType ->
"$getterName != null ? !$getterName.equals(that.$getterName) " +
": that.$getterName != null"
else -> throw IllegalStateException("unknown type: $type")
}
beginControlFlow("if ($N)", compareExpression).apply {
addStatement("return false")
}
endControlFlow()
}
if (additionalCode != null) {
addCode(additionalCode)
}
addStatement("return true")
returns(TypeName.BOOLEAN)
}.build()
private fun getterFromArgName(sanitizedName: String, suffix: String = ""): String {
val capitalizedName = sanitizedName.capitalize(Locale.US)
return "get${capitalizedName}$suffix"
}
fun hashCodeMethod(
additionalCode: CodeBlock? = null
) = MethodSpec.methodBuilder("hashCode").apply {
addAnnotation(Override::class.java)
addModifiers(Modifier.PUBLIC)
addStatement("int result = 1")
args.forEach { (_, type, _, _, sanitizedName) ->
val getterName = getterFromArgName(sanitizedName, "()")
val hashCodeExpression = when (type) {
IntType, ReferenceType -> getterName
FloatType -> "Float.floatToIntBits($getterName)"
IntArrayType, LongArrayType, FloatArrayType, StringArrayType,
BoolArrayType, ReferenceArrayType, is ObjectArrayType ->
"java.util.Arrays.hashCode($getterName)"
StringType, is ObjectType ->
"($getterName != null ? $getterName.hashCode() : 0)"
BoolType -> "($getterName ? 1 : 0)"
LongType -> "(int)($getterName ^ ($getterName >>> 32))"
else -> throw IllegalStateException("unknown type: $type")
}
addStatement("result = 31 * result + $N", hashCodeExpression)
}
if (additionalCode != null) {
addCode(additionalCode)
}
addStatement("return result")
returns(TypeName.INT)
}.build()
fun toStringMethod(
className: ClassName,
toStringHeaderBlock: CodeBlock? = null
) = MethodSpec.methodBuilder("toString").apply {
addAnnotation(Override::class.java)
addModifiers(Modifier.PUBLIC)
addCode(
CodeBlock.builder().apply {
if (toStringHeaderBlock != null) {
add("${BEGIN_STMT}return $L", toStringHeaderBlock)
} else {
add("${BEGIN_STMT}return $S", "${className.simpleName()}{")
}
args.forEachIndexed { index, (_, _, _, _, sanitizedName) ->
val getterName = getterFromArgName(sanitizedName, "()")
val prefix = if (index == 0) "" else ", "
add("\n+ $S + $L", "$prefix$sanitizedName=", getterName)
}
add("\n+ $S;\n$END_STMT", "}")
}.build()
)
returns(ClassName.get(String::class.java))
}.build()
private fun generateParameterSpec(arg: Argument): ParameterSpec {
return ParameterSpec.builder(arg.type.typeName(), arg.sanitizedName).apply {
if (arg.type.allowsNullable()) {
if (arg.isNullable) {
addAnnotation(androidAnnotations.NULLABLE_CLASSNAME)
} else {
addAnnotation(androidAnnotations.NONNULL_CLASSNAME)
}
}
}.build()
}
}
internal fun MethodSpec.Builder.addNullCheck(
arg: Argument,
variableName: String
) {
if (arg.type.allowsNullable() && !arg.isNullable) {
beginControlFlow("if ($N == null)", variableName).apply {
addStatement(
"throw new $T($S)", IllegalArgumentException::class.java,
"Argument \"${arg.name}\" is marked as non-null but was passed a null value."
)
}
endControlFlow()
}
}
internal fun Destination.toClassName(): ClassName {
val destName = name ?: throw IllegalStateException("Destination with actions must have name")
return ClassName.get(destName.packageName(), "${destName.simpleName()}Directions")
}
| apache-2.0 | 68b5cd34485bf1ad67ad5e0c35453b3c | 40.177877 | 100 | 0.583309 | 5.171391 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/hints/HintType.kt | 2 | 11587 | // 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.codeInsight.hints
import com.intellij.codeInsight.hints.InlayInfo
import com.intellij.codeInsight.hints.Option
import com.intellij.codeInspection.util.IntentionName
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.parameterInfo.*
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.getReturnTypeReference
import org.jetbrains.kotlin.idea.util.RangeKtExpressionType.*
import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode
import org.jetbrains.kotlin.idea.util.getRangeBinaryExpressionType
import org.jetbrains.kotlin.idea.util.isRangeExpression
import org.jetbrains.kotlin.lexer.KtKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
enum class HintType(
@Nls private val description: String,
@Nls @IntentionName val showDescription: String,
@Nls @IntentionName val hideDescription: String,
defaultEnabled: Boolean
) {
PROPERTY_HINT(
KotlinBundle.message("hints.settings.types.property"),
KotlinBundle.message("hints.settings.show.types.property"),
KotlinBundle.message("hints.settings.dont.show.types.property"),
false
) {
override fun provideHintDetails(e: PsiElement): List<InlayInfoDetails> {
return providePropertyTypeHint(e)
}
override fun isApplicable(e: PsiElement): Boolean = e is KtProperty && e.getReturnTypeReference() == null && !e.isLocal
},
LOCAL_VARIABLE_HINT(
KotlinBundle.message("hints.settings.types.variable"),
KotlinBundle.message("hints.settings.show.types.variable"),
KotlinBundle.message("hints.settings.dont.show.types.variable"),
false
) {
override fun provideHintDetails(e: PsiElement): List<InlayInfoDetails> {
return providePropertyTypeHint(e)
}
override fun isApplicable(e: PsiElement): Boolean =
(e is KtProperty && e.getReturnTypeReference() == null && e.isLocal) ||
(e is KtParameter && e.isLoopParameter && e.typeReference == null) ||
(e is KtDestructuringDeclarationEntry && e.getReturnTypeReference() == null)
},
FUNCTION_HINT(
KotlinBundle.message("hints.settings.types.return"),
KotlinBundle.message("hints.settings.show.types.return"),
KotlinBundle.message("hints.settings.dont.show.types.return"),
false
) {
override fun provideHintDetails(e: PsiElement): List<InlayInfoDetails> {
e.safeAs<KtNamedFunction>()?.let { namedFunction ->
namedFunction.valueParameterList?.let { paramList ->
provideTypeHint(namedFunction, paramList.endOffset)?.let { return listOf(it) }
}
}
e.safeAs<KtExpression>()?.let { expression ->
provideLambdaReturnTypeHints(expression)?.let { return listOf(it) }
}
return emptyList()
}
override fun isApplicable(e: PsiElement): Boolean {
return e is KtNamedFunction && !(e.hasBlockBody() || e.hasDeclaredReturnType()) ||
Registry.`is`("kotlin.enable.inlay.hint.for.lambda.return.type") && e is KtExpression && e !is KtFunctionLiteral && !e.isNameReferenceInCall() && e.isLambdaReturnValueHintsApplicable(allowOneLiner = true)
}
},
PARAMETER_TYPE_HINT(
KotlinBundle.message("hints.settings.types.parameter"),
KotlinBundle.message("hints.settings.show.types.parameter"),
KotlinBundle.message("hints.settings.dont.show.types.parameter"),
false
) {
override fun provideHintDetails(e: PsiElement): List<InlayInfoDetails> {
(e as? KtParameter)?.let { param ->
param.nameIdentifier?.let { ident ->
provideTypeHint(param, ident.endOffset)?.let { return listOf(it) }
}
}
return emptyList()
}
override fun isApplicable(e: PsiElement): Boolean = e is KtParameter && e.typeReference == null && !e.isLoopParameter
},
PARAMETER_HINT(
KotlinBundle.message("hints.title.argument.name.enabled"),
KotlinBundle.message("hints.title.show.argument.name.enabled"),
KotlinBundle.message("hints.title.dont.show.argument.name.enabled"),
true
) {
override fun provideHints(e: PsiElement): List<InlayInfo> {
val callElement = e.getStrictParentOfType<KtCallElement>() ?: return emptyList()
return provideArgumentNameHints(callElement)
}
override fun isApplicable(e: PsiElement): Boolean = e is KtValueArgumentList
},
LAMBDA_RETURN_EXPRESSION(
KotlinBundle.message("hints.settings.lambda.return"),
KotlinBundle.message("hints.settings.show.lambda.return"),
KotlinBundle.message("hints.settings.dont.show.lambda.return"),
true
) {
override fun isApplicable(e: PsiElement): Boolean {
return e is KtExpression &&
e !is KtFunctionLiteral &&
!e.isNameReferenceInCall() &&
e.isLambdaReturnValueHintsApplicable()
}
override fun provideHintDetails(e: PsiElement): List<InlayInfoDetails> {
e.safeAs<KtExpression>()?.let { expression ->
provideLambdaReturnValueHints(expression)?.let { return listOf(it) }
}
return emptyList()
}
},
LAMBDA_IMPLICIT_PARAMETER_RECEIVER(
KotlinBundle.message("hints.settings.lambda.receivers.parameters"),
KotlinBundle.message("hints.settings.show.lambda.receivers.parameters"),
KotlinBundle.message("hints.settings.dont.show.lambda.receivers.parameters"),
true
) {
override fun isApplicable(e: PsiElement): Boolean {
return e is KtFunctionLiteral && e.parent is KtLambdaExpression && (e.parent as KtLambdaExpression).leftCurlyBrace.isFollowedByNewLine()
}
override fun provideHintDetails(e: PsiElement): List<InlayInfoDetails> {
e.safeAs<KtFunctionLiteral>()?.parent.safeAs<KtLambdaExpression>()?.let { expression ->
provideLambdaImplicitHints(expression)?.let { return it }
}
return emptyList()
}
},
SUSPENDING_CALL(
KotlinBundle.message("hints.settings.suspending"),
KotlinBundle.message("hints.settings.show.suspending"),
KotlinBundle.message("hints.settings.dont.show.suspending"),
false
) {
override fun isApplicable(e: PsiElement) = e.isNameReferenceInCall() && isApplicationInternalMode()
override fun provideHints(e: PsiElement): List<InlayInfo> {
val callExpression = e.parent as? KtCallExpression ?: return emptyList()
return provideSuspendingCallHint(callExpression)?.let { listOf(it) } ?: emptyList()
}
},
RANGES(
KotlinBundle.message("hints.settings.ranges"),
KotlinBundle.message("hints.settings.show.ranges"),
KotlinBundle.message("hints.settings.dont.show.ranges"),
true
) {
override fun isApplicable(e: PsiElement): Boolean = e is KtBinaryExpression && e.isRangeExpression()
override fun provideHintDetails(e: PsiElement): List<InlayInfoDetails> {
val binaryExpression = e.safeAs<KtBinaryExpression>() ?: return emptyList()
val leftExp = binaryExpression.left ?: return emptyList()
val rightExp = binaryExpression.right ?: return emptyList()
val operationReference: KtOperationReferenceExpression = binaryExpression.operationReference
val type = binaryExpression.getRangeBinaryExpressionType() ?: return emptyList()
val (leftText: String, rightText: String?) = when (type) {
RANGE_TO -> {
KotlinBundle.message("hints.ranges.lessOrEqual") to KotlinBundle.message("hints.ranges.lessOrEqual")
}
RANGE_UNTIL -> {
KotlinBundle.message("hints.ranges.lessOrEqual") to null
}
DOWN_TO -> {
if (operationReference.hasIllegalLiteralPrefixOrSuffix()) return emptyList()
KotlinBundle.message("hints.ranges.greaterOrEqual") to KotlinBundle.message("hints.ranges.greaterOrEqual")
}
UNTIL -> {
if (operationReference.hasIllegalLiteralPrefixOrSuffix()) return emptyList()
KotlinBundle.message("hints.ranges.lessOrEqual") to KotlinBundle.message("hints.ranges.less")
}
}
val leftInfo = InlayInfo(text = leftText, offset = leftExp.endOffset)
val rightInfo = rightText?.let { InlayInfo(text = it, offset = rightExp.startOffset) }
return listOfNotNull(
InlayInfoDetails(leftInfo, listOf(TextInlayInfoDetail(leftText, smallText = false))),
rightInfo?.let { InlayInfoDetails(it, listOf(TextInlayInfoDetail(rightText, smallText = false))) }
)
}
};
companion object {
private val values = values()
fun resolve(e: PsiElement): List<HintType> =
values.filter { it.isApplicable(e) }
private fun KtOperationReferenceExpression.hasIllegalLiteralPrefixOrSuffix(): Boolean {
val prevLeaf = PsiTreeUtil.prevLeaf(this)
val nextLeaf = PsiTreeUtil.nextLeaf(this)
return prevLeaf?.illegalLiteralPrefixOrSuffix() == true || nextLeaf?.illegalLiteralPrefixOrSuffix() == true
}
private fun PsiElement.illegalLiteralPrefixOrSuffix(): Boolean {
val elementType = this.node.elementType
return (elementType === KtTokens.IDENTIFIER) ||
(elementType === KtTokens.INTEGER_LITERAL) ||
(elementType === KtTokens.FLOAT_LITERAL) ||
elementType is KtKeywordToken
}
}
abstract fun isApplicable(e: PsiElement): Boolean
open fun provideHints(e: PsiElement): List<InlayInfo> = emptyList()
open fun provideHintDetails(e: PsiElement): List<InlayInfoDetails> =
provideHints(e).map { InlayInfoDetails(it, listOf(TextInlayInfoDetail(it.text))) }
val option = Option("SHOW_${this.name}", { this.description }, defaultEnabled)
val enabled
get() = option.get()
}
data class InlayInfoDetails(val inlayInfo: InlayInfo, val details: List<InlayInfoDetail>)
sealed class InlayInfoDetail(val text: String)
class TextInlayInfoDetail(text: String, val smallText: Boolean = true): InlayInfoDetail(text) {
override fun toString(): String = "[$text]"
}
class TypeInlayInfoDetail(text: String, val fqName: String?): InlayInfoDetail(text) {
override fun toString(): String = "[$text :$fqName]"
}
class PsiInlayInfoDetail(text: String, val element: PsiElement): InlayInfoDetail(text) {
override fun toString(): String = "[$text @ $element]"
}
| apache-2.0 | 3ccd77f7c92dbf3e28295cd43d96a926 | 44.261719 | 224 | 0.662639 | 4.915995 | false | false | false | false |
JetBrains/xodus | utils/src/main/kotlin/jetbrains/exodus/core/dataStructures/persistent/PersistentBitTreeLongSet.kt | 1 | 9850 | /**
* Copyright 2010 - 2022 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
*
* 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 jetbrains.exodus.core.dataStructures.persistent
import jetbrains.exodus.core.dataStructures.hash.LongIterator
import java.util.*
private const val BITS_PER_ENTRY = 10
class PersistentBitTreeLongSet : PersistentLongSet {
private val root: Root
private val bitsPerEntry: Int
private val elementsPerEntry: Int
private val mask: Int
@JvmOverloads constructor(bitsPerEntry: Int = BITS_PER_ENTRY) {
this.bitsPerEntry = bitsPerEntry
elementsPerEntry = 1 shl bitsPerEntry
mask = elementsPerEntry - 1
this.root = Root(Persistent23Tree(), 0)
}
private constructor(source: PersistentBitTreeLongSet) {
bitsPerEntry = source.bitsPerEntry
elementsPerEntry = source.elementsPerEntry
mask = source.mask
this.root = source.root.clone
}
override fun beginRead(): PersistentLongSet.ImmutableSet {
return ImmutableSet(root.map.beginRead(), root.size, bitsPerEntry, mask)
}
override fun getClone(): PersistentLongSet {
return PersistentBitTreeLongSet(this)
}
override fun beginWrite(): PersistentLongSet.MutableSet {
return MutableSet(root.map.beginWrite(), root.size, bitsPerEntry, mask, this)
}
private class ImmutableSet internal constructor(private val map: AbstractPersistent23Tree<Entry>,
private val size: Int,
private val bitsPerEntry: Int,
private val mask: Int) : PersistentLongSet.ImmutableSet {
private fun getEntryByIndex(index: Long): Entry? {
val root = map.root ?: return null
return root.getByWeight(index)
}
override fun contains(key: Long): Boolean {
val entry = getEntryByIndex(key shr bitsPerEntry)
return entry != null && entry.bits.get(key.toInt() and mask)
}
override fun longIterator(): LongIterator {
return ItemIterator(map.iterator(), bitsPerEntry)
}
override fun reverseLongIterator(): LongIterator {
return ItemIterator(map.reverseIterator(), bitsPerEntry, isReversed = true)
}
override fun tailLongIterator(key: Long): LongIterator {
val entry = getEntryByIndex(key shr bitsPerEntry)
return if (entry == null) LongIterator.EMPTY else
skipTail(ItemIterator(map.tailIterator(entry), bitsPerEntry), key)
}
override fun tailReverseLongIterator(key: Long): LongIterator {
val entry = getEntryByIndex(key shr bitsPerEntry)
return if (entry == null) LongIterator.EMPTY else
skipTail(ItemIterator(map.tailReverseIterator(entry), bitsPerEntry, isReversed = true), key)
}
override fun isEmpty(): Boolean {
return size == 0
}
override fun size(): Int {
return size
}
}
internal class MutableSet internal constructor(private val mutableSet: Persistent23Tree.MutableTree<Entry>,
private var size: Int,
private val bitsPerEntry: Int,
private val mask: Int,
private val baseSet: PersistentBitTreeLongSet) : PersistentLongSet.MutableSet {
private fun getEntryByIndex(index: Long): Entry? {
val root = mutableSet.root ?: return null
return root.getByWeight(index)
}
override fun contains(key: Long): Boolean {
val entry = getEntryByIndex(key shr bitsPerEntry)
return entry != null && entry.bits.get(key.toInt() and mask)
}
override fun longIterator(): LongIterator {
return ItemIterator(mutableSet.iterator(), bitsPerEntry)
}
override fun reverseLongIterator(): LongIterator {
return ItemIterator(mutableSet.reverseIterator(), bitsPerEntry, isReversed = true)
}
override fun tailLongIterator(key: Long): LongIterator {
val entry = getEntryByIndex(key shr bitsPerEntry)
return if (entry == null) LongIterator.EMPTY else
skipTail(ItemIterator(mutableSet.tailIterator(entry), bitsPerEntry), key)
}
override fun tailReverseLongIterator(key: Long): LongIterator {
val entry = getEntryByIndex(key shr bitsPerEntry)
return if (entry == null) LongIterator.EMPTY else
skipTail(ItemIterator(mutableSet.tailReverseIterator(entry), bitsPerEntry, isReversed = true), key)
}
override fun isEmpty(): Boolean {
return size == 0
}
override fun size(): Int {
return size
}
override fun add(key: Long) {
val index = key shr bitsPerEntry
var entry = getEntryByIndex(index)
val bitIndex = key.toInt() and mask
if (entry == null) {
entry = Entry(index, mask + 1)
mutableSet.add(entry)
size++
} else {
if (entry.bits.get(bitIndex)) {
return
} else {
val copy = Entry(index, entry, mask + 1)
mutableSet.add(copy)
entry = copy
size++
}
}
entry.bits.set(bitIndex)
}
override fun remove(key: Long): Boolean {
val index = key shr bitsPerEntry
val entry = getEntryByIndex(index) ?: return false
val bitIndex = key.toInt() and mask
if (entry.bits.get(bitIndex)) {
size--
} else {
return false
}
val copy = Entry(index, entry, mask + 1)
copy.bits.clear(bitIndex)
if (copy.bits.isEmpty) {
mutableSet.exclude(entry)
} else {
mutableSet.add(copy)
}
return true
}
override fun clear() {
mutableSet.root = null
size = 0
}
override fun endWrite(): Boolean {
if (!mutableSet.endWrite()) {
return false
}
// TODO: consistent size update
baseSet.root.size = size
return true
}
}
internal class Entry : LongComparable<Entry> {
internal val index: Long
internal val bits: BitSet
constructor(index: Long, elementsPerEntry: Int) {
this.index = index
this.bits = BitSet(elementsPerEntry)
}
constructor(index: Long, other: Entry, elementsPerEntry: Int) {
this.index = index
this.bits = BitSet(elementsPerEntry)
this.bits.or(other.bits)
}
override fun getWeight(): Long {
return index
}
override fun compareTo(other: Entry): Int {
return index.compareTo(other.index)
}
}
internal class Root internal constructor(internal val map: Persistent23Tree<Entry>, internal var size: Int) {
val clone: Root get() = Root(map.clone, size)
}
private open class ItemIterator internal constructor(private val iterator: Iterator<Entry>,
private val bitsPerEntry: Int,
private val isReversed: Boolean = false) : LongIterator {
private lateinit var currentEntry: Entry
private var currentEntryBase: Long = 0
private var next = -1
override fun next(): Long {
return nextLong()
}
override fun nextLong(): Long {
if (!hasNext()) {
throw NoSuchElementException()
}
val index = this.next
val result = index + currentEntryBase
this.next = nextBit(currentEntry, next + if (isReversed) -1 else 1)
return result
}
override fun hasNext(): Boolean {
return next != -1 || fetchEntry()
}
private fun fetchEntry(): Boolean {
while (iterator.hasNext()) {
val entry = iterator.next()
val nextIndex = nextBit(entry)
if (nextIndex != -1) {
currentEntry = entry
currentEntryBase = entry.index shl bitsPerEntry
next = nextIndex
return true
}
}
return false
}
override fun remove() {
throw UnsupportedOperationException()
}
private fun nextBit(e: Entry, fromBit: Int = Int.MAX_VALUE): Int {
val bits = e.bits
return if (isReversed) {
bits.previousSetBit(if (fromBit == Int.MAX_VALUE) bits.size() else fromBit)
} else {
bits.nextSetBit(if (fromBit == Int.MAX_VALUE) 0 else fromBit)
}
}
}
}
| apache-2.0 | 4dd60d61b8b4912d42ddb29403bc9ac2 | 33.929078 | 130 | 0.560609 | 4.959718 | false | false | false | false |
SimpleMobileTools/Simple-Calendar | app/src/main/kotlin/com/simplemobiletools/calendar/pro/dialogs/EditEventTypeDialog.kt | 1 | 3893 | package com.simplemobiletools.calendar.pro.dialogs
import android.app.Activity
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.calendar.pro.R
import com.simplemobiletools.calendar.pro.extensions.eventsHelper
import com.simplemobiletools.calendar.pro.helpers.OTHER_EVENT
import com.simplemobiletools.calendar.pro.models.EventType
import com.simplemobiletools.commons.dialogs.ColorPickerDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import kotlinx.android.synthetic.main.dialog_event_type.view.*
class EditEventTypeDialog(val activity: Activity, var eventType: EventType? = null, val callback: (eventType: EventType) -> Unit) {
private var isNewEvent = eventType == null
init {
if (eventType == null) {
eventType = EventType(null, "", activity.getProperPrimaryColor())
}
val view = activity.layoutInflater.inflate(R.layout.dialog_event_type, null).apply {
setupColor(type_color)
type_title.setText(eventType!!.title)
type_color.setOnClickListener {
if (eventType?.caldavCalendarId == 0) {
ColorPickerDialog(activity, eventType!!.color) { wasPositivePressed, color ->
if (wasPositivePressed) {
eventType!!.color = color
setupColor(type_color)
}
}
} else {
SelectEventTypeColorDialog(activity, eventType!!) {
eventType!!.color = it
setupColor(type_color)
}
}
}
}
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view, this, if (isNewEvent) R.string.add_new_type else R.string.edit_type) { alertDialog ->
alertDialog.showKeyboard(view.type_title)
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
ensureBackgroundThread {
eventTypeConfirmed(view.type_title.value, alertDialog)
}
}
}
}
}
private fun setupColor(view: ImageView) {
view.setFillWithStroke(eventType!!.color, activity.getProperBackgroundColor())
}
private fun eventTypeConfirmed(title: String, dialog: AlertDialog) {
val eventTypeClass = eventType?.type ?: OTHER_EVENT
val eventTypeId = if (eventTypeClass == OTHER_EVENT) {
activity.eventsHelper.getEventTypeIdWithTitle(title)
} else {
activity.eventsHelper.getEventTypeIdWithClass(eventTypeClass)
}
var isEventTypeTitleTaken = isNewEvent && eventTypeId != -1L
if (!isEventTypeTitleTaken) {
isEventTypeTitleTaken = !isNewEvent && eventType!!.id != eventTypeId && eventTypeId != -1L
}
if (title.isEmpty()) {
activity.toast(R.string.title_empty)
return
} else if (isEventTypeTitleTaken) {
activity.toast(R.string.type_already_exists)
return
}
eventType!!.title = title
if (eventType!!.caldavCalendarId != 0) {
eventType!!.caldavDisplayName = title
}
eventType!!.id = activity.eventsHelper.insertOrUpdateEventTypeSync(eventType!!)
if (eventType!!.id != -1L) {
activity.runOnUiThread {
dialog.dismiss()
callback(eventType!!)
}
} else {
activity.toast(R.string.editing_calendar_failed)
}
}
}
| gpl-3.0 | 7e0ece53be4aee540bb00ca140b6e6b5 | 38.323232 | 133 | 0.601593 | 5.06901 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/lookups/factories/KotlinFirLookupElementFactory.kt | 3 | 3380 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.completion.lookups.factories
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtNamedSymbol
import org.jetbrains.kotlin.analysis.api.types.KtSubstitutor
import org.jetbrains.kotlin.idea.completion.impl.k2.ImportStrategyDetector
import org.jetbrains.kotlin.idea.completion.lookups.CallableInsertionOptions
import org.jetbrains.kotlin.idea.completion.lookups.ImportStrategy
import org.jetbrains.kotlin.idea.completion.lookups.detectCallableOptions
import org.jetbrains.kotlin.name.FqName
@ApiStatus.Internal
class KotlinFirLookupElementFactory {
private val classLookupElementFactory = ClassLookupElementFactory()
private val variableLookupElementFactory = VariableLookupElementFactory()
private val functionLookupElementFactory = FunctionLookupElementFactory()
private val typeParameterLookupElementFactory = TypeParameterLookupElementFactory()
private val packagePartLookupElementFactory = PackagePartLookupElementFactory()
fun KtAnalysisSession.createLookupElement(
symbol: KtNamedSymbol,
importStrategyDetector: ImportStrategyDetector,
importingStrategy: ImportStrategy? = null,
substitutor: KtSubstitutor = KtSubstitutor.Empty(token)
): LookupElement {
return when (symbol) {
is KtCallableSymbol -> createCallableLookupElement(
symbol,
detectCallableOptions(symbol, importStrategyDetector),
substitutor,
)
is KtClassLikeSymbol -> with(classLookupElementFactory) { createLookup(symbol, importingStrategy ?: importStrategyDetector.detectImportStrategy(symbol)) }
is KtTypeParameterSymbol -> with(typeParameterLookupElementFactory) { createLookup(symbol) }
else -> throw IllegalArgumentException("Cannot create a lookup element for $symbol")
}
}
fun KtAnalysisSession.createCallableLookupElement(
symbol: KtCallableSymbol,
options: CallableInsertionOptions,
substitutor: KtSubstitutor,
): LookupElementBuilder {
return when (symbol) {
is KtFunctionSymbol -> with(functionLookupElementFactory) { createLookup(symbol, options, substitutor) }
is KtVariableLikeSymbol -> with(variableLookupElementFactory) { createLookup(symbol, options, substitutor) }
else -> throw IllegalArgumentException("Cannot create a lookup element for $symbol")
}
}
fun createPackagePartLookupElement(packagePartFqName: FqName): LookupElement =
packagePartLookupElementFactory.createPackagePartLookupElement(packagePartFqName)
fun KtAnalysisSession.createLookupElementForClassLikeSymbol(
symbol: KtClassLikeSymbol,
importingStrategy: ImportStrategy,
): LookupElement? {
if (symbol !is KtNamedSymbol) return null
return with(classLookupElementFactory) { createLookup(symbol, importingStrategy) }
}
}
| apache-2.0 | dde98659e0eb92fb6fd05f1e601bd611 | 47.985507 | 166 | 0.766272 | 5.531915 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.