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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
FredJul/TaskGame | TaskGame-Hero/src/main/java/net/fred/taskgame/hero/models/Card.kt | 1 | 24436 | /*
* Copyright (c) 2012-2017 Frederic Julian
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package net.fred.taskgame.hero.models
import android.support.annotation.DrawableRes
import android.util.SparseBooleanArray
import net.fred.taskgame.hero.R
import net.fred.taskgame.hero.logic.BattleManager
import net.frju.androidquery.annotation.DbField
import net.frju.androidquery.annotation.DbModel
import net.frju.androidquery.gen.CARD
import org.parceler.Parcel
import java.util.*
@Parcel(Parcel.Serialization.BEAN)
@DbModel(databaseProvider = LocalDatabaseProvider::class)
class Card : Cloneable {
interface FightAction {
fun applyDamageFromOpponent(current: Card, opponent: Card)
}
interface SupportAction {
fun executeSupportAction(manager: BattleManager, fromEnemyPointOfView: Boolean)
}
enum class Type {
CREATURE, SUPPORT
}
@DbField(primaryKey = true)
var id = INVALID_ID
@DbField
var isObtained: Boolean = false
@DbField
var isInDeck: Boolean = false
var type = Type.CREATURE
var name = ""
var desc = ""
var neededSlots: Int = 0
var attack: Int = 0
var defense: Int = 0
var useWeapon: Boolean = false
var useMagic: Boolean = false
@DrawableRes
var iconResId = INVALID_ID
var price: Int = 0
@Transient
var fightAction: FightAction
@org.parceler.Transient get
@org.parceler.Transient set
@Transient
var supportAction: SupportAction? = null
@org.parceler.Transient get
@org.parceler.Transient set
init {
fightAction = object : FightAction {
override fun applyDamageFromOpponent(current: Card, opponent: Card) {
current.defense -= opponent.attack
}
}
}
public override fun clone(): Card {
val card = Card()
card.id = id
card.type = type
card.name = name
card.desc = desc
card.neededSlots = neededSlots
card.attack = attack
card.defense = defense
card.useWeapon = useWeapon
card.useMagic = useMagic
card.iconResId = iconResId
card.price = price
card.isObtained = isObtained
card.isInDeck = isInDeck
card.fightAction = fightAction
card.supportAction = supportAction
return card
}
companion object {
val CREATURE_TROLL = 0
val CREATURE_TROLL_2 = 1
val CREATURE_TROLL_3 = 2
val CREATURE_TROLL_4 = 3
val CREATURE_SKELETON = 10
val CREATURE_SKELETON_2 = 11
val CREATURE_SKELETON_3 = 12
val CREATURE_ENCHANTED_TREE = 20
val CREATURE_ENCHANTED_TREE_2 = 21
val CREATURE_SYLPH = 30
val CREATURE_SYLPH_2 = 31
val CREATURE_SYLPH_3 = 32
val CREATURE_SNAKE = 40
val CREATURE_SNAKE_2 = 41
val CREATURE_ZOMBIE = 50
val CREATURE_ZOMBIE_2 = 51
val CREATURE_MERMAN = 60
val CREATURE_MERMAN_2 = 61
val CREATURE_MERMAN_3 = 62
val CREATURE_MERMAN_4 = 63
val CREATURE_EMPTY_ARMOR = 70
val CREATURE_EMPTY_ARMOR_2 = 71
val CREATURE_EMPTY_ARMOR_3 = 72
val CREATURE_EMPTY_ARMOR_4 = 73
val CREATURE_GRUNT = 80
val CREATURE_GRUNT_2 = 81
val CREATURE_GRUNT_3 = 82
val CREATURE_GRUNT_4 = 83
val CREATURE_LICH = 90
val CREATURE_LICH_2 = 91
val CREATURE_LICH_3 = 92
val CREATURE_LICH_4 = 93
val CREATURE_SPECTRE = 100
val CREATURE_SPECTRE_2 = 101
val CREATURE_SPECTRE_3 = 102
val CREATURE_SPECTRE_4 = 103
val CREATURE_SPECTRE_5 = 104
val SUPPORT_POWER_POTION = 10000
val SUPPORT_ADD_WEAPON = 10001
val SUPPORT_WEAPON_EROSION = 10002
val SUPPORT_FREEDOM = 10003
val SUPPORT_CONFUSION = 10004
val SUPPORT_SURPRISE = 10005
val SUPPORT_MEDICAL_ATTENTION = 10006
val SUPPORT_SWITCH_POTION = 10007
val INVALID_ID = 0
val allCardsMap = LinkedHashMap<Int, Card>()
val obtainedCardList: MutableList<Card>
get() {
return Card.allCardsMap.values.filter(Card::isObtained).toMutableList()
}
val nonObtainedCardList: MutableList<Card>
get() = getNonObtainedCardList(Level.correspondingDeckSlots)
fun getNonObtainedCardList(totalDeckSlots: Int): MutableList<Card> {
val nonObtainedList = Card.allCardsMap.values.filterTo(ArrayList<Card>()) {
// Do not display all card immediately
!it.isObtained && it.neededSlots <= totalDeckSlots / 2
}
return nonObtainedList
}
val deckCardList: List<Card>
get() {
val deckCardList = Card.allCardsMap.values.filterTo(ArrayList<Card>(), Card::isInDeck)
return deckCardList
}
fun populate() {
allCardsMap.clear()
val obtainedList = SparseBooleanArray()
val inDeckList = SparseBooleanArray()
for (card in CARD.select().query().toArray()) {
obtainedList.append(card.id, card.isObtained)
inDeckList.append(card.id, card.isInDeck)
}
/** */
/****** CREATURE CARDS */
/** */
var card = generateDefaultCreatureCard(CREATURE_MERMAN, 1, obtainedList, inDeckList)
card.price = 0 // First one is free
card.name = "Merman"
card.attack = 1
card.defense = 1
card.iconResId = R.drawable.merman
card.desc = "Mermans are famous for their courage, even if it's not always enough to save their lives\n ● Resistant to magic: -1 received damage"
card.fightAction = object : FightAction {
override fun applyDamageFromOpponent(current: Card, opponent: Card) {
if (opponent.useMagic) {
current.defense -= if (opponent.attack >= 1) opponent.attack - 1 else opponent.attack
} else {
current.defense -= opponent.attack
}
}
}
checkCreatureCard(card)
card = generateDefaultCreatureCard(CREATURE_SYLPH, 1, obtainedList, inDeckList)
card.name = "Sylph"
card.attack = 1
card.defense = 2
card.useMagic = true
card.iconResId = R.drawable.sylph
card.desc = "Looks kind and peaceful, but her basic wind magic can surprise you\n ● Weak against weapons: +1 received damage"
card.fightAction = object : FightAction {
override fun applyDamageFromOpponent(current: Card, opponent: Card) {
if (opponent.useWeapon) {
current.defense -= opponent.attack + 1
} else {
current.defense -= opponent.attack
}
}
}
checkCreatureCard(card)
card = generateDefaultCreatureCard(CREATURE_TROLL, 2, obtainedList, inDeckList)
card.isObtained = true // the only card you get for free at the beginning
card.isInDeck = inDeckList.size() == 0 || inDeckList.get(card.id) // by default, add it
card.name = "Baby Troll"
card.attack = 2
card.defense = 4
card.iconResId = R.drawable.troll
card.desc = "Troll babies always try to eat everything and doesn't really care if it's human or not\n ● Weak against magic: +1 received damage"
card.fightAction = object : FightAction {
override fun applyDamageFromOpponent(current: Card, opponent: Card) {
if (opponent.useMagic) {
current.defense -= opponent.attack + 1
} else {
current.defense -= opponent.attack
}
}
}
checkCreatureCard(card)
card = generateDefaultCreatureCard(CREATURE_SKELETON, 2, obtainedList, inDeckList)
card.name = "Skeleton Archer"
card.attack = 1
card.defense = 6
card.useWeapon = true
card.iconResId = R.drawable.skeleton
card.desc = "Deads are not totally dead, and they strangely know how to send arrows in your face\n ● Resistant to magic: -1 received damage"
card.fightAction = object : FightAction {
override fun applyDamageFromOpponent(current: Card, opponent: Card) {
if (opponent.useMagic) {
current.defense -= if (opponent.attack >= 1) opponent.attack - 1 else opponent.attack
} else {
current.defense -= opponent.attack
}
}
}
checkCreatureCard(card)
card = generateDefaultCreatureCard(CREATURE_SYLPH_2, 3, obtainedList, inDeckList)
card.name = "Charming Sylph"
card.attack = 2
card.defense = 7
card.useMagic = true
card.iconResId = R.drawable.sylph_2
card.desc = "Will you dare hit a beautiful lady?\n ● Weak against weapons: +1 received damage"
card.fightAction = object : FightAction {
override fun applyDamageFromOpponent(current: Card, opponent: Card) {
if (opponent.useWeapon) {
current.defense -= opponent.attack + 1
} else {
current.defense -= opponent.attack
}
}
}
checkCreatureCard(card)
card = generateDefaultCreatureCard(CREATURE_GRUNT, 3, obtainedList, inDeckList)
card.name = "Grunt"
card.attack = 3
card.defense = 5
card.iconResId = R.drawable.grunt
card.desc = "Half human, half beast. Killing someone is a natural law for them and they don't perceive that as a problem."
checkCreatureCard(card)
card = generateDefaultCreatureCard(CREATURE_ENCHANTED_TREE, 3, obtainedList, inDeckList)
card.name = "Enchanted Tree"
card.attack = 3
card.defense = 6
card.iconResId = R.drawable.enchanted_tree
card.desc = "Nature is beautiful, except maybe when it tries to kill you\n ● Weak against weapons: +2 received damage"
card.fightAction = object : FightAction {
override fun applyDamageFromOpponent(current: Card, opponent: Card) {
if (opponent.useWeapon) {
current.defense -= opponent.attack + 2
} else {
current.defense -= opponent.attack
}
}
}
checkCreatureCard(card)
card = generateDefaultCreatureCard(CREATURE_LICH, 4, obtainedList, inDeckList)
card.name = "Lich"
card.attack = 5
card.defense = 6
card.useMagic = true
card.iconResId = R.drawable.lich
card.desc = "Ancient mage who found a way to not be affected by the time anymore"
checkCreatureCard(card)
card = generateDefaultCreatureCard(CREATURE_EMPTY_ARMOR, 4, obtainedList, inDeckList)
card.name = "Empty armor"
card.attack = 3
card.defense = 11
card.useWeapon = true
card.iconResId = R.drawable.empty_armor
card.desc = "Looks empty and harmless, but don't turn your back on it or you may regret it"
checkCreatureCard(card)
card = generateDefaultCreatureCard(CREATURE_SPECTRE, 5, obtainedList, inDeckList)
card.name = "Spectre"
card.attack = 6
card.price = card.neededSlots * 50 + 100
card.defense = 10
card.useMagic = true
card.iconResId = R.drawable.spectre
card.desc = "It's never good when nightmare creatures are becoming reality and attack you"
checkCreatureCard(card)
card = generateDefaultCreatureCard(CREATURE_ZOMBIE, 6, obtainedList, inDeckList)
card.name = "Zombie"
card.attack = 4
card.defense = 14
card.iconResId = R.drawable.zombie
card.desc = "Why dead people cannot live like everyone else?"
checkCreatureCard(card)
card = generateDefaultCreatureCard(CREATURE_SNAKE, 6, obtainedList, inDeckList)
card.name = "M. Python"
card.attack = 7
card.defense = 9
card.useWeapon = true
card.iconResId = R.drawable.snake
card.desc = "They are fast and, like Brian, always look at the bright side of life\n ● Weak against magic: +3 received damage"
card.fightAction = object : FightAction {
override fun applyDamageFromOpponent(current: Card, opponent: Card) {
if (opponent.useMagic) {
current.defense -= opponent.attack + 3
} else {
current.defense -= opponent.attack
}
}
}
checkCreatureCard(card)
card = generateDefaultCreatureCard(CREATURE_TROLL_2, 7, obtainedList, inDeckList)
card.name = "Slinger Troll"
card.attack = 4
card.defense = 17
card.useWeapon = true
card.iconResId = R.drawable.troll_2
card.desc = "Always play 'Rock' in rock-paper-scissor game\n ● Resistant to weapon: -2 received damage\n ● Weak against magic: +3 received damage"
card.fightAction = object : FightAction {
override fun applyDamageFromOpponent(current: Card, opponent: Card) {
if (opponent.useMagic) {
current.defense -= opponent.attack + 3
} else if (opponent.useWeapon) {
current.defense -= if (opponent.attack - 2 > 0) opponent.attack - 2 else 0
} else {
current.defense -= opponent.attack
}
}
}
checkCreatureCard(card)
card = generateDefaultCreatureCard(CREATURE_GRUNT_2, 7, obtainedList, inDeckList)
card.name = "Crossbowman Grunt"
card.attack = 9
card.defense = 11
card.useWeapon = true
card.iconResId = R.drawable.grunt_2
card.desc = "Born with less muscles than others, he compensates with a good manipulation of a crossbow"
checkCreatureCard(card)
/** */
/****** SUPPORT CARDS */
/** */
card = generateDefaultSupportCard(SUPPORT_MEDICAL_ATTENTION, 2, obtainedList, inDeckList)
card.name = "Medical Attention"
card.iconResId = R.drawable.medical_attention
card.desc = "Ok it's a summoned creature, but does that means you should be heartless?\n ● +4 defense if wounded"
card.supportAction = object : SupportAction {
override fun executeSupportAction(manager: BattleManager, fromEnemyPointOfView: Boolean) {
manager.getLastUsedPlayerCreatureCard(fromEnemyPointOfView)?.let { player ->
//TODO: does not take in account the previous defense increase
allCardsMap[player.id]?.let { originalCard ->
val defenseDiff = originalCard.defense - player.defense
if (defenseDiff > 0) {
player.defense += Math.min(4, defenseDiff)
}
}
}
}
}
card = generateDefaultSupportCard(SUPPORT_ADD_WEAPON, 3, obtainedList, inDeckList)
card.name = "Battle axe"
card.iconResId = R.drawable.axe
card.desc = "The best way to gain respect from your enemy is by putting an axe in his face\n ● +6 attack if he doesn't use weapon nor magic"
card.supportAction = object : SupportAction {
override fun executeSupportAction(manager: BattleManager, fromEnemyPointOfView: Boolean) {
manager.getLastUsedPlayerCreatureCard(fromEnemyPointOfView)?.let { player ->
if (!player.useWeapon && !player.useMagic) {
player.attack += 6
}
}
}
}
card = generateDefaultSupportCard(SUPPORT_WEAPON_EROSION, 3, obtainedList, inDeckList)
card.name = "Weapon erosion"
card.iconResId = R.drawable.erode_weapon
card.desc = "Your enemy weapon starts to run into pieces. Serves him damned right!\n ● -5 attack if he uses a weapon"
card.supportAction = object : SupportAction {
override fun executeSupportAction(manager: BattleManager, fromEnemyPointOfView: Boolean) {
manager.getLastUsedEnemyCreatureCard(fromEnemyPointOfView)?.let { enemy ->
if (enemy.useWeapon) {
enemy.attack -= 5
if (enemy.attack < 0) {
enemy.attack = 0
}
}
}
}
}
card = generateDefaultSupportCard(SUPPORT_POWER_POTION, 4, obtainedList, inDeckList)
card.name = "(Fake) Potion of invincibility"
card.iconResId = R.drawable.red_potion
card.desc = "It's only syrup, but placebo effect makes your creature feel invincible\n ● Multiply attack by 2\n ● Divide defense by 1.3"
card.supportAction = object : SupportAction {
override fun executeSupportAction(manager: BattleManager, fromEnemyPointOfView: Boolean) {
manager.getLastUsedPlayerCreatureCard(fromEnemyPointOfView)?.let { player ->
player.attack *= 2
player.defense = (player.defense / 1.3).toInt()
if (player.defense <= 0) {
player.defense = 1
}
}
}
}
card = generateDefaultSupportCard(SUPPORT_SURPRISE, 4, obtainedList, inDeckList)
card.name = "Surprise!"
card.iconResId = R.drawable.surprise
card.desc = "Forget honor and attack the enemy from behind, it's more effective\n ● If you kill the enemy this turn, you'll not receive any damage"
card.supportAction = object : SupportAction {
override fun executeSupportAction(manager: BattleManager, fromEnemyPointOfView: Boolean) {
manager.getLastUsedPlayerCreatureCard(fromEnemyPointOfView)?.let { player ->
manager.getLastUsedEnemyCreatureCard(fromEnemyPointOfView)?.let { enemy ->
if (enemy.defense <= player.attack) {
player.defense += enemy.attack
}
}
}
}
}
card = generateDefaultSupportCard(SUPPORT_CONFUSION, 5, obtainedList, inDeckList)
card.name = "Confusion"
card.iconResId = R.drawable.confusion
card.desc = "Confuse your enemy with a sneaky but efficient lie\n ● Enemy is confused and skips one turn"
card.supportAction = object : SupportAction {
override fun executeSupportAction(manager: BattleManager, fromEnemyPointOfView: Boolean) {
manager.stunEnemy(fromEnemyPointOfView)
}
}
card = generateDefaultSupportCard(SUPPORT_FREEDOM, 6, obtainedList, inDeckList)
card.name = "Freedom"
card.iconResId = R.drawable.unshackled
card.desc = "Free your creature from your control. It will charge the enemy with all his forces, and profit of the breach to run away.\n ● Multiply attack by 3\n ● Your creature run away after 1 round"
card.supportAction = object : SupportAction {
override fun executeSupportAction(manager: BattleManager, fromEnemyPointOfView: Boolean) {
manager.getLastUsedPlayerCreatureCard(fromEnemyPointOfView)?.let { player ->
player.defense = 0 //TODO: not really dead, but does the job for now
player.attack *= 3
}
}
}
card = generateDefaultSupportCard(SUPPORT_SWITCH_POTION, 7, obtainedList, inDeckList)
card.name = "Switch potion"
card.iconResId = R.drawable.purple_potion
card.desc = "Your creature switch it's attack/defense level with his opponent's ones. How does the potion work? Well, it's a secret."
card.supportAction = object : SupportAction {
override fun executeSupportAction(manager: BattleManager, fromEnemyPointOfView: Boolean) {
manager.getLastUsedPlayerCreatureCard(fromEnemyPointOfView)?.let { player ->
manager.getLastUsedEnemyCreatureCard(fromEnemyPointOfView)?.let { enemy ->
val playerAttack = player.attack
val playerDefense = player.defense
player.attack = enemy.attack
player.defense = enemy.defense
enemy.attack = playerAttack
enemy.defense = playerDefense
}
}
}
}
}
private fun generateDefaultCreatureCard(id: Int, neededSlots: Int, obtainedList: SparseBooleanArray, inDeckList: SparseBooleanArray): Card {
val card = Card()
card.id = id
card.isObtained = obtainedList.get(card.id)
card.isInDeck = inDeckList.get(card.id)
card.neededSlots = neededSlots
card.price = card.neededSlots * 50
allCardsMap.put(card.id, card)
return card
}
private fun generateDefaultSupportCard(id: Int, neededSlots: Int, obtainedList: SparseBooleanArray, inDeckList: SparseBooleanArray): Card {
val card = Card()
card.id = id
card.type = Type.SUPPORT
card.isObtained = obtainedList.get(card.id)
card.isInDeck = inDeckList.get(card.id)
card.neededSlots = neededSlots
card.price = card.neededSlots * 50
allCardsMap.put(card.id, card)
return card
}
private fun checkCreatureCard(card: Card) {
// rules are:
// - points to split are equals to 3*slots +- 30%
// - defense need to be greater than 1.2*attack
// - attack is more important than defense, so big attackers should be penalised
val acceptableSum = card.neededSlots * 3
val margin = Math.round(acceptableSum / 100f * 30f)
if (card.attack > Math.round(card.defense / 1.2) || card.attack + card.defense > acceptableSum + margin || card.attack + card.defense < acceptableSum - margin) {
throw IllegalStateException("Card " + card.name + " does not respect rules")
}
}
}
}
| gpl-3.0 | 4a339cc4dc662bcd067e9505de4772a9 | 42.262411 | 213 | 0.572172 | 4.5085 | false | false | false | false |
Reyurnible/gitsalad-android | app/src/main/kotlin/com/hosshan/android/salad/repository/pref/PreferencesRepository.kt | 1 | 1567 | package com.hosshan.android.salad.repository.pref
import com.f2prateek.rx.preferences.RxSharedPreferences
import com.hosshan.android.salad.manager.GsonManager
import com.hosshan.android.salad.repository.github.entity.Author
import com.hosshan.android.salad.repository.github.entity.Repository
import rx.Observable
import rx.schedulers.Schedulers
/**
* Preferences repository.
*/
class PreferencesRepository(private val pref: RxSharedPreferences) {
object Key {
const val Repo = "repo"
const val Author = "author"
}
// Repository
fun getRepo(): Repository? = pref.getString(Key.Repo, "").get()?.let {
if (it.isEmpty()) {
null
} else {
GsonManager.getInstance().fromJson(it, Repository::class.java)
}
}
fun observeRepo(): Observable<Repository?> = pref.getString(Key.Repo, "").asObservable().observeOn(Schedulers.io()).map {
if (it.isEmpty()) {
null
} else {
GsonManager.getInstance().fromJson(it, Repository::class.java)
}
}
fun setRepo(repository: Repository) {
pref.getString(Key.Repo).set(GsonManager.getInstance().toJson(repository))
}
// Author
fun getAuthor(): Author? = pref.getString(Key.Author, "").get()?.let {
if (it.isEmpty()) {
null
} else {
GsonManager.getInstance().fromJson(it, Author::class.java)
}
}
fun setRepo(author: Author) {
pref.getString(Key.Author).set(GsonManager.getInstance().toJson(author))
}
}
| mit | 6b2c1dc091db8073784ba3c031ac72cf | 28.018519 | 125 | 0.639438 | 4.178667 | false | false | false | false |
petrbalat/jlib | src/test/java/cz/softdeluxe/jlib/io/IOHelpersTest.kt | 1 | 3899 | package cz.softdeluxe.jlib.io
import cz.softdeluxe.jlib.system.isWindows
import org.junit.Test
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.file.Paths
import java.util.zip.ZipInputStream
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* Created by Petr on 29. 4. 2015.
*/
class IOHelpersTest {
@Test
fun createThumbnail() {
val file = File(jpgPath).createThumbnail(156)
assertEquals("drevo-thumb.jpg", file.name)
// file.delete()
}
@Test
fun zipEntrySequence() {
ZipInputStream(FileInputStream(zipPath)).use { zip ->
val list = zip.entrySequence().toList()
assertEquals(3, list.size)
assertTrue(list.any { it.name == "1.txt" })
assertTrue(list.any { it.name == "2soubor.txt" })
assertTrue(list.any { it.name == "3.txt" })
}
}
@Test
fun zipWriteTo() {
val pathTestFile = Paths.get("testZip.txt").toAbsolutePath().toString()
val testWriteFile = File(pathTestFile)
testWriteFile.delete()
val fos = FileOutputStream(testWriteFile)
ZipInputStream(FileInputStream(zipPath)).use { zip ->
zip.entrySequence().firstOrNull { it.name == "2soubor.txt" }?.let {
zip.writeTo(fos)
}
}
assertEquals("ble ble", testWriteFile.readText())
}
@Test
fun contentSequence() {
ZipInputStream(FileInputStream(zipPath)).use { zip ->
zip.contentSequence().forEach {
if (it.first.name == "2soubor.txt") {
assertEquals("ble ble", it.second)
} else if (it.first.name == "1.txt") {
assertEquals("aaa", it.second)
} else if (it.first.name == "3.txt") {
assertEquals("ccccc", it.second)
}
}
}
}
@Test
fun loadAsProperties() {
val properties = File(propertiesPath).loadAsProperties()
assertEquals("baf", properties["mess1"])
assertEquals("bleble", properties["mess.baf2"])
}
@Test
fun probeContentType() {
if (isWindows) return
assertEquals("text/plain", File(txtPath).probeContentType)
assertEquals("application/x-zip-compressed", File(zipPath).probeContentType)
assertEquals("image/jpeg", File(jpgPath).probeContentType)
assertEquals("video/avi", File(aviPath).probeContentType)
assertEquals("application/pdf", File(pdfPath).probeContentType)
assertEquals("application/x-shar", File(shPath).probeContentType)
assertEquals("application/application/vnd.oasis.opendocument.formula", File(odfPath).probeContentType)
assertEquals("application/vnd.ms-powerpoint", File(pptPath).probeContentType)
assertEquals("application/vnd.openxmlformats-officedocument.presentationml.presentation", File(pptxPath).probeContentType)
}
val txtPath = Paths.get("src/test/resources/test.txt").toAbsolutePath().toString()
val zipPath = Paths.get("src/test/resources/test.zip").toAbsolutePath().toString()
val jpgPath = Paths.get("src/test/resources/drevo.jpg").toAbsolutePath().toString()
val aviPath = Paths.get("src/test/resources/flame.avi").toAbsolutePath().toString()
val pdfPath = Paths.get("src/test/resources/test.pdf").toAbsolutePath().toString()
val shPath = Paths.get("src/test/resources/test.sh").toAbsolutePath().toString()
val pptPath = Paths.get("src/test/resources/test.ppt").toAbsolutePath().toString()
val pptxPath = Paths.get("src/test/resources/test.pptx").toAbsolutePath().toString()
val odfPath = Paths.get("src/test/resources/test.odf").toAbsolutePath().toString()
val propertiesPath = Paths.get("src/test/resources/test.properties").toAbsolutePath().toString()
} | apache-2.0 | 4ada386947d5cbc27d2321428f99cc21 | 38 | 130 | 0.647345 | 4.130297 | false | true | false | false |
OurFriendIrony/MediaNotifier | app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/musicbrainz/artist/search/ArtistSearchArtist.kt | 1 | 2431 | package uk.co.ourfriendirony.medianotifier.clients.musicbrainz.artist.search
import com.fasterxml.jackson.annotation.*
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder(
"id",
"type",
"type-id",
"score",
"name",
"sort-name",
"country",
"area",
"begin-area",
"disambiguation",
"isnis",
"life-span",
"aliases",
"tags",
"gender"
)
class ArtistSearchArtist {
@get:JsonProperty("id")
@set:JsonProperty("id")
@JsonProperty("id")
var id: String? = null
@get:JsonProperty("type")
@set:JsonProperty("type")
@JsonProperty("type")
var type: String? = null
@get:JsonProperty("type-id")
@set:JsonProperty("type-id")
@JsonProperty("type-id")
var typeId: String? = null
@get:JsonProperty("score")
@set:JsonProperty("score")
@JsonProperty("score")
var score: Int? = null
@get:JsonProperty("name")
@set:JsonProperty("name")
@JsonProperty("name")
var name: String? = null
@get:JsonProperty("sort-name")
@set:JsonProperty("sort-name")
@JsonProperty("sort-name")
var sortName: String? = null
@get:JsonProperty("country")
@set:JsonProperty("country")
@JsonProperty("country")
var country: String? = null
@get:JsonProperty("area")
@set:JsonProperty("area")
@JsonProperty("area")
var area: ArtistSearchArea? = null
@get:JsonProperty("begin-area")
@set:JsonProperty("begin-area")
@JsonProperty("begin-area")
var beginArea: ArtistSearchBeginArea? = null
@get:JsonProperty("disambiguation")
@set:JsonProperty("disambiguation")
@JsonProperty("disambiguation")
var disambiguation: String? = null
@get:JsonProperty("isnis")
@set:JsonProperty("isnis")
@JsonProperty("isnis")
var isnis: List<String>? = null
@get:JsonProperty("life-span")
@set:JsonProperty("life-span")
@JsonProperty("life-span")
var lifeSpan: ArtistSearchLifeSpan? = null
@get:JsonProperty("aliases")
@set:JsonProperty("aliases")
@JsonProperty("aliases")
var aliases: List<ArtistSearchAlias>? = null
@get:JsonProperty("tags")
@set:JsonProperty("tags")
@JsonProperty("tags")
var tags: List<ArtistSearchTag>? = null
@get:JsonProperty("gender")
@set:JsonProperty("gender")
@JsonProperty("gender")
var gender: String? = null
} | apache-2.0 | cad0393c3b0706d606d04ce82c4f48a4 | 23.565657 | 76 | 0.64747 | 3.828346 | false | false | false | false |
charlag/Promind | app/src/main/java/com/charlag/promind/core/data/models/Location.kt | 1 | 3511 | package com.charlag.promind.core.data.models
/**
* Created by charlag on 25/02/2017.
*/
data class Location(val latitude: Double, val longitude: Double) {
fun distanceTo(another: Location): Double {
// implementation stripped from the Android sources
// Based on http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf
// using the "Inverse Formula" (section 4)
val MAXITERS = 20
// Convert lat/long to radians
val lat1 = latitude * Math.PI / 180.0
val lat2 = another.latitude * Math.PI / 180.0
val lon1 = longitude * Math.PI / 180.0
val lon2 = another.longitude * Math.PI / 180.0
val a = 6378137.0 // WGS84 major axis
val b = 6356752.3142 // WGS84 semi-major axis
val f = (a - b) / a
val aSqMinusBSqOverBSq = (a * a - b * b) / (b * b)
val L = lon2 - lon1
var A = 0.0
val U1 = Math.atan((1.0 - f) * Math.tan(lat1))
val U2 = Math.atan((1.0 - f) * Math.tan(lat2))
val cosU1 = Math.cos(U1)
val cosU2 = Math.cos(U2)
val sinU1 = Math.sin(U1)
val sinU2 = Math.sin(U2)
val cosU1cosU2 = cosU1 * cosU2
val sinU1sinU2 = sinU1 * sinU2
var sigma = 0.0
var deltaSigma = 0.0
var cosSqAlpha: Double
var cos2SM: Double
var cosSigma: Double
var sinSigma: Double
var cosLambda: Double
var sinLambda: Double
var lambda = L // initial guess
for (iter in 0..MAXITERS - 1) {
val lambdaOrig = lambda
cosLambda = Math.cos(lambda)
sinLambda = Math.sin(lambda)
val t1 = cosU2 * sinLambda
val t2 = cosU1 * sinU2 - sinU1 * cosU2 * cosLambda
val sinSqSigma = t1 * t1 + t2 * t2 // (14)
sinSigma = Math.sqrt(sinSqSigma)
cosSigma = sinU1sinU2 + cosU1cosU2 * cosLambda // (15)
sigma = Math.atan2(sinSigma, cosSigma) // (16)
val sinAlpha = if (sinSigma == 0.0)
0.0
else
cosU1cosU2 * sinLambda / sinSigma // (17)
cosSqAlpha = 1.0 - sinAlpha * sinAlpha
cos2SM = if (cosSqAlpha == 0.0)
0.0
else
cosSigma - 2.0 * sinU1sinU2 / cosSqAlpha // (18)
val uSquared = cosSqAlpha * aSqMinusBSqOverBSq // defn
A = 1 + uSquared / 16384.0 * // (3)
(4096.0 + uSquared * (-768 + uSquared * (320.0 - 175.0 * uSquared)))
val B = uSquared / 1024.0 * // (4)
(256.0 + uSquared * (-128.0 + uSquared * (74.0 - 47.0 * uSquared)))
val C = f / 16.0 *
cosSqAlpha *
(4.0 + f * (4.0 - 3.0 * cosSqAlpha)) // (10)
val cos2SMSq = cos2SM * cos2SM
deltaSigma = B * sinSigma * // (6)
(cos2SM + B / 4.0 * (cosSigma * (-1.0 + 2.0 * cos2SMSq) - B / 6.0 * cos2SM *
(-3.0 + 4.0 * sinSigma * sinSigma) *
(-3.0 + 4.0 * cos2SMSq)))
lambda = L + (1.0 - C) * f * sinAlpha *
(sigma + C * sinSigma *
(cos2SM + C * cosSigma *
(-1.0 + 2.0 * cos2SM * cos2SM))) // (11)
val delta = (lambda - lambdaOrig) / lambda
if (Math.abs(delta) < 1.0e-12) {
break
}
}
return (b * A * (sigma - deltaSigma))
}
} | mit | 0a7b6252e87e248ccb35050d46a899b6 | 35.583333 | 96 | 0.482484 | 3.256957 | false | false | false | false |
toastkidjp/Yobidashi_kt | lib/src/main/java/jp/toastkid/lib/preference/PreferenceApplier.kt | 1 | 17216 | package jp.toastkid.lib.preference
import android.content.Context
import android.content.SharedPreferences
import android.content.res.Configuration
import android.graphics.Color
import androidx.annotation.ColorInt
import androidx.core.content.ContextCompat
import jp.toastkid.lib.R
import jp.toastkid.lib.Urls
import java.io.File
import java.util.Locale
import kotlin.math.max
/**
* Preferences wrapper.
* @author toastkidjp
*/
class PreferenceApplier(private val context: Context) {
@Suppress("unused")
@Deprecated("These keys are deprecated.")
private enum class DefunctKey {
USE_DAILY_ALARM, USE_INTERNAL_BROWSER, MENU_POS, USE_INVERSION, ENABLE_APP_SEARCH,
LAST_AD_DATE, FULL_SCREEN
}
private enum class Key {
BG_COLOR, FONT_COLOR,
ENABLE_SUGGESTION, ENABLE_SEARCH_HISTORY, ENABLE_VIEW_HISTORY, ENABLE_URL_MODULE,
ENABLE_TREND_MODULE, ENABLE_FAVORITE_SEARCH, DISABLE_SEARCH_CATEGORIES,
BG_IMAGE, SHOW_DISPLAY_EFFECT,
USE_NOTIFICATION_WIDGET, USE_DAILY_NOTIFICATION, RETAIN_TABS, USE_JS,
LOAD_IMAGE, SAVE_FORM, USER_AGENT, HOME_URL, USE_COLOR_FILTER, FILTER_COLOR,
DEFAULT_SEARCH_ENGINE, ENABLE_SEARCH_QUERY_EXTRACT, ENABLE_SEARCH_WITH_CLIP, START_UP, SAVE_VIEW_HISTORY,
SCREEN_MODE, WIFI_ONLY_MODE, AD_REMOVE, WEB_VIEW_POOL_SIZE,
EDITOR_BACKGROUND_COLOR, EDITOR_FONT_COLOR, EDITOR_CURSOR_COLOR, EDITOR_HIGHLIGHT_COLOR,
EDITOR_FONT_SIZE, CAMERA_FAB_BUTTON_POSITION_X, CAMERA_FAB_BUTTON_POSITION_Y,
MENU_FAB_BUTTON_POSITION_X, MENU_FAB_BUTTON_POSITION_Y,
WEB_VIEW_BACKGROUND_ALPHA, RSS_READER_TARGETS, IMAGE_VIEWER_EXCLUDED_PATHS,
IMAGE_VIEWER_SORT_TYPE, BROWSER_DARK_MODE, USE_TITLE_FILTER,
ARTICLE_LIST_SORT_TYPE, LAST_CLIPPED_WORD,
NUMBER_PLACE_MASKING_COUNT, NUMBER_PLACE_LAST_GAME_PATH
}
private val preferences: SharedPreferences =
context.getSharedPreferences(javaClass.canonicalName, Context.MODE_PRIVATE)
var color: Int
get() = preferences.getInt(Key.BG_COLOR.name, ContextCompat.getColor(context, R.color.colorPrimaryDark))
set(color) = preferences.edit().putInt(Key.BG_COLOR.name, color).apply()
var fontColor: Int
get() = preferences.getInt(Key.FONT_COLOR.name, ContextCompat.getColor(context, R.color.default_text_color))
set(color) = preferences.edit().putInt(Key.FONT_COLOR.name, color).apply()
fun colorPair(): ColorPair = ColorPair(color, fontColor)
val isEnableSuggestion: Boolean
get() = preferences.getBoolean(Key.ENABLE_SUGGESTION.name, true)
val isDisableSuggestion: Boolean
get() = !isEnableSuggestion
fun switchEnableSuggestion() {
preferences.edit().putBoolean(Key.ENABLE_SUGGESTION.name, !isEnableSuggestion).apply()
}
val isEnableSearchHistory: Boolean
get() = preferences.getBoolean(Key.ENABLE_SEARCH_HISTORY.name, true)
fun switchEnableSearchHistory() {
preferences.edit().putBoolean(Key.ENABLE_SEARCH_HISTORY.name, !isEnableSearchHistory)
.apply()
}
val isEnableFavoriteSearch: Boolean
get() = preferences.getBoolean(Key.ENABLE_FAVORITE_SEARCH.name, true)
fun switchEnableFavoriteSearch() {
preferences.edit().putBoolean(Key.ENABLE_FAVORITE_SEARCH.name, !isEnableFavoriteSearch)
.apply()
}
val isEnableViewHistory: Boolean
get() = preferences.getBoolean(Key.ENABLE_VIEW_HISTORY.name, true)
fun switchEnableViewHistory() {
preferences.edit().putBoolean(Key.ENABLE_VIEW_HISTORY.name, !isEnableViewHistory)
.apply()
}
fun isEnableUrlModule(): Boolean {
return preferences.getBoolean(Key.ENABLE_URL_MODULE.name, true)
}
fun switchEnableUrlModule() {
preferences.edit().putBoolean(Key.ENABLE_URL_MODULE.name, !isEnableUrlModule())
.apply()
}
fun isEnableTrendModule(): Boolean {
return preferences.getBoolean(Key.ENABLE_TREND_MODULE.name, true)
}
fun switchEnableTrendModule() {
preferences.edit().putBoolean(Key.ENABLE_TREND_MODULE.name, !isEnableTrendModule())
.apply()
}
fun addDisableSearchCategory(name: String) {
val set = readDisableSearchCategory()
set?.add(name)
preferences.edit().putStringSet(Key.DISABLE_SEARCH_CATEGORIES.name, set).apply()
}
fun removeDisableSearchCategory(name: String) {
val set = readDisableSearchCategory()
set?.remove(name)
preferences.edit().putStringSet(Key.DISABLE_SEARCH_CATEGORIES.name, set).apply()
}
fun readDisableSearchCategory(): MutableSet<String>? {
return preferences.getStringSet(Key.DISABLE_SEARCH_CATEGORIES.name, mutableSetOf())
}
fun switchShowDisplayEffect() {
preferences.edit().putBoolean(Key.SHOW_DISPLAY_EFFECT.name, showDisplayEffect().not()).apply()
}
fun showDisplayEffect(): Boolean {
return preferences.getBoolean(Key.SHOW_DISPLAY_EFFECT.name, false)
}
var backgroundImagePath: String
get() = preferences.getString(Key.BG_IMAGE.name, "") ?: ""
set(path) = preferences.edit().putString(Key.BG_IMAGE.name, path).apply()
fun removeBackgroundImagePath() {
preferences.edit().remove(Key.BG_IMAGE.name).apply()
}
fun isFirstLaunch(): Boolean {
val firstLaunch = File(context.filesDir, "firstLaunch")
if (firstLaunch.exists()) {
return false
}
firstLaunch.mkdirs()
return true
}
fun setUseNotificationWidget(newState: Boolean) {
preferences.edit().putBoolean(Key.USE_NOTIFICATION_WIDGET.name, newState).apply()
}
fun useNotificationWidget(): Boolean =
preferences.getBoolean(Key.USE_NOTIFICATION_WIDGET.name, false)
fun setUseDailyNotification(newState: Boolean) {
preferences.edit().putBoolean(Key.USE_DAILY_NOTIFICATION.name, newState).apply()
}
fun useDailyNotification(): Boolean =
preferences.getBoolean(Key.USE_DAILY_NOTIFICATION.name, false)
fun setRetainTabs(newState: Boolean) {
preferences.edit().putBoolean(Key.RETAIN_TABS.name, newState).apply()
}
fun doesRetainTabs(): Boolean = preferences.getBoolean(Key.RETAIN_TABS.name, true)
fun setUseJavaScript(newState: Boolean) {
preferences.edit().putBoolean(Key.USE_JS.name, newState).apply()
}
fun useJavaScript(): Boolean = preferences.getBoolean(Key.USE_JS.name, true)
fun setLoadImage(newState: Boolean) {
preferences.edit().putBoolean(Key.LOAD_IMAGE.name, newState).apply()
}
fun doesLoadImage(): Boolean = preferences.getBoolean(Key.LOAD_IMAGE.name, true)
fun setSaveForm(newState: Boolean) {
preferences.edit().putBoolean(Key.SAVE_FORM.name, newState).apply()
}
fun doesSaveForm(): Boolean = preferences.getBoolean(Key.SAVE_FORM.name, false)
fun setUserAgent(path: String) {
preferences.edit().putString(Key.USER_AGENT.name, path).apply()
}
fun userAgent(): String = preferences.getString(Key.USER_AGENT.name, "DEFAULT") ?: ""
var homeUrl: String
get() = preferences.getString(Key.HOME_URL.name,
if (Locale.getDefault().language == Locale.ENGLISH.language) {
"https://www.yahoo.com"
} else {
"https://m.yahoo.co.jp"
}
) ?: ""
set(path) {
if (Urls.isInvalidUrl(path)) {
return
}
preferences.edit().putString(Key.HOME_URL.name, path).apply()
}
fun setUseColorFilter(newState: Boolean) {
preferences.edit().putBoolean(Key.USE_COLOR_FILTER.name, newState).apply()
}
fun useColorFilter(): Boolean = preferences.getBoolean(Key.USE_COLOR_FILTER.name, false)
fun setFilterColor(@ColorInt newState: Int) {
preferences.edit().putInt(Key.FILTER_COLOR.name, newState).apply()
}
@ColorInt fun filterColor(substitute: Int): Int =
preferences.getInt(
Key.FILTER_COLOR.name,
substitute
)
fun setDefaultSearchEngine(category: String) {
preferences.edit().putString(Key.DEFAULT_SEARCH_ENGINE.name, category).apply()
}
fun getDefaultSearchEngine(): String? {
return preferences.getString(
Key.DEFAULT_SEARCH_ENGINE.name,
""
)
}
var enableSearchQueryExtract: Boolean
get () = preferences.getBoolean(Key.ENABLE_SEARCH_WITH_CLIP.name, true)
set (newState) {
preferences.edit().putBoolean(Key.ENABLE_SEARCH_WITH_CLIP.name, newState).apply()
}
var enableSearchWithClip: Boolean
get () = preferences.getBoolean(Key.ENABLE_SEARCH_QUERY_EXTRACT.name, true)
set (newState) {
preferences.edit().putBoolean(Key.ENABLE_SEARCH_QUERY_EXTRACT.name, newState).apply()
}
var startUp: String?
get () = preferences.getString(Key.START_UP.name, "")
set (newValue) = preferences.edit().putString(Key.START_UP.name, newValue).apply()
var saveViewHistory: Boolean
get () = preferences.getBoolean(Key.SAVE_VIEW_HISTORY.name, true)
set (newState) = preferences.edit().putBoolean(Key.SAVE_VIEW_HISTORY.name, newState).apply()
fun setBrowserScreenMode(newState: String) {
preferences.edit().putString(Key.SCREEN_MODE.name, newState).apply()
}
fun browserScreenMode(): String? = preferences.getString(Key.SCREEN_MODE.name, "")
var wifiOnly: Boolean
get () = preferences.getBoolean(Key.WIFI_ONLY_MODE.name, true)
set (newValue) = preferences.edit().putBoolean(Key.WIFI_ONLY_MODE.name, newValue).apply()
var adRemove: Boolean
get () = preferences.getBoolean(Key.AD_REMOVE.name, true)
set (newValue) = preferences.edit().putBoolean(Key.AD_REMOVE.name, newValue).apply()
var poolSize: Int
get () = preferences.getInt(Key.WEB_VIEW_POOL_SIZE.name, 6)
set (newValue) = preferences.edit().putInt(Key.WEB_VIEW_POOL_SIZE.name, newValue).apply()
fun setEditorBackgroundColor(@ColorInt newValue: Int) {
preferences.edit().putInt(Key.EDITOR_BACKGROUND_COLOR.name, newValue).apply()
}
fun editorBackgroundColor(): Int {
return preferences.getInt(Key.EDITOR_BACKGROUND_COLOR.name, 0xAAFFFFFF.toInt())
}
fun setEditorFontColor(@ColorInt newValue: Int) {
preferences.edit().putInt(Key.EDITOR_FONT_COLOR.name, newValue).apply()
}
fun editorFontColor(): Int {
return preferences.getInt(Key.EDITOR_FONT_COLOR.name, Color.BLACK)
}
fun setEditorCursorColor(@ColorInt newValue: Int) {
preferences.edit().putInt(Key.EDITOR_CURSOR_COLOR.name, newValue).apply()
}
@ColorInt
fun editorCursorColor(@ColorInt substitute: Int): Int {
return preferences.getInt(Key.EDITOR_CURSOR_COLOR.name, substitute)
}
fun setEditorHighlightColor(@ColorInt newValue: Int) {
preferences.edit().putInt(Key.EDITOR_HIGHLIGHT_COLOR.name, newValue).apply()
}
@ColorInt
fun editorHighlightColor(@ColorInt substitute: Int): Int {
return preferences.getInt(Key.EDITOR_HIGHLIGHT_COLOR.name, substitute)
}
fun setEditorFontSize(newSize: Int) {
preferences.edit().putInt(Key.EDITOR_FONT_SIZE.name, newSize).apply()
}
fun editorFontSize(): Int {
return preferences.getInt(Key.EDITOR_FONT_SIZE.name, 16)
}
fun setNewCameraFabPosition(x: Float, y: Float) {
preferences.edit()
.putFloat(Key.CAMERA_FAB_BUTTON_POSITION_X.name, x)
.putFloat(Key.CAMERA_FAB_BUTTON_POSITION_Y.name, y)
.apply()
}
fun clearCameraFabPosition() {
preferences.edit()
.remove(Key.CAMERA_FAB_BUTTON_POSITION_X.name)
.remove(Key.CAMERA_FAB_BUTTON_POSITION_Y.name)
.apply()
}
fun cameraFabPosition(): Pair<Float, Float>? {
if (!preferences.contains(Key.CAMERA_FAB_BUTTON_POSITION_X.name)
|| !preferences.contains(Key.CAMERA_FAB_BUTTON_POSITION_Y.name)) {
return null
}
return preferences.getFloat(Key.CAMERA_FAB_BUTTON_POSITION_X.name, -1f) to
preferences.getFloat(Key.CAMERA_FAB_BUTTON_POSITION_Y.name, -1f)
}
fun setNewMenuFabPosition(x: Float, y: Float) {
preferences.edit()
.putFloat(Key.MENU_FAB_BUTTON_POSITION_X.name, max(0f, x))
.putFloat(Key.MENU_FAB_BUTTON_POSITION_Y.name, max(0f, y))
.apply()
}
fun clearMenuFabPosition() {
preferences.edit()
.remove(Key.MENU_FAB_BUTTON_POSITION_X.name)
.remove(Key.MENU_FAB_BUTTON_POSITION_Y.name)
.apply()
}
fun menuFabPosition(): Pair<Float, Float>? {
if (!preferences.contains(Key.MENU_FAB_BUTTON_POSITION_X.name)
|| !preferences.contains(Key.MENU_FAB_BUTTON_POSITION_Y.name)) {
return null
}
return preferences.getFloat(Key.MENU_FAB_BUTTON_POSITION_X.name, -1f) to
preferences.getFloat(Key.MENU_FAB_BUTTON_POSITION_Y.name, -1f)
}
fun setWebViewBackgroundAlpha(alpha: Float) {
preferences.edit().putFloat(Key.WEB_VIEW_BACKGROUND_ALPHA.name, alpha).apply()
}
fun getWebViewBackgroundAlpha(): Float {
return preferences.getFloat(Key.WEB_VIEW_BACKGROUND_ALPHA.name, 1f)
}
fun readRssReaderTargets(): MutableSet<String> {
return preferences.getStringSet(Key.RSS_READER_TARGETS.name, mutableSetOf())
?: mutableSetOf()
}
fun saveNewRssReaderTargets(url: String) {
val targets = readRssReaderTargets()
targets.add(url)
preferences.edit().putStringSet(Key.RSS_READER_TARGETS.name, targets).apply()
}
fun removeFromRssReaderTargets(url: String) {
val targets = readRssReaderTargets()
targets.remove(url)
preferences.edit().putStringSet(Key.RSS_READER_TARGETS.name, targets).apply()
}
fun containsRssTarget(url: String) = readRssReaderTargets().contains(url)
fun clear() {
preferences.edit().clear().apply()
}
fun addExcludeItem(path: String) {
preferences.edit().putStringSet(
Key.IMAGE_VIEWER_EXCLUDED_PATHS.name,
mutableSetOf(path).also { it.addAll(excludedItems()) }
)
.apply()
}
fun excludedItems(): Set<String> =
preferences.getStringSet(Key.IMAGE_VIEWER_EXCLUDED_PATHS.name, emptySet()) ?: emptySet()
fun removeFromExcluding(path: String) {
mutableSetOf<String>().also {
it.addAll(excludedItems())
it.remove(path)
preferences
.edit()
.putStringSet(Key.IMAGE_VIEWER_EXCLUDED_PATHS.name, it)
.apply()
}
}
fun imageViewerSort(): String? {
return preferences.getString(Key.IMAGE_VIEWER_SORT_TYPE.name, null)
}
fun setImageViewerSort(sort: String) {
preferences.edit().putString(Key.IMAGE_VIEWER_SORT_TYPE.name, sort).apply()
}
fun useDarkMode(): Boolean {
return preferences.getBoolean(
Key.BROWSER_DARK_MODE.name,
(context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
)
}
fun setUseDarkMode(newState: Boolean) {
preferences.edit().putBoolean(Key.BROWSER_DARK_MODE.name, newState).apply()
}
fun switchUseTitleFilter(checked: Boolean) {
preferences.edit().putBoolean(Key.USE_TITLE_FILTER.name, checked).apply()
}
fun useTitleFilter(): Boolean {
return preferences.getBoolean(Key.USE_TITLE_FILTER.name, false)
}
fun setArticleSort(name: String) {
preferences.edit().putString(Key.ARTICLE_LIST_SORT_TYPE.name, name).apply()
}
fun articleSort(): String {
return preferences.getString(Key.ARTICLE_LIST_SORT_TYPE.name, "") ?: ""
}
fun setLastClippedWord(word: String?) {
if (word.isNullOrBlank()) {
return
}
preferences.edit().putString(Key.LAST_CLIPPED_WORD.name, word).apply()
}
fun lastClippedWord(): String {
return preferences.getString(Key.LAST_CLIPPED_WORD.name, "") ?: ""
}
fun setMaskingCount(count: Int) {
preferences.edit().putInt(Key.NUMBER_PLACE_MASKING_COUNT.name, count).apply()
}
fun getMaskingCount(): Int {
return preferences.getInt(Key.NUMBER_PLACE_MASKING_COUNT.name, 20)
}
fun setLastNumberPlaceGamePath(path: String) {
preferences.edit().putString(Key.NUMBER_PLACE_LAST_GAME_PATH.name, path).apply()
}
fun lastNumberPlaceGamePath(): String? {
return preferences.getString(Key.NUMBER_PLACE_LAST_GAME_PATH.name, "")
}
fun clearLastNumberPlaceGamePath() {
preferences.edit().remove(Key.NUMBER_PLACE_LAST_GAME_PATH.name).apply()
}
}
| epl-1.0 | 0c676e843ca9636bb1eb4b563d856deb | 34.423868 | 128 | 0.653171 | 4.090283 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsTraitItem.kt | 1 | 5128 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.Condition
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.stubs.IStubElementType
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.Query
import org.rust.cargo.project.workspace.PackageOrigin
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.psi.*
import org.rust.lang.core.resolve.STD_DERIVABLE_TRAITS
import org.rust.lang.core.stubs.RsTraitItemStub
import org.rust.lang.core.types.BoundElement
import org.rust.lang.core.types.RsPsiTypeImplUtil
import org.rust.lang.core.types.ty.Ty
import org.rust.lang.core.types.ty.TyEnum
import org.rust.lang.utils.filterIsInstanceQuery
import org.rust.lang.utils.filterQuery
import org.rust.lang.utils.mapQuery
import javax.swing.Icon
val RsTraitItem.langAttribute: String? get() = queryAttributes.langAttribute
val RsTraitItem.isStdDerivable: Boolean get() {
val derivableTrait = STD_DERIVABLE_TRAITS[name] ?: return false
return containingCargoPackage?.origin == PackageOrigin.STDLIB &&
containingMod.modName == derivableTrait.modName
}
val BoundElement<RsTraitItem>.flattenHierarchy: Collection<BoundElement<RsTraitItem>> get() {
val result = mutableSetOf<BoundElement<RsTraitItem>>()
val visited = mutableSetOf<RsTraitItem>()
fun dfs(boundTrait: BoundElement<RsTraitItem>) {
if (boundTrait.element in visited) return
visited += boundTrait.element
result += boundTrait
boundTrait.element.superTraits.forEach(::dfs)
}
dfs(this)
return result
}
val BoundElement<RsTraitItem>.associatedTypesTransitively: Collection<RsTypeAlias>
get() = flattenHierarchy.flatMap { it.element.members?.typeAliasList.orEmpty() }
fun RsTraitItem.searchForImplementations(): Query<RsImplItem> {
return ReferencesSearch.search(this, this.useScope)
.mapQuery { it.element.parent?.parent }
.filterIsInstanceQuery<RsImplItem>()
.filterQuery(Condition { it.typeReference != null })
}
private val RsTraitItem.superTraits: Sequence<BoundElement<RsTraitItem>> get() {
val bounds = typeParamBounds?.polyboundList.orEmpty().asSequence()
return bounds.mapNotNull { it.bound.traitRef?.resolveToBoundTrait }
}
abstract class RsTraitItemImplMixin : RsStubbedNamedElementImpl<RsTraitItemStub>, RsTraitItem {
constructor(node: ASTNode) : super(node)
constructor(stub: RsTraitItemStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override val innerAttrList: List<RsInnerAttr>
get() = PsiTreeUtil.getStubChildrenOfTypeAsList(this, RsInnerAttr::class.java)
override val outerAttrList: List<RsOuterAttr>
get() = PsiTreeUtil.getStubChildrenOfTypeAsList(this, RsOuterAttr::class.java)
override fun getIcon(flags: Int): Icon =
iconWithVisibility(flags, RsIcons.TRAIT)
override val isPublic: Boolean get() = RsPsiImplUtil.isPublic(this, stub)
override val crateRelativePath: String? get() = RsPsiImplUtil.crateRelativePath(this)
override val implementedTrait: BoundElement<RsTraitItem>? get() = BoundElement(this)
override val associatedTypesTransitively: Collection<RsTypeAlias>
get() = BoundElement(this).associatedTypesTransitively
override val isUnsafe: Boolean get() {
val stub = stub
return stub?.isUnsafe ?: (unsafe != null)
}
override val declaredType: Ty get() = RsPsiTypeImplUtil.declaredType(this)
}
class TraitImplementationInfo private constructor(
traitMembers: RsMembers,
implMembers: RsMembers,
// Macros can add methods
hasMacros: Boolean
) {
val declared = traitMembers.abstractable()
private val implemented = implMembers.abstractable()
private val declaredByName = declared.associateBy { it.name!! }
private val implementedByName = implemented.associateBy { it.name!! }
val missingImplementations: List<RsAbstractable> = if (!hasMacros)
declared.filter { it.isAbstract }.filter { it.name !in implementedByName }
else emptyList()
val nonExistentInTrait: List<RsAbstractable> = implemented.filter { it.name !in declaredByName }
val implementationToDeclaration: List<Pair<RsAbstractable, RsAbstractable>> =
implemented.mapNotNull { imp ->
val dec = declaredByName[imp.name]
if (dec != null) imp to dec else null
}
private fun RsMembers.abstractable(): List<RsAbstractable> =
PsiTreeUtil.getStubChildrenOfTypeAsList(this, RsAbstractable::class.java)
.filter { it.name != null }
companion object {
fun create(trait: RsTraitItem, impl: RsImplItem): TraitImplementationInfo? {
val traitMembers = trait.members ?: return null
val implMembers = impl.members ?: return null
val hasMacros = implMembers.macroCallList.orEmpty().isNotEmpty()
return TraitImplementationInfo(traitMembers, implMembers, hasMacros)
}
}
}
| mit | 04b5308d50fdac4fde1964d43c1fd6ba | 36.985185 | 100 | 0.73869 | 4.360544 | false | false | false | false |
ItsPriyesh/chroma | chroma/src/main/kotlin/me/priyesh/chroma/ChromaDialog.kt | 1 | 4093 | /*
* Copyright 2016 Priyesh Patel
*
* 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.priyesh.chroma
import android.app.AlertDialog
import android.app.Dialog
import android.content.res.Configuration.ORIENTATION_LANDSCAPE
import android.os.Bundle
import android.support.annotation.ColorInt
import android.support.v4.app.DialogFragment
import android.view.WindowManager
import me.priyesh.chroma.internal.ChromaView
import kotlin.properties.Delegates
class ChromaDialog constructor() : DialogFragment() {
companion object {
private val ArgInitialColor = "arg_initial_color"
private val ArgColorModeName = "arg_color_mode_name"
@JvmStatic
private fun newInstance(@ColorInt initialColor: Int, colorMode: ColorMode): ChromaDialog {
val fragment = ChromaDialog()
fragment.arguments = makeArgs(initialColor, colorMode)
return fragment
}
@JvmStatic
private fun makeArgs(@ColorInt initialColor: Int, colorMode: ColorMode): Bundle {
val args = Bundle()
args.putInt(ArgInitialColor, initialColor)
args.putString(ArgColorModeName, colorMode.name)
return args
}
}
class Builder {
@ColorInt private var initialColor: Int = ChromaView.DefaultColor
private var colorMode: ColorMode = ChromaView.DefaultModel
private var listener: ColorSelectListener? = null
fun initialColor(@ColorInt initialColor: Int): Builder {
this.initialColor = initialColor
return this
}
fun colorMode(colorMode: ColorMode): Builder {
this.colorMode = colorMode
return this
}
fun onColorSelected(listener: ColorSelectListener): Builder {
this.listener = listener
return this
}
fun create(): ChromaDialog {
val fragment = newInstance(initialColor, colorMode)
fragment.listener = listener
return fragment
}
}
private var listener: ColorSelectListener? = null
private var chromaView: ChromaView by Delegates.notNull<ChromaView>()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
chromaView = if (savedInstanceState == null) {
ChromaView(
arguments.getInt(ArgInitialColor),
ColorMode.fromName(arguments.getString(ArgColorModeName)),
context)
} else {
ChromaView(
savedInstanceState.getInt(ArgInitialColor, ChromaView.DefaultColor),
ColorMode.fromName(savedInstanceState.getString(ArgColorModeName)),
context
)
}
chromaView.enableButtonBar(object : ChromaView.ButtonBarListener {
override fun onNegativeButtonClick() = dismiss()
override fun onPositiveButtonClick(color: Int) {
listener?.onColorSelected(color)
dismiss()
}
})
return AlertDialog.Builder(context).setView(chromaView).create().apply {
setOnShowListener {
val width: Int; val height: Int
if (orientation(context) == ORIENTATION_LANDSCAPE) {
height = resources.getDimensionPixelSize(R.dimen.chroma_dialog_height)
width = 80 percentOf screenDimensions(context).widthPixels
} else {
height = WindowManager.LayoutParams.WRAP_CONTENT
width = resources.getDimensionPixelSize(R.dimen.chroma_dialog_width)
}
window.setLayout(width, height)
}
}
}
override fun onSaveInstanceState(outState: Bundle?) {
outState?.putAll(makeArgs(chromaView.currentColor, chromaView.colorMode))
super.onSaveInstanceState(outState)
}
override fun onDestroyView() {
super.onDestroyView()
listener = null
}
}
| apache-2.0 | 5d54202d58f74c7a94978cf7a75fe3a7 | 31.228346 | 94 | 0.711703 | 4.453754 | false | false | false | false |
http4k/http4k | http4k-client/okhttp/src/main/kotlin/org/http4k/client/OkHttpWebsocketClient.kt | 1 | 4274 | package org.http4k.client
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import okio.ByteString.Companion.toByteString
import org.http4k.client.PreCannedOkHttpClients.defaultOkHttpClient
import org.http4k.core.Body
import org.http4k.core.Headers
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.StreamBody
import org.http4k.core.Uri
import org.http4k.websocket.PushPullAdaptingWebSocket
import org.http4k.websocket.Websocket
import org.http4k.websocket.WsClient
import org.http4k.websocket.WsConsumer
import org.http4k.websocket.WsMessage
import org.http4k.websocket.WsStatus
import java.time.Duration
import java.time.temporal.ChronoUnit
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutionException
import java.util.concurrent.LinkedBlockingQueue
object OkHttpWebsocketClient {
fun blocking(
uri: Uri,
headers: Headers = emptyList(),
timeout: Duration = Duration.of(5, ChronoUnit.SECONDS),
client: OkHttpClient = defaultOkHttpClient()
): WsClient = OkHttpBlockingWebsocket(uri, headers, timeout, client).awaitConnected()
fun nonBlocking(
uri: Uri,
headers: Headers = emptyList(),
timeout: Duration = Duration.ZERO,
client: OkHttpClient = defaultOkHttpClient(),
onError: (Throwable) -> Unit = {},
onConnect: WsConsumer = {}
): Websocket = OkHttpNonBlockingWebsocket(uri, headers, timeout, client, onError, onConnect)
}
private class OkHttpBlockingWebsocket(
uri: Uri,
headers: Headers,
timeout: Duration,
client: OkHttpClient
) : WsClient {
private val connected = CompletableFuture<WsClient>()
private val queue = LinkedBlockingQueue<() -> WsMessage?>()
private val websocket = OkHttpNonBlockingWebsocket(uri, headers, timeout, client, connected::completeExceptionally) { ws ->
ws.onMessage { queue += { it } }
ws.onError { queue += { throw it } }
ws.onClose { queue += { null } }
connected.complete(this)
}
fun awaitConnected(): WsClient = try {
connected.get()
} catch (e: ExecutionException) {
throw (e.cause ?: e)
}
override fun received(): Sequence<WsMessage> = generateSequence { queue.take()() }
override fun close(status: WsStatus) = websocket.close(status)
override fun send(message: WsMessage) = websocket.send(message)
}
private class OkHttpNonBlockingWebsocket(
uri: Uri,
headers: Headers,
timeout: Duration,
client: OkHttpClient,
onError: (Throwable) -> Unit,
private val onConnect: WsConsumer
) : PushPullAdaptingWebSocket(Request(Method.GET, uri).headers(headers)) {
init {
onError(onError)
}
private val ws = client.newBuilder().connectTimeout(timeout).build()
.newWebSocket(upgradeRequest.asOkHttp(), Listener())
override fun send(message: WsMessage) {
val messageSent = when (message.body) {
is StreamBody -> ws.send(message.body.payload.toByteString())
else -> ws.send(message.body.toString())
}
check(messageSent) {
"Connection to ${upgradeRequest.uri} is closed."
}
}
override fun close(status: WsStatus) {
ws.close(status.code, status.description)
}
inner class Listener : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
onConnect(this@OkHttpNonBlockingWebsocket)
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
triggerClose(WsStatus(code, reason))
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
webSocket.close(code, reason)
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
triggerError(t)
}
override fun onMessage(webSocket: WebSocket, text: String) {
triggerMessage(WsMessage(text))
}
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
triggerMessage(WsMessage(Body(bytes.toByteArray().inputStream())))
}
}
}
| apache-2.0 | e86f79fa433bf4bdaf44247aad590283 | 31.378788 | 127 | 0.687412 | 4.339086 | false | false | false | false |
stoman/CompetitiveProgramming | problems/2021adventofcode12a/submissions/accepted/Stefan.kt | 2 | 1143 | import java.util.*
private data class Node(val name: String) {
fun canBeVisitedMultipleTimes(): Boolean = name.first().isUpperCase()
}
private data class PathStatus(val current: Node, val visited: Set<Node>)
fun main() {
val s = Scanner(System.`in`).useDelimiter("""[\n-]""")
val connections = mutableMapOf<Node, Set<Node>>()
while (s.hasNext()) {
val a = Node(s.next())
val b = Node(s.next())
connections[a] = connections.getOrDefault(a, setOf()) + b
connections[b] = connections.getOrDefault(b, setOf()) + a
}
val queue = ArrayDeque<PathStatus>()
var pathsToEnd = 0
val startStatus = PathStatus(Node("start"), setOf(Node("start")))
queue.add(startStatus)
while (queue.isNotEmpty()) {
val status = queue.removeFirst()
for (next in connections.getOrDefault(status.current, setOf())) {
if (next.canBeVisitedMultipleTimes() || next !in status.visited) {
val nextStatus = PathStatus(next, status.visited + next)
if (next.name != "end") {
queue.addLast(nextStatus)
}
else {
pathsToEnd++
}
}
}
}
println(pathsToEnd)
}
| mit | 55138304167e77ab0ee0a2d7fddaf33f | 27.575 | 72 | 0.630796 | 3.784768 | false | false | false | false |
http4k/http4k | http4k-core/src/test/kotlin/org/http4k/lens/BodyTest.kt | 1 | 4990 | package org.http4k.lens
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.throws
import org.http4k.core.Body
import org.http4k.core.ContentType
import org.http4k.core.ContentType.Companion.TEXT_PLAIN
import org.http4k.core.Method.GET
import org.http4k.core.Request
import org.http4k.core.with
import org.http4k.lens.Header.CONTENT_TYPE
import org.junit.jupiter.api.Test
class BodyTest {
private val emptyRequest = Request(GET, "")
@Test
fun `can get string body when lax`() {
val laxContentType = Body.string(TEXT_PLAIN).toLens()
assertThat(laxContentType(emptyRequest.body("some value")), equalTo("some value"))
assertThat(laxContentType(emptyRequest.header("Content-type", TEXT_PLAIN.toHeaderValue()).body("some value")), equalTo("some value"))
}
@Test
fun `can get regex body`() {
val regexBody = Body.regex("bob(.+)alice").toLens()
assertThat(regexBody(emptyRequest.body("bobritaalice")), equalTo("rita"))
assertThat({ regexBody(emptyRequest.body("foobaralice")) }, throws(lensFailureWith<Request>(Invalid(Meta(true, "body", ParamMeta.StringParam, "body")), overallType = Failure.Type.Invalid)))
}
@Test
fun `non empty string`() {
val nonEmpty = Body.nonEmptyString(TEXT_PLAIN).toLens()
assertThat(nonEmpty(emptyRequest.body("123")), equalTo("123"))
assertThat({ nonEmpty(emptyRequest.body("")) }, throws(lensFailureWith<Request>(Invalid(Meta(true, "body", ParamMeta.StringParam, "body")), overallType = Failure.Type.Invalid)))
}
@Test
fun `rejects invalid or missing content type when ContentNegotiation Strict`() {
val strictBody = Body.string(TEXT_PLAIN, contentNegotiation = ContentNegotiation.Strict).toLens()
assertThat({ strictBody(emptyRequest.body("some value")) }, throws(lensFailureWith<Any?>(Unsupported(CONTENT_TYPE.meta), overallType = Failure.Type.Unsupported)))
assertThat({ strictBody(emptyRequest.header("content-type", "text/bob;charset=not-utf-8").body("some value")) }, throws(lensFailureWith<ContentType>(Unsupported(CONTENT_TYPE.meta), overallType = Failure.Type.Unsupported)))
}
@Test
fun `rejects invalid or missing content type when ContentNegotiation StrictNoDirective`() {
val strictNoDirectiveBody = Body.string(TEXT_PLAIN, contentNegotiation = ContentNegotiation.StrictNoDirective).toLens()
assertThat({ strictNoDirectiveBody(emptyRequest.body("some value")) }, throws(lensFailureWith<Any?>(Unsupported(CONTENT_TYPE.meta), overallType = Failure.Type.Unsupported)))
assertThat(strictNoDirectiveBody(emptyRequest.header("content-type", "text/plain; charset= not-utf-8 ").body("some value")), equalTo("some value"))
}
@Test
fun `rejects invalid content type when ContentNegotiation NonStrict`() {
val strictBody = Body.string(TEXT_PLAIN, contentNegotiation = ContentNegotiation.NonStrict).toLens()
assertThat({ strictBody(emptyRequest.header("content-type", "text/bob; charset= not-utf-8 ").body("some value")) }, throws(lensFailureWith<ContentType>(Unsupported(CONTENT_TYPE.meta), overallType = Failure.Type.Unsupported)))
assertThat(strictBody(emptyRequest.body("some value")), equalTo("some value"))
}
@Test
fun `accept any content type when ContentNegotiation None`() {
val noneBody = Body.string(TEXT_PLAIN, contentNegotiation = ContentNegotiation.None).toLens()
noneBody(emptyRequest.body("some value"))
noneBody(emptyRequest.body("some value").header("content-type", "text/bob"))
}
@Test
fun `sets value on request`() {
val body = Body.string(TEXT_PLAIN).toLens()
val withBody = emptyRequest.with(body of "hello")
assertThat(body(withBody), equalTo("hello"))
assertThat(CONTENT_TYPE(withBody), equalTo(TEXT_PLAIN))
}
@Test
fun `synonym methods roundtrip`() {
val body = Body.string(TEXT_PLAIN).toLens()
body.inject("hello", emptyRequest)
val withBody = emptyRequest.with(body of "hello")
assertThat(body.extract(withBody), equalTo("hello"))
}
@Test
fun `can create a custom Body type and get and set on request`() {
val customBody = Body.string(TEXT_PLAIN).map(::MyCustomType, MyCustomType::value).toLens()
val custom = MyCustomType("hello world!")
val reqWithBody = customBody(custom, emptyRequest)
assertThat(reqWithBody.bodyString(), equalTo("hello world!"))
assertThat(customBody(reqWithBody), equalTo(MyCustomType("hello world!")))
}
@Test
fun `can create a one way custom Body type`() {
val customBody = Body.string(TEXT_PLAIN).map(::MyCustomType).toLens()
assertThat(customBody(emptyRequest
.header("Content-type", TEXT_PLAIN.toHeaderValue())
.body("hello world!")), equalTo(MyCustomType("hello world!")))
}
}
| apache-2.0 | 10a061c2a7409f9aad6bbc185d2f2a4c | 47.446602 | 235 | 0.700401 | 4.09688 | false | true | false | false |
swishy/Mitsumame | core/src/main/kotlin/com/st8vrt/mitsumame/library/utilities/Encryption.kt | 1 | 5877 | package com.st8vrt.mitsumame.library.utilities
import com.st8vrt.mitsumame.configuration.mitsumameConfiguration
import org.apache.commons.codec.binary.Base64
import org.slf4j.LoggerFactory
import java.security.InvalidParameterException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
/**
* Created by swishy on 30/10/13.
*/
public class Encryption
{
internal val salt = "Adfas" + 24576 + "6&#N%^BW" + ",.|%^&*"
private val aesBlockSize = 256;
private var log = LoggerFactory.getLogger(Session::class.java)
public fun encryptByteArray(array : ByteArray, key : ByteArray) : String {
var iv = getRandomIv();
return Base64.encodeBase64String(iv) + encryptByteArray(array, key, salt.toByteArray(), iv as ByteArray)
}
public fun encryptString(message : String, key : ByteArray) : String {
var iv = getRandomIv();
return Base64.encodeBase64String(iv) + encryptString(message, key, salt.toByteArray(), iv as ByteArray)
}
public fun encryptByteArray(array:ByteArray, encryptionKey:ByteArray, salt:ByteArray, iv:ByteArray) : String {
try{
var factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
var charEncryptionKey = encryptionKey.toCharArray()
var keyspec = PBEKeySpec(charEncryptionKey, salt, mitsumameConfiguration.keyIterations, aesBlockSize)
var secretKey = factory?.generateSecret(keyspec)
var cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher?.init(Cipher.ENCRYPT_MODE, SecretKeySpec(secretKey?.getEncoded(), "AES")
, IvParameterSpec(iv));
return Base64.encodeBase64String(cipher?.doFinal(array))
} catch(e:Exception) {
log?.error("Unable to encrypt message", e)
throw Exception("Unable to encrypt message")
}
}
public fun encryptString(plainText:String, encryptionKey:ByteArray, salt:ByteArray, iv:ByteArray) : String {
try{
var factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
var charEncryptionKey = encryptionKey.toCharArray()
var keyspec = PBEKeySpec(charEncryptionKey, salt, mitsumameConfiguration.keyIterations, aesBlockSize)
var secretKey = factory?.generateSecret(keyspec)
var cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher?.init(Cipher.ENCRYPT_MODE, SecretKeySpec(secretKey?.getEncoded(), "AES")
, IvParameterSpec(iv));
return Base64.encodeBase64String(cipher?.doFinal(plainText.toByteArray()))
} catch(e:Exception) {
log?.error("Unable to encrypt message", e)
throw Exception("Unable to encrypt message")
}
}
public fun decryptString(encryptedPayload:String) : String {
var iv = getIvFromPayload(encryptedPayload) as ByteArray
var message = getEncryptedMessageFromPayload(encryptedPayload)
var key = Base64.decodeBase64("")
return decryptString(message, key, salt.toByteArray(), iv)
}
public fun decryptString(cipherText:String, key:ByteArray, salt:ByteArray, iv:ByteArray) : String {
try{
var factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
var keyspec = PBEKeySpec(key.toCharArray(), salt,1024, aesBlockSize);
var secretKey = factory?.generateSecret(keyspec);
var cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher?.init(Cipher.DECRYPT_MODE, SecretKeySpec(secretKey?.getEncoded(), "AES"), IvParameterSpec(iv))
var ciphertext = Base64.decodeBase64(cipherText);
return cipher?.doFinal(ciphertext)?.toString("UTF-8") as String
} catch(e:Exception) {
log?.error("Unable to decrypt message")
throw Exception("Unable to decrypt message");
}
}
public fun getRandomIv() : ByteArray? {
try {
var keyGen = KeyGenerator.getInstance("AES")
var sr = SecureRandom.getInstance("SHA1PRNG")
keyGen?.init(128, sr)
var secretKey = keyGen?.generateKey()
return secretKey?.getEncoded()
} catch(e : Exception) {
log?.error("Unable to create random IV", e)
throw Exception("Unable to create random IV")
}
}
/**
* Retrieves the first 16bytes from the given payload
* @param payload Base64 encoded string
* @return the IV as as a ByteArray
*/
public fun getIvFromPayload(payload:String) : ByteArray? {
var iv = payload.substring(0, 24)
return Base64.decodeBase64(iv)
}
/**
* Retrieves the encrypted message from the payload
* (ie. everything after the IV)
* @param payload Base64 encoded string
* @return the encrypted message as a Base64 string
*/
public fun getEncryptedMessageFromPayload(payload:String) : String {
return payload.substring(24, payload.length)
}
public fun generateKey(password : String, salt : String) : ByteArray
{
var array = ByteArray(0)
try
{
var digest = MessageDigest.getInstance("SHA-256")
array = digest?.digest((salt + password).toByteArray()) as ByteArray
}
catch(exception: NoSuchAlgorithmException)
{
log?.error("Unable to generate an encryption key: ${exception}")
InvalidParameterException("Unable to generate an encryption key")
}
return array
}
} | apache-2.0 | e7db12b8146f559ec7d8f3f6e616d2ea | 36.43949 | 114 | 0.657478 | 4.61303 | false | false | false | false |
mehulsbhatt/emv-bertlv | src/main/java/io/github/binaryfoo/tlv/Tag.kt | 1 | 4709 | package io.github.binaryfoo.tlv
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
import java.util.Arrays
import io.github.binaryfoo.TagMetaData
import org.apache.commons.lang.builder.HashCodeBuilder
import kotlin.platform.platformStatic
import io.github.binaryfoo.TagInfo
/**
* The tag in T-L-V. Sometimes called Type but EMV 4.3 Book 3 - B3 Coding of the Value Field of Data Objects uses the term.
*/
public data class Tag(val bytes: ByteArray, val compliant: Boolean = true) {
{
if (compliant) {
validate(bytes)
}
}
private fun validate(b: ByteArray?) {
if (b == null || b.size == 0) {
throw IllegalArgumentException("Tag must be constructed with a non-empty byte array")
}
if (b.size == 1) {
if ((b[0].toInt() and 0x1F) == 0x1F) {
throw IllegalArgumentException("If bit 6 to bit 1 are set tag must not be only one byte long")
}
} else {
if ((b[b.size - 1].toInt() and 0x80) != 0) {
throw IllegalArgumentException("For multibyte tag bit 8 of the final byte must be 0: " + Integer.toHexString(b[b.size - 1].toInt()))
}
if (b.size > 2) {
for (i in 1..b.size - 2) {
if ((b[i].toInt() and 0x80) != 0x80) {
throw IllegalArgumentException("For multibyte tag bit 8 of the internal bytes must be 1: " + Integer.toHexString(b[i].toInt()))
}
}
}
}
}
public val hexString: String
get() = ISOUtil.hexString(bytes)
public val constructed: Boolean
get() = (bytes[0].toInt() and 0x20) == 0x20
public fun isConstructed(): Boolean = constructed
override fun toString(): String {
return ISOUtil.hexString(bytes)
}
public fun toString(tagMetaData: TagMetaData): String {
return toString(tagMetaData.get(this))
}
public fun toString(tagInfo: TagInfo): String {
return "${ISOUtil.hexString(bytes)} (${tagInfo.fullName})"
}
class object {
platformStatic public fun fromHex(hexString: String): Tag {
return Tag(ISOUtil.hex2byte(hexString))
}
platformStatic public fun parse(buffer: ByteBuffer): Tag = parse(buffer, CompliantTagMode)
platformStatic public fun parse(buffer: ByteBuffer, recognitionMode: TagRecognitionMode): Tag {
val out = ByteArrayOutputStream()
var b = buffer.get()
out.write(b.toInt())
if ((b.toInt() and 0x1F) == 0x1F) {
do {
b = buffer.get()
out.write(b.toInt())
} while (recognitionMode.keepReading(b, out))
}
return Tag(out.toByteArray(), recognitionMode == CompliantTagMode)
}
}
}
public trait TagRecognitionMode {
fun keepReading(current: Byte, all: ByteArrayOutputStream): Boolean
}
/**
* Follows EMV 4.3 Book 3, Annex B Rules for BER-TLV Data Objects to the letter.
*/
public object CompliantTagMode: TagRecognitionMode {
override fun keepReading(current: Byte, all: ByteArrayOutputStream): Boolean = (current.toInt() and 0x80) == 0x80
}
/**
* EMV 4.3 Book 3, Annex B Rules for BER-TLV Data Objects unless it's in a list of special cases.
*/
public class QuirkListTagMode(val nonStandard: Set<String>) : TagRecognitionMode {
override fun keepReading(current: Byte, all: ByteArrayOutputStream): Boolean {
return CompliantTagMode.keepReading(current, all) && !nonStandard.contains(all.toByteArray().toHexString())
}
}
/**
* Seems at least one vendor read the following and thought I'll pick 9F80 as the start of my private tag range.
* According to Book 3 anything greater than 7F in byte two means the tag is at least 3 three bytes long, not two.
*
* <blockquote>
* The coding of primitive context-specific class data objects in the range '9F50' to '9F7F' is reserved for the payment systems.
* <footer>
* <cite>EMV 4.3 Book 3, Annex B Rules for BER-TLV Data Objects</cite>
* </footer>
* </blockquote>
*/
public object CommonVendorErrorMode: TagRecognitionMode {
override fun keepReading(current: Byte, all: ByteArrayOutputStream): Boolean {
return CompliantTagMode.keepReading(current, all) && (all.size() != 2 || !isCommonError(all.toByteArray()))
}
public fun isCommonError(tag: ByteArray): Boolean {
return tag.size > 1 && (tag[0] == 0x9F.toByte() && (tag[1].toInt() and 0xF0) == 0x80)
}
}
public fun hasCommonVendorErrorTag(tlv: BerTlv): Boolean = CommonVendorErrorMode.isCommonError(tlv.tag.bytes)
| mit | 77f5707ec571267d712bd92ccee3bce3 | 35.503876 | 151 | 0.632618 | 3.940586 | false | false | false | false |
yuyashuai/SurfaceViewFrameAnimation | frameanimation/src/main/java/com/yuyashuai/frameanimation/FrameAnimationView.kt | 1 | 2059 | package com.yuyashuai.frameanimation
import android.content.Context
import android.util.AttributeSet
import android.view.TextureView
import android.view.View
/**
* the frame animation view to handle the animation life circle
* @see TextureView
* @author yuyashuai 2019-05-16.
*/
class FrameAnimationView private constructor(context: Context, attributeSet: AttributeSet?, defStyle: Int, val animation: FrameAnimation)
: TextureView(context, attributeSet, defStyle), AnimationController by animation {
constructor(context: Context, attributeSet: AttributeSet?, defStyle: Int)
: this(context, attributeSet, defStyle, FrameAnimation(context))
constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
constructor(context: Context) : this(context, null)
private var lastStopIndex = 0
private var lastStopPaths: MutableList<FrameAnimation.PathData>? = null
/**
* whether to resume playback
*/
var restoreEnable = true
init {
animation.bindView(this)
isAvailable
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
saveAndStop()
}
/**
* stop the animation, save the index when the animation stops playing
*/
private fun saveAndStop() {
lastStopPaths = animation.mPaths?.toMutableList()
lastStopIndex = stopAnimation()
}
/**
* resume animation
*/
private fun restoreAndStart() {
if (lastStopPaths != null && restoreEnable) {
playAnimation(lastStopPaths!!, lastStopIndex)
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
restoreAndStart()
}
override fun onVisibilityChanged(changedView: View, visibility: Int) {
super.onVisibilityChanged(changedView, visibility)
if (visibility == View.GONE || visibility == View.INVISIBLE) {
saveAndStop()
} else if (visibility == View.VISIBLE) {
restoreAndStart()
}
}
} | apache-2.0 | a2cbd8f42f48e41a6a1c688e3b5cb97c | 28.855072 | 137 | 0.673142 | 4.822014 | false | false | false | false |
pdvrieze/ProcessManager | ProcessEngine/core/src/jvmTest/kotlin/nl/adaptivity/process/engine/test/loanOrigination/systems/EngineService.kt | 1 | 3637 | /*
* Copyright (c) 2019.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine.test.loanOrigination.systems
import nl.adaptivity.process.engine.PNIHandle
import nl.adaptivity.process.engine.ProcessEngineDataAccess
import nl.adaptivity.process.engine.test.loanOrigination.LoanActivityContext
import nl.adaptivity.process.engine.test.loanOrigination.auth.*
import java.security.Principal
import java.util.*
class EngineService(
private val engineData: ProcessEngineDataAccess,
authService: AuthService,
serviceAuth: IdSecretAuthInfo
) : ServiceImpl(authService, serviceAuth) {
override fun getServiceState(): String = ""
/**
* Accept the activity and return an authorization code for the user to identify itself with in relation to
* the activity.
*/
fun acceptActivity(
authToken: AuthToken,
nodeInstanceHandle: PNIHandle,
principal: Principal,
pendingPermissions: ArrayDeque<LoanActivityContext.PendingPermission>
): AuthorizationCode {
logMe(authToken, nodeInstanceHandle, principal)
validateAuthInfo(authToken, LoanPermissions.ACCEPT_TASK(nodeInstanceHandle)) // TODO mark correct expected permission
if (nodeInstanceHandle!= authToken.nodeInstanceHandle) throw IllegalArgumentException("Mismatch with node instances")
// Should register owner.
// val taskAuthorizationCode = authService.createAuthorizationCode(serviceAuth, authToken.principal.name, authToken.nodeInstanceHandle, this)
return authService.createAuthorizationCode(serviceAuth, principal.name, authToken.nodeInstanceHandle, authService, LoanPermissions.IDENTIFY).also { authorizationCode ->
val clientId = principal.name
// Also use the result to register permissions for it
while (pendingPermissions.isNotEmpty()) {
val pendingPermission = pendingPermissions.removeFirst()
authService.grantPermission(
serviceAuth,
authorizationCode,
authService,
LoanPermissions.GRANT_ACTIVITY_PERMISSION.restrictTo(nodeInstanceHandle, clientId, pendingPermission.service, pendingPermission.scope))
}
}
}
fun registerActivityToTaskList(taskList: TaskList, pniHandle: PNIHandle) {
logMe(pniHandle)
val permissions = listOf(LoanPermissions.UPDATE_ACTIVITY_STATE(pniHandle),
LoanPermissions.ACCEPT_TASK(pniHandle))
val taskListToEngineAuthToken = authService.createAuthorizationCode(
serviceAuth,
taskList.serviceId,
pniHandle,
this,
UnionPermissionScope(permissions)
)
val taskListAuth = authTokenForService(taskList)
taskList.postTask(taskListAuth, taskListToEngineAuthToken, pniHandle)
}
}
| lgpl-3.0 | efd01025601903dbfc24fd77ca87a2a7 | 42.297619 | 176 | 0.697553 | 5.225575 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/util/UserReportingHandler.kt | 1 | 2648 | /*
* Copyright (c) 2017. Toshi Inc
*
* 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.toshi.util
import android.app.Dialog
import android.content.Context
import android.support.v7.app.AlertDialog
import android.view.View
import com.toshi.R
import com.toshi.model.local.Report
class UserReportingHandler(
private val context: Context,
private val onReportListener: (Report) -> Unit) {
private var reportDialog: Dialog? = null
private var confirmationDialog: AlertDialog? = null
fun showReportDialog(userAddress: String) {
this.reportDialog = Dialog(this.context)
this.reportDialog?.setContentView(R.layout.view_report_dialog)
this.reportDialog?.findViewById<View>(R.id.spam)?.setOnClickListener { reportSpam(userAddress) }
this.reportDialog?.findViewById<View>(R.id.inappropriate)?.setOnClickListener { reportInappropriate(userAddress) }
this.reportDialog?.show()
}
private fun reportSpam(userAddress: String) {
val details = context.getString(R.string.report_spam)
val report = Report()
.setUserAddress(userAddress)
.setDetails(details)
onReportListener(report)
}
private fun reportInappropriate(userAddress: String) {
val details = context.getString(R.string.report_inappropriate)
val report = Report()
.setUserAddress(userAddress)
.setDetails(details)
onReportListener(report)
}
fun showConfirmationDialog() {
this.reportDialog?.dismiss()
val builder = DialogUtil.getBaseDialog(
this.context,
R.string.report_confirmation_title,
R.string.report_confirmation_message,
R.string.dismiss
)
this.confirmationDialog = builder.create()
this.confirmationDialog?.show()
}
fun clear() {
this.reportDialog?.dismiss()
this.confirmationDialog?.dismiss()
}
} | gpl-3.0 | da10b18f3c92bf2dbb44d7565dacc541 | 32.961538 | 122 | 0.671828 | 4.348112 | false | false | false | false |
songzhw/Hello-kotlin | KotlinPlayground/src/main/kotlin/ca/six/klplay/advanced/delegation/lazy/LazyDemo.kt | 1 | 672 | package ca.six.klplay.advanced.delegation.lazy
class LazyDemo : Activity(){
val textView : String by lazy{
println("find view by id")
findViewById(100);
}
}
fun main(args: Array<String>) {
val lazyDemo = LazyDemo()
println(lazyDemo.textView)
println("===========")
println(lazyDemo.textView)
}
/*
//=>
find view by id
textView
===========
textView
*/
/*
$ javap LazyDemo.class
public final class LazyDemo extends Activity {
static final kotlin.reflect.KProperty[] $$delegatedProperties; //▼
public final java.lang.String getTextView();
public ca.six.kplay.delegation.LazyDemo();
static {}; //▼
}
*/ | apache-2.0 | 1019b9db2e577e3a6f1ad16669165371 | 19.272727 | 68 | 0.636228 | 3.711111 | false | false | false | false |
wtopolski/testing-workshop-app | app/src/main/java/com/github/wtopolski/testingworkshopapp/binding/RecycleViewBinder.kt | 1 | 1203 | package com.github.wtopolski.testingworkshopapp.binding
import android.databinding.Bindable
import android.support.v7.widget.RecyclerView
import com.github.wtopolski.testingworkshopapp.BR
class RecycleViewBinder<L : RecyclerView.Adapter<*>>(enabled: Boolean, visibility: Boolean) : BaseBinder(enabled, visibility) {
@get:Bindable
var adapter: L? = null
set(adapter) {
field = adapter
notifyPropertyChanged(BR.adapter)
}
@get:Bindable
var fixedSize: Boolean = false
private set
@get:Bindable
var itemAnimator: RecyclerView.ItemAnimator? = null
private set
@get:Bindable
var layoutManager: RecyclerView.LayoutManager? = null
private set
@get:Bindable
var itemDecoration: RecyclerView.ItemDecoration? = null
private set
fun configure(fixedSize: Boolean, itemAnimator: RecyclerView.ItemAnimator, layoutManager: RecyclerView.LayoutManager, itemDecoration: RecyclerView.ItemDecoration?) {
this.fixedSize = fixedSize
this.itemAnimator = itemAnimator
this.layoutManager = layoutManager
this.itemDecoration = itemDecoration
notifyChange()
}
}
| apache-2.0 | d68cde889a86022d5c6f3f9b0625e551 | 29.075 | 169 | 0.709061 | 4.910204 | false | false | false | false |
sabi0/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/remote/client/JUnitClientImpl.kt | 1 | 5354 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.remote.client
import com.intellij.openapi.diagnostic.Logger
import com.intellij.testGuiFramework.remote.transport.MessageType
import com.intellij.testGuiFramework.remote.transport.TransportMessage
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Socket
import java.net.SocketException
import java.util.*
import java.util.concurrent.BlockingQueue
import java.util.concurrent.Executors
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
/**
* @author Sergey Karashevich
*/
class JUnitClientImpl(host: String, val port: Int, initHandlers: Array<ClientHandler>? = null) : JUnitClient {
private val LOG = Logger.getInstance("#com.intellij.testGuiFramework.remote.client.JUnitClientImpl")
private val RECEIVE_THREAD = "JUnit Client Receive Thread"
private val SEND_THREAD = "JUnit Client Send Thread"
private val KEEP_ALIVE_THREAD = "JUnit Keep Alive Thread"
private val connection: Socket
private val clientConnectionTimeout = 60000 //in ms
private val clientReceiveThread: ClientReceiveThread
private val clientSendThread: ClientSendThread
private val poolOfMessages: BlockingQueue<TransportMessage> = LinkedBlockingQueue()
private val objectInputStream: ObjectInputStream
private val objectOutputStream: ObjectOutputStream
private val handlers: ArrayList<ClientHandler> = ArrayList()
private val keepAliveThread: KeepAliveThread
init {
if (initHandlers != null) handlers.addAll(initHandlers)
LOG.info("Client connecting to Server($host, $port) ...")
connection = Socket()
connection.connect(InetSocketAddress(InetAddress.getByName(host), port), clientConnectionTimeout)
LOG.info("Client connected to Server($host, $port) successfully")
objectOutputStream = ObjectOutputStream(connection.getOutputStream())
clientSendThread = ClientSendThread(connection, objectOutputStream)
clientSendThread.start()
objectInputStream = ObjectInputStream(connection.getInputStream())
clientReceiveThread = ClientReceiveThread(connection, objectInputStream)
clientReceiveThread.start()
keepAliveThread = KeepAliveThread(connection)
keepAliveThread.start()
}
override fun addHandler(handler: ClientHandler) {
handlers.add(handler)
}
override fun removeHandler(handler: ClientHandler) {
handlers.remove(handler)
}
override fun removeAllHandlers() {
handlers.clear()
}
override fun send(message: TransportMessage) {
poolOfMessages.add(message)
}
override fun stopClient() {
val clientPort = connection.port
LOG.info("Stopping client on port: $clientPort ...")
poolOfMessages.clear()
handlers.clear()
connection.close()
keepAliveThread.cancel()
LOG.info("Stopped client on port: $clientPort")
}
inner class ClientReceiveThread(private val connection: Socket, private val objectInputStream: ObjectInputStream) : Thread(
RECEIVE_THREAD) {
override fun run() {
LOG.info("Starting Client Receive Thread")
try {
while (connection.isConnected) {
val obj = objectInputStream.readObject()
LOG.info("Received message: $obj")
obj as TransportMessage
handlers
.filter { it.accept(obj) }
.forEach { it.handle(obj) }
}
}
catch (e: Exception) {
LOG.info("Transport receiving message exception", e)
}
finally {
objectInputStream.close()
}
}
}
inner class ClientSendThread(private val connection: Socket, private val objectOutputStream: ObjectOutputStream) : Thread(SEND_THREAD) {
override fun run() {
try {
LOG.info("Starting Client Send Thread")
while (connection.isConnected) {
val transportMessage = poolOfMessages.take()
LOG.info("Sending message: $transportMessage")
objectOutputStream.writeObject(transportMessage)
}
}
catch (e: InterruptedException) {
Thread.currentThread().interrupt()
}
finally {
objectOutputStream.close()
}
}
}
inner class KeepAliveThread(private val connection: Socket) : Thread(KEEP_ALIVE_THREAD) {
private val myExecutor = Executors.newSingleThreadScheduledExecutor()
override fun run() {
myExecutor.scheduleWithFixedDelay(
{
if (connection.isConnected) {
send(TransportMessage(MessageType.KEEP_ALIVE))
}
else {
throw SocketException("Connection is broken")
}
}, 0L, 5, TimeUnit.SECONDS)
}
fun cancel() {
myExecutor.shutdownNow()
}
}
}
| apache-2.0 | 509cb0432cebf1a4ba4855ec97c6db34 | 31.646341 | 138 | 0.716474 | 4.801794 | false | false | false | false |
KotlinKit/Reactant | Core/src/main/kotlin/org/brightify/reactant/controller/HamburgerMenuController.kt | 1 | 5774 | package org.brightify.reactant.controller
import android.app.Activity
import android.view.Gravity
import android.view.Menu
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.drawerlayout.widget.DrawerLayout
import com.google.android.material.navigation.NavigationView
import org.brightify.reactant.autolayout.util.children
import org.brightify.reactant.controller.util.TransactionManager
/**
* @author <a href="mailto:[email protected]">Filip Dolnik</a>
*/
// TODO Refactor common code from TabBarController
open class HamburgerMenuController(private val viewControllers: List<ViewController>): ViewController() {
val navigationView: NavigationView
get() = navigationView_ ?: viewNotLoadedError()
val drawer: DrawerLayout
get() = view as DrawerLayout
var selectedViewController: ViewController
get() = displayedViewController
set(value) {
if (selectedViewController != value) {
transactionManager.transaction {
clearLayout(true)
showViewController(value)
displayedViewController.viewDidAppear()
}
}
}
var selectedViewControllerIndex: Int
get() = (0 until navigationView.menu.size()).firstOrNull { navigationView.menu.getItem(it).isChecked } ?: 0
set(value) {
selectedViewController = viewControllers[value]
}
private var layout: FrameLayout? = null
private var navigationView_: NavigationView? = null
private var displayedViewController: ViewController = viewControllers[0]
private val transactionManager = TransactionManager()
init {
viewControllers.forEach {
it.hamburgerMenuController = this
}
}
override fun activityDidChange(oldActivity: Activity?) {
super.activityDidChange(oldActivity)
viewControllers.forEach {
it.activity_ = activity_
}
}
override fun loadView() {
super.loadView()
layout = FrameLayout(activity)
navigationView_ = NavigationView(activity)
view_ = DrawerLayout(activity).children(layout, navigationView)
view.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
layout?.layoutParams = DrawerLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
navigationView.layoutParams =
DrawerLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT).apply {
gravity = Gravity.START
}
viewControllers.forEach {
updateMenuItem(it)
}
transactionManager.enabled = true
// Fix shrinking of layout when both keyboard and navigationView is visible.
navigationView.getChildAt(0).isScrollContainer = false
}
override fun viewWillAppear() {
super.viewWillAppear()
transactionManager.transaction {
clearLayout(false)
showViewController(selectedViewController)
}
}
override fun viewDidAppear() {
super.viewDidAppear()
displayedViewController.viewDidAppear()
}
override fun viewWillDisappear() {
super.viewWillDisappear()
displayedViewController.viewWillDisappear()
}
override fun viewDidDisappear() {
super.viewDidDisappear()
displayedViewController.viewDidDisappear()
}
override fun viewDestroyed() {
super.viewDestroyed()
transactionManager.enabled = false
layout = null
navigationView_ = null
}
override fun deactivated() {
super.deactivated()
viewControllers.forEach {
it.activity_ = null
}
}
override fun onBackPressed(): Boolean = displayedViewController.onBackPressed()
override fun destroyViewHierarchy() {
super.destroyViewHierarchy()
viewControllers.forEach {
it.destroyViewHierarchy()
}
}
fun updateMenuItem(viewController: ViewController) {
if (navigationView_ == null) {
return
}
val index = viewControllers.indexOf(viewController)
navigationView.menu.removeItem(index)
val text = viewController.hamburgerMenuItem?.titleRes?.let { activity.getString(it) } ?: "Undefined"
val item = navigationView.menu.add(Menu.NONE, index, index, text)
item.isCheckable = true
viewController.hamburgerMenuItem?.imageRes?.let { item.setIcon(it) }
item.setOnMenuItemClickListener {
selectedViewController = viewControllers[item.itemId]
drawer.closeDrawer(navigationView)
return@setOnMenuItemClickListener false
}
}
fun invalidateChild() {
if (!transactionManager.isInTransaction) {
clearLayout(false)
addViewToHierarchy()
}
}
private fun clearLayout(callCallbacks: Boolean) {
if (callCallbacks) {
displayedViewController.viewWillDisappear()
}
layout?.removeAllViews()
if (callCallbacks) {
displayedViewController.viewDidDisappear()
}
}
private fun showViewController(viewController: ViewController) {
displayedViewController = viewController
navigationView.setCheckedItem(viewControllers.indexOf(viewController))
displayedViewController.hamburgerMenuController = this
displayedViewController.viewWillAppear()
addViewToHierarchy()
}
private fun addViewToHierarchy() {
layout?.addView(displayedViewController.view)
}
} | mit | 79b4027f7b46704d61511b41c33b13eb | 29.555556 | 130 | 0.666263 | 5.406367 | false | false | false | false |
Harvard2017/matchr | app/src/main/java/com/matchr/data/Data.kt | 1 | 1656 | package com.matchr.data
import android.widget.TextView
import com.matchr.R
import com.matchr.iitems.ChoiceItem
import com.mikepenz.fastadapter.commons.adapters.FastItemAdapter
/**
* Created by Allan Wang on 2017-10-20.
*/
enum class QuestionType(
val layoutRes: Int, private val withMultiSelect: Boolean
) {
SINGLE_CHOICE(R.layout.iitem_choice_single, false),
MULTIPLE_CHOICE(R.layout.iitem_choice_multi, true);
fun updateAdapter(question: Question, title: TextView, adapter: FastItemAdapter<ChoiceItem>) {
title.setText(question.question)
adapter.set(question.options.map { ChoiceItem(this, it.first) })
adapter.withMultiSelect(withMultiSelect)
}
companion object {
val values = values()
operator fun invoke(index: Int) = values[index]
}
}
data class User(val id: String, val name: String, val email: String)
data class Matchr(val rId1: Int, val rId2: Int, val weight: Float)
data class Response(val userId: String, val qOrdinal: Int, val data: List<String>)
data class Question(val id: Int, val question: String, val options: List<Pair<String, Int>>, val type: Int) {
fun delegate() = QuestionType(type)
fun nextId(selected: Set<Int>): Int
= options[selected.firstOrNull() ?: 0].second
}
fun singleChoiceQuestion(id: Int, question: String, vararg options: Pair<String, Int>)
= Question(id, question, options.asList(), QuestionType.SINGLE_CHOICE.ordinal)
fun multiChoiceQuestion(id: Int, question: String, nextId: Int, vararg options: String)
= Question(id, question, options.map { it to nextId }, QuestionType.MULTIPLE_CHOICE.ordinal) | apache-2.0 | 30cb49e079f062f5660a7f6eee3690e8 | 35.822222 | 109 | 0.71558 | 3.738149 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/fragments/BusyDialog.kt | 1 | 1458 | package com.pr0gramm.app.ui.fragments
import android.app.Dialog
import android.content.Context
import android.widget.TextView
import androidx.annotation.StringRes
import com.pr0gramm.app.BuildConfig
import com.pr0gramm.app.Logger
import com.pr0gramm.app.R
import com.pr0gramm.app.ui.fragments.BusyDialogHelper.dismiss
import com.pr0gramm.app.ui.showDialog
import com.pr0gramm.app.util.checkMainThread
private object BusyDialogHelper {
private val logger = Logger("BusyDialog")
fun show(context: Context, text: String): Dialog {
return showDialog(context) {
layout(R.layout.progress_dialog)
cancelable()
onShow {
val view = it.findViewById<TextView>(R.id.text)
view?.text = text
}
}
}
fun dismiss(dialog: Dialog) {
try {
checkMainThread()
dialog.dismiss()
} catch (err: Throwable) {
logger.warn("Could not dismiss busy dialog:", err)
if (BuildConfig.DEBUG) {
throw err
}
}
}
}
suspend fun <T> withBusyDialog(
context: Context, @StringRes textId: Int = R.string.please_wait, block: suspend () -> T): T {
checkMainThread()
val dialog = run {
val text = context.getString(textId)
BusyDialogHelper.show(context, text)
}
try {
return block()
} finally {
dismiss(dialog)
}
}
| mit | 0eb76c5523575284ad067fea90df877f | 24.137931 | 101 | 0.616598 | 4.130312 | false | false | false | false |
AoEiuV020/PaNovel | api/src/main/java/cc/aoeiuv020/panovel/api/site/jdxs520.kt | 1 | 4901 | package cc.aoeiuv020.panovel.api.site
import cc.aoeiuv020.base.jar.ownTextListSplitWhitespace
import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext
import cc.aoeiuv020.regex.matches
import cc.aoeiuv020.regex.pick
import java.net.URL
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by AoEiuV020 on 2018.06.03-18:49:36.
*/
class Jdxs520 : DslJsoupNovelContext() {init {
// 网站整个变了,模板变了数据变了,已经不是原来的网站了,虽然还能打开,但有需要的话要另开一个网站,
hide = true
site {
name = "经典小说520"
baseUrl = "http://www.jdxs5200.net"
logo = "http://www.jdxs5200.net/jdxs/images/logo.png"
}
search {
get {
// http://www.jdxs5200.com/modules/article/search.php?searchtype=articlename&searchkey=%B6%BC%CA%D0&page=1
charset = "GBK"
url = "/modules/article/search.php"
data {
"searchtype" to "articlename"
"searchkey" to it
// 加上&page=1可以避开搜索时间间隔的限制,
// 也可以通过不加载cookies避开搜索时间间隔的限制,
"page" to "1"
}
}
document {
if (URL(root.ownerDocument().location()).path.startsWith("/book_")) {
single {
name("#info > h1")
author("#info > span")
}
} else {
items("body > div.warpper > div.o_all > div.o_content > div > table > tbody > tr:not(:nth-child(1))") {
name("> td:nth-child(1) > a")
author("> td:nth-child(3)")
}
}
}
}
// http://www.jdxs5200.com/book_77903/
bookIdRegex = "/book_(\\d+)"
detailPageTemplate = "/book_%s/"
detail {
document {
novel {
name("#info > h1")
author("#info > span")
}
image("#fmimg > img")
/*
<div id="intro">
本书已更新<b class="txt-lg txt-orange">202万</b>字,念念不忘,总裁乘胜追妻最新章节:<a class="link-lastchapter" href="46358897.html" title="第148章 重新开始">第148章 重新开始</a>(2018-06-02 21:52)
<br> 初见,她在下,他在上,他的口中叫着别人的名字。<br>
再见,她衣裳凌乱,披头散发,被人屈辱按在地上,狼狈不堪……<br>
他是人人敬畏的传奇人物,霍家太子爷。<br>
顺手救下她,冷漠送她四个字“咎由自取!”<br>
狼狈的她,却露出一抹明媚的笑,声音清脆“姐夫……谢谢啊!”
念念不忘,总裁乘胜追妻是作者七爷精心创作的玄幻小说大作,经典小说网实时同步更新念念不忘,总裁乘胜追妻最新章节无弹窗广告版。书友所发表的念念不忘,总裁乘胜追妻评论,并不代表经典小说网赞同或者支持念念不忘,总裁乘胜追妻读者的观点。
<br>七爷的其他作品:<a href="/book_130135/" target="_blank">爱不言衷</a>、<a href="/book_124032/" target="_blank">怦然心动, 娇妻心间宠</a>、<a href="/book_40728/" target="_blank">冷血总裁放过我</a>
<br>您要是觉得《念念不忘,总裁乘胜追妻》还不错,请点击右上角的分享按钮分享到你的朋友圈吧!
</div>
*/
introduction("#intro") {
it.textNodes()
.dropWhile { !it.wholeText.trim().matches("\\(\\S+ \\S+\\)") }
.also {
update = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA).parse(it.first().wholeText.trim().pick("\\((\\S+ \\S+)\\)").first())
}
.drop(1)
.dropLastWhile { !it.wholeText.trim().endsWith("的其他作品:") }
.dropLast(1)
.flatMap { it.ownTextListSplitWhitespace() }
.dropLast(1)
.joinToString("\n")
}
}
}
chapters {
document {
items("body > div:nth-child(4) > div:nth-child(1) > ul > li > a")
lastUpdate("#intro", format = "yyyy-MM-dd HH:mm", block = pickString("\\((\\S+ \\S+)\\)"))
}
}
// http://www.jdxs5200.com/book_77903/46358897.html
bookIdWithChapterIdRegex = "/book_(\\d+/\\d+)"
contentPageTemplate = "/book_%s.html"
content {
document {
items("#htmlContent") {
it.textNodes().drop(1)
.flatMap { it.ownTextListSplitWhitespace() }
}
}
}
}
}
| gpl-3.0 | c898bb589b404404534be339bd342a15 | 37.009434 | 183 | 0.509059 | 2.786307 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/preferences/fragments/BaseAccountPreference.kt | 1 | 2066 | package org.tasks.preferences.fragments
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.tasks.R
import org.tasks.billing.BillingClient
import org.tasks.billing.PurchaseActivity
import org.tasks.injection.InjectingPreferenceFragment
import javax.inject.Inject
abstract class BaseAccountPreference : InjectingPreferenceFragment() {
@Inject lateinit var billingClient: BillingClient
override suspend fun setupPreferences(savedInstanceState: Bundle?) {
findPreference(R.string.logout).setOnPreferenceClickListener {
dialogBuilder
.newDialog()
.setMessage(R.string.logout_warning)
.setPositiveButton(R.string.remove) { _, _ ->
lifecycleScope.launch {
withContext(NonCancellable) {
removeAccount()
}
activity?.onBackPressed()
}
}
.setNegativeButton(R.string.cancel, null)
.show()
false
}
}
protected abstract suspend fun removeAccount()
protected fun showPurchaseDialog(): Boolean {
startActivityForResult(
Intent(context, PurchaseActivity::class.java),
REQUEST_PURCHASE
)
return false
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_PURCHASE) {
if (resultCode == Activity.RESULT_OK) {
lifecycleScope.launch {
billingClient.queryPurchases()
}
}
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
companion object {
const val REQUEST_PURCHASE = 10201
}
} | gpl-3.0 | be11a4190b99d46a0bdb2c1c80cd56a1 | 30.8 | 85 | 0.603098 | 5.787115 | false | false | false | false |
wiltonlazary/kotlin-native | Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/StubIrTextEmitter.kt | 1 | 28650 | /*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.native.interop.gen
import org.jetbrains.kotlin.native.interop.gen.jvm.KotlinPlatform
import org.jetbrains.kotlin.native.interop.indexer.*
import org.jetbrains.kotlin.utils.addIfNotNull
import java.lang.IllegalStateException
/**
* Emits stubs and bridge functions as *.kt and *.c files.
* Many unintuitive printings are made for compatability with previous version of stub generator.
*
* [omitEmptyLines] is useful for testing output (e.g. diff calculating).
*/
class StubIrTextEmitter(
private val context: StubIrContext,
private val builderResult: StubIrBuilderResult,
private val bridgeBuilderResult: BridgeBuilderResult,
private val omitEmptyLines: Boolean = false
) {
private val kotlinFile = bridgeBuilderResult.kotlinFile
private val nativeBridges = bridgeBuilderResult.nativeBridges
private val propertyAccessorBridgeBodies = bridgeBuilderResult.propertyAccessorBridgeBodies
private val functionBridgeBodies = bridgeBuilderResult.functionBridgeBodies
private val pkgName: String
get() = context.configuration.pkgName
private val StubContainer.isTopLevelContainer: Boolean
get() = this == builderResult.stubs || this in builderResult.stubs.simpleContainers
/**
* The output currently used by the generator.
* Should append line separator after any usage.
*/
private var out: (String) -> Unit = {
throw IllegalStateException()
}
private fun emitEmptyLine() {
if (!omitEmptyLines) {
out("")
}
}
private fun <R> withOutput(output: (String) -> Unit, action: () -> R): R {
val oldOut = out
out = output
try {
return action()
} finally {
out = oldOut
}
}
private fun <R> withOutput(appendable: Appendable, action: () -> R): R {
return withOutput({ appendable.appendLine(it) }, action)
}
private fun generateLinesBy(action: () -> Unit): List<String> {
val result = mutableListOf<String>()
withOutput({ result.add(it) }, action)
return result
}
private fun generateKotlinFragmentBy(block: () -> Unit): Sequence<String> {
val lines = generateLinesBy(block)
return lines.asSequence()
}
private fun <R> indent(action: () -> R): R {
val oldOut = out
return withOutput({ oldOut(" $it") }, action)
}
private fun <R> block(header: String, body: () -> R): R {
out("$header {")
val res = indent {
body()
}
out("}")
return res
}
private fun emitKotlinFileHeader() {
if (context.platform == KotlinPlatform.JVM) {
out("@file:JvmName(${context.jvmFileClassName.quoteAsKotlinLiteral()})")
}
if (context.platform == KotlinPlatform.NATIVE) {
out("@file:kotlinx.cinterop.InteropStubs")
}
val suppress = mutableListOf("UNUSED_VARIABLE", "UNUSED_EXPRESSION").apply {
if (context.configuration.library.language == Language.OBJECTIVE_C) {
add("CONFLICTING_OVERLOADS")
add("RETURN_TYPE_MISMATCH_ON_INHERITANCE")
add("PROPERTY_TYPE_MISMATCH_ON_INHERITANCE") // Multiple-inheriting property with conflicting types
add("VAR_TYPE_MISMATCH_ON_INHERITANCE") // Multiple-inheriting mutable property with conflicting types
add("RETURN_TYPE_MISMATCH_ON_OVERRIDE")
add("WRONG_MODIFIER_CONTAINING_DECLARATION") // For `final val` in interface.
add("PARAMETER_NAME_CHANGED_ON_OVERRIDE")
add("UNUSED_PARAMETER") // For constructors.
add("MANY_IMPL_MEMBER_NOT_IMPLEMENTED") // Workaround for multiple-inherited properties.
add("MANY_INTERFACES_MEMBER_NOT_IMPLEMENTED") // Workaround for multiple-inherited properties.
add("EXTENSION_SHADOWED_BY_MEMBER") // For Objective-C categories represented as extensions.
add("REDUNDANT_NULLABLE") // This warning appears due to Obj-C typedef nullability incomplete support.
add("DEPRECATION") // For uncheckedCast.
add("DEPRECATION_ERROR") // For initializers.
}
}
out("@file:Suppress(${suppress.joinToString { it.quoteAsKotlinLiteral() }})")
if (pkgName != "") {
out("package ${context.validPackageName}")
out("")
}
if (context.platform == KotlinPlatform.NATIVE) {
out("import kotlin.native.SymbolName")
out("import kotlinx.cinterop.internal.*")
}
out("import kotlinx.cinterop.*")
kotlinFile.buildImports().forEach {
out(it)
}
out("")
out("// NOTE THIS FILE IS AUTO-GENERATED")
}
fun emit(ktFile: Appendable) {
// Stubs generation may affect imports list so do it before header generation.
val stubLines = generateKotlinFragmentBy {
printer.visitSimpleStubContainer(builderResult.stubs, null)
}
withOutput(ktFile) {
emitKotlinFileHeader()
stubLines.forEach(out)
nativeBridges.kotlinLines.forEach(out)
if (context.platform == KotlinPlatform.JVM)
out("private val loadLibrary = loadKonanLibrary(\"${context.libName}\")")
}
}
private val printer = object : StubIrVisitor<StubContainer?, Unit> {
override fun visitClass(element: ClassStub, data: StubContainer?) {
element.annotations.forEach {
out(renderAnnotation(it))
}
val header = renderClassHeader(element)
when {
element.children.isEmpty() -> out(header)
else -> block(header) {
if (element is ClassStub.Enum) {
emitEnumEntries(element)
}
element.children
// We render a primary constructor as part of a header.
.filterNot { it is ConstructorStub && it.isPrimary }
.forEach {
emitEmptyLine()
it.accept(this, element)
}
if (element is ClassStub.Enum) {
emitEnumVarClass(element)
}
}
}
}
override fun visitTypealias(element: TypealiasStub, data: StubContainer?) {
val alias = renderClassifierDeclaration(element.alias)
val aliasee = renderStubType(element.aliasee)
out("typealias $alias = $aliasee")
}
override fun visitFunction(element: FunctionStub, data: StubContainer?) {
if (element in bridgeBuilderResult.excludedStubs) return
val header = run {
val parameters = element.parameters.joinToString(prefix = "(", postfix = ")") { renderFunctionParameter(it) }
val receiver = element.receiver?.let { renderFunctionReceiver(it) + "." } ?: ""
val typeParameters = renderTypeParameters(element.typeParameters)
val override = if (element.isOverride) "override " else ""
val modality = renderMemberModality(element.modality, data)
"$override${modality}fun$typeParameters $receiver${element.name.asSimpleName()}$parameters: ${renderStubType(element.returnType)}"
}
if (!nativeBridges.isSupported(element)) {
sequenceOf(
annotationForUnableToImport,
"$header = throw UnsupportedOperationException()"
).forEach(out)
return
}
element.annotations.forEach {
out(renderAnnotation(it))
}
when {
element.external -> out("external $header")
element.isOptionalObjCMethod() -> out("$header = optional()")
element.origin is StubOrigin.Synthetic.EnumByValue ->
out("$header = values().find { it.value == value }!!")
data != null && data.isInterface -> out(header)
else -> block(header) {
functionBridgeBodies.getValue(element).forEach(out)
}
}
}
override fun visitProperty(element: PropertyStub, data: StubContainer?) =
emitProperty(element, data)
override fun visitConstructor(constructorStub: ConstructorStub, data: StubContainer?) {
constructorStub.annotations.forEach {
out(renderAnnotation(it))
}
val visibility = renderVisibilityModifier(constructorStub.visibility)
out("${visibility}constructor(${constructorStub.parameters.joinToString { renderFunctionParameter(it) }}) {}")
}
override fun visitPropertyAccessor(propertyAccessor: PropertyAccessor, data: StubContainer?) {
}
override fun visitSimpleStubContainer(simpleStubContainer: SimpleStubContainer, data: StubContainer?) {
if (simpleStubContainer.meta.textAtStart.isNotEmpty()) {
out(simpleStubContainer.meta.textAtStart)
}
simpleStubContainer.classes.forEach {
emitEmptyLine()
it.accept(this, simpleStubContainer)
}
simpleStubContainer.functions.forEach {
emitEmptyLine()
it.accept(this, simpleStubContainer)
}
simpleStubContainer.properties.forEach {
emitEmptyLine()
it.accept(this, simpleStubContainer)
}
simpleStubContainer.typealiases.forEach {
emitEmptyLine()
it.accept(this, simpleStubContainer)
}
simpleStubContainer.simpleContainers.forEach {
emitEmptyLine()
it.accept(this, simpleStubContainer)
}
if (simpleStubContainer.meta.textAtEnd.isNotEmpty()) {
out(simpleStubContainer.meta.textAtEnd)
}
}
}
// About method naming convention:
// - "emit" prefix means that method will call `out` by itself.
// - "render" prefix means that method returns string that should be emitted by caller.
private fun emitEnumEntries(enum: ClassStub.Enum) {
enum.entries.forEach {
out(renderEnumEntry(it) + ",")
}
out(";")
}
private fun emitEnumVarClass(enum: ClassStub.Enum) {
val simpleKotlinName = enum.classifier.topLevelName.asSimpleName()
val typeMirror = builderResult.bridgeGenerationComponents.enumToTypeMirror.getValue(enum)
val basePointedTypeName = typeMirror.pointedType.render(kotlinFile)
block("class Var(rawPtr: NativePtr) : CEnumVar(rawPtr)") {
out("companion object : Type($basePointedTypeName.size.toInt())")
out("var value: $simpleKotlinName")
out(" get() = byValue(this.reinterpret<$basePointedTypeName>().value)")
out(" set(value) { this.reinterpret<$basePointedTypeName>().value = value.value }")
}
}
private fun emitProperty(element: PropertyStub, owner: StubContainer?) {
if (element in bridgeBuilderResult.excludedStubs) return
val override = if (element.isOverride) "override " else ""
val modality = "$override${renderMemberModality(element.modality, owner)}"
val receiver = if (element.receiverType != null) "${renderStubType(element.receiverType)}." else ""
val name = if (owner?.isTopLevelContainer == true) {
getTopLevelPropertyDeclarationName(kotlinFile, element).asSimpleName()
} else {
element.name.asSimpleName()
}
val header = "$receiver$name: ${renderStubType(element.type)}"
if (element.kind is PropertyStub.Kind.Val && !nativeBridges.isSupported(element.kind.getter)
|| element.kind is PropertyStub.Kind.Var && !nativeBridges.isSupported(element.kind.getter)) {
out(annotationForUnableToImport)
out("val $header")
out(" get() = TODO()")
} else {
element.annotations.forEach {
out(renderAnnotation(it))
}
when (val kind = element.kind) {
is PropertyStub.Kind.Constant -> {
out("${modality}const val $header = ${renderValueUsage(kind.constant)}")
}
is PropertyStub.Kind.Val -> {
val shouldWriteInline = kind.getter.let {
(it is PropertyAccessor.Getter.SimpleGetter && it.constant != null)
// We should render access to constructor parameter inline.
// Otherwise, it may be access to the property itself. (val f: Any get() = f)
|| it is PropertyAccessor.Getter.GetConstructorParameter
}
if (shouldWriteInline) {
out("${modality}val $header ${renderGetter(kind.getter)}")
} else {
out("${modality}val $header")
indent {
out(renderGetter(kind.getter))
}
}
}
is PropertyStub.Kind.Var -> {
val isSupported = nativeBridges.isSupported(kind.setter)
val variableKind = if (isSupported) "var" else "val"
out("$modality$variableKind $header")
indent {
out(renderGetter(kind.getter))
if (isSupported) {
out(renderSetter(kind.setter))
}
}
}
}
}
}
private fun renderFunctionReceiver(receiver: ReceiverParameterStub): String {
return renderStubType(receiver.type)
}
private fun renderFunctionParameter(parameter: FunctionParameterStub): String {
val annotations = if (parameter.annotations.isEmpty())
""
else
parameter.annotations.joinToString(separator = " ") { renderAnnotation(it) } + " "
val vararg = if (parameter.isVararg) "vararg " else ""
return "$annotations$vararg${parameter.name.asSimpleName()}: ${renderStubType(parameter.type)}"
}
private fun renderMemberModality(modality: MemberStubModality, container: StubContainer?): String =
if (container?.defaultMemberModality == modality) {
""
} else
when (modality) {
MemberStubModality.OPEN -> "open "
MemberStubModality.FINAL -> "final "
MemberStubModality.ABSTRACT -> "abstract "
}
private fun renderVisibilityModifier(visibilityModifier: VisibilityModifier) = when (visibilityModifier) {
VisibilityModifier.PRIVATE -> "private "
VisibilityModifier.PROTECTED -> "protected "
VisibilityModifier.INTERNAL -> "internal "
VisibilityModifier.PUBLIC -> ""
}
private fun renderClassHeader(classStub: ClassStub): String {
val modality = when (classStub) {
is ClassStub.Simple -> renderClassStubModality(classStub.modality)
is ClassStub.Companion -> ""
is ClassStub.Enum -> "enum class "
}
val className = when (classStub) {
is ClassStub.Simple -> renderClassifierDeclaration(classStub.classifier)
is ClassStub.Companion -> "companion object"
is ClassStub.Enum -> renderClassifierDeclaration(classStub.classifier)
}
val constructorParams = classStub.explicitPrimaryConstructor?.parameters?.let(this::renderConstructorParams) ?: ""
val inheritance = mutableListOf<String>().apply {
// Enum inheritance is implicit.
if (classStub !is ClassStub.Enum) {
addIfNotNull(classStub.superClassInit?.let { renderSuperInit(it) })
}
addAll(classStub.interfaces.map { renderStubType(it) })
}.let { if (it.isNotEmpty()) " : ${it.joinToString()}" else "" }
return "$modality$className$constructorParams$inheritance"
}
private fun renderClassifierDeclaration(classifier: Classifier): String =
kotlinFile.declare(classifier).asSimpleName()
private fun renderClassStubModality(classStubModality: ClassStubModality): String = when (classStubModality) {
ClassStubModality.INTERFACE -> "interface "
ClassStubModality.OPEN -> "open class "
ClassStubModality.ABSTRACT -> "abstract class "
ClassStubModality.NONE -> "class "
}
private fun renderConstructorParams(parameters: List<FunctionParameterStub>): String =
if (parameters.isEmpty()) {
""
} else {
parameters.joinToString(prefix = "(", postfix = ")") { renderFunctionParameter(it) }
}
private fun renderSuperInit(superClassInit: SuperClassInit): String {
val parameters = superClassInit.arguments.joinToString(prefix = "(", postfix = ")") { renderValueUsage(it) }
return "${renderStubType(superClassInit.type)}$parameters"
}
private fun renderStubType(stubType: StubType): String {
val nullable = if (stubType.nullable) "?" else ""
return when (stubType) {
is ClassifierStubType -> {
val classifier = kotlinFile.reference(stubType.classifier)
val typeArguments = renderTypeArguments(stubType.typeArguments)
"$classifier$typeArguments$nullable"
}
is FunctionalType -> buildString {
if (stubType.nullable) append("(")
append('(')
stubType.parameterTypes.joinTo(this) { renderStubType(it) }
append(") -> ")
append(renderStubType(stubType.returnType))
if (stubType.nullable) append(")?")
}
is TypeParameterType -> "${stubType.name}$nullable"
is AbbreviatedType -> {
val classifier = kotlinFile.reference(stubType.abbreviatedClassifier)
val typeArguments = renderTypeArguments(stubType.typeArguments)
"$classifier$typeArguments$nullable"
}
}
}
private fun renderValueUsage(value: ValueStub): String = when (value) {
is StringConstantStub -> value.value.quoteAsKotlinLiteral()
is IntegralConstantStub -> renderIntegralConstant(value)!!
is DoubleConstantStub -> renderDoubleConstant(value)!!
is GetConstructorParameter -> value.constructorParameterStub.name
}
private fun renderAnnotation(annotationStub: AnnotationStub): String = when (annotationStub) {
AnnotationStub.ObjC.ConsumesReceiver -> "@CCall.ConsumesReceiver"
AnnotationStub.ObjC.ReturnsRetained -> "@CCall.ReturnsRetained"
is AnnotationStub.ObjC.Method -> {
val stret = if (annotationStub.isStret) ", true" else ""
val selector = annotationStub.selector.quoteAsKotlinLiteral()
val encoding = annotationStub.encoding.quoteAsKotlinLiteral()
"@ObjCMethod($selector, $encoding$stret)"
}
is AnnotationStub.ObjC.Factory -> {
val stret = if (annotationStub.isStret) ", true" else ""
val selector = annotationStub.selector.quoteAsKotlinLiteral()
val encoding = annotationStub.encoding.quoteAsKotlinLiteral()
"@ObjCFactory($selector, $encoding$stret)"
}
AnnotationStub.ObjC.Consumed ->
"@CCall.Consumed"
is AnnotationStub.ObjC.Constructor ->
"@ObjCConstructor(${annotationStub.selector.quoteAsKotlinLiteral()}, ${annotationStub.designated})"
is AnnotationStub.ObjC.ExternalClass -> {
val protocolGetter = annotationStub.protocolGetter.quoteAsKotlinLiteral()
val binaryName = annotationStub.binaryName.quoteAsKotlinLiteral()
"@ExternalObjCClass" + when {
annotationStub.protocolGetter.isEmpty() && annotationStub.binaryName.isEmpty() -> ""
annotationStub.protocolGetter.isEmpty() -> "(\"\", $binaryName)"
annotationStub.binaryName.isEmpty() -> "($protocolGetter)"
else -> "($protocolGetter, $binaryName)"
}
}
AnnotationStub.CCall.CString ->
"@CCall.CString"
AnnotationStub.CCall.WCString ->
"@CCall.WCString"
is AnnotationStub.CCall.Symbol ->
"@CCall(${annotationStub.symbolName.quoteAsKotlinLiteral()})"
is AnnotationStub.CStruct ->
"@CStruct(${annotationStub.struct.quoteAsKotlinLiteral()})"
is AnnotationStub.CNaturalStruct ->
"@CNaturalStruct(${annotationStub.members.joinToString { it.name.quoteAsKotlinLiteral() }})"
is AnnotationStub.CLength ->
"@CLength(${annotationStub.length})"
is AnnotationStub.Deprecated ->
"@Deprecated(${annotationStub.message.quoteAsKotlinLiteral()}, " +
"ReplaceWith(${annotationStub.replaceWith.quoteAsKotlinLiteral()}), " +
"DeprecationLevel.ERROR)"
is AnnotationStub.CEnumEntryAlias,
is AnnotationStub.CEnumVarTypeSize,
is AnnotationStub.CStruct.MemberAt,
is AnnotationStub.CStruct.ArrayMemberAt,
is AnnotationStub.CStruct.BitField,
is AnnotationStub.CStruct.VarType ->
error("${annotationStub.classifier.fqName} annotation is unsupported in textual mode")
}
private fun renderEnumEntry(enumEntryStub: EnumEntryStub): String =
"${enumEntryStub.name.asSimpleName()}(${renderValueUsage(enumEntryStub.constant)})"
private fun renderGetter(accessor: PropertyAccessor.Getter): String {
val annotations = accessor.annotations.joinToString(separator = "") { renderAnnotation(it) + " " }
return annotations + when (accessor) {
is PropertyAccessor.Getter.ExternalGetter -> {
"external get"
}
is PropertyAccessor.Getter.GetConstructorParameter -> "= ${renderPropertyAccessorBody(accessor)}"
else -> {
"get() = ${renderPropertyAccessorBody(accessor)}"
}
}
}
private fun renderSetter(accessor: PropertyAccessor.Setter): String {
val annotations = accessor.annotations.joinToString(separator = "") { renderAnnotation(it) + " " }
return annotations + if (accessor is PropertyAccessor.Setter.ExternalSetter) {
"external set"
} else {
"set(value) { ${renderPropertyAccessorBody(accessor)} }"
}
}
private fun renderPropertyAccessorBody(accessor: PropertyAccessor): String = when (accessor) {
is PropertyAccessor.Getter.SimpleGetter -> {
when {
accessor in propertyAccessorBridgeBodies -> propertyAccessorBridgeBodies.getValue(accessor)
accessor.constant != null -> renderValueUsage(accessor.constant)
else -> error("Bridge body for getter was not generated")
}
}
is PropertyAccessor.Getter.GetConstructorParameter -> accessor.constructorParameter.name
is PropertyAccessor.Getter.ArrayMemberAt -> "arrayMemberAt(${accessor.offset})"
is PropertyAccessor.Getter.MemberAt -> {
val typeArguments = renderTypeArguments(accessor.typeArguments)
val valueAccess = if (accessor.hasValueAccessor) ".value" else ""
"memberAt$typeArguments(${accessor.offset})$valueAccess"
}
is PropertyAccessor.Getter.ReadBits -> {
propertyAccessorBridgeBodies.getValue(accessor)
}
is PropertyAccessor.Getter.GetEnumEntry -> accessor.enumEntryStub.name
is PropertyAccessor.Setter.SimpleSetter -> when {
accessor in propertyAccessorBridgeBodies -> propertyAccessorBridgeBodies.getValue(accessor)
else -> error("Bridge body for setter was not generated")
}
is PropertyAccessor.Setter.MemberAt -> {
if (accessor.typeArguments.isEmpty()) {
error("Unexpected memberAt setter without type parameters!")
} else {
val typeArguments = renderTypeArguments(accessor.typeArguments)
"memberAt$typeArguments(${accessor.offset}).value = value"
}
}
is PropertyAccessor.Setter.WriteBits -> {
propertyAccessorBridgeBodies.getValue(accessor)
}
is PropertyAccessor.Getter.InterpretPointed -> {
val typeParameters = accessor.typeParameters.joinToString(prefix = "<", postfix = ">") { renderStubType(it) }
val getAddressExpression = propertyAccessorBridgeBodies.getValue(accessor)
"interpretPointed$typeParameters($getAddressExpression)"
}
is PropertyAccessor.Getter.ExternalGetter,
is PropertyAccessor.Setter.ExternalSetter -> error("External property accessor shouldn't have a body!")
}
private fun renderIntegralConstant(integralValue: IntegralConstantStub): String? {
val (value, size, isSigned) = integralValue
return if (isSigned) {
if (value == Long.MIN_VALUE) {
return "${value + 1} - 1" // Workaround for "The value is out of range" compile error.
}
val narrowedValue: Number = when (size) {
1 -> value.toByte()
2 -> value.toShort()
4 -> value.toInt()
8 -> value
else -> return null
}
narrowedValue.toString()
} else {
// Note: stub generator is built and run with different ABI versions,
// so Kotlin unsigned types can't be used here currently.
val narrowedValue: String = when (size) {
1 -> (value and 0xFF).toString()
2 -> (value and 0xFFFF).toString()
4 -> (value and 0xFFFFFFFF).toString()
8 -> java.lang.Long.toUnsignedString(value)
else -> return null
}
"${narrowedValue}u"
}
}
private fun renderDoubleConstant(doubleValue: DoubleConstantStub): String? {
val (value, size) = doubleValue
return when (size) {
4 -> {
val floatValue = value.toFloat()
val bits = java.lang.Float.floatToRawIntBits(floatValue)
"bitsToFloat($bits) /* == $floatValue */"
}
8 -> {
val bits = java.lang.Double.doubleToRawLongBits(value)
"bitsToDouble($bits) /* == $value */"
}
else -> null
}
}
private fun renderTypeArguments(typeArguments: List<TypeArgument>) = if (typeArguments.isNotEmpty()) {
typeArguments.joinToString(", ", "<", ">") { renderTypeArgument(it) }
} else {
""
}
private fun renderTypeArgument(typeArgument: TypeArgument) = when (typeArgument) {
is TypeArgumentStub -> {
val variance = when (typeArgument.variance) {
TypeArgument.Variance.INVARIANT -> ""
TypeArgument.Variance.IN -> "in "
TypeArgument.Variance.OUT -> "out "
}
"$variance${renderStubType(typeArgument.type)}"
}
TypeArgument.StarProjection -> "*"
else -> error("Unexpected type argument: $typeArgument")
}
private fun renderTypeParameters(typeParameters: List<TypeParameterStub>) = if (typeParameters.isNotEmpty()) {
typeParameters.joinToString(", ", " <", ">") { renderTypeParameter(it) }
} else {
""
}
private fun renderTypeParameter(typeParameterStub: TypeParameterStub): String {
val name = typeParameterStub.name
return typeParameterStub.upperBound?.let {
"$name : ${renderStubType(it)}"
} ?: name
}
} | apache-2.0 | 9c97927b09106ae45f9a3ffd4eafbaae | 42.344932 | 146 | 0.597696 | 5.20436 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/ide/intentions/MoveGuardToMatchArmIntention.kt | 1 | 1501 | package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RsExpr
import org.rust.lang.core.psi.RsIfExpr
import org.rust.lang.core.psi.RsMatchArmGuard
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.ext.parentMatchArm
import org.rust.lang.core.psi.ext.parentOfType
class MoveGuardToMatchArmIntention : RsElementBaseIntentionAction<MoveGuardToMatchArmIntention.Context>() {
override fun getText(): String = "Move guard inside the match arm"
override fun getFamilyName(): String = text
data class Context(
val guard: RsMatchArmGuard,
val armBody: RsExpr
)
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
val guard = element.parentOfType<RsMatchArmGuard>() ?: return null
val armBody = guard.parentMatchArm.expr ?: return null
return Context(guard, armBody)
}
override fun invoke(project: Project, editor: Editor, ctx: Context) {
val (guard, oldBody) = ctx
val caretOffsetInGuard = editor.caretModel.offset - guard.textOffset
val psiFactory = RsPsiFactory(project)
var newBody = psiFactory.createIfExpression(guard.expr, oldBody)
newBody = oldBody.replace(newBody) as RsIfExpr
guard.delete()
editor.caretModel.moveToOffset(newBody.textOffset + caretOffsetInGuard)
}
}
| mit | 6c24a707d9f0701eb6ef5b3614937e58 | 39.567568 | 107 | 0.740839 | 4.288571 | false | false | false | false |
adgvcxz/ViewModel | app/src/main/kotlin/com/adgvcxz/viewmodel/sample/SimpleRecyclerActivity.kt | 1 | 2768 | package com.adgvcxz.viewmodel.sample
import android.content.Intent
import androidx.recyclerview.widget.LinearLayoutManager
import com.adgvcxz.add
import com.adgvcxz.addTo
import com.adgvcxz.bindEvent
import com.adgvcxz.bindModel
import com.adgvcxz.recyclerviewmodel.*
import com.jakewharton.rxbinding4.swiperefreshlayout.refreshes
import kotlinx.android.synthetic.main.activity_simple_recycler.*
class SimpleRecyclerActivity : BaseActivity<SimpleRecyclerViewModel, RecyclerModel>() {
override val layoutId: Int = R.layout.activity_simple_recycler
override val viewModel: SimpleRecyclerViewModel = SimpleRecyclerViewModel()
override fun initBinding() {
val adapter = RecyclerAdapter(viewModel) {
when (it) {
is TextItemViewModel -> TextItemView()
else -> LoadingItemView()
}
}
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = adapter
// recyclerView.setHasFixedSize(true)
viewModel.bindEvent {
add({ refreshLayout.refreshes() }, { Refresh })
}
adapter.itemClicks().map { viewModel.currentModel().items[it].currentModel() }
.ofType(TextItemViewModel.Model::class.java)
.subscribe {
if (it.id == 0) {
val intent = Intent(this, TestActivity::class.java)
intent.putExtra("id", it.id)
intent.putExtra("value", it.content)
startActivity(intent)
} else {
viewModel.action.onNext(
ReplaceData(
arrayListOf(it.id),
arrayListOf(TextItemViewModel())
)
)
}
}
.addTo(viewModel.disposables)
// adapter.itemClicks()
// .filter { it != adapter.itemCount - 1 }
// .map { RecyclerViewModel.RemoveDataEvent(arrayListOf(it)) }
// .bindTo(viewModel.action)
// .addTo(disposables)
// adapter.itemClicks()
// .filter { it != adapter.itemCount - 1 }
// .subscribe { adapter.notifyDataSetChanged() }
// .addTo(disposables)
// adapter.itemClicks()
// .filter { it != adapter.itemCount - 1 }
// .map { RecyclerViewModel.ReplaceDataEvent(arrayListOf(it), arrayListOf(TextItemViewModel())) }
// .bindTo(viewModel.action)
// .addTo(disposables)
viewModel.bindModel {
add({ isRefresh }, { refreshLayout.isRefreshing = this })
}
viewModel.action.onNext(Refresh)
}
}
| apache-2.0 | ab6426073b48214c6ceca37b7c167574 | 33.17284 | 112 | 0.574783 | 5.051095 | false | false | false | false |
stoman/competitive-programming | problems/2020adventofcode02b/submissions/accepted/Stefan.kt | 2 | 377 | import java.util.Scanner
fun main() {
val s = Scanner(System.`in`).useDelimiter("-|\\s|:\\s")
var r = 0
while(s.hasNext()) {
val a = s.nextInt() - 1
val b = s.nextInt() - 1
val char = s.next()[0]
val password = s.next()
if((password[a] == char) xor (password[b] == char)) {
r++
}
}
println(r)
}
| mit | 0cbe4b682e9115aa59d17c72597f7ac7 | 21.176471 | 61 | 0.461538 | 3.25 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/main/java/com/ichi2/utils/AdaptionUtil.kt | 1 | 7058 | /****************************************************************************************
* Copyright (c) 2020 [email protected] *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.utils
import android.app.ActivityManager
import android.content.ComponentName
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.net.Uri
import android.os.Build
import android.provider.Settings
import com.ichi2.anki.AnkiDroidApp
import timber.log.Timber
import java.lang.Exception
import java.util.*
object AdaptionUtil {
private var sHasRunRestrictedLearningDeviceCheck = false
private var sIsRestrictedLearningDevice = false
private var sHasRunWebBrowserCheck = false
private var sHasWebBrowser = true
private var sIsRunningMiUI: Boolean? = null
@JvmStatic
fun hasWebBrowser(context: Context): Boolean {
if (sHasRunWebBrowserCheck) {
return sHasWebBrowser
}
sHasWebBrowser = checkHasWebBrowser(context)
sHasRunWebBrowserCheck = true
return sHasWebBrowser
}
@JvmStatic
val isUserATestClient: Boolean
get() = try {
ActivityManager.isUserAMonkey() ||
isRunningUnderFirebaseTestLab
} catch (e: Exception) {
Timber.w(e)
false
}
val isRunningUnderFirebaseTestLab: Boolean
get() = try {
isRunningUnderFirebaseTestLab(AnkiDroidApp.getInstance().contentResolver)
} catch (e: Exception) {
Timber.w(e)
false
}
private fun isRunningUnderFirebaseTestLab(contentResolver: ContentResolver): Boolean {
// https://firebase.google.com/docs/test-lab/android/android-studio#modify_instrumented_test_behavior_for
val testLabSetting = Settings.System.getString(contentResolver, "firebase.test.lab")
return "true" == testLabSetting
}
private fun checkHasWebBrowser(context: Context): Boolean {
// The test monkey often gets stuck on the Shared Decks WebView, ignore it as it shouldn't crash.
if (isUserATestClient) {
return false
}
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"))
val pm = context.packageManager
val list = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
for (ri in list) {
if (!isValidBrowser(ri)) {
continue
}
// If we aren't a restricted device, any browser will do
if (!isRestrictedLearningDevice) {
return true
}
// If we are a restricted device, only a system browser will do
if (isSystemApp(ri.activityInfo.packageName, pm)) {
return true
}
}
// Either there are no web browsers, or we're a restricted learning device and there's no system browsers.
return false
}
private fun isValidBrowser(ri: ResolveInfo?): Boolean {
// https://stackoverflow.com/a/57223246/
return ri != null && ri.activityInfo != null && ri.activityInfo.exported
}
private fun isSystemApp(packageName: String?, pm: PackageManager): Boolean {
return if (packageName != null) {
try {
val info = pm.getPackageInfo(packageName, 0)
info != null && info.applicationInfo != null &&
info.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0
} catch (e: PackageManager.NameNotFoundException) {
Timber.w(e)
false
}
} else {
false
}
}
@JvmStatic
val isRestrictedLearningDevice: Boolean
get() {
if (!sHasRunRestrictedLearningDeviceCheck) {
sIsRestrictedLearningDevice = "Xiaomi".equals(Build.MANUFACTURER, ignoreCase = true) &&
("Archytas".equals(Build.PRODUCT, ignoreCase = true) || "Archimedes".equals(Build.PRODUCT, ignoreCase = true))
sHasRunRestrictedLearningDeviceCheck = true
}
return sIsRestrictedLearningDevice
}
fun canUseContextMenu(): Boolean {
return !isRunningMiui
}
private val isRunningMiui: Boolean
get() {
if (sIsRunningMiUI == null) {
sIsRunningMiUI = queryIsMiui()
}
return sIsRunningMiUI!!
}
// https://stackoverflow.com/questions/47610456/how-to-detect-miui-rom-programmatically-in-android
private fun isIntentResolved(ctx: Context, intent: Intent?): Boolean {
return intent != null && ctx.packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null
}
private fun queryIsMiui(): Boolean {
val ctx: Context = AnkiDroidApp.getInstance()
return (
isIntentResolved(ctx, Intent("miui.intent.action.OP_AUTO_START").addCategory(Intent.CATEGORY_DEFAULT)) ||
isIntentResolved(ctx, Intent().setComponent(ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"))) ||
isIntentResolved(ctx, Intent("miui.intent.action.POWER_HIDE_MODE_APP_LIST").addCategory(Intent.CATEGORY_DEFAULT)) ||
isIntentResolved(ctx, Intent().setComponent(ComponentName("com.miui.securitycenter", "com.miui.powercenter.PowerSettings")))
)
}
/** See: https://en.wikipedia.org/wiki/Vivo_(technology_company) */
@JvmStatic
val isVivo: Boolean
get() {
val manufacturer = Build.MANUFACTURER ?: return false
return manufacturer.lowercase(Locale.ROOT) == "vivo"
}
}
| gpl-3.0 | 89219c495bfa2a9e24f6987c58fa5544 | 42.036585 | 166 | 0.591952 | 4.911621 | false | true | false | false |
mix-it/mixit | src/main/kotlin/mixit/web/handler/AuthenticationHandler.kt | 1 | 9413 | package mixit.web.handler
import mixit.MixitProperties
import mixit.model.User
import mixit.util.Cryptographer
import mixit.util.decodeFromBase64
import mixit.util.locale
import mixit.util.validator.EmailValidator
import mixit.web.handler.AuthenticationHandler.LoginError.DUPLICATE_EMAIL
import mixit.web.handler.AuthenticationHandler.LoginError.DUPLICATE_LOGIN
import mixit.web.handler.AuthenticationHandler.LoginError.INVALID_EMAIL
import mixit.web.handler.AuthenticationHandler.LoginError.REQUIRED_CREDENTIALS
import mixit.web.handler.AuthenticationHandler.LoginError.SIGN_UP_ERROR
import mixit.web.service.AuthenticationService
import mixit.web.service.CredentialValidatorException
import mixit.web.service.EmailValidatorException
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.BodyExtractors.toFormData
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.reactive.function.server.ServerResponse
import org.springframework.web.reactive.function.server.ServerResponse.ok
import org.springframework.web.reactive.function.server.ServerResponse.seeOther
import org.springframework.web.reactive.function.server.ServerResponse.temporaryRedirect
import org.springframework.web.server.WebSession
import reactor.core.publisher.Mono
import java.net.URI
import java.net.URLDecoder
@Component
class AuthenticationHandler(
private val authenticationService: AuthenticationService,
private val properties: MixitProperties,
private val emailValidator: EmailValidator,
private val cryptographer: Cryptographer
) {
private fun displayView(page: LoginPage, context: Map<String, String> = emptyMap()) = ok().render(page.template, context)
private fun displayErrorView(error: LoginError): Mono<ServerResponse> = displayView(LoginPage.ERROR, mapOf(Pair("description", error.i18n)))
private enum class LoginPage(val template: String) {
// Page with a field to send his email
LOGIN("login"),
// An error page with a description of this error
ERROR("login-error"),
// Page with a field to send his token (received by email)
CONFIRMATION("login-confirmation"),
// Page displayed when a user is unknown
CREATION("login-creation")
}
private enum class LoginError(val i18n: String) {
// Email is invalid
INVALID_EMAIL("login.error.creation.mail"),
INVALID_TOKEN("login.error.badtoken.text"),
TOKEN_SENT("login.error.sendtoken.text"),
DUPLICATE_LOGIN("login.error.uniquelogin.text"),
DUPLICATE_EMAIL("login.error.uniqueemail.text"),
SIGN_UP_ERROR("login.error.field.text"),
REQUIRED_CREDENTIALS("login.error.required.text")
}
private fun duplicateException(e: Throwable): LoginError = if (e.message != null && e.message!!.contains("login")) DUPLICATE_LOGIN else DUPLICATE_EMAIL
/**
* Display a view with a form to send the email of the user
*/
fun loginView(req: ServerRequest) = displayView(LoginPage.LOGIN)
/**
* Action called by an HTTP post when a user send his email to connect to our application. If user is found
* we send him a token by email. If not we ask him more informations to create an account. But before we
* try to find him in ticket database
*/
fun login(req: ServerRequest): Mono<ServerResponse> = req.body(toFormData()).flatMap {
try {
val nonEncryptedMail = emailValidator.check(it.toSingleValueMap()["email"])
authenticationService.searchUserByEmailOrCreateHimFromTicket(nonEncryptedMail)
// If user is found we send him a token
.flatMap { generateAndSendToken(req, it, nonEncryptedMail) }
// An error can be thrown when we try to create a user from ticketting
.onErrorResume { displayErrorView(duplicateException(it)) }
// if user is not found we ask him if he wants to create a new account
.switchIfEmpty(Mono.defer { displayView(LoginPage.CREATION, mapOf(Pair("email", nonEncryptedMail))) })
} catch (e: EmailValidatorException) {
displayErrorView(LoginError.INVALID_EMAIL)
}
}
fun sendToken(req: ServerRequest): Mono<ServerResponse> = req.body(toFormData()).flatMap {
try {
val nonEncryptedMail = emailValidator.check(it.toSingleValueMap()["email"])
authenticationService.searchUserByEmailOrCreateHimFromTicket(nonEncryptedMail)
// If user is found we send him a token
.flatMap { displayView(LoginPage.CONFIRMATION, mapOf(Pair("email", nonEncryptedMail))) }
// An error can be thrown when we try to create a user from ticketting
.onErrorResume { displayErrorView(duplicateException(it)) }
// if user is not found we ask him if he wants to create a new account
.switchIfEmpty(Mono.defer { displayView(LoginPage.CREATION, mapOf(Pair("email", nonEncryptedMail))) })
} catch (e: EmailValidatorException) {
displayErrorView(LoginError.INVALID_EMAIL)
}
}
/**
* Action called by an HTTP post when a user want to sign up to our application and create his account. If creation
* is OK, we send him a token by email
*/
fun signUp(req: ServerRequest): Mono<ServerResponse> = req.body(toFormData()).flatMap {
it.toSingleValueMap().let { formData ->
try {
val newUser = authenticationService.createUser(formData["email"], formData["firstname"], formData["lastname"])
authenticationService.createUserIfEmailDoesNotExist(nonEncryptedMail = newUser.first, user = newUser.second)
.flatMap { generateAndSendToken(req, nonEncryptedMail = newUser.first, user = newUser.second) }
} catch (e: EmailValidatorException) {
displayErrorView(INVALID_EMAIL)
} catch (e: CredentialValidatorException) {
displayErrorView(SIGN_UP_ERROR)
}
}
}
private fun generateAndSendToken(req: ServerRequest, user: User, nonEncryptedMail: String): Mono<ServerResponse> =
authenticationService.generateAndSendToken(user, req.locale())
// if token is sent we call the the screen where user can type this token
.flatMap { displayView(LoginPage.CONFIRMATION, mapOf(Pair("email", nonEncryptedMail))) }
// An error can occur when email is sent
.onErrorResume { displayErrorView(LoginError.TOKEN_SENT) }
/**
* Action when user wants to send his token to open a session. This token is valid only for a limited time
* This action is launched when user clicks on the link sent by email
*/
fun signInViaUrl(req: ServerRequest): Mono<ServerResponse> {
val email = URLDecoder.decode(req.pathVariable("email"), "UTF-8").decodeFromBase64()
val token = req.pathVariable("token")
return displayView(
LoginPage.CONFIRMATION,
mapOf(
Pair("email", emailValidator.check(email)),
Pair("token", token)
)
)
}
/**
* Action called by an HTTP post when user wants to send his email and his token to open a session.
*/
fun signIn(req: ServerRequest): Mono<ServerResponse> = req.body(toFormData()).flatMap {
it.toSingleValueMap().let { formData ->
// If email or token are null we can't open a session
if (formData["email"] == null || formData["token"] == null) {
displayErrorView(REQUIRED_CREDENTIALS)
} else {
// Email sent can be crypted or not
val nonEncryptedMail = if (formData["email"]!!.contains("@")) formData["email"] else cryptographer.decrypt(formData["email"])
val token = formData["token"]!!
authenticationService.checkUserEmailAndToken(nonEncryptedMail!!, token)
.flatMap { user ->
req.session().flatMap { session ->
session.apply {
attributes["role"] = user.role
attributes["email"] = nonEncryptedMail
attributes["token"] = token
}
seeOther(URI("${properties.baseUri}/me")).cookie(authenticationService.createCookie(user)).build()
}
}
.onErrorResume { displayErrorView(LoginError.INVALID_TOKEN) }
}
}
}
/**
* Action when user wants to log out
*/
fun logout(req: ServerRequest): Mono<ServerResponse> = req.session().flatMap { session ->
Mono.justOrEmpty(session.getAttribute<String>("email"))
.flatMap { authenticationService.clearToken(it).flatMap { clearSession(session) } }
.switchIfEmpty(Mono.defer { clearSession(session) })
}
private fun clearSession(session: WebSession): Mono<ServerResponse> {
session.attributes.apply {
remove("email")
remove("login")
remove("token")
remove("role")
}
return temporaryRedirect(URI("${properties.baseUri}/")).build()
}
}
| apache-2.0 | 642fcbbe20e6e4f5edc25fe318571b53 | 48.026042 | 155 | 0.661638 | 4.676105 | false | false | false | false |
grozail/kovision | src/main/kotlin/ui/swing/frames/TestFrame.kt | 1 | 2301 | package ui.swing.frames
import ui.swing.panels.HoughCirclesSliderPanel
import ui.swing.panels.InRangeSliderPanel
import org.opencv.core.Mat
import org.opencv.imgproc.Imgproc
import ui.swing.components.CaptureComponent
import vision.*
import vision.imgproc.GaussianBlur
import vision.imgproc.drawHoughCircles
import java.awt.BorderLayout
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import javax.swing.JFrame
import kotlin.concurrent.thread
class TestFrame : JFrame("Test Frame") {
private val FRAME_WIDTH = 1920
private val FRAME_HEIGHT = 800
val leftVideoCapture = CaptureComponent()
val rightVideoCapture = CaptureComponent()
val sliderPanel = HoughCirclesSliderPanel()
val inRangePanel = InRangeSliderPanel()
private val exitListener = object : WindowAdapter() {
override fun windowClosing(e: WindowEvent?) {
Camera.release()
System.exit(0)
}
}
init {
addWindowListener(exitListener)
layout = BorderLayout()
setSize(FRAME_WIDTH, FRAME_HEIGHT)
add(leftVideoCapture, BorderLayout.WEST)
add(rightVideoCapture, BorderLayout.EAST)
add(inRangePanel, BorderLayout.CENTER)
isVisible = true
captureThread {
leftVideoCapture.apply {
image = Camera.getBufferedImage()
repaint()
}
Thread.sleep(50)
}
captureThread {
rightVideoCapture.apply {
val source = Mat()
Camera.currentFrame.copyTo(source)
inRangePanel.apply {
image = source.inRange().toBufferedImage()
}
repaint()
}
Thread.sleep(500)
}
}
fun startCustomCapture() {
thread {
while (true) {
val source = Mat()
Camera.currentFrame.copyTo(source)
sliderPanel.apply {
val circles = source.convertColor(Imgproc.COLOR_BGR2GRAY)
.GaussianBlur(3)
.HoughCircles()
println(separation)
rightVideoCapture.apply {
image = source.drawHoughCircles(circles).toBufferedImage()
repaint()
}
}
Thread.sleep(1000)
}
}
}
inline fun captureThread(crossinline block: () -> Unit) {
thread {
while (true) {
block()
}
}
}
fun main(args: Array<String>) {
}
} | mit | ba988b97d70184e452229c6b7dc56e76 | 24.296703 | 70 | 0.654933 | 4.222018 | false | false | false | false |
RocketChat/Rocket.Chat.Android.Lily | app/src/main/java/chat/rocket/android/profile/presentation/ProfilePresenter.kt | 2 | 7400 | package chat.rocket.android.profile.presentation
import android.graphics.Bitmap
import android.net.Uri
import chat.rocket.android.chatroom.domain.UriInteractor
import chat.rocket.android.core.behaviours.showMessage
import chat.rocket.android.core.lifecycle.CancelStrategy
import chat.rocket.android.helper.UserHelper
import chat.rocket.android.main.presentation.MainNavigator
import chat.rocket.android.server.domain.GetCurrentServerInteractor
import chat.rocket.android.server.domain.TokenRepository
import chat.rocket.android.server.infrastructure.RocketChatClientFactory
import chat.rocket.android.util.extension.compressImageAndGetByteArray
import chat.rocket.android.util.extension.launchUI
import chat.rocket.android.util.extensions.avatarUrl
import chat.rocket.android.util.retryIO
import chat.rocket.common.RocketChatException
import chat.rocket.common.model.UserStatus
import chat.rocket.common.util.ifNull
import chat.rocket.core.RocketChatClient
import chat.rocket.core.internal.realtime.setDefaultStatus
import chat.rocket.core.internal.rest.me
import chat.rocket.core.internal.rest.resetAvatar
import chat.rocket.core.internal.rest.setAvatar
import chat.rocket.core.internal.rest.updateProfile
import java.util.*
import javax.inject.Inject
import javax.inject.Named
class ProfilePresenter @Inject constructor(
private val view: ProfileView,
private val strategy: CancelStrategy,
private val navigator: MainNavigator,
private val uriInteractor: UriInteractor,
val userHelper: UserHelper,
serverInteractor: GetCurrentServerInteractor,
factory: RocketChatClientFactory,
tokenRepository: TokenRepository
) {
private val serverUrl = serverInteractor.get()!!
private val client: RocketChatClient = factory.get(serverUrl)
private val user = userHelper.user()
private val token = tokenRepository.get(serverUrl)
fun loadUserProfile() {
launchUI(strategy) {
view.showLoading()
try {
val me = retryIO(description = "me", times = 5) {
client.me()
}
view.showProfile(
me.status.toString(),
serverUrl.avatarUrl(me.username!!, token?.userId, token?.authToken),
me.name ?: "",
me.username ?: "",
me.emails?.getOrNull(0)?.address ?: ""
)
} catch (exception: RocketChatException) {
view.showMessage(exception)
} finally {
view.hideLoading()
}
}
}
fun updateUserProfile(email: String, name: String, username: String) {
launchUI(strategy) {
view.showLoading()
try {
user?.id?.let { id ->
retryIO {
client.updateProfile(
userId = id,
email = email,
name = name,
username = username
)
}
view.onProfileUpdatedSuccessfully(email, name, username)
view.showProfile(
user.status.toString(),
serverUrl.avatarUrl(user.username!!, token?.userId, token?.authToken),
name,
username,
email
)
}
} catch (exception: RocketChatException) {
exception.message?.let {
view.showMessage(it)
}.ifNull {
view.showGenericErrorMessage()
}
} finally {
view.hideLoading()
}
}
}
fun updateAvatar(uri: Uri) {
launchUI(strategy) {
view.showLoading()
try {
retryIO {
client.setAvatar(
uriInteractor.getFileName(uri) ?: uri.toString(),
uriInteractor.getMimeType(uri)
) {
uriInteractor.getInputStream(uri)
}
}
user?.username?.let {
view.reloadUserAvatar(
serverUrl.avatarUrl(
it,
token?.userId,
token?.authToken
)
)
}
} catch (exception: RocketChatException) {
exception.message?.let {
view.showMessage(it)
}.ifNull {
view.showGenericErrorMessage()
}
} finally {
view.hideLoading()
}
}
}
fun preparePhotoAndUpdateAvatar(bitmap: Bitmap) {
launchUI(strategy) {
view.showLoading()
try {
val byteArray = bitmap.compressImageAndGetByteArray("image/png")
retryIO {
client.setAvatar(
UUID.randomUUID().toString() + ".png",
"image/png"
) {
byteArray?.inputStream()
}
}
user?.username?.let {
view.reloadUserAvatar(
serverUrl.avatarUrl(
it,
token?.userId,
token?.authToken
)
)
}
} catch (exception: RocketChatException) {
exception.message?.let {
view.showMessage(it)
}.ifNull {
view.showGenericErrorMessage()
}
} finally {
view.hideLoading()
}
}
}
fun resetAvatar() {
launchUI(strategy) {
view.showLoading()
try {
user?.id?.let { id ->
retryIO { client.resetAvatar(id) }
}
user?.username?.let {
view.reloadUserAvatar(
serverUrl.avatarUrl(
it,
token?.userId,
token?.authToken
)
)
}
} catch (exception: RocketChatException) {
exception.message?.let {
view.showMessage(it)
}.ifNull {
view.showGenericErrorMessage()
}
} finally {
view.hideLoading()
}
}
}
fun updateStatus(status: UserStatus) {
launchUI(strategy) {
try {
client.setDefaultStatus(status)
} catch (exception: RocketChatException) {
exception.message?.let {
view.showMessage(it)
}.ifNull {
view.showGenericErrorMessage()
}
}
}
}
fun toProfileImage() = user?.username?.let { username ->
navigator.toProfileImage(serverUrl.avatarUrl(username, token?.userId, token?.authToken))
}
} | mit | 9f3d9ea15063fefa76e9d934f6564591 | 33.263889 | 96 | 0.495811 | 5.640244 | false | false | false | false |
exponent/exponent | packages/expo-dev-launcher/android/src/main/java/expo/modules/devlauncher/launcher/menu/DevLauncherMenuDelegate.kt | 2 | 2252 | package expo.modules.devlauncher.launcher.menu
import android.os.Bundle
import com.facebook.react.ReactInstanceManager
import expo.interfaces.devmenu.DevMenuDelegateInterface
import expo.modules.devlauncher.BuildConfig
import expo.modules.devlauncher.DevLauncherController
import expo.modules.devlauncher.launcher.DevLauncherControllerInterface
private class LauncherDelegate(private val controller: DevLauncherControllerInterface) : DevMenuDelegateInterface {
override fun appInfo(): Bundle = Bundle().apply {
putString("appName", "Development Client")
putString("appVersion", BuildConfig.VERSION)
putString("appIcon", null)
putString("hostUrl", null)
}
override fun reactInstanceManager(): ReactInstanceManager {
return controller.devClientHost.reactInstanceManager
}
override fun supportsDevelopment(): Boolean {
return false
}
}
private class AppDelegate(private val controller: DevLauncherControllerInterface) : DevMenuDelegateInterface {
override fun appInfo(): Bundle = Bundle().apply {
putString("appName", controller.manifest?.getName() ?: "Development Client - App")
putString("appVersion", controller.manifest?.getVersion())
putString("appIcon", null)
putString("hostUrl", controller.manifest?.getHostUri()
?: reactInstanceManager().devSupportManager?.sourceUrl)
}
override fun reactInstanceManager(): ReactInstanceManager {
return controller.appHost.reactInstanceManager
}
override fun supportsDevelopment(): Boolean {
return true
}
}
class DevLauncherMenuDelegate(private val controller: DevLauncherControllerInterface) : DevMenuDelegateInterface {
private val launcherDelegate = LauncherDelegate(controller)
private val appDelegate = AppDelegate(controller)
private val currentDelegate: DevMenuDelegateInterface
get() = if (controller.mode == DevLauncherController.Mode.LAUNCHER) {
launcherDelegate
} else {
appDelegate
}
override fun appInfo(): Bundle? {
return currentDelegate.appInfo()
}
override fun reactInstanceManager(): ReactInstanceManager {
return currentDelegate.reactInstanceManager()
}
override fun supportsDevelopment(): Boolean {
return currentDelegate.supportsDevelopment()
}
}
| bsd-3-clause | 802dad50b5eea7fa0c8773d79da2369b | 32.61194 | 115 | 0.774423 | 5.298824 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/crate/impl/CrateGraphServiceImpl.kt | 2 | 16486 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.crate.impl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.SimpleModificationTracker
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.VirtualFileWithId
import com.intellij.psi.util.CachedValue
import com.intellij.psi.util.CachedValueProvider
import com.intellij.util.CachedValueImpl
import com.intellij.util.containers.addIfNotNull
import gnu.trove.TIntObjectHashMap
import org.jetbrains.annotations.TestOnly
import org.rust.cargo.project.model.CargoProject
import org.rust.cargo.project.model.CargoProjectsService.CargoProjectsListener
import org.rust.cargo.project.model.CargoProjectsService.Companion.CARGO_PROJECTS_TOPIC
import org.rust.cargo.project.model.cargoProjects
import org.rust.cargo.project.workspace.CargoWorkspace
import org.rust.cargo.project.workspace.FeatureState
import org.rust.cargo.project.workspace.PackageOrigin
import org.rust.lang.core.crate.Crate
import org.rust.lang.core.crate.CrateGraphService
import org.rust.lang.core.crate.CratePersistentId
import org.rust.openapiext.checkReadAccessAllowed
import org.rust.openapiext.isUnitTestMode
import org.rust.stdext.applyWithSymlink
import org.rust.stdext.enumSetOf
import org.rust.stdext.exhaustive
import java.nio.file.Path
class CrateGraphServiceImpl(val project: Project) : CrateGraphService {
private val cargoProjectsModTracker = SimpleModificationTracker()
init {
project.messageBus.connect().subscribe(CARGO_PROJECTS_TOPIC, CargoProjectsListener { _, _ ->
cargoProjectsModTracker.incModificationCount()
})
}
private val crateGraphCachedValue: CachedValue<CrateGraph> = CachedValueImpl {
val result = buildCrateGraph(project.cargoProjects.allProjects)
CachedValueProvider.Result(result, cargoProjectsModTracker, VirtualFileManager.VFS_STRUCTURE_MODIFICATIONS)
}
private val crateGraph: CrateGraph
get() = crateGraphCachedValue.value
override val topSortedCrates: List<Crate>
get() {
checkReadAccessAllowed()
return crateGraph.topSortedCrates
}
override fun findCrateById(id: CratePersistentId): Crate? {
checkReadAccessAllowed()
return crateGraph.idToCrate.get(id)
}
override fun findCrateByRootMod(rootModFile: VirtualFile): Crate? {
checkReadAccessAllowed()
return rootModFile.applyWithSymlink { if (it is VirtualFileWithId) findCrateById(it.id) else null }
}
@TestOnly
fun hasUpToDateGraph(): Boolean = crateGraphCachedValue.hasUpToDateValue()
}
private data class CrateGraph(
val topSortedCrates: List<Crate>,
val idToCrate: TIntObjectHashMap<Crate>
)
private val LOG: Logger = logger<CrateGraphServiceImpl>()
private fun buildCrateGraph(cargoProjects: Collection<CargoProject>): CrateGraph {
val builder = CrateGraphBuilder()
for (cargoProject in cargoProjects) {
val workspace = cargoProject.workspace ?: continue
for (pkg in workspace.packages) {
try {
builder.lowerPackage(ProjectPackage(cargoProject, pkg))
} catch (e: CyclicGraphException) {
// This should not occur, but if it is, let's just log the exception instead of breaking everything
LOG.error(e)
}
}
}
return builder.build()
}
private class CrateGraphBuilder {
private val states = hashMapOf<Path, NodeState>()
private val topSortedCrates = mutableListOf<CargoBasedCrate>()
private val cratesToLowerLater = mutableListOf<NonLibraryCrates>()
private val cratesToReplaceTargetLater = mutableListOf<ReplaceProjectAndTarget>()
fun lowerPackage(pkg: ProjectPackage): CargoBasedCrate? {
when (val state = states[pkg.rootDirectory]) {
is NodeState.Done -> {
val libCrate = state.libCrate
if (state.pkgs.add(pkg.pkg)) {
// Duplicated package found. This can occur if a package is used in multiple CargoProjects.
// Merging them into a single crate
if (libCrate != null) {
libCrate.features = mergeFeatures(pkg.pkg.featureState, libCrate.features)
}
// Prefer workspace target
if (pkg.pkg.origin == PackageOrigin.WORKSPACE) {
cratesToReplaceTargetLater += ReplaceProjectAndTarget(state, pkg)
}
// It's possible that there are two packages, but only one of them has a valid proc macro artifact
if (pkg.pkg.procMacroArtifact != null) {
state.libCrate?.let { it.procMacroArtifact = pkg.pkg.procMacroArtifact }
}
}
return libCrate
}
NodeState.Processing -> throw CyclicGraphException(pkg.pkg.name)
else -> states[pkg.rootDirectory] = NodeState.Processing
}
val (buildDeps, normalAndNonCyclicDevDeps, cyclicDevDependencies) = lowerPackageDependencies(pkg)
val customBuildCrate = pkg.pkg.customBuildTarget?.let { target ->
CargoBasedCrate(pkg.project, target, buildDeps, buildDeps.flattenTopSortedDeps())
}
topSortedCrates.addIfNotNull(customBuildCrate)
val flatNormalAndNonCyclicDevDeps = normalAndNonCyclicDevDeps.flattenTopSortedDeps()
val libCrate = pkg.pkg.libTarget?.let { libTarget ->
CargoBasedCrate(
pkg.project,
libTarget,
normalAndNonCyclicDevDeps,
flatNormalAndNonCyclicDevDeps,
pkg.pkg.procMacroArtifact
)
}
val newState = NodeState.Done(libCrate)
newState.pkgs += pkg.pkg
newState.nonLibraryCrates.addIfNotNull(customBuildCrate)
states[pkg.rootDirectory] = newState
topSortedCrates.addIfNotNull(libCrate)
lowerNonLibraryCratesLater(
NonLibraryCrates(
pkg,
newState,
normalAndNonCyclicDevDeps,
cyclicDevDependencies,
flatNormalAndNonCyclicDevDeps
)
)
return libCrate
}
private class ReplaceProjectAndTarget(
val state: NodeState.Done,
val pkg: ProjectPackage
)
private fun ReplaceProjectAndTarget.replaceProjectAndTarget() {
val libCrate = state.libCrate
if (libCrate != null) {
pkg.pkg.libTarget?.let {
libCrate.cargoTarget = it
libCrate.cargoProject = pkg.project
}
}
for (crate in state.nonLibraryCrates) {
val newTarget = pkg.pkg.targets.find { it.name == crate.cargoTarget.name }
?: continue
crate.cargoTarget = newTarget
crate.cargoProject = pkg.project
}
}
private data class LoweredPackageDependencies(
val buildDeps: List<Crate.Dependency>,
val normalAndNonCyclicDevDeps: List<Crate.Dependency>,
val cyclicDevDependencies: List<CargoWorkspace.Dependency>
)
private fun lowerPackageDependencies(pkg: ProjectPackage): LoweredPackageDependencies {
return when (val dependencies = pkg.pkg.dependencies.classify()) {
is SplitDependencies.Classified -> {
val buildDeps = lowerDependencies(dependencies.build, pkg)
val normalDeps = lowerDependencies(dependencies.normal, pkg)
val (nonCyclicDevDeps, cyclicDevDependencies) = lowerDependenciesWithCycles(dependencies.dev, pkg)
val normalAndNonCyclicDevDeps = normalDeps + nonCyclicDevDeps
LoweredPackageDependencies(buildDeps, normalAndNonCyclicDevDeps, cyclicDevDependencies)
}
is SplitDependencies.Unclassified -> {
// Here we can't distinguish normal/dev/build dependencies because of old Cargo (prior to `1.41.0`).
//
val (lowered, cyclic) = lowerDependenciesWithCycles(dependencies.dependencies, pkg)
LoweredPackageDependencies(lowered, lowered, cyclic)
}
}
}
private sealed class SplitDependencies {
data class Classified(
val normal: Collection<CargoWorkspace.Dependency>,
val dev: Collection<CargoWorkspace.Dependency>,
val build: Collection<CargoWorkspace.Dependency>
) : SplitDependencies()
// For old Cargo versions prior to `1.41.0`
data class Unclassified(val dependencies: Collection<CargoWorkspace.Dependency>) : SplitDependencies()
}
private fun Collection<CargoWorkspace.Dependency>.classify(): SplitDependencies {
val unclassified = mutableListOf<CargoWorkspace.Dependency>()
val normal = mutableListOf<CargoWorkspace.Dependency>()
val dev = mutableSetOf<CargoWorkspace.Dependency>()
val build = mutableListOf<CargoWorkspace.Dependency>()
for (dependency in this) {
val visitedDepKinds = enumSetOf<CargoWorkspace.DepKind>()
for (depKind in dependency.depKinds) {
// `cargo metadata` sometimes duplicate `depKinds` for some reason
if (!visitedDepKinds.add(depKind.kind)) continue
when (depKind.kind) {
CargoWorkspace.DepKind.Stdlib -> {
normal += dependency
build += dependency
// No `dev += dependency` because all crates that use `dev` dependencies also use
// `normal` dependencies
}
CargoWorkspace.DepKind.Unclassified -> unclassified += dependency
CargoWorkspace.DepKind.Normal -> normal += dependency
CargoWorkspace.DepKind.Development -> dev += dependency
CargoWorkspace.DepKind.Build -> build += dependency
}.exhaustive
}
}
dev.removeAll(normal)
return if (unclassified.isNotEmpty()) {
// If these is at least one unclassified dependency, then we're on old Cargo and all dependencies
// are unclassified
SplitDependencies.Unclassified(unclassified + normal)
} else {
SplitDependencies.Classified(normal, dev, build)
}
}
private fun lowerDependencies(
deps: Iterable<CargoWorkspace.Dependency>,
pkg: ProjectPackage
): List<Crate.Dependency> {
return try {
deps.mapNotNull { dep ->
lowerPackage(ProjectPackage(pkg.project, dep.pkg))?.let { Crate.Dependency(dep.name, it) }
}
} catch (e: CyclicGraphException) {
states.remove(pkg.rootDirectory)
e.pushCrate(pkg.pkg.name)
throw e
}
}
private data class LoweredAndCyclicDependencies(
val lowered: List<Crate.Dependency>,
val cyclic: List<CargoWorkspace.Dependency>
)
private fun lowerDependenciesWithCycles(
devDependencies: Collection<CargoWorkspace.Dependency>,
pkg: ProjectPackage
): LoweredAndCyclicDependencies {
val cyclic = mutableListOf<CargoWorkspace.Dependency>()
val lowered = devDependencies.mapNotNull { dep ->
try {
lowerPackage(ProjectPackage(pkg.project, dep.pkg))?.let { Crate.Dependency(dep.name, it) }
} catch (ignored: CyclicGraphException) {
// This can occur because `dev-dependencies` can cyclic depends on this package
CrateGraphTestmarks.CyclicDevDependency.hit()
cyclic += dep
null
}
}
return LoweredAndCyclicDependencies(lowered, cyclic)
}
private fun lowerNonLibraryCratesLater(ctx: NonLibraryCrates) {
if (ctx.cyclicDevDependencies.isEmpty()) {
ctx.lowerNonLibraryCrates()
} else {
cratesToLowerLater += ctx
}
}
private class NonLibraryCrates(
val pkg: ProjectPackage,
val doneState: NodeState.Done,
val normalAndNonCyclicTestDeps: List<Crate.Dependency>,
val cyclicDevDependencies: List<CargoWorkspace.Dependency>,
val flatNormalAndNonCyclicDevDeps: LinkedHashSet<Crate>
)
private fun NonLibraryCrates.lowerNonLibraryCrates() {
val cyclicDevDeps = lowerDependencies(cyclicDevDependencies, pkg)
val normalAndTestDeps = normalAndNonCyclicTestDeps + cyclicDevDeps
val libCrate = doneState.libCrate
val (depsWithLib, flatDepsWithLib) = if (libCrate != null) {
val libDep = Crate.Dependency(libCrate.normName, libCrate)
val flatDeps = LinkedHashSet<Crate>(flatNormalAndNonCyclicDevDeps)
flatDeps += cyclicDevDeps.flattenTopSortedDeps()
flatDeps += libCrate
Pair(normalAndTestDeps + libDep, flatDeps)
} else {
normalAndTestDeps to flatNormalAndNonCyclicDevDeps
}
val nonLibraryCrates = pkg.pkg.targets.mapNotNull { target ->
if (target.kind.isLib || target.kind == CargoWorkspace.TargetKind.CustomBuild) return@mapNotNull null
CargoBasedCrate(pkg.project, target, depsWithLib, flatDepsWithLib)
}
doneState.nonLibraryCrates += nonLibraryCrates
topSortedCrates += nonLibraryCrates
if (cyclicDevDeps.isNotEmpty()) {
libCrate?.cyclicDevDeps = cyclicDevDeps
}
}
fun build(): CrateGraph {
for (ctx in cratesToLowerLater) {
ctx.lowerNonLibraryCrates()
}
for (ctx in cratesToReplaceTargetLater) {
ctx.replaceProjectAndTarget()
}
topSortedCrates.assertTopSorted()
val idToCrate = TIntObjectHashMap<Crate>()
for (crate in topSortedCrates) {
crate.checkInvariants()
val id = crate.id
if (id != null) {
idToCrate.put(id, crate)
}
}
return CrateGraph(topSortedCrates, idToCrate)
}
}
private fun Crate.checkInvariants() {
if (!isUnitTestMode) return
flatDependencies.assertTopSorted()
for (dep in dependencies) {
check(dep.crate in flatDependencies) {
"Error in structure of crate `$this`: no `${dep.crate}`" +
" dependency in flatDependencies: $flatDependencies"
}
}
}
private fun Iterable<Crate>.assertTopSorted() {
if (!isUnitTestMode) return
val set = hashSetOf<Crate>()
for (crate in this) {
check(crate.dependencies.all { it.crate in set })
set += crate
}
}
private fun mergeFeatures(
features1: Map<String, FeatureState>,
features2: Map<String, FeatureState>
): Map<String, FeatureState> {
val featureMap = features1.toMutableMap()
for ((k, v) in features2) {
featureMap.merge(k, v) { v1, v2 ->
when {
v1 == FeatureState.Enabled -> FeatureState.Enabled
v2 == FeatureState.Enabled -> FeatureState.Enabled
else -> FeatureState.Disabled
}
}
}
return featureMap
}
private data class ProjectPackage(
val project: CargoProject,
val pkg: CargoWorkspace.Package,
// Extracted to a field due to performance reasons
val rootDirectory: Path = pkg.rootDirectory
)
private sealed class NodeState {
data class Done(
val libCrate: CargoBasedCrate?,
val nonLibraryCrates: MutableList<CargoBasedCrate> = mutableListOf(),
val pkgs: MutableSet<CargoWorkspace.Package> = hashSetOf()
) : NodeState()
object Processing : NodeState()
}
private class CyclicGraphException(crateName: String) : RuntimeException("Cyclic graph detected") {
private val stack: MutableList<String> = mutableListOf(crateName)
fun pushCrate(crateName: String) {
stack += crateName
}
override val message: String
get() = super.message + stack.asReversed().joinToString(prefix = " (", separator = " -> ", postfix = ")")
}
| mit | 2b697bc143cf19f305d29020b7854709 | 36.38322 | 118 | 0.64946 | 4.844549 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/os/unix/UnixConsoleManager.kt | 1 | 2707 | /*
Copyright 2017-2020 Charles Korn.
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 batect.os.unix
import batect.logging.Logger
import batect.os.ConsoleManager
import batect.os.ProcessRunner
import batect.ui.ConsoleInfo
class UnixConsoleManager(
private val consoleInfo: ConsoleInfo,
private val processRunner: ProcessRunner,
private val logger: Logger
) : ConsoleManager {
override fun enableConsoleEscapeSequences() {
// Nothing to do on Linux or OS X.
}
override fun enterRawMode(): AutoCloseable {
if (!consoleInfo.stdinIsTTY) {
logger.info {
message("Terminal is not a TTY, won't enter raw mode.")
}
return AutoCloseable { }
}
val existingState = getExistingTerminalState()
startRawMode()
return TerminalStateRestorer(existingState, processRunner)
}
private fun getExistingTerminalState(): String {
val output = processRunner.runWithStdinAttached(listOf("stty", "-g"))
if (output.exitCode != 0) {
throw RuntimeException("Invoking 'stty -g' failed with exit code ${output.exitCode}: ${output.output.trim()}")
}
return output.output.trim()
}
private fun startRawMode() {
val command = listOf("stty", "-ignbrk", "-brkint", "-parmrk", "-istrip", "-inlcr", "-igncr", "-icrnl", "-ixon", "-opost", "-echo", "-echonl",
"-icanon", "-isig", "-iexten", "-parenb", "cs8", "min", "1", "time", "0")
val output = processRunner.runWithStdinAttached(command)
if (output.exitCode != 0) {
throw RuntimeException("Invoking '${command.joinToString(" ")}' failed with exit code ${output.exitCode}: ${output.output.trim()}")
}
}
}
data class TerminalStateRestorer(private val oldState: String, private val processRunner: ProcessRunner) : AutoCloseable {
override fun close() {
val output = processRunner.runWithStdinAttached(listOf("stty", oldState))
if (output.exitCode != 0) {
throw RuntimeException("Invoking 'stty $oldState' failed with exit code ${output.exitCode}: ${output.output.trim()}")
}
}
}
| apache-2.0 | e85c65fb54bfd567eecd348486d0cd67 | 33.705128 | 149 | 0.659402 | 4.262992 | false | false | false | false |
android/identity-samples | Fido2/app/src/main/java/com/google/android/gms/identity/sample/fido2/ui/username/UsernameFragment.kt | 1 | 2297 | /*
* Copyright 2021 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.gms.identity.sample.fido2.ui.username
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.google.android.gms.identity.sample.fido2.databinding.UsernameFragmentBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
@AndroidEntryPoint
class UsernameFragment : Fragment() {
private val viewModel: UsernameViewModel by viewModels()
private lateinit var binding: UsernameFragmentBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = UsernameFragmentBinding.inflate(inflater, container, false)
binding.lifecycleOwner = viewLifecycleOwner
binding.viewModel = viewModel
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
viewModel.sending.collect { sending ->
if (sending) {
binding.sending.show()
} else {
binding.sending.hide()
}
}
}
binding.inputUsername.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_NEXT) {
viewModel.sendUsername()
true
} else {
false
}
}
}
}
| apache-2.0 | 8b369e11dba0f17154890c13e7796ef4 | 32.779412 | 87 | 0.688289 | 4.929185 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/font/FontVariation.kt | 3 | 12525 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.font
import androidx.compose.runtime.Immutable
import androidx.compose.ui.text.ExperimentalTextApi
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.util.fastAny
/**
* Set font variation settings.
*
* To learn more about the font variation settings, see the list supported by
* [fonts.google.com](https://fonts.google.com/variablefonts#axis-definitions).
*/
@ExperimentalTextApi
object FontVariation {
/**
* A collection of settings to apply to a single font.
*
* Settings must be unique on [Setting.axisName]
*/
@Immutable
class Settings(vararg settings: Setting) {
/**
* All settings, unique by [FontVariation.Setting.axisName]
*/
val settings: List<Setting>
/**
* True if density is required to resolve any of these settings
*
* If false, density will not affect the result of any [Setting.toVariationValue].
*/
internal val needsDensity: Boolean
init {
this.settings = ArrayList(settings
.groupBy { it.axisName }
.flatMap { (key, value) ->
require(value.size == 1) {
"'$key' must be unique. Actual [ [${value.joinToString()}]"
}
value
})
needsDensity = this.settings.fastAny { it.needsDensity }
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Settings) return false
if (settings != other.settings) return false
return true
}
override fun hashCode(): Int {
return settings.hashCode()
}
}
/**
* Represents a single point in a variation, such as 0.7 or 100
*/
@Immutable
sealed interface Setting {
/**
* Convert a value to a final value for use as a font variation setting.
*
* If [needsDensity] is false, density may be null
*
* @param density to resolve from Compose types to feature-specific ranges.
*/
fun toVariationValue(density: Density?): Float
/**
* True if this setting requires density to resolve
*
* When false, may toVariationValue may be called with null or any Density
*/
val needsDensity: Boolean
/**
* The font variation axis, such as 'wdth' or 'ital'
*/
val axisName: String
}
@Immutable
private class SettingFloat(
override val axisName: String,
val value: Float
) : Setting {
override fun toVariationValue(density: Density?): Float = value
override val needsDensity: Boolean = false
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is SettingFloat) return false
if (axisName != other.axisName) return false
if (value != other.value) return false
return true
}
override fun hashCode(): Int {
var result = axisName.hashCode()
result = 31 * result + value.hashCode()
return result
}
override fun toString(): String {
return "FontVariation.Setting(axisName='$axisName', value=$value)"
}
}
@Immutable
private class SettingTextUnit(
override val axisName: String,
val value: TextUnit
) : Setting {
override fun toVariationValue(density: Density?): Float {
// we don't care about pixel density as 12sp is the same "visual" size on all devices
// instead we only care about font scaling, which changes visual size
requireNotNull(density) { "density must not be null" }
return value.value * density.fontScale
}
override val needsDensity: Boolean = true
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is SettingTextUnit) return false
if (axisName != other.axisName) return false
if (value != other.value) return false
return true
}
override fun hashCode(): Int {
var result = axisName.hashCode()
result = 31 * result + value.hashCode()
return result
}
override fun toString(): String {
return "FontVariation.Setting(axisName='$axisName', value=$value)"
}
}
@Immutable
private class SettingInt(
override val axisName: String,
val value: Int
) : Setting {
override fun toVariationValue(density: Density?): Float = value.toFloat()
override val needsDensity: Boolean = false
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is SettingInt) return false
if (axisName != other.axisName) return false
if (value != other.value) return false
return true
}
override fun hashCode(): Int {
var result = axisName.hashCode()
result = 31 * result + value
return result
}
override fun toString(): String {
return "FontVariation.Setting(axisName='$axisName', value=$value)"
}
}
/**
* Create a font variation setting for any axis supported by a font.
*
* ```
* val setting = FontVariation.Setting('wght', 400f);
* ```
*
* You should typically not use this in app-code directly, instead define a method for each
* setting supported by your app/font.
*
* If you had a setting `fzzt` that set a variation setting called fizzable between 1 and 11,
* define a function like this:
*
* ```
* fun FontVariation.fizzable(fiz: Int): FontVariation.Setting {
* require(fiz in 1..11) { "'fzzt' must be in 1..11" }
* return Setting("fzzt", fiz.toFloat())
* ```
*
* @param name axis name, must be 4 characters
* @param value value for axis, not validated and directly passed to font
*/
fun Setting(name: String, value: Float): Setting {
require(name.length == 4) {
"Name must be exactly four characters. Actual: '$name'"
}
return SettingFloat(name, value)
}
/**
* Italic or upright, equivalent to [FontStyle]
*
* 'ital', 0.0f is upright, and 1.0f is italic.
*
* A platform _may_ provide automatic setting of `ital` on font load. When supported, `ital` is
* automatically applied based on [FontStyle] if platform and the loaded font support 'ital'.
*
* Automatic mapping is done via [Settings]\([FontWeight], [FontStyle]\)
*
* To override this behavior provide an explicit FontVariation.italic to a [Font] that supports
* variation settings.
*
* @param value [0.0f, 1.0f]
*/
fun italic(value: Float): Setting {
require(value in 0.0f..1.0f) {
"'ital' must be in 0.0f..1.0f. Actual: $value"
}
return SettingFloat("ital", value)
}
/**
* Optical size is how "big" a font appears to the eye.
*
* It should be set by a ratio from a font size.
*
* Adapt the style to specific text sizes. At smaller sizes, letters typically become optimized
* for more legibility. At larger sizes, optimized for headlines, with more extreme weights and
* widths.
*
* A Platform _may_ choose to support automatic optical sizing. When present, this will set the
* optical size based on the font size.
*
* To override this behavior provide an explicit FontVariation.opticalSizing to a [Font] that
* supports variation settings.
*
* @param textSize font-size at the expected display, must be in sp
*/
fun opticalSizing(textSize: TextUnit): Setting {
require(textSize.isSp) {
"'opsz' must be provided in sp units"
}
return SettingTextUnit("opsz", textSize)
}
/**
* Adjust the style from upright to slanted, also known to typographers as an 'oblique' style.
*
* Rarely, slant can work in the other direction, called a 'backslanted' or 'reverse oblique'
* style.
*
* 'slnt', values as an angle, 0f is upright.
*
* @param value -90f to 90f, represents an angle
*/
fun slant(value: Float): Setting {
require(value in -90f..90f) {
"'slnt' must be in -90f..90f. Actual: $value"
}
return SettingFloat("slnt", value)
}
/**
* Width of the type.
*
* Adjust the style from narrower to wider, by varying the proportions of counters, strokes,
* spacing and kerning, and other aspects of the type. This typically changes the typographic
* color in a subtle way, and so may be used in conjunction with Width and Grade axes.
*
* 'wdth', such as 10f
*
* @param value > 0.0f represents the width
*/
fun width(value: Float): Setting {
require(value > 0.0f) {
"'wdth' must be strictly > 0.0f. Actual: $value"
}
return SettingFloat("wdth", value)
}
/**
* Weight, equivalent to [FontWeight]
*
* Setting weight always causes visual text reflow, to make text "bolder" or "thinner" without
* reflow see [grade]
*
* Adjust the style from lighter to bolder in typographic color, by varying stroke weights,
* spacing and kerning, and other aspects of the type. This typically changes overall width,
* and so may be used in conjunction with Width and Grade axes.
*
* This is equivalent to [FontWeight], and platforms _may_ support automatically setting 'wghts'
* from [FontWeight] during font load.
*
* Setting this does not change [FontWeight]. If an explicit value and [FontWeight] disagree,
* the weight specified by `wght` will be shown if the font supports it.
*
* Automatic mapping is done via [Settings]\([FontWeight], [FontStyle]\)
*
* @param value weight, in 1..1000
*/
fun weight(value: Int): Setting {
require(value in 1..1000) {
"'wght' value must be in [1, 1000]. Actual: $value"
}
return SettingInt("wght", value)
}
/**
* Change visual weight of text without text reflow.
*
* Finesse the style from lighter to bolder in typographic color, without any changes overall
* width, line breaks or page layout. Negative grade makes the style lighter, while positive
* grade makes it bolder. The units are the same as in the Weight axis.
*
* Visual appearance of text with weight and grade set is similar to text with
*
* ```
* weight = (weight + grade)
* ```
*
* @param value grade, in -1000..1000
*/
fun grade(value: Int): Setting {
require(value in -1000..1000) {
"'GRAD' must be in -1000..1000"
}
return SettingInt("GRAD", value)
}
/**
* Variation settings to configure a font with [FontWeight] and [FontStyle]
*
* @param weight to set 'wght' with [weight]\([FontWeight.weight])
* @param style to set 'ital' with [italic]\([FontStyle.value])
* @param settings other settings to apply, must not contain 'wght' or 'ital'
* @return settings that configure [FontWeight] and [FontStyle] on a font that supports
* 'wght' and 'ital'
*/
fun Settings(
weight: FontWeight,
style: FontStyle,
vararg settings: Setting
): Settings {
return Settings(weight(weight.weight), italic(style.value.toFloat()), *settings)
}
} | apache-2.0 | 9a089ca3dff481837a92ff950f7485a1 | 32.491979 | 100 | 0.602954 | 4.365633 | false | false | false | false |
djkovrik/YapTalker | app/src/main/java/com/sedsoftware/yaptalker/presentation/delegate/LinkBrowserDelegate.kt | 1 | 3148 | package com.sedsoftware.yaptalker.presentation.delegate
import android.content.Context
import com.sedsoftware.yaptalker.domain.device.Settings
import com.sedsoftware.yaptalker.domain.interactor.VideoTokenInteractor
import com.sedsoftware.yaptalker.presentation.base.enums.navigation.NavigationScreen
import com.sedsoftware.yaptalker.presentation.extensions.extractYoutubeVideoId
import com.sedsoftware.yaptalker.presentation.extensions.validateUrl
import com.sedsoftware.yaptalker.presentation.feature.topic.GalleryInitialState
import io.reactivex.Single
import org.jetbrains.anko.browse
import ru.terrakok.cicerone.Router
import javax.inject.Inject
class LinkBrowserDelegate @Inject constructor(
private val router: Router,
private val tokenInteractor: VideoTokenInteractor,
private val settings: Settings,
context: Context?
) {
private val weakContext: Context? by weak(context)
fun browse(
url: String,
directUrl: String,
type: String,
html: String,
isVideo: Boolean,
state: GalleryInitialState? = null
) {
when {
isVideo && url.contains("youtube") -> {
val videoId = url.extractYoutubeVideoId()
weakContext?.browse("http://www.youtube.com/watch?v=$videoId")
}
isVideo && url.contains("coub") && settings.isExternalCoubPlayer() -> {
weakContext?.browse(url.validateUrl())
}
isVideo && settings.isExternalYapPlayer() && type == "YapFiles" -> {
weakContext?.browse(directUrl.validateUrl())
}
isVideo && !url.contains("youtube") -> {
router.navigateTo(NavigationScreen.VIDEO_DISPLAY_SCREEN, html)
}
state != null -> {
router.navigateTo(NavigationScreen.TOPIC_GALLERY, state)
}
else -> {
router.navigateTo(NavigationScreen.IMAGE_DISPLAY_SCREEN, url)
}
}
}
fun checkVideoLink(directUrl: String): Single<String> =
if (directUrl.contains("yapfiles.ru") && settings.isExternalYapPlayer()) {
when {
directUrl.contains("token") ->
tokenInteractor.getVideoToken(directUrl).map { token ->
val mainId = directUrl.substringAfter("files/").substringBefore("/")
val videoId = directUrl.substringAfterLast("/").substringBefore(".mp4")
"http://www.yapfiles.ru/files/$mainId/$videoId.mp4?token=$token"
}
directUrl.contains(".html") ->
tokenInteractor.getVideoToken(directUrl).map { token ->
val mainId = directUrl.substringAfter("show/").substringBefore("/")
val videoId = directUrl.substringAfterLast("/").substringBefore(".mp4")
"http://www.yapfiles.ru/files/$mainId/$videoId.mp4?token=$token"
}
else -> Single.just(directUrl)
}
} else {
Single.just(directUrl)
}
}
| apache-2.0 | a57118c4045e7047ccd8ccf656412979 | 38.848101 | 95 | 0.610229 | 4.806107 | false | false | false | false |
androidx/androidx | room/room-compiler-processing/src/main/java/androidx/room/compiler/codegen/PoetExt.kt | 3 | 1497 | /*
* 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.room.compiler.codegen
typealias JCodeBlock = com.squareup.javapoet.CodeBlock
typealias JCodeBlockBuilder = com.squareup.javapoet.CodeBlock.Builder
typealias JAnnotationSpecBuilder = com.squareup.javapoet.AnnotationSpec.Builder
typealias JTypeSpecBuilder = com.squareup.javapoet.TypeSpec.Builder
typealias KCodeBlock = com.squareup.kotlinpoet.CodeBlock
typealias KCodeBlockBuilder = com.squareup.kotlinpoet.CodeBlock.Builder
typealias KAnnotationSpecBuilder = com.squareup.kotlinpoet.AnnotationSpec.Builder
typealias KTypeSpecBuilder = com.squareup.kotlinpoet.TypeSpec.Builder
typealias KMemberName = com.squareup.kotlinpoet.MemberName
typealias JArrayTypeName = com.squareup.javapoet.ArrayTypeName
// TODO(b/127483380): Recycle to room-compiler?
internal val L = "\$L"
internal val T = "\$T"
internal val N = "\$N"
internal val S = "\$S"
internal val W = "\$W"
| apache-2.0 | 17825e2b8949c148637201a074ace8b4 | 41.771429 | 81 | 0.788243 | 4.289398 | false | false | false | false |
nrizzio/Signal-Android | app/src/androidTest/java/org/thoughtcrime/securesms/database/RecipientDatabaseTest_processPnpTupleToChangeSet.kt | 1 | 21887 | package org.thoughtcrime.securesms.database
import androidx.core.content.contentValuesOf
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.testing.SignalDatabaseRule
import org.thoughtcrime.securesms.util.Util
import org.whispersystems.signalservice.api.push.ACI
import org.whispersystems.signalservice.api.push.PNI
import org.whispersystems.signalservice.api.push.ServiceId
import java.lang.AssertionError
import java.lang.IllegalStateException
import java.util.UUID
@RunWith(AndroidJUnit4::class)
class RecipientDatabaseTest_processPnpTupleToChangeSet {
@Rule
@JvmField
val databaseRule = SignalDatabaseRule(deleteAllThreadsOnEachRun = false)
private lateinit var db: RecipientDatabase
@Before
fun setup() {
db = SignalDatabase.recipients
}
@Test
fun noMatch_e164Only() {
val changeSet = db.processPnpTupleToChangeSet(E164_A, null, null, pniVerified = false)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpInsert(E164_A, null, null)
),
changeSet
)
}
@Test
fun noMatch_e164AndPni() {
val changeSet = db.processPnpTupleToChangeSet(E164_A, PNI_A, null, pniVerified = false)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpInsert(E164_A, PNI_A, null)
),
changeSet
)
}
@Test
fun noMatch_aciOnly() {
val changeSet = db.processPnpTupleToChangeSet(null, null, ACI_A, pniVerified = false)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpInsert(null, null, ACI_A)
),
changeSet
)
}
@Test(expected = IllegalStateException::class)
fun noMatch_noData() {
db.processPnpTupleToChangeSet(null, null, null, pniVerified = false)
}
@Test
fun noMatch_allFields() {
val changeSet = db.processPnpTupleToChangeSet(E164_A, PNI_A, ACI_A, pniVerified = false)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpInsert(E164_A, PNI_A, ACI_A)
),
changeSet
)
}
@Test
fun fullMatch() {
val result = applyAndAssert(
Input(E164_A, PNI_A, ACI_A),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.id)
),
result.changeSet
)
}
@Test
fun onlyE164Matches() {
val result = applyAndAssert(
Input(E164_A, null, null),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.id),
operations = listOf(
PnpOperation.SetPni(result.id, PNI_A),
PnpOperation.SetAci(result.id, ACI_A)
)
),
result.changeSet
)
}
@Test
fun onlyE164Matches_pniChanges_noAciProvided_existingPniSession() {
val result = applyAndAssert(
Input(E164_A, PNI_B, null, pniSession = true),
Update(E164_A, PNI_A, null),
Output(E164_A, PNI_A, null)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.id),
operations = listOf(
PnpOperation.SetPni(result.id, PNI_A),
PnpOperation.SessionSwitchoverInsert(result.id)
)
),
result.changeSet
)
}
@Test
fun onlyE164Matches_pniChanges_noAciProvided_noPniSession() {
val result = applyAndAssert(
Input(E164_A, PNI_B, null),
Update(E164_A, PNI_A, null),
Output(E164_A, PNI_A, null)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.id),
operations = listOf(
PnpOperation.SetPni(result.id, PNI_A)
)
),
result.changeSet
)
}
@Test
fun e164AndPniMatches_noExistingSession() {
val result = applyAndAssert(
Input(E164_A, PNI_A, null),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.id),
operations = listOf(
PnpOperation.SetAci(result.id, ACI_A)
)
),
result.changeSet
)
}
@Test
fun e164AndPniMatches_existingPniSession() {
val result = applyAndAssert(
Input(E164_A, PNI_A, null, pniSession = true),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.id),
operations = listOf(
PnpOperation.SetAci(result.id, ACI_A),
PnpOperation.SessionSwitchoverInsert(result.id)
)
),
result.changeSet
)
}
@Test
fun e164AndAciMatches() {
val result = applyAndAssert(
Input(E164_A, null, ACI_A),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.id),
operations = listOf(
PnpOperation.SetPni(result.id, PNI_A)
)
),
result.changeSet
)
}
@Test
fun onlyPniMatches_noExistingSession() {
val result = applyAndAssert(
Input(null, PNI_A, null),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.id),
operations = listOf(
PnpOperation.SetE164(result.id, E164_A),
PnpOperation.SetAci(result.id, ACI_A)
)
),
result.changeSet
)
}
@Test
fun onlyPniMatches_existingPniSession() {
val result = applyAndAssert(
Input(null, PNI_A, null, pniSession = true),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.id),
operations = listOf(
PnpOperation.SetE164(result.id, E164_A),
PnpOperation.SetAci(result.id, ACI_A),
PnpOperation.SessionSwitchoverInsert(result.id)
)
),
result.changeSet
)
}
@Test
fun onlyPniMatches_existingPniSession_changeNumber() {
val result = applyAndAssert(
Input(E164_B, PNI_A, null, pniSession = true),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.id),
operations = listOf(
PnpOperation.SetE164(result.id, E164_A),
PnpOperation.SetAci(result.id, ACI_A),
PnpOperation.ChangeNumberInsert(
recipientId = result.id,
oldE164 = E164_B,
newE164 = E164_A
),
PnpOperation.SessionSwitchoverInsert(result.id)
)
),
result.changeSet
)
}
@Test
fun pniAndAciMatches() {
val result = applyAndAssert(
Input(null, PNI_A, ACI_A),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.id),
operations = listOf(
PnpOperation.SetE164(result.id, E164_A),
)
),
result.changeSet
)
}
@Test
fun pniAndAciMatches_changeNumber() {
val result = applyAndAssert(
Input(E164_B, PNI_A, ACI_A),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.id),
operations = listOf(
PnpOperation.SetE164(result.id, E164_A),
PnpOperation.ChangeNumberInsert(
recipientId = result.id,
oldE164 = E164_B,
newE164 = E164_A
)
)
),
result.changeSet
)
}
@Test
fun onlyAciMatches() {
val result = applyAndAssert(
Input(null, null, ACI_A),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.id),
operations = listOf(
PnpOperation.SetE164(result.id, E164_A),
PnpOperation.SetPni(result.id, PNI_A)
)
),
result.changeSet
)
}
@Test
fun onlyAciMatches_changeNumber() {
val result = applyAndAssert(
Input(E164_B, null, ACI_A),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.id),
operations = listOf(
PnpOperation.SetE164(result.id, E164_A),
PnpOperation.SetPni(result.id, PNI_A),
PnpOperation.ChangeNumberInsert(
recipientId = result.id,
oldE164 = E164_B,
newE164 = E164_A
)
)
),
result.changeSet
)
}
@Test
fun merge_e164Only_pniOnly_aciOnly() {
val result = applyAndAssert(
listOf(
Input(E164_A, null, null),
Input(null, PNI_A, null),
Input(null, null, ACI_A)
),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.thirdId),
operations = listOf(
PnpOperation.Merge(
primaryId = result.firstId,
secondaryId = result.secondId
),
PnpOperation.Merge(
primaryId = result.thirdId,
secondaryId = result.firstId
)
)
),
result.changeSet
)
}
@Test
fun merge_e164Only_pniOnly_noAciProvided() {
val result = applyAndAssert(
listOf(
Input(E164_A, null, null),
Input(null, PNI_A, null),
),
Update(E164_A, PNI_A, null),
Output(E164_A, PNI_A, null)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.firstId),
operations = listOf(
PnpOperation.Merge(
primaryId = result.firstId,
secondaryId = result.secondId
)
)
),
result.changeSet
)
}
@Test
fun merge_e164Only_pniOnly_aciProvidedButNoAciRecord() {
val result = applyAndAssert(
listOf(
Input(E164_A, null, null),
Input(null, PNI_A, null),
),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.firstId),
operations = listOf(
PnpOperation.Merge(
primaryId = result.firstId,
secondaryId = result.secondId
),
PnpOperation.SetAci(
recipientId = result.firstId,
aci = ACI_A
)
)
),
result.changeSet
)
}
@Test
fun merge_e164Only_pniAndE164_noAciProvided() {
val result = applyAndAssert(
listOf(
Input(E164_A, null, null),
Input(E164_B, PNI_A, null),
),
Update(E164_A, PNI_A, null),
Output(E164_A, PNI_A, null)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.firstId),
operations = listOf(
PnpOperation.RemovePni(result.secondId),
PnpOperation.SetPni(
recipientId = result.firstId,
pni = PNI_A
),
)
),
result.changeSet
)
}
@Test
fun merge_e164AndPni_pniOnly_noAciProvided() {
val result = applyAndAssert(
listOf(
Input(E164_A, PNI_B, null),
Input(null, PNI_A, null),
),
Update(E164_A, PNI_A, null),
Output(E164_A, PNI_A, null)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.firstId),
operations = listOf(
PnpOperation.RemovePni(result.firstId),
PnpOperation.Merge(
primaryId = result.firstId,
secondaryId = result.secondId
),
)
),
result.changeSet
)
}
@Test
fun merge_e164AndPni_e164AndPni_noAciProvided_noSessions() {
val result = applyAndAssert(
listOf(
Input(E164_A, PNI_B, null),
Input(E164_B, PNI_A, null),
),
Update(E164_A, PNI_A, null),
Output(E164_A, PNI_A, null)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.firstId),
operations = listOf(
PnpOperation.RemovePni(result.secondId),
PnpOperation.SetPni(result.firstId, PNI_A)
)
),
result.changeSet
)
}
@Test
fun merge_e164AndPni_e164AndPni_noAciProvided_sessionsExist() {
val result = applyAndAssert(
listOf(
Input(E164_A, PNI_B, null, pniSession = true),
Input(E164_B, PNI_A, null, pniSession = true),
),
Update(E164_A, PNI_A, null),
Output(E164_A, PNI_A, null)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.firstId),
operations = listOf(
PnpOperation.RemovePni(result.secondId),
PnpOperation.SetPni(result.firstId, PNI_A),
PnpOperation.SessionSwitchoverInsert(result.secondId),
PnpOperation.SessionSwitchoverInsert(result.firstId)
)
),
result.changeSet
)
}
@Test
fun merge_e164AndPni_aciOnly() {
val result = applyAndAssert(
listOf(
Input(E164_A, PNI_A, null),
Input(null, null, ACI_A),
),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.secondId),
operations = listOf(
PnpOperation.Merge(
primaryId = result.secondId,
secondaryId = result.firstId
),
)
),
result.changeSet
)
}
@Test
fun merge_e164AndPni_aciOnly_e164RecordHasSeparateE164() {
val result = applyAndAssert(
listOf(
Input(E164_B, PNI_A, null),
Input(null, null, ACI_A),
),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.secondId),
operations = listOf(
PnpOperation.RemovePni(result.firstId),
PnpOperation.SetPni(
recipientId = result.secondId,
pni = PNI_A,
),
PnpOperation.SetE164(
recipientId = result.secondId,
e164 = E164_A,
)
)
),
result.changeSet
)
}
@Test
fun merge_e164AndPni_aciOnly_e164RecordHasSeparateE164_changeNumber() {
val result = applyAndAssert(
listOf(
Input(E164_B, PNI_A, null),
Input(E164_C, null, ACI_A),
),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.secondId),
operations = listOf(
PnpOperation.RemovePni(result.firstId),
PnpOperation.SetPni(
recipientId = result.secondId,
pni = PNI_A,
),
PnpOperation.SetE164(
recipientId = result.secondId,
e164 = E164_A,
),
PnpOperation.ChangeNumberInsert(
recipientId = result.secondId,
oldE164 = E164_C,
newE164 = E164_A
)
)
),
result.changeSet
)
}
@Test
fun merge_e164AndPni_e164AndPniAndAci_changeNumber() {
val result = applyAndAssert(
listOf(
Input(E164_A, PNI_A, null),
Input(E164_B, PNI_B, ACI_A),
),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.secondId),
operations = listOf(
PnpOperation.RemovePni(result.secondId),
PnpOperation.RemoveE164(result.secondId),
PnpOperation.Merge(
primaryId = result.secondId,
secondaryId = result.firstId
),
PnpOperation.ChangeNumberInsert(
recipientId = result.secondId,
oldE164 = E164_B,
newE164 = E164_A
)
)
),
result.changeSet
)
}
@Test
fun merge_e164AndPni_e164Aci_changeNumber() {
val result = applyAndAssert(
listOf(
Input(E164_A, PNI_A, null),
Input(E164_B, null, ACI_A),
),
Update(E164_A, PNI_A, ACI_A),
Output(E164_A, PNI_A, ACI_A)
)
assertEquals(
PnpChangeSet(
id = PnpIdResolver.PnpNoopId(result.secondId),
operations = listOf(
PnpOperation.RemoveE164(result.secondId),
PnpOperation.Merge(
primaryId = result.secondId,
secondaryId = result.firstId
),
PnpOperation.ChangeNumberInsert(
recipientId = result.secondId,
oldE164 = E164_B,
newE164 = E164_A
)
)
),
result.changeSet
)
}
private fun insert(e164: String?, pni: PNI?, aci: ACI?): RecipientId {
val id: Long = SignalDatabase.rawDatabase.insert(
RecipientDatabase.TABLE_NAME,
null,
contentValuesOf(
RecipientDatabase.PHONE to e164,
RecipientDatabase.SERVICE_ID to (aci ?: pni)?.toString(),
RecipientDatabase.PNI_COLUMN to pni?.toString(),
RecipientDatabase.REGISTERED to RecipientDatabase.RegisteredState.REGISTERED.id
)
)
return RecipientId.from(id)
}
private fun insertMockSessionFor(account: ServiceId, address: ServiceId) {
SignalDatabase.rawDatabase.insert(
SessionDatabase.TABLE_NAME, null,
contentValuesOf(
SessionDatabase.ACCOUNT_ID to account.toString(),
SessionDatabase.ADDRESS to address.toString(),
SessionDatabase.DEVICE to 1,
SessionDatabase.RECORD to Util.getSecretBytes(32)
)
)
}
data class Input(val e164: String?, val pni: PNI?, val aci: ACI?, val pniSession: Boolean = false, val aciSession: Boolean = false)
data class Update(val e164: String?, val pni: PNI?, val aci: ACI?, val pniVerified: Boolean = false)
data class Output(val e164: String?, val pni: PNI?, val aci: ACI?)
data class PnpMatchResult(val ids: List<RecipientId>, val changeSet: PnpChangeSet) {
val id
get() = if (ids.size == 1) {
ids[0]
} else {
throw IllegalStateException("There are multiple IDs, but you assumed 1!")
}
val firstId
get() = ids[0]
val secondId
get() = ids[1]
val thirdId
get() = ids[2]
}
private fun applyAndAssert(input: Input, update: Update, output: Output): PnpMatchResult {
return applyAndAssert(listOf(input), update, output)
}
/**
* Helper method that will call insert your recipients, call [RecipientDatabase.processPnpTupleToChangeSet] with your params,
* and then verify your output matches what you expect.
*
* It results the inserted ID's and changeset for additional verification.
*
* But basically this is here to make the tests more readable. It gives you a clear list of:
* - input
* - update
* - output
*
* that you can spot check easily.
*
* Important: The output will only include records that contain fields from the input. That means
* for:
*
* Input: E164_B, PNI_A, null
* Update: E164_A, PNI_A, null
*
* You will get:
* Output: E164_A, PNI_A, null
*
* Even though there was an update that will also result in the row (E164_B, null, null)
*/
private fun applyAndAssert(input: List<Input>, update: Update, output: Output): PnpMatchResult {
val ids = input.map { insert(it.e164, it.pni, it.aci) }
input
.filter { it.pniSession }
.forEach { insertMockSessionFor(databaseRule.localAci, it.pni!!) }
input
.filter { it.aciSession }
.forEach { insertMockSessionFor(databaseRule.localAci, it.aci!!) }
val byE164 = update.e164?.let { db.getByE164(it).orElse(null) }
val byPniSid = update.pni?.let { db.getByServiceId(it).orElse(null) }
val byAciSid = update.aci?.let { db.getByServiceId(it).orElse(null) }
val data = PnpDataSet(
e164 = update.e164,
pni = update.pni,
aci = update.aci,
byE164 = byE164,
byPniSid = byPniSid,
byPniOnly = update.pni?.let { db.getByPni(it).orElse(null) },
byAciSid = byAciSid,
e164Record = byE164?.let { db.getRecord(it) },
pniSidRecord = byPniSid?.let { db.getRecord(it) },
aciSidRecord = byAciSid?.let { db.getRecord(it) }
)
val changeSet = db.processPnpTupleToChangeSet(update.e164, update.pni, update.aci, pniVerified = update.pniVerified)
val finalData = data.perform(changeSet.operations)
val finalRecords = setOfNotNull(finalData.e164Record, finalData.pniSidRecord, finalData.aciSidRecord)
assertEquals("There's still multiple records in the resulting record set! $finalRecords", 1, finalRecords.size)
finalRecords.firstOrNull { record -> record.e164 == output.e164 && record.pni == output.pni && record.serviceId == (output.aci ?: output.pni) }
?: throw AssertionError("Expected output was not found in the result set! Expected: $output")
return PnpMatchResult(
ids = ids,
changeSet = changeSet
)
}
companion object {
val ACI_A = ACI.from(UUID.fromString("3436efbe-5a76-47fa-a98a-7e72c948a82e"))
val ACI_B = ACI.from(UUID.fromString("8de7f691-0b60-4a68-9cd9-ed2f8453f9ed"))
val PNI_A = PNI.from(UUID.fromString("154b8d92-c960-4f6c-8385-671ad2ffb999"))
val PNI_B = PNI.from(UUID.fromString("ba92b1fb-cd55-40bf-adda-c35a85375533"))
const val E164_A = "+12221234567"
const val E164_B = "+13331234567"
const val E164_C = "+14441234567"
}
}
| gpl-3.0 | b4fbb8525d2f5629d679d7ca86679884 | 24.994062 | 147 | 0.599168 | 3.311696 | false | false | false | false |
robohorse/RoboPOJOGenerator | generator/src/main/kotlin/com/robohorse/robopojogenerator/filewriter/common/KotlinSingleFileWriterDelegate.kt | 1 | 3009 | package com.robohorse.robopojogenerator.filewriter.common
import com.robohorse.robopojogenerator.delegates.MessageDelegate
import com.robohorse.robopojogenerator.delegates.PreWriterDelegate
import com.robohorse.robopojogenerator.filewriter.BaseWriterDelegate
import com.robohorse.robopojogenerator.filewriter.FileWriter
import com.robohorse.robopojogenerator.models.GenerationModel
import com.robohorse.robopojogenerator.models.ProjectModel
import com.robohorse.robopojogenerator.postrocessing.PostProcessorFactory
import com.robohorse.robopojogenerator.postrocessing.common.KotlinDataClassPostProcessor
import com.robohorse.robopojogenerator.properties.ClassItem
import com.robohorse.robopojogenerator.properties.templates.ClassTemplate
internal class KotlinSingleFileWriterDelegate(
messageDelegate: MessageDelegate,
factory: PostProcessorFactory,
fileWriterDelegate: FileWriter,
preWriterDelegate: PreWriterDelegate,
private val kotlinDataClassPostProcessor: KotlinDataClassPostProcessor
) : BaseWriterDelegate(messageDelegate, factory, fileWriterDelegate, preWriterDelegate) {
override fun writeFiles(
set: Set<ClassItem>,
generationModel: GenerationModel,
projectModel: ProjectModel
) {
val imports = resolveImports(set, generationModel)
val targets = set.toMutableList()
targets.firstOrNull { it.className == generationModel.rootClassName }?.let {
val index = targets.indexOf(it)
targets.removeAt(index)
targets.add(FIRST_TARGET_POSITION, it)
}
val rootClassBuilder = StringBuilder()
targets.forEachIndexed { index, it ->
it.apply {
it.classImports.clear()
it.packagePath = null
if (index > 0) {
rootClassBuilder.append(ClassTemplate.NEW_LINE)
}
rootClassBuilder.append(prepareClass(it, generationModel))
}
}
val classBody = kotlinDataClassPostProcessor.createClassItemText(
packagePath = projectModel.packageName,
classTemplate = rootClassBuilder.toString(),
imports = kotlinDataClassPostProcessor.proceedClassImports(imports, generationModel).toString()
)
writeFile(
className = generationModel.rootClassName,
classItemBody = classBody,
generationModel = generationModel,
projectModel = projectModel
)
}
private fun resolveImports(
set: Set<ClassItem>,
generationModel: GenerationModel
): HashSet<String> {
val imports = HashSet<String>().apply {
set.forEach { addAll(it.classImports) }
}
val universalClassItem = ClassItem()
kotlinDataClassPostProcessor.applyAnnotations(generationModel, universalClassItem)
imports.addAll(universalClassItem.classImports)
return imports
}
}
private const val FIRST_TARGET_POSITION = 0
| mit | 52a2c8f9efde78b0c32bba47c9055604 | 40.791667 | 107 | 0.712529 | 5.269702 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/codeInsight/LuaRainbowVisitor.kt | 2 | 2398 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.codeInsight
import com.intellij.codeInsight.daemon.RainbowVisitor
import com.intellij.codeInsight.daemon.impl.HighlightVisitor
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import com.tang.intellij.lua.Constants
import com.tang.intellij.lua.comment.psi.LuaDocParamNameRef
import com.tang.intellij.lua.highlighting.LuaHighlightingData
import com.tang.intellij.lua.psi.*
class LuaRainbowVisitor : RainbowVisitor() {
override fun clone(): HighlightVisitor = LuaRainbowVisitor()
override fun visit(element: PsiElement) {
if (element is LuaNameExpr ||
element is LuaNameDef ||
element is LuaDocParamNameRef)
{
val resolve = when (element) {
is LuaNameExpr -> resolveLocal(element, null)
else -> element
}
if (resolve is LuaFuncBodyOwner) return
// exclude 'self'
if (resolve !is LuaParamNameDef && element.text == Constants.WORD_SELF) return
val context = PsiTreeUtil.findFirstParent(resolve) { it is LuaFuncBodyOwner }
if (context != null) {
val rainbowElement = element
val name = when (resolve) {
is LuaNameDef -> resolve.name
else -> rainbowElement.text
}
val key = when (resolve) {
is LuaParamNameDef -> LuaHighlightingData.PARAMETER
else -> null
}
val info = getInfo(context, rainbowElement, name, key)
addInfo(info)
}
}
}
override fun suitableForFile(p0: PsiFile): Boolean = p0 is LuaPsiFile
} | apache-2.0 | 13f6a8c41364bf146fd5b43fbb3d4a88 | 35.907692 | 90 | 0.645538 | 4.629344 | false | false | false | false |
kazhida/kotos2d | src/jp/kazhida/kotos2d/Kotos2dLocalStorage.kt | 1 | 3114 | package jp.kazhida.kotos2d
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.content.Context
import android.util.Log
import android.database.Cursor
/**
* Created by kazhida on 2013/07/29.
*/
public class Kotos2dLocalStorage {
class object {
private val TAG: String = "Kotos2dLocalStorage"
private var DATABASE_NAME: String = "kotos2d.sqlite"
private var TABLE_NAME: String = "data"
private val DATABASE_VERSION: Int = 1
private var helper: Kotos2dLocalStorage.DBOpenHelper? = null
private var database: SQLiteDatabase? = null
public fun init(dbName : String, tableName : String) : Boolean {
val context = Kotos2dActivity.context
if (context != null) {
DATABASE_NAME = dbName
TABLE_NAME = tableName
helper = Kotos2dLocalStorage.DBOpenHelper(context)
database = helper?.getWritableDatabase()
return true
} else {
return false
}
}
public fun destroy() : Unit {
database?.close()
}
public fun setItem(key : String, value : String) : Unit {
try {
var sql : String = "replace into " + TABLE_NAME + "(key,value)values('" + key + "','" + value + "')"
database?.execSQL(sql)
} catch (e : Exception) {
e.printStackTrace()
}
}
public fun getItem(key : String): String {
var ret : String? = null
try {
var sql : String = "select value from " + TABLE_NAME + " where key='" + key + "'"
var c : Cursor? = database?.rawQuery(sql, null)
while (c!!.moveToNext()) {
if (ret != null) {
Log.e(TAG, "The key contains more than one value.")
break
}
ret = c!!.getString(c!!.getColumnIndex("value"))
}
c!!.close()
} catch (e : Exception) {
e.printStackTrace()
}
return ret ?: ""
}
public fun removeItem(key : String?) : Unit {
try {
var sql : String? = "delete from " + TABLE_NAME + " where key='" + key + "'"
database?.execSQL(sql)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
private class DBOpenHelper(context : Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
public override fun onCreate(db : SQLiteDatabase?) : Unit {
db?.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(key TEXT PRIMARY KEY,value TEXT);")
}
public override fun onUpgrade(db : SQLiteDatabase?, oldVersion : Int, newVersion : Int) : Unit {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data")
}
}
} | mit | 72d27a3fd8677e6a080be79d666fc0d7 | 34.397727 | 131 | 0.526975 | 4.689759 | false | false | false | false |
MarkNKamau/JustJava-Android | app/src/main/java/com/marknkamau/justjava/di/RepositoriesModule.kt | 1 | 1816 | package com.marknkamau.justjava.di
import com.marknjunge.core.data.local.PreferencesRepository
import com.marknjunge.core.data.network.service.*
import com.marknjunge.core.data.repository.*
import com.marknkamau.justjava.data.db.CartDao
import com.marknkamau.justjava.data.db.DbRepository
import com.marknkamau.justjava.data.db.DbRepositoryImpl
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
object RepositoriesModule {
@Provides
fun providesDbRepository(cardDao: CartDao): DbRepository = DbRepositoryImpl(cardDao)
@Provides
fun provideProductsRepository(apiService: ApiService): ProductsRepository = ApiProductsRepository(apiService)
@Provides
fun provideAuthRepository(
authService: AuthService,
preferencesRepository: PreferencesRepository,
googleSignInService: GoogleSignInService
): AuthRepository = ApiAuthRepository(authService, preferencesRepository, googleSignInService)
@Provides
fun provideCartRepository(cartService: CartService): CartRepository = ApiCartRepository(cartService)
@Provides
fun provideOrdersRepository(ordersService: OrdersService): OrdersRepository = ApiOrdersRepository(ordersService)
@Provides
fun providePaymentsRepository(
paymentsService: PaymentsService
): PaymentsRepository = ApiPaymentsRepository(paymentsService)
@Provides
fun provideUsersRepository(
usersService: UsersService,
preferencesRepository: PreferencesRepository,
googleSignInService: GoogleSignInService,
firebaseService: FirebaseService
): UsersRepository = ApiUsersRepository(usersService, preferencesRepository, googleSignInService, firebaseService)
}
| apache-2.0 | 7d668e47e0e3f33ef44b7adf8337636c | 36.833333 | 118 | 0.801762 | 5.115493 | false | false | false | false |
jdiazcano/modulartd | editor/core/src/main/kotlin/com/jdiazcano/modulartd/ResourceManager.kt | 1 | 4101 | package com.jdiazcano.modulartd
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.assets.AssetManager
import com.badlogic.gdx.assets.loaders.resolvers.AbsoluteFileHandleResolver
import com.badlogic.gdx.graphics.g2d.Sprite
import com.badlogic.gdx.utils.Disposable
import com.jdiazcano.modulartd.beans.Map
import com.jdiazcano.modulartd.beans.Resource
import com.jdiazcano.modulartd.beans.ResourceType
import com.jdiazcano.modulartd.bus.Bus
import com.jdiazcano.modulartd.bus.BusTopic
import com.jdiazcano.modulartd.utils.SpriteLoader
import mu.KLogging
/**
* This will be the resource manager that will become the handler for all the resources. A resource is a file auto loaded
* from a file which can be of any of the ResourceType(s)
*/
class ResourceManager(map: Map): Disposable {
companion object : KLogging() {
val NO_SOUND = Resource(Gdx.files.absolute(" - No sound - "), ResourceType.SOUND)
}
private val manager = AssetManager(AbsoluteFileHandleResolver())
private var resources: MutableSet<Resource> = map.resources
init {
// Custom handler for the Sprites because they actually need to load different images all corresponding to the
// same sprite.
manager.setLoader(Sprite::class.java, SpriteLoader(AbsoluteFileHandleResolver()))
Bus.register<Resource>(BusTopic.CREATED) {
addResource(it)
manager.finishLoading()
logger.debug { "Loaded resource: $it" }
}
Bus.register<Resource>(BusTopic.DELETED) {
removeResource(it)
logger.debug { "Deleted resource: $it" }
}
Bus.register<Resource>(BusTopic.UPDATED) {
if (it in resources) {
reloadResource(it)
logger.debug { "Reloaded resource $it" }
}
}
Bus.register<MutableSet<Resource>>(BusTopic.RESOURCES_RELOAD) { resources ->
manager.clear()
this.resources = resources
resources.forEach {
addResource(it, true)
}
manager.finishLoading()
}
// The NO_SOUND needs to be addressed because an action is not mandatory to have a sound
Bus.post(NO_SOUND, BusTopic.CREATED)
}
private fun reloadResource(resource: Resource) {
val path = resource.file.path()
manager.unload(path)
manager.load(path, resource.assetType())
manager.finishLoadingAsset(path)
Bus.post(resource, BusTopic.LOAD_FINISHED)
}
/**
* Removes a resource from the manager to free up space.
*
* This should not be used directly because the bus will catch the delete event and should remove it automatically
*/
private fun removeResource(resource: Resource) {
resources.remove(resource)
manager.unload(resource.file.path())
}
/**
* Adds a resource to the manager.
*
* This should not be used directly because the bus should catch the event and act accordingly.
*/
private fun addResource(resource: Resource, loadOnly: Boolean = false) {
if (!loadOnly) {
resources.add(resource)
}
if (resource != NO_SOUND) { // This is a resource that we can't load, it doesn't exist!
manager.load(resource.file.path(), resource.assetType())
}
}
/**
* Filter resources by type.
*
* Mostly used for combo boxes where you can select the resource to use.
*/
fun getResourcesByType(type: ResourceType) = resources.filter { it.resourceType == type }
fun getAssetsByType(type: ResourceType) = getResourcesByType(type).map { manager.get(it.file.path(), it.assetType()) }
fun isLoaded(path: String) = manager.isLoaded(path)
fun exists(resource: Resource) = resources.contains(resource)
override fun dispose() {
manager.dispose()
resources.clear()
}
operator fun contains(resource: Resource) = resource in resources
fun <T> get(path: String, clazz: Class<T>): T {
return manager.get(path, clazz)
}
} | apache-2.0 | 36a6147795f08bb5234e3a391e12e165 | 33.470588 | 122 | 0.658376 | 4.44312 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/modules/api/screens/ScreenStackFragment.kt | 2 | 8433 | package abi43_0_0.host.exp.exponent.modules.api.screens
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationSet
import android.view.animation.Transformation
import android.widget.LinearLayout
import androidx.appcompat.widget.Toolbar
import androidx.coordinatorlayout.widget.CoordinatorLayout
import abi43_0_0.com.facebook.react.bridge.UiThreadUtil
import abi43_0_0.com.facebook.react.uimanager.PixelUtil
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.AppBarLayout.ScrollingViewBehavior
class ScreenStackFragment : ScreenFragment {
private var mAppBarLayout: AppBarLayout? = null
private var mToolbar: Toolbar? = null
private var mShadowHidden = false
private var mIsTranslucent = false
@SuppressLint("ValidFragment")
constructor(screenView: Screen) : super(screenView)
constructor() {
throw IllegalStateException(
"ScreenStack fragments should never be restored. Follow instructions from https://github.com/software-mansion/react-native-screens/issues/17#issuecomment-424704067 to properly configure your main activity."
)
}
fun removeToolbar() {
mAppBarLayout?.let {
mToolbar?.let { toolbar ->
if (toolbar.parent === it) {
it.removeView(toolbar)
}
}
}
mToolbar = null
}
fun setToolbar(toolbar: Toolbar) {
mAppBarLayout?.addView(toolbar)
val params = AppBarLayout.LayoutParams(
AppBarLayout.LayoutParams.MATCH_PARENT, AppBarLayout.LayoutParams.WRAP_CONTENT
)
params.scrollFlags = 0
toolbar.layoutParams = params
mToolbar = toolbar
}
fun setToolbarShadowHidden(hidden: Boolean) {
if (mShadowHidden != hidden) {
mAppBarLayout?.targetElevation = if (hidden) 0f else PixelUtil.toPixelFromDIP(4f)
mShadowHidden = hidden
}
}
fun setToolbarTranslucent(translucent: Boolean) {
if (mIsTranslucent != translucent) {
val params = screen.layoutParams
(params as CoordinatorLayout.LayoutParams).behavior = if (translucent) null else ScrollingViewBehavior()
mIsTranslucent = translucent
}
}
override fun onContainerUpdate() {
val headerConfig = screen.headerConfig
headerConfig?.onUpdate()
}
override fun onViewAnimationEnd() {
super.onViewAnimationEnd()
notifyViewAppearTransitionEnd()
}
override fun onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int): Animation? {
// this means that the fragment will appear with a custom transition, in the case
// of animation: 'none', onViewAnimationStart and onViewAnimationEnd
// won't be called and we need to notify stack directly from here.
// When using the Toolbar back button this is called an extra time with transit = 0 but in
// this case we don't want to notify. The way I found to detect is case is check isHidden.
if (transit == 0 && !isHidden &&
screen.stackAnimation === Screen.StackAnimation.NONE
) {
if (enter) {
// Android dispatches the animation start event for the fragment that is being added first
// however we want the one being dismissed first to match iOS. It also makes more sense
// from a navigation point of view to have the disappear event first.
// Since there are no explicit relationships between the fragment being added / removed
// the practical way to fix this is delaying dispatching the appear events at the end of
// the frame.
UiThreadUtil.runOnUiThread {
dispatchOnWillAppear()
dispatchOnAppear()
}
} else {
dispatchOnWillDisappear()
dispatchOnDisappear()
notifyViewAppearTransitionEnd()
}
}
return null
}
private fun notifyViewAppearTransitionEnd() {
val screenStack = view?.parent
if (screenStack is ScreenStack) {
screenStack.onViewAppearTransitionEnd()
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view: NotifyingCoordinatorLayout? = context?.let { NotifyingCoordinatorLayout(it, this) }
val params = CoordinatorLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT
)
params.behavior = if (mIsTranslucent) null else ScrollingViewBehavior()
screen.layoutParams = params
view?.addView(recycleView(screen))
mAppBarLayout = context?.let { AppBarLayout(it) }
// By default AppBarLayout will have a background color set but since we cover the whole layout
// with toolbar (that can be semi-transparent) the bar layout background color does not pay a
// role. On top of that it breaks screens animations when alfa offscreen compositing is off
// (which is the default)
mAppBarLayout?.setBackgroundColor(Color.TRANSPARENT)
mAppBarLayout?.layoutParams = AppBarLayout.LayoutParams(
AppBarLayout.LayoutParams.MATCH_PARENT, AppBarLayout.LayoutParams.WRAP_CONTENT
)
view?.addView(mAppBarLayout)
if (mShadowHidden) {
mAppBarLayout?.targetElevation = 0f
}
mToolbar?.let { mAppBarLayout?.addView(recycleView(it)) }
return view
}
fun canNavigateBack(): Boolean {
val container: ScreenContainer<*>? = screen.container
check(container is ScreenStack) { "ScreenStackFragment added into a non-stack container" }
return if (container.rootScreen == screen) {
// this screen is the root of the container, if it is nested we can check parent container
// if it is also a root or not
val parentFragment = parentFragment
if (parentFragment is ScreenStackFragment) {
parentFragment.canNavigateBack()
} else {
false
}
} else {
true
}
}
fun dismiss() {
val container: ScreenContainer<*>? = screen.container
check(container is ScreenStack) { "ScreenStackFragment added into a non-stack container" }
container.dismiss(this)
}
private class NotifyingCoordinatorLayout(context: Context, private val mFragment: ScreenFragment) : CoordinatorLayout(context) {
private val mAnimationListener: Animation.AnimationListener = object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
mFragment.onViewAnimationStart()
}
override fun onAnimationEnd(animation: Animation) {
mFragment.onViewAnimationEnd()
}
override fun onAnimationRepeat(animation: Animation) {}
}
override fun startAnimation(animation: Animation) {
// For some reason View##onAnimationEnd doesn't get called for
// exit transitions so we explicitly attach animation listener.
// We also have some animations that are an AnimationSet, so we don't wrap them
// in another set since it causes some visual glitches when going forward.
// We also set the listener only when going forward, since when going back,
// there is already a listener for dismiss action added, which would be overridden
// and also this is not necessary when going back since the lifecycle methods
// are correctly dispatched then.
// We also add fakeAnimation to the set of animations, which sends the progress of animation
val fakeAnimation = ScreensAnimation(mFragment)
fakeAnimation.duration = animation.duration
if (animation is AnimationSet && !mFragment.isRemoving) {
animation.addAnimation(fakeAnimation)
animation.setAnimationListener(mAnimationListener)
super.startAnimation(animation)
} else {
val set = AnimationSet(true)
set.addAnimation(animation)
set.addAnimation(fakeAnimation)
set.setAnimationListener(mAnimationListener)
super.startAnimation(set)
}
}
}
private class ScreensAnimation(private val mFragment: ScreenFragment) : Animation() {
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
super.applyTransformation(interpolatedTime, t)
// interpolated time should be the progress of the current transition
mFragment.dispatchTransitionProgress(interpolatedTime, !mFragment.isResumed)
}
}
}
| bsd-3-clause | 389729a4ebf05ad9c35111881e525d40 | 37.861751 | 212 | 0.7224 | 4.829897 | false | false | false | false |
world-federation-of-advertisers/virtual-people-core-serving | src/main/kotlin/org/wfanet/virtualpeople/core/model/UpdateMatrixImpl.kt | 1 | 5278 | // Copyright 2022 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.virtualpeople.core.model
import org.wfanet.virtualpeople.common.LabelerEvent
import org.wfanet.virtualpeople.common.UpdateMatrix
import org.wfanet.virtualpeople.common.fieldfilter.FieldFilter
import org.wfanet.virtualpeople.core.model.utils.*
/**
* @param hashMatcher The matcher used to match input events to the column events when using hash
* field mask.
* @param filtersMatcher The matcher used to match input events to the column conditions when not
* using hash field mask.
* @param rowHashings Each entry of the list represents a hashing based on the probability
* distribution of a column. The size of the list is the columns count.
* @param randomSeed The seed used in hashing.
* @param rows All the rows, of which the selected row will be merged to the input event.
* @param passThroughNonMatches When calling Update, if no column matches, throws error if
* passThroughNonMatches is [PassThroughNonMatches.NO].
*/
internal class UpdateMatrixImpl
private constructor(
private val hashMatcher: HashFieldMaskMatcher?,
private val filtersMatcher: FieldFiltersMatcher?,
private val rowHashings: List<DistributedConsistentHashing>,
private val randomSeed: String,
private val rows: List<LabelerEvent>,
private val passThroughNonMatches: PassThroughNonMatches
) : AttributesUpdaterInterface {
/**
* Updates [event] with selected row. The row is selected in 2 steps
* 1. Select the column with [event] matches the condition.
* 2. Use hashing to select the row based on the probability distribution of the column.
*
* Throws an error if no column matches [event], and [passThroughNonMatches] is
* [PassThroughNonMatches.NO].
*/
override fun update(event: LabelerEvent.Builder) {
val indexes =
selectFromMatrix(hashMatcher, filtersMatcher, rowHashings, randomSeed, event.build())
if (indexes.columnIndex == -1) {
if (passThroughNonMatches == PassThroughNonMatches.YES) {
return
} else {
error("No column matching for event: $event")
}
}
if (indexes.rowIndex < 0 || indexes.rowIndex >= rows.size) {
error("The returned row index is out of range.")
}
event.mergeFrom(rows[indexes.rowIndex])
return
}
internal companion object {
/**
* Always use [AttributesUpdaterInterface].build to get an [AttributesUpdaterInterface] object.
* Users should not call the factory method or the constructor of the derived classes directly.
*
* Throws an error when any of the following happens:
* 1. [config].rows is empty.
* 2. [config].columns is empty.
* 3. In [config], the probabilities count does not equal to rows count multiplies columns
* count.
* 4. Fails to build [FieldFilter] from any column.
* 5. Fails to build [DistributedConsistentHashing] from the probability distribution of any
* column.
*/
internal fun build(config: UpdateMatrix): UpdateMatrixImpl {
if (config.rowsCount == 0) {
error("No row exists in UpdateMatrix: $config")
}
if (config.columnsCount == 0) {
error("No column exists in UpdateMatrix: $config")
}
if (config.rowsCount * config.columnsCount != config.probabilitiesCount) {
error("Probabilities count must equal to row * column: $config")
}
val hashMatcher: HashFieldMaskMatcher? =
if (config.hasHashFieldMask()) {
HashFieldMaskMatcher.build(config.columnsList, config.hashFieldMask)
} else {
null
}
val filtersMatcher: FieldFiltersMatcher? =
if (!config.hasHashFieldMask()) {
FieldFiltersMatcher(config.columnsList.map { FieldFilter.create(it) })
} else {
null
}
/** Converts the probability distribution of each column to [DistributedConsistentHashing]. */
val rowHashings: List<DistributedConsistentHashing> =
(0 until config.columnsCount).map { columnIndex ->
val distributions =
(0 until config.rowsCount).map { rowIndex ->
val probability =
config.getProbabilities(rowIndex * config.columnsCount + columnIndex)
DistributionChoice(rowIndex, probability.toDouble())
}
DistributedConsistentHashing(distributions)
}
val passThroughNonMatches =
if (config.passThroughNonMatches) PassThroughNonMatches.YES else PassThroughNonMatches.NO
return UpdateMatrixImpl(
hashMatcher,
filtersMatcher,
rowHashings,
config.randomSeed,
config.rowsList,
passThroughNonMatches
)
}
}
}
| apache-2.0 | 37c023ea6b6e176cebe24ca1b5e8c753 | 38.684211 | 100 | 0.700076 | 4.589565 | false | true | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/autotune/data/PeakDeviation.kt | 1 | 1073 | package info.nightscout.androidaps.plugins.general.autotune.data
import org.json.JSONException
import org.json.JSONObject
class PeakDeviation(var peak: Int = 0, var meanDeviation: Double = 0.0, var smrDeviation: Double = 0.0, var rmsDeviation: Double = 0.0) {
constructor(json: JSONObject) : this() {
try {
if (json.has("peak")) peak = json.getInt("peak")
if (json.has("meanDeviation")) meanDeviation = json.getDouble("meanDeviation")
if (json.has("SMRDeviation")) smrDeviation = json.getDouble("SMRDeviation")
if (json.has("RMSDeviation")) rmsDeviation = json.getDouble("RMSDeviation")
} catch (e: JSONException) {
}
}
fun toJSON(): JSONObject {
val crjson = JSONObject()
try {
crjson.put("peak", peak)
crjson.put("meanDeviation", meanDeviation.toInt())
crjson.put("SMRDeviation", smrDeviation)
crjson.put("RMSDeviation", rmsDeviation.toInt())
} catch (e: JSONException) {
}
return crjson
}
} | agpl-3.0 | 982034c1159ef97ccda8d68ef054a6e8 | 36.034483 | 137 | 0.618826 | 3.901818 | false | false | false | false |
sjnyag/stamp | app/src/main/java/com/sjn/stamp/model/dao/SongDao.kt | 1 | 5009 | package com.sjn.stamp.model.dao
import android.content.Context
import android.support.v4.media.MediaMetadataCompat
import com.sjn.stamp.model.Song
import com.sjn.stamp.utils.MediaItemHelper
import com.sjn.stamp.utils.MediaRetrieveHelper
import io.realm.Realm
object SongDao : BaseDao<Song>() {
fun findById(realm: Realm, id: Long): Song? =
realm.where(Song::class.java).equalTo("id", id).findFirst()
private fun findByMediaId(realm: Realm, mediaId: String): Song? =
realm.where(Song::class.java).equalTo("mediaId", mediaId).findFirst()
@Suppress("unused")
fun findByTitleArtistAlbum(realm: Realm, title: String, artist: String, album: String): Song? =
realm.where(Song::class.java).equalTo("title", title).equalTo("album", album).equalTo("artist.name", artist).findFirst()
fun findByMediaMetadata(realm: Realm, metadata: MediaMetadataCompat): Song? =
realm.where(Song::class.java).equalTo("title", MediaItemHelper.getTitle(metadata)).equalTo("album", MediaItemHelper.getAlbum(metadata)).equalTo("artist.name", MediaItemHelper.getArtist(metadata)).findFirst()
fun findUnknown(realm: Realm): List<Song> {
val mediaId: String? = null
return realm.where(Song::class.java).equalTo("mediaId", "").or().equalTo("mediaId", mediaId).findAll()
?: emptyList()
}
fun findAll(realm: Realm): List<Song> =
realm.where(Song::class.java).findAll() ?: emptyList()
fun findOrCreate(realm: Realm, metadata: MediaMetadataCompat): Song {
var song: Song? = findByMediaMetadata(realm, metadata)
if (song == null) {
song = Song()
song.id = getAutoIncrementId(realm)
val artist = ArtistDao.findOrCreate(realm, MediaItemHelper.getArtist(metadata), MediaItemHelper.getAlbumArtUri(metadata))
val totalSongHistory = TotalSongHistoryDao.findOrCreate(realm, song.id)
song.artist = artist
song.totalSongHistory = totalSongHistory
song.loadMediaMetadataCompat(metadata)
realm.beginTransaction()
realm.copyToRealm(song)
realm.commitTransaction()
return song
}
return song
}
fun findOrCreateByMusicId(realm: Realm, mediaId: String, context: Context): Song? {
var song: Song? = findByMediaId(realm, mediaId)
if (song == null) {
try {
val metadata = MediaRetrieveHelper.findByMusicId(context, mediaId.toLong(), null)
metadata ?: return null
song = Song()
song.id = getAutoIncrementId(realm)
val artist = ArtistDao.findOrCreate(realm, MediaItemHelper.getArtist(metadata), MediaItemHelper.getAlbumArtUri(metadata))
val totalSongHistory = TotalSongHistoryDao.findOrCreate(realm, song.id)
song.artist = artist
song.totalSongHistory = totalSongHistory
song.loadMediaMetadataCompat(metadata)
realm.beginTransaction()
realm.copyToRealm(song)
realm.commitTransaction()
return song
} catch (e: NumberFormatException) {
return null
}
}
return song
}
fun loadLocalMedia(realm: Realm, songId: Long, musicList: Collection<MediaMetadataCompat>): Boolean {
val song = findById(realm, songId) ?: return false
val localMedia = musicList.find { MediaItemHelper.isSameSong(it, song) }
if (localMedia == null) {
saveUnknown(realm, song.id)
return false
}
val realmSong = findById(realm, song.id) ?: return false
realm.beginTransaction()
realmSong.loadMediaMetadataCompat(localMedia)
realm.commitTransaction()
return true
}
fun merge(realm: Realm, unknownSongId: Long, songId: Long): Boolean {
val unknownSong = findById(realm, unknownSongId) ?: return false
val newSong = findById(realm, songId) ?: return false
realm.beginTransaction()
newSong.merge(unknownSong)
unknownSong.deleteFromRealm()
realm.commitTransaction()
return true
}
fun delete(realm: Realm, songId: Long) {
realm.executeTransactionAsync { r ->
val song = findById(r, songId) ?: return@executeTransactionAsync
song.songHistoryList?.forEach {
it.deleteFromRealm()
}
song.songStampList.forEach {
if (it.songList.contains(song)) {
it.songList.remove(song)
}
}
song.totalSongHistory.deleteFromRealm()
song.deleteFromRealm()
}
}
private fun saveUnknown(realm: Realm, songId: Long) {
val realmSong = findById(realm, songId) ?: return
realm.beginTransaction()
realmSong.mediaId = ""
realm.commitTransaction()
}
} | apache-2.0 | 48dd6dd37003b4b49413d4783a10b622 | 39.731707 | 219 | 0.626073 | 4.703286 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/InlineCallableUsagesSearcher.kt | 2 | 5925 | // 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.debugger
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.xdebugger.impl.XDebuggerManagerImpl
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter
import org.jetbrains.kotlin.idea.base.projectStructure.matches
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.debugger.DebuggerClassNameProvider.Companion.getRelevantElement
import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinDebuggerCaches.ComputedClassNames
import org.jetbrains.kotlin.idea.search.isImportUsage
import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.inline.InlineUtil
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class InlineCallableUsagesSearcher(val project: Project, val searchScope: GlobalSearchScope) {
fun findInlinedCalls(
declaration: KtDeclaration,
alreadyVisited: Set<PsiElement>,
transformer: (PsiElement, Set<PsiElement>) -> ComputedClassNames
): ComputedClassNames {
if (!checkIfInline(declaration)) {
return ComputedClassNames.EMPTY
} else {
val searchResult = hashSetOf<PsiElement>()
val declarationName = runReadAction { declaration.name ?: "<error>" }
val task = Runnable {
for (reference in ReferencesSearch.search(declaration, getScopeForInlineDeclarationUsages(declaration))) {
ProgressManager.checkCanceled()
processReference(declaration, reference, alreadyVisited)?.let { searchResult += it }
}
}
var isSuccess = true
val applicationEx = ApplicationManagerEx.getApplicationEx()
if (applicationEx.isDispatchThread) {
isSuccess = ProgressManager.getInstance().runProcessWithProgressSynchronously(
task,
KotlinDebuggerCoreBundle.message("find.inline.calls.task.compute.names", declarationName),
true,
project
)
} else {
try {
ProgressManager.getInstance().runProcess(task, EmptyProgressIndicator())
} catch (e: InterruptedException) {
isSuccess = false
}
}
if (!isSuccess) {
XDebuggerManagerImpl.getNotificationGroup().createNotification(
KotlinDebuggerCoreBundle.message("find.inline.calls.task.cancelled", declarationName),
MessageType.WARNING
).notify(project)
}
val newAlreadyVisited = HashSet<PsiElement>().apply {
addAll(alreadyVisited)
addAll(searchResult)
add(declaration)
}
val results = searchResult.map { transformer(it, newAlreadyVisited) }
return ComputedClassNames(results.flatMap { it.classNames }, shouldBeCached = results.all { it.shouldBeCached })
}
}
private fun processReference(declaration: KtDeclaration, reference: PsiReference, alreadyVisited: Set<PsiElement>): PsiElement? {
if (runReadAction { reference.isImportUsage() }) {
return null
}
val usage = (reference.element as? KtElement)?.let(::getRelevantElement) ?: return null
val shouldAnalyze = runReadAction { !declaration.isAncestor(usage) && usage !in alreadyVisited }
return if (shouldAnalyze) usage else null
}
private fun checkIfInline(declaration: KtDeclaration) =
ReadAction.nonBlocking<Boolean> {
ProgressManager.checkCanceled()
checkIfInlineInReadAction(declaration)
}.executeSynchronously()
private fun checkIfInlineInReadAction(declaration: KtDeclaration): Boolean {
if (DumbService.isDumb(project)) {
return false
}
val bindingContext = declaration.analyze(BodyResolveMode.PARTIAL)
val descriptor = bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, declaration) ?: return false
return when (descriptor) {
is FunctionDescriptor -> InlineUtil.isInline(descriptor)
is PropertyDescriptor -> InlineUtil.hasInlineAccessors(descriptor)
else -> false
}
}
private fun getScopeForInlineDeclarationUsages(inlineDeclaration: KtDeclaration): GlobalSearchScope {
val virtualFile = runReadAction { inlineDeclaration.containingFile.virtualFile }
return if (virtualFile != null && RootKindFilter.libraryFiles.matches(project, virtualFile)) {
searchScope.uniteWith(
KotlinSourceFilterScope.librarySources(GlobalSearchScope.allScope(project), project)
)
} else {
searchScope
}
}
} | apache-2.0 | 0d719a3a97c1e566520975c232ff3760 | 45.296875 | 158 | 0.698059 | 5.460829 | false | false | false | false |
livefront/bridge | bridgesample/src/main/java/com/livefront/bridgesample/main/view/MainItemView.kt | 1 | 1188 | package com.livefront.bridgesample.main.view
import android.content.Context
import android.util.AttributeSet
import android.widget.RelativeLayout
import androidx.annotation.DrawableRes
import com.livefront.bridgesample.R
import com.livefront.bridgesample.util.layoutInflater
import kotlinx.android.synthetic.main.view_main_item_content.view.descriptionView
import kotlinx.android.synthetic.main.view_main_item_content.view.imageView
import kotlinx.android.synthetic.main.view_main_item_content.view.titleView
class MainItemView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr, defStyleRes) {
init {
layoutInflater.inflate(R.layout.view_main_item_content, this)
}
var description: CharSequence
get() = descriptionView.text
set(value) {
descriptionView.text = value
}
var title: CharSequence
get() = titleView.text
set(value) {
titleView.text = value
}
fun setImageResource(@DrawableRes value: Int) {
imageView.setImageResource(value)
}
}
| apache-2.0 | 8760bacf94dd80d28c9b2343aee15180 | 30.263158 | 81 | 0.726431 | 4.416357 | false | false | false | false |
SourceUtils/hl2-toolkit | src/main/kotlin/com/timepath/hl2/io/demo/Message.kt | 1 | 7454 | package com.timepath.hl2.io.demo
import com.timepath.DataUtils
import com.timepath.Logger
import com.timepath.io.BitBuffer
import com.timepath.io.OrderedOutputStream
import com.timepath.io.struct.StructField
import com.timepath.with
import java.nio.BufferUnderflowException
import java.nio.ByteBuffer
import java.text.MessageFormat
import java.util.LinkedList
import java.util.logging.Level
public class Message(
private val outer: HL2DEM,
public val type: MessageType?,
StructField(index = 1) public val tick: Int) {
public var data: ByteBuffer? = null
set(data) {
$data = data
$size = data?.capacity() ?: 0
}
public var meta: TupleMap<Any, Any?> = TupleMap()
public var incomplete: Boolean = false
/** Command / sequence info. TODO: use */
StructField(index = 2, nullable = true) public var cseq: ByteArray? = null
/** Outgoing sequence number. TODO: use */
StructField(index = 3, nullable = true) public var oseq: ByteArray? = null
StructField(index = 4) public var size: Int = 0
StructField(index = 0) private val op: Byte = 0
private var parsed: Boolean = false
public fun write(out: OrderedOutputStream) {
out.writeByte(type!!.ordinal() + 1)
out.writeInt(tick)
cseq?.let { out.write(it) }
oseq?.let { out.write(it) }
when (type) {
MessageType.Synctick, MessageType.Stop -> Unit
else -> out.writeInt(size)
}
data?.let {
it.position(0)
val dst = ByteArray(it.limit())
it.get(dst)
out.write(dst)
}
}
override fun toString() = "${type}, tick ${tick}, ${data?.limit() ?: 0} bytes"
fun parse() {
if (type == null) return
if (data == null) return
if (parsed) return
when (type) {
MessageType.Signon, MessageType.Packet -> {
val bb = BitBuffer(data!!)
var error: String? = null
var thrown: Throwable? = null
val opSize = if ((outer.header.networkProtocol >= 16)) 6 else 5
while (bb.remainingBits() > opSize) {
try {
val op = bb.getBits(opSize).toInt()
val type = Packet[op]
if (type == null) {
error = "Unknown message type ${op} in ${this}"
thrown = Exception("Unknown message")
} else {
val p = Packet(type, bb.positionBits())
try {
if (!type.read(bb, p.list, outer)) {
error = "Incomplete read of ${p} in ${this}"
}
} catch (e: BufferUnderflowException) {
error = "Out of data in ${this}"
} catch (e: Exception) {
error = "Exception in ${p} in ${this}"
thrown = e
}
meta[p] = p.list
}
} catch (e: BufferUnderflowException) {
error = "Out of data in ${this}"
}
meta["remaining bits"] = bb.remainingBits()
if (error != null) {
incomplete = true
meta["error"] = error
thrown?.let { LOG.log(Level.WARNING, { error }, it) }
break
}
}
}
MessageType.ConsoleCmd -> {
val cmd = DataUtils.getText(data!!, true)
meta["cmd"] = cmd
}
MessageType.UserCmd -> {
// https://github.com/LestaD/SourceEngine2007/blob/master/se2007/game/shared/usercmd.cpp#L199
val bb = BitBuffer(data!!)
if (bb.getBoolean()) {
meta["Command number"] = bb.getInt()
} // else assume steady increment
if (bb.getBoolean()) {
meta["Tick count"] = bb.getInt()
} // else assume steady increment
if (bb.getBoolean()) {
meta["Viewangle pitch"] = bb.getFloat()
}
if (bb.getBoolean()) {
meta["Viewangle yaw"] = bb.getFloat()
}
if (bb.getBoolean()) {
meta["Viewangle roll"] = bb.getFloat()
}
if (bb.getBoolean()) {
meta["Foward move"] = bb.getFloat()
}
if (bb.getBoolean()) {
meta["Side move"] = bb.getFloat()
}
if (bb.getBoolean()) {
meta["Up move"] = bb.getFloat()
}
if (bb.getBoolean()) {
meta["Buttons"] = Input[bb.getInt()]
}
if (bb.getBoolean()) {
meta["Impulse"] = bb.getByte()
}
if (bb.getBoolean()) {
meta["Weapon select"] = bb.getBits(HL2DEM.MAX_EDICT_BITS)
if (bb.getBoolean()) {
meta["Weapon subtype"] = bb.getBits(HL2DEM.WEAPON_SUBTYPE_BITS)
}
}
if (bb.getBoolean()) {
meta["Mouse Dx"] = bb.getShort()
}
if (bb.getBoolean()) {
meta["Mouse Dy"] = bb.getShort()
}
if (bb.remaining() > 0) {
meta["Underflow"] = bb.remaining()
}
}
MessageType.DataTables, MessageType.StringTables -> Unit // TODO
}
parsed = true
}
companion object {
private val LOG = Logger()
fun parse(outer: HL2DEM, buffer: ByteBuffer): Message {
val op = buffer.get().toInt()
val type = MessageType[op]
if (type == null) {
LOG.severe { "Unknown demo message type encountered: ${op}" }
}
val tick = buffer.getInt()
LOG.fine { "${type} at tick ${tick} (${buffer.position()}), ${buffer.remaining()} remaining bytes" }
return Message(outer, type, tick).with {
val m = this
when {
m.type == MessageType.Synctick,
m.type == MessageType.Stop -> Unit
else -> {
when {
m.type == MessageType.Packet,
m.type == MessageType.Signon -> {
val dst = ByteArray(21 * 4)
buffer.get(dst)
m.cseq = dst
}
m.type == MessageType.UserCmd -> {
val dst = ByteArray(4)
buffer.get(dst)
m.oseq = dst
}
}
m.size = buffer.getInt()
}
}
}
}
}
}
| artistic-2.0 | bbafbd9fbf1ff270d197068216047b57 | 37.225641 | 112 | 0.427019 | 4.936424 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/mysite/cards/quickactions/QuickActionsViewHolder.kt | 1 | 1711 | package org.wordpress.android.ui.mysite.cards.quickactions
import android.view.View
import android.view.ViewGroup
import org.wordpress.android.databinding.MySiteCardToolbarBinding
import org.wordpress.android.databinding.MySiteQuickActionsCardBinding
import org.wordpress.android.databinding.QuickActionsCardBinding
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.QuickActionsCard
import org.wordpress.android.ui.mysite.MySiteCardAndItemViewHolder
import org.wordpress.android.ui.utils.UiHelpers
import org.wordpress.android.util.extensions.viewBinding
class QuickActionsViewHolder(
parent: ViewGroup,
private val uiHelpers: UiHelpers
) : MySiteCardAndItemViewHolder<MySiteQuickActionsCardBinding>(
parent.viewBinding(MySiteQuickActionsCardBinding::inflate)
) {
fun bind(card: QuickActionsCard) = with(binding) {
quickActionsToolbar.update(card)
quickActionsCard.update(card)
}
private fun MySiteCardToolbarBinding.update(card: QuickActionsCard) {
mySiteCardToolbarTitle.text = uiHelpers.getTextOfUiString(itemView.context, card.title)
}
private fun QuickActionsCardBinding.update(card: QuickActionsCard) {
quickActionStatsButton.setOnClickListener { card.onStatsClick.click() }
quickActionPostsButton.setOnClickListener { card.onPostsClick.click() }
quickActionMediaButton.setOnClickListener { card.onMediaClick.click() }
quickActionPagesButton.setOnClickListener { card.onPagesClick.click() }
val pagesVisibility = if (card.showPages) View.VISIBLE else View.GONE
quickActionPagesButton.visibility = pagesVisibility
quickActionPagesLabel.visibility = pagesVisibility
}
}
| gpl-2.0 | 4e1dd41b4f38f59217911eec5dd341e2 | 44.026316 | 95 | 0.79661 | 4.599462 | false | false | false | false |
DanielGrech/anko | preview/attrs/src/org/jetbrains/kotlin/android/Attrs.kt | 3 | 1394 | /*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.android.attrs
import java.io.File
public data class NameValue(
val name: String = "",
val value: String = "")
public data class Attr(
val name: String = "",
val format: List<String> = listOf(),
val flags: List<NameValue>? = null,
val enum: List<NameValue>? = null)
public val NoAttr: Attr = Attr()
public data class Styleable(
val name: String = "",
val attrs: List<Attr> = listOf())
public data class Attrs(
val free: List<Attr> = listOf(),
val styleables: Map<String, Styleable> = mapOf())
public fun readResource(filename: String): String {
return javaClass<Attrs>().getClassLoader().getResourceAsStream(filename)?.reader()?.readText() ?:
File(filename).readText()
} | apache-2.0 | 86a7baa8280b3b46ae246efeed4f3ac9 | 30.704545 | 101 | 0.678623 | 4.1 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/jvm-debugger/base/util/src/org/jetbrains/kotlin/idea/debugger/base/util/JdiTypeUtils.kt | 3 | 1051 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("JdiTypeUtils")
package org.jetbrains.kotlin.idea.debugger.base.util
import com.sun.jdi.ClassType
import com.sun.jdi.Type
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.org.objectweb.asm.Type as AsmType
@ApiStatus.Internal
fun Type.isSubtype(className: String): Boolean = isSubtype(AsmType.getObjectType(className))
@ApiStatus.Internal
fun Type.isSubtype(type: AsmType): Boolean {
if (this.signature() == type.descriptor) {
return true
}
if (type.sort != AsmType.OBJECT || this !is ClassType) {
return false
}
val superTypeName = type.className
if (allInterfaces().any { it.name() == superTypeName }) {
return true
}
var superClass = superclass()
while (superClass != null) {
if (superClass.name() == superTypeName) {
return true
}
superClass = superClass.superclass()
}
return false
} | apache-2.0 | 45a4de2d9bcec28a872a32acd85e0857 | 25.3 | 120 | 0.683159 | 4.01145 | false | false | false | false |
austinv11/D4JBot | src/main/kotlin/com/austinv11/d4j/bot/command/impl/QueueCommand.kt | 1 | 3587 | package com.austinv11.d4j.bot.command.impl
import com.austinv11.d4j.bot.audio.appendQueueInfo
import com.austinv11.d4j.bot.audio.playerManager
import com.austinv11.d4j.bot.command.CommandExecutor
import com.austinv11.d4j.bot.command.Executor
import com.austinv11.d4j.bot.command.Parameter
import com.austinv11.d4j.bot.command.context
import com.austinv11.d4j.bot.extensions.buffer
import com.austinv11.d4j.bot.extensions.embed
import sx.blah.discord.util.EmbedBuilder
class QueueCommand : CommandExecutor() {
override val name: String = "queue"
override val aliases: Array<String> = arrayOf("enqueue")
override val guildOnly: Boolean = true
@Executor("Gets the current queue information.")
fun execute(): EmbedBuilder = context.embed.appendQueueInfo(context.guild!!.playerManager)
@Executor("Queues a track.")
fun execute(@Parameter("The track to queue.") track: String) {
val channel = context.channel
channel.typingStatus = true
val context = context
val msg = buffer { channel.sendMessage(context.embed.withTitle("Processing...").build()) }
context.guild!!.playerManager.queue.add(msg to context, track.removePrefix("<").removeSuffix(">"))
}
@Executor("Performs an action on the queue.")
fun execute(@Parameter("The action to perform.") action: NoArgQueueAction): EmbedBuilder = context.embed.apply {
when(action) {
NoArgQueueAction.INFO -> {
return@execute execute()
}
NoArgQueueAction.CLEAR -> {
val cleared = context.guild!!.playerManager.queue.clear()
withTitle("Cleared $cleared tracks")
}
}
}
@Executor("Performs an action on the queue.")
fun execute(@Parameter("The action to perform.") action: OneArgQueueAction,
@Parameter("The track to effect.") track: String): EmbedBuilder? = context.embed.apply {
when(action) {
OneArgQueueAction.ADD -> {
execute(track)
return@execute null
}
OneArgQueueAction.REMOVE -> {
val did = context.guild!!.playerManager.queue.tracks.removeIf { it.info.title == track }
if (did) {
withTitle("Removed")
} else {
withTitle("Cannot find track `$track`")
}
}
}
}
@Executor("Performs an action on the queue.")
fun execute(@Parameter("The action to perform.") action: OneArgQueueAction,
@Parameter("The track to effect.") track: Int): EmbedBuilder = context.embed.apply {
when(action) {
OneArgQueueAction.ADD -> {
context.guild!!.playerManager.queue.add(context.guild!!.playerManager.queue.tracks.filterIndexed { index, audioTrack -> index == track }.first().makeClone())
return execute()
}
OneArgQueueAction.REMOVE -> {
val did = context.guild!!.playerManager.queue.size() > track
if (did) {
context.guild!!.playerManager.queue.tracks.remove(context.guild!!.playerManager.queue.tracks.filterIndexed { index, audioTrack -> index == track }.first())
withTitle("Removed")
} else {
withTitle("Cannot find track `$track`")
}
}
}
}
enum class NoArgQueueAction {
INFO, CLEAR
}
enum class OneArgQueueAction {
ADD, REMOVE
}
}
| gpl-3.0 | 951dbd4ba715275af58b2622eb038500 | 38.855556 | 175 | 0.60552 | 4.461443 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/settings/view/TimeFormatPickerDialogController.kt | 1 | 3413 | package io.ipoli.android.settings.view
import android.content.DialogInterface
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.text.format.DateFormat
import android.view.LayoutInflater
import android.view.View
import io.ipoli.android.R
import io.ipoli.android.common.datetime.Time
import io.ipoli.android.common.view.ReduxDialogController
import io.ipoli.android.common.view.stringRes
import io.ipoli.android.pet.AndroidPetAvatar
import io.ipoli.android.pet.LoadPetDialogAction
import io.ipoli.android.pet.PetDialogReducer
import io.ipoli.android.pet.PetDialogViewState
import io.ipoli.android.player.data.Player.Preferences
import kotlinx.android.synthetic.main.view_dialog_header.view.*
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 5/17/18.
*/
class TimeFormatPickerDialogController(args: Bundle? = null) :
ReduxDialogController<LoadPetDialogAction, PetDialogViewState, PetDialogReducer>(args) {
override val reducer = PetDialogReducer
private lateinit var selectedTimeFormat: Preferences.TimeFormat
private var listener: (Preferences.TimeFormat) -> Unit = {}
constructor(
selectedTimeFormat: Preferences.TimeFormat,
listener: (Preferences.TimeFormat) -> Unit
) : this() {
this.selectedTimeFormat = selectedTimeFormat
this.listener = listener
}
override fun onCreateContentView(inflater: LayoutInflater, savedViewState: Bundle?): View =
inflater.inflate(R.layout.dialog_time_format, null)
override fun onHeaderViewCreated(headerView: View) {
headerView.dialogHeaderTitle.setText(R.string.select_time_format)
}
override fun onCreateDialog(
dialogBuilder: AlertDialog.Builder,
contentView: View,
savedViewState: Bundle?
): AlertDialog {
val formats = listOf(
Preferences.TimeFormat.DEVICE_DEFAULT,
Preferences.TimeFormat.TWELVE_HOURS,
Preferences.TimeFormat.TWENTY_FOUR_HOURS
)
val items = listOf(
stringRes(
R.string.device_default_time_format,
Time.now().toString(DateFormat.is24HourFormat(contentView.context))
),
stringRes(R.string.twelve_hour_format, Time.now().toString(false)),
stringRes(R.string.twenty_four_hour_format, Time.now().toString(true))
)
val checked = formats.indexOfFirst { it == selectedTimeFormat }
return dialogBuilder
.setSingleChoiceItems(
items.toTypedArray(),
checked
) { _, which ->
selectedTimeFormat = formats[which]
}
.setPositiveButton(R.string.dialog_ok, null)
.setNegativeButton(R.string.cancel, null)
.create()
}
override fun onDialogCreated(dialog: AlertDialog, contentView: View) {
dialog.setOnShowListener {
dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener { _ ->
listener(selectedTimeFormat)
dismiss()
}
}
}
override fun onCreateLoadAction() = LoadPetDialogAction
override fun render(state: PetDialogViewState, view: View) {
if (state.type == PetDialogViewState.Type.PET_LOADED) {
changeIcon(AndroidPetAvatar.valueOf(state.petAvatar!!.name).headImage)
}
}
} | gpl-3.0 | e0a4ed0e291562cb77268550ce674440 | 33.484848 | 95 | 0.682977 | 4.733703 | false | false | false | false |
AberrantFox/hotbot | src/main/kotlin/me/aberrantfox/hotbot/commandframework/commands/utility/XKCDCommands.kt | 1 | 1732 | package me.aberrantfox.hotbot.commandframework.commands.utility
import khttp.get
import me.aberrantfox.hotbot.commandframework.parsing.ArgumentType
import me.aberrantfox.hotbot.dsls.command.CommandSet
import me.aberrantfox.hotbot.dsls.command.arg
import me.aberrantfox.hotbot.dsls.command.commands
import me.aberrantfox.hotbot.utility.randomInt
import java.net.URLEncoder
@CommandSet
fun xkcdCommands() = commands {
command("xkcd") {
expect(arg(ArgumentType.Integer, true, { randomInt(1, getAmount()) }))
execute {
val target = it.args.component1() as Int
val link =
if (target <= getAmount() && target > 0) {
produceURL(target)
} else {
"Please enter a valid comic number between 1 and ${getAmount()}"
}
it.respond(link)
}
}
command("xkcd-latest") {
execute {
it.respond("https://xkcd.com/" + getAmount())
}
}
command("xkcd-search") {
expect(ArgumentType.Sentence)
execute {
val what = it.args.component1() as String
it.respond(produceURL(search(what)))
}
}
}
private fun search(what: String): Int {
val comicNumberParseRegex = "(?:\\S+\\s+){2}(\\S+)".toRegex()
return comicNumberParseRegex.find(
get("https://relevantxkcd.appspot.com/process?action=xkcd&query=" + URLEncoder.encode(
what, "UTF-8")).text)!!.groups[1]?.value!!.toInt()
}
private fun getAmount() =
get("https://xkcd.com/info.0.json").jsonObject.getInt("num")
private fun produceURL(comicNumber: Int) =
"http://xkcd.com/$comicNumber/" | mit | a98fd073345862cda02c4acfbcb12e7b | 30.509091 | 98 | 0.601617 | 4.084906 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/utils/src/org/jetbrains/kotlin/idea/codeinsight/utils/RedundantSemicolonUtils.kt | 1 | 4345 | // 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.utils
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.idea.util.isLineBreak
import org.jetbrains.kotlin.kdoc.psi.api.KDoc
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
fun isRedundantSemicolon(semicolon: PsiElement): Boolean {
val nextLeaf = semicolon.nextLeaf { it !is PsiWhiteSpace && it !is PsiComment || it.isLineBreak() }
val isAtEndOfLine = nextLeaf == null || nextLeaf.isLineBreak()
if (!isAtEndOfLine) {
//when there is no imports parser generates empty import list with no spaces
if (semicolon.parent is KtPackageDirective && (nextLeaf as? KtImportList)?.imports?.isEmpty() == true) {
return true
}
if (semicolon.prevLeaf { it !is PsiWhiteSpace && it !is PsiComment || it.isLineBreak() } is PsiWhiteSpace &&
!semicolon.isBeforeLeftBrace()
) {
return true
}
return false
}
if (semicolon.prevLeaf()?.node?.elementType == KtNodeTypes.ELSE) return false
if (semicolon.parent is KtEnumEntry) return false
(semicolon.parent.parent as? KtClass)?.let { clazz ->
if (clazz.isEnum() && clazz.getChildrenOfType<KtEnumEntry>().isEmpty()) {
if (semicolon.prevLeaf {
it !is PsiWhiteSpace && it !is PsiComment && !it.isLineBreak()
}?.node?.elementType == KtTokens.LBRACE &&
clazz.declarations.isNotEmpty()
) {
//first semicolon in enum with no entries, but with some declarations
return false
}
}
}
(semicolon.prevLeaf()?.parent as? KtLoopExpression)?.let {
if (it !is KtDoWhileExpression && it.body == null)
return false
}
semicolon.prevLeaf()?.parent?.safeAs<KtIfExpression>()?.also { ifExpression ->
if (ifExpression.then == null)
return false
}
if (nextLeaf.isBeforeLeftBrace()) {
return false // case with statement starting with '{' and call on the previous line
}
return !isSemicolonRequired(semicolon)
}
private fun PsiElement?.isBeforeLeftBrace(): Boolean {
return this?.nextLeaf {
it !is PsiWhiteSpace && it !is PsiComment && it.getStrictParentOfType<KDoc>() == null &&
it.getStrictParentOfType<KtAnnotationEntry>() == null
}?.node?.elementType == KtTokens.LBRACE
}
private fun isSemicolonRequired(semicolon: PsiElement): Boolean {
if (isRequiredForCompanion(semicolon)) {
return true
}
val prevSibling = semicolon.getPrevSiblingIgnoringWhitespaceAndComments()
val nextSibling = semicolon.getNextSiblingIgnoringWhitespaceAndComments()
if (prevSibling.safeAs<KtNameReferenceExpression>()?.text in softModifierKeywords && nextSibling is KtDeclaration) {
// enum; class Foo
return true
}
if (nextSibling is KtPrefixExpression && nextSibling.operationToken == KtTokens.EXCL) {
val typeElement = semicolon.prevLeaf()?.getStrictParentOfType<KtTypeReference>()?.typeElement
if (typeElement != null) {
return typeElement !is KtNullableType // trailing '?' fixes parsing
}
}
return false
}
private fun isRequiredForCompanion(semicolon: PsiElement): Boolean {
val prev = semicolon.getPrevSiblingIgnoringWhitespaceAndComments() as? KtObjectDeclaration ?: return false
if (!prev.isCompanion()) return false
if (prev.nameIdentifier != null || prev.getChildOfType<KtClassBody>() != null) return false
val next = semicolon.getNextSiblingIgnoringWhitespaceAndComments() ?: return false
val firstChildNode = next.firstChild?.node ?: return false
if (KtTokens.KEYWORDS.contains(firstChildNode.elementType)) return false
return true
}
private val softModifierKeywords: List<String> = KtTokens.SOFT_KEYWORDS.types.mapNotNull { (it as? KtModifierKeywordToken)?.toString() } | apache-2.0 | 0603e35b6a730d8a3a22b0b424a4db9c | 39.240741 | 136 | 0.690449 | 5.046458 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/contributors/FirCompletionContributorBase.kt | 3 | 10103 | // 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.contributors
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.PrefixMatcher
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementDecorator
import com.intellij.codeInsight.lookup.LookupElementPresentation
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.scopes.KtScopeNameFilter
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.analysis.api.types.KtType
import org.jetbrains.kotlin.idea.base.analysis.api.utils.KtSymbolFromIndexProvider
import org.jetbrains.kotlin.idea.base.fir.codeInsight.HLIndexHelper
import org.jetbrains.kotlin.idea.completion.ItemPriority
import org.jetbrains.kotlin.idea.completion.LookupElementSink
import org.jetbrains.kotlin.idea.completion.context.FirBasicCompletionContext
import org.jetbrains.kotlin.idea.completion.context.FirRawPositionCompletionContext
import org.jetbrains.kotlin.idea.completion.contributors.helpers.CallableMetadataProvider
import org.jetbrains.kotlin.idea.completion.contributors.helpers.CallableMetadataProvider.getCallableMetadata
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.factories.KotlinFirLookupElementFactory
import org.jetbrains.kotlin.idea.completion.priority
import org.jetbrains.kotlin.idea.completion.weighers.Weighers
import org.jetbrains.kotlin.idea.completion.weighers.WeighingContext
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.deprecation.DeprecationLevelValue
internal class FirCompletionContributorOptions(
val priority: Int = 0
) {
companion object {
val DEFAULT = FirCompletionContributorOptions()
}
}
internal abstract class FirCompletionContributorBase<C : FirRawPositionCompletionContext>(
protected val basicContext: FirBasicCompletionContext,
options: FirCompletionContributorOptions,
) {
constructor(basicContext: FirBasicCompletionContext, priority: Int) :
this(basicContext, FirCompletionContributorOptions(priority))
protected val prefixMatcher: PrefixMatcher get() = basicContext.prefixMatcher
protected val parameters: CompletionParameters get() = basicContext.parameters
protected val sink: LookupElementSink = basicContext.sink.withPriority(options.priority)
protected val originalKtFile: KtFile get() = basicContext.originalKtFile
protected val fakeKtFile: KtFile get() = basicContext.fakeKtFile
protected val project: Project get() = basicContext.project
protected val targetPlatform: TargetPlatform get() = basicContext.targetPlatform
protected val indexHelper: HLIndexHelper get() = basicContext.indexHelper
protected val symbolFromIndexProvider: KtSymbolFromIndexProvider get() = basicContext.symbolFromIndexProvider
protected val lookupElementFactory: KotlinFirLookupElementFactory get() = basicContext.lookupElementFactory
protected val importStrategyDetector: ImportStrategyDetector get() = basicContext.importStrategyDetector
protected val visibleScope = basicContext.visibleScope
protected val scopeNameFilter: KtScopeNameFilter =
{ name -> !name.isSpecial && prefixMatcher.prefixMatches(name.identifier) }
abstract fun KtAnalysisSession.complete(positionContext: C)
protected fun KtAnalysisSession.addSymbolToCompletion(expectedType: KtType?, symbol: KtSymbol) {
if (symbol !is KtNamedSymbol) return
// Don't offer any hidden deprecated items.
if (symbol.deprecationStatus?.deprecationLevel == DeprecationLevelValue.HIDDEN) return
with(lookupElementFactory) {
createLookupElement(symbol, importStrategyDetector)
.let(sink::addElement)
}
}
protected fun KtAnalysisSession.addClassifierSymbolToCompletion(
symbol: KtClassifierSymbol,
context: WeighingContext,
importingStrategy: ImportStrategy = importStrategyDetector.detectImportStrategy(symbol),
) {
if (symbol !is KtNamedSymbol) return
// Don't offer any deprecated items that could leads to compile errors.
if (symbol.deprecationStatus?.deprecationLevel == DeprecationLevelValue.HIDDEN) return
val lookup = with(lookupElementFactory) {
when (symbol) {
is KtClassLikeSymbol -> createLookupElementForClassLikeSymbol(symbol, importingStrategy)
is KtTypeParameterSymbol -> createLookupElement(symbol, importStrategyDetector)
}
} ?: return
lookup.availableWithoutImport = importingStrategy == ImportStrategy.DoNothing
applyWeighers(context, lookup, symbol, KtSubstitutor.Empty(token))
sink.addElement(lookup)
}
protected fun KtAnalysisSession.addCallableSymbolToCompletion(
context: WeighingContext,
symbol: KtCallableSymbol,
options: CallableInsertionOptions,
substitutor: KtSubstitutor = KtSubstitutor.Empty(token),
priority: ItemPriority? = null,
explicitReceiverTypeHint: KtType? = null,
) {
if (symbol !is KtNamedSymbol) return
// Don't offer any deprecated items that could leads to compile errors.
if (symbol.deprecationStatus?.deprecationLevel == DeprecationLevelValue.HIDDEN) return
val lookup = with(lookupElementFactory) {
createCallableLookupElement(symbol, options, substitutor)
}
priority?.let { lookup.priority = it }
lookup.callableWeight = getCallableMetadata(context, symbol, substitutor)
applyWeighers(context, lookup, symbol, substitutor)
sink.addElement(lookup.adaptToReceiver(context, explicitReceiverTypeHint?.render()))
}
private fun LookupElement.adaptToReceiver(weigherContext: WeighingContext, explicitReceiverTypeHint: String?): LookupElement {
val explicitReceiverRange = weigherContext.explicitReceiver?.textRange
val explicitReceiverText = weigherContext.explicitReceiver?.text
return when (val kind = callableWeight?.kind) {
// Make the text bold if it's immediate member of the receiver
CallableMetadataProvider.CallableKind.ThisClassMember, CallableMetadataProvider.CallableKind.ThisTypeExtension ->
object : LookupElementDecorator<LookupElement>(this) {
override fun renderElement(presentation: LookupElementPresentation) {
super.renderElement(presentation)
presentation.isItemTextBold = true
}
}
// TODO this code should be uncommented when KTIJ-20913 is fixed
//// Make the text gray and insert type cast if the receiver type does not match.
//is CallableMetadataProvider.CallableKind.ReceiverCastRequired -> object : LookupElementDecorator<LookupElement>(this) {
// override fun renderElement(presentation: LookupElementPresentation) {
// super.renderElement(presentation)
// presentation.itemTextForeground = LookupElementFactory.CAST_REQUIRED_COLOR
// // gray all tail fragments too:
// val fragments = presentation.tailFragments
// presentation.clearTail()
// for (fragment in fragments) {
// presentation.appendTailText(fragment.text, true)
// }
// }
//
// override fun handleInsert(context: InsertionContext) {
// super.handleInsert(context)
// if (explicitReceiverRange == null || explicitReceiverText == null) return
// val castType = explicitReceiverTypeHint ?: kind.fullyQualifiedCastType
// val newReceiver = "(${explicitReceiverText} as $castType)"
// context.document.replaceString(explicitReceiverRange.startOffset, explicitReceiverRange.endOffset, newReceiver)
// context.commitDocument()
// shortenReferencesInRange(
// context.file as KtFile,
// explicitReceiverRange.grown(newReceiver.length)
// )
// }
//}
else -> this
}
}
protected fun KtExpression.reference() = when (this) {
is KtDotQualifiedExpression -> selectorExpression?.mainReference
else -> mainReference
}
private fun KtAnalysisSession.applyWeighers(
context: WeighingContext,
lookupElement: LookupElement,
symbol: KtSymbol,
substitutor: KtSubstitutor,
): LookupElement = lookupElement.apply {
with(Weighers) { applyWeighsToLookupElement(context, lookupElement, symbol, substitutor) }
}
}
internal var LookupElement.availableWithoutImport: Boolean by NotNullableUserDataProperty(Key("KOTLIN_AVAILABLE_FROM_CURRENT_SCOPE"), true)
internal fun <C : FirRawPositionCompletionContext> KtAnalysisSession.complete(
contextContributor: FirCompletionContributorBase<C>,
positionContext: C,
) {
with(contextContributor) {
complete(positionContext)
}
}
internal var LookupElement.callableWeight by UserDataProperty(Key<CallableMetadataProvider.CallableMetadata>("KOTLIN_CALLABlE_WEIGHT"))
private set
| apache-2.0 | 0e4e8a8603bdfcec014467755c5e0b55 | 50.810256 | 158 | 0.732555 | 5.25924 | false | false | false | false |
jk1/intellij-community | uast/uast-common/src/org/jetbrains/uast/UastLanguagePlugin.kt | 4 | 4946 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast
import com.intellij.lang.Language
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.psi.*
interface UastLanguagePlugin {
companion object {
val extensionPointName: ExtensionPointName<UastLanguagePlugin> =
ExtensionPointName.create<UastLanguagePlugin>("org.jetbrains.uast.uastLanguagePlugin")
private val extensionArray: Array<UastLanguagePlugin> by lazy(LazyThreadSafetyMode.PUBLICATION) { extensionPointName.extensions }
fun getInstances(): Collection<UastLanguagePlugin> = extensionArray.toList()
fun byLanguage(language: Language): UastLanguagePlugin? = extensionArray.firstOrNull { it.language === language }
}
data class ResolvedMethod(val call: UCallExpression, val method: PsiMethod)
data class ResolvedConstructor(val call: UCallExpression, val constructor: PsiMethod, val clazz: PsiClass)
val language: Language
/**
* Checks if the file with the given [fileName] is supported.
*
* @param fileName the source file name.
* @return true, if the file is supported by this converter, false otherwise.
*/
fun isFileSupported(fileName: String): Boolean
/**
* Returns the converter priority. Might be positive, negative or 0 (Java's is 0).
* UastConverter with the higher priority will be queried earlier.
*
* Priority is useful when a language N wraps its own elements (NElement) to, for example, Java's PsiElements,
* and Java resolves the reference to such wrapped PsiElements, not the original NElement.
* In this case N implementation can handle such wrappers in UastConverter earlier than Java's converter,
* so N language converter will have a higher priority.
*/
val priority: Int
/**
* Converts a PSI element, the parent of which already has an UAST representation, to UAST.
*
* @param element the element to convert
* @param parent the parent as an UAST element, or null if the element is a file
* @param requiredType the expected type of the result.
* @return the converted element, or null if the element isn't supported or doesn't match the required result type.
*/
fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>? = null): UElement?
/**
* Converts a PSI element, along with its chain of parents, to UAST.
*
* @param element the element to convert
* @param requiredType the expected type of the result.
* @return the converted element, or null if the element isn't supported or doesn't match the required result type.
*/
fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement?
fun getMethodCallExpression(
element: PsiElement,
containingClassFqName: String?,
methodName: String
): ResolvedMethod?
fun getConstructorCallExpression(
element: PsiElement,
fqName: String
): ResolvedConstructor?
fun getMethodBody(element: PsiMethod): UExpression? {
if (element is UMethod) return element.uastBody
return (convertElementWithParent(element, null) as? UMethod)?.uastBody
}
fun getInitializerBody(element: PsiClassInitializer): UExpression {
if (element is UClassInitializer) return element.uastBody
return (convertElementWithParent(element, null) as? UClassInitializer)?.uastBody ?: UastEmptyExpression(null)
}
fun getInitializerBody(element: PsiVariable): UExpression? {
if (element is UVariable) return element.uastInitializer
return (convertElementWithParent(element, null) as? UVariable)?.uastInitializer
}
/**
* Returns true if the expression value is used.
* Do not rely on this property too much, its value can be approximate in some cases.
*/
fun isExpressionValueUsed(element: UExpression): Boolean
}
inline fun <reified T : UElement> UastLanguagePlugin.convertOpt(element: PsiElement?, parent: UElement?): T? {
if (element == null) return null
return convertElement(element, parent) as? T
}
inline fun <reified T : UElement> UastLanguagePlugin.convert(element: PsiElement, parent: UElement?): T {
return convertElement(element, parent, T::class.java) as T
}
inline fun <reified T : UElement> UastLanguagePlugin.convertWithParent(element: PsiElement?): T? {
if (element == null) return null
return convertElementWithParent(element, T::class.java) as? T
} | apache-2.0 | 0fa8be8725fffa2b50f5754299ec0d5b | 39.884298 | 133 | 0.748888 | 4.701521 | false | false | false | false |
brianwernick/PlaylistCore | library/src/main/kotlin/com/devbrackets/android/playlistcore/components/audiofocus/DefaultAudioFocusProvider.kt | 1 | 4259 | /*
* Copyright (C) 2016 - 2017 Brian Wernick
*
* 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.devbrackets.android.playlistcore.components.audiofocus
import android.content.Context
import android.media.AudioManager
import com.devbrackets.android.playlistcore.api.PlaylistItem
import com.devbrackets.android.playlistcore.components.playlisthandler.PlaylistHandler
import com.devbrackets.android.playlistcore.util.SimplifiedAudioManager
open class DefaultAudioFocusProvider<I : PlaylistItem>(context: Context) : AudioFocusProvider<I>, AudioManager.OnAudioFocusChangeListener {
companion object {
const val AUDIOFOCUS_NONE = 0
}
protected var pausedForFocusLoss = false
protected var currentAudioFocus = AUDIOFOCUS_NONE
protected var handler: PlaylistHandler<I>? = null
protected var audioManager = SimplifiedAudioManager(context)
override fun setPlaylistHandler(playlistHandler: PlaylistHandler<I>) {
handler = playlistHandler
}
override fun refreshFocus() {
if (handler?.currentMediaPlayer?.handlesOwnAudioFocus != false) {
return
}
handleFocusChange(currentAudioFocus)
}
override fun requestFocus(): Boolean {
if (handler?.currentMediaPlayer?.handlesOwnAudioFocus != false) {
return false
}
if (currentAudioFocus == AudioManager.AUDIOFOCUS_GAIN) {
return true
}
val status = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN)
return AudioManager.AUDIOFOCUS_REQUEST_GRANTED == status
}
override fun abandonFocus(): Boolean {
if (handler?.currentMediaPlayer?.handlesOwnAudioFocus != false) {
return false
}
if (currentAudioFocus == AUDIOFOCUS_NONE) {
return true
}
val status = audioManager.abandonAudioFocus(this)
if (AudioManager.AUDIOFOCUS_REQUEST_GRANTED == status) {
currentAudioFocus = AUDIOFOCUS_NONE
}
return AudioManager.AUDIOFOCUS_REQUEST_GRANTED == status
}
override fun onAudioFocusChange(focusChange: Int) {
if (currentAudioFocus == focusChange) {
return
}
handleFocusChange(focusChange)
}
open fun handleFocusChange(newFocus: Int) {
currentAudioFocus = newFocus
if (handler?.currentMediaPlayer?.handlesOwnAudioFocus != false) {
return
}
when (newFocus) {
AudioManager.AUDIOFOCUS_GAIN -> onFocusGained()
AudioManager.AUDIOFOCUS_LOSS -> onFocusLoss()
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> onFocusLossTransient()
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> onFocusLossTransientCanDuck()
}
}
open fun onFocusGained() {
handler?.currentMediaPlayer?.let {
if (pausedForFocusLoss && !it.isPlaying) {
pausedForFocusLoss = false
handler?.play()
} else {
it.setVolume(1.0f, 1.0f)
}
}
}
open fun onFocusLoss() {
handler?.currentMediaPlayer?.let {
if (it.isPlaying) {
pausedForFocusLoss = true
handler?.pause(false)
}
}
}
open fun onFocusLossTransient() {
handler?.currentMediaPlayer?.let {
if (it.isPlaying) {
pausedForFocusLoss = true
handler?.pause(true)
}
}
}
open fun onFocusLossTransientCanDuck() {
handler?.currentMediaPlayer?.let {
if (it.isPlaying) {
it.setVolume(0.1f, 0.1f)
}
}
}
} | apache-2.0 | 079ef5608e14e333d1a81e08662ef60a | 30.323529 | 139 | 0.643109 | 4.806998 | false | false | false | false |
AsamK/TextSecure | core-util/src/main/java/org/signal/core/util/FontUtil.kt | 2 | 1225 | package org.signal.core.util
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import kotlin.math.abs
object FontUtil {
private const val SAMPLE_EMOJI = "\uD83C\uDF0D" // 🌍
/**
* Certain platforms cannot render emoji above a certain font size.
*
* This will attempt to render an emoji at the specified font size and tell you if it's possible.
* It does this by rendering an emoji into a 1x1 bitmap and seeing if the resulting pixel is non-transparent.
*
* https://stackoverflow.com/a/50988748
*/
@JvmStatic
fun canRenderEmojiAtFontSize(size: Float): Boolean {
val bitmap: Bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val paint = Paint()
paint.textSize = size
paint.textAlign = Paint.Align.CENTER
val ascent: Float = abs(paint.ascent())
val descent: Float = abs(paint.descent())
val halfHeight = (ascent + descent) / 2.0f
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
canvas.drawText(SAMPLE_EMOJI, 0.5f, 0.5f + halfHeight - descent, paint)
return bitmap.getPixel(0, 0) != 0
}
} | gpl-3.0 | b0c2e1fdee59af9b5cc732d3ea35d4a0 | 29.575 | 111 | 0.716858 | 3.771605 | false | false | false | false |
codebutler/farebot | farebot-app/src/main/java/com/codebutler/farebot/app/feature/keys/add/AddKeyScreenView.kt | 1 | 2662 | /*
* AddKeyScreenView.kt
*
* This file is part of FareBot.
* Learn more at: https://codebutler.github.io/farebot/
*
* Copyright (C) 2017 Eric Butler <[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.codebutler.farebot.app.feature.keys.add
import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import android.widget.Button
import android.widget.TextView
import com.codebutler.farebot.R
import com.codebutler.farebot.app.core.kotlin.bindView
import com.codebutler.farebot.base.util.ByteUtils
import com.wealthfront.magellan.BaseScreenView
@SuppressLint("ViewConstructor")
class AddKeyScreenView(context: Context, private val listener: Listener) :
BaseScreenView<AddKeyScreen>(context) {
private val cardTypeTextView: TextView by bindView(R.id.card_type)
private val contentView: View by bindView(R.id.content)
private val importFileButton: Button by bindView(R.id.import_file)
private val keyDataTextView: TextView by bindView(R.id.key_data)
private val saveButton: Button by bindView(R.id.save)
private val splashView: View by bindView(R.id.splash)
private val tagIdTextView: TextView by bindView(R.id.tag_id)
init {
inflate(context, R.layout.screen_keys_add, this)
importFileButton.setOnClickListener { listener.onImportFile() }
saveButton.setOnClickListener { listener.onSave() }
}
fun update(tagInfo: AddKeyScreen.TagInfo) {
tagIdTextView.text = ByteUtils.getHexString(tagInfo.tagId)
cardTypeTextView.text = tagInfo.cardType.toString()
keyDataTextView.text = ByteUtils.getHexString(tagInfo.keyData, null)
contentView.visibility = if (tagInfo.tagId != null) View.VISIBLE else View.GONE
splashView.visibility = if (tagInfo.tagId != null) View.GONE else View.VISIBLE
saveButton.isEnabled = tagInfo.tagId != null && tagInfo.cardType != null && tagInfo.keyData != null
}
interface Listener {
fun onImportFile()
fun onSave()
}
}
| gpl-3.0 | c672320b81c35040a51a213407055984 | 38.147059 | 107 | 0.740421 | 4.027231 | false | false | false | false |
jguerinet/MyMartlet-Android | app/src/main/java/model/place/Category.kt | 2 | 2173 | /*
* Copyright 2014-2019 Julien Guerinet
*
* 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.guerinet.mymartlet.model.place
import android.content.Context
import com.google.firebase.firestore.DocumentSnapshot
import com.guerinet.mymartlet.R
import timber.log.Timber
import java.util.Locale
/**
* A type of place that the user can filter by
* @author Julien Guerinet
* @since 1.0.0
*/
data class Category(
val id: Int,
val en: String,
val fr: String
) {
/** Localized category name */
val name: String
get() = if (Locale.getDefault().language == "fr") fr else en
/**
* Constructor used to create the All category. Uses the app [context] to retrieve the necessary String
* Set the same translation for both languages, as this gets regenerated every time the map is opened anyway
*/
constructor(context: Context) : this(ALL, context.getString(R.string.map_all), context.getString(R.string.map_all))
companion object {
/** All of the places */
internal const val ALL = -1
/**
* Converts a Firestore [document] into a [Category] (null if error during the parsing)
*/
fun fromDocument(document: DocumentSnapshot): Category? {
val id = document.id.toInt()
val en = document["en"] as? String
val fr = document["fr"] as? String
return if (en != null && fr != null) {
Category(id, en, fr)
} else {
Timber.tag("LoadCategories").e(Exception("Error parsing Category with id $id. en: $en, fr: $fr"))
null
}
}
}
}
| apache-2.0 | 16a2257cb926d4cbed084725032f0d41 | 31.432836 | 119 | 0.647492 | 4.170825 | false | false | false | false |
nlgcoin/guldencoin-official | src/frontend/android/unity_wallet/app/src/main/java/com/gulden/unity_wallet/TransactionInfoActivity.kt | 2 | 8488 | // Copyright (c) 2018 The Gulden developers
// Authored by: Malcolm MacLeod ([email protected]), Willem de Jonge ([email protected])
// Distributed under the GULDEN software license, see the accompanying
// file COPYING
package com.gulden.unity_wallet
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.gulden.jniunifiedbackend.MonitorListener
import com.gulden.jniunifiedbackend.ILibraryController
import com.gulden.jniunifiedbackend.TransactionRecord
import com.gulden.jniunifiedbackend.TransactionStatus
import com.gulden.unity_wallet.util.AppBaseActivity
import kotlinx.android.synthetic.main.activity_transaction_info.*
import kotlinx.android.synthetic.main.content_transaction_info.*
import kotlinx.android.synthetic.main.transaction_info_item.view.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.textAppearance
import org.jetbrains.anko.textColor
class TransactionInfoActivity : AppBaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_transaction_info)
setSupportActionBar(toolbar)
}
override fun onWalletReady() {
fillTxInfo()
}
private fun fillTxInfo() {
val txHash = intent.getStringExtra(EXTRA_TRANSACTION)
try {
val tx = ILibraryController.getTransaction(txHash)
// transaction id
transactionId.text = tx.txHash
// view transaction in browser
transactionId.onClick {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(Config.BLOCK_EXPLORER_TX_TEMPLATE.format(tx.txHash)))
startActivity(intent)
}
// status
status.text = statusText(tx)
// Amount instantly
amount.text = formatNativeAndLocal(tx.amount, 0.0)
setAmountAndColor(amount, tx.amount, 0.0, true)
// inputs
tx.inputs.forEach { output ->
val v = layoutInflater.inflate(R.layout.transaction_info_item, null)
if (output.address.isNotEmpty())
v.address.text = output.address
else {
v.address.text = getString(R.string.tx_detail_address_unavailable)
v.address.textAppearance = R.style.TxDetailMissing
}
if (output.isMine)
v.subscript.text = getString(R.string.tx_detail_wallet_address)
else {
if (output.label.isNotEmpty())
v.subscript.text = output.label
else
v.subscript.text = getString(R.string.tx_detail_sending_address)
}
from_container.addView(v)
}
// Update amount and display tx output details after getting rate (or failure)
this.launch(Dispatchers.Main) {
var rate = 0.0
try {
rate = fetchCurrencyRate(localCurrency.code)
} catch (e: Throwable) {
// silently ignore failure of getting rate here
}
[email protected](amount, tx.amount, rate, true)
// internal transfer if all inputs and outputs are mine
val internalTransfer = (tx.inputs.size == tx.inputs.count { it.isMine }) && (tx.outputs.size == tx.outputs.count { it.isMine })
// outputs
val signedByMe = tx.fee > 0
tx.outputs.forEach { output ->
if (output.isMine && !signedByMe || internalTransfer) {
val v = layoutInflater.inflate(R.layout.transaction_info_item, null)
v.address.text = output.address
v.subscript.text = getString(R.string.tx_detail_wallet_address)
v.amount.textColor = ContextCompat.getColor(this@TransactionInfoActivity, R.color.change_positive)
v.amount.text = formatNativeAndLocal(output.amount, rate, useNativePrefix = true, nativeFirst = false)
to_container.addView(v)
}
else if (!output.isMine && signedByMe) {
val v = layoutInflater.inflate(R.layout.transaction_info_item, null)
v.address.text = output.address
if (output.label.isNotEmpty())
v.subscript.text = output.label
else
v.subscript.text = getString(R.string.tx_detail_payment_address)
v.amount.textColor = ContextCompat.getColor(this@TransactionInfoActivity, R.color.change_negative)
v.amount.text = formatNativeAndLocal(-output.amount, rate, useNativePrefix = true, nativeFirst = false)
to_container.addView(v)
}
//else {
// output.isMine && signedByMe, this is likely change so don't display
// !output.isMine && !signedByMe, this is likely change for the other side or something else we don't care about
//}
}
// fee
if (signedByMe) { // transaction created by me, show fee
val v = layoutInflater.inflate(R.layout.transaction_info_item, null)
v.address.visibility = View.GONE
v.subscript.text = getString(R.string.tx_detail_network_fee)
[email protected](v.amount, -tx.fee, rate,false)
to_container.addView(v)
}
}
}
catch (e: Throwable)
{
transactionId.text = getString(R.string.no_tx_details).format(txHash)
}
}
private fun setAmountAndColor(textView: TextView, nativeAmount: Long, rate: Double, nativeFirst: Boolean = true) {
textView.textColor = ContextCompat.getColor(this,
if (nativeAmount > 0)
R.color.change_positive
else
R.color.change_negative)
textView.text = formatNativeAndLocal(nativeAmount, rate, true, nativeFirst)
}
private fun statusText(tx: TransactionRecord): String {
return when (tx.status) {
TransactionStatus.ABANDONED -> getString(R.string.tx_status_abandoned)
TransactionStatus.CONFLICTED -> getString(R.string.tx_status_conflicted)
TransactionStatus.CONFIRMING -> getString(R.string.tx_status_confirming)
.format(tx.depth, Constants.RECOMMENDED_CONFIRMATIONS)
TransactionStatus.UNCONFIRMED -> getString(R.string.tx_status_unconfirmed)
TransactionStatus.CONFIRMED -> getString(R.string.tx_status_confirmed)
.format(tx.height, java.text.SimpleDateFormat("HH:mm").format(java.util.Date(tx.blockTime * 1000L)))
else -> getString(R.string.tx_status_unknown)
}
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
override fun onResume() {
super.onResume()
ILibraryController.RegisterMonitorListener(monitoringListener)
}
override fun onPause() {
ILibraryController.UnregisterMonitorListener(monitoringListener)
super.onPause()
}
private val monitoringListener = object: MonitorListener() {
override fun onPruned(height: Int) {}
override fun onProcessedSPVBlocks(height: Int) {}
override fun onPartialChain(height: Int, probableHeight: Int, offset: Int) {
runOnUiThread {
val txHash = intent.getStringExtra(EXTRA_TRANSACTION)
try {
val tx = ILibraryController.getTransaction(txHash)
status.text = statusText(tx)
}
catch (e: Throwable)
{
// silently ignore
}
}
}
}
companion object {
const val EXTRA_TRANSACTION = "transaction"
}
}
| mit | 0d34fefb14fc0afa40493b2849e95b5b | 41.019802 | 143 | 0.59484 | 4.726058 | false | false | false | false |
android/project-replicator | model/src/test/kotlin/com/android/gradle/replicator/model/internal/ModuleAdapterTest.kt | 1 | 12245 | /*
* 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.android.gradle.replicator.model.internal
import com.android.gradle.replicator.model.*
import com.android.gradle.replicator.model.internal.fixtures.module
import com.android.gradle.replicator.model.internal.filedata.AbstractAndroidResourceProperties
import com.android.gradle.replicator.model.internal.filedata.DefaultAndroidResourceProperties
import com.android.gradle.replicator.model.internal.filedata.ValuesAndroidResourceProperties
import com.android.gradle.replicator.model.internal.filedata.ResourcePropertyType
import com.android.gradle.replicator.model.internal.filedata.ValuesMap
import com.google.common.truth.Truth
import org.junit.Test
internal class ModuleAdapterTest {
@Test
fun `test write empty module`() {
Truth.assertThat(emptyModuleObject().toJson()).isEqualTo(EMPTY_MODULE)
}
@Test
fun `test load empty module`() {
val module = emptyModuleObject()
val loadedModule = EMPTY_MODULE.fromJson(ModuleAdapter())
Truth.assertThat(loadedModule).isEqualTo(module)
}
@Test
fun `test load + write empty module`() {
val loadedModule = EMPTY_MODULE.fromJson(ModuleAdapter())
Truth.assertThat(loadedModule.toJson()).isEqualTo(EMPTY_MODULE)
}
@Test
fun `test write full module`() {
Truth.assertThat(fullModuleObject().toJson()).isEqualTo(FULL_MODULE)
}
@Test
fun `test load full module`() {
val module = fullModuleObject()
val loadedModule = FULL_MODULE.fromJson(ModuleAdapter())
assertModuleInfoEquals(loadedModule, module)
}
@Test
fun `test load + write full module`() {
val loadedModule = FULL_MODULE.fromJson(ModuleAdapter())
Truth.assertThat(loadedModule.toJson()).isEqualTo(FULL_MODULE)
}
// --------------------------
/**
* this should match [EMPTY_MODULE]
*/
private fun emptyModuleObject() = module {
path = ":foo"
}
/**
* this should match [FULL_MODULE]
*/
private fun fullModuleObject() = module {
path = ":foo"
plugins = listOf(PluginType.ANDROID_APP, PluginType.KOTLIN_ANDROID)
javaSources {
fileCount = 1
}
kotlinSources {
fileCount = 2
}
androidResources {
resourceMap = mutableMapOf(
"mipmap" to mutableListOf<AbstractAndroidResourceProperties>(
DefaultAndroidResourceProperties(
qualifiers = "",
extension = ".xml",
quantity = 3,
fileData = listOf(64, 128, 256)
),
DefaultAndroidResourceProperties(
qualifiers = "",
extension = ".png",
quantity = 2,
fileData = listOf(512, 1024)
),
DefaultAndroidResourceProperties(
qualifiers = "hidpi",
extension = ".xml",
quantity = 3,
fileData = listOf(2048, 4096, 8192)
),
DefaultAndroidResourceProperties(
qualifiers = "hidpi",
extension = ".png",
quantity = 2,
fileData = listOf(16384, 32768)
)
),
"values" to mutableListOf<AbstractAndroidResourceProperties>(
ValuesAndroidResourceProperties(
qualifiers = "",
extension = ".xml",
quantity = 5,
valuesMapPerFile = listOf(
ValuesMap(stringCount = 5),
ValuesMap(stringCount = 2, intCount = 6),
ValuesMap(stringCount = 2, intCount = 6, colorCount = 1),
ValuesMap(stringCount = 2, intCount = 6, colorCount = 2, dimenCount = 1),
ValuesMap(stringCount = 2, intCount = 6, colorCount = 3, dimenCount = 2, idCount = 1)
)
)
)
)
}
javaResources {
fileData = mapOf("json" to listOf<Long>(3, 4, 5))
}
assets {
fileData = mapOf("png" to listOf<Long>(3, 4, 5))
}
dependencies = listOf(
DefaultDependenciesInfo(DependencyType.MODULE, "module1", "api"),
DefaultDependenciesInfo(DependencyType.MODULE, "module2", "implementation"),
DefaultDependenciesInfo(DependencyType.EXTERNAL_LIBRARY, "lib:foo:1.0", "api")
)
android {
compileSdkVersion = "android-30"
minSdkVersion = 24
targetSdkVersion = 30
buildFeatures {
androidResources = true
compose = true
}
}
}
private fun assertModuleInfoEquals(subj: DefaultModuleInfo, obj: DefaultModuleInfo) {
Truth.assertThat(subj.path).isEqualTo(obj.path)
Truth.assertThat(subj.plugins).isEqualTo(obj.plugins)
Truth.assertThat(subj.javaSources).isEqualTo(obj.javaSources)
Truth.assertThat(subj.kotlinSources).isEqualTo(obj.kotlinSources)
Truth.assertThat(subj.javaResources).isEqualTo(obj.javaResources)
Truth.assertThat(subj.dependencies).isEqualTo(obj.dependencies)
Truth.assertThat(subj.android).isEqualTo(obj.android)
// Manually compare resources
subj.androidResources?.resourceMap?.forEach { subjResourceType ->
Truth.assertThat(obj.androidResources!!.resourceMap).containsKey(subjResourceType.key)
val objResourceType = obj.androidResources!!.resourceMap.get(subjResourceType.key)!!
subjResourceType.value.forEachIndexed { index, subjResourceProperties ->
val objResourceProperties = objResourceType[index]
Truth.assertThat(subjResourceProperties.propertyType).isEqualTo(objResourceProperties.propertyType)
Truth.assertThat(subjResourceProperties.qualifiers).isEqualTo(objResourceProperties.qualifiers)
Truth.assertThat(subjResourceProperties.extension).isEqualTo(objResourceProperties.extension)
Truth.assertThat(subjResourceProperties.quantity).isEqualTo(objResourceProperties.quantity)
when (subjResourceProperties.propertyType) {
ResourcePropertyType.VALUES -> {
val realSubjProperties = subjResourceProperties as ValuesAndroidResourceProperties
val realObjProperties = objResourceProperties as ValuesAndroidResourceProperties
Truth.assertThat(realSubjProperties.valuesMapPerFile).isEqualTo(realObjProperties.valuesMapPerFile)
}
ResourcePropertyType.DEFAULT -> {
val realSubjProperties = subjResourceProperties as DefaultAndroidResourceProperties
val realObjProperties = objResourceProperties as DefaultAndroidResourceProperties
Truth.assertThat(realSubjProperties.fileData).isEqualTo(realObjProperties.fileData)
}
}
}
}
}
}
private val EMPTY_MODULE = """
{
"path": ":foo",
"plugins": [],
"dependencies": []
}
""".trimIndent()
private val FULL_MODULE = """
{
"path": ":foo",
"plugins": [
"com.android.application",
"org.jetbrains.kotlin.android"
],
"javaSources": {
"fileCount": 1
},
"kotlinSources": {
"fileCount": 2
},
"androidResources": {
"mipmap": [
{
"qualifiers": "",
"extension": ".xml",
"quantity": 3,
"fileData": [
64,
128,
256
]
},
{
"qualifiers": "",
"extension": ".png",
"quantity": 2,
"fileData": [
512,
1024
]
},
{
"qualifiers": "hidpi",
"extension": ".xml",
"quantity": 3,
"fileData": [
2048,
4096,
8192
]
},
{
"qualifiers": "hidpi",
"extension": ".png",
"quantity": 2,
"fileData": [
16384,
32768
]
}
],
"values": [
{
"qualifiers": "",
"extension": ".xml",
"quantity": 5,
"valuesFileList": [
{
"stringCount": 5,
"intCount": 0,
"boolCount": 0,
"colorCount": 0,
"dimenCount": 0,
"idCount": 0,
"integerArrayCount": [],
"arrayCount": [],
"styleCount": []
},
{
"stringCount": 2,
"intCount": 6,
"boolCount": 0,
"colorCount": 0,
"dimenCount": 0,
"idCount": 0,
"integerArrayCount": [],
"arrayCount": [],
"styleCount": []
},
{
"stringCount": 2,
"intCount": 6,
"boolCount": 0,
"colorCount": 1,
"dimenCount": 0,
"idCount": 0,
"integerArrayCount": [],
"arrayCount": [],
"styleCount": []
},
{
"stringCount": 2,
"intCount": 6,
"boolCount": 0,
"colorCount": 2,
"dimenCount": 1,
"idCount": 0,
"integerArrayCount": [],
"arrayCount": [],
"styleCount": []
},
{
"stringCount": 2,
"intCount": 6,
"boolCount": 0,
"colorCount": 3,
"dimenCount": 2,
"idCount": 1,
"integerArrayCount": [],
"arrayCount": [],
"styleCount": []
}
]
}
]
},
"javaResources": {
"json": [
3,
4,
5
]
},
"assets": {
"png": [
3,
4,
5
]
},
"dependencies": [
{
"moduleName": "module1",
"method": "api"
},
{
"moduleName": "module2",
"method": "implementation"
},
{
"library": "lib:foo:1.0",
"method": "api"
}
],
"android": {
"compileSdkVersion": "android-30",
"minSdkVersion": 24,
"targetSdkVersion": 30,
"buildFeatures": {
"androidResources": true,
"compose": true
}
}
}
""".trimIndent()
| apache-2.0 | 0beef7acf5507909d808ec9704f56159 | 32.365123 | 123 | 0.493018 | 5.319288 | false | false | false | false |
Frederikam/FredBoat | FredBoat/src/main/java/fredboat/audio/queue/IdentifierContext.kt | 1 | 1699 | /*
* MIT License
*
* Copyright (c) 2017 Frederik Ar. Mikkelsen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package fredboat.audio.queue
import fredboat.messaging.internal.Context
import fredboat.sentinel.Guild
import fredboat.sentinel.Member
import fredboat.sentinel.TextChannel
import fredboat.sentinel.User
class IdentifierContext(
val identifier: String,
override val textChannel: TextChannel,
override val member: Member
) : Context() {
override val guild: Guild
get() = member.guild
override val user: User
get() = member.user
var isQuiet = false
var isPriority = false
var position = 0L
}
| mit | 483d73d309f15260adcfd3e3914c6482 | 35.934783 | 81 | 0.743378 | 4.542781 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/analytics/aggregated/internal/evaluator/indicatorengine/IndicatorEngine.kt | 1 | 6416 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.indicatorengine
import javax.inject.Inject
import org.hisp.dhis.android.core.analytics.aggregated.MetadataItem
import org.hisp.dhis.android.core.analytics.aggregated.internal.AnalyticsServiceEvaluationItem
import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.DataElementSQLEvaluator
import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.EventDataItemSQLEvaluator
import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.ProgramIndicatorSQLEvaluator
import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore
import org.hisp.dhis.android.core.arch.helpers.UidsHelper.mapByUid
import org.hisp.dhis.android.core.category.internal.CategoryOptionComboStore
import org.hisp.dhis.android.core.constant.Constant
import org.hisp.dhis.android.core.dataelement.DataElement
import org.hisp.dhis.android.core.indicator.Indicator
import org.hisp.dhis.android.core.indicator.IndicatorType
import org.hisp.dhis.android.core.parser.internal.expression.CommonExpressionVisitor
import org.hisp.dhis.android.core.parser.internal.expression.CommonParser
import org.hisp.dhis.android.core.parser.internal.expression.ParserUtils
import org.hisp.dhis.android.core.parser.internal.service.ExpressionService
import org.hisp.dhis.android.core.program.ProgramIndicatorCollectionRepository
import org.hisp.dhis.android.core.program.internal.ProgramStoreInterface
import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttribute
@Suppress("LongParameterList")
internal class IndicatorEngine @Inject constructor(
private val indicatorTypeStore: IdentifiableObjectStore<IndicatorType>,
private val dataElementStore: IdentifiableObjectStore<DataElement>,
private val trackedEntityAttributeStore: IdentifiableObjectStore<TrackedEntityAttribute>,
private val categoryOptionComboStore: CategoryOptionComboStore,
private val programStore: ProgramStoreInterface,
private val programIndicatorRepository: ProgramIndicatorCollectionRepository,
private val dataElementEvaluator: DataElementSQLEvaluator,
private val programIndicatorEvaluator: ProgramIndicatorSQLEvaluator,
private val eventDataItemEvaluator: EventDataItemSQLEvaluator,
private val constantStore: IdentifiableObjectStore<Constant>,
private val expressionService: ExpressionService
) {
fun evaluateIndicator(
indicator: Indicator,
contextEvaluationItem: AnalyticsServiceEvaluationItem,
contextMetadata: Map<String, MetadataItem>
): String? {
val indicatorContext = IndicatorContext(
dataElementStore = dataElementStore,
trackedEntityAttributeStore = trackedEntityAttributeStore,
categoryOptionComboStore = categoryOptionComboStore,
programStore = programStore,
programIndicatorRepository = programIndicatorRepository,
dataElementEvaluator = dataElementEvaluator,
programIndicatorEvaluator = programIndicatorEvaluator,
eventDataItemEvaluator = eventDataItemEvaluator,
evaluationItem = contextEvaluationItem,
contextMetadata = contextMetadata
)
val indicatorType = indicator.indicatorType()?.let {
indicatorTypeStore.selectByUid(it.uid())
}
val visitor = newVisitor(indicatorContext)
IndicatorParserUtils.getDays(contextEvaluationItem, contextMetadata)?.let {
visitor.days = it.toDouble()
}
val numerator = evaluate(indicator.numerator()!!, visitor)
val denominator = evaluate(indicator.denominator()!!, visitor)
return if (numerator != null && denominator != null) {
val formula = "${indicatorType?.factor() ?: 1} * $numerator / $denominator"
expressionService.getExpressionValue(formula)?.let {
val valueStr = it.toString()
IndicatorParserUtils.roundValue(valueStr, indicator.decimals())
}
} else {
null
}
}
private fun evaluate(expression: String, visitor: CommonExpressionVisitor): Any? {
return CommonParser.visit(expression, visitor)
}
private val constantMap: Map<String, Constant>
get() {
val constants = constantStore.selectAll()
return mapByUid(constants)
}
private fun newVisitor(indicatorContext: IndicatorContext): CommonExpressionVisitor {
return CommonExpressionVisitor.newBuilder()
.withItemMap(IndicatorParserUtils.INDICATOR_EXPRESSION_ITEMS)
.withItemMethod(ParserUtils.ITEM_EVALUATE)
.withConstantMap(constantMap)
.withIndicatorContext(indicatorContext)
.buildForAnalyticsIndicator()
}
}
| bsd-3-clause | e487269484e788ad1b530fc4b5b909d9 | 49.920635 | 102 | 0.760754 | 5.000779 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/injection/src/org/jetbrains/kotlin/idea/injection/InjectionInfo.kt | 6 | 1271 | // 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.injection
import org.intellij.plugins.intelliLang.inject.LanguageInjectionSupport
import org.intellij.plugins.intelliLang.inject.config.BaseInjection
internal class InjectionInfo(val languageId: String?, val prefix: String?, val suffix: String?) {
fun toBaseInjection(injectionSupport: LanguageInjectionSupport): BaseInjection? {
if (languageId == null) return null
val baseInjection = BaseInjection(injectionSupport.id)
baseInjection.injectedLanguageId = languageId
if (prefix != null) {
baseInjection.prefix = prefix
}
if (suffix != null) {
baseInjection.suffix = suffix
}
return baseInjection
}
companion object {
fun fromBaseInjection(baseInjection: BaseInjection?): InjectionInfo? {
if (baseInjection == null) {
return null
}
return InjectionInfo(
baseInjection.injectedLanguageId,
baseInjection.prefix,
baseInjection.suffix
)
}
}
} | apache-2.0 | df2f4fc5b94098319a41d2bede480735 | 31.615385 | 158 | 0.653029 | 5.166667 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/ui/projectTree/MarkdownTreeStructureProvider.kt | 8 | 2677 | // 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.intellij.plugins.markdown.ui.projectTree
import com.intellij.ide.projectView.TreeStructureProvider
import com.intellij.ide.projectView.ViewSettings
import com.intellij.ide.util.treeView.AbstractTreeNode
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile
class MarkdownTreeStructureProvider(private val project: Project) : TreeStructureProvider {
override fun modify(
parent: AbstractTreeNode<*>,
children: MutableCollection<AbstractTreeNode<*>>,
settings: ViewSettings?
): MutableCollection<AbstractTreeNode<*>> {
if (children.find { it.value is MarkdownFile } == null) {
return children
}
val result = mutableListOf<AbstractTreeNode<*>>()
val childrenToRemove = mutableListOf<AbstractTreeNode<*>>()
for (child in children) {
val childValue = (child.value as? MarkdownFile)
val childVirtualFile = childValue?.virtualFile
if (childVirtualFile != null && parent.value !is MarkdownFileNode) {
val markdownChildren = findMarkdownFileNodeChildren(childVirtualFile, children)
if (markdownChildren.size <= 1) {
result.add(child)
continue
}
result.add(createMarkdownViewNode(childVirtualFile, markdownChildren, settings))
childrenToRemove.addAll(markdownChildren)
} else {
result.add(child)
}
}
result.removeAll(childrenToRemove)
return result
}
private fun findMarkdownFileNodeChildren(
markdownFile: VirtualFile,
children: MutableCollection<AbstractTreeNode<*>>
): MutableCollection<AbstractTreeNode<*>> {
val fileName = markdownFile.nameWithoutExtension
return children.asSequence().filter { node ->
val file = (node.value as? PsiFile)?.virtualFile
file?.let { it.extension?.lowercase() in extensionsToFold && it.nameWithoutExtension == fileName } == true
}.toMutableList()
}
private fun createMarkdownViewNode(
markdownFile: VirtualFile,
children: MutableCollection<AbstractTreeNode<*>>,
settings: ViewSettings?
): MarkdownViewNode {
val nodeChildren = children.mapNotNull { it.value as? PsiFile }
val markdownNode = MarkdownFileNode(markdownFile.nameWithoutExtension, nodeChildren)
return MarkdownViewNode(project, markdownNode, settings, children)
}
companion object {
private val extensionsToFold = listOf("pdf", "docx", "html", "md")
}
}
| apache-2.0 | 8b64792d1edf6b67811012fa8e5a49d0 | 39.560606 | 158 | 0.734404 | 4.814748 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/columnviewholder/ViewHolderHeaderBase.kt | 1 | 1719 | package jp.juggler.subwaytooter.columnviewholder
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import jp.juggler.subwaytooter.ActMain
import jp.juggler.subwaytooter.api.entity.TootAccountRef
import jp.juggler.subwaytooter.column.Column
import jp.juggler.subwaytooter.table.SavedAccount
import jp.juggler.util.LogCategory
import jp.juggler.util.scan
abstract class ViewHolderHeaderBase(
val activity: ActMain,
val viewRoot: View
) : RecyclerView.ViewHolder(viewRoot) {
companion object {
private val log = LogCategory("HeaderViewHolderBase")
}
internal lateinit var column: Column
internal lateinit var accessInfo: SavedAccount
init {
viewRoot.scan { v ->
try {
if (v is Button) {
// ボタンは太字なので触らない
} else if (v is TextView) {
v.typeface = ActMain.timelineFont
if (!activity.timelineFontSizeSp.isNaN()) {
v.textSize = activity.timelineFontSizeSp
}
val fv = activity.timelineSpacing
if (fv != null) v.setLineSpacing(0f, fv)
}
} catch (ex: Throwable) {
log.trace(ex)
}
}
}
internal open fun bindData(column: Column) {
this.column = column
this.accessInfo = column.accessInfo
}
internal abstract fun showColor()
internal abstract fun onViewRecycled()
internal open fun getAccount(): TootAccountRef? = null
}
| apache-2.0 | 8ee0f526f86c0e08f21a2dd51c66f0c0 | 28.232143 | 64 | 0.608978 | 4.782486 | false | false | false | false |
tommyli/nem12-manager | fenergy-service/src/main/kotlin/co/firefire/fenergy/battery/domain/Battery.kt | 1 | 2893 | // Tommy Li ([email protected]), 2018-04-28
package co.firefire.fenergy.battery.domain
import co.firefire.fenergy.shared.domain.IntervalLength
import co.firefire.fenergy.shared.domain.LoginNmi
import co.firefire.fenergy.shared.domain.UnitOfMeasure
import co.firefire.fenergy.shared.repository.IntervalLengthConverter
import org.hibernate.annotations.GenericGenerator
import org.hibernate.annotations.Parameter
import java.time.Duration
import java.util.*
import javax.persistence.CascadeType
import javax.persistence.Convert
import javax.persistence.EnumType
import javax.persistence.Enumerated
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.JoinColumn
import javax.persistence.ManyToOne
import javax.persistence.MapKey
import javax.persistence.OneToMany
import javax.persistence.OrderBy
//@Entity
data class Battery(
@ManyToOne(optional = false)
@JoinColumn(name = "login_nmi", referencedColumnName = "id", nullable = false)
var loginNmi: LoginNmi = LoginNmi()
) : Comparable<Battery> {
@Id
@GenericGenerator(
name = "BatteryIdSeq",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = arrayOf(
Parameter(name = "sequence_name", value = "battery_id_seq"),
Parameter(name = "initial_value", value = "1000"),
Parameter(name = "increment_size", value = "1")
)
)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "BatteryIdSeq")
var id: Long? = null
var version: Int? = 0
@Enumerated(EnumType.STRING)
var uom: UnitOfMeasure = UnitOfMeasure.KWH
@Convert(converter = IntervalLengthConverter::class)
var intervalLength: IntervalLength = IntervalLength.IL_30
@OneToMany(mappedBy = "battery", cascade = arrayOf(CascadeType.ALL), orphanRemoval = true)
@MapKey(name = "dateInterval")
@OrderBy("dateInterval")
var batteryDayValues: SortedMap<DateInterval, BatteryDayValue> = TreeMap()
fun intervalRange(): IntRange {
return 1..(Duration.ofDays(1).toMinutes().toInt() / intervalLength.minute)
}
fun mergeIntervalDays(newBatteryDays: Collection<BatteryDayValue>) {
newBatteryDays.forEach({ mergeBatteryDay(it) })
}
fun mergeBatteryDay(newBatteryDay: BatteryDayValue) {
batteryDayValues.merge(newBatteryDay.dateInterval, newBatteryDay, { existing: BatteryDayValue, new: BatteryDayValue ->
existing.charge = new.charge
existing.disCharge = new.disCharge
existing.stateOfCharge = new.stateOfCharge
existing
})
}
override fun compareTo(other: Battery) = compareValuesBy(this, other, { it.loginNmi })
override fun toString() = "Battery(id=$id, loginNmi='$loginNmi')"
}
| apache-2.0 | 5416777f357aeab4c150708ebd056eb1 | 34.280488 | 126 | 0.713792 | 4.292285 | false | false | false | false |
tommyli/nem12-manager | fenergy-service/src/main/kotlin/co/firefire/fenergy/nem12/service/Nem12Service.kt | 1 | 1221 | // Tommy Li ([email protected]), 2017-07-03
package co.firefire.fenergy.nem12.service
import co.firefire.fenergy.shared.domain.Login
import co.firefire.fenergy.shared.domain.LoginNmi
import co.firefire.fenergy.shared.repository.LoginNmiRepository
import org.springframework.core.io.Resource
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
interface Nem12Service {
fun uploadNem12(login: Login, nem12Resource: Resource)
}
@Transactional
@Service
class Nem12ServiceImpl(val loginNmiRepo: LoginNmiRepository) : Nem12Service {
@Transactional
override fun uploadNem12(login: Login, nem12Resource: Resource) {
val nmiMeterRegisters = Nem12ParserImpl(login).parseNem12Resource(nem12Resource)
nmiMeterRegisters.forEach { nmr ->
val existingLoginNmi = loginNmiRepo.findByLoginAndNmi(nmr.loginNmi.login, nmr.loginNmi.nmi)
if (existingLoginNmi == null) {
val newLoginNmi = loginNmiRepo.save(LoginNmi(login, nmr.loginNmi.nmi))
newLoginNmi.addNmiMeterRegister(nmr)
} else {
existingLoginNmi.mergeNmiMeterRegister(nmr)
}
}
}
}
| apache-2.0 | 142bc7bda7da5e4540cf16082f1098ca | 33.885714 | 103 | 0.733006 | 3.791925 | false | false | false | false |
airbnb/epoxy | epoxy-modelfactorytest/src/test/java/com/airbnb/epoxy/FromModelPropertiesTest.kt | 1 | 7616 | package com.airbnb.epoxy
import android.view.View
import com.airbnb.epoxymodelfactory.R
import com.airbnb.paris.styles.Style
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Test
/**
* Asserts that using from(ModelProperties) to create a model applies the property values correctly
*/
class FromModelPropertiesTest {
@Test
fun getId() {
val model = TestModelPropertiesViewModel_.from(
TestModelProperties(
id = "100"
)
)
assertFalse(model.hasDefaultId())
}
@Test
fun getBoolean() {
val model = TestModelPropertiesViewModel_.from(
TestModelProperties(
booleanValue = true
)
)
assertEquals(true, model.booleanValue())
}
@Test
fun getBoxedBoolean() {
val model =
TestModelPropertiesViewModel_.from(
TestModelProperties(
boxedBooleanValue = true
)
)
assertEquals(true, model.boxedBooleanValue())
}
@Test
fun getDouble() {
val model = TestModelPropertiesViewModel_.from(
TestModelProperties(
doubleValue = 42.0
)
)
assertEquals(42.0, model.doubleValue(), 0.0)
}
@Test
fun getBoxedDouble() {
val model = TestModelPropertiesViewModel_.from(
TestModelProperties(
boxedDoubleValue = 42.0
)
)
assertEquals(42.0, model.boxedDoubleValue(), 0.0)
}
@Test
fun getDrawableRes() {
val drawableRes = android.R.drawable.alert_dark_frame
val model =
TestModelPropertiesViewModel_.from(
TestModelProperties(
drawableRes = drawableRes
)
)
assertEquals(drawableRes, model.drawableRes())
}
@Test
fun getEpoxyModelList() {
val epoxyModelList = emptyList<EpoxyModel<*>>()
val model =
TestModelPropertiesViewModel_.from(
TestModelProperties(
epoxyModelList = epoxyModelList
)
)
assertEquals(epoxyModelList, model.epoxyModelList())
}
@Test
fun getInt() {
val model = TestModelPropertiesViewModel_.from(
TestModelProperties(
intValue = 51
)
)
assertEquals(51, model.intValue())
}
@Test
fun getBoxedInt() {
val model = TestModelPropertiesViewModel_.from(
TestModelProperties(
boxedIntValue = 51
)
)
assertEquals(51, model.boxedIntValue())
}
@Test
fun getLong() {
val model = TestModelPropertiesViewModel_.from(
TestModelProperties(
longValue = 3000000
)
)
assertEquals(3000000, model.longValue())
}
@Test
fun getBoxedLong() {
val model =
TestModelPropertiesViewModel_.from(
TestModelProperties(
boxedLongValue = 3000000
)
)
assertEquals(3000000, model.boxedLongValue())
}
@Test
fun getOnClickListener() {
val clickListener = View.OnClickListener { }
val model =
TestModelPropertiesViewModel_.from(
TestModelProperties(
onClickListener = clickListener
)
)
assertEquals(clickListener, model.onClickListener())
}
@Test
fun getNullOnClickListener() {
val model = TestModelPropertiesViewModel_.from(
TestModelProperties(
onClickListener = null
)
)
assertNull(model.onClickListener())
}
@Test
fun getRawRes() {
// We use an arbitrary int rather than adding a test-only raw resource, which isn't easy
val model =
TestModelPropertiesViewModel_.from(
TestModelProperties(
rawRes = 42
)
)
assertEquals(42, model.rawRes())
}
@Test
fun getString() {
val model =
TestModelPropertiesViewModel_.from(
TestModelProperties(
stringValue = "ModelFactory"
)
)
assertEquals("ModelFactory", model.stringValue())
}
@Test
fun getStringList() {
val stringList = listOf("Model", "Factory")
val model = TestModelPropertiesViewModel_.from(
TestModelProperties(
stringList = stringList
)
)
assertEquals(stringList, model.stringList())
}
class TestModelProperties(
private val id: String = "",
private val booleanValue: Boolean? = null,
private val boxedBooleanValue: Boolean? = null,
private val doubleValue: Double? = null,
private val boxedDoubleValue: Double? = null,
private val drawableRes: Int? = null,
private val epoxyModelList: List<EpoxyModel<*>>? = null,
private val intValue: Int? = null,
private val boxedIntValue: Int? = null,
private val longValue: Long? = null,
private val boxedLongValue: Long? = null,
private val onClickListener: View.OnClickListener? = null,
private val rawRes: Int? = null,
private val stringValue: String? = null,
private val stringList: List<String>? = null,
private val styleValue: Style? = null
) : ModelProperties {
private val propertyNameToValue = mapOf(
"booleanValue" to booleanValue,
"boxedBooleanValue" to boxedBooleanValue,
"doubleValue" to doubleValue,
"boxedDoubleValue" to boxedDoubleValue,
"drawableRes" to drawableRes,
"epoxyModelList" to epoxyModelList,
"intValue" to intValue,
"boxedIntValue" to boxedIntValue,
"longValue" to longValue,
"boxedLongValue" to boxedLongValue,
"onClickListener" to onClickListener,
"rawRes" to rawRes,
"stringList" to stringList,
"stringValue" to stringValue
)
@Suppress("UNCHECKED_CAST")
private fun <T> getValue(propertyName: String): T = propertyNameToValue[propertyName]!! as T
override fun getId() = id
override fun has(propertyName: String) = propertyNameToValue[propertyName] != null
override fun getBoolean(propertyName: String): Boolean = getValue(propertyName)
override fun getDouble(propertyName: String): Double = getValue(propertyName)
override fun getDrawableRes(propertyName: String): Int = getValue(propertyName)
override fun getEpoxyModelList(propertyName: String): List<EpoxyModel<*>> =
getValue(propertyName)
override fun getInt(propertyName: String): Int = getValue(propertyName)
override fun getLong(propertyName: String): Long = getValue(propertyName)
override fun getOnClickListener(propertyName: String): View.OnClickListener =
getValue(propertyName)
override fun getRawRes(propertyName: String): Int = getValue(propertyName)
override fun getString(propertyName: String): String = getValue(propertyName)
override fun getStringList(propertyName: String): List<String> = getValue(propertyName)
override fun getStyle() = styleValue
}
}
| apache-2.0 | 2896238ff1256e992bd1b9726da2a1e9 | 28.866667 | 100 | 0.585347 | 5.374735 | false | true | false | false |
paplorinc/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/ext/logback/LogbackTopLevelMemberContributor.kt | 7 | 2287 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.ext.logback
import com.intellij.psi.*
import com.intellij.psi.CommonClassNames.JAVA_LANG_STRING
import com.intellij.psi.impl.light.LightVariableBuilder
import com.intellij.psi.scope.ElementClassHint
import com.intellij.psi.scope.NameHint
import com.intellij.psi.scope.PsiScopeProcessor
import org.jetbrains.plugins.groovy.GroovyLanguage
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil
class LogbackTopLevelMemberContributor : NonCodeMembersContributor() {
override fun getParentClassName(): String = "logback"
override fun processDynamicElements(qualifierType: PsiType,
aClass: PsiClass?,
processor: PsiScopeProcessor,
place: PsiElement,
state: ResolveState) {
if (!aClass.isLogbackConfig()) return
val scope = place.resolveScope
if (ResolveUtil.shouldProcessProperties(processor.getHint(ElementClassHint.KEY))) {
if (processor.getHint(NameHint.KEY)?.getName(state).let { it == null || it == "hostname" }) {
val variable = LightVariableBuilder<LightVariableBuilder<*>>(
place.manager, "hostname", TypesUtil.createType(JAVA_LANG_STRING, place), GroovyLanguage
)
if (!processor.execute(variable, state)) return
}
}
JavaPsiFacade.getInstance(place.project).findClass(configDelegateFqn, scope)?.processDeclarations(processor, state, null, place)
}
} | apache-2.0 | f490ab153194e91bdc4b0746d06b9650 | 42.169811 | 132 | 0.717971 | 4.60161 | false | false | false | false |
paplorinc/intellij-community | python/src/com/jetbrains/python/inspections/PyOverloadsInspection.kt | 7 | 4274 | // 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.jetbrains.python.inspections
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElementVisitor
import com.intellij.util.Processor
import com.intellij.util.containers.SortedList
import com.jetbrains.python.codeInsight.controlflow.ScopeOwner
import com.jetbrains.python.psi.PyClass
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyFunction
import com.jetbrains.python.psi.PyUtil
import com.jetbrains.python.pyi.PyiFile
import com.jetbrains.python.pyi.PyiUtil
import java.util.*
class PyOverloadsInspection : PyInspection() {
override fun buildVisitor(holder: ProblemsHolder,
isOnTheFly: Boolean,
session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, session)
private class Visitor(holder: ProblemsHolder, session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) {
override fun visitPyClass(node: PyClass?) {
if (node?.containingFile is PyiFile) return
super.visitPyClass(node)
if (node != null) {
processScope(node, { node.visitMethods(it, false, myTypeEvalContext) })
}
}
override fun visitPyFile(node: PyFile?) {
if (node is PyiFile) return
super.visitPyFile(node)
if (node != null) {
processScope(node, { processor -> node.topLevelFunctions.forEach { processor.process(it) } })
}
}
private fun processScope(owner: ScopeOwner, processorUsage: (GroupingFunctionsByNameProcessor) -> Unit) {
val processor = GroupingFunctionsByNameProcessor()
processorUsage(processor)
processor.result.values.forEach { processSameNameFunctions(owner, it) }
}
private fun processSameNameFunctions(owner: ScopeOwner, functions: List<PyFunction>) {
if (functions.find { PyiUtil.isOverload(it, myTypeEvalContext) } == null) return
val implementation = functions.lastOrNull { !PyiUtil.isOverload(it, myTypeEvalContext) }
if (implementation == null) {
functions
.maxBy { it.textOffset }
?.let {
registerProblem(it.nameIdentifier,
"A series of @overload-decorated ${chooseBetweenFunctionsAndMethods(owner)} " +
"should always be followed by an implementation that is not @overload-ed")
}
}
else {
if (implementation != functions.last()) {
registerProblem(functions.last().nameIdentifier,
"A series of @overload-decorated ${chooseBetweenFunctionsAndMethods(owner)} " +
"should always be followed by an implementation that is not @overload-ed")
}
functions
.asSequence()
.filter { isIncompatibleOverload(implementation, it) }
.forEach {
registerProblem(it.nameIdentifier,
"Signature of this @overload-decorated ${chooseBetweenFunctionAndMethod(owner)} " +
"is not compatible with the implementation")
}
}
}
private fun chooseBetweenFunctionsAndMethods(owner: ScopeOwner) = if (owner is PyClass) "methods" else "functions"
private fun chooseBetweenFunctionAndMethod(owner: ScopeOwner) = if (owner is PyClass) "method" else "function"
private fun isIncompatibleOverload(implementation: PyFunction, overload: PyFunction): Boolean {
return implementation != overload &&
PyiUtil.isOverload(overload, myTypeEvalContext) &&
!PyUtil.isSignatureCompatibleTo(implementation, overload, myTypeEvalContext)
}
}
private class GroupingFunctionsByNameProcessor : Processor<PyFunction> {
val result: MutableMap<String, MutableList<PyFunction>> = HashMap()
override fun process(t: PyFunction?): Boolean {
val name = t?.name
if (name != null) {
result
.getOrPut(name, { SortedList<PyFunction> { f1, f2 -> f1.textOffset - f2.textOffset } })
.add(t)
}
return true
}
}
} | apache-2.0 | 91c9214b09c11d1b998dcbc805097c58 | 37.863636 | 140 | 0.67548 | 4.759465 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/templateExpressions.kt | 2 | 8494 | // 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.quickfix.createFromUsage.callableBuilder
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.codeInsight.template.Expression
import com.intellij.codeInsight.template.ExpressionContext
import com.intellij.codeInsight.template.Result
import com.intellij.codeInsight.template.TextResult
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.idea.core.CollectingNameValidator
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getValueParameters
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import java.util.*
/**
* Special <code>Expression</code> for parameter names based on its type.
*/
internal class ParameterNameExpression(
private val names: Array<String>,
private val parameterTypeToNamesMap: Map<String, Array<String>>
) : Expression() {
init {
assert(names.all(String::isNotEmpty))
}
override fun calculateResult(context: ExpressionContext?): Result? {
val lookupItems = calculateLookupItems(context) ?: return null
return TextResult(if (lookupItems.isEmpty()) "" else lookupItems.first().lookupString)
}
override fun calculateQuickResult(context: ExpressionContext?) = calculateResult(context)
override fun calculateLookupItems(context: ExpressionContext?): Array<LookupElement>? {
context ?: return null
val names = LinkedHashSet(this.names.toList())
// find the parameter list
val project = context.project ?: return null
val offset = context.startOffset
val editor = context.editor ?: return null
val document = editor.document
PsiDocumentManager.getInstance(project).commitDocument(document)
val file = PsiDocumentManager.getInstance(project).getPsiFile(document) as KtFile
val elementAt = file.findElementAt(offset)
val declaration = PsiTreeUtil.getParentOfType(elementAt, KtFunction::class.java, KtClass::class.java) ?: return arrayOf()
val parameterList = when (declaration) {
is KtFunction -> declaration.valueParameterList!!
is KtClass -> declaration.getPrimaryConstructorParameterList()!!
else -> throw KotlinExceptionWithAttachments("Unexpected declaration kind: ${declaration::class.java}")
.withPsiAttachment("declaration", declaration)
}
// add names based on selected type
val parameter = elementAt?.getStrictParentOfType<KtParameter>()
if (parameter != null) {
val parameterTypeRef = parameter.typeReference
if (parameterTypeRef != null) {
val suggestedNamesBasedOnType = parameterTypeToNamesMap[parameterTypeRef.text]
if (suggestedNamesBasedOnType != null) {
names.addAll(suggestedNamesBasedOnType)
}
}
}
// remember other parameter names for later use
val parameterNames = parameterList.parameters.mapNotNullTo(HashSet<String>()) { ktParameter ->
if (ktParameter == parameter) null else ktParameter.name
}
// add fallback parameter name
if (names.isEmpty()) {
names.add("arg")
}
// ensure there are no conflicts
val validator = CollectingNameValidator(parameterNames)
return names.map { LookupElementBuilder.create(Fe10KotlinNameSuggester.suggestNameByName(it, validator)) }.toTypedArray()
}
}
/**
* An <code>Expression</code> for type references and delegation specifiers.
*/
internal abstract class TypeExpression(val typeCandidates: List<TypeCandidate>) : Expression() {
class ForTypeReference(typeCandidates: List<TypeCandidate>) : TypeExpression(typeCandidates) {
override val cachedLookupElements: Array<LookupElement> =
typeCandidates.map { LookupElementBuilder.create(it, it.renderedTypes.first()) }.toTypedArray()
}
class ForDelegationSpecifier(typeCandidates: List<TypeCandidate>) : TypeExpression(typeCandidates) {
override val cachedLookupElements: Array<LookupElement> = typeCandidates.map {
val types = it.theType.decomposeIntersection()
val text = (types zip it.renderedTypes).joinToString { (type, renderedType) ->
val descriptor = type.constructor.declarationDescriptor as ClassDescriptor
renderedType + if (descriptor.kind == ClassKind.INTERFACE) "" else "()"
}
LookupElementBuilder.create(it, text)
}.toTypedArray()
}
protected abstract val cachedLookupElements: Array<LookupElement>
override fun calculateResult(context: ExpressionContext?): Result {
val lookupItems = calculateLookupItems(context)
return TextResult(if (lookupItems.size == 0) "" else lookupItems[0].lookupString)
}
override fun calculateQuickResult(context: ExpressionContext?) = calculateResult(context)
override fun calculateLookupItems(context: ExpressionContext?) = cachedLookupElements
}
/**
* A sort-of dummy <code>Expression</code> for parameter lists, to allow us to update the parameter list as the user makes selections.
*/
internal class TypeParameterListExpression(
private val mandatoryTypeParameters: List<RenderedTypeParameter>,
private val parameterTypeToTypeParameterNamesMap: Map<String, List<RenderedTypeParameter>>,
insertLeadingSpace: Boolean
) : Expression() {
private val prefix = if (insertLeadingSpace) " <" else "<"
var currentTypeParameters: List<TypeParameterDescriptor> = Collections.emptyList()
private set
override fun calculateResult(context: ExpressionContext?): Result {
context!!
val project = context.project!!
val offset = context.startOffset
val editor = context.editor!!
val document = editor.document
val documentManager = PsiDocumentManager.getInstance(project)
documentManager.commitDocument(document)
val file = documentManager.getPsiFile(document) as KtFile
val elementAt = file.findElementAt(offset)
val declaration = elementAt?.getStrictParentOfType<KtNamedDeclaration>() ?: return TextResult("")
val renderedTypeParameters = LinkedHashSet<RenderedTypeParameter>()
renderedTypeParameters.addAll(mandatoryTypeParameters)
for (parameter in declaration.getValueParameters()) {
val parameterTypeRef = parameter.typeReference
if (parameterTypeRef != null) {
val typeParameterNamesFromParameter = parameterTypeToTypeParameterNamesMap[parameterTypeRef.text]
if (typeParameterNamesFromParameter != null) {
renderedTypeParameters.addAll(typeParameterNamesFromParameter)
}
}
}
val returnTypeRef = declaration.getReturnTypeReference()
if (returnTypeRef != null) {
val typeParameterNamesFromReturnType = parameterTypeToTypeParameterNamesMap[returnTypeRef.text]
if (typeParameterNamesFromReturnType != null) {
renderedTypeParameters.addAll(typeParameterNamesFromReturnType)
}
}
val sortedRenderedTypeParameters = renderedTypeParameters.sortedBy { if (it.fake) it.typeParameter.index else -1 }
currentTypeParameters = sortedRenderedTypeParameters.map { it.typeParameter }
return TextResult(
if (sortedRenderedTypeParameters.isEmpty()) "" else sortedRenderedTypeParameters.joinToString(", ", prefix, ">") { it.text }
)
}
override fun calculateQuickResult(context: ExpressionContext?): Result = calculateResult(context)
// do not offer the user any choices
override fun calculateLookupItems(context: ExpressionContext?) = arrayOf<LookupElement>()
}
| apache-2.0 | a7affd76bd2a5268eb9ed52388b3e5b6 | 45.928177 | 158 | 0.719684 | 5.451861 | false | false | false | false |
JetBrains/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/lang/parser/MarkdownDefaultFlavour.kt | 1 | 4075 | // 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 org.intellij.plugins.markdown.lang.parser
import org.intellij.markdown.IElementType
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.ast.ASTNode
import org.intellij.markdown.flavours.MarkdownFlavourDescriptor
import org.intellij.markdown.flavours.gfm.GFMFlavourDescriptor
import org.intellij.markdown.flavours.gfm.GFMTokenTypes
import org.intellij.markdown.flavours.gfm.StrikeThroughDelimiterParser
import org.intellij.markdown.html.GeneratingProvider
import org.intellij.markdown.html.HtmlGenerator
import org.intellij.markdown.html.SimpleInlineTagProvider
import org.intellij.markdown.html.TransparentInlineHolderProvider
import org.intellij.markdown.lexer.MarkdownLexer
import org.intellij.markdown.parser.LinkMap
import org.intellij.markdown.parser.MarkerProcessorFactory
import org.intellij.markdown.parser.sequentialparsers.EmphasisLikeParser
import org.intellij.markdown.parser.sequentialparsers.SequentialParser
import org.intellij.markdown.parser.sequentialparsers.SequentialParserManager
import org.intellij.markdown.parser.sequentialparsers.impl.*
import org.intellij.plugins.markdown.lang.parser.blocks.DefinitionListMarkerProvider
import org.intellij.plugins.markdown.lang.parser.blocks.frontmatter.FrontMatterHeaderMarkerProvider
import org.intellij.plugins.markdown.ui.preview.html.HeaderGeneratingProvider
import java.net.URI
open class MarkdownDefaultFlavour: MarkdownFlavourDescriptor {
private val delegate = GFMFlavourDescriptor()
override val markerProcessorFactory: MarkerProcessorFactory
get() = MarkdownDefaultMarkerProcessor.Factory
override val sequentialParserManager: SequentialParserManager = DefaultSequentialParserManager()
override fun createInlinesLexer(): MarkdownLexer {
return delegate.createInlinesLexer()
}
override fun createHtmlGeneratingProviders(linkMap: LinkMap, baseURI: URI?): Map<IElementType, GeneratingProvider> {
val base = delegate.createHtmlGeneratingProviders(linkMap, baseURI)
val result = HashMap(base)
addCustomProviders(result)
return result
}
protected fun addCustomProviders(providers: MutableMap<IElementType, GeneratingProvider>) {
providers[DefinitionListMarkerProvider.DEFINITION_LIST] = SimpleInlineTagProvider("dl")
providers[DefinitionListMarkerProvider.DEFINITION] = SimpleInlineTagProvider("dd")
providers[DefinitionListMarkerProvider.TERM] = SimpleInlineTagProvider("dt")
providers[DefinitionListMarkerProvider.DEFINITION_MARKER] = TransparentInlineHolderProvider()
providers[FrontMatterHeaderMarkerProvider.FRONT_MATTER_HEADER] = ExcludedElementProvider()
providers[MarkdownElementTypes.ATX_1] = HeaderGeneratingProvider("h1")
providers[MarkdownElementTypes.ATX_2] = HeaderGeneratingProvider("h2")
providers[MarkdownElementTypes.ATX_3] = HeaderGeneratingProvider("h3")
providers[MarkdownElementTypes.ATX_4] = HeaderGeneratingProvider("h4")
providers[MarkdownElementTypes.ATX_5] = HeaderGeneratingProvider("h5")
providers[MarkdownElementTypes.ATX_6] = HeaderGeneratingProvider("h6")
providers[MarkdownElementTypes.SETEXT_1] = HeaderGeneratingProvider("h1")
providers[MarkdownElementTypes.SETEXT_2] = HeaderGeneratingProvider("h2")
}
protected class DefaultSequentialParserManager: SequentialParserManager() {
override fun getParserSequence(): List<SequentialParser> {
return listOf(
AutolinkParser(listOf(MarkdownTokenTypes.AUTOLINK, GFMTokenTypes.GFM_AUTOLINK)),
BacktickParser(),
ImageParser(),
InlineLinkParser(),
ReferenceLinkParser(),
EmphasisLikeParser(EmphStrongDelimiterParser(), StrikeThroughDelimiterParser())
)
}
}
private class ExcludedElementProvider: GeneratingProvider {
override fun processNode(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) = Unit
}
}
| apache-2.0 | 7d5f8fbc70e82ed292025be268d33888 | 50.582278 | 140 | 0.820123 | 4.845422 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinInplaceParameterIntroducer.kt | 1 | 10716 | // 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.refactoring.introduce.introduceParameter
import com.intellij.codeInsight.template.impl.TemplateManagerImpl
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.impl.DocumentMarkupModel
import com.intellij.openapi.editor.markup.EffectType
import com.intellij.openapi.editor.markup.HighlighterTargetArea
import com.intellij.openapi.editor.markup.MarkupModel
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.ui.JBColor
import com.intellij.ui.NonFocusableCheckBox
import org.jetbrains.kotlin.idea.base.psi.unifier.toRange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinValVar
import org.jetbrains.kotlin.idea.refactoring.introduce.AbstractKotlinInplaceIntroducer
import org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable.KotlinInplaceVariableIntroducer
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.supertypes
import java.awt.Color
import javax.swing.JCheckBox
class KotlinInplaceParameterIntroducer(
val originalDescriptor: IntroduceParameterDescriptor,
val parameterType: KotlinType,
val suggestedNames: Array<out String>,
project: Project,
editor: Editor
) : AbstractKotlinInplaceIntroducer<KtParameter>(
null,
originalDescriptor.originalRange.elements.single() as KtExpression,
originalDescriptor.occurrencesToReplace.map { it.elements.single() as KtExpression }.toTypedArray(),
INTRODUCE_PARAMETER,
project,
editor
) {
companion object {
private val LOG = Logger.getInstance(KotlinInplaceParameterIntroducer::class.java)
}
enum class PreviewDecorator {
FOR_ADD() {
override val textAttributes: TextAttributes = with(TextAttributes()) {
effectType = EffectType.ROUNDED_BOX
effectColor = JBColor.RED
this
}
},
FOR_REMOVAL() {
override val textAttributes: TextAttributes = with(TextAttributes()) {
effectType = EffectType.STRIKEOUT
effectColor = Color.BLACK
this
}
};
protected abstract val textAttributes: TextAttributes
fun applyToRange(range: TextRange, markupModel: MarkupModel) {
markupModel.addRangeHighlighter(
range.startOffset,
range.endOffset,
0,
textAttributes,
HighlighterTargetArea.EXACT_RANGE
)
}
}
private inner class Preview(addedParameter: KtParameter?, currentName: String?) {
private val _rangesToRemove = ArrayList<TextRange>()
var addedRange: TextRange? = null
private set
var text: String = ""
private set
val rangesToRemove: List<TextRange> get() = _rangesToRemove
init {
val templateState = TemplateManagerImpl.getTemplateState(myEditor)
val currentType = if (templateState?.template != null) {
templateState.getVariableValue(KotlinInplaceVariableIntroducer.TYPE_REFERENCE_VARIABLE_NAME)?.text
} else null
val builder = StringBuilder()
with(descriptor) {
(callable as? KtFunction)?.receiverTypeReference?.let { receiverTypeRef ->
builder.append(receiverTypeRef.text).append('.')
if (!descriptor.withDefaultValue && receiverTypeRef in parametersToRemove) {
_rangesToRemove.add(TextRange(0, builder.length))
}
}
builder.append(callable.name)
val parameters = callable.getValueParameters()
builder.append("(")
for (i in parameters.indices) {
val parameter = parameters[i]
val parameterText = if (parameter == addedParameter) {
val parameterName = currentName ?: parameter.name
val parameterType = currentType ?: parameter.typeReference!!.text
descriptor = descriptor.copy(newParameterName = parameterName!!, newParameterTypeText = parameterType)
val modifier = if (valVar != KotlinValVar.None) "${valVar.keywordName} " else ""
val defaultValue = if (withDefaultValue) {
" = ${if (newArgumentValue is KtProperty) newArgumentValue.name else newArgumentValue.text}"
} else ""
"$modifier$parameterName: $parameterType$defaultValue"
} else {
parameter.allChildren.toList()
.dropLastWhile { it is PsiComment || it is PsiWhiteSpace }
.joinToString(separator = "") { it.text }
}
builder.append(parameterText)
val range = TextRange(builder.length - parameterText.length, builder.length)
if (parameter == addedParameter) {
addedRange = range
} else if (!descriptor.withDefaultValue && parameter in parametersToRemove) {
_rangesToRemove.add(range)
}
if (i < parameters.lastIndex) {
builder.append(", ")
}
}
builder.append(")")
if (addedRange == null) {
LOG.error("Added parameter not found: ${callable.getElementTextWithContext()}")
}
}
text = builder.toString()
}
}
private var descriptor = originalDescriptor
private var replaceAllCheckBox: JCheckBox? = null
init {
initFormComponents {
addComponent(previewComponent)
val defaultValueCheckBox = NonFocusableCheckBox(KotlinBundle.message("checkbox.text.introduce.default.value"))
defaultValueCheckBox.isSelected = descriptor.withDefaultValue
defaultValueCheckBox.addActionListener {
descriptor = descriptor.copy(withDefaultValue = defaultValueCheckBox.isSelected)
updateTitle(variable)
}
addComponent(defaultValueCheckBox)
val occurrenceCount = descriptor.occurrencesToReplace.size
if (occurrenceCount > 1) {
val replaceAllCheckBox = NonFocusableCheckBox(
KotlinBundle.message("checkbox.text.replace.all.occurrences.0", occurrenceCount))
replaceAllCheckBox.isSelected = true
addComponent(replaceAllCheckBox)
[email protected] = replaceAllCheckBox
}
}
}
override fun getActionName() = "IntroduceParameter"
override fun checkLocalScope() = descriptor.callable
override fun getVariable() = originalDescriptor.callable.getValueParameters().lastOrNull()
override fun suggestNames(replaceAll: Boolean, variable: KtParameter?) = suggestedNames
override fun createFieldToStartTemplateOn(replaceAll: Boolean, names: Array<out String>): KtParameter {
return runWriteAction {
with(descriptor) {
val parameterList = callable.getValueParameterList()
?: (callable as KtClass).createPrimaryConstructorParameterListIfAbsent()
val parameter = KtPsiFactory(myProject).createParameter("$newParameterName: $newParameterTypeText")
parameterList.addParameter(parameter)
}
}
}
override fun deleteTemplateField(psiField: KtParameter) {
if (psiField.isValid) {
(psiField.parent as? KtParameterList)?.removeParameter(psiField)
}
}
override fun isReplaceAllOccurrences() = replaceAllCheckBox?.isSelected ?: true
override fun setReplaceAllOccurrences(allOccurrences: Boolean) {
replaceAllCheckBox?.isSelected = allOccurrences
}
override fun getComponent() = myWholePanel
override fun updateTitle(addedParameter: KtParameter?, currentName: String?) {
val preview = Preview(addedParameter, currentName)
val document = previewEditor.document
runWriteAction { document.setText(preview.text) }
val markupModel = DocumentMarkupModel.forDocument(document, myProject, true)
markupModel.removeAllHighlighters()
preview.rangesToRemove.forEach { PreviewDecorator.FOR_REMOVAL.applyToRange(it, markupModel) }
preview.addedRange?.let { PreviewDecorator.FOR_ADD.applyToRange(it, markupModel) }
revalidate()
}
override fun getRangeToRename(element: PsiElement): TextRange {
if (element is KtProperty) return element.nameIdentifier!!.textRange.shiftRight(-element.startOffset)
return super.getRangeToRename(element)
}
override fun createMarker(element: PsiElement): RangeMarker {
if (element is KtProperty) return super.createMarker(element.nameIdentifier)
return super.createMarker(element)
}
override fun performIntroduce() {
getDescriptorToRefactor(isReplaceAllOccurrences).performRefactoring()
}
private fun getDescriptorToRefactor(replaceAll: Boolean): IntroduceParameterDescriptor {
val originalRange = expr.toRange()
return descriptor.copy(
originalRange = originalRange,
occurrencesToReplace = if (replaceAll) occurrences.map { it.toRange() } else listOf(originalRange),
argumentValue = expr!!
)
}
fun switchToDialogUI() {
stopIntroduce(myEditor)
KotlinIntroduceParameterDialog(
myProject,
myEditor,
getDescriptorToRefactor(true),
myNameSuggestions.toTypedArray(),
listOf(parameterType) + parameterType.supertypes(),
KotlinIntroduceParameterHelper.Default
).show()
}
}
| apache-2.0 | e4e2d17103b809c51257c44077bce496 | 39.900763 | 158 | 0.653695 | 5.969916 | false | false | false | false |
aquatir/remember_java_api | code-sample-kotlin/spring-boot/code-sample-kotlin-graphql-SPQR/src/main/kotlin/codesample/kotlin/graphql/spqr/config/CartGraph.kt | 1 | 2606 | package codesample.kotlin.graphql.spqr.config
import codesample.kotlin.graphql.spqr.domain.DomainObject
import codesample.kotlin.graphql.spqr.entitry.Cart
import codesample.kotlin.graphql.spqr.entitry.CartItem
import codesample.kotlin.graphql.spqr.repository.DomainObjectRepository
import codesample.kotlin.graphql.spqr.service.CartService
import graphql.execution.batched.Batched
import io.leangen.graphql.annotations.GraphQLArgument
import io.leangen.graphql.annotations.GraphQLContext
import io.leangen.graphql.annotations.GraphQLQuery
import io.leangen.graphql.spqr.spring.annotation.GraphQLApi
import org.springframework.stereotype.Service
@GraphQLApi
@Service
class CartGraph(val cartService: CartService,
val domainObjectRepository: DomainObjectRepository) {
/** This is an entry point for all our queries SPQR. Notice that @GraphQLQuery annotation does not have a name
* attribute. This defines top-level query.
*/
@GraphQLQuery(name = "cart")
fun cart(@GraphQLArgument(name = "id") id: Long) : Cart = cartService.getCartById(id)
/**
* After we have queried the cart, we can continue and query this cart's items.
* So we specify Cart as our GraphQLContext and also apply limit to it with default value
* the save way we did when we were configuring graphql with schema file
*/
@GraphQLQuery(name = "cartItems")
fun cartItems(@GraphQLContext cart: Cart,
@GraphQLArgument(name = "limit", defaultValue = "0") limit: Int) : List<CartItem>
= cart.cartItems.subList(0, if (limit > 0) limit else cart.cartItems.size)
@GraphQLQuery(name = "domainObjects")
fun domainObjects(@GraphQLContext cartItem: CartItem): DomainObject
= domainObjectRepository.getByCartItem(cartItem)
/**
*
* TODO: THIS SHOULD BE @BATCHED QUERY BUT I CAN NOT MAKE IT WORK FOR NOW
*
* We use this query as batched, which means that when graphQL have to get DomainObject for
* more then one CardItem, it will use this single query instead of multiple queries
*
* We also going to pass field which were queried to repository, because we don't want all the field to be returned
* other the "network" (Note: graphql will never show all fields to client, HOWEVER they will still go other the network
* if this function was going over the net)
*/
//@Batched
@GraphQLQuery(name = "domainObjects")
fun domainObjects(@GraphQLContext cartItems: List<CartItem>): List<DomainObject>
= domainObjectRepository.getByCartItemsList(cartItems)
}
| mit | 55885b604f36012c84d70a32810e946d | 41.032258 | 124 | 0.737145 | 4.2443 | false | false | false | false |
allotria/intellij-community | plugins/groovy/test/org/jetbrains/plugins/groovy/codeInsight/hint/GroovyParameterTypeHintsInlayProviderTest.kt | 1 | 3338 | // 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 org.jetbrains.plugins.groovy.codeInsight.hint
import com.intellij.openapi.util.registry.Registry
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.utils.inlays.InlayHintsProviderTestCase
import org.jetbrains.plugins.groovy.GroovyProjectDescriptors
import org.jetbrains.plugins.groovy.intentions.style.inference.MethodParameterAugmenter
class GroovyParameterTypeHintsInlayProviderTest : InlayHintsProviderTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor {
return GroovyProjectDescriptors.GROOVY_3_0
}
private fun testTypeHints(text: String, settings:
GroovyParameterTypeHintsInlayProvider.Settings = GroovyParameterTypeHintsInlayProvider.Settings(showInferredParameterTypes = true,
showTypeParameterList = true)) {
testProvider("test.groovy", text, GroovyParameterTypeHintsInlayProvider(), settings)
}
override fun setUp() {
Registry.get(MethodParameterAugmenter.GROOVY_COLLECT_METHOD_CALLS_FOR_INFERENCE).setValue(true)
super.setUp()
}
override fun tearDown() {
Registry.get(MethodParameterAugmenter.GROOVY_COLLECT_METHOD_CALLS_FOR_INFERENCE).resetToDefault()
super.tearDown()
}
fun testSingleType() {
val text = """
def foo(<# [Integer ] #>a) {}
foo(1)
""".trimIndent()
testTypeHints(text)
}
fun testWildcard() {
val text = """
def foo(<# [[List < [? [ super Number]] >] ] #>a) {
a.add(1)
}
foo(null as List<Object>)
foo(null as List<Number>)
""".trimIndent()
testTypeHints(text)
}
fun testTypeParameters() {
val text = """
def<# [< T >] #> foo(<# [[ArrayList < T >] ] #>a, <# [[ArrayList < [? [ extends T]] >] ] #>b) {
a.add(b[0])
}
foo([1], [1])
foo(['q'], ['q'])
""".trimIndent()
testTypeHints(text)
}
fun testClosure() {
val text = """
def<# [< [T extends A] >] #> foo(<# [T ] #>a, <# [[Closure < [? ] >] ] #>c) {
c(a)
}
interface A{def foo()}
foo(null as A) {<# [A it -> ] #>
it.foo()
}
""".trimIndent()
testTypeHints(text)
}
fun testInsideClosure() {
val text = """
def foo(<# [Integer ] #>arg, <# [[Closure < [? ] >] ] #>closure) {
closure(arg)
}
foo(1) { <# [Integer ] #>a -> a.byteValue() }
""".trimIndent()
testTypeHints(text)
}
fun testInsideLambda() {
val text = """
def foo(<# [Integer ] #>arg, <# [[Closure < [? ] >] ] #>closure) {
closure(arg)
}
foo(1, <# [Integer ] #>a -> a.byteValue())
""".trimIndent()
testTypeHints(text)
}
fun testNoTypeHintsWithoutTypeInformation() {
val text = """
def foo(x) {}
""".trimIndent()
testTypeHints(text)
}
fun testNestedClosureBlockWithUnresolvableVariables() {
val text = """
import groovy.transform.stc.ClosureParams
import groovy.transform.stc.SimpleType
def foo(@ClosureParams(value=SimpleType, options=['java.lang.Integer'])Closure a) {}
def bar(@ClosureParams(value=SimpleType, options=['java.lang.Integer'])Closure b) {}
foo { <# [Integer ] #>a ->
bar { <# [Integer ] #>b ->
for (x in y){}
}
}
""".trimIndent()
testTypeHints(text)
}
} | apache-2.0 | e46b8297a8960e96bdcab988afa6cca9 | 25.927419 | 140 | 0.63541 | 3.62039 | false | true | false | false |
android/wear-os-samples | WearTilesKotlin/app/src/main/java/com/example/wear/tiles/messaging/Images.kt | 1 | 2229 | /*
* 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.wear.tiles.messaging
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import androidx.wear.tiles.ResourceBuilders
import androidx.wear.tiles.ResourceBuilders.ImageResource
import coil.ImageLoader
import coil.request.ImageRequest
import coil.transform.CircleCropTransformation
import java.nio.ByteBuffer
suspend fun ImageLoader.loadAvatar(context: Context, contact: Contact, size: Int? = 64): Bitmap? {
val request = ImageRequest.Builder(context)
.data(contact.avatarUrl)
.apply {
if (size != null) {
size(size)
}
}
.allowRgb565(true)
.transformations(CircleCropTransformation())
.allowHardware(false)
.build()
val response = execute(request)
return (response.drawable as? BitmapDrawable)?.bitmap
}
fun bitmapToImageResource(bitmap: Bitmap): ImageResource {
// TODO check if needed
val safeBitmap = bitmap.toRgb565()
val byteBuffer = ByteBuffer.allocate(safeBitmap.byteCount)
safeBitmap.copyPixelsToBuffer(byteBuffer)
val bytes: ByteArray = byteBuffer.array()
return ImageResource.Builder().setInlineResource(
ResourceBuilders.InlineImageResource.Builder()
.setData(bytes)
.setWidthPx(bitmap.width)
.setHeightPx(bitmap.height)
.setFormat(ResourceBuilders.IMAGE_FORMAT_RGB_565)
.build()
)
.build()
}
private fun Bitmap.toRgb565(): Bitmap {
// TODO avoid copy
return this.copy(Bitmap.Config.RGB_565, false)
}
| apache-2.0 | be944ffd7c13345173046815f7300f75 | 32.772727 | 98 | 0.709287 | 4.422619 | false | false | false | false |
Homes-MinecraftServerMod/Homes | src/main/kotlin/com/masahirosaito/spigot/homes/commands/subcommands/player/listcommands/PlayerListPlayerCommand.kt | 1 | 1413 | package com.masahirosaito.spigot.homes.commands.subcommands.player.listcommands
import com.masahirosaito.spigot.homes.Configs.onFriendHome
import com.masahirosaito.spigot.homes.Homes.Companion.homes
import com.masahirosaito.spigot.homes.Permission.home_admin
import com.masahirosaito.spigot.homes.Permission.home_command_list
import com.masahirosaito.spigot.homes.Permission.home_command_list_player
import com.masahirosaito.spigot.homes.PlayerDataManager
import com.masahirosaito.spigot.homes.commands.PlayerSubCommand
import com.masahirosaito.spigot.homes.commands.subcommands.player.PlayerCommand
import com.masahirosaito.spigot.homes.findOfflinePlayer
import com.masahirosaito.spigot.homes.strings.commands.ListCommandStrings.HOME_LIST
import org.bukkit.entity.Player
class PlayerListPlayerCommand(listCommand: PlayerListCommand) : PlayerSubCommand(listCommand), PlayerCommand {
override val permissions: List<String> = listOf(home_command_list, home_command_list_player)
override fun fee(): Double = homes.fee.LIST_PLAYER
override fun configs(): List<Boolean> = listOf(onFriendHome)
override fun isValidArgs(args: List<String>): Boolean = args.size == 1
override fun execute(player: Player, args: List<String>) {
PlayerDataManager.findPlayerData(findOfflinePlayer(args[0])).let {
send(player, HOME_LIST(it, !player.hasPermission(home_admin)))
}
}
}
| apache-2.0 | 1df76e878a764b11fbbe3c9e00e401ae | 46.1 | 110 | 0.80184 | 4.131579 | false | true | false | false |
leafclick/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/impl/namedVariant/NamedVariantTransformationSupport.kt | 1 | 3071 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.transformations.impl.namedVariant
import com.intellij.psi.CommonClassNames.JAVA_LANG_OBJECT
import com.intellij.psi.CommonClassNames.JAVA_UTIL_MAP
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil.getAnnotation
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightModifierList
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightParameter
import org.jetbrains.plugins.groovy.transformations.AstTransformationSupport
import org.jetbrains.plugins.groovy.transformations.TransformationContext
class NamedVariantTransformationSupport : AstTransformationSupport {
override fun applyTransformation(context: TransformationContext) {
context.codeClass.codeMethods.forEach {
if (!it.hasAnnotation(GROOVY_TRANSFORM_NAMED_VARIANT)) return@forEach
val method = constructNamedMethod(it) ?: return@forEach
context.addMethod(method)
}
}
private fun constructNamedMethod(method: GrMethod): GrLightMethodBuilder? {
val parameters = mutableListOf<GrParameter>()
val mapType = TypesUtil.createType(JAVA_UTIL_MAP, method)
val mapParameter = GrLightParameter(NAMED_ARGS_PARAMETER_NAME, mapType, method)
val modifierList = GrLightModifierList(mapParameter)
mapParameter.modifierList = modifierList
parameters.add(mapParameter)
val namedParams = collectNamedParamsFromNamedVariantMethod(method)
namedParams.forEach { namedParam ->
modifierList.addAnnotation(GROOVY_TRANSFORM_NAMED_PARAM).let {
it.addAttribute("type", namedParam.type?.presentableText ?: JAVA_LANG_OBJECT)
it.addAttribute("value", "\"${namedParam.name}\"")
it.addAttribute("required", "${namedParam.required}")
}
}
method.parameterList.parameters
.filter {
getAnnotation(it, GROOVY_TRANSFORM_NAMED_PARAM) == null && getAnnotation(it, GROOVY_TRANSFORM_NAMED_DELEGATE) == null
}.forEach { parameters.add(GrLightParameter(it)) }
return buildMethod(parameters, method)
}
private fun buildMethod(parameters: List<GrParameter>, method: GrMethod): GrLightMethodBuilder? {
val builder = GrLightMethodBuilder(method.manager, method.name + "")
val psiClass = method.containingClass ?: return null
builder.containingClass = psiClass
builder.returnType = method.returnType
builder.navigationElement = method
parameters.forEach {
builder.addParameter(it)
}
method.throwsList.referencedTypes.forEach {
builder.addException(it)
}
builder.originInfo = NAMED_VARIANT_ORIGIN_INFO
return builder
}
} | apache-2.0 | 8d33538ab7a5d73cfadd5c95e74c426d | 46.261538 | 140 | 0.774341 | 4.55638 | false | false | false | false |
leafclick/intellij-community | platform/platform-api/src/com/intellij/ide/SaveAndSyncHandler.kt | 1 | 2896 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide
import com.intellij.openapi.application.AccessToken
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.ApiStatus
abstract class SaveAndSyncHandler {
companion object {
@JvmStatic
fun getInstance(): SaveAndSyncHandler {
return ApplicationManager.getApplication().getService(SaveAndSyncHandler::class.java)
}
}
/**
* Schedule to save documents, all opened projects (or only passed project if not null) and application.
*
* Save is not performed immediately and not finished on method call return.
*/
fun scheduleSaveDocumentsAndProjectsAndApp(onlyProject: Project?) {
scheduleSave(SaveTask(onlyProject))
}
data class SaveTask @JvmOverloads constructor(val onlyProject: Project? = null, val saveDocuments: Boolean = true, val forceSavingAllSettings: Boolean = false) {
companion object {
// for Java clients
@JvmStatic
fun projectIncludingAllSettings(project: Project) = SaveTask(onlyProject = project, saveDocuments = false, forceSavingAllSettings = true)
}
fun isMoreGenericThan(other: SaveTask): Boolean {
return onlyProject == null && other.onlyProject != null && saveDocuments == other.saveDocuments && forceSavingAllSettings == other.forceSavingAllSettings
}
}
@ApiStatus.Experimental
abstract fun scheduleSave(task: SaveTask, forceExecuteImmediately: Boolean = false)
fun scheduleProjectSave(project: Project) = scheduleSave(SaveTask(project, saveDocuments = false))
@Deprecated("", ReplaceWith("FileDocumentManager.getInstance().saveAllDocuments()", "com.intellij.openapi.fileEditor.FileDocumentManager"))
fun saveProjectsAndDocuments() {
// used only by https://plugins.jetbrains.com/plugin/11072-openjml-esc
// so, just save documents and nothing more, to simplify SaveAndSyncHandlerImpl
FileDocumentManager.getInstance().saveAllDocuments()
}
abstract fun scheduleRefresh()
abstract fun refreshOpenFiles()
open fun disableAutoSave(): AccessToken = AccessToken.EMPTY_ACCESS_TOKEN
abstract fun blockSaveOnFrameDeactivation()
abstract fun unblockSaveOnFrameDeactivation()
abstract fun blockSyncOnFrameActivation()
abstract fun unblockSyncOnFrameActivation()
@ApiStatus.Experimental
open fun maybeRefresh(modalityState: ModalityState) {
}
@ApiStatus.Experimental
open fun cancelScheduledSave() {
}
@ApiStatus.Experimental
abstract fun saveSettingsUnderModalProgress(componentManager: ComponentManager): Boolean
}
| apache-2.0 | 2d18a25d91bf65ba91701a5df1c59621 | 36.61039 | 163 | 0.778315 | 5.107584 | false | false | false | false |
byoutline/kickmaterial | app/src/main/java/com/byoutline/kickmaterial/dagger/AndroidModules.kt | 1 | 3420 | package com.byoutline.kickmaterial.dagger
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.content.SharedPreferences
import com.byoutline.kickmaterial.features.projectdetails.ProjectDetailsActivity
import com.byoutline.kickmaterial.features.projectlist.MainActivity
import com.byoutline.kickmaterial.features.projectlist.ProjectListViewModel
import com.byoutline.kickmaterial.features.projectlist.ProjectsListFragment
import com.byoutline.kickmaterial.features.rewardlist.RewardListViewModel
import com.byoutline.kickmaterial.features.rewardlist.RewardsListActivity
import com.byoutline.kickmaterial.features.search.SearchListFragment
import com.byoutline.kickmaterial.features.search.SearchViewModel
import com.byoutline.kickmaterial.features.selectcategory.CategoriesListActivity
import com.byoutline.kickmaterial.features.selectcategory.CategoriesListViewModel
import com.byoutline.kickmaterial.model.DiscoverQuery
import com.byoutline.kickmaterial.model.DiscoverResponse
import com.byoutline.observablecachedfield.ObservableCachedFieldWithArg
import com.byoutline.secretsauce.di.ViewModelFactory
import com.byoutline.secretsauce.di.ViewModelKey
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.android.ContributesAndroidInjector
import dagger.multibindings.IntoMap
import javax.inject.Singleton
@Module
abstract class MainActivityModule {
@ContributesAndroidInjector(modules = [ProjectsListFragmentsModule::class])
abstract fun mainActivity(): MainActivity
@ContributesAndroidInjector abstract fun projectDetailsActivity(): ProjectDetailsActivity
@ContributesAndroidInjector abstract fun rewardsListActivity(): RewardsListActivity
@ContributesAndroidInjector abstract fun categoriesListActivity(): CategoriesListActivity
}
@Module
abstract class ProjectsListFragmentsModule {
@ContributesAndroidInjector abstract fun projectsListFragment(): ProjectsListFragment
@ContributesAndroidInjector abstract fun searchListFragment(): SearchListFragment
}
@Module
abstract class ViewModelMapModule {
@Binds @Singleton
abstract fun viewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory
}
@Module
class ViewModelProvidersModule {
@Provides @IntoMap
@ViewModelKey(ProjectListViewModel::class)
fun projectListViewModel(sharedPrefs: SharedPreferences,
discoverField: ObservableCachedFieldWithArg<DiscoverResponse, DiscoverQuery>): ViewModel {
// show header on first launch
val showHeader = sharedPrefs.getBoolean(ProjectsListFragment.PREFS_SHOW_HEADER, true)
sharedPrefs.edit().putBoolean(ProjectsListFragment.PREFS_SHOW_HEADER, false).apply()
return ProjectListViewModel(showHeader, discoverField)
}
@Provides @IntoMap
@ViewModelKey(SearchViewModel::class)
fun searchViewModel(discoverField: ObservableCachedFieldWithArg<DiscoverResponse, DiscoverQuery>): ViewModel
= SearchViewModel(discoverField)
@Provides @IntoMap
@ViewModelKey(RewardListViewModel::class)
fun rewardListViewModel(): ViewModel = RewardListViewModel()
@Provides @IntoMap
@ViewModelKey(CategoriesListViewModel::class)
fun categoriesListViewModel(discoverField: ObservableCachedFieldWithArg<DiscoverResponse, DiscoverQuery>): ViewModel
= CategoriesListViewModel(discoverField)
}
| apache-2.0 | 101a7a4c4f3266c215accdef12d94dc5 | 44 | 120 | 0.830117 | 5.507246 | false | false | false | false |
AndroidX/androidx | compose/integration-tests/docs-snippets/src/main/java/androidx/compose/integration/docs/theming/Material3.kt | 3 | 5546 | // ktlint-disable indent https://github.com/pinterest/ktlint/issues/967
/*
* 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.
*/
// Ignore lint warnings in documentation snippets
@file:Suppress(
"unused", "UNUSED_PARAMETER", "UNUSED_VARIABLE", "RemoveEmptyParenthesesFromLambdaCall"
)
package androidx.compose.integration.docs.theming
import android.annotation.SuppressLint
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.Typography
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
/**
* This file lets DevRel track changes to snippets present in
* https://developer.android.com/jetpack/compose/themes/material#material3
*
* No action required if it's modified.
*/
private object Material3Snippet1 {
/* Can't be compiled. See snippet below for changes.
MaterialTheme(
colorScheme = …,
typography = …
// Updates to shapes coming soon
) {
// M3 app content
}
*/
@Composable
fun MaterialTheming() {
MaterialTheme(
colorScheme = MaterialTheme.colorScheme,
typography = MaterialTheme.typography
) { }
}
}
private object Material3Snippet2 {
private val Blue40 = Color(0xff1e40ff)
private val DarkBlue40 = Color(0xff3e41f4)
private val Yellow40 = Color(0xff7d5700)
// Remaining colors from tonal palettes
private val LightColorScheme = lightColorScheme(
primary = Blue40,
secondary = DarkBlue40,
tertiary = Yellow40,
// error, primaryContainer, onSecondary, etc.
)
private val DarkColorScheme = darkColorScheme(
primary = Blue80,
secondary = DarkBlue80,
tertiary = Yellow80,
// error, primaryContainer, onSecondary, etc.
)
}
private object Material3Snippet3 {
@Composable
fun Material3Theming() {
val darkTheme = isSystemInDarkTheme()
MaterialTheme(
colorScheme = if (darkTheme) DarkColorScheme else LightColorScheme
) {
// M3 app content
}
}
}
private object Material3Snippet4 {
@SuppressLint("NewApi")
@Composable
fun Material3Theming() {
// Dynamic color is available on Android 12+
val dynamicColor = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
val colorScheme = when {
dynamicColor && darkTheme -> dynamicDarkColorScheme(LocalContext.current)
dynamicColor && !darkTheme -> dynamicLightColorScheme(LocalContext.current)
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
}
}
private object Material3Snippet5 {
@Composable
fun Material3Theming() {
Text(
text = "Hello M3 theming",
color = MaterialTheme.colorScheme.tertiary
)
}
}
private object Material3Snippet6 {
val KarlaFontFamily = FontFamily(
Font(R.font.karla_regular),
Font(R.font.karla_bold, FontWeight.Bold)
)
val AppTypography = Typography(
bodyLarge = TextStyle(
fontFamily = KarlaFontFamily,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.15.sp
),
// titleMedium, labelSmall, etc.
)
}
private object Material3Snippet7 {
@Composable
fun Material3Theming() {
MaterialTheme(
typography = AppTypography
) {
// M3 app content
}
}
}
private object Material3Snippet8 {
@Composable
fun Material3Theming() {
Text(
text = "Hello M3 theming",
style = MaterialTheme.typography.bodyLarge
)
}
}
private object Material3Snippet9 {
@Composable
fun Material3Theming() {
Surface(
tonalElevation = 16.dp,
shadowElevation = 16.dp
) {
// Surface content
}
}
}
/*
Fakes needed for snippets to build:
*/
private val Blue80 = Color(0xff1e40ff)
private val DarkBlue80 = Color(0xff3e41f4)
private val Yellow80 = Color(0xff7d5700)
private val DarkColorScheme = darkColorScheme()
private val LightColorScheme = lightColorScheme()
private const val darkTheme = true
private val AppTypography = Typography()
| apache-2.0 | 23023aae2ff87caefa668ab9b9354137 | 27.715026 | 91 | 0.683327 | 4.43715 | false | false | false | false |
AndroidX/androidx | compose/ui/ui-text/samples/src/main/java/androidx/compose/ui/text/samples/SpanStyleSamples.kt | 3 | 2010 | /*
* 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.compose.ui.text.samples
import androidx.annotation.Sampled
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.ExperimentalTextApi
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.sp
@Sampled
@Composable
fun SpanStyleSample() {
Text(
fontSize = 16.sp,
text = buildAnnotatedString {
withStyle(style = SpanStyle(color = Color.Red)) {
append("Hello")
}
withStyle(SpanStyle(color = Color.Blue)) {
append(" World")
}
}
)
}
@OptIn(ExperimentalTextApi::class)
@Sampled
@Composable
fun SpanStyleBrushSample() {
val brushColors = listOf(Color.Red, Color.Blue, Color.Green, Color.Yellow)
Text(
fontSize = 16.sp,
text = buildAnnotatedString {
withStyle(SpanStyle(
brush = Brush.radialGradient(brushColors)
)) {
append("Hello")
}
withStyle(SpanStyle(
brush = Brush.radialGradient(brushColors.asReversed())
)) {
append(" World")
}
}
)
}
| apache-2.0 | a78572eab941d7614b0e3b8f19974df4 | 29.454545 | 78 | 0.661194 | 4.437086 | false | false | false | false |
smmribeiro/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/library/ProjectModifiableLibraryTableBridgeImpl.kt | 3 | 5715 | // 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.workspaceModel.ide.impl.legacyBridge.library
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectModelExternalSource
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryProperties
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import com.intellij.openapi.util.Disposer
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.impl.JpsEntitySourceFactory
import com.intellij.workspaceModel.ide.impl.legacyBridge.LegacyBridgeModifiableBase
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.findLibraryEntity
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.libraryMap
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.mutableLibraryMap
import com.intellij.workspaceModel.ide.legacyBridge.ProjectModifiableLibraryTableBridge
import com.intellij.workspaceModel.storage.CachedValue
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.*
import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer
internal class ProjectModifiableLibraryTableBridgeImpl(
originalStorage: WorkspaceEntityStorage,
private val libraryTable: ProjectLibraryTableBridgeImpl,
private val project: Project,
diff: WorkspaceEntityStorageBuilder = WorkspaceEntityStorageBuilder.from(originalStorage),
cacheStorageResult: Boolean = true
) : LegacyBridgeModifiableBase(diff, cacheStorageResult), ProjectModifiableLibraryTableBridge {
private val myAddedLibraries = mutableListOf<LibraryBridgeImpl>()
private val librariesArrayValue = CachedValue<Array<Library>> { storage ->
storage.entities(LibraryEntity::class.java).filter { it.tableId == LibraryTableId.ProjectLibraryTableId }
.mapNotNull { storage.libraryMap.getDataByEntity(it) }
.toList().toTypedArray()
}
private val librariesArray: Array<Library>
get() = entityStorageOnDiff.cachedValue(librariesArrayValue)
override fun createLibrary(name: String?): Library = createLibrary(name = name, type = null)
override fun createLibrary(name: String?, type: PersistentLibraryKind<out LibraryProperties<*>>?): Library =
createLibrary(name = name, type = type, externalSource = null)
override fun createLibrary(name: String?,
type: PersistentLibraryKind<out LibraryProperties<*>>?,
externalSource: ProjectModelExternalSource?): Library {
if (name.isNullOrBlank()) error("Project Library must have a name")
assertModelIsLive()
val libraryTableId = LibraryTableId.ProjectLibraryTableId
val libraryEntity = diff.addLibraryEntity(
roots = emptyList(),
tableId = LibraryTableId.ProjectLibraryTableId,
name = name,
excludedRoots = emptyList(),
source = JpsEntitySourceFactory.createEntitySourceForProjectLibrary(project, externalSource)
)
if (type != null) {
diff.addLibraryPropertiesEntity(
library = libraryEntity,
libraryType = type.kindId,
propertiesXmlTag = serializeComponentAsString(JpsLibraryTableSerializer.PROPERTIES_TAG, type.createDefaultProperties())
)
}
val library = LibraryBridgeImpl(
libraryTable = libraryTable,
project = project,
initialId = LibraryId(name, libraryTableId),
initialEntityStorage = entityStorageOnDiff,
targetBuilder = this.diff
)
myAddedLibraries.add(library)
diff.mutableLibraryMap.addMapping(libraryEntity, library)
return library
}
override fun removeLibrary(library: Library) {
assertModelIsLive()
val libraryEntity = entityStorageOnDiff.current.findLibraryEntity(library as LibraryBridge)
if (libraryEntity != null) {
diff.removeEntity(libraryEntity)
if (myAddedLibraries.remove(library)) {
Disposer.dispose(library)
}
}
}
override fun commit() {
prepareForCommit()
WorkspaceModel.getInstance(project).updateProjectModel {
it.addDiff(diff)
}
}
override fun prepareForCommit() {
assertModelIsLive()
modelIsCommittedOrDisposed = true
val storage = WorkspaceModel.getInstance(project).entityStorage.current
myAddedLibraries.forEach { library ->
if (storage.resolve(library.libraryId) != null) {
// it may happen that actual library table already has a library with such name (e.g. when multiple projects are imported in parallel)
// in such case we need to skip the new library to avoid exceptions.
diff.removeEntity(diff.libraryMap.getEntities(library).first())
Disposer.dispose(library)
}
library.clearTargetBuilder()
}
}
override fun getLibraryIterator(): Iterator<Library> = librariesArray.iterator()
override fun getLibraryByName(name: String): Library? {
val libraryEntity = diff.resolve(LibraryId(name, LibraryTableId.ProjectLibraryTableId)) ?: return null
return diff.libraryMap.getDataByEntity(libraryEntity)
}
override fun getLibraries(): Array<Library> = librariesArray
override fun dispose() {
modelIsCommittedOrDisposed = true
myAddedLibraries.forEach { Disposer.dispose(it) }
myAddedLibraries.clear()
}
override fun isChanged(): Boolean = !diff.isEmpty()
}
| apache-2.0 | 57cc4d147efc248d7151f3cbb9696449 | 41.022059 | 158 | 0.769379 | 5.247934 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/party/PartyInviteFragment.kt | 1 | 2784 | package com.habitrpg.android.habitica.ui.fragments.social.party
import android.os.Bundle
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.ui.fragments.BaseFragment
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.helpers.resetViews
import java.util.*
import javax.inject.Inject
class PartyInviteFragment : BaseFragment() {
@Inject
lateinit var configManager: AppConfigManager
var isEmailInvite: Boolean = false
private val inviteDescription: TextView? by bindView(R.id.inviteDescription)
private val invitationWrapper: LinearLayout? by bindView(R.id.invitationWrapper)
private val addInviteButton: Button? by bindView(R.id.addInviteButton)
val values: Array<String>
get() {
val values = ArrayList<String>()
for (i in 0 until (invitationWrapper?.childCount ?: 0)) {
val valueEditText = invitationWrapper?.getChildAt(i) as? EditText
if (valueEditText?.text?.toString()?.isNotEmpty() == true) {
values.add(valueEditText.text.toString())
}
}
return values.toTypedArray()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
return inflater.inflate(R.layout.fragment_party_invite, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
resetViews()
if (isEmailInvite) {
inviteDescription?.text = getString(R.string.invite_email_description)
} else {
inviteDescription?.text = getString(R.string.invite_username_description)
}
addInviteField()
addInviteButton?.setOnClickListener { addInviteField() }
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
private fun addInviteField() {
val editText = EditText(context)
if (isEmailInvite) {
editText.setHint(R.string.email)
editText.inputType = InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
} else {
editText.setHint(R.string.username)
}
invitationWrapper?.addView(editText)
}
}
| gpl-3.0 | f7f39be5c80d56d273198d0956b33fa1 | 33.8 | 116 | 0.703305 | 4.663317 | false | false | false | false |
Pattonville-App-Development-Team/Android-App | app/src/main/java/org/pattonvillecs/pattonvilleapp/service/repository/news/NewsSyncJobService.kt | 1 | 5080 | /*
* Copyright (C) 2017 - 2018 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.pattonvillecs.pattonvilleapp.service.repository.news
import android.os.AsyncTask
import android.util.Log
import com.firebase.jobdispatcher.*
import com.github.magneticflux.rss.namespaces.standard.elements.Rss
import com.google.common.base.Function
import com.google.common.util.concurrent.FutureCallback
import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.Futures.transform
import com.google.common.util.concurrent.ListenableFuture
import com.google.firebase.crash.FirebaseCrash
import org.pattonvillecs.pattonvilleapp.service.model.DataSource
import org.pattonvillecs.pattonvilleapp.service.model.news.ArticleSummary
import org.pattonvillecs.pattonvilleapp.service.repository.DaggerJobService
import java.io.IOException
import java.util.concurrent.TimeUnit
import javax.inject.Inject
typealias SourcedRss = Pair<Rss, DataSource>
/**
* Created by Mitchell Skaggs on 1/15/2018.
*
* @since 1.4.0
*/
class NewsSyncJobService : DaggerJobService() {
@field:Inject
lateinit var newsRepository: NewsRepository
@field:Inject
lateinit var newsRetrofitService: NewsRetrofitService
override fun onStartJob(job: JobParameters): Boolean {
Log.i(TAG, "Starting news sync service!")
Futures.addCallback(
Futures.allAsList(DataSource.NEWS.map(this::dataSourceToSourcedRss)),
SourcedNewsListCallback(this, job, newsRepository),
AsyncTask.THREAD_POOL_EXECUTOR)
return true
}
private fun dataSourceToSourcedRss(dataSource: DataSource): ListenableFuture<SourcedRss> =
transform(newsRetrofitService.getRss(dataSource), Function<Rss, SourcedRss> { it: Rss? -> it!! to dataSource }, AsyncTask.THREAD_POOL_EXECUTOR)
override fun onStopJob(job: JobParameters): Boolean = false
class SourcedNewsListCallback(
private val newsSyncJobService: NewsSyncJobService,
private val job: JobParameters,
private val newsRepository: NewsRepository
) : FutureCallback<List<SourcedRss>> {
override fun onSuccess(result: List<SourcedRss>?) {
Log.i(TAG, "Successful download!")
val articles = mutableListOf<ArticleSummary>()
result.orEmpty().forEach {
Log.i(TAG, "Processed ${it.second} with ${it.first.channel.items.size} articles")
it.first.channel.items.forEach { item ->
articles += ArticleSummary(item, it.second)
}
}
newsRepository.updateArticles(articles)
newsSyncJobService.jobFinished(job, false)
}
override fun onFailure(t: Throwable) {
if (t !is IOException) {
FirebaseCrash.logcat(Log.WARN, TAG, "Download failed!")
FirebaseCrash.report(t)
}
newsSyncJobService.jobFinished(job, true)
}
}
companion object {
private const val TAG = "NewsSyncJobService"
@JvmStatic
fun getRecurringNewsSyncJob(firebaseJobDispatcher: FirebaseJobDispatcher): Job =
firebaseJobDispatcher.newJobBuilder()
.setReplaceCurrent(true)
.setTag("recurring_news_sync_job")
.setService(NewsSyncJobService::class.java)
.addConstraint(Constraint.DEVICE_CHARGING)
.addConstraint(Constraint.ON_UNMETERED_NETWORK)
.setLifetime(Lifetime.FOREVER)
.setRecurring(true)
.setTrigger(Trigger.executionWindow(TimeUnit.HOURS.toSeconds(1).toInt(), TimeUnit.HOURS.toSeconds(4).toInt()))
.build()
@JvmStatic
fun getInstantNewsSyncJob(firebaseJobDispatcher: FirebaseJobDispatcher): Job =
firebaseJobDispatcher.newJobBuilder()
.setReplaceCurrent(true)
.setTag("instant_news_sync_job")
.setService(NewsSyncJobService::class.java)
.addConstraint(Constraint.ON_ANY_NETWORK)
.setLifetime(Lifetime.FOREVER)
.setTrigger(Trigger.NOW)
.build()
}
} | gpl-3.0 | 2f6f97495275807de0bbf6126e22f48d | 39.325397 | 155 | 0.665157 | 4.690674 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-data/src/main/kotlin/slatekit/data/encoders/Encoders.kt | 1 | 1020 | package slatekit.data.encoders
/**
* Stores all the encoders for all supported data types
*/
open class Encoders<TId, T>(val utc:Boolean = true) where TId: kotlin.Comparable<TId>, T:Any {
open val bools = BoolEncoder()
open val strings = StringEncoder()
open val shorts = ShortEncoder()
open val ints = IntEncoder()
open val longs = LongEncoder()
open val floats = FloatEncoder()
open val doubles = DoubleEncoder()
open val localDates = LocalDateEncoder()
open val localTimes = LocalTimeEncoder()
open val localDateTimes = LocalDateTimeEncoder()
open val zonedDateTimes = ZonedDateTimeEncoder(utc = utc)
open val dateTimes = DateTimeEncoder(utc = utc)
open val instants = InstantEncoder()
open val uuids = UUIDEncoder()
open val upids = UPIDEncoder()
open val enums = EnumEncoder()
}
| apache-2.0 | a9a7198856ed82fa4b08201991a85dbe | 41.5 | 94 | 0.588235 | 4.700461 | false | false | false | false |
siosio/intellij-community | plugins/devkit/devkit-core/src/formConversion/ConvertFormToDslAction.kt | 1 | 17543 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.devkit.formConversion
import com.intellij.codeInsight.hint.HintManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.codeStyle.NameUtil
import com.intellij.psi.search.ProjectScope
import com.intellij.psi.search.PsiShortNamesCache
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.uiDesigner.PsiPropertiesProvider
import com.intellij.uiDesigner.binding.FormClassIndex
import com.intellij.uiDesigner.compiler.Utils.getRootContainer
import com.intellij.uiDesigner.core.GridLayoutManager
import com.intellij.uiDesigner.lw.*
import org.jetbrains.idea.devkit.DevKitBundle
import org.jetbrains.uast.UClass
import org.jetbrains.uast.UastVisibility
import org.jetbrains.uast.toUElement
import java.util.*
class ConvertFormToDslAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val editor = e.getRequiredData(CommonDataKeys.EDITOR)
val psiFile = e.getRequiredData(CommonDataKeys.PSI_FILE) as PsiJavaFile
val project = psiFile.project
val element = psiFile.findElementAt(editor.caretModel.offset)
val psiClass = PsiTreeUtil.getParentOfType(element, PsiClass::class.java) ?: run {
HintManager.getInstance().showErrorHint(editor, DevKitBundle.message("convert.form.hint.caret.not.in.form.bound.class"))
return
}
val qName = psiClass.qualifiedName ?: return
val formFile = FormClassIndex.findFormsBoundToClass(project, qName).singleOrNull() ?: run {
HintManager.getInstance().showErrorHint(editor, DevKitBundle.message("convert.form.hint.class.not.bound.to.form", qName))
return
}
convertFormToUiDsl(psiClass, formFile)
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = e.getData(CommonDataKeys.PSI_FILE) is PsiJavaFile &&
e.getData(CommonDataKeys.EDITOR) != null
}
}
@Suppress("HardCodedStringLiteral")
fun convertFormToUiDsl(boundClass: PsiClass, formFile: PsiFile) {
val project = boundClass.project
val psiFile = boundClass.containingFile as PsiJavaFile
val module = ModuleUtil.findModuleForPsiElement(psiFile) ?: return
val dialog = ConvertFormDialog(project, "${boundClass.name}Ui")
if (!dialog.showAndGet()) return
val boundInstanceUClass = findBoundInstanceUClass(project, dialog.boundInstanceType)
val rootContainer = getRootContainer(formFile.text, PsiPropertiesProvider(module))
val form = convertRootContainer(module, rootContainer, boundInstanceUClass)
val imports = LinkedHashSet(form.imports)
boundInstanceUClass?.qualifiedName?.let {
imports.add(it)
}
if (dialog.generateDescriptors) {
imports.add("com.intellij.application.options.editor.*")
}
if (dialog.baseClass == ConvertFormDialog.FormBaseClass.Configurable) {
imports.add("com.intellij.openapi.options.BoundConfigurable")
imports.add("com.intellij.openapi.ui.DialogPanel")
}
val optionDescriptors = if (dialog.generateDescriptors) {
buildString {
generateOptionDescriptors(form.root, this)
}
}
else {
""
}
val uiName = dialog.className
val ktFileType = FileTypeRegistry.getInstance().getFileTypeByExtension("kt")
val ktFileText = buildString {
if (psiFile.packageName.isNotEmpty()) {
append("package ${psiFile.packageName}\n\n")
}
append("import com.intellij.ui.layout.*\n")
for (usedImport in imports) {
append("import $usedImport\n")
}
append("\n")
if (optionDescriptors.isNotEmpty()) {
append("private val model = ${dialog.boundInstanceExpression}")
append(optionDescriptors)
append("\n")
}
append("class $uiName")
if (dialog.baseClass == ConvertFormDialog.FormBaseClass.Configurable) {
append(" : BoundConfigurable(TODO(), TODO())")
}
else if (boundInstanceUClass != null) {
append("(val model: ${dialog.boundInstanceType.substringAfterLast('.')})")
}
append(" {")
for (binding in form.componentBindings) {
val typeParameters = buildTypeParametersString(module, binding.type)
append("lateinit var ${binding.name}: ${binding.type.substringAfterLast('.')}$typeParameters\n")
}
if (dialog.baseClass == ConvertFormDialog.FormBaseClass.Configurable) {
append("override fun createPanel(): DialogPanel {\n")
if (dialog.boundInstanceExpression.isNotEmpty()) {
append("val model = ${dialog.boundInstanceExpression}\n")
}
else if (boundInstanceUClass != null) {
append("val model: ${dialog.boundInstanceType.substringAfterLast('.')} = TODO()\n")
}
append("return panel {\n")
form.root.render(this)
append("}\n")
}
else {
append("val panel = panel {\n")
form.root.render(this)
append("}\n")
}
append("}")
}
val ktFile = PsiFileFactory.getInstance(project).createFileFromText("$uiName.kt", ktFileType, ktFileText)
WriteCommandAction.runWriteCommandAction(project) {
val ktFileReal = psiFile.containingDirectory.add(ktFile) as PsiFile
CodeStyleManager.getInstance(project).reformat(ktFileReal)
ktFileReal.navigate(true)
}
}
private fun findBoundInstanceUClass(project: Project, boundInstanceType: String): UClass? {
val psiClass = JavaPsiFacade.getInstance(project).findClass(boundInstanceType, ProjectScope.getAllScope(project))
if (psiClass == null) return null
return psiClass.navigationElement.toUElement(UClass::class.java)
}
private fun convertRootContainer(module: Module,
rootContainer: LwRootContainer,
boundInstanceUClass: UClass?): UiForm {
val call = FormToDslConverter(module, boundInstanceUClass).convertContainer(rootContainer)
for (buttonGroup in rootContainer.buttonGroups) {
call.checkConvertButtonGroup(buttonGroup.componentIds)
}
return UiForm(module, call)
}
@Suppress("HardCodedStringLiteral")
private fun generateOptionDescriptors(call: FormCall, optionDescriptors: StringBuilder) {
val propertyName = call.binding
val size = call.args.size
if (call.callee == "checkBox" && propertyName != null && size >= 1) {
optionDescriptors.append("val $propertyName = CheckboxDescriptor(${call.args[0]}, ")
val propertyBindingArg =
when {
size == 1 -> "TODO()"
size == 2 -> "${call.args[1]}.toBinding()"
else -> "PropertyBinding(${call.args[1]}, ${call.args[2]})"
}
optionDescriptors.append(propertyBindingArg).append(")\n")
call.args.clear()
call.args.add(propertyName)
}
for (content in call.contents) {
generateOptionDescriptors(content, optionDescriptors)
}
}
@Suppress("HardCodedStringLiteral")
class FormCall(
val callee: String,
val args: MutableList<String> = mutableListOf(),
val contents: MutableList<FormCall> = mutableListOf(),
var origin: IComponent? = null,
var binding: String? = null,
var bindingType: String? = null,
var generateProperty: Boolean = false
) {
constructor(callee: String, vararg args: String): this(callee) {
this.args.addAll(args.toList())
}
fun addArgIfPresent(arg: Array<String>?): FormCall {
if (arg != null) {
Collections.addAll(args, *arg)
}
return this
}
fun addArgOrDefault(arg: Array<String>?, vararg default: String): FormCall {
if (arg != null) {
Collections.addAll(args, *arg)
}
else {
Collections.addAll(args, *default)
}
return this
}
fun render(builder: StringBuilder) {
if (callee == "row" && args.isEmpty() && contents.all { it.callee == "row" }) {
for (content in contents) {
content.render(builder)
}
return
}
builder.append(callee)
if (args.isNotEmpty()) {
builder.append(args.joinToString(prefix = "(", postfix = ")", separator = ", "))
}
if (contents.isNotEmpty()) {
builder.append("{\n")
for (content in contents) {
content.render(builder)
}
builder.append("}")
}
if (generateProperty) {
builder.append(".also { $binding = it }")
}
builder.append("\n")
}
}
data class ComponentBinding(val name: String, val type: String)
@Suppress("HardCodedStringLiteral")
class UiForm(module: Module, val root: FormCall) {
private val _imports = sortedSetOf<String>()
private val _componentBindings = mutableListOf<ComponentBinding>()
val imports: Collection<String> get() { return _imports }
val componentBindings: Collection<ComponentBinding> get() { return _componentBindings }
init {
collectUsedImportsAndBindings(module, root)
}
private fun collectUsedImportsAndBindings(module: Module, formCall: FormCall) {
for (arg in formCall.args) {
val callee = arg.substringBefore('.', "")
if (callee.endsWith("Bundle")) {
val shortNamesCache = PsiShortNamesCache.getInstance(module.project)
val classesByName = shortNamesCache.getClassesByName(callee, module.moduleContentWithDependenciesScope)
if (classesByName.isNotEmpty()) {
val qualifiedName = classesByName[0].qualifiedName
if (qualifiedName != null) {
_imports.add(qualifiedName)
}
}
}
}
if (formCall.generateProperty) {
formCall.bindingType?.let { bindingType ->
_imports.add(bindingType)
formCall.binding?.let { bindingName -> _componentBindings.add(ComponentBinding(bindingName, bindingType))}
}
}
for (content in formCall.contents) {
collectUsedImportsAndBindings(module, content)
}
}
}
internal class PropertyBinding(val type: PsiType?, val bindingCallParameters: Array<String>)
@Suppress("HardCodedStringLiteral")
class FormToDslConverter(private val module: Module, private val boundInstanceUClass: UClass?) {
fun convertContainer(container: LwContainer): FormCall {
val row: FormCall
val borderTitle = container.borderTitle
if (borderTitle != null) {
row = FormCall("titledRow", origin = container)
row.args.add(convertStringDescriptor(borderTitle))
}
else {
row = FormCall("row", origin = container)
}
val layoutManager = container.layout
if (layoutManager is GridLayoutManager) {
for (rowIndex in 0 until layoutManager.rowCount) {
row.appendGridRow(container, layoutManager, rowIndex)
}
}
else {
for (index in 0 until container.componentCount) {
row.contents.add(convertComponentOrContainer(container.getComponent(index)))
}
}
return row
}
private fun FormCall.appendGridRow(container: LwContainer, layoutManager: GridLayoutManager, rowIndex: Int) {
val allComponents = container.collectComponentsInRow(rowIndex, layoutManager.columnCount)
val components = allComponents.filter { it !is LwHSpacer && it !is LwVSpacer }
if (components.isEmpty()) return
val row = FormCall("row", origin = container)
contents.add(row)
if (components.first().componentClassName == "javax.swing.JLabel") {
row.args.add(convertComponentText(components.first()))
for (component in components.drop(1)) {
row.contents.add(convertComponentOrContainer(component))
}
}
else {
for (component in components) {
row.contents.add(convertComponentOrContainer((component)))
}
}
}
private fun LwContainer.collectComponentsInRow(row: Int, columnCount: Int): List<IComponent> {
val result = arrayOfNulls<IComponent>(columnCount)
for (i in 0 until componentCount) {
val component = getComponent(i)
val constraints = component.constraints
if (constraints.row == row) {
result[constraints.column] = component
}
}
return result.toList().filterNotNull()
}
private fun convertComponentOrContainer(component: IComponent): FormCall {
val result = if (component is LwContainer) {
return convertContainer(component)
}
else {
convertComponent(component)
}
result.origin = component
result.binding = component.binding
result.bindingType = component.componentClassName
return result
}
private fun convertComponent(component: IComponent): FormCall {
val propertyBinding = convertBinding(component.binding)
return when (component.componentClassName) {
"javax.swing.JCheckBox",
"com.intellij.ui.components.JBCheckBox" ->
FormCall("checkBox", convertComponentText(component))
.addArgIfPresent(propertyBinding?.bindingCallParameters)
"javax.swing.JTextField" -> {
val methodName = if (propertyBinding?.type?.canonicalText == "int") "intTextField" else "textField"
FormCall(methodName)
.addArgOrDefault(propertyBinding?.bindingCallParameters, "{ \"\" }", "{}")
}
"com.intellij.openapi.ui.TextFieldWithBrowseButton" -> {
FormCall("textFieldWithBrowseButton")
.addArgOrDefault(propertyBinding?.bindingCallParameters, "{ \"\" }", "{}")
}
"javax.swing.JRadioButton",
"com.intellij.ui.components.JBRadioButton"->
FormCall("radioButton", convertComponentText(component))
"javax.swing.JButton" ->
FormCall("button", convertComponentText(component), "actionListener = { TODO() }")
"javax.swing.JLabel",
"com.intellij.ui.components.JBLabel" ->
FormCall("label", convertComponentText(component))
"javax.swing.JComboBox",
"com.intellij.openapi.ui.ComboBox" ->
FormCall("comboBox", "TODO()")
else -> {
val typeParameters = buildTypeParametersString(module, component.componentClassName)
val classShortName = component.componentClassName.substringAfterLast('.')
FormCall("$classShortName$typeParameters()", generateProperty = true)
}
}
}
private fun convertBinding(binding: String?): PropertyBinding? {
if (binding == null || boundInstanceUClass == null) return null
val field = boundInstanceUClass.fields.find { it.matchesBinding(binding) }
if (field != null && !field.isStatic && field.visibility != UastVisibility.PRIVATE) {
return PropertyBinding(field.type, arrayOf("model::${field.name}"))
}
val getter = boundInstanceUClass.methods.find {
!it.name.startsWith("set") && it.matchesBinding(binding)
}
val setter = boundInstanceUClass.methods.find {
it.name.startsWith("set") && it.matchesBinding(binding)
}
if (getter != null && setter != null) {
return PropertyBinding(getter.returnType, arrayOf("model::${getter.name}", "model::${setter.name}"))
}
return null
}
private fun PsiNamedElement.matchesBinding(binding: String): Boolean {
val bindingWords = NameUtil.nameToWordsLowerCase(binding.removePrefix("my"))
val elementWords = NameUtil.nameToWordsLowerCase(name?.removePrefix("my") ?: "")
if (bindingWords.size == 1 && elementWords.size == 1) {
return bindingWords[0] == elementWords[0]
}
return bindingWords.count { it in elementWords } > 1
}
private fun convertComponentText(component: IComponent): String {
val propertyValue = component.getPropertyValue("text") ?: return ""
return convertStringDescriptor(propertyValue as StringDescriptor)
}
private fun convertStringDescriptor(text: StringDescriptor): String {
text.value?.let {
return "\"${StringUtil.escapeQuotes(it)}\""
}
return "${text.bundleName.substringAfterLast('/')}.message(\"${text.key}\")"
}
}
@Suppress("HardCodedStringLiteral")
private fun buildTypeParametersString(module: Module, className: String): String {
val javaPsiFacade = JavaPsiFacade.getInstance(module.project)
val componentClass = javaPsiFacade.findClass(className, module.moduleWithDependenciesScope)
return if (componentClass != null && componentClass.typeParameters.isNotEmpty()) {
Array(componentClass.typeParameters.size) { "Any" }.joinToString(prefix = "<", postfix = ">", separator = ", ")
}
else
""
}
private fun IComponent.getPropertyValue(name: String): Any? {
val prop = modifiedProperties.find { it.name == name } ?: return null
return prop.getPropertyValue(this)
}
fun FormCall.checkConvertButtonGroup(ids: Array<String>) {
if (contents.any { it.isRadioButtonRow(ids) }) {
val firstIndex = contents.indexOfFirst { it.isRadioButtonRow(ids) }
val lastIndex = contents.indexOfLast { it.isRadioButtonRow(ids) }
val buttonGroupNode = FormCall("buttonGroup")
val buttonGroupControls = contents.subList(firstIndex, lastIndex + 1)
buttonGroupNode.contents.addAll(buttonGroupControls)
contents.removeAll(buttonGroupControls)
contents.add(firstIndex, buttonGroupNode)
return
}
for (content in contents) {
content.checkConvertButtonGroup(ids)
}
}
@Suppress("HardCodedStringLiteral")
private fun FormCall.isRadioButtonRow(ids: Array<String>): Boolean {
return callee == "row" && contents.singleOrNull()?.origin?.id?.let { it in ids } == true
}
| apache-2.0 | e22b326000bca331b84d991e308565d5 | 34.802041 | 140 | 0.7033 | 4.365016 | false | false | false | false |
siosio/intellij-community | plugins/git4idea/src/git4idea/GitStatisticsCollector.kt | 1 | 5773 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea
import com.google.common.collect.HashMultiset
import com.intellij.internal.statistic.beans.*
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Comparing
import com.intellij.util.io.URLUtil
import com.intellij.vcs.log.impl.VcsLogApplicationSettings
import com.intellij.vcs.log.impl.VcsLogProjectTabsProperties
import com.intellij.vcs.log.impl.VcsLogUiProperties
import com.intellij.vcs.log.impl.VcsProjectLog
import com.intellij.vcs.log.ui.VcsLogUiImpl
import git4idea.config.GitVcsApplicationSettings
import git4idea.config.GitVcsSettings
import git4idea.repo.GitCommitTemplateTracker
import git4idea.repo.GitRemote
import git4idea.repo.GitRepository
import git4idea.ui.branch.dashboard.CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY
import git4idea.ui.branch.dashboard.SHOW_GIT_BRANCHES_LOG_PROPERTY
class GitStatisticsCollector : ProjectUsagesCollector() {
override fun getGroupId(): String = "git.configuration"
override fun getVersion(): Int = 4
override fun getMetrics(project: Project): MutableSet<MetricEvent> {
val set = HashSet<MetricEvent>()
val repositoryManager = GitUtil.getRepositoryManager(project)
val repositories = repositoryManager.repositories
val settings = GitVcsSettings.getInstance(project)
val defaultSettings = GitVcsSettings()
addEnumIfDiffers(set, settings, defaultSettings, { it.syncSetting }, "repo.sync")
addEnumIfDiffers(set, settings, defaultSettings, { it.updateMethod }, "update.type")
addEnumIfDiffers(set, settings, defaultSettings, { it.saveChangesPolicy }, "save.policy")
addBoolIfDiffers(set, settings, defaultSettings, { it.autoUpdateIfPushRejected() }, "push.autoupdate")
addBoolIfDiffers(set, settings, defaultSettings, { it.shouldUpdateAllRootsIfPushRejected() }, "push.update.all.roots")
addBoolIfDiffers(set, settings, defaultSettings, { it.warnAboutCrlf() }, "warn.about.crlf")
addBoolIfDiffers(set, settings, defaultSettings, { it.warnAboutDetachedHead() }, "warn.about.detached")
val appSettings = GitVcsApplicationSettings.getInstance()
val defaultAppSettings = GitVcsApplicationSettings()
addBoolIfDiffers(set, appSettings, defaultAppSettings, { it.isStagingAreaEnabled }, "staging.area.enabled")
val version = GitVcs.getInstance(project).version
set.add(newMetric("executable", FeatureUsageData().addData("version", version.presentation).addData("type", version.type.name)))
for (repository in repositories) {
val branches = repository.branches
val metric = newMetric("repository")
metric.data.addData("local_branches", branches.localBranches.size)
metric.data.addData("remote_branches", branches.remoteBranches.size)
metric.data.addData("remotes", repository.remotes.size)
val remoteTypes = HashMultiset.create(repository.remotes.mapNotNull { getRemoteServerType(it) })
for (remoteType in remoteTypes) {
metric.data.addData("remote_$remoteType", remoteTypes.count(remoteType))
}
set.add(metric)
}
addCommitTemplateMetrics(project, repositories, set)
addGitLogMetrics(project, set)
return set
}
private fun addCommitTemplateMetrics(project: Project, repositories: List<GitRepository>, set: java.util.HashSet<MetricEvent>) {
if (repositories.isEmpty()) return
val templatesCount = project.service<GitCommitTemplateTracker>().templatesCount()
if (templatesCount == 0) return
val metric = newMetric("commit_template")
metric.data.addData("count", templatesCount)
metric.data.addData("multiple_root", repositories.size > 1)
set.add(metric)
}
private fun addGitLogMetrics(project: Project, metrics: MutableSet<MetricEvent>) {
val projectLog = VcsProjectLog.getInstance(project) ?: return
val ui = projectLog.mainLogUi ?: return
addPropertyMetricIfDiffers(metrics, ui, SHOW_GIT_BRANCHES_LOG_PROPERTY, "showGitBranchesInLog")
addPropertyMetricIfDiffers(metrics, ui, CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY, "updateBranchesFilterInLogOnSelection")
}
private fun addPropertyMetricIfDiffers(metrics: MutableSet<MetricEvent>,
ui: VcsLogUiImpl,
property: VcsLogUiProperties.VcsLogUiProperty<Boolean>,
eventId: String) {
val defaultValue = (property as? VcsLogProjectTabsProperties.CustomBooleanTabProperty)?.defaultValue(ui.id)
?: (property as? VcsLogApplicationSettings.CustomBooleanProperty)?.defaultValue() ?: return
val properties = ui.properties
val value = if (properties.exists(property)) properties[property] else defaultValue
if (!Comparing.equal(value, defaultValue)) {
metrics.add(newBooleanMetric(eventId, value))
}
}
companion object {
private fun getRemoteServerType(remote: GitRemote): String? {
val hosts = remote.urls.map(URLUtil::parseHostFromSshUrl).distinct()
if (hosts.contains("github.com")) return "github"
if (hosts.contains("gitlab.com")) return "gitlab"
if (hosts.contains("bitbucket.org")) return "bitbucket"
if (remote.urls.any { it.contains("github") }) return "github_custom"
if (remote.urls.any { it.contains("gitlab") }) return "gitlab_custom"
if (remote.urls.any { it.contains("bitbucket") }) return "bitbucket_custom"
return null
}
}
}
| apache-2.0 | baa4e3b901cb813b350ebcc0b574a4f4 | 44.456693 | 140 | 0.744673 | 4.433948 | false | false | false | false |
3sidedcube/react-native-navigation | lib/android/app/src/test/java/com/reactnativenavigation/utils/MotionEventTest.kt | 1 | 1419 | package com.reactnativenavigation.utils
import android.app.Activity
import android.view.MotionEvent
import android.view.View
import android.view.View.MeasureSpec
import android.widget.FrameLayout
import androidx.core.view.marginTop
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import com.reactnativenavigation.BaseTest
import org.assertj.core.api.Java6Assertions.assertThat
import org.junit.Test
class MotionEventTest : BaseTest() {
private lateinit var uut: MotionEvent
private lateinit var activity: Activity
private lateinit var parent: FrameLayout
private val x = 173f
private val y = 249f
override fun beforeEach() {
uut = MotionEvent.obtain(0L, 0, 0, x, y, 0)
activity = newActivity()
parent = FrameLayout(activity)
activity.setContentView(parent)
}
@Test
fun coordinatesInsideView() {
val v: View = mock()
assertThat(uut.coordinatesInsideView(v)).isFalse()
}
@Test
fun coordinatesInsideView_inside() {
val view = View(activity)
parent.addView(view, 200, 300)
assertThat(uut.coordinatesInsideView(view)).isTrue()
}
@Test
fun coordinatesInsideView_outside() {
val view = View(activity)
parent.addView(view, 200, 300)
view.top = (y + 1).toInt()
assertThat(uut.coordinatesInsideView(view)).isFalse()
}
} | mit | df2ba1348803d2aac33e053eb27d3c04 | 27.979592 | 61 | 0.702607 | 4.261261 | false | true | false | false |
dkrivoruchko/ScreenStream | app/src/main/kotlin/info/dvkr/screenstream/ui/activity/AppActivity.kt | 1 | 7875 | package info.dvkr.screenstream.ui.activity
import android.animation.ObjectAnimator
import android.animation.PropertyValuesHolder
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Build
import android.os.Bundle
import android.text.InputType
import android.view.View
import android.view.animation.OvershootInterpolator
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import com.afollestad.materialdialogs.LayoutMode
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.WhichButton
import com.afollestad.materialdialogs.actions.setActionButtonEnabled
import com.afollestad.materialdialogs.bottomsheets.BottomSheet
import com.afollestad.materialdialogs.input.getInputField
import com.afollestad.materialdialogs.input.input
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.elvishew.xlog.XLog
import info.dvkr.screenstream.BaseApp
import info.dvkr.screenstream.R
import info.dvkr.screenstream.common.getLog
import info.dvkr.screenstream.databinding.ActivityAppBinding
import info.dvkr.screenstream.logging.sendLogsInEmail
import info.dvkr.screenstream.service.ServiceMessage
import info.dvkr.screenstream.service.TileActionService
import info.dvkr.screenstream.service.helper.IntentAction
import info.dvkr.screenstream.ui.viewBinding
import kotlinx.coroutines.flow.first
class AppActivity : CastPermissionActivity(R.layout.activity_app) {
companion object {
fun getAppActivityIntent(context: Context): Intent = Intent(context, AppActivity::class.java)
fun getStartIntent(context: Context): Intent = getAppActivityIntent(context)
}
private val binding by viewBinding { activity -> ActivityAppBinding.bind(activity.findViewById(R.id.container)) }
private val scaleX = PropertyValuesHolder.ofFloat(View.SCALE_X, 0.5f, 1f)
private val scaleY = PropertyValuesHolder.ofFloat(View.SCALE_Y, 0.5f, 1f)
private val alpha = PropertyValuesHolder.ofFloat(View.ALPHA, 0f, 1f)
private var lastServiceMessage: ServiceMessage.ServiceState? = null
private val prefListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
if (key == BaseApp.LOGGING_ON_KEY) setLogging()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setLogging()
routeIntentAction(intent)
(application as BaseApp).sharedPreferences.registerOnSharedPreferenceChangeListener(prefListener)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
lifecycleScope.launchWhenResumed {
if (isNotificationPermissionGranted().not() || appSettings.addTileAsked.first()) return@launchWhenResumed
appSettings.setAddTileAsked(true)
TileActionService.askToAddTile(this@AppActivity)
}
}
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
with(findNavController(R.id.fr_activity_app_nav_host_fragment)) {
binding.bottomNavigationActivityApp.setupWithNavController(this)
addOnDestinationChangedListener { _, destination, _ ->
if (destination.id == R.id.nav_exitFragment) {
IntentAction.Exit.sendToAppService(this@AppActivity)
}
}
}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
routeIntentAction(intent)
}
override fun onDestroy() {
(application as BaseApp).sharedPreferences.unregisterOnSharedPreferenceChangeListener(prefListener)
super.onDestroy()
}
private fun routeIntentAction(intent: Intent?) {
val intentAction = IntentAction.fromIntent(intent) ?: return
XLog.d(getLog("routeIntentAction", "IntentAction: $intentAction"))
if (intentAction is IntentAction.StartStream) {
IntentAction.StartStream.sendToAppService(this)
}
}
@SuppressLint("CheckResult")
private fun setLogging() {
val loggingOn = (application as BaseApp).isLoggingOn
binding.llActivityAppLogs.visibility = if (loggingOn) View.VISIBLE else View.GONE
binding.vActivityAppLogs.visibility = if (loggingOn) View.VISIBLE else View.GONE
if (loggingOn)
binding.bActivityAppSendLogs.setOnClickListener {
MaterialDialog(this, BottomSheet(LayoutMode.WRAP_CONTENT)).show {
lifecycleOwner(this@AppActivity)
title(R.string.app_activity_send_logs_dialog_title)
icon(R.drawable.ic_about_feedback_24dp)
message(R.string.app_activity_send_logs_dialog_message)
input(
waitForPositiveButton = false,
allowEmpty = true,
inputType = InputType.TYPE_TEXT_FLAG_MULTI_LINE
) { dialog, text -> dialog.setActionButtonEnabled(WhichButton.NEGATIVE, text.isNotBlank()) }
positiveButton(android.R.string.cancel)
negativeButton(android.R.string.ok) {
sendLogsInEmail(applicationContext, getInputField().text.toString())
}
@Suppress("DEPRECATION")
neutralButton(R.string.app_activity_send_logs_dialog_neutral) {
(application as BaseApp).isLoggingOn = false
}
setActionButtonEnabled(WhichButton.NEGATIVE, false)
}
}
else
binding.bActivityAppSendLogs.setOnClickListener(null)
}
override fun onServiceMessage(serviceMessage: ServiceMessage) {
super.onServiceMessage(serviceMessage)
if (serviceMessage is ServiceMessage.ServiceState) {
lastServiceMessage != serviceMessage || return
XLog.d([email protected]("onServiceMessage", "$serviceMessage"))
binding.bottomNavigationActivityApp.menu.findItem(R.id.menu_fab).title =
if (serviceMessage.isStreaming) getString(R.string.bottom_menu_stop)
else getString(R.string.bottom_menu_start)
with(binding.fabActivityAppStartStop) {
visibility = View.VISIBLE
isEnabled = serviceMessage.isBusy.not()
backgroundTintList = if (serviceMessage.isBusy) {
ContextCompat.getColorStateList(this@AppActivity, R.color.colorIconDisabled)
} else {
ContextCompat.getColorStateList(this@AppActivity, R.color.colorAccent)
}
contentDescription = if (serviceMessage.isStreaming) {
setImageResource(R.drawable.ic_fab_stop_24dp)
setOnClickListener { IntentAction.StopStream.sendToAppService(this@AppActivity) }
getString(R.string.bottom_menu_stop)
} else {
setImageResource(R.drawable.ic_fab_start_24dp)
setOnClickListener { IntentAction.StartStream.sendToAppService(this@AppActivity) }
getString(R.string.bottom_menu_start)
}
}
if (serviceMessage.isStreaming != lastServiceMessage?.isStreaming) {
ObjectAnimator.ofPropertyValuesHolder(binding.fabActivityAppStartStop, scaleX, scaleY, alpha)
.apply { interpolator = OvershootInterpolator(); duration = 750 }
.start()
}
lastServiceMessage = serviceMessage
}
}
} | mit | c5307e35607f46b7b489bd7131a9b620 | 43.247191 | 121 | 0.681778 | 5.133638 | false | false | false | false |
JetBrains/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/serialization/KonanIrModuleSerializer.kt | 1 | 1746 | package org.jetbrains.kotlin.backend.konan.serialization
import org.jetbrains.kotlin.backend.common.serialization.*
import org.jetbrains.kotlin.backend.common.serialization.signature.IdSignatureSerializer
import org.jetbrains.kotlin.backend.konan.ir.interop.IrProviderForCEnumAndCStructStubs
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
import org.jetbrains.kotlin.ir.symbols.IrSymbol
import org.jetbrains.kotlin.ir.util.IrMessageLogger
class KonanIrModuleSerializer(
messageLogger: IrMessageLogger,
irBuiltIns: IrBuiltIns,
private val expectDescriptorToSymbol: MutableMap<DeclarationDescriptor, IrSymbol>,
val skipExpects: Boolean
) : IrModuleSerializer<KonanIrFileSerializer>(messageLogger) {
private val signaturer = IdSignatureSerializer(KonanManglerIr)
private val globalDeclarationTable = KonanGlobalDeclarationTable(signaturer, irBuiltIns)
// We skip files with IR for C structs and enums because they should be
// generated anew.
//
// See [IrProviderForCEnumAndCStructStubs.kt#L31] on why we generate IR.
// We may switch from IR generation to LazyIR later (at least for structs; enums are tricky)
// without changing kotlin libraries that depend on interop libraries.
override fun backendSpecificFileFilter(file: IrFile): Boolean =
file.fileEntry.name != IrProviderForCEnumAndCStructStubs.cTypeDefinitionsFileName
override fun createSerializerForFile(file: IrFile): KonanIrFileSerializer =
KonanIrFileSerializer(messageLogger, KonanDeclarationTable(globalDeclarationTable), expectDescriptorToSymbol, skipExpects = skipExpects)
}
| apache-2.0 | a6aae351aa68c13451c0a6fd886df5c3 | 51.909091 | 148 | 0.811569 | 4.570681 | false | false | false | false |
BijoySingh/Quick-Note-Android | base/src/main/java/com/maubis/scarlet/base/support/ui/ThemedBottomSheetFragment.kt | 1 | 3269 | package com.maubis.scarlet.base.support.ui
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.core.content.ContextCompat
import com.github.bijoysingh.starter.fragments.SimpleBottomSheetFragment
import com.maubis.scarlet.base.MainActivity
import com.maubis.scarlet.base.R
import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTheme
abstract class ThemedBottomSheetFragment : SimpleBottomSheetFragment() {
var appContext: Context? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val isTablet = maybeContext()?.resources?.getBoolean(R.bool.is_tablet) ?: false
val dialog = when {
isTablet -> BottomSheetTabletDialog(themedContext(), theme)
else -> super.onCreateDialog(savedInstanceState)
}
retainInstance = true
return dialog
}
override fun setupView(dialog: Dialog?) {
if (dialog == null) {
return
}
appContext = dialog.context.applicationContext
resetBackground(dialog)
}
fun themedActivity(): Activity = activity ?: context as AppCompatActivity
fun themedContext(): Context = maybeContext()!!
fun maybeContext(): Context? = context ?: activity ?: appContext
abstract fun getBackgroundView(): Int
fun resetBackground(dialog: Dialog) {
val backgroundColor = sAppTheme.get(ThemeColorType.BACKGROUND)
val containerLayout = dialog.findViewById<View>(getBackgroundView())
containerLayout.setBackgroundColor(backgroundColor)
for (viewId in getBackgroundCardViewIds()) {
val cardView = dialog.findViewById<CardView>(viewId)
cardView.setCardBackgroundColor(backgroundColor)
}
}
open fun getOptionsTitleColor(selected: Boolean): Int {
val colorResource = when {
sAppTheme.isNightTheme() && selected -> R.color.material_blue_300
sAppTheme.isNightTheme() -> R.color.light_secondary_text
selected -> R.color.material_blue_700
else -> R.color.dark_secondary_text
}
return ContextCompat.getColor(themedContext(), colorResource)
}
open fun getOptionsSubtitleColor(selected: Boolean): Int {
val colorResource = when {
sAppTheme.isNightTheme() && selected -> R.color.material_blue_200
sAppTheme.isNightTheme() -> R.color.light_tertiary_text
selected -> R.color.material_blue_500
else -> R.color.dark_tertiary_text
}
return ContextCompat.getColor(themedContext(), colorResource)
}
open fun getBackgroundCardViewIds(): Array<Int> = emptyArray()
fun makeBackgroundTransparent(dialog: Dialog, rootLayoutId: Int) {
val containerView = dialog.findViewById<View>(getBackgroundView())
containerView.setBackgroundColor(Color.TRANSPARENT)
val rootView = dialog.findViewById<View>(rootLayoutId)
val parentView = rootView.parent
if (parentView is View) {
parentView.setBackgroundResource(R.drawable.note_option_bs_gradient)
}
}
companion object {
fun openSheet(activity: MainActivity, sheet: ThemedBottomSheetFragment) {
sheet.show(activity.supportFragmentManager, sheet.tag)
}
}
} | gpl-3.0 | 32c8adddf29a8245644118f6219d50e7 | 33.421053 | 83 | 0.746406 | 4.643466 | false | false | false | false |
kotlinx/kotlinx.html | src/jsMain/kotlin/generated/gen-event-attrs-js.kt | 1 | 14325 | package kotlinx.html.js
import kotlinx.html.*
import kotlinx.html.attributes.*
import kotlinx.html.dom.*
import org.w3c.dom.events.*
/*******************************************************************************
DO NOT EDIT
This file was generated by module generate
*******************************************************************************/
var CommonAttributeGroupFacade.onAbortFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onAbort")
set(newValue) {consumer.onTagEvent(this, "onabort", newValue)}
var CommonAttributeGroupFacade.onBlurFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onBlur")
set(newValue) {consumer.onTagEvent(this, "onblur", newValue)}
var CommonAttributeGroupFacade.onCanPlayFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onCanPlay")
set(newValue) {consumer.onTagEvent(this, "oncanplay", newValue)}
var CommonAttributeGroupFacade.onCanPlayThroughFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onCanPlayThrough")
set(newValue) {consumer.onTagEvent(this, "oncanplaythrough", newValue)}
var CommonAttributeGroupFacade.onChangeFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onChange")
set(newValue) {consumer.onTagEvent(this, "onchange", newValue)}
var CommonAttributeGroupFacade.onClickFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onClick")
set(newValue) {consumer.onTagEvent(this, "onclick", newValue)}
var CommonAttributeGroupFacade.onContextMenuFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onContextMenu")
set(newValue) {consumer.onTagEvent(this, "oncontextmenu", newValue)}
var CommonAttributeGroupFacade.onDoubleClickFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onDoubleClick")
set(newValue) {consumer.onTagEvent(this, "ondblclick", newValue)}
var CommonAttributeGroupFacade.onDragFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onDrag")
set(newValue) {consumer.onTagEvent(this, "ondrag", newValue)}
var CommonAttributeGroupFacade.onDragEndFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onDragEnd")
set(newValue) {consumer.onTagEvent(this, "ondragend", newValue)}
var CommonAttributeGroupFacade.onDragEnterFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onDragEnter")
set(newValue) {consumer.onTagEvent(this, "ondragenter", newValue)}
var CommonAttributeGroupFacade.onDragLeaveFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onDragLeave")
set(newValue) {consumer.onTagEvent(this, "ondragleave", newValue)}
var CommonAttributeGroupFacade.onDragOverFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onDragOver")
set(newValue) {consumer.onTagEvent(this, "ondragover", newValue)}
var CommonAttributeGroupFacade.onDragStartFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onDragStart")
set(newValue) {consumer.onTagEvent(this, "ondragstart", newValue)}
var CommonAttributeGroupFacade.onDropFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onDrop")
set(newValue) {consumer.onTagEvent(this, "ondrop", newValue)}
var CommonAttributeGroupFacade.onDurationChangeFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onDurationChange")
set(newValue) {consumer.onTagEvent(this, "ondurationchange", newValue)}
var CommonAttributeGroupFacade.onEmptiedFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onEmptied")
set(newValue) {consumer.onTagEvent(this, "onemptied", newValue)}
var CommonAttributeGroupFacade.onEndedFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onEnded")
set(newValue) {consumer.onTagEvent(this, "onended", newValue)}
var CommonAttributeGroupFacade.onErrorFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onError")
set(newValue) {consumer.onTagEvent(this, "onerror", newValue)}
var CommonAttributeGroupFacade.onFocusFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onFocus")
set(newValue) {consumer.onTagEvent(this, "onfocus", newValue)}
var CommonAttributeGroupFacade.onFocusInFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onFocusIn")
set(newValue) {consumer.onTagEvent(this, "onfocusin", newValue)}
var CommonAttributeGroupFacade.onFocusOutFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onFocusOut")
set(newValue) {consumer.onTagEvent(this, "onfocusout", newValue)}
var CommonAttributeGroupFacade.onFormChangeFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onFormChange")
set(newValue) {consumer.onTagEvent(this, "onformchange", newValue)}
var CommonAttributeGroupFacade.onFormInputFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onFormInput")
set(newValue) {consumer.onTagEvent(this, "onforminput", newValue)}
var CommonAttributeGroupFacade.onInputFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onInput")
set(newValue) {consumer.onTagEvent(this, "oninput", newValue)}
var CommonAttributeGroupFacade.onInvalidFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onInvalid")
set(newValue) {consumer.onTagEvent(this, "oninvalid", newValue)}
var CommonAttributeGroupFacade.onKeyDownFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onKeyDown")
set(newValue) {consumer.onTagEvent(this, "onkeydown", newValue)}
var CommonAttributeGroupFacade.onKeyPressFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onKeyPress")
set(newValue) {consumer.onTagEvent(this, "onkeypress", newValue)}
var CommonAttributeGroupFacade.onKeyUpFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onKeyUp")
set(newValue) {consumer.onTagEvent(this, "onkeyup", newValue)}
var CommonAttributeGroupFacade.onLoadFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onLoad")
set(newValue) {consumer.onTagEvent(this, "onload", newValue)}
var CommonAttributeGroupFacade.onLoadedDataFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onLoadedData")
set(newValue) {consumer.onTagEvent(this, "onloadeddata", newValue)}
var CommonAttributeGroupFacade.onLoadedMetaDataFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onLoadedMetaData")
set(newValue) {consumer.onTagEvent(this, "onloadedmetadata", newValue)}
var CommonAttributeGroupFacade.onLoadStartFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onLoadStart")
set(newValue) {consumer.onTagEvent(this, "onloadstart", newValue)}
var CommonAttributeGroupFacade.onMouseDownFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onMouseDown")
set(newValue) {consumer.onTagEvent(this, "onmousedown", newValue)}
var CommonAttributeGroupFacade.onMouseMoveFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onMouseMove")
set(newValue) {consumer.onTagEvent(this, "onmousemove", newValue)}
var CommonAttributeGroupFacade.onMouseOutFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onMouseOut")
set(newValue) {consumer.onTagEvent(this, "onmouseout", newValue)}
var CommonAttributeGroupFacade.onMouseOverFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onMouseOver")
set(newValue) {consumer.onTagEvent(this, "onmouseover", newValue)}
var CommonAttributeGroupFacade.onMouseUpFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onMouseUp")
set(newValue) {consumer.onTagEvent(this, "onmouseup", newValue)}
var CommonAttributeGroupFacade.onMouseWheelFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onMouseWheel")
set(newValue) {consumer.onTagEvent(this, "onmousewheel", newValue)}
var CommonAttributeGroupFacade.onPauseFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onPause")
set(newValue) {consumer.onTagEvent(this, "onpause", newValue)}
var CommonAttributeGroupFacade.onPlayFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onPlay")
set(newValue) {consumer.onTagEvent(this, "onplay", newValue)}
var CommonAttributeGroupFacade.onPlayingFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onPlaying")
set(newValue) {consumer.onTagEvent(this, "onplaying", newValue)}
var CommonAttributeGroupFacade.onProgressFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onProgress")
set(newValue) {consumer.onTagEvent(this, "onprogress", newValue)}
var CommonAttributeGroupFacade.onRateChangeFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onRateChange")
set(newValue) {consumer.onTagEvent(this, "onratechange", newValue)}
var CommonAttributeGroupFacade.onReadyStateChangeFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onReadyStateChange")
set(newValue) {consumer.onTagEvent(this, "onreadystatechange", newValue)}
var CommonAttributeGroupFacade.onScrollFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onScroll")
set(newValue) {consumer.onTagEvent(this, "onscroll", newValue)}
var CommonAttributeGroupFacade.onSearchFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onSearch")
set(newValue) {consumer.onTagEvent(this, "onsearch", newValue)}
var CommonAttributeGroupFacade.onSeekedFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onSeeked")
set(newValue) {consumer.onTagEvent(this, "onseeked", newValue)}
var CommonAttributeGroupFacade.onSeekingFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onSeeking")
set(newValue) {consumer.onTagEvent(this, "onseeking", newValue)}
var CommonAttributeGroupFacade.onSelectFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onSelect")
set(newValue) {consumer.onTagEvent(this, "onselect", newValue)}
var CommonAttributeGroupFacade.onShowFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onShow")
set(newValue) {consumer.onTagEvent(this, "onshow", newValue)}
var CommonAttributeGroupFacade.onStalledFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onStalled")
set(newValue) {consumer.onTagEvent(this, "onstalled", newValue)}
var CommonAttributeGroupFacade.onSubmitFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onSubmit")
set(newValue) {consumer.onTagEvent(this, "onsubmit", newValue)}
var CommonAttributeGroupFacade.onSuspendFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onSuspend")
set(newValue) {consumer.onTagEvent(this, "onsuspend", newValue)}
var CommonAttributeGroupFacade.onTimeUpdateFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onTimeUpdate")
set(newValue) {consumer.onTagEvent(this, "ontimeupdate", newValue)}
var CommonAttributeGroupFacade.onTouchCancelFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onTouchCancel")
set(newValue) {consumer.onTagEvent(this, "ontouchcancel", newValue)}
var CommonAttributeGroupFacade.onTouchEndFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onTouchEnd")
set(newValue) {consumer.onTagEvent(this, "ontouchend", newValue)}
var CommonAttributeGroupFacade.onTouchMoveFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onTouchMove")
set(newValue) {consumer.onTagEvent(this, "ontouchmove", newValue)}
var CommonAttributeGroupFacade.onTouchStartFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onTouchStart")
set(newValue) {consumer.onTagEvent(this, "ontouchstart", newValue)}
var CommonAttributeGroupFacade.onVolumeChangeFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onVolumeChange")
set(newValue) {consumer.onTagEvent(this, "onvolumechange", newValue)}
var CommonAttributeGroupFacade.onWaitingFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onWaiting")
set(newValue) {consumer.onTagEvent(this, "onwaiting", newValue)}
var CommonAttributeGroupFacade.onWheelFunction : (Event) -> Unit
get() = throw UnsupportedOperationException("You can't read variable onWheel")
set(newValue) {consumer.onTagEvent(this, "onwheel", newValue)}
| apache-2.0 | 553926f43f0e7120a94e21a0088c062c | 54.096154 | 94 | 0.755881 | 4.415845 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.