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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Cardstock/Cardstock
|
src/test/kotlin/xyz/cardstock/cardstock/games/GameRegistrarSpec.kt
|
1
|
2702
|
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package xyz.cardstock.cardstock.games
import org.jetbrains.spek.api.Spek
import org.kitteh.irc.client.library.element.Channel
import org.powermock.api.mockito.PowerMockito.mock
import xyz.cardstock.cardstock.implementations.DummyCardstock
import xyz.cardstock.cardstock.implementations.games.DummyGameRegistrar
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
class GameRegistrarSpec : Spek({
fun makeChannel(): Channel {
val channel = mock(Channel::class.java)
return channel
}
given("a standard game registrar") {
val cardstock = DummyCardstock()
val channel = makeChannel()
val gameRegistrar = DummyGameRegistrar(cardstock)
on("registering a game") {
val game = gameRegistrar.on(channel)
it("should have one game") {
assertEquals(1, gameRegistrar.all().size)
}
it("should return the same game if queried by channel") {
assertTrue(game === gameRegistrar.find(channel))
}
}
on("registering the same game again") {
val oldGame = gameRegistrar.find(channel)
val game = gameRegistrar.on(channel)
it("should return the same game") {
assertTrue(oldGame === game)
}
}
}
given("a game registrar with one game") {
val cardstock = DummyCardstock()
val channel = makeChannel()
val gameRegistrar = DummyGameRegistrar(cardstock)
gameRegistrar.on(channel)
on("unregistering the same game") {
gameRegistrar.end(channel)
it("should have zero games") {
assertEquals(0, gameRegistrar.all().size)
}
it("should return null if queried by channel") {
assertNull(gameRegistrar.find(channel))
}
}
}
given("another game registrar with one game") {
val cardstock = DummyCardstock()
val channel = makeChannel()
val gameRegistrar = DummyGameRegistrar(cardstock)
val game = gameRegistrar.on(channel)
on("unregistering the same game") {
gameRegistrar.end(game)
it("should have zero games") {
assertEquals(0, gameRegistrar.all().size)
}
it("should return null if queried by channel") {
assertNull(gameRegistrar.find(channel))
}
}
}
})
|
mpl-2.0
|
b7026f4901513dea0607eb600e7fde08
| 35.026667 | 71 | 0.6151 | 4.564189 | false | false | false | false |
signed/intellij-community
|
plugins/stats-collector/log-events/test/com/intellij/stats/events/completion/RealTextValidator.kt
|
1
|
2390
|
package com.intellij.stats.events.completion
import org.assertj.core.api.Assertions
import org.junit.Test
class RealTextValidator {
@Test
fun test_NegativeIndexToErrChannel() {
val file = getFile("data/completion_data.txt")
val output = java.io.ByteArrayOutputStream()
val err = java.io.ByteArrayOutputStream()
val separator = com.intellij.stats.events.completion.SessionsInputSeparator(java.io.FileInputStream(file), output, err)
separator.processInput()
}
private fun getFile(path: String): java.io.File {
return java.io.File(javaClass.classLoader.getResource(path).file)
}
@Test
fun test0() {
val file = getFile("data/0")
val output = java.io.ByteArrayOutputStream()
val err = java.io.ByteArrayOutputStream()
val separator = com.intellij.stats.events.completion.SessionsInputSeparator(java.io.FileInputStream(file), output, err)
separator.processInput()
Assertions.assertThat(err.size()).isEqualTo(0)
}
@Test
fun testError0() {
val file = getFile("data/1")
val output = java.io.ByteArrayOutputStream()
val err = java.io.ByteArrayOutputStream()
val separator = com.intellij.stats.events.completion.SessionsInputSeparator(java.io.FileInputStream(file), output, err)
separator.processInput()
Assertions.assertThat(err.size()).isEqualTo(0)
}
}
class ErrorSessionDumper(input: java.io.InputStream, output: java.io.OutputStream, error: java.io.OutputStream) : com.intellij.stats.events.completion.SessionsInputSeparator(input, output, error) {
var totalFailedSessions = 0
var totalSuccessSessions = 0
private val dir = java.io.File("errors")
init {
dir.mkdir()
}
override fun onSessionProcessingFinished(session: List<com.intellij.stats.events.completion.EventLine>, isValidSession: Boolean) {
if (!isValidSession) {
val file = java.io.File(dir, totalFailedSessions.toString())
if (file.exists()) {
file.delete()
}
file.createNewFile()
session.forEach {
file.appendText(it.line)
file.appendText("\n")
}
totalFailedSessions++
}
else {
totalSuccessSessions++
}
}
}
|
apache-2.0
|
21c87b522a8a395942b0c719db6cfa36
| 31.310811 | 197 | 0.64477 | 4.361314 | false | true | false | false |
JiangKlijna/leetcode-learning
|
kt/035 Search Insert Position/SearchInsertPosition.kt
|
1
|
596
|
//Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
class SearchInsertPosition {
fun searchInsert(nums: IntArray, target: Int): Int {
var left = 0
var right = nums.size - 1
while (left <= right) {
var mid = (left + right) / 2
if (nums[mid] === target)
return mid
else if (nums[mid] < target)
left = mid + 1
else
right = mid - 1
}
return left
}
}
|
mit
|
fca6d482754af0440b947c6c9d483b11
| 32.111111 | 156 | 0.525168 | 4.28777 | false | false | false | false |
gatheringhallstudios/MHGenDatabase
|
app/src/main/java/com/ghstudios/android/features/monsters/detail/MonsterSummaryFragment.kt
|
1
|
10458
|
package com.ghstudios.android.features.monsters.detail
import androidx.lifecycle.Observer
import android.content.Context
import android.os.Bundle
import androidx.annotation.DrawableRes
import androidx.fragment.app.Fragment
import androidx.core.content.ContextCompat
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import com.ghstudios.android.ClickListeners.LocationClickListener
import com.ghstudios.android.components.SectionHeaderCell
import com.ghstudios.android.components.TitleBarCell
import com.ghstudios.android.mhgendatabase.R
import com.ghstudios.android.*
import com.ghstudios.android.data.classes.*
import com.ghstudios.android.mhgendatabase.databinding.FragmentMonsterSummaryBinding
private fun imageFromWeaknessRating(weaknessRating: WeaknessRating) = when(weaknessRating) {
WeaknessRating.WEAK -> R.drawable.effectiveness_2
WeaknessRating.VERY_WEAK -> R.drawable.effectiveness_3
else -> null
}
private fun localizeAilment(ctx: Context, ailmentStr: String): String {
val resId = when (ailmentStr) {
"Small Roar" -> R.string.ailment_roar_small
"Large Roar" -> R.string.ailment_roar_large
"Small Special Roar" -> R.string.ailment_roar_small_special
"Special Roar" -> R.string.ailment_roar_special
"Small Wind Pressure" -> R.string.ailment_wind_small
"Large Wind Pressure" -> R.string.ailment_wind_large
"Dragon Wind Pressure" -> R.string.ailment_wind_dragon
"Tremor" -> R.string.ailment_tremor
"Fireblight" -> R.string.ailment_fire
"Waterblight" -> R.string.ailment_water
"Thunderblight" -> R.string.ailment_thunder
"Iceblight" -> R.string.ailment_ice
"Dragonblight" -> R.string.ailment_dragon
"Blastblight" -> R.string.ailment_blast
"Bleeding" -> R.string.ailment_bleed
"Poison" -> R.string.ailment_poison
"Noxious Poison" -> R.string.ailment_poison_noxious
"Deadly Poison" -> R.string.ailment_poison_deadly
"Sleep" -> R.string.ailment_sleep
"Paralysis" -> R.string.ailment_paralysis
"Stun" -> R.string.ailment_stun
"Snowman" -> R.string.ailment_snowman
"Muddy" -> R.string.ailment_muddy
"Bubbles" -> R.string.ailment_bubbles
"Boned" -> R.string.ailment_boned
"Mucus" -> R.string.ailment_mucus
"Soiled" -> R.string.ailment_soiled
"Environmental" -> R.string.ailment_environmental
"Defense Down" -> R.string.ailment_defensedown
"Frenzy Virus" -> R.string.ailment_frenzy
"Confusion" -> R.string.ailment_confusion
else -> 0
}
if (resId == 0) {
Log.e("MonsterSummary", "Ailment localization failed for $ailmentStr")
return ailmentStr
}
return ctx.getString(resId)
}
/**
* Represents a subfragment displayed in the summary tab of the monster detail.
*/
class MonsterSummaryFragment : Fragment() {
companion object {
private val ARG_MONSTER_ID = "MONSTER_ID"
@JvmStatic
fun newInstance(monsterId: Long): MonsterSummaryFragment {
val args = Bundle()
args.putLong(ARG_MONSTER_ID, monsterId)
val f = MonsterSummaryFragment()
f.arguments = args
return f
}
}
private val TAG = this::class.java.simpleName
private lateinit var binding: FragmentMonsterSummaryBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
binding = FragmentMonsterSummaryBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val viewModel = ViewModelProvider(activity!!).get(MonsterDetailViewModel::class.java)
viewModel.monsterData.observe(viewLifecycleOwner, Observer { monster ->
if (monster == null) return@Observer
binding.monsterHeader.setIcon(monster)
binding.monsterHeader.setTitleText(monster.name)
})
viewModel.weaknessData.observe(viewLifecycleOwner, Observer(::updateWeaknesses))
viewModel.ailmentData.observe(viewLifecycleOwner, Observer(::populateAilments))
viewModel.habitatData.observe(viewLifecycleOwner, Observer(::populateHabitats))
}
/**
* Populates weakness data in the view using the provided data.
* If null or empty, then nothing is rendered regarding weaknesses
*/
private fun updateWeaknesses(weaknesses: List<MonsterWeaknessResult>?) {
binding.monsterStateList.removeAllViews()
if (weaknesses == null || weaknesses.isEmpty()) return
for (weakness in weaknesses) {
addWeakness(weakness)
}
}
private fun addWeakness(mWeakness: MonsterWeaknessResult) {
val inflater = LayoutInflater.from(context)
val weaknessView = inflater.inflate(R.layout.fragment_monster_summary_state, binding.monsterStateList, false)
// Set title
val header = weaknessView.findViewById<SectionHeaderCell>(R.id.state_name)
header.setLabelText(mWeakness.state)
val weaknessListView = weaknessView.findViewById<ViewGroup>(R.id.weakness_data)
val itemListView = weaknessView.findViewById<ViewGroup>(R.id.item_data)
// weakness line (element part)
for (value in mWeakness.element) {
val imagePath = ElementRegistry[value.type]
val imageModification = imageFromWeaknessRating(value.rating)
addIcon(weaknessListView, imagePath, imageModification)
}
// weakness line (status part)
for (value in mWeakness.status) {
val imagePath = ElementRegistry[value.type]
val imageModification = imageFromWeaknessRating(value.rating)
addIcon(weaknessListView, imagePath, imageModification)
}
// items line
for (trapType in mWeakness.items) {
val imagePath = when (trapType) {
WeaknessType.PITFALL_TRAP -> R.drawable.item_trap_pitfall
WeaknessType.SHOCK_TRAP -> R.drawable.item_trap_shock
WeaknessType.MEAT -> R.drawable.item_meat
WeaknessType.FLASH_BOMB -> R.drawable.item_bomb_flash
WeaknessType.SONIC_BOMB -> R.drawable.item_bomb_sonic
WeaknessType.DUNG_BOMB -> R.drawable.item_bomb_dung
}
addIcon(itemListView, imagePath, null)
}
binding.monsterStateList.addView(weaknessView)
}
/**
* Populates ailment data in the view using the provided data.
* If null or empty is given, the blank slate is shown instead.
*/
private fun populateAilments(ailments: List<MonsterAilment>?) {
// if no ailments, show blank slate instead of the ailment list, and return
if (ailments == null || ailments.isEmpty()) {
binding.ailmentsEmpty.root.visibility = View.VISIBLE
binding.ailmentsData.visibility = View.GONE
return
}
// hide blank slate, and make the ailment list visible
binding.ailmentsEmpty.root.visibility = View.GONE
binding.ailmentsData.visibility = View.VISIBLE
binding.ailmentsData.text = ailments.joinToString("\n") {
localizeAilment(context!!, it.ailment)
}
}
/**
* Populates habitat data in th e view using the provided data.
* If null or empty is given, the blank slate is shown instead.
*/
private fun populateHabitats(habitats: List<Habitat>?) {
if (habitats == null || habitats.isEmpty()) {
binding.habitatsEmpty.root.visibility = View.VISIBLE
return
}
binding.habitatsEmpty.root.visibility = View.GONE
val inflater = LayoutInflater.from(context)
binding.habitatList.removeAllViews()
for (habitat in habitats) {
val view = inflater.inflate(R.layout.fragment_monster_habitat_listitem, binding.habitatList, false)
val itemLayout = view.findViewById<RelativeLayout>(R.id.listitem)
val mapView = view.findViewById<ImageView>(R.id.mapImage)
val mapTextView = view.findViewById<TextView>(R.id.map)
val startTextView = view.findViewById<TextView>(R.id.start)
val areaTextView = view.findViewById<TextView>(R.id.move)
val restTextView = view.findViewById<TextView>(R.id.rest)
mapTextView.text = habitat.location?.name
startTextView.text = habitat.start.toString()
areaTextView.text = habitat.areas?.joinToString(", ")
restTextView.text = habitat.rest.toString()
AssetLoader.setIcon(mapView,habitat.location!!)
val locationId = habitat.location?.id
if (locationId != null) {
itemLayout.tag = locationId
itemLayout.setOnClickListener(LocationClickListener(context, locationId))
}
binding.habitatList.addView(view)
}
}
// Add small_icon to a particular LinearLayout
private fun addIcon(parentview: ViewGroup, @DrawableRes image: Int?, @DrawableRes mod: Int?) {
if (image == null) {
Log.e(TAG, "Tried to add null image as an icon")
return
}
// Create new small_icon layout
val inflater = LayoutInflater.from(context)
val view = inflater.inflate(R.layout.fragment_monster_summary_weakness, parentview, false)
// Get reference to image in small_icon layout
val mImage = view.findViewById<ImageView>(R.id.image)
val mImageMod = view.findViewById<ImageView>(R.id.image_mod)
// Open Image
val mainImage = ContextCompat.getDrawable(context!!, image)
mImage.setImageDrawable(mainImage)
// Open Image Mod if applicable
if (mod != null) {
val modImage = ContextCompat.getDrawable(context!!, mod)
mImageMod.setImageDrawable(modImage)
mImageMod.visibility = View.VISIBLE
}
// Add small_icon to appropriate layout
parentview.addView(view)
}
}
|
mit
|
cf4692ed326c0c0307bc98c6ef468d79
| 38.464151 | 117 | 0.665232 | 4.1832 | false | false | false | false |
RyanAndroidTaylor/Rapido
|
rapidocommon/src/main/java/com/izeni/rapidocommon/network/RetroPagination.kt
|
1
|
4686
|
@file:Suppress("unused")
package com.izeni.rapidocommon.network
import android.net.Uri
import com.izeni.rapidocommon.network.NetworkCallback
import com.izeni.rapidocommon.network.SimpleNetworkCallback
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.ArrayList
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 Izeni, Inc.
*
* 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.
**/
fun <T> Observable<PagedObject<T>>.getPage(callback: NetworkCallback<PagedResult<T>>) =
subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
val nextPage = if (it.next.isNullOrBlank()) null else Uri.parse(it.next).getQueryParameter("page")?.toInt()
callback.onSuccess(PagedResult(it.results, nextPage))
},
{
if (it is HttpException) callback.onError(it) else callback.onFatal(it)
}
)!!
class PagedResult<out T>(val results: List<T>, val nextPage: Int?)
fun <T> Observable<PagedObject<T>>.pagedListTransformer() = map { it.results }!!
class PagedObject<T> {
var count: Int = 0
var next: String? = null
var previous: String? = null
var results: List<T> = ArrayList()
}
class PageHandler<T>(pageInterface: (Int) -> Observable<PagedObject<T>>) {
var nextPage: Int? = 0
private set
private var pageObservable: (Int) -> Observable<PagedObject<T>>
init {
pageObservable = pageInterface
}
fun modifyPageObservable(pageInterface: (Int) -> Observable<PagedObject<T>>, reset: Boolean) {
pageObservable = pageInterface
if (reset) reset()
}
fun reset() {
nextPage = 0
}
fun getNextPage(onSuccess: (List<T>) -> Unit, onError: (Throwable) -> Unit) {
getSpecificPage(nextPage, onError) {
val newList: MutableList<T> = arrayListOf()
newList.addAll(it.results)
nextPage = it.nextPage
onSuccess(newList)
}
}
private fun getSpecificPage(page: Int?, onError: (Throwable) -> Unit, onNext: (PagedResult<T>) -> Unit) {
if (page != null) {
pageObservable(page).getPage(
object : SimpleNetworkCallback<PagedResult<T>>() {
override fun onError(exception: HttpException) {
onError(exception)
}
override fun onFatal(exception: Throwable) {
onError(exception)
}
override fun onSuccess(data: PagedResult<T>) {
onNext(data)
}
})
}
}
fun getAllPages(onSuccess: (List<T>) -> Unit, onError: (Throwable) -> Unit, pageStart: Int = 0) {
val newList: MutableList<T> = arrayListOf()
getPageRecursive(newList, pageStart, onSuccess, onError)
}
private fun getPageRecursive(list: MutableList<T>, page: Int?, onSuccess: (List<T>) -> Unit, onError: (Throwable) -> Unit) {
getSpecificPage(page, onError) {
list.addAll(it.results)
if (it.nextPage == null) {
nextPage = it.nextPage
onSuccess(list)
} else {
getPageRecursive(list, it.nextPage, onSuccess, onError)
}
}
}
}
|
mit
|
6d6ec09ce9647aeb3dcdecb5ed996aa8
| 35.905512 | 135 | 0.61545 | 4.612205 | false | false | false | false |
luoyuan800/NeverEnd
|
dataModel/src/cn/luo/yuan/maze/model/goods/types/RandomAccessoryElement.kt
|
1
|
1402
|
package cn.luo.yuan.maze.model.goods.types
import cn.luo.yuan.maze.model.Accessory
import cn.luo.yuan.maze.model.Element
import cn.luo.yuan.maze.model.Parameter
import cn.luo.yuan.maze.model.goods.GoodsProperties
import cn.luo.yuan.maze.model.goods.UsableGoods
import cn.luo.yuan.maze.service.InfoControlInterface
import cn.luo.yuan.maze.utils.Field
/**
* Created by luoyuan on 2017/9/4.
*/
class RandomAccessoryElement: UsableGoods() {
companion object {
private const val serialVersionUID: Long = Field.SERVER_VERSION
}
override fun perform(properties: GoodsProperties): Boolean {
val context:InfoControlInterface? = properties[Parameter.CONTEXT] as InfoControlInterface
val hero = properties.hero
if(context!=null){
try {
val acc:Accessory = context.random.randomItem(hero.accessories.toList())!!
acc.element = context.random.randomItem(Element.values())
context.dataManager.saveAccessory(acc)
return true
}catch (e :Exception){
return false
}
}
return false
}
override var desc: String = "随机选择一件<br>身上</b>的装备,随机改变该装备的五行属性"
override var name: String = "五行珠"
override var price: Long = 900000
override fun canLocalSell(): Boolean {
return false
}
}
|
bsd-3-clause
|
30c7514316e1c8f97a59aa0a356f02d3
| 31.902439 | 97 | 0.675074 | 3.862464 | false | false | false | false |
Magneticraft-Team/Magneticraft
|
src/main/kotlin/com/cout970/magneticraft/systems/computer/Motherboard.kt
|
2
|
2525
|
package com.cout970.magneticraft.systems.computer
import com.cout970.magneticraft.api.computer.*
import gnu.trove.map.hash.TIntObjectHashMap
/**
* Created by cout970 on 2016/09/30.
*/
class Motherboard(
private val cpu: ICPU,
private val ram: IRAM,
private val rom: IROM
) : IMotherboard {
companion object {
const val CPU_START_POINT = 0xE000
}
var cyclesPerTick = 1_000_000 / 20 // 1MHz
val deviceMap = TIntObjectHashMap<IDevice>()
private val bus = Bus(ram) { deviceMap[it] }
private var cpuCycles = -1
private var clock = 0
private var sleep = 0
init {
cpu.setMotherboard(this)
}
fun iterate() {
if (sleep > 0) {
sleep--
return
}
if (cpuCycles >= 0) {
cpuCycles += cyclesPerTick
// Limits cycles if the CPU halts using sleep();
if (cpuCycles > cyclesPerTick * 10) {
cpuCycles = cyclesPerTick * 10
}
while (cpuCycles > 0) {
cpuCycles--
clock++
cpu.iterate()
}
}
}
fun sleep(ticks: Int) {
if (ticks > 0) {
cpuCycles = 0
sleep = ticks
}
}
override fun start() {
cpuCycles = 0
}
override fun halt() {
cpuCycles = -1
}
override fun isOnline() = cpuCycles >= 0
override fun reset() {
clock = 0
cpu.reset()
deviceMap.values().filterIsInstance<IResettable>().forEach { it.reset() }
rom.bios.use {
var index = CPU_START_POINT
while (true) {
val r = it.read()
if (r == -1) break
ram.writeByte(index++, r.toByte())
}
}
}
override fun getBus(): IRW = bus
override fun getCPU(): ICPU = cpu
override fun getRAM(): IRAM = ram
override fun getROM(): IROM = rom
override fun getClock(): Int = clock
override fun serialize(): Map<String, Any> {
return mapOf(
"sleep" to sleep,
"cycles" to cpuCycles,
"cpu" to cpu.serialize(),
"ram" to ram.serialize()
)
}
@Suppress("UNCHECKED_CAST")
override fun deserialize(map: Map<String, Any>) {
sleep = map["sleep"] as Int
cpuCycles = map["cycles"] as Int
cpu.deserialize(map["cpu"] as Map<String, Any>)
ram.deserialize(map["ram"] as Map<String, Any>)
}
}
|
gpl-2.0
|
79914996e605922732a62eb3289e2089
| 21.553571 | 81 | 0.520792 | 4.13257 | false | false | false | false |
alondero/nestlin
|
src/test/kotlin/com/github/alondero/nestlin/GoldenLogTest.kt
|
1
|
3252
|
package com.github.alondero.nestlin
import com.github.alondero.nestlin.cpu.UnhandledOpcodeException
import org.junit.Test
import java.io.ByteArrayOutputStream
import java.io.PrintStream
import java.nio.file.Files
import java.nio.file.Paths
class GoldenLogTest {
@Test // TODO: Tidy up when more of a regression test
fun compareToGoldenLog() {
val prevOut = System.out
var nestlinOut = ByteArrayOutputStream()
System.setOut(PrintStream(nestlinOut))
try {
Nestlin().apply {
load(Paths.get("testroms/nestest.nes"))
powerReset()
enableLogging()
start()
}
} catch (e: UnhandledOpcodeException) {
// Do nothing
}
System.setOut(prevOut)
println("START\n${nestlinOut}\nEND")
// Trawl through output comparing line by line with the golden log
val log = LogComparison(golden = Files.readAllLines(Paths.get("src/test/resources/nestest.log")), currLog = nestlinOut.toString().split(System.getProperty("line.separator")))
(0..log.size - 1)
.filter { !log.emptyLine(it) }
.map { log.lineComparison(it) }
.forEach {
line -> line.mismatchedTokens().firstOrNull()?.let {
throw AssertionError("Token mismatch on line ${line.line}, with address ${line.currLogTokens[0]}. Expected token:${it.tokenName()} to be ${line.goldenTokens[it]} but was ${line.currLogTokens[it]}.\nExpected line:\n${line.goldenLine}\nActual line:\n${line.currLogLine}")
}
}
}
class LogComparison(val golden: List<String>, val currLog: List<String>) {
val size = currLog.size
fun lineComparison(line: Int) = LogLine(line, golden[line], currLog[line])
fun emptyLine(line: Int) = currLog[line].isEmpty()
}
class LogLine(val line: Int, val goldenLine: String, val currLogLine: String) {
val goldenTokens = split(goldenLine)
val currLogTokens = split(currLogLine)
fun mismatchedTokens() = (0..currLogTokens.size - 1)
.filter { !currLogTokens[it].equals(goldenTokens[it]) }
.filter { !(it == 5 && currLogTokens[it].contains("=")) }
.filter { !(it == 6 && currLogTokens[1].equals("29")) }
private fun split(line: String) = arrayOf(
line.substring(0, 4),
line.substring(6, 8),
line.substring(9, 11),
line.substring(12, 14),
line.substring(16, 19),
line.substring(20, 48),
line.substring(50, 52),
line.substring(55, 57),
line.substring(60, 62),
line.substring(65, 67),
line.substring(71, 73))
// Ignore cycles for now
}
private fun Int.tokenName() =
when (this) {
0 -> "PC"
1 -> "O#"
2 -> "M1"
3 -> "M2"
4 -> "M3"
5 -> "OP"
6 -> "A"
7 -> "X"
8 -> "Y"
9 -> "P"
10 -> "SP"
else -> "CYC"
}
}
|
gpl-3.0
|
e9fc295da786ae2e2c76d246f6914b49
| 34.747253 | 293 | 0.536593 | 4.02974 | false | true | false | false |
ScreamingHawk/phone-saver
|
app/src/main/java/link/standen/michael/phonesaver/util/DebugLogger.kt
|
1
|
2293
|
package link.standen.michael.phonesaver.util
import android.app.Activity
import android.content.Context
import android.preference.PreferenceManager
import android.util.Log
import android.widget.Toast
import link.standen.michael.phonesaver.R
import java.util.*
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
/**
* A log wrapper that also logs to the user.
* logLevel: 0 = None, 1 = Error, 2 = Warn, 3 = Info, 4 = Debug, 5 = Verbose
*/
class DebugLogger(private val context: Context, forceTag: String? = null) {
private val tag = forceTag?.let {
it
}?: context::class.java.simpleName
private val logLevel = context.resources.getStringArray(R.array.pref_list_values_log_to_user).indexOf(
PreferenceManager.getDefaultSharedPreferences(context).getString(
"log_to_user", context.resources.getString(R.string.pref_default_value_log_to_user)))
companion object {
private var EXECUTOR: ScheduledExecutorService? = null
private val TOAST_QUEUE: Queue<Runnable> = ConcurrentLinkedQueue()
}
init {
if (EXECUTOR == null){
EXECUTOR = Executors.newSingleThreadScheduledExecutor()
EXECUTOR?.scheduleAtFixedRate({
TOAST_QUEUE.poll()?.run()
}, 0, 100, TimeUnit.MILLISECONDS)
}
}
fun v(msg: String){
Log.v(tag, msg)
if (logLevel >= 5){
makeToast("VERBOSE: $msg")
}
}
fun d(msg: String){
Log.d(tag, msg)
if (logLevel >= 4){
makeToast("DEBUG: $msg")
}
}
fun i(msg: String){
Log.i(tag, msg)
if (logLevel >= 3){
makeToast("INFO: $msg")
}
}
fun w(msg: String){
Log.w(tag, msg)
if (logLevel >= 2){
makeToast("WARN: $msg")
}
}
fun e(msg: String, e: Exception? = null){
Log.e(tag, msg, e)
if (logLevel >= 1){
makeToast("ERROR: $msg")
e?.let {
makeToast("ERROR: ${it.message}")
}
}
}
private fun makeToast(msg: String){
if (EXECUTOR == null){
Log.e(tag, "No executor for debug toaster")
} else {
if (context is Activity) {
TOAST_QUEUE.offer(Runnable {
context.runOnUiThread {
Toast.makeText(context.applicationContext, msg, Toast.LENGTH_SHORT).show()
}
// Sleep for length of a short toast
Thread.sleep(2000)
})
}
}
}
}
|
mit
|
c7061030c2e37f6a295fba6d62ea9257
| 22.885417 | 103 | 0.682948 | 3.243281 | false | false | false | false |
toastkidjp/Jitte
|
app/src/main/java/jp/toastkid/yobidashi/menu/MenuAdapter.kt
|
1
|
2282
|
/*
* Copyright (c) 2019 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.menu
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import jp.toastkid.yobidashi.R
import jp.toastkid.lib.preference.PreferenceApplier
/**
* @author toastkidjp
*/
internal class MenuAdapter(
private val inflater: LayoutInflater,
private val preferenceApplier: PreferenceApplier,
private val menuViewModel: MenuViewModel?
) : RecyclerView.Adapter<MenuViewHolder>() {
/**
* Menu.
*/
private val menus: Array<Menu> = Menu.values()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MenuViewHolder =
MenuViewHolder(
DataBindingUtil.inflate(inflater, LAYOUT_ID, parent, false)
)
override fun onBindViewHolder(holder: MenuViewHolder, position: Int) {
val menu = menus[position % menus.size]
holder.setColorPair(preferenceApplier.colorPair())
holder.setText(menu.titleId)
holder.setImage(menu.iconId)
holder.setOnClick(View.OnClickListener { menuViewModel?.click(menu) })
holder.setOnLongClick(
View.OnLongClickListener {
menuViewModel?.longClick(menu)
true
}
)
}
override fun getItemCount(): Int = MAXIMUM
companion object {
/**
* Layout ID.
*/
@LayoutRes
private const val LAYOUT_ID = R.layout.item_home_menu
/**
* Maximum length of menus.
*/
private val MAXIMUM = Menu.values().size * 20
/**
* Medium position of menus.
*/
private val MEDIUM = MAXIMUM / 2
/**
* Return medium position of menus.
* @return MEDIUM
*/
fun mediumPosition(): Int = MEDIUM
}
}
|
epl-1.0
|
0e90ca13c353878fa5ba3d6de74c3a75
| 28.25641 | 88 | 0.641981 | 4.896996 | false | false | false | false |
wenhaiz/ListenAll
|
app/src/main/java/com/wenhaiz/himusic/module/main/local/LocalFragment.kt
|
1
|
8190
|
package com.wenhaiz.himusic.module.main.local
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import butterknife.Unbinder
import com.wenhaiz.himusic.R
import com.wenhaiz.himusic.data.bean.Collect
import com.wenhaiz.himusic.data.bean.LikedCollect
import com.wenhaiz.himusic.data.bean.LikedCollect_
import com.wenhaiz.himusic.ext.hide
import com.wenhaiz.himusic.ext.show
import com.wenhaiz.himusic.ext.showToast
import com.wenhaiz.himusic.module.detail.DetailContract
import com.wenhaiz.himusic.module.detail.DetailFragment
import com.wenhaiz.himusic.module.liked.LikedFragment
import com.wenhaiz.himusic.module.playhistory.PlayHistoryFragment
import com.wenhaiz.himusic.utils.BoxUtil
import com.wenhaiz.himusic.utils.GlideApp
import com.wenhaiz.himusic.utils.addFragmentToMainView
class LocalFragment : android.support.v4.app.Fragment() {
@BindView(R.id.main_song_list)
lateinit var mCollects: RecyclerView
// @BindView(R.id.main_local_scroll)
// lateinit var mScrollView: ScrollView
@BindView(R.id.main_local_btn_liked_collect)
lateinit var mBtnLikedCollect: Button
@BindView(R.id.main_local_btn_my_collect)
lateinit var mBtnMyCollect: Button
@BindView(R.id.main_local_create_collect)
lateinit var mBtnCreateCollect: ImageButton
private lateinit var mUnBinder: Unbinder
private lateinit var mCollectAdapter: CollectAdapter
private var curShowType = MY_COLLECT//当前显示的歌单类型(收藏歌单或者自建歌单)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val rootView = inflater.inflate(R.layout.fragment_main_local, container, false)
mUnBinder = ButterKnife.bind(this, rootView)
initView()
return rootView
}
fun initView() {
mCollectAdapter = CollectAdapter(ArrayList())
mCollects.adapter = mCollectAdapter
mCollects.layoutManager = LinearLayoutManager(context)
}
override fun onResume() {
super.onResume()
showCollects()
}
@OnClick(R.id.main_local_btn_songs, R.id.main_local_btn_recent_play, R.id.main_local_btn_liked,
R.id.main_local_btn_my_collect, R.id.main_local_btn_liked_collect, R.id.main_local_create_collect)
fun onClick(v: View) {
when (v.id) {
R.id.main_local_btn_songs -> {//本地歌曲
}
R.id.main_local_btn_recent_play -> {//最近播放
addFragmentToMainView(fragmentManager!!, PlayHistoryFragment())
}
R.id.main_local_btn_liked -> {//收藏
addFragmentToMainView(fragmentManager!!, LikedFragment())
}
R.id.main_local_btn_my_collect -> {//我的歌单
curShowType = MY_COLLECT
showCollects()
}
R.id.main_local_btn_liked_collect -> {//收藏歌单
curShowType = LIKED_COLLECT
showCollects()
}
R.id.main_local_create_collect -> {//创建歌单
val intent = Intent(context, EditCollectActivity::class.java)
intent.action = EditCollectActivity.ACTION_CREATE
startActivityForResult(intent, REQUEST_CREATE_COLLECT)
}
}
}
/**
* 显示歌单
*/
fun showCollects() {
setButtonTextColor(curShowType)
if (curShowType == MY_COLLECT) {//显示自建歌单
mBtnCreateCollect.show()
val collectBox = BoxUtil.getBoxStore(context!!).boxFor(Collect::class.java)
val myCollects = collectBox.query().build().find()
mCollectAdapter.setData(myCollects)
} else {//显示收藏歌单
mBtnCreateCollect.hide()
val collectBox = BoxUtil.getBoxStore(context!!).boxFor(LikedCollect::class.java)
val likedCollectList = collectBox.query().orderDesc(LikedCollect_.likedTime).build().find()
val collectList = ArrayList<Collect>()
likedCollectList.mapTo(collectList) { it.collect }
mCollectAdapter.setData(collectList)
}
}
@Suppress("DEPRECATION")
private fun setButtonTextColor(select: Int) {
if (select == MY_COLLECT) {
mBtnMyCollect.setTextColor(context!!.resources.getColor(R.color.colorBlack))
mBtnLikedCollect.setTextColor(context!!.resources.getColor(R.color.colorGray))
} else {
mBtnMyCollect.setTextColor(context!!.resources.getColor(R.color.colorGray))
mBtnLikedCollect.setTextColor(context!!.resources.getColor(R.color.colorBlack))
}
}
private fun showCollectDetail(collect: Collect) {
val data = Bundle()
val detailFragment = DetailFragment()
if (curShowType == MY_COLLECT) {
data.putSerializable(DetailContract.ARGS_ID, collect)
data.putBoolean(DetailContract.ARGS_IS_USER_COLLECT, true)
//用于删除歌单时刷新显示
detailFragment.localFragment = this
} else {
data.putSerializable(DetailContract.ARGS_ID, collect)
data.putBoolean(DetailContract.ARGS_IS_USER_COLLECT, false)
}
data.putSerializable(DetailContract.ARGS_LOAD_TYPE, DetailContract.LoadType.COLLECT)
detailFragment.arguments = data
addFragmentToMainView(fragmentManager!!, detailFragment)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CREATE_COLLECT && resultCode == RESULT_COLLECT_CREATED) {
context!!.showToast("歌单创建成功")
}
}
override fun onDestroyView() {
super.onDestroyView()
mUnBinder.unbind()
}
companion object {
const val TAG = "LocalFragment"
const val MY_COLLECT = 1
const val LIKED_COLLECT = 2
const val REQUEST_CREATE_COLLECT = 0x00
const val RESULT_COLLECT_CREATED = 0x01
}
inner class CollectAdapter(var collects: List<Collect>)
: RecyclerView.Adapter<CollectAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemView = LayoutInflater.from(context).inflate(R.layout.item_liked_collect, parent, false)
return ViewHolder(itemView)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val collect = collects[position]
holder.name.text = collect.title
val songCount = if (collect.isFromUser()) {
collect.songs.size
} else {
collect.songCount
}
val displaySongNumber = "$songCount 首"
holder.songNumber.text = displaySongNumber
GlideApp.with(context)
.load(collect.coverUrl)
.error(R.drawable.ic_main_all_music)
.placeholder(R.drawable.ic_main_all_music)
.into(holder.cover)
holder.itemView.setOnClickListener {
showCollectDetail(collect)
}
}
fun setData(data: List<Collect>) {
collects = data
notifyDataSetChanged()
}
override fun getItemCount(): Int = collects.size
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val cover: ImageView = itemView.findViewById(R.id.liked_collect_cover)
val name: TextView = itemView.findViewById(R.id.liked_collect_name)
val songNumber: TextView = itemView.findViewById(R.id.liked_collect_song_number)
}
}
}
|
apache-2.0
|
3989f49299c4c36eea18afde2f359ec6
| 36.203704 | 115 | 0.657043 | 4.308847 | false | false | false | false |
google/horologist
|
media-ui/src/debug/java/com/google/android/horologist/media/ui/components/MediaChipPreview.kt
|
1
|
2998
|
/*
* 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.
*/
@file:OptIn(ExperimentalHorologistMediaUiApi::class)
package com.google.android.horologist.media.ui.components
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Album
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import com.google.android.horologist.base.ui.util.rememberVectorPainter
import com.google.android.horologist.compose.tools.WearPreview
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
import com.google.android.horologist.media.ui.state.model.MediaUiModel
@WearPreview
@Composable
fun MediaChipPreview() {
MediaChip(
media = MediaUiModel(
id = "id",
title = "Red Hot Chilli Peppers",
artworkUri = "artworkUri"
),
onClick = {},
placeholder = rememberVectorPainter(
image = Icons.Default.Album,
tintColor = Color.Blue
)
)
}
@Preview(
name = "No artwork",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun MediaChipPreviewNoArtwork() {
MediaChip(
media = MediaUiModel(id = "id", title = "Red Hot Chilli Peppers"),
onClick = {},
placeholder = rememberVectorPainter(
image = Icons.Default.Album,
tintColor = Color.Blue
)
)
}
@Preview(
name = "No title",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun MediaChipPreviewNoTitle() {
MediaChip(
media = MediaUiModel(id = "id", artworkUri = "artworkUri"),
onClick = {},
defaultTitle = "No title",
placeholder = rememberVectorPainter(
image = Icons.Default.Album,
tintColor = Color.Blue
)
)
}
@Preview(
name = "Very long title",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun MediaChipPreviewVeryLongTitle() {
MediaChip(
media = MediaUiModel(
id = "id",
title = "Very very very very very very very very very very very very very very very very very very very long title",
artworkUri = "artworkUri"
),
onClick = {},
placeholder = rememberVectorPainter(
image = Icons.Default.Album,
tintColor = Color.Blue
)
)
}
|
apache-2.0
|
bc2bbe9ae7307463ed60acfba2862df7
| 28.392157 | 128 | 0.668779 | 4.395894 | false | false | false | false |
fython/PackageTracker
|
mobile/src/main/kotlin/info/papdt/express/helper/ui/ChooseIconActivity.kt
|
1
|
7456
|
package info.papdt.express.helper.ui
import android.animation.Animator
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Handler
import androidx.annotation.RequiresApi
import androidx.appcompat.app.ActionBar
import androidx.appcompat.widget.AppCompatEditText
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.text.Editable
import android.text.TextWatcher
import android.view.*
import info.papdt.express.helper.R
import info.papdt.express.helper.support.ResourcesUtils
import info.papdt.express.helper.support.Settings
import info.papdt.express.helper.ui.adapter.MaterialIconsGridAdapter
import info.papdt.express.helper.ui.common.AbsActivity
import moe.feng.kotlinyan.common.*
class ChooseIconActivity : AbsActivity() {
private val mList: RecyclerView by lazyFindNonNullView(R.id.recycler_view)
private val mSearchEdit: AppCompatEditText by lazyFindNonNullView(R.id.search_edit)
private val rootLayout: View by lazyFindNonNullView(R.id.root_layout)
private val mAdapter: MaterialIconsGridAdapter = MaterialIconsGridAdapter()
@SuppressLint("NewApi")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!isNightMode) {
window.navigationBarColor = resources.color[R.color.lollipop_status_bar_grey]
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
if (!isNightMode) {
window.navigationBarColor = Color.WHITE
ifSupportSDK (Build.VERSION_CODES.P) {
window.navigationBarDividerColor = Color.argb(30, 0, 0, 0)
}
} else {
window.navigationBarColor = ResourcesUtils.getColorIntFromAttr(
theme, android.R.attr.windowBackground)
ifSupportSDK (Build.VERSION_CODES.P) {
window.navigationBarDividerColor = Color.argb(60, 255, 255, 255)
}
}
}
setContentView(R.layout.activity_icon_choose)
if (savedInstanceState == null) {
rootLayout.makeInvisible()
val viewTreeObserver = rootLayout.viewTreeObserver
if (viewTreeObserver.isAlive) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
Handler().postDelayed({
overridePendingTransition(R.anim.do_not_move, R.anim.do_not_move)
var flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
if (!isNightMode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
flag = flag or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1
&& !isNightMode) {
flag = flag or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
}
}
window.decorView.systemUiVisibility = flag
window.statusBarColor =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
Color.TRANSPARENT
else
resources.color[R.color.lollipop_status_bar_grey]
circularRevealActivity()
}, 100)
rootLayout.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
})
}
}
}
override fun setUpViews() {
mActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
findViewById<View>(R.id.action_back).setOnClickListener { onBackPressed() }
mSearchEdit.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
mAdapter.update(charSequence.toString())
}
override fun afterTextChanged(editable: Editable) {
}
})
/** Set up company list */
mList.setHasFixedSize(true)
mList.layoutManager = GridLayoutManager(
this, 4, RecyclerView.VERTICAL, false)
mAdapter.callback = {
setResult(RESULT_OK, Intent().apply { putExtra(EXTRA_RESULT_ICON_CODE, it) })
finish()
}
mList.adapter = mAdapter
mAdapter.update()
}
override fun onDestroy() {
super.onDestroy()
mAdapter.destroy()
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private fun circularRevealActivity() {
val cx = (rootLayout.width / 2)
val cy = (rootLayout.height / 2)
val finalRadius = Math.max(rootLayout.width, rootLayout.height).toFloat()
// create the animator for this view (the start radius is zero)
val circularReveal = ViewAnimationUtils.createCircularReveal(
rootLayout, cx, cy, 0f, finalRadius)
circularReveal.duration = 300
circularReveal.addListener(object : Animator.AnimatorListener {
override fun onAnimationRepeat(p0: Animator?) {}
override fun onAnimationEnd(p0: Animator?) { mSearchEdit.showKeyboard() }
override fun onAnimationCancel(p0: Animator?) {}
override fun onAnimationStart(p0: Animator?) {}
})
// make the view visible and start the animation
rootLayout.makeVisible()
circularReveal.start()
}
override fun onBackPressed() {
val cx = (rootLayout.width / 2)
val cy = (rootLayout.height / 2)
val finalRadius = Math.max(rootLayout.width, rootLayout.height).toFloat()
val circularReveal = ViewAnimationUtils.createCircularReveal(
rootLayout, cx, cy, finalRadius, 0f)
circularReveal.addListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animator: Animator) {}
override fun onAnimationCancel(animator: Animator) {}
override fun onAnimationRepeat(animator: Animator) {}
override fun onAnimationEnd(animator: Animator) { rootLayout.makeInvisible(); finish() }
})
circularReveal.duration = 400
circularReveal.start()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_search, menu)
menu.tintItemsColor(resources.color[R.color.black_in_light])
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.action_clear) {
mSearchEdit.setText("")
return true
}
return super.onOptionsItemSelected(item)
}
companion object {
const val EXTRA_RESULT_ICON_CODE = "result_icon_code"
}
}
|
gpl-3.0
|
f40025c0c3fb22a07e1f24b884e8b05e
| 38.877005 | 109 | 0.608101 | 5.103354 | false | false | false | false |
spinnaker/keiko
|
keiko-core/src/main/kotlin/com/netflix/spinnaker/q/Queue.kt
|
4
|
3995
|
/*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.q
import java.time.Duration.ZERO
import java.time.temporal.TemporalAmount
/**
* A queue that handles various [Message] types. Messages may be pushed for
* immediate delivery or with a delivery time in the future. Polling will fetch
* a single ready message from the queue and dispatch it to a [MessageHandler]
* depending on its type. If a message is not acknowledged within [ackTimeout]
* it is re-queued for immediate delivery.
*/
interface Queue {
/**
* Polls the queue for ready messages.
*
* Implementations may invoke [callback] any number of times. Some
* implementations may deliver a maximum of one message per call, others may
* deliver all ready messages.
*
* If no messages exist on the queue or all messages have a remaining delay
* [callback] is not invoked.
*
* Messages *must* be acknowledged by calling the function passed to
* [callback] or they will be retried after [ackTimeout]. Acknowledging via a
* nested callback allows the message to be processed asynchronously.
*
* @param callback invoked with the next message from the queue if there is
* one and an _acknowledge_ function to call once processing is complete.
*/
fun poll(callback: QueueCallback): Unit
/**
* Polls the queue for ready messages, processing up-to [maxMessages].
*/
fun poll(maxMessages: Int, callback: QueueCallback): Unit
/**
* Push [message] for immediate delivery.
*/
fun push(message: Message): Unit = push(message, ZERO)
/**
* Push [message] for delivery after [delay].
*/
fun push(message: Message, delay: TemporalAmount): Unit
/**
* Update [message] if it exists for immediate delivery.
*/
fun reschedule(message: Message): Unit = reschedule(message, ZERO)
/**
* Update [message] if it exists for delivery after [delay].
*/
fun reschedule(message: Message, delay: TemporalAmount): Unit
/**
* Ensure [message] is present within the queue or is currently being worked on.
* Add to the queue after [delay] if not present. No action is taken if
* [message] already exists.
*/
fun ensure(message: Message, delay: TemporalAmount): Unit
/**
* Check for any un-acknowledged messages that are overdue and move them back
* onto the queue.
*
* This method is not intended to be called by clients directly but typically
* scheduled in some way.
*/
fun retry() {}
/**
* The expired time after which un-acknowledged messages will be retried.
*/
val ackTimeout: TemporalAmount
/**
* A handler for messages that have failed to acknowledge delivery more than
* [Queue.ackTimeout] times.
*/
val deadMessageHandlers: List<DeadMessageCallback>
/**
* Denotes a queue implementation capable of processing multiple messages per poll.
*/
val canPollMany: Boolean
companion object {
/**
* The maximum number of times an un-acknowledged message will be retried
* before failing permanently.
*/
val maxRetries: Int = 5
}
}
/**
* The callback parameter type passed to [Queue.poll]. The queue implementation
* will invoke the callback passing the next message from the queue and an "ack"
* function used to acknowledge successful processing of the message.
*/
typealias QueueCallback = (Message, () -> Unit) -> Unit
typealias DeadMessageCallback = (Queue, Message) -> Unit
|
apache-2.0
|
8942794025267b1b368ed4888b2bb802
| 31.745902 | 85 | 0.710388 | 4.356598 | false | false | false | false |
charlesmadere/smash-ranks-android
|
smash-ranks-android/app/src/main/java/com/garpr/android/features/player/MatchItemView.kt
|
1
|
2394
|
package com.garpr.android.features.player
import android.content.Context
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import androidx.annotation.ColorInt
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import com.garpr.android.R
import com.garpr.android.data.models.MatchResult
import com.garpr.android.data.models.TournamentMatch
import com.garpr.android.extensions.getAttrColor
import kotlinx.android.synthetic.main.item_match.view.*
class MatchItemView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : FrameLayout(context, attrs), View.OnClickListener, View.OnLongClickListener {
private val originalBackground: Drawable? = background
@ColorInt
private val cardBackgroundColor: Int = ContextCompat.getColor(context, R.color.card_background)
@ColorInt
private val exclusionColor: Int = context.getAttrColor(android.R.attr.textColorSecondary)
@ColorInt
private val loseColor: Int = ContextCompat.getColor(context, R.color.lose)
@ColorInt
private val winColor: Int = ContextCompat.getColor(context, R.color.win)
var listeners: Listeners? = null
private var _match: TournamentMatch? = null
val match: TournamentMatch
get() = checkNotNull(_match)
interface Listeners {
fun onClick(v: MatchItemView)
fun onLongClick(v: MatchItemView)
}
init {
setOnClickListener(this)
setOnLongClickListener(this)
}
override fun onClick(v: View) {
listeners?.onClick(this)
}
override fun onLongClick(v: View): Boolean {
listeners?.onLongClick(this)
return true
}
fun setContent(match: TournamentMatch, isIdentity: Boolean) {
_match = match
name.text = match.opponent.name
name.setTextColor(when (match.result) {
MatchResult.EXCLUDED -> exclusionColor
MatchResult.LOSE -> loseColor
MatchResult.WIN -> winColor
})
if (isIdentity) {
name.typeface = Typeface.DEFAULT_BOLD
setBackgroundColor(cardBackgroundColor)
} else {
name.typeface = Typeface.DEFAULT
ViewCompat.setBackground(this, originalBackground)
}
}
}
|
unlicense
|
b50fc0038d84386a4612552598aa7c87
| 28.555556 | 99 | 0.705514 | 4.666667 | false | false | false | false |
Fitbit/MvRx
|
mvrx-mocking/src/main/kotlin/com/airbnb/mvrx/mocking/DataClassSetDsl.kt
|
1
|
9549
|
package com.airbnb.mvrx.mocking
import androidx.annotation.VisibleForTesting
import com.airbnb.mvrx.Async
import com.airbnb.mvrx.Fail
import com.airbnb.mvrx.Loading
import com.airbnb.mvrx.Success
import java.util.LinkedList
import kotlin.reflect.KProperty0
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.isAccessible
/**
* When a lambda has a receiver that extends this class it can make use of this special DSL syntax for changing properties on a data class.
* This syntax makes it easier to change deeply nested properties.
*
* Example: mavericksState.set { ::listing { ::host { ::name } } }.with { "Elena" }
*/
interface DataClassSetDsl {
/**
* A small utility function to help copy kotlin data classes when changing a single property, especially where there is deep nesting.
* This is heavy on reflection, so isn't intended for high performance use cases.
*
* This can only be called on Kotlin Data classes, and all nested objects that are modified must also be data classes.
*
* @sample setExample
*/
fun <DataClass : Any, Type> DataClass.set(block: DataClass.() -> KProperty0<Type>): Setter<DataClass, Type> {
return Setter(this, block())
}
/**
* A shortcut to setting a property to null, instead of "data.set { ::property }.with { null }".
*/
fun <DataClass : Any, Type> DataClass.setNull(block: DataClass.() -> KProperty0<Type?>): DataClass {
return Setter(this, block()).with { null }
}
/** Shortcut to set a Boolean property to true. */
fun <DataClass : Any> DataClass.setTrue(block: DataClass.() -> KProperty0<Boolean?>): DataClass {
return Setter(this, block()).with { true }
}
/** Shortcut to set a Boolean property to false. */
fun <DataClass : Any> DataClass.setFalse(block: DataClass.() -> KProperty0<Boolean?>): DataClass {
return Setter(this, block()).with { false }
}
/** Shortcut to set a numeric property to zero. */
fun <DataClass : Any> DataClass.setZero(block: DataClass.() -> KProperty0<Number?>): DataClass {
return Setter(this, block()).with { 0 }
}
/** Shortcut to set a List property to an empty list. */
fun <DataClass : Any, T> DataClass.setEmpty(block: DataClass.() -> KProperty0<List<T>?>): DataClass {
return Setter(this, block()).with { emptyList() }
}
/**
* A shortcut to setting an Async property to Loading, instead of "data.set { ::property }.with { Loading() }".
*/
fun <DataClass : Any, Type : Async<AsyncType>, AsyncType> DataClass.setLoading(block: DataClass.() -> KProperty0<Type>): DataClass {
return Setter<DataClass, Async<AsyncType>?>(this, block()).with { Loading() }
}
/**
* A shortcut to setting an Async property to Fail, instead of "data.set { ::property }.with { Fail() }".
*/
fun <DataClass : Any, Type : Async<AsyncType>, AsyncType> DataClass.setNetworkFailure(block: DataClass.() -> KProperty0<Type>): DataClass {
return Setter<DataClass, Async<AsyncType>?>(this, block()).with { Fail(Throwable("Network request failed")) }
}
@Suppress("UNCHECKED_CAST")
operator fun <Type1 : Any, Type2> KProperty0<Type1?>.invoke(block: Type1.() -> KProperty0<Type2>): KProperty0<Type2> {
val thisValue = requireNotNull(get()) { "The value for '$name' is null, properties on it can't be changed." }
return NestedProperty(
this as KProperty0<Type1>,
thisValue.block()
)
}
/**
* Use this to update the property value of an Async's type when it is in the Success state. This will throw an exception if the Async it is used
* on is not Success.
*
* Example: state.set { ::myAsync { success { ::text } } }.with { "hello" }
*
* If you would like to replace the whole value of the Success object you can instead do
* state.set { ::myAsync }.with { Success(MyClass(text = "hello")) }
*/
fun <T, Type> Async<T>.success(block: T.() -> KProperty0<Type>): KProperty0<Type> {
val successValue = this.invoke()
?: error("Async value is not in the success state, it is `${this::class.simpleName}`")
return successValue.block()
}
/**
* Provide the new value to update your property to. "it" in the lambda is the lambda is the current value, and you should return the new value.
*/
fun <PropertyType, DataClass : Any> Setter<DataClass, PropertyType>.with(block: (PropertyType) -> PropertyType): DataClass {
return set(block(property.get()))
}
private fun setExample() {
data class DisclaimerInfo(val text: String)
data class BookingDetails(val num: Int = 7, val disclaimerInfo: DisclaimerInfo?)
data class State(val bookingDetails: BookingDetails)
val myState = State(BookingDetails(disclaimerInfo = DisclaimerInfo("text")))
// Using the helper utils we can update the nested text value like this
myState.set { ::bookingDetails { ::disclaimerInfo { ::text } } }.with { "hello world" }
// The standard way to set a nested value is much longer
myState.copy(
bookingDetails = myState.bookingDetails.copy(
disclaimerInfo = myState.bookingDetails.disclaimerInfo?.copy(
text = "hello world"
)
)
)
}
/**
* Helper to copy a nested class and update a property on it.
*/
class Setter<DataClass : Any, PropType>(private val instance: DataClass, internal val property: KProperty0<PropType>) {
init {
val clazz = instance::class
if (instance is Async<*>) {
require(instance is Success<*>) {
"Cannot set ${clazz.simpleName} property ${property.nameForErrorMsg()}, the Async value it is in is not in the Success state"
}
} else {
require(clazz.isData) {
"${clazz.simpleName} property '${property.nameForErrorMsg()}' must be a data class to change mock values with 'set'"
}
}
// We could support other class types as long as they have predictable builder methods, like AutoValue classes.
// We just need to create reflection based copy methods for them
}
/**
* This assumes the data class is the top level data class.
* This doesn't work to start in the middle of the chain.
*/
@Suppress("UNCHECKED_CAST")
fun getValue(dataClass: DataClass): PropType {
val propertyChain = LinkedList<KProperty0<Any?>>()
var nextProp: KProperty0<Any?>? = property
while (nextProp != null) {
propertyChain.add(0, nextProp)
nextProp = (nextProp as? NestedProperty<*, *>)?.wrapperProperty
}
return propertyChain.fold<KProperty0<Any?>, Any?>(dataClass) { data, kProp0 ->
checkNotNull(data) {
"Value of data class is null, cannot get property ${kProp0.name}"
}
val kProp1 = data::class.memberProperties.singleOrNull { it.name == kProp0.name }
?: error("Could not find property of name ${kProp0.name} on class ${data::class.simpleName}")
// it is valid for the final result to be null, but intermediate values in the chain
// cannot be null.
kProp1.call(data)
} as PropType
}
@Suppress("UNCHECKED_CAST")
@VisibleForTesting
fun set(value: PropType): DataClass {
val (recursiveProperty: KProperty0<Any?>, recursiveValue: Any?) = when (property) {
is NestedProperty<*, *> -> property.wrapperProperty to ((property.buildSetter() as Setter<Any, Any?>).set(
value
))
else -> property to value
}
return if (instance is Success<*>) {
val successValue = instance.invoke()
?: error("Success value is null - cannot set ${property.name}")
require(successValue::class.isData) { "${successValue::class.simpleName} must be a data class" }
val updatedSuccess = successValue.callCopy(recursiveProperty.name to recursiveValue)
Success(updatedSuccess) as DataClass
} else {
instance.callCopy(recursiveProperty.name to recursiveValue)
}
}
}
/**
* Represents two properties that are associated by a nested object hierarchy.
*
* @property wrapperProperty A property whose type contains the nestedProperty
* @property nestedProperty The property that this class represents.
*/
open class NestedProperty<Type : Any, NestedType>(
val wrapperProperty: KProperty0<Type>,
val nestedProperty: KProperty0<NestedType>
) : KProperty0<NestedType> by nestedProperty {
init {
wrapperProperty.isAccessible = true
nestedProperty.isAccessible = true
}
open fun buildSetter(): Setter<Type, NestedType> {
return Setter(wrapperProperty.get(), nestedProperty)
}
}
}
private fun KProperty0<*>.nameForErrorMsg(): String {
return when (this) {
is DataClassSetDsl.NestedProperty<*, *> -> "${wrapperProperty.nameForErrorMsg()}:${nestedProperty.nameForErrorMsg()}"
else -> name
}
}
|
apache-2.0
|
f770d21f762ab1f59616c8873685d5f6
| 42.013514 | 149 | 0.62017 | 4.519167 | false | false | false | false |
laurencegw/jenjin
|
jenjin-core/src/main/kotlin/com/binarymonks/jj/core/audio/SoundPlayer.kt
|
1
|
5159
|
package com.binarymonks.jj.core.audio
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.audio.Music
import com.badlogic.gdx.audio.Sound
import com.badlogic.gdx.math.MathUtils
import com.binarymonks.jj.core.JJ
fun getSoundPlayer(params: SoundParams): SoundPlayer {
if (!params.isBig) {
return ShortSound(params)
}
return LongSound(params)
}
abstract class SoundPlayer constructor(internal var parameters: SoundParams) : Sound {
internal var currentSoundPath: String? = null
fun selectRandom() {
currentSoundPath = selectRandom(parameters.soundPaths)
}
private fun selectRandom(soundPaths: List<String>): String {
val roll = MathUtils.random(0, soundPaths.size - 1)
return soundPaths[roll]
}
abstract fun triggering()
fun canTriggerSingleton(): Boolean {
return JJ.B.audio.effects.canTriggerSingleton(myCurrentSoundPath())
}
fun myCurrentSoundPath(): String {
if (currentSoundPath != null) {
return currentSoundPath!!
}
throw Exception("No soundpath to fetch")
}
}
private class ShortSound constructor(parameters: SoundParams) : SoundPlayer(parameters) {
internal var sound: Sound? = null
override fun triggering() {
sound = JJ.B.assets.getAsset(myCurrentSoundPath(), Sound::class)
}
override fun play(): Long {
return checkNotNull(sound).play()
}
override fun play(volume: Float): Long {
return checkNotNull(sound).play(volume)
}
override fun play(volume: Float, pitch: Float, pan: Float): Long {
return checkNotNull(sound).play(volume, pitch, pan)
}
override fun loop(): Long {
return checkNotNull(sound).loop()
}
override fun loop(volume: Float): Long {
return checkNotNull(sound).loop(volume)
}
override fun loop(volume: Float, pitch: Float, pan: Float): Long {
return loop(volume, pitch, pan)
}
override fun stop() {
checkNotNull(sound).stop()
}
override fun pause() {
checkNotNull(sound).pause()
}
override fun resume() {
checkNotNull(sound).resume()
}
override fun dispose() {
checkNotNull(sound).dispose()
}
override fun stop(soundId: Long) {
checkNotNull(sound).stop(soundId)
}
override fun pause(soundId: Long) {
checkNotNull(sound).pause(soundId)
}
override fun resume(soundId: Long) {
checkNotNull(sound).resume(soundId)
}
override fun setLooping(soundId: Long, looping: Boolean) {
checkNotNull(sound).setLooping(soundId, looping)
}
override fun setPitch(soundId: Long, pitch: Float) {
checkNotNull(sound).setPitch(soundId, pitch)
}
override fun setVolume(soundId: Long, volume: Float) {
checkNotNull(sound).setVolume(soundId, volume)
}
override fun setPan(soundId: Long, pan: Float, volume: Float) {
checkNotNull(sound).setPan(soundId, pan, volume)
}
}
private class LongSound(parameters: SoundParams) : SoundPlayer(parameters) {
internal var sound: Music? = null
override fun triggering() {
sound = Gdx.audio.newMusic(Gdx.files.internal(currentSoundPath))
}
override fun play(): Long {
checkNotNull(sound).play()
return 1
}
override fun play(volume: Float): Long {
checkNotNull(sound).volume = volume
checkNotNull(sound).play()
return 1
}
override fun play(volume: Float, pitch: Float, pan: Float): Long {
checkNotNull(sound).setPan(pan, volume)
checkNotNull(sound).play()
return 1
}
override fun loop(): Long {
checkNotNull(sound).isLooping = true
checkNotNull(sound).play()
return 1
}
override fun loop(volume: Float): Long {
checkNotNull(sound).isLooping = true
checkNotNull(sound).volume = volume
checkNotNull(sound).play()
return 1
}
override fun loop(volume: Float, pitch: Float, pan: Float): Long {
checkNotNull(sound).isLooping = true
checkNotNull(sound).setPan(pan, volume)
checkNotNull(sound).play()
return 1
}
override fun stop() {
checkNotNull(sound).stop()
}
override fun pause() {
checkNotNull(sound).pause()
}
override fun resume() {
checkNotNull(sound).play()
}
override fun dispose() {
checkNotNull(sound).dispose()
}
override fun stop(soundId: Long) {
checkNotNull(sound).stop()
}
override fun pause(soundId: Long) {
checkNotNull(sound).pause()
}
override fun resume(soundId: Long) {
checkNotNull(sound).play()
}
override fun setLooping(soundId: Long, looping: Boolean) {
checkNotNull(sound).isLooping = looping
}
override fun setPitch(soundId: Long, pitch: Float) {}
override fun setVolume(soundId: Long, volume: Float) {
checkNotNull(sound).volume = volume
}
override fun setPan(soundId: Long, pan: Float, volume: Float) {
checkNotNull(sound).setPan(pan, volume)
}
}
|
apache-2.0
|
995abd2d8f73279ea8d98abdddd74818
| 23.450237 | 89 | 0.634813 | 4.270695 | false | false | false | false |
tkiapril/Weisseliste
|
tests/kotlin/sql/tests/h2/DDLTests.kt
|
1
|
5844
|
package kotlin.sql.tests.h2
import org.junit.Test
import kotlin.sql.Table
import kotlin.sql.exists
import kotlin.sql.insert
import kotlin.sql.select
import kotlin.test.assertEquals
public class DDLTests : DatabaseTestsBase() {
@Test fun tableExists01() {
val TestTable = object : Table("test") {
val id = integer("id").primaryKey()
val name = varchar("name", length = 42)
}
withDb {
assertEquals (false, TestTable.exists())
}
}
@Test fun tableExists02() {
val TestTable = object : Table() {
val id = integer("id").primaryKey()
val name = varchar("name", length = 42)
}
withTables(TestTable) {
assertEquals (true, TestTable.exists())
}
}
@Test fun unnamedTableWithQuotesSQL() {
val TestTable = object : Table() {
val id = integer("id").primaryKey()
val name = varchar("name", length = 42)
}
withTables(TestTable) {
assertEquals("CREATE TABLE IF NOT EXISTS \"unnamedTableWithQuotesSQL\$TestTable$1\" (id INT PRIMARY KEY NOT NULL, name VARCHAR(42) NOT NULL)", TestTable.ddl)
}
}
@Test fun namedEmptyTableWithoutQuotesSQL() {
val TestTable = object : Table("test_named_table") {
}
withTables(TestTable) {
assertEquals("CREATE TABLE IF NOT EXISTS test_named_table", TestTable.ddl)
}
}
@Test fun tableWithDifferentColumnTypesSQL() {
val TestTable = object : Table("test_table_with_different_column_types") {
val id = integer("id").autoIncrement()
val name = varchar("name", 42).primaryKey()
val age = integer("age").nullable()
// not applicable in H2 database
// val testCollate = varchar("testCollate", 2, "ascii_general_ci")
}
withTables(TestTable) {
assertEquals("CREATE TABLE IF NOT EXISTS test_table_with_different_column_types (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(42) PRIMARY KEY NOT NULL, age INT NULL)", TestTable.ddl)
}
}
@Test fun testDefaults01() {
val TestTable = object : Table("t") {
val s = varchar("s", 100).default("test")
val l = long("l").default(42)
}
withTables(TestTable) {
assertEquals("CREATE TABLE IF NOT EXISTS t (s VARCHAR(100) NOT NULL DEFAULT 'test', l BIGINT NOT NULL DEFAULT 42)", TestTable.ddl)
}
}
@Test fun testIndices01() {
val t = object : Table("t1") {
val id = integer("id").primaryKey()
val name = varchar("name", 255).index()
}
withTables(t) {
val alter = createIndex(t.indices[0].first, t.indices[0].second)
assertEquals("CREATE INDEX t1_name ON t1 (name)", alter)
}
}
@Test fun testIndices02() {
val t = object : Table("t2") {
val id = integer("id").primaryKey()
val lvalue = integer("lvalue")
val rvalue = integer("rvalue");
val name = varchar("name", 255).index()
init {
index (false, lvalue, rvalue)
}
}
withTables(t) {
val a1 = createIndex(t.indices[0].first, t.indices[0].second)
assertEquals("CREATE INDEX t2_name ON t2 (name)", a1)
val a2 = createIndex(t.indices[1].first, t.indices[1].second)
assertEquals("CREATE INDEX t2_lvalue_rvalue ON t2 (lvalue, rvalue)", a2)
}
}
@Test fun testIndices03() {
val t = object : Table("t1") {
val id = integer("id").primaryKey()
val name = varchar("name", 255).uniqueIndex()
}
withTables(t) {
val alter = createIndex(t.indices[0].first, t.indices[0].second)
assertEquals("CREATE UNIQUE INDEX t1_name_unique ON t1 (name)", alter)
}
}
@Test fun testBlob() {
val t = object: Table("t1") {
val id = integer("id").autoIncrement().primaryKey()
val b = blob("blob")
}
withTables(t) {
val blob = connection.createBlob()!!
blob.setBytes(1, "Hello there!".toByteArray())
val id = t.insert {
it[t.b] = blob
} get (t.id)
val readOn = t.select{t.id eq id}.first()[t.b]
val text = readOn.binaryStream.reader().readText()
assertEquals("Hello there!", text)
}
}
@Test fun tablesWithCrossReferencesSQL() {
val TestTableWithReference1 = object : Table("test_table_1") {
val id = integer("id").primaryKey()
val testTable2Id = integer("id_ref")
}
val TestTableWithReference2 = object : Table("test_table_2") {
val id = integer("id").primaryKey()
val testTable1Id = (integer("id_ref") references TestTableWithReference1.id).nullable()
}
with (TestTableWithReference1) {
testTable2Id.references( TestTableWithReference2.id)
}
withDb {
val statements = createStatements(TestTableWithReference1, TestTableWithReference2)
assertEquals ("CREATE TABLE IF NOT EXISTS test_table_1 (id INT PRIMARY KEY NOT NULL, id_ref INT NOT NULL)", statements[0])
assertEquals ("CREATE TABLE IF NOT EXISTS test_table_2 (id INT PRIMARY KEY NOT NULL, id_ref INT NULL)", statements[1])
assertEquals ("ALTER TABLE test_table_1 ADD FOREIGN KEY (id_ref) REFERENCES test_table_2(id)", statements[2])
assertEquals ("ALTER TABLE test_table_2 ADD FOREIGN KEY (id_ref) REFERENCES test_table_1(id)", statements[3])
create(TestTableWithReference1, TestTableWithReference2)
}
}
}
|
agpl-3.0
|
b141b1203ae6b58304c4217083f0da75
| 32.976744 | 194 | 0.570329 | 4.147622 | false | true | false | false |
cemrich/zapp
|
app/src/main/java/de/christinecoenen/code/zapp/app/mediathek/ui/list/models/LengthFilter.kt
|
1
|
474
|
package de.christinecoenen.code.zapp.app.mediathek.ui.list.models
data class LengthFilter(
var minDurationSeconds: Int = 0,
var maxDurationSeconds: Int? = null
) {
val isApplied: Boolean
get() = minDurationSeconds != 0 || maxDurationSeconds != null
val minDurationMinutes: Float
get() = minDurationSeconds / 60f
val maxDurationMinutes: Float?
get() {
val maxDuration = maxDurationSeconds
return if (maxDuration == null) null else maxDuration / 60f
}
}
|
mit
|
67c9da98b468f151cd59562941686fb5
| 25.333333 | 65 | 0.736287 | 3.732283 | false | false | false | false |
tipsy/javalin
|
javalin/src/main/java/io/javalin/core/compression/CompressionStrategy.kt
|
1
|
2877
|
package io.javalin.core.compression
import com.nixxcode.jvmbrotli.common.BrotliLoader
import io.javalin.core.util.JavalinLogger
import io.javalin.core.util.OptionalDependency
import io.javalin.core.util.Util
/**
* This class is a settings container for Javalin's content compression.
*
* It is used by the JavalinResponseWrapper to determine the encoding and parameters that should be used when compressing a response.
*
* @see io.javalin.http.JavalinResponseWrapper
*
* @param brotli instance of Brotli handler, default = null
* @param gzip instance of Gzip handler, default = null
*/
class CompressionStrategy(brotli: Brotli? = null, gzip: Gzip? = null) {
companion object {
@JvmField
val NONE = CompressionStrategy()
@JvmField
val GZIP = CompressionStrategy(null, Gzip())
}
val brotli: Brotli?
val gzip: Gzip?
init {
//Enabling brotli requires special handling since jvm-brotli is platform dependent
this.brotli = if (brotli != null) tryLoadBrotli(brotli) else null
this.gzip = gzip
}
/** 1500 is the size of a packet, compressing responses smaller than this serves no purpose */
var minSizeForCompression = 1500
/** Those mime types will be processed using NONE compression strategy */
var excludedMimeTypesFromCompression = listOf(
"image/",
"audio/",
"video/",
"application/compress",
"application/zip",
"application/gzip",
"application/bzip2",
"application/brotli",
"application/x-xz",
"application/x-rar-compressed"
)
/**
* When enabling Brotli, we try loading the jvm-brotli native library first.
* If this fails, we keep Brotli disabled and warn the user.
*/
private fun tryLoadBrotli(brotli: Brotli): Brotli? {
Util.ensureDependencyPresent(OptionalDependency.JVMBROTLI, startupCheck = true)
return if (BrotliLoader.isBrotliAvailable()) {
brotli
} else {
JavalinLogger.warn("""${"\n"}
Failed to enable Brotli compression, because the jvm-brotli native library couldn't be loaded.
jvm-brotli is currently only supported on Windows, Linux and Mac OSX.
If you are running Javalin on a supported system, but are still getting this error,
try re-importing your Maven and/or Gradle dependencies. If that doesn't resolve it,
please create an issue at https://github.com/tipsy/javalin/
---------------------------------------------------------------
If you still want compression, please ensure GZIP is enabled!
---------------------------------------------------------------
""".trimIndent())
null
}
}
}
|
apache-2.0
|
880e971869348ea1242a7bc3958b87a9
| 37.36 | 133 | 0.614529 | 4.523585 | false | false | false | false |
wleroux/fracturedskies
|
src/main/kotlin/com/fracturedskies/engine/jeact/Point.kt
|
1
|
362
|
package com.fracturedskies.engine.jeact
data class Point(val x: Int, val y: Int) {
override fun toString(): String = "($x, $y)"
infix fun within(bounds: Bounds?): Boolean {
return if (bounds == null) {
true
} else {
bounds.x <= x && x <= bounds.x + bounds.width &&
bounds.y <= y && y <= bounds.y + bounds.height
}
}
}
|
unlicense
|
b9c63a249a9ffaa21d54029cdcc5c787
| 26.923077 | 60 | 0.563536 | 3.480769 | false | false | false | false |
BrianLusina/MovieReel
|
app/src/main/kotlin/com/moviereel/ui/entertain/base/EntertainPageBaseFragment.kt
|
1
|
2830
|
package com.moviereel.ui.entertain.base
import android.os.Bundle
import android.support.annotation.StringRes
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.moviereel.R
import com.moviereel.ui.base.BaseFragment
import com.moviereel.utils.listeners.EndlessRecyclerViewScrollListener
import kotlinx.android.synthetic.main.fragment_entertainment_page.view.*
import org.jetbrains.anko.toast
/**
* @author lusinabrian on 13/09/17.
* @Notes base fragment for movie pages
*/
abstract class EntertainPageBaseFragment : BaseFragment(), EntertainPageBaseView, SwipeRefreshLayout.OnRefreshListener{
lateinit var mRecyclerView: RecyclerView
lateinit var mGridLinearLayoutManager : GridLayoutManager
lateinit var rootView : View
lateinit var mEndlessScrollListener: EndlessRecyclerViewScrollListener
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = inflater.inflate(R.layout.fragment_entertainment_page, container, false)
return rootView
}
override fun onResume() {
super.onResume()
}
/**
* Used to setup views in this fragment
* @param view
*/
override fun setUp(view: View) {
mGridLinearLayoutManager = GridLayoutManager(activity, resources.getInteger(R.integer.num_columns))
val ctx = this
mGridLinearLayoutManager.orientation = GridLayoutManager.VERTICAL
with(view) {
mRecyclerView = fragRecyclerView
fragSwipeRefreshLayout.setColorSchemeResources(R.color.dark_slate_blue,
R.color.dark_slate_gray, R.color.dark_cyan, R.color.dark_turquoise,
R.color.dark_sea_green)
fragSwipeRefreshLayout.setOnRefreshListener(ctx)
fragRecyclerView.setHasFixedSize(true)
fragRecyclerView.layoutManager = mGridLinearLayoutManager
fragRecyclerView.itemAnimator = DefaultItemAnimator()
}
}
override fun stopSwipeRefresh() {
with(rootView){
if(fragSwipeRefreshLayout.isRefreshing){
fragSwipeRefreshLayout.isRefreshing = false
}
}
}
override fun showApiErrorSnackbar(message: String, actionMessage: String, length: Int) {
}
override fun showApiErrorSnackbar(@StringRes resId: Int, @StringRes actionId: Int, length: Int) {
}
override fun displayToast(message: String, messageType: Int) {
activity.toast(message)
}
override fun onDestroy() {
super.onDestroy()
}
}
|
mit
|
cb6040c2514890f109f650ad67999c67
| 30.808989 | 119 | 0.720848 | 4.913194 | false | false | false | false |
matkoniecz/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/data/elementfilter/StringWithCursor.kt
|
1
|
3268
|
package de.westnordost.streetcomplete.data.elementfilter
import kotlin.math.min
/** Convenience class to make it easier to go step by step through a string */
class StringWithCursor(private val string: String) {
var cursorPos = 0
private set
private val char: Char?
get() = if (cursorPos < string.length) string[cursorPos] else null
/** Advances the cursor if str is the next thing at the cursor.
* Returns whether the next string was the str */
fun nextIsAndAdvance(str: String): Boolean {
if (!nextIs(str)) return false
advanceBy(str.length)
return true
}
fun nextIsAndAdvance(c: Char): Boolean {
if (!nextIs(c)) return false
advance()
return true
}
/** Advances the cursor if str or str.uppercase() is the next thing at the cursor
*
* Returns whether the next string was the str or str.uppercase
*/
fun nextIsAndAdvanceIgnoreCase(str: String): Boolean {
if (!nextIsIgnoreCase(str)) return false
advanceBy(str.length)
return true
}
/** returns whether the cursor reached the end */
fun isAtEnd(x: Int = 0): Boolean = cursorPos + x >= string.length
fun findNext(str: String): Int = toDelta(string.indexOf(str, cursorPos))
fun findNext(c: Char, offs: Int = 0): Int = toDelta(string.indexOf(c, cursorPos + offs))
/** Advance cursor by one and return the character that was at that position
*
* throws IndexOutOfBoundsException if cursor is already at the end
*/
fun advance(): Char {
val result = string[cursorPos]
cursorPos = min(string.length, cursorPos + 1)
return result
}
/** Advance cursor by x and return the string that inbetween the two positions.
* If cursor+x is beyond the end of the string, the method will just return the string until
* the end of the string
*
* throws IndexOutOfBoundsException if x < 0
*/
fun advanceBy(x: Int): String {
val end = cursorPos + x
val result: String
if (string.length < end) {
result = string.substring(cursorPos)
cursorPos = string.length
} else {
result = string.substring(cursorPos, end)
cursorPos = end
}
return result
}
fun previousIs(c: Char): Boolean = c == string[cursorPos - 1]
fun nextIs(c: Char): Boolean = c == char
fun nextIs(str: String): Boolean = string.startsWith(str, cursorPos)
fun nextIsIgnoreCase(str: String): Boolean =
nextIs(str.lowercase()) || nextIs(str.uppercase())
fun nextMatches(regex: Regex): MatchResult? {
val match = regex.find(string, cursorPos) ?: return null
if (match.range.first != cursorPos) return null
return match
}
fun nextMatchesAndAdvance(regex: Regex): MatchResult? {
val result = nextMatches(regex) ?: return null
advanceBy(result.value.length)
return result
}
private fun toDelta(index: Int): Int =
if (index == -1) string.length - cursorPos else index - cursorPos
// good for debugging
override fun toString(): String =
string.substring(0, cursorPos) + "►" + string.substring(cursorPos)
}
|
gpl-3.0
|
fada6a59642661456d97d4dc616257c1
| 33.378947 | 96 | 0.635334 | 4.247074 | false | false | false | false |
apoi/quickbeer-android
|
app/src/main/java/quickbeer/android/domain/review/store/ReviewEntity.kt
|
2
|
1724
|
package quickbeer.android.domain.review.store
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.TypeConverters
import org.threeten.bp.ZonedDateTime
import quickbeer.android.data.room.converter.ZonedDateTimeConverter
import quickbeer.android.data.store.Merger
import quickbeer.android.domain.review.Review
@Entity(tableName = "reviews")
@TypeConverters(ZonedDateTimeConverter::class)
data class ReviewEntity(
@PrimaryKey val id: Int,
@ColumnInfo(name = "appearance") val appearance: Int?,
@ColumnInfo(name = "aroma") val aroma: Int?,
@ColumnInfo(name = "flavor") val flavor: Int?,
@ColumnInfo(name = "mouthfeel") val mouthfeel: Int?,
@ColumnInfo(name = "overall") val overall: Int?,
@ColumnInfo(name = "total_score") val totalScore: Float?,
@ColumnInfo(name = "comments") val comments: String?,
@ColumnInfo(name = "time_entered") val timeEntered: ZonedDateTime?,
@ColumnInfo(name = "time_updated") val timeUpdated: ZonedDateTime?,
@ColumnInfo(name = "user_id") val userId: Int?,
@ColumnInfo(name = "user_name") val userName: String?,
@ColumnInfo(name = "city") val city: String?,
@ColumnInfo(name = "state_id") val stateId: Int?,
@ColumnInfo(name = "state") val state: String?,
@ColumnInfo(name = "country_id") val countryId: Int?,
@ColumnInfo(name = "country") val country: String?,
@ColumnInfo(name = "rate_count") val rateCount: Int?
) {
companion object {
val merger: Merger<ReviewEntity> = { old, new ->
val merged = Review.merger(ReviewEntityMapper.mapTo(old), ReviewEntityMapper.mapTo(new))
ReviewEntityMapper.mapFrom(merged)
}
}
}
|
gpl-3.0
|
79707196c0170fb4c0ffad020867cf65
| 41.04878 | 100 | 0.705916 | 3.918182 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android
|
fluxc/src/main/java/org/wordpress/android/fluxc/model/encryptedlogging/EncryptedLog.kt
|
2
|
3143
|
package org.wordpress.android.fluxc.model.encryptedlogging
import com.yarolegovich.wellsql.core.Identifiable
import com.yarolegovich.wellsql.core.annotation.Column
import com.yarolegovich.wellsql.core.annotation.PrimaryKey
import com.yarolegovich.wellsql.core.annotation.RawConstraints
import com.yarolegovich.wellsql.core.annotation.Table
import org.wordpress.android.fluxc.model.encryptedlogging.EncryptedLogUploadState.QUEUED
import org.wordpress.android.util.DateTimeUtils
import java.io.File
import java.util.Date
/**
* [EncryptedLog] and [EncryptedLogModel] are tied to each other, any change in one should be reflected in the other.
* [EncryptedLog] should be used within the app, [EncryptedLogModel] should be used for DB interactions.
*/
data class EncryptedLog(
val uuid: String,
val file: File,
val dateCreated: Date = Date(),
val uploadState: EncryptedLogUploadState = QUEUED,
val failedCount: Int = 0
) {
companion object {
fun fromEncryptedLogModel(encryptedLogModel: EncryptedLogModel) =
EncryptedLog(
dateCreated = DateTimeUtils.dateUTCFromIso8601(encryptedLogModel.dateCreated),
// Crash if values are missing which shouldn't happen if there are no logic errors
uuid = encryptedLogModel.uuid!!,
file = File(encryptedLogModel.filePath),
uploadState = encryptedLogModel.uploadState,
failedCount = encryptedLogModel.failedCount
)
}
}
@Table
@RawConstraints("UNIQUE(UUID) ON CONFLICT REPLACE")
class EncryptedLogModel(@PrimaryKey @Column private var id: Int = 0) : Identifiable {
@Column var uuid: String? = null
@Column var filePath: String? = null
@Column var dateCreated: String? = null // ISO 8601-formatted date in UTC, e.g. 1955-11-05T14:15:00Z
@Column var uploadStateDbValue: Int = QUEUED.value
@Column var failedCount: Int = 0
override fun getId(): Int = id
override fun setId(id: Int) {
this.id = id
}
val uploadState: EncryptedLogUploadState
get() =
requireNotNull(
EncryptedLogUploadState.values()
.firstOrNull { it.value == uploadStateDbValue }) {
"The stateDbValue of the EncryptedLogUploadState didn't match any of the `EncryptedLogUploadState`s. " +
"This likely happened because the EncryptedLogUploadState values " +
"were altered without a DB migration."
}
companion object {
fun fromEncryptedLog(encryptedLog: EncryptedLog) = EncryptedLogModel()
.also {
it.uuid = encryptedLog.uuid
it.filePath = encryptedLog.file.path
it.dateCreated = DateTimeUtils.iso8601UTCFromDate(encryptedLog.dateCreated)
it.uploadStateDbValue = encryptedLog.uploadState.value
it.failedCount = encryptedLog.failedCount
}
}
}
enum class EncryptedLogUploadState(val value: Int) {
QUEUED(1),
UPLOADING(2),
FAILED(3)
}
|
gpl-2.0
|
a7573bb8c2500d680f44daa60a044ba3
| 39.294872 | 120 | 0.668788 | 4.872868 | false | false | false | false |
andersonlucasg3/SpriteKit-Android
|
SpriteKitLib/src/main/java/br/com/insanitech/spritekit/opengl/model/GLTexture.kt
|
1
|
2864
|
package br.com.insanitech.spritekit.opengl.model
import android.graphics.Bitmap
import java.nio.Buffer
import java.nio.ByteBuffer
import java.nio.ByteOrder
import br.com.insanitech.spritekit.opengl.renderer.GLRenderer
/**
* Created by anderson on 7/3/15.
*/
internal class GLTexture : GLGeometry {
private lateinit var buffer: ByteBuffer
private var bytesPerRow: Int = 0
private var bufferSize: Int = 0
private var texture = IntArray(1)
val size = GLSize()
val texVertexBuffer: Buffer
get() = this.vertexBuffer
val glTexture: Int
get() = this.texture[0]
constructor(other: GLTexture) : super() {
this.buffer = other.buffer
this.bytesPerRow = other.bytesPerRow
this.bufferSize = other.bufferSize
this.texture = other.texture
this.size.assignByValue(other.size)
}
/**
* Creates a OpenGL texture with the bitmap as source.
* The bitmap is recycled internally.
*
* @param bitmap to use as source to the texture
*/
constructor(bitmap: Bitmap) {
this.size.width = bitmap.width.toFloat()
this.size.height = bitmap.height.toFloat()
this.loadBitmap(bitmap)
this.generateTexCoords(GLRect(0f, 0f, 1f, 1f))
}
constructor(buffer: ByteBuffer, bytesPerRow: Int, size: Int) {
if (buffer.order() != ByteOrder.nativeOrder()) {
buffer.flip()
}
this.buffer = buffer
this.bytesPerRow = bytesPerRow
this.bufferSize = size
this.generateTexCoords(GLRect(0f, 0f, 1f, 1f))
}
fun generateTexCoords(coords: GLRect) {
coords.size.width = coords.x + coords.width
coords.size.height = coords.y + coords.height
coords.origin.y = 1.0f - coords.y
coords.size.height = 1.0f - coords.height
this.vertices = floatArrayOf(
coords.x, coords.y, //0.0f, 0.0f,
coords.width, coords.y, //1.0f, 0.0f
coords.x, coords.height, //0.0f, 1.0f,
coords.width, coords.height //1.0f, 1.0f,
)
this.componentsPerVertices = 2
this.generateVertex()
}
private fun loadBitmap(bitmap: Bitmap) {
this.bytesPerRow = bitmap.rowBytes
this.bufferSize = this.bytesPerRow * bitmap.height
this.buffer = ByteBuffer.allocate(this.bufferSize)
this.buffer.order(ByteOrder.nativeOrder())
bitmap.copyPixelsToBuffer(this.buffer)
this.buffer.position(0)
bitmap.recycle()
}
fun loadTexture(renderer: GLRenderer, filterMode: Int) {
renderer.loadTexture(this.buffer, this.bufferSize, this.bytesPerRow, filterMode, this.texture)
}
fun unloadTexture(renderer: GLRenderer) {
renderer.unloadTexture(this.texture)
}
}
|
bsd-3-clause
|
7087c85ae10ef7f90e79e96061b1f3c8
| 28.525773 | 102 | 0.625349 | 3.886024 | false | false | false | false |
renard314/auto-adapter
|
auto-adapter-processor/src/main/java/com/renard/auto_adapter/processor/AutoAdapterProcessor.kt
|
1
|
9426
|
package com.renard.auto_adapter.processor
import com.google.common.base.Optional
import com.renard.auto_adapter.processor.AutoAdapterProcessor.Companion.ADAPTER_ITEM_ANNOTATION_NAME
import com.renard.auto_adapter.processor.AutoAdapterProcessor.Companion.ON_CLICK_ANNOTATION_NAME
import com.renard.auto_adapter.processor.code_generation.AdapterGenerator
import com.renard.auto_adapter.processor.code_generation.AndroidClassNames
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.JavaFile
import com.squareup.javapoet.TypeSpec
import java.io.IOException
import java.util.*
import javax.annotation.processing.*
import javax.lang.model.SourceVersion
import javax.lang.model.element.*
import javax.lang.model.util.Elements
import javax.lang.model.util.Types
import javax.tools.Diagnostic
import kotlin.collections.LinkedHashSet
fun VariableElement.isAnnotatedModel(model: TypeElement) =
Util.typeToString(asType()) == Util.typeToString(model.asType())
fun VariableElement.isAndroidView() =
Util.typeToString(asType()) == AndroidClassNames.VIEW.toString()
fun VariableElement.isIn(models: Iterable<TypeElement>): Boolean {
return models.count {
Util.typeToString(asType()) == Util.typeToString(it.asType())
} > 0
}
@SupportedSourceVersion(SourceVersion.RELEASE_7)
@SupportedAnnotationTypes(ON_CLICK_ANNOTATION_NAME, ADAPTER_ITEM_ANNOTATION_NAME)
class AutoAdapterProcessor : AbstractProcessor() {
private lateinit var typeUtils: Types
private lateinit var elementUtils: Elements
private lateinit var filer: Filer
private lateinit var messager: Messager
private val annotatedModels = LinkedHashSet<AnnotatedModel>()
@Synchronized override fun init(processingEnvironment: ProcessingEnvironment) {
super.init(processingEnvironment)
filer = processingEnvironment.filer
messager = processingEnvironment.messager
typeUtils = processingEnvironment.typeUtils
elementUtils = processingEnvironment.elementUtils
}
override fun process(annotations: Set<TypeElement>, roundEnvironment: RoundEnvironment): Boolean {
val typeSpecs = ArrayList<TypeSpec>()
var hasProcessedAnnotation = false
if (!annotations.isEmpty()) {
val adapters = generateAdapters(roundEnvironment)
typeSpecs.addAll(adapters)
hasProcessedAnnotation = !adapters.isEmpty()
}
val iterator = annotatedModels.iterator()
while (iterator.hasNext()) {
val annotatedModel = iterator.next()
val spec = annotatedModel.generateTypeSpecs(roundEnvironment)
if (!spec.isEmpty()) {
iterator.remove()
typeSpecs.addAll(spec)
}
}
saveGeneratedTypes(typeSpecs)
return hasProcessedAnnotation
}
private fun generateAdapters(roundEnvironment: RoundEnvironment): List<TypeSpec> {
val adapterNamesToModels = findAllClassesAnnotatedWithAdapterItem(roundEnvironment)
return if (adapterNamesToModels.isEmpty()) {
emptyList()
} else {
val onClickElement = elementUtils.getTypeElement(ON_CLICK_ANNOTATION_NAME)
val methodsWithOnClick: MutableSet<out Element> = roundEnvironment.getElementsAnnotatedWith(onClickElement)
generateAdapters(adapterNamesToModels, methodsWithOnClick)
}
}
private fun generateAdapters(adaptersWithModels: Map<String, List<TypeElement>>, methodsWithOnClick: Set<Element>): List<TypeSpec> {
val copyMethodsWithOnClick: MutableSet<Element> = LinkedHashSet(methodsWithOnClick)
val typeSpecs = ArrayList<TypeSpec>()
for ((adapterNames, models) in adaptersWithModels) {
val modelToFactory = HashMap<TypeElement, ClassName>()
for (model in models) {
val annotation = model.annotationMirrors.first { isAdapterItemAnnotation(it); }
val values = annotation.elementValues.filterKeys { it.simpleName.toString() == "viewBinder" }.values
val value = when {
values.isEmpty() -> Optional.absent()
else -> {
val firstValue = values.iterator().next()
if (firstValue.value == "<error>") {
messager.printMessage(Diagnostic.Kind.ERROR, "Specified ViewBinder is not a class.", model, annotation)
return emptyList()
}
Optional.of(firstValue)
}
}
val viewIds: Set<Int> = getObservedViewIds(copyMethodsWithOnClick, model)
val annotatedModel = AnnotatedModel(model, typeUtils, elementUtils, messager, value, viewIds)
annotatedModels.add(annotatedModel)
modelToFactory.put(model, annotatedModel.viewHolderFactoryClassName)
}
// enclosing type -> List<{annotatedmethod}>
val listenerToMethodAndIds: Map<Element, List<ExecutableElement>> = methodsWithOnClick.filter {
val method = it as ExecutableElement
val hasModel = method.parameters.count { it.isIn(models) } == 1
val hasView = method.parameters.count { it.isAndroidView() } == 1
method.parameters.isEmpty()
|| (hasView && method.parameters.size == 1)
|| (hasModel && method.parameters.size==1)
|| (hasView && hasModel && method.parameters.size==2)
}.groupBy(keySelector = { it.enclosingElement }, valueTransform = { it as ExecutableElement })
val adapterGenerator = AdapterGenerator(adapterNames, modelToFactory, listenerToMethodAndIds)
val adapter = adapterGenerator.generate()
typeSpecs.add(adapter)
}
return typeSpecs
}
private fun getObservedViewIds(methodsWithOnClick: MutableSet<Element>, model: TypeElement): Set<Int> {
//all click listeners for this model
val methodsForThis: List<Element> = methodsWithOnClick.filter {
val method = it as ExecutableElement
when {
method.parameters.size == 2 -> {
val viewParamsCount = method.parameters.count { it.isAndroidView() }
val modelParamsCount = method.parameters.count { it.isAnnotatedModel(model) }
viewParamsCount == 1 && modelParamsCount == 1
}
method.parameters.size == 1 -> {
method.parameters.first().isAndroidView() || method.parameters.first().isAnnotatedModel(model)
}
else -> {
method.parameters.isEmpty()
}
}
}
//get all viewIds for this model
return methodsForThis.flatMap { method ->
val clickAnnotations = method.annotationMirrors
.filter { Util.typeToString(it.annotationType) == ON_CLICK_ANNOTATION_NAME }
val valueListener = IntAnnotationValueVisitor()
clickAnnotations.forEach {
it.elementValues.filterKeys { "value" == it.simpleName.toString() }.values.first().accept(valueListener, null)
}
valueListener.ids
}.toSet()
}
private fun isAdapterItemAnnotation(it: AnnotationMirror) =
Util.typeToString(it.annotationType) == ADAPTER_ITEM_ANNOTATION_NAME
private fun saveGeneratedTypes(typeSpecs: List<TypeSpec>) {
for (spec in typeSpecs) {
val builder = JavaFile.builder(LIBRARY_PACKAGE, spec)
val file = builder.build()
try {
file.writeTo(filer)
} catch (e: IOException) {
messager.printMessage(Diagnostic.Kind.ERROR, e.message)
e.printStackTrace()
}
}
}
private fun findAllClassesAnnotatedWithAdapterItem(
roundEnvironment: RoundEnvironment): Map<String, List<TypeElement>> {
val result = HashMap<String, MutableList<TypeElement>>()
val adapterItemElement = elementUtils.getTypeElement(ADAPTER_ITEM_ANNOTATION_NAME)
for (element in roundEnvironment.getElementsAnnotatedWith(adapterItemElement)) {
if (element.kind != ElementKind.CLASS) {
messager.printMessage(Diagnostic.Kind.WARNING, "AdapterItem can only be applied to a class.")
continue
}
val annotation = (element as TypeElement).annotationMirrors.first { isAdapterItemAnnotation(it); }
val annotationValue = annotation.elementValues.filterKeys { "value" == it.simpleName.toString() }.values.first()
val value = annotationValue.value
var strings: MutableList<TypeElement>? = result[value.toString()]
if (strings == null) {
strings = ArrayList()
result.put(value.toString(), strings)
}
strings.add(element)
}
return result
}
companion object {
const val LIBRARY_PACKAGE = "com.renard.auto_adapter"
const val ADAPTER_ITEM_ANNOTATION_NAME = "com.renard.auto_adapter.AdapterItem"
const val ON_CLICK_ANNOTATION_NAME = "com.renard.auto_adapter.OnClick"
}
}
|
apache-2.0
|
4720f0f730266229fe4143e974b14dfa
| 39.982609 | 136 | 0.643857 | 5.067742 | false | false | false | false |
ziggy42/Blum
|
app/src/main/java/com/andreapivetta/blu/ui/conversation/ConversationActivity.kt
|
1
|
3755
|
package com.andreapivetta.blu.ui.conversation
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.widget.Toast
import com.andreapivetta.blu.R
import com.andreapivetta.blu.common.utils.visible
import com.andreapivetta.blu.data.model.PrivateMessage
import com.andreapivetta.blu.data.storage.AppStorageFactory
import com.andreapivetta.blu.ui.custom.ThemedActivity
import kotlinx.android.synthetic.main.activity_conversation.*
import timber.log.Timber
import twitter4j.User
class ConversationActivity : ThemedActivity(), ConversationMvpView {
companion object {
const val ARG_OTHER_ID = "other_id"
fun launch(context: Context, otherId: Long) {
val intent = Intent(context, ConversationActivity::class.java)
intent.putExtra(ARG_OTHER_ID, otherId)
context.startActivity(intent)
}
}
private val receiver: PrivateMessagesReceiver? by lazy { PrivateMessagesReceiver() }
private val presenter: ConversationPresenter by lazy {
ConversationPresenter(AppStorageFactory.getAppStorage(),
intent.getLongExtra(ARG_OTHER_ID, -1L))
}
private val adapter = ConversationAdapter()
override fun onResume() {
super.onResume()
registerReceiver(receiver, IntentFilter(PrivateMessage.NEW_PRIVATE_MESSAGE_INTENT))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_conversation)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
toolbar.setNavigationOnClickListener { finish() }
val linearLayoutManager = LinearLayoutManager(this)
linearLayoutManager.stackFromEnd = true
conversationRecyclerView.layoutManager = linearLayoutManager
conversationRecyclerView.adapter = adapter
conversationRecyclerView.setHasFixedSize(true)
sendMessageImageButton.setOnClickListener {
presenter.sendPrivateMessage(messageEditText.text.toString())
messageEditText.setText("")
}
presenter.attachView(this)
}
override fun onDestroy() {
super.onDestroy()
presenter.detachView()
unregisterReceiver(receiver)
}
override fun showLoading() {
loadingProgressBar.visible()
conversationRecyclerView.visible(false)
}
override fun hideLoading() {
loadingProgressBar.visible(false)
conversationRecyclerView.visible(true)
}
override fun showError() {
Toast.makeText(this, getString(R.string.cant_find_user), Toast.LENGTH_SHORT).show()
finish()
}
override fun showUserData(user: User) {
toolbar.title = user.name
}
override fun showConversation(messages: MutableList<PrivateMessage>) {
adapter.messages = messages
adapter.notifyDataSetChanged()
}
override fun showNewPrivateMessage() {
adapter.notifyItemInserted(adapter.messages.size)
conversationRecyclerView.scrollToPosition(adapter.messages.size)
}
override fun showSendFailed() {
Toast.makeText(this, getString(R.string.sending_message_error), Toast.LENGTH_SHORT).show()
}
inner class PrivateMessagesReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action === PrivateMessage.NEW_PRIVATE_MESSAGE_INTENT) {
Timber.i(intent.toString())
presenter.onNewPrivateMessage()
}
}
}
}
|
apache-2.0
|
f40e8b02e2ecf236cf0c52ae2df52f8d
| 32.230088 | 98 | 0.706791 | 5.129781 | false | false | false | false |
Mauin/detekt
|
detekt-core/src/test/kotlin/io/gitlab/arturbosch/detekt/core/CustomRuleSetProviderSpec.kt
|
1
|
782
|
package io.gitlab.arturbosch.detekt.core
import io.gitlab.arturbosch.detekt.test.resource
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import java.nio.file.Paths
/**
* @author Artur Bosch
*/
class CustomRuleSetProviderSpec : Spek({
describe("custom rule sets should be loadable through jars") {
val sampleRuleSet = Paths.get(resource("sample-rule-set.jar"))
it("should load the sample provider") {
val settings = ProcessingSettings(path, excludeDefaultRuleSets = true, pluginPaths = listOf(sampleRuleSet))
val detekt = DetektFacade.create(settings)
val result = detekt.run()
assertThat(result.findings.keys).contains("sample")
}
}
})
|
apache-2.0
|
52f01a8824f736590856ebb7537566d3
| 27.962963 | 110 | 0.763427 | 3.637209 | false | false | false | false |
grassrootza/grassroot-android-v2
|
app/src/main/java/za/org/grassroot2/view/adapter/MembersAdapter.kt
|
1
|
2746
|
package za.org.grassroot2.view.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Filter
import android.widget.Filterable
import com.jakewharton.rxbinding2.view.RxView
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.item_member.view.*
import za.org.grassroot2.R
import za.org.grassroot2.model.Membership
import za.org.grassroot2.model.util.PhoneNumberFormatter
import javax.inject.Inject
/**
* Created by luke on 2017/12/10.
*/
class MembersAdapter @Inject
constructor(private val context: Context, private var data: List<Membership>) : RecyclerView.Adapter<RecyclerView.ViewHolder>(), Filterable {
private var filteredData : List<Membership> = data.toList()
private val viewClickSubject = PublishSubject.create<Membership>()
val viewClickObservable: Observable<Membership>
get() = viewClickSubject
override fun getItemCount(): Int = filteredData.size
override fun getFilter(): Filter = object: Filter() {
override fun performFiltering(constraint: CharSequence): FilterResults {
val results = FilterResults()
val filtered = data.filter { membership -> membership.containsString(constraint) }
results.values = filtered
results.count = filtered.size
return results
}
override fun publishResults(constraint: CharSequence, results: FilterResults) {
filteredData = results.values as List<Membership>
notifyDataSetChanged()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
MembershipViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_member, parent, false))
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val member = filteredData[position]
(holder as MembershipViewHolder).memberName.text = member.name
val roleDescription = context.getString(member.roleNameRes)
holder.memberDetails.text = context.getString(R.string.member_description_format, roleDescription,
PhoneNumberFormatter.formatNumberForDisplay(member.phoneNumber, " "))
RxView.clicks(holder.root).map { _ -> member }.subscribe(viewClickSubject)
}
// todo : add user profile images
internal class MembershipViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
var root = itemView.root
var memberName = itemView.memberName
var memberDetails = itemView.memberDetails
}
}
|
bsd-3-clause
|
f57ef916c2b86eba22b08ceba3b9cc54
| 39.397059 | 141 | 0.736344 | 4.817544 | false | false | false | false |
SuperAwesomeLTD/sa-mobile-sdk-android
|
superawesome-common/src/main/java/tv/superawesome/sdk/publisher/common/components/Device.kt
|
1
|
1026
|
package tv.superawesome.sdk.publisher.common.components
import android.util.DisplayMetrics
import kotlin.math.pow
import kotlin.math.sqrt
interface DeviceType {
var genericType: DeviceCategory
}
enum class DeviceCategory {
phone, tablet;
}
class Device(private val displayMetrics: DisplayMetrics) : DeviceType {
override var genericType: DeviceCategory = deviceCategory
private val systemSize: Double
get() {
val width = displayMetrics.widthPixels
val height = displayMetrics.heightPixels
val density = displayMetrics.densityDpi
val widthDp = width.toDouble() / density.toDouble()
val heightDp = height.toDouble() / density.toDouble()
return sqrt(widthDp.pow(2.0) + heightDp.pow(2.0))
}
private val deviceCategory: DeviceCategory
get() = if (systemSize <= PHONE_SCREEN_MAX) DeviceCategory.phone else DeviceCategory.tablet
companion object {
private const val PHONE_SCREEN_MAX = 6.2
}
}
|
lgpl-3.0
|
e826fb14da701c218a87fefbc47321ad
| 28.314286 | 99 | 0.691033 | 4.621622 | false | false | false | false |
AoEiuV020/PaNovel
|
api/src/main/java/cc/aoeiuv020/panovel/api/ext.kt
|
1
|
2825
|
@file:Suppress("unused")
package cc.aoeiuv020.panovel.api
import java.io.FilterInputStream
import java.io.InputStream
import java.io.OutputStream
/**
* Created by AoEiuV020 on 2017.10.02-16:01:09.
*/
/**
* 结尾不要斜杆/,因为有的地址可能整数后面接文件后缀.html,
* 开头要有斜杆/,因为有的网站可能host有整数,
*/
const val firstIntPattern: String = "/(\\d+)"
const val firstTwoIntPattern: String = "/(\\d+/\\d+)"
const val firstThreeIntPattern: String = "/(\\d+/\\d+/\\d+)"
/**
* 倒序删除重复章节,有的网站章节列表开头有倒序的最新章节,
* 987123456789 删除后得到 123456789,
*/
fun List<NovelChapter>.reverseRemoveDuplication(): List<NovelChapter> {
// 以防万一,
if (this.size == 1) return this
// 倒序列表判断是否重复章节,
val first = this.first()
// 可能有延迟,开头的最新章节列表可能不是最新,先反着删除不是第一章的,再正着删除和最后一章一致的,
val reversedList = this.dropLastWhile { desc ->
!(first.name == desc.name && first.extra == desc.extra)
}.asReversed()
if (reversedList.size == 1) return this
var index = 0
return this.dropWhile { asc ->
val desc = reversedList[index]
(asc.name == desc.name && asc.extra == desc.extra).also {
++index
}
}
}
fun InputStream.copyTo(
out: OutputStream,
maxSize: Long = 0L,
listener: ((Long, Long) -> Unit)? = null,
bufferSize: Int = 4 * 1024
): Long {
var bytesCopied: Long = 0
listener?.invoke(bytesCopied, maxSize)
val buffer = ByteArray(bufferSize)
var bytes = read(buffer)
while (bytes >= 0) {
out.write(buffer, 0, bytes)
bytesCopied += bytes
listener?.invoke(bytesCopied, maxSize)
bytes = read(buffer)
}
return bytesCopied
}
class LoggerInputStream(
input: InputStream,
private val maxSize: Long = 0L,
private val listener: ((Long, Long) -> Unit)? = null
) : FilterInputStream(input) {
private var bytesCopied: Long = 0
init {
listener?.invoke(bytesCopied, maxSize)
}
override fun read(): Int {
return super.read().also {
if (it > 0) {
bytesCopied++
listener?.invoke(bytesCopied, maxSize)
}
}
}
// FilterInputStream的这个方法就是调用自己的read,不能重复处理了,
/*
override fun read(b: ByteArray): Int = read(b, 0, b.size)
*/
override fun read(b: ByteArray, off: Int, len: Int): Int {
return super.read(b, off, len).also {
if (it > 0) {
bytesCopied += it
listener?.invoke(bytesCopied, maxSize)
}
}
}
}
|
gpl-3.0
|
15d45fb8bfb59686aacb03d80644f064
| 25.041667 | 71 | 0.593037 | 3.427984 | false | false | false | false |
PolymerLabs/arcs-live
|
particles/Tutorial/Kotlin/Demo/src/TTTRandomComputer.kt
|
2
|
1203
|
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.tutorials.tictactoe
import arcs.sdk.wasm.WasmHandle
class TTTRandomComputer : AbstractTTTRandomComputer() {
override fun onHandleSync(handle: WasmHandle, allSynced: Boolean) =
getMove(handles.gameState.fetch())
init {
handles.gameState.onUpdate { gameState ->
getMove(gameState)
}
}
fun getMove(gameState: TTTRandomComputer_GameState?) {
val gs = gameState ?: TTTRandomComputer_GameState()
// Ensure we are the current player
val boardArr = gs.board.split(",")
val emptyCells = mutableListOf<Double>()
// Find all the empty cells
boardArr.forEachIndexed { index, cell ->
if (cell == "") emptyCells.add(index.toDouble())
}
// Choose a random cell as the move
if (emptyCells.isNotEmpty()) {
val mv = emptyCells.shuffled().first()
handles.myMove.store(TTTRandomComputer_MyMove(move = mv))
}
}
}
|
bsd-3-clause
|
891c23de27813d8a8092838e3da970bd
| 26.976744 | 96 | 0.691604 | 3.931373 | false | false | false | false |
michaelgallacher/intellij-community
|
python/educational-core/student/src/com/jetbrains/edu/learning/actions/StudySwitchTaskPanelAction.kt
|
10
|
2383
|
package com.jetbrains.edu.learning.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogWrapper
import com.jetbrains.edu.learning.StudyTaskManager
import com.jetbrains.edu.learning.StudyUtils
import javax.swing.DefaultComboBoxModel
import javax.swing.JComponent
import javax.swing.JLabel
class StudySwitchTaskPanelAction: AnAction() {
override fun actionPerformed(e: AnActionEvent?) {
val project = e?.project
if (project != null) {
if (createDialog(project).showAndGet()) {
StudyUtils.initToolWindows(project)
}
}
}
fun createDialog(project: Project): DialogWrapper {
return MyDialog(project, false)
}
class MyDialog: DialogWrapper {
val JAVAFX_ITEM = "JavaFX"
val SWING_ITEM = "Swing"
private val myProject: Project
private val myComboBox: ComboBox<String>
constructor(project: Project, canBeParent: Boolean) : super(project, canBeParent) {
myProject = project
myComboBox = ComboBox<String>()
val comboBoxModel = DefaultComboBoxModel<String>()
if (StudyUtils.hasJavaFx()) {
comboBoxModel.addElement(JAVAFX_ITEM)
}
comboBoxModel.addElement(SWING_ITEM)
comboBoxModel.selectedItem =
if (StudyUtils.hasJavaFx() && StudyTaskManager.getInstance(project).shouldUseJavaFx()) JAVAFX_ITEM else SWING_ITEM
myComboBox.model = comboBoxModel
title = "Switch Task Description Panel"
myComboBox.setMinimumAndPreferredWidth(250)
init()
}
override fun createCenterPanel(): JComponent? {
return myComboBox
}
override fun createNorthPanel(): JComponent? {
return JLabel("Choose panel: ")
}
override fun getPreferredFocusedComponent(): JComponent? {
return myComboBox
}
override fun doOKAction() {
super.doOKAction()
StudyTaskManager.getInstance(myProject).setShouldUseJavaFx(myComboBox.selectedItem == JAVAFX_ITEM)
}
}
override fun update(e: AnActionEvent?) {
val project = e?.project
if (project != null && StudyUtils.isStudyProject(project)) {
e?.presentation?.isEnabled = true
}
else {
e?.presentation?.isEnabled = false
}
}
}
|
apache-2.0
|
bc1da317172d1f49f6850b2788817cf7
| 27.380952 | 124 | 0.704154 | 4.565134 | false | false | false | false |
rcgroot/open-gpstracker-ng
|
studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/graphs/GraphsViewModel.kt
|
1
|
2754
|
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) 2017 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker 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.
*
* OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.ng.features.graphs
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import android.net.Uri
import nl.sogeti.android.gpstracker.ng.features.graphs.dataproviders.GraphDataCalculator
import nl.sogeti.android.gpstracker.ng.features.graphs.widgets.GraphPoint
import nl.sogeti.android.opengpstrack.ng.features.R
class GraphsViewModel {
val trackUri = ObservableField<Uri?>()
val startTime = ObservableField<Long>(0L)
val timeSpan = ObservableField<Long>(0L)
val paused = ObservableField<Long>(0)
val distance = ObservableField<Float>(0F)
val duration = ObservableField<Long>(0L)
val speed = ObservableField<Float>(0F)
val waypoints = ObservableField<String>("-")
val distanceSelected = ObservableBoolean(false)
val durationSelected = ObservableBoolean(false)
val inverseSpeed = ObservableBoolean(false)
val graphData = ObservableField<List<GraphPoint>>(emptyList())
val graphLabels = ObservableField<GraphDataCalculator>(GraphDataCalculator.DefaultGraphValueDescriptor)
val xLabel = ObservableInt(R.string.graph_label_time)
val yLabel = ObservableInt(R.string.graph_label_speed)
}
|
gpl-3.0
|
92bd7473f4ccfcc9db9fb6a096b3de3c
| 45.677966 | 107 | 0.671024 | 4.789565 | false | false | false | false |
aglne/mycollab
|
mycollab-servlet/src/main/java/com/mycollab/module/file/servlet/ResourceGetHandler.kt
|
3
|
2614
|
/**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.module.file.servlet
import com.mycollab.core.utils.MimeTypesUtil
import com.mycollab.module.ecm.service.ResourceService
import com.mycollab.servlet.GenericHttpServlet
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.IOException
import javax.servlet.ServletException
import javax.servlet.annotation.WebServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* @author MyCollab Ltd.
* @since 4.4.0
*/
@WebServlet(urlPatterns = ["/file/*"], name = "resourceGetHandler")
class ResourceGetHandler : GenericHttpServlet() {
@Autowired
private lateinit var resourceService: ResourceService
@Throws(ServletException::class, IOException::class)
override fun onHandleRequest(request: HttpServletRequest, response: HttpServletResponse) {
val path = request.pathInfo
val inputStream = resourceService.getContentStream(path)
if (inputStream != null) {
response.setHeader("Content-Type", MimeTypesUtil.detectMimeType(path))
response.setHeader("Content-Length", inputStream.available().toString())
BufferedInputStream(inputStream).use { input ->
BufferedOutputStream(response.outputStream).use { output ->
val buffer = ByteArray(8192)
var length = input.read(buffer)
while (length > 0) {
output.write(buffer, 0, length)
length = input.read(buffer)
}
}
}
} else {
LOG.error("Can not find resource has path $path")
}
}
companion object {
private val LOG = LoggerFactory.getLogger(ResourceGetHandler::class.java)
}
}
|
agpl-3.0
|
c4abb6431ccf2a0f383a67ea618ab726
| 36.869565 | 94 | 0.694221 | 4.682796 | false | false | false | false |
material-components/material-components-android-examples
|
Owl/app/src/main/java/com/materialstudies/owl/model/Lesson.kt
|
1
|
2833
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.materialstudies.owl.model
import androidx.recyclerview.widget.DiffUtil
data class Lesson(
val title: String,
val formattedStepNumber: String,
val length: String,
val imageUrl: String,
val imageContentDescription: String = ""
)
object LessonDiff : DiffUtil.ItemCallback<Lesson>() {
override fun areItemsTheSame(oldItem: Lesson, newItem: Lesson) = oldItem.title == newItem.title
override fun areContentsTheSame(oldItem: Lesson, newItem: Lesson) = oldItem == newItem
}
val lessons = listOf(
Lesson(
title = "An introduction to the Landscape",
formattedStepNumber = "01",
length = "4:14",
imageUrl = "https://source.unsplash.com/NRQV-hBF10M"
),
Lesson(
title = "Movement and Expression",
formattedStepNumber = "02",
length = "7:28",
imageUrl = "https://source.unsplash.com/JhqhGfX_Wd8"
),
Lesson(
title = "Composition and the Urban Canvas",
formattedStepNumber = "03",
length = "3:43",
imageUrl = "https://source.unsplash.com/0OjzOqlJyoU"
),
Lesson(
title = "Lighting Techniques and Aesthetics",
formattedStepNumber = "04",
length = "4:45",
imageUrl = "https://source.unsplash.com/J5-Kqu_fxyo"
),
Lesson(
title = "Special Effects",
formattedStepNumber = "05",
length = "6:19",
imageUrl = "https://source.unsplash.com/9ZCZoH69dZQ"
),
Lesson(
title = "Techniques with Structures",
formattedStepNumber = "06",
length = "9:41",
imageUrl = "https://source.unsplash.com/RFDP7_80v5A"
),
Lesson(
title = "Deep Focus Using a Camera Dolly",
formattedStepNumber = "07",
length = "4:43",
imageUrl = "https://source.unsplash.com/0rZ2-QWtkwY"
),
Lesson(
title = "Point of View Shots with Structures",
formattedStepNumber = "08",
length = "9:41",
imageUrl = "https://source.unsplash.com/iQnR_xEsBj0"
),
Lesson(
title = "Photojournalism: Street Art",
formattedStepNumber = "09",
length = "9:41",
imageUrl = "https://source.unsplash.com/qX9Ie7ieb1E"
)
)
|
apache-2.0
|
5f2b0e39238f853ec9025dd154afd6c4
| 30.831461 | 99 | 0.632898 | 3.782377 | false | false | false | false |
DemonWav/IntelliJBukkitSupport
|
src/main/kotlin/translations/lang/psi/mixins/LangEntryImplMixin.kt
|
1
|
2117
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.lang.psi.mixins
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.translations.lang.LangFile
import com.demonwav.mcdev.translations.lang.LangFileType
import com.demonwav.mcdev.translations.lang.gen.psi.LangEntry
import com.demonwav.mcdev.translations.lang.gen.psi.LangTypes
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.navigation.ItemPresentation
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileFactory
abstract class LangEntryImplMixin(node: ASTNode) : ASTWrapperPsiElement(node), LangEntryMixin {
override val key: String
get() = node.findChildByType(LangTypes.KEY)?.text ?: ""
override val value: String
get() = node.findChildByType(LangTypes.VALUE)?.text ?: ""
override fun getNameIdentifier() = node.findChildByType(LangTypes.KEY)?.psi
override fun getName() = key
override fun setName(name: String): PsiElement {
val keyElement = node.findChildByType(LangTypes.KEY)
val tmpFile = PsiFileFactory.getInstance(project).createFileFromText("name", LangFileType, "name=") as LangFile
val renamed = tmpFile.firstChild as LangEntry
val newKey = renamed.node.findChildByType(LangTypes.KEY)
if (newKey != null) {
if (keyElement != null) {
this.node.replaceChild(keyElement, newKey)
} else {
this.node.addChild(newKey, node.findChildByType(LangTypes.EQUALS))
}
} else if (keyElement != null) {
this.node.removeChild(keyElement)
}
return this
}
override fun getPresentation() = object : ItemPresentation {
override fun getPresentableText() = key
override fun getLocationString() = containingFile.name
override fun getIcon(unused: Boolean) = PlatformAssets.MINECRAFT_ICON
}
override fun toString() = "LangEntry($key=$value)"
}
|
mit
|
b07be81615d038e3b92fedf6804842ff
| 33.704918 | 119 | 0.705716 | 4.42887 | false | false | false | false |
openHPI/android-app
|
app/src/main/java/de/xikolo/storages/UserStorage.kt
|
1
|
575
|
package de.xikolo.storages
import android.content.Context
import de.xikolo.storages.base.BaseStorage
class UserStorage : BaseStorage(PREF_USER, Context.MODE_PRIVATE) {
var userId: String?
get() = getString(USER_ID)
set(value) = putString(USER_ID, value)
var accessToken: String?
get() = getString(ACCESS_TOKEN)
set(value) = putString(ACCESS_TOKEN, value)
companion object {
private const val PREF_USER = "pref_user_v2"
private const val USER_ID = "id"
private const val ACCESS_TOKEN = "token"
}
}
|
bsd-3-clause
|
f2ec1d8b5ab8df7d6039a6dfb1f6940e
| 25.136364 | 66 | 0.65913 | 3.733766 | false | false | false | false |
Kotlin/kotlin-coroutines
|
examples/context/threadContext-example.kt
|
1
|
762
|
package context
import delay.*
import future.*
import util.*
fun main(args: Array<String>) {
log("Starting MyEventThread")
val context = newSingleThreadContext("MyEventThread")
val f = future(context) {
log("Hello, world!")
val f1 = future(context) {
log("f1 is sleeping")
delay(1000) // sleep 1s
log("f1 returns 1")
1
}
val f2 = future(context) {
log("f2 is sleeping")
delay(1000) // sleep 1s
log("f2 returns 2")
2
}
log("I'll wait for both f1 and f2. It should take just a second!")
val sum = f1.await() + f2.await()
log("And the sum is $sum")
}
f.get()
log("Terminated")
}
|
apache-2.0
|
9c18fa40b558e9e03e4905c60b139992
| 24.4 | 74 | 0.518373 | 3.848485 | false | false | false | false |
stoman/competitive-programming
|
problems/2021adventofcode03b/submissions/accepted/Stefan.kt
|
2
|
1070
|
import java.util.*
private fun <T> List<T>.mode(tieBreaker: Comparator<T>): T? {
val comparator = compareBy<Map.Entry<T, List<T>>> { it.value.size }.thenBy(tieBreaker, { it.key })
return groupBy { it }.maxOfWithOrNull(comparator, { it })?.key
}
private fun filter(bits: List<List<Boolean>>, selector: (List<Boolean>) -> Boolean, index: Int = 0): List<Boolean> {
val bitCriterion = selector(bits.map { it[index] })
val selection = bits.filter { it[index] == bitCriterion }
return if (selection.size == 1) selection[0] else filter(selection, selector, index + 1)
}
private fun List<Boolean>.binary(): Int = reversed().mapIndexed { i, b -> if (b) 1 shl i else 0 }.sum()
@ExperimentalStdlibApi
fun main() {
val s = Scanner(System.`in`)
val report = buildList {
while (s.hasNext()) {
add(s.next().map { it == '1' })
}
}
val oxygenGeneratorRating = filter(report, { it.mode(naturalOrder())!! }).binary()
val co2ScrubberRating = filter(report, { !it.mode(naturalOrder())!! }).binary()
println(oxygenGeneratorRating * co2ScrubberRating)
}
|
mit
|
1f8cf5225a39d244e5b433fa76bce345
| 38.666667 | 116 | 0.665421 | 3.34375 | false | false | false | false |
rmnn/compiler
|
src/main/kotlin/ru/dageev/compiler/parser/visitor/expression/VariableReferenceVisitor.kt
|
1
|
1381
|
package ru.dageev.compiler.parser.visitor.expression
import ru.dageev.compiler.domain.ClassesContext
import ru.dageev.compiler.domain.node.expression.VariableReference
import ru.dageev.compiler.domain.scope.Scope
import ru.dageev.compiler.domain.type.ClassType
import ru.dageev.compiler.grammar.ElaginBaseVisitor
import ru.dageev.compiler.grammar.ElaginParser
import ru.dageev.compiler.parser.CompilationException
import ru.dageev.compiler.parser.helper.getField
/**
* Created by dageev
* on 10/30/16.
*/
class VariableReferenceVisitor(scope: Scope, val classesContext: ClassesContext) : ElaginBaseVisitor<VariableReference>() {
val scope: Scope
init {
this.scope = scope.copy()
}
override fun visitVariableReference(ctx: ElaginParser.VariableReferenceContext): VariableReference {
val name = ctx.text
val localVariable = scope.localVariables[name]
return if (localVariable != null) {
VariableReference.LocalVariableReference(localVariable)
} else {
val field = getField(classesContext, scope, ClassType(scope.className), name)
return if (field.isPresent) {
VariableReference.FieldReference(field.get())
} else {
throw CompilationException("Local variable '$name' not found for class '${scope.className}'")
}
}
}
}
|
apache-2.0
|
5b5447218e30da5e96b0c7a1a6177206
| 36.351351 | 123 | 0.714699 | 4.572848 | false | false | false | false |
vondear/RxTools
|
RxUI/src/main/java/com/tamsiree/rxui/view/ticker/RxTickerUtils.kt
|
1
|
1697
|
package com.tamsiree.rxui.view.ticker
/**
* @author tamsiree
* Static utility class for the ticker package. This class contains helper methods such as those
* that generate default character lists to use for animation.
*/
object RxTickerUtils {
const val EMPTY_CHAR = 0.toChar()// Special case EMPTY_CHAR and '.' <-> '/'
/**
* @return a default ordering for all viewable ASCII characters. This list also special cases
* space to be in front of the 0 and swap '.' with '/'. These special cases make
* typical US currency animations intuitive.
*/
val defaultListForUSCurrency: CharArray
get() {
val indexOf0 = '0'.toInt()
val indexOfPeriod = '.'.toInt()
val indexOfSlash = '/'.toInt()
val start = 33
val end = 256
val charList = CharArray(end - start + 1)
for (i in start until indexOf0) {
charList[i - start] = i.toChar()
}
// Special case EMPTY_CHAR and '.' <-> '/'
charList[indexOf0 - start] = EMPTY_CHAR
charList[indexOfPeriod - start] = '/'
charList[indexOfSlash - start] = '.'
for (i in indexOf0 + 1 until end + 1) {
charList[i - start] = (i - 1).toChar()
}
return charList
}
/**
* @return a default ordering for numbers (including periods).
*/
val defaultNumberList: CharArray
get() {
val charList = CharArray(11)
charList[0] = EMPTY_CHAR
for (i in 0..9) {
charList[i + 1] = (i + 48).toChar()
}
return charList
}
}
|
apache-2.0
|
0a868804090f1f73649a2db5d97bd10a
| 32.96 | 97 | 0.542133 | 4.442408 | false | false | false | false |
icapps/niddler-ui
|
client-lib/src/main/kotlin/com/icapps/niddler/lib/debugger/model/DebuggerInterface.kt
|
1
|
3346
|
package com.icapps.niddler.lib.debugger.model
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.annotations.Expose
/**
* @author nicolaverbeeck
*/
interface DebuggerInterface {
fun activate()
fun deactivate()
fun updateBlacklist(active: Iterable<String>)
fun updateDefaultResponses(items: Iterable<LocalRequestIntercept>)
fun updateResponseIntercepts(items: List<LocalResponseIntercept>)
fun updateRequestIntercepts(items: Iterable<LocalRequestIntercept>)
fun mute()
fun unmute()
fun updateDelays(delays: DebuggerDelays?)
fun debugDelays(): DebuggerDelays?
fun connect()
fun disconnect()
}
interface BaseAction {
var id: String
var repeatCount: Int?
var active: Boolean
fun updateJson(json: JsonObject) {
json.addProperty("id", id)
json.addProperty("active", active)
json.addProperty("repeatCount", repeatCount)
}
}
interface BaseMatcher : BaseAction {
var regex: String?
var matchMethod: String?
override fun updateJson(json: JsonObject) {
super.updateJson(json)
json.addProperty("regex", regex)
json.addProperty("matchMethod", matchMethod)
}
}
interface ResponseMatcher : BaseMatcher {
var responseCode: Int?
override fun updateJson(json: JsonObject) {
super.updateJson(json)
json.addProperty("responseCode", responseCode)
}
}
data class LocalRequestOverride(@Expose override var id: String = "",
@Expose override var active: Boolean = false,
@Expose override var regex: String? = null,
@Expose override var matchMethod: String? = null,
@Expose override var repeatCount: Int? = null,
@Expose var debugRequest: DebugRequest? = null) : BaseMatcher {
override fun toString(): String {
return regex ?: matchMethod ?: ""
}
}
data class LocalRequestIntercept(@Expose override var id: String = "",
@Expose override var active: Boolean = false,
@Expose override var regex: String? = null,
@Expose override var matchMethod: String? = null,
@Expose override var repeatCount: Int? = null,
@Expose var debugResponse: DebugResponse? = null) : BaseMatcher {
fun toServerJson(gson: Gson): JsonObject {
val json = JsonObject()
updateJson(json)
json.merge(gson, debugResponse)
return json
}
}
data class LocalResponseIntercept(@Expose override var id: String = "",
@Expose override var active: Boolean = false,
@Expose override var regex: String? = null,
@Expose override var matchMethod: String? = null,
@Expose override var repeatCount: Int? = null,
@Expose override var responseCode: Int? = null,
@Expose var response: DebugResponse? = null) : ResponseMatcher {
override fun toString(): String {
return regex ?: matchMethod ?: ""
}
}
|
apache-2.0
|
ebcb2655ed4566259f846e022bd9b629
| 29.990741 | 98 | 0.590257 | 5.039157 | false | false | false | false |
openstreetview/android
|
app/src/main/java/com/telenav/osv/data/collector/phonedata/collector/ApplicationIDCollector.kt
|
1
|
1941
|
package com.telenav.osv.data.collector.phonedata.collector
import android.content.Context
import android.os.Handler
import com.telenav.osv.data.collector.datatype.datatypes.ApplicationIdObject
import com.telenav.osv.data.collector.datatype.util.LibraryUtil
import com.telenav.osv.data.collector.phonedata.manager.PhoneDataListener
import java.util.*
/**
* ApplicationIDCollector class generates an id used for app identification.
* The id is removed when the app is uninstalled
*/
class ApplicationIDCollector(phoneDataListener: PhoneDataListener?, notifyHandler: Handler?) : PhoneCollector(phoneDataListener, notifyHandler) {
/**
* Generate an unique ID and send the information to the client.
* The ID is stored in shared preferences and it is lost when app is uninstaled
* The method is called once when the service is started
*/
fun sendApplicationID(context: Context) {
val prefs = context
.getSharedPreferences(PREFS_FILE, 0)
var id: String? = null
if (prefs != null) {
id = prefs.getString(PREFS_DEVICE_ID, null)
}
val uuid: UUID
if (id != null) {
// Use the ids previously computed and stored in the
// prefs file
uuid = UUID.fromString(id)
} else {
uuid = UUID.randomUUID()
prefs?.edit()?.putString(PREFS_DEVICE_ID, uuid.toString())?.apply()
}
val applicationIdObject = ApplicationIdObject(uuid.toString(), LibraryUtil.PHONE_SENSOR_READ_SUCCESS)
onNewSensorEvent(applicationIdObject)
}
companion object {
/**
* The name of the preferences file used for saving the UUID of the device
*/
private const val PREFS_FILE = "device_id.xml"
/**
* The tag used for retrieve the UUID from the preferences
*/
private const val PREFS_DEVICE_ID = "device_id"
}
}
|
lgpl-3.0
|
5e17859123d9d6bd4782bd09a29c07e6
| 37.078431 | 145 | 0.665636 | 4.513953 | false | false | false | false |
syrop/Victor-Events
|
events/src/main/kotlin/pl/org/seva/events/main/data/firestore/FsWriter.kt
|
1
|
2701
|
/*
* Copyright (C) 2017 Wiktor Nizio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.events.main.data.firestore
import com.google.firebase.firestore.SetOptions
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import pl.org.seva.events.comm.Comm
import pl.org.seva.events.event.Event
import pl.org.seva.events.login.Login
import pl.org.seva.events.main.init.instance
import java.util.*
open class FsWriter : FsBase() {
private val login by instance<Login>()
infix fun create(comm: Comm) {
comm.writeEvent(Event.creationEvent.copy(comm = comm.name))
comm.writeName()
}
open infix fun add(event: Event) = event.comm.toLowerCase(Locale.getDefault()).writeEvent(event)
open fun addAll(vararg events: Event) = events.forEach { add(it) }
infix fun update(comm: Comm) = with(comm) {
lcName.comm.set(mapOf(COMM_NAME to name, COMM_DESC to desc), SetOptions.merge())
}
suspend infix fun delete(comm: Comm) = coroutineScope {
launch {
comm.lcName.events.read().map { event ->
launch { event.reference.delete() }
}.joinAll()
comm.lcName.comm.delete()
}
launch {
comm.lcName.admins.read().map { admin ->
launch {
admin.reference.delete()
}
}.joinAll()
comm.lcName.privateComm.delete()
}
}
infix fun grantAdmin(comm: Comm) = grantAdmin(comm, login.email)
fun grantAdmin(comm: Comm, email: String) =
comm.lcName.admins.document(email).set(mapOf(ADMIN_GRANTED to true))
private infix fun Comm.writeEvent(event: Event) = lcName writeEvent event
private infix fun String.writeEvent(event: Event) = with (event.fsEvent) {
events.document(timestamp.toString()).set(this)
}
private fun Comm.writeName() = lcName.comm.set(mapOf(COMM_NAME to name))
}
|
gpl-3.0
|
37134997f8bc4d6fa1fb71b49c3b5427
| 33.628205 | 100 | 0.680118 | 3.864092 | false | false | false | false |
exponent/exponent
|
packages/expo-haptics/android/src/main/java/expo/modules/haptics/arguments/HapticsVibrationType.kt
|
2
|
767
|
package expo.modules.haptics.arguments
data class HapticsVibrationType(
val timings: LongArray,
val amplitudes: IntArray,
val oldSDKPattern: LongArray
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as HapticsVibrationType
if (!timings.contentEquals(other.timings)) return false
if (!amplitudes.contentEquals(other.amplitudes)) return false
if (!oldSDKPattern.contentEquals(other.oldSDKPattern)) return false
return true
}
override fun hashCode(): Int {
var result = timings.contentHashCode()
result = 31 * result + amplitudes.contentHashCode()
result = 31 * result + oldSDKPattern.contentHashCode()
return result
}
}
|
bsd-3-clause
|
a2db5aeab3c6aa46a88fd1662aee5e09
| 27.407407 | 71 | 0.720991 | 4.48538 | false | false | false | false |
peervalhoegen/SudoQ
|
sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/sudoku/sudokuTypes/SudokuType.kt
|
1
|
8123
|
/*
* SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least.
* Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
package de.sudoq.model.sudoku.sudokuTypes
import de.sudoq.model.solverGenerator.solver.helper.Helpers
import de.sudoq.model.sudoku.Constraint
import de.sudoq.model.sudoku.Position
import de.sudoq.model.sudoku.Sudoku
import de.sudoq.model.sudoku.complexity.Complexity
import de.sudoq.model.sudoku.complexity.ComplexityConstraint
import de.sudoq.model.sudoku.complexity.ComplexityFactory
import java.util.*
import kotlin.collections.ArrayList
/**
* A SudokuType represents the Attributes of a specific sudoku type.
* This includes especially the Constraints that describe a sudoku type.
*/
open class SudokuType : Iterable<Constraint>, ComplexityFactory {
/** Enum holding this Type */
open var enumType: SudokuTypes? = null
//TODO make fillFromXML statis - make this nonnullable
/** The ratio of fields that are to be allocated i.e. already filled when starting a sudoku game */
@JvmField
var standardAllocationFactor: Float = 0f
/**
* Gibt den Standard Belegungsfaktor zurück
*/
override fun getStandardAllocationFactor(): Float {
return standardAllocationFactor //this is needed explicitly because of ComplexityFactory TODO combine with field one everything is kotlin
}
/**
* The size of the sudoku as a [Position] object where
* the x-coordinate is the maximum number of (columns) horizontal cells and
* the y-coordinate is the maximum number of (rows) vertical cells.
*/
var size: Position? = null
protected set
/**
* The Dimensions of one quadratic block, i.e. for a normal 9x9 Sudoku: 3,3.
* But for Squiggly or Stairstep: 0,0
* and for 4x4: 2,2
*/
var blockSize: Position = Position.get(0, 0)
protected set
/**
* Number of symbols that can be entered in a cell.
*/
var numberOfSymbols = 0
private set
/**
* The list of constraints for this sudoku type
*/
@JvmField
var constraints: MutableList<Constraint>
/**
* All [Position]s that are contained in at least one constraint.
* (For a Samurai sudoku not all positions are part of a constraint)
*/
protected lateinit var positions: MutableList<Position>
/**
* list of admissible permutations for this sudoku type
*/
var permutationProperties: List<PermutationProperties>
var helperList: MutableList<Helpers>
@JvmField
var ccb: ComplexityConstraintBuilder
/**
* Creates a SudokuType
*
* @param width width of the sudoku in cells
* @param height height of the sudoku in cells
* @param numberOfSymbols the number of symbols that can be used in this sudoku
*/
constructor(width: Int, height: Int, numberOfSymbols: Int) {
require(numberOfSymbols >= 0) { "Number of symbols < 0 : $numberOfSymbols" }
require(width >= 0) { "Sudoku width < 0 : $width" }
require(height >= 0) { "Sudoku height < 0 : $height" }
enumType = null
standardAllocationFactor = -1.0f
this.numberOfSymbols = numberOfSymbols
size = Position.get(width, height)
constraints = ArrayList()
positions = ArrayList()
permutationProperties = ArrayList()
helperList = ArrayList()
ccb = ComplexityConstraintBuilder()
}
/**
* used to initialize from SudokuTypeBE
*/
constructor(
enumType: SudokuTypes,
numberOfSymbols: Int,
standardAllocationFactor: Float,
size: Position,
blockSize: Position,
constraints: MutableList<Constraint>,
permutationProperties: List<PermutationProperties>,
helperList: MutableList<Helpers>,
ccb: ComplexityConstraintBuilder
) {
this.enumType = enumType
this.numberOfSymbols = numberOfSymbols
this.standardAllocationFactor = standardAllocationFactor
this.size = size
this.blockSize = blockSize
this.constraints = constraints
this.permutationProperties = permutationProperties
this.helperList = helperList
this.ccb = ccb
initPositionsList()
}
/**
* Checks if the passed [Sudoku] satisfies all [Constraint]s of this [SudokuType].
*
* @param sudoku Sudoku to check for constraint satisfaction
* @return true, iff the sudoku satisfies all constraints
*/
fun checkSudoku(sudoku: Sudoku): Boolean {
return constraints.all { it.isSaturated(sudoku) }
}
/**
* Returns an Iterator over the [Constraint]s of this sudoku type.
*
* @return Iterator over the [Constraint]s of this sudoku type
*/
override fun iterator(): Iterator<Constraint> {
return constraints.iterator()
}
private inner class Positions : Iterable<Position> {
override fun iterator(): Iterator<Position> {
return positions.iterator()
}
}
/**
* Returns an iterator over all valid positions in this type.
* valid meaning a position that appears in a constraint
* @return all positions
*/
val validPositions: Iterable<Position>
get() = Positions()
/**
* returns a (monotone) Iterable over all symbols in this type starting at 0, for use in for each loops
* @return a (monotone) Iterable over all symbols in this type starting at 0
*/
val symbolIterator: Iterable<Int>
get() = object : AbstractList<Int>() {
override fun get(index: Int): Int {
return index
}
override val size: Int
get() = numberOfSymbols
}
/**
* Returns a complexity constraint for a complexity.
*
* @param complexity Complexity for which to return a ComplexityConstraint
*/
override fun buildComplexityConstraint(complexity: Complexity?): ComplexityConstraint? {
return ccb.getComplexityConstraint(complexity)
}
/**
* Returns the sudoku type as string.
*
* @return sudoku type as string
*/
override fun toString(): String {
return "" + enumType
}
/**
* Sets the type
* @param type Type
*/
fun setTypeName(type: SudokuTypes) {
enumType = type
}
fun setDimensions(p: Position) {
size = p
}
fun setNumberOfSymbols(numberOfSymbols: Int) {
if (numberOfSymbols > 0) this.numberOfSymbols = numberOfSymbols
}
/**
* @return A list of the [Constraint]s of this SudokuType.
*/
@Deprecated(
"Gibt eine Liste der Constraints, welche zu diesem Sudokutyp gehören zurück. " +
"Hinweis: Wenn möglich stattdessen den Iterator benutzen.",
ReplaceWith(
"iterator()",
"kotlin.collections.Iterator",
"de.sudoq.model.sudoku.Constraint"
)
)
fun getConstraints(): ArrayList<Constraint> {
return constraints as ArrayList<Constraint>
}
//make a method that returns an iterator over all positions !=null. I think we need this a lot
fun addConstraint(c: Constraint) {
constraints.add(c)
}
private fun initPositionsList() {
positions = ArrayList()
for (c in constraints) for (p in c) if (!positions.contains(p)) positions.add(p)
}
}
|
gpl-3.0
|
33de8807a2e65c7dc3c6748a7120b96f
| 32.004065 | 243 | 0.659892 | 4.586441 | false | false | false | false |
exponent/exponent
|
packages/unimodules-test-core/android/src/main/java/org/unimodules/test/core/UnimoduleMocks.kt
|
2
|
2164
|
package org.unimodules.test.core
import io.mockk.MockKGateway
import io.mockk.every
import io.mockk.mockk
import io.mockk.spyk
import expo.modules.core.ExportedModule
import expo.modules.core.ModuleRegistry
import expo.modules.core.interfaces.InternalModule
import java.util.*
@JvmOverloads
fun moduleRegistryMock(
internalModules: List<InternalModule> = Collections.emptyList(),
exportedModules: List<ExportedModule> = Collections.emptyList()
): ModuleRegistry {
return mockk<ModuleRegistry>().also {
mockInternalModules(it, internalModules)
mockExternalModules(it, exportedModules)
}
}
inline fun <reified T : InternalModule> mockkInternalModule(relaxed: Boolean = false, asInterface: Class<*> = T::class.java): T {
val mock: T = mockk(relaxed = relaxed)
every { mock.exportedInterfaces } returns listOf(asInterface)
return mock
}
private fun mockInternalModules(mock: ModuleRegistry, internalModules: List<InternalModule>) {
internalModules.forEach {
mock.mockInternalModule(it)
}
every { mock.getModule<Any>(any()) } returns null
}
private fun mockExternalModules(mock: ModuleRegistry, exportedModules: List<ExportedModule>) {
exportedModules.forEach {
every { mock.getExportedModule(it.name) } returns it
}
every { mock.getExportedModule(any()) } returns null
}
fun ModuleRegistry.mockInternalModule(module: InternalModule) =
if (!this.isMock) {
throw IllegalStateException("Mocking modules available only for mocked module registry!")
} else {
module.exportedInterfaces.forEach {
every { [email protected](it) } returns module
}
}
fun ModuleRegistry.mockExportedModule(module: ExportedModule) =
if (!this.isMock) {
throw IllegalStateException("Mocking modules available only for mocked module registry!")
} else {
every { [email protected](module.name) } returns module
}
fun mockPromise(): PromiseMock {
return spyk()
}
private val <T : Any> T.isMock: Boolean
get() {
return try {
MockKGateway.implementation().mockFactory.isMock(this)
} catch (e: UninitializedPropertyAccessException) {
false
}
}
|
bsd-3-clause
|
d709e35e7e677cd84dc27d3a2e96c8c5
| 29.914286 | 129 | 0.752773 | 4.259843 | false | false | false | false |
HabitRPG/habitrpg-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/models/responses/TaskDirectionDataTemp.kt
|
1
|
471
|
package com.habitrpg.android.habitica.models.responses
class TaskDirectionDataTemp {
var drop: TaskDirectionDataDrop? = null
var quest: TaskDirectionDataQuest? = null
var crit: Float? = null
}
class TaskDirectionDataQuest {
var progressDelta: Double = 0.0
var collection: Int = 0
}
class TaskDirectionDataDrop {
var value: Int = 0
var key: String? = null
var type: String? = null
var dialog: String? = null
}
|
gpl-3.0
|
a5cfa5f2f2bb027cd88799db9d571b1a
| 20.428571 | 54 | 0.666667 | 4.095652 | false | false | false | false |
HabitRPG/habitrpg-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/dialogs/QuestCompletedDialog.kt
|
2
|
1117
|
package com.habitrpg.android.habitica.ui.views.dialogs
import android.content.Context
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.models.inventory.QuestContent
class QuestCompletedDialog(context: Context) : HabiticaAlertDialog(context) {
var quest: QuestContent? = null
set(value) {
field = value
if (value == null) return
val contentView = QuestCompletedDialogContent(context)
contentView.setQuestContent(value)
setAdditionalContentView(contentView)
}
override fun dismiss() {
dialog = null
super.dismiss()
}
companion object {
private var dialog: QuestCompletedDialog? = null
fun showWithQuest(context: Context, quest: QuestContent) {
if (dialog != null) return
dialog = QuestCompletedDialog(context)
dialog?.quest = quest
dialog?.setTitle(R.string.quest_completed)
dialog?.addButton(R.string.onwards, isPrimary = true, isDestructive = false)
dialog?.enqueue()
}
}
}
|
gpl-3.0
|
64b13d18307501bc018247812bff41c9
| 29.189189 | 88 | 0.645479 | 4.793991 | false | false | false | false |
androidx/androidx
|
bluetooth/bluetooth-core/src/main/java/androidx/bluetooth/core/BluetoothGattService.kt
|
3
|
14351
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.bluetooth.core
import android.bluetooth.BluetoothGattService as FwkBluetoothGattService
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
import java.util.UUID
/**
* @hide
*/
class BluetoothGattService internal constructor(service: FwkBluetoothGattService) :
Bundleable {
companion object {
/**
* Primary service
*/
const val SERVICE_TYPE_PRIMARY = FwkBluetoothGattService.SERVICE_TYPE_PRIMARY
/**
* Secondary service (included by primary services)
*/
const val SERVICE_TYPE_SECONDARY = FwkBluetoothGattService.SERVICE_TYPE_SECONDARY
/**
* A companion object to create [BluetoothGattService] from bundle
*/
val CREATOR: Bundleable.Creator<BluetoothGattService> =
if (Build.VERSION.SDK_INT >= 24) {
GattServiceImplApi24.CREATOR
} else {
GattServiceImplApi21.CREATOR
}
internal fun keyForField(field: Int): String {
return field.toString(Character.MAX_RADIX)
}
}
/**
* Create a new BluetoothGattService.
*
* @param uuid The UUID for this service
* @param type The type of this service,
* {@link BluetoothGattService#SERVICE_TYPE_PRIMARY}
* or {@link BluetoothGattService#SERVICE_TYPE_SECONDARY}
*/
constructor(uuid: UUID, type: Int = SERVICE_TYPE_PRIMARY) : this(
FwkBluetoothGattService(
uuid,
type
)
)
private val impl =
if (Build.VERSION.SDK_INT >= 24) {
GattServiceImplApi24(service, this)
} else {
GattServiceImplApi21(service, this)
}
/**
* The underlying framework's [android.bluetooth.BluetoothGattService]
*/
internal val fwkService: FwkBluetoothGattService
get() = impl.fwkService
/**
* Service's instanceId
*/
val instanceId: Int
get() = impl.instanceId
/**
* Service's type (Primary or Secondary)
*/
val type: Int
get() = impl.type
/**
* Service's universal unique identifier
*/
val uuid: UUID
get() = impl.uuid
/**
* List of [BluetoothGattCharacteristic] that this service include
*/
val characteristics: List<BluetoothGattCharacteristic>
get() = impl.characteristics
/**
* List of [BluetoothGattService] that this service include
*/
val includedServices: List<BluetoothGattService>
get() = impl.includedServices
/**
* Add a characteristic to this service
*
* @param characteristic The [BluetoothGattCharacteristic] to be included
*/
fun addCharacteristic(characteristic: BluetoothGattCharacteristic): Boolean {
return impl.addCharacteristic(characteristic)
}
/**
* Returns a characteristic with a given UUID out of the list of
* characteristics offered by this service.
*
* <p>This is a convenience function to allow access to a given characteristic
* without enumerating over the list returned by {@link #getCharacteristics}
* manually.
*
* <p>If a remote service offers multiple characteristics with the same
* UUID, the first instance of a characteristic with the given UUID
* is returned.
*
* @return GATT characteristic object or null if no characteristic with the given UUID was
* found.
*/
fun getCharacteristic(uuid: UUID): BluetoothGattCharacteristic? {
return impl.getCharacteristic(uuid)
}
/**
* Add a included service to this service
*
* @param service The [BluetoothGattService] to be included
*/
fun addService(service: BluetoothGattService): Boolean {
return impl.addService(service)
}
/**
* Returns a [BluetoothGattService] with a given UUID out of the list of included
* services offered by this service.
*
* <p>If a remote service offers multiple [BluetoothGattService] with the same
* UUID, the first instance of a [BluetoothGattService] with the given UUID
* is returned.
*
* @return GATT [BluetoothGattService] object or null if no service with the given UUID
* was found.
*/
fun getIncludedService(uuid: UUID): BluetoothGattService? {
return impl.getIncludedService(uuid)
}
/**
* Create a [Bundle] from this object.
*/
override fun toBundle(): Bundle {
return impl.toBundle()
}
private interface GattServiceImpl {
val fwkService: FwkBluetoothGattService
val instanceId: Int
val type: Int
val uuid: UUID
val includedServices: List<BluetoothGattService>
val characteristics: List<BluetoothGattCharacteristic>
fun addCharacteristic(characteristic: BluetoothGattCharacteristic): Boolean
fun getCharacteristic(uuid: UUID): BluetoothGattCharacteristic?
fun addService(service: BluetoothGattService): Boolean
fun getIncludedService(uuid: UUID): BluetoothGattService?
fun toBundle(): Bundle
}
private open class GattServiceImplApi21(
final override val fwkService: FwkBluetoothGattService,
private val service: BluetoothGattService
) : GattServiceImpl {
companion object {
internal const val FIELD_FWK_SERVICE_INSTANCE_ID = 1
internal const val FIELD_FWK_SERVICE_TYPE = 2
internal const val FIELD_FWK_SERVICE_CHARACTERISTICS = 3
internal const val FIELD_FWK_SERVICE_SERVICES = 4
internal const val FIELD_FWK_SERVICE_UUID = 5
val CREATOR: Bundleable.Creator<BluetoothGattService> =
object : Bundleable.Creator<BluetoothGattService> {
@SuppressLint("SoonBlockedPrivateApi")
override fun fromBundle(bundle: Bundle): BluetoothGattService {
val uuid = bundle.getString(keyForField(FIELD_FWK_SERVICE_UUID))
?: throw IllegalArgumentException("Bundle doesn't include uuid")
val instanceId =
bundle.getInt(keyForField(FIELD_FWK_SERVICE_INSTANCE_ID), 0)
val type = bundle.getInt(keyForField(FIELD_FWK_SERVICE_TYPE), -1)
if (type == -1) {
throw IllegalArgumentException("Bundle doesn't include service type")
}
val fwkServiceWithoutInstanceId =
FwkBluetoothGattService(UUID.fromString(uuid), type)
val fwkService = fwkServiceWithoutInstanceId.runCatching {
this.javaClass.getDeclaredField("mInstanceId").let {
it.isAccessible = true
it.setInt(this, instanceId)
}
this
}.getOrDefault(fwkServiceWithoutInstanceId)
val gattService = BluetoothGattService(fwkService)
Utils.getParcelableArrayListFromBundle(
bundle,
keyForField(FIELD_FWK_SERVICE_CHARACTERISTICS),
Bundle::class.java
).forEach {
gattService.addCharacteristic(
BluetoothGattCharacteristic.CREATOR.fromBundle(
it
)
)
}
Utils.getParcelableArrayListFromBundle(
bundle,
keyForField(FIELD_FWK_SERVICE_SERVICES),
Bundle::class.java
).forEach {
val includedServices = Utils.getParcelableArrayListFromBundle(
it,
keyForField(FIELD_FWK_SERVICE_SERVICES),
Bundle::class.java
)
if (includedServices.isNotEmpty()) {
throw IllegalArgumentException(
"Included service shouldn't pass " +
"its included services to bundle"
)
}
val includedCharacteristics = Utils.getParcelableArrayListFromBundle(
it,
keyForField(FIELD_FWK_SERVICE_CHARACTERISTICS),
Bundle::class.java
)
if (includedCharacteristics.isNotEmpty()) {
throw IllegalArgumentException(
"Included service shouldn't pass characteristic to bundle"
)
}
gattService.addService(BluetoothGattService.CREATOR.fromBundle(it))
}
return gattService
}
}
}
override val instanceId: Int
get() = fwkService.instanceId
override val type: Int
get() = fwkService.type
override val uuid: UUID
get() = fwkService.uuid
private val _includedServices = mutableListOf<BluetoothGattService>()
override val includedServices: List<BluetoothGattService>
get() = _includedServices.toList()
private val _characteristics = mutableListOf<BluetoothGattCharacteristic>()
override val characteristics
get() = _characteristics.toList()
init {
this.fwkService.characteristics.forEach {
val characteristic = BluetoothGattCharacteristic(it)
_characteristics.add(characteristic)
characteristic.service = service
}
this.fwkService.includedServices.forEach {
_includedServices.add(BluetoothGattService(it))
}
}
override fun addCharacteristic(characteristic: BluetoothGattCharacteristic): Boolean {
return if (fwkService.addCharacteristic(characteristic.fwkCharacteristic)) {
_characteristics.add(characteristic)
characteristic.service = service
true
} else {
false
}
}
override fun getCharacteristic(uuid: UUID): BluetoothGattCharacteristic? {
return _characteristics.firstOrNull {
it.uuid == uuid
}
}
override fun addService(service: BluetoothGattService): Boolean {
return if (fwkService.addService(service.fwkService)) {
_includedServices.add(service)
true
} else {
false
}
}
override fun getIncludedService(uuid: UUID): BluetoothGattService? {
return _includedServices.firstOrNull {
it.uuid == uuid
}
}
override fun toBundle(): Bundle {
val bundle = Bundle()
bundle.putString(keyForField(FIELD_FWK_SERVICE_UUID), uuid.toString())
bundle.putInt(keyForField(FIELD_FWK_SERVICE_INSTANCE_ID), instanceId)
bundle.putInt(keyForField(FIELD_FWK_SERVICE_TYPE), type)
bundle.putParcelableArrayList(
keyForField(FIELD_FWK_SERVICE_CHARACTERISTICS),
ArrayList(_characteristics.map { it.toBundle() })
)
bundle.putParcelableArrayList(
keyForField(FIELD_FWK_SERVICE_SERVICES),
// Cut all included services & characteristics of included services. Developers
// should directly send the included services if need it
ArrayList(_includedServices.map {
BluetoothGattService(it.uuid, it.type).toBundle()
})
)
return bundle
}
}
@RequiresApi(Build.VERSION_CODES.N)
private class GattServiceImplApi24(
fwkService: FwkBluetoothGattService,
service: BluetoothGattService
) : GattServiceImplApi21(fwkService, service) {
companion object {
internal const val FIELD_FWK_SERVICE = 0
@Suppress("DEPRECATION")
val CREATOR: Bundleable.Creator<BluetoothGattService> =
object : Bundleable.Creator<BluetoothGattService> {
override fun fromBundle(bundle: Bundle): BluetoothGattService {
val fwkService =
Utils.getParcelableFromBundle(
bundle,
keyForField(FIELD_FWK_SERVICE),
FwkBluetoothGattService::class.java
)
?: throw IllegalArgumentException(
"Bundle doesn't contain framework service"
)
return BluetoothGattService(fwkService)
}
}
}
override fun toBundle(): Bundle {
val bundle = Bundle()
bundle.putParcelable(keyForField(FIELD_FWK_SERVICE), fwkService)
return bundle
}
}
}
|
apache-2.0
|
b4a47ff202d087df5abc0e5367584b50
| 35.612245 | 97 | 0.567556 | 5.888798 | false | false | false | false |
bsmr-java/lwjgl3
|
modules/templates/src/main/kotlin/org/lwjgl/opengles/templates/GLES20.kt
|
1
|
28048
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengles.templates
import org.lwjgl.generator.*
import org.lwjgl.opengles.*
import org.lwjgl.opengles.BufferType.*
val GLES20 = "GLES20".nativeClassGLES("GLES20", postfix = "") {
documentation =
"The core OpenGL ES 2.0 functionality."
IntConstant(
"",
"DEPTH_BUFFER_BIT"..0x00000100,
"STENCIL_BUFFER_BIT"..0x00000400,
"COLOR_BUFFER_BIT"..0x00004000,
"FALSE".."0",
"TRUE".."1",
"POINTS"..0x0000,
"LINES"..0x0001,
"LINE_LOOP"..0x0002,
"LINE_STRIP"..0x0003,
"TRIANGLES"..0x0004,
"TRIANGLE_STRIP"..0x0005,
"TRIANGLE_FAN"..0x0006,
"ZERO".."0",
"ONE".."1",
"SRC_COLOR"..0x0300,
"ONE_MINUS_SRC_COLOR"..0x0301,
"SRC_ALPHA"..0x0302,
"ONE_MINUS_SRC_ALPHA"..0x0303,
"DST_ALPHA"..0x0304,
"ONE_MINUS_DST_ALPHA"..0x0305,
"DST_COLOR"..0x0306,
"ONE_MINUS_DST_COLOR"..0x0307,
"SRC_ALPHA_SATURATE"..0x0308,
"FUNC_ADD"..0x8006,
"BLEND_EQUATION"..0x8009,
"BLEND_EQUATION_RGB"..0x8009,
"BLEND_EQUATION_ALPHA"..0x883D,
"FUNC_SUBTRACT"..0x800A,
"FUNC_REVERSE_SUBTRACT"..0x800B,
"BLEND_DST_RGB"..0x80C8,
"BLEND_SRC_RGB"..0x80C9,
"BLEND_DST_ALPHA"..0x80CA,
"BLEND_SRC_ALPHA"..0x80CB,
"CONSTANT_COLOR"..0x8001,
"ONE_MINUS_CONSTANT_COLOR"..0x8002,
"CONSTANT_ALPHA"..0x8003,
"ONE_MINUS_CONSTANT_ALPHA"..0x8004,
"BLEND_COLOR"..0x8005,
"ARRAY_BUFFER"..0x8892,
"ELEMENT_ARRAY_BUFFER"..0x8893,
"ARRAY_BUFFER_BINDING"..0x8894,
"ELEMENT_ARRAY_BUFFER_BINDING"..0x8895,
"STREAM_DRAW"..0x88E0,
"STATIC_DRAW"..0x88E4,
"DYNAMIC_DRAW"..0x88E8,
"BUFFER_SIZE"..0x8764,
"BUFFER_USAGE"..0x8765,
"CURRENT_VERTEX_ATTRIB"..0x8626,
"FRONT"..0x0404,
"BACK"..0x0405,
"FRONT_AND_BACK"..0x0408,
"TEXTURE_2D"..0x0DE1,
"CULL_FACE"..0x0B44,
"BLEND"..0x0BE2,
"DITHER"..0x0BD0,
"STENCIL_TEST"..0x0B90,
"DEPTH_TEST"..0x0B71,
"SCISSOR_TEST"..0x0C11,
"POLYGON_OFFSET_FILL"..0x8037,
"SAMPLE_ALPHA_TO_COVERAGE"..0x809E,
"SAMPLE_COVERAGE"..0x80A0,
"NO_ERROR".."0",
"INVALID_ENUM"..0x0500,
"INVALID_VALUE"..0x0501,
"INVALID_OPERATION"..0x0502,
"OUT_OF_MEMORY"..0x0505,
"CW"..0x0900,
"CCW"..0x0901,
"LINE_WIDTH"..0x0B21,
"ALIASED_POINT_SIZE_RANGE"..0x846D,
"ALIASED_LINE_WIDTH_RANGE"..0x846E,
"CULL_FACE_MODE"..0x0B45,
"FRONT_FACE"..0x0B46,
"DEPTH_RANGE"..0x0B70,
"DEPTH_WRITEMASK"..0x0B72,
"DEPTH_CLEAR_VALUE"..0x0B73,
"DEPTH_FUNC"..0x0B74,
"STENCIL_CLEAR_VALUE"..0x0B91,
"STENCIL_FUNC"..0x0B92,
"STENCIL_FAIL"..0x0B94,
"STENCIL_PASS_DEPTH_FAIL"..0x0B95,
"STENCIL_PASS_DEPTH_PASS"..0x0B96,
"STENCIL_REF"..0x0B97,
"STENCIL_VALUE_MASK"..0x0B93,
"STENCIL_WRITEMASK"..0x0B98,
"STENCIL_BACK_FUNC"..0x8800,
"STENCIL_BACK_FAIL"..0x8801,
"STENCIL_BACK_PASS_DEPTH_FAIL"..0x8802,
"STENCIL_BACK_PASS_DEPTH_PASS"..0x8803,
"STENCIL_BACK_REF"..0x8CA3,
"STENCIL_BACK_VALUE_MASK"..0x8CA4,
"STENCIL_BACK_WRITEMASK"..0x8CA5,
"VIEWPORT"..0x0BA2,
"SCISSOR_BOX"..0x0C10,
"COLOR_CLEAR_VALUE"..0x0C22,
"COLOR_WRITEMASK"..0x0C23,
"UNPACK_ALIGNMENT"..0x0CF5,
"PACK_ALIGNMENT"..0x0D05,
"MAX_TEXTURE_SIZE"..0x0D33,
"MAX_VIEWPORT_DIMS"..0x0D3A,
"SUBPIXEL_BITS"..0x0D50,
"RED_BITS"..0x0D52,
"GREEN_BITS"..0x0D53,
"BLUE_BITS"..0x0D54,
"ALPHA_BITS"..0x0D55,
"DEPTH_BITS"..0x0D56,
"STENCIL_BITS"..0x0D57,
"POLYGON_OFFSET_UNITS"..0x2A00,
"POLYGON_OFFSET_FACTOR"..0x8038,
"TEXTURE_BINDING_2D"..0x8069,
"SAMPLE_BUFFERS"..0x80A8,
"SAMPLES"..0x80A9,
"SAMPLE_COVERAGE_VALUE"..0x80AA,
"SAMPLE_COVERAGE_INVERT"..0x80AB,
"NUM_COMPRESSED_TEXTURE_FORMATS"..0x86A2,
"COMPRESSED_TEXTURE_FORMATS"..0x86A3,
"DONT_CARE"..0x1100,
"FASTEST"..0x1101,
"NICEST"..0x1102,
"GENERATE_MIPMAP_HINT"..0x8192,
"BYTE"..0x1400,
"UNSIGNED_BYTE"..0x1401,
"SHORT"..0x1402,
"UNSIGNED_SHORT"..0x1403,
"INT"..0x1404,
"UNSIGNED_INT"..0x1405,
"FLOAT"..0x1406,
"FIXED"..0x140C,
"DEPTH_COMPONENT"..0x1902,
"ALPHA"..0x1906,
"RGB"..0x1907,
"RGBA"..0x1908,
"LUMINANCE"..0x1909,
"LUMINANCE_ALPHA"..0x190A,
"UNSIGNED_SHORT_4_4_4_4"..0x8033,
"UNSIGNED_SHORT_5_5_5_1"..0x8034,
"UNSIGNED_SHORT_5_6_5"..0x8363,
"FRAGMENT_SHADER"..0x8B30,
"VERTEX_SHADER"..0x8B31,
"MAX_VERTEX_ATTRIBS"..0x8869,
"MAX_VERTEX_UNIFORM_VECTORS"..0x8DFB,
"MAX_VARYING_VECTORS"..0x8DFC,
"MAX_COMBINED_TEXTURE_IMAGE_UNITS"..0x8B4D,
"MAX_VERTEX_TEXTURE_IMAGE_UNITS"..0x8B4C,
"MAX_TEXTURE_IMAGE_UNITS"..0x8872,
"MAX_FRAGMENT_UNIFORM_VECTORS"..0x8DFD,
"SHADER_TYPE"..0x8B4F,
"DELETE_STATUS"..0x8B80,
"LINK_STATUS"..0x8B82,
"VALIDATE_STATUS"..0x8B83,
"ATTACHED_SHADERS"..0x8B85,
"ACTIVE_UNIFORMS"..0x8B86,
"ACTIVE_UNIFORM_MAX_LENGTH"..0x8B87,
"ACTIVE_ATTRIBUTES"..0x8B89,
"ACTIVE_ATTRIBUTE_MAX_LENGTH"..0x8B8A,
"SHADING_LANGUAGE_VERSION"..0x8B8C,
"CURRENT_PROGRAM"..0x8B8D,
"NEVER"..0x0200,
"LESS"..0x0201,
"EQUAL"..0x0202,
"LEQUAL"..0x0203,
"GREATER"..0x0204,
"NOTEQUAL"..0x0205,
"GEQUAL"..0x0206,
"ALWAYS"..0x0207,
"KEEP"..0x1E00,
"REPLACE"..0x1E01,
"INCR"..0x1E02,
"DECR"..0x1E03,
"INVERT"..0x150A,
"INCR_WRAP"..0x8507,
"DECR_WRAP"..0x8508,
"VENDOR"..0x1F00,
"RENDERER"..0x1F01,
"VERSION"..0x1F02,
"EXTENSIONS"..0x1F03,
"NEAREST"..0x2600,
"LINEAR"..0x2601,
"NEAREST_MIPMAP_NEAREST"..0x2700,
"LINEAR_MIPMAP_NEAREST"..0x2701,
"NEAREST_MIPMAP_LINEAR"..0x2702,
"LINEAR_MIPMAP_LINEAR"..0x2703,
"TEXTURE_MAG_FILTER"..0x2800,
"TEXTURE_MIN_FILTER"..0x2801,
"TEXTURE_WRAP_S"..0x2802,
"TEXTURE_WRAP_T"..0x2803,
"TEXTURE"..0x1702,
"TEXTURE_CUBE_MAP"..0x8513,
"TEXTURE_BINDING_CUBE_MAP"..0x8514,
"TEXTURE_CUBE_MAP_POSITIVE_X"..0x8515,
"TEXTURE_CUBE_MAP_NEGATIVE_X"..0x8516,
"TEXTURE_CUBE_MAP_POSITIVE_Y"..0x8517,
"TEXTURE_CUBE_MAP_NEGATIVE_Y"..0x8518,
"TEXTURE_CUBE_MAP_POSITIVE_Z"..0x8519,
"TEXTURE_CUBE_MAP_NEGATIVE_Z"..0x851A,
"MAX_CUBE_MAP_TEXTURE_SIZE"..0x851C,
"TEXTURE0"..0x84C0,
"TEXTURE1"..0x84C1,
"TEXTURE2"..0x84C2,
"TEXTURE3"..0x84C3,
"TEXTURE4"..0x84C4,
"TEXTURE5"..0x84C5,
"TEXTURE6"..0x84C6,
"TEXTURE7"..0x84C7,
"TEXTURE8"..0x84C8,
"TEXTURE9"..0x84C9,
"TEXTURE10"..0x84CA,
"TEXTURE11"..0x84CB,
"TEXTURE12"..0x84CC,
"TEXTURE13"..0x84CD,
"TEXTURE14"..0x84CE,
"TEXTURE15"..0x84CF,
"TEXTURE16"..0x84D0,
"TEXTURE17"..0x84D1,
"TEXTURE18"..0x84D2,
"TEXTURE19"..0x84D3,
"TEXTURE20"..0x84D4,
"TEXTURE21"..0x84D5,
"TEXTURE22"..0x84D6,
"TEXTURE23"..0x84D7,
"TEXTURE24"..0x84D8,
"TEXTURE25"..0x84D9,
"TEXTURE26"..0x84DA,
"TEXTURE27"..0x84DB,
"TEXTURE28"..0x84DC,
"TEXTURE29"..0x84DD,
"TEXTURE30"..0x84DE,
"TEXTURE31"..0x84DF,
"ACTIVE_TEXTURE"..0x84E0,
"REPEAT"..0x2901,
"CLAMP_TO_EDGE"..0x812F,
"MIRRORED_REPEAT"..0x8370,
"FLOAT_VEC2"..0x8B50,
"FLOAT_VEC3"..0x8B51,
"FLOAT_VEC4"..0x8B52,
"INT_VEC2"..0x8B53,
"INT_VEC3"..0x8B54,
"INT_VEC4"..0x8B55,
"BOOL"..0x8B56,
"BOOL_VEC2"..0x8B57,
"BOOL_VEC3"..0x8B58,
"BOOL_VEC4"..0x8B59,
"FLOAT_MAT2"..0x8B5A,
"FLOAT_MAT3"..0x8B5B,
"FLOAT_MAT4"..0x8B5C,
"SAMPLER_2D"..0x8B5E,
"SAMPLER_CUBE"..0x8B60,
"VERTEX_ATTRIB_ARRAY_ENABLED"..0x8622,
"VERTEX_ATTRIB_ARRAY_SIZE"..0x8623,
"VERTEX_ATTRIB_ARRAY_STRIDE"..0x8624,
"VERTEX_ATTRIB_ARRAY_TYPE"..0x8625,
"VERTEX_ATTRIB_ARRAY_NORMALIZED"..0x886A,
"VERTEX_ATTRIB_ARRAY_POINTER"..0x8645,
"VERTEX_ATTRIB_ARRAY_BUFFER_BINDING"..0x889F,
"IMPLEMENTATION_COLOR_READ_TYPE"..0x8B9A,
"IMPLEMENTATION_COLOR_READ_FORMAT"..0x8B9B,
"COMPILE_STATUS"..0x8B81,
"INFO_LOG_LENGTH"..0x8B84,
"SHADER_SOURCE_LENGTH"..0x8B88,
"SHADER_COMPILER"..0x8DFA,
"SHADER_BINARY_FORMATS"..0x8DF8,
"NUM_SHADER_BINARY_FORMATS"..0x8DF9,
"LOW_FLOAT"..0x8DF0,
"MEDIUM_FLOAT"..0x8DF1,
"HIGH_FLOAT"..0x8DF2,
"LOW_INT"..0x8DF3,
"MEDIUM_INT"..0x8DF4,
"HIGH_INT"..0x8DF5,
"FRAMEBUFFER"..0x8D40,
"RENDERBUFFER"..0x8D41,
"RGBA4"..0x8056,
"RGB5_A1"..0x8057,
"RGB565"..0x8D62,
"DEPTH_COMPONENT16"..0x81A5,
"STENCIL_INDEX8"..0x8D48,
"RENDERBUFFER_WIDTH"..0x8D42,
"RENDERBUFFER_HEIGHT"..0x8D43,
"RENDERBUFFER_INTERNAL_FORMAT"..0x8D44,
"RENDERBUFFER_RED_SIZE"..0x8D50,
"RENDERBUFFER_GREEN_SIZE"..0x8D51,
"RENDERBUFFER_BLUE_SIZE"..0x8D52,
"RENDERBUFFER_ALPHA_SIZE"..0x8D53,
"RENDERBUFFER_DEPTH_SIZE"..0x8D54,
"RENDERBUFFER_STENCIL_SIZE"..0x8D55,
"FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE"..0x8CD0,
"FRAMEBUFFER_ATTACHMENT_OBJECT_NAME"..0x8CD1,
"FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL"..0x8CD2,
"FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE"..0x8CD3,
"COLOR_ATTACHMENT0"..0x8CE0,
"DEPTH_ATTACHMENT"..0x8D00,
"STENCIL_ATTACHMENT"..0x8D20,
"NONE".."0",
"FRAMEBUFFER_COMPLETE"..0x8CD5,
"FRAMEBUFFER_INCOMPLETE_ATTACHMENT"..0x8CD6,
"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"..0x8CD7,
"FRAMEBUFFER_INCOMPLETE_DIMENSIONS"..0x8CD9,
"FRAMEBUFFER_UNSUPPORTED"..0x8CDD,
"FRAMEBUFFER_BINDING"..0x8CA6,
"RENDERBUFFER_BINDING"..0x8CA7,
"MAX_RENDERBUFFER_SIZE"..0x84E8,
"INVALID_FRAMEBUFFER_OPERATION"..0x0506
)
void(
"ActiveTexture",
"",
GLenum.IN("texture", "")
)
void(
"AttachShader",
"",
GLuint.IN("program", ""),
GLuint.IN("shader", "")
)
void(
"BindAttribLocation",
"",
GLuint.IN("program", ""),
GLuint.IN("index", ""),
const..GLcharASCII_p.IN("name", "")
)
void(
"BindBuffer",
"",
GLenum.IN("target", ""),
GLuint.IN("buffer", "")
)
void(
"BindFramebuffer",
"",
GLenum.IN("target", ""),
GLuint.IN("framebuffer", "")
)
void(
"BindRenderbuffer",
"",
GLenum.IN("target", ""),
GLuint.IN("renderbuffer", "")
)
void(
"BindTexture",
"",
GLenum.IN("target", ""),
GLuint.IN("texture", "")
)
void(
"BlendColor",
"",
GLfloat.IN("red", ""),
GLfloat.IN("green", ""),
GLfloat.IN("blue", ""),
GLfloat.IN("alpha", "")
)
void(
"BlendEquation",
"",
GLenum.IN("mode", "")
)
void(
"BlendEquationSeparate",
"",
GLenum.IN("modeRGB", ""),
GLenum.IN("modeAlpha", "")
)
void(
"BlendFunc",
"",
GLenum.IN("sfactor", ""),
GLenum.IN("dfactor", "")
)
void(
"BlendFuncSeparate",
"",
GLenum.IN("sfactorRGB", ""),
GLenum.IN("dfactorRGB", ""),
GLenum.IN("sfactorAlpha", ""),
GLenum.IN("dfactorAlpha", "")
)
void(
"BufferData",
"",
GLenum.IN("target", ""),
AutoSize("data")..GLsizeiptr.IN("size", ""),
optional..MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT
)..const..void_p.IN("data", ""),
GLenum.IN("usage", "")
)
void(
"BufferSubData",
"",
GLenum.IN("target", ""),
GLintptr.IN("offset", ""),
AutoSize("data")..GLsizeiptr.IN("size", ""),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT
)..const..void_p.IN("data", "")
)
GLenum(
"CheckFramebufferStatus",
"",
GLenum.IN("target", "")
)
void(
"Clear",
"",
GLbitfield.IN("mask", "")
)
void(
"ClearColor",
"",
GLfloat.IN("red", ""),
GLfloat.IN("green", ""),
GLfloat.IN("blue", ""),
GLfloat.IN("alpha", "")
)
void(
"ClearDepthf",
"",
GLfloat.IN("d", "")
)
void(
"ClearStencil",
"",
GLint.IN("s", "")
)
void(
"ColorMask",
"",
GLboolean.IN("red", ""),
GLboolean.IN("green", ""),
GLboolean.IN("blue", ""),
GLboolean.IN("alpha", "")
)
void(
"CompileShader",
"",
GLuint.IN("shader", "")
)
void(
"CompressedTexImage2D",
"",
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLint.IN("border", ""),
AutoSize("data")..GLsizei.IN("imageSize", ""),
PIXEL_UNPACK_BUFFER..nullable..const..void_p.IN("data", "")
)
void(
"CompressedTexSubImage2D",
"",
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLint.IN("yoffset", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLenum.IN("format", ""),
AutoSize("data")..GLsizei.IN("imageSize", ""),
PIXEL_UNPACK_BUFFER..const..void_p.IN("data", "")
)
void(
"CopyTexImage2D",
"",
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("internalformat", ""),
GLint.IN("x", ""),
GLint.IN("y", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLint.IN("border", "")
)
void(
"CopyTexSubImage2D",
"",
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLint.IN("yoffset", ""),
GLint.IN("x", ""),
GLint.IN("y", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", "")
)
GLuint(
"CreateProgram",
""
)
GLuint(
"CreateShader",
"",
GLenum.IN("type", "")
)
void(
"CullFace",
"",
GLenum.IN("mode", "")
)
void(
"DeleteBuffers",
"",
AutoSize("buffers")..GLsizei.IN("n", ""),
SingleValue("buffer")..const..GLuint_p.IN("buffers", "")
)
void(
"DeleteFramebuffers",
"",
AutoSize("framebuffers")..GLsizei.IN("n", ""),
SingleValue("framebuffer")..const..GLuint_p.IN("framebuffers", "")
)
void(
"DeleteProgram",
"",
GLuint.IN("program", "")
)
void(
"DeleteRenderbuffers",
"",
AutoSize("renderbuffers")..GLsizei.IN("n", ""),
SingleValue("renderbuffer")..const..GLuint_p.IN("renderbuffers", "")
)
void(
"DeleteShader",
"",
GLuint.IN("shader", "")
)
void(
"DeleteTextures",
"",
AutoSize("textures")..GLsizei.IN("n", ""),
SingleValue("texture")..const..GLuint_p.IN("textures", "")
)
void(
"DepthFunc",
"",
GLenum.IN("func", "")
)
void(
"DepthMask",
"",
GLboolean.IN("flag", "")
)
void(
"DepthRangef",
"",
GLfloat.IN("n", ""),
GLfloat.IN("f", "")
)
void(
"DetachShader",
"",
GLuint.IN("program", ""),
GLuint.IN("shader", "")
)
void(
"Disable",
"",
GLenum.IN("cap", "")
)
void(
"DisableVertexAttribArray",
"",
GLuint.IN("index", "")
)
void(
"DrawArrays",
"",
GLenum.IN("mode", ""),
GLint.IN("first", ""),
GLsizei.IN("count", "")
)
void(
"DrawElements",
"",
GLenum.IN("mode", ""),
AutoSizeShr("GLESChecks.typeToByteShift(type)", "indices")..GLsizei.IN("count", ""),
AutoType("indices", GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT, GL_UNSIGNED_INT)..GLenum.IN("type", ""),
ELEMENT_ARRAY_BUFFER..const..void_p.IN("indices", "")
)
void(
"Enable",
"",
GLenum.IN("cap", "")
)
void(
"EnableVertexAttribArray",
"",
GLuint.IN("index", "")
)
void(
"Finish",
""
)
void(
"Flush",
""
)
void(
"FramebufferRenderbuffer",
"",
GLenum.IN("target", ""),
GLenum.IN("attachment", ""),
GLenum.IN("renderbuffertarget", ""),
GLuint.IN("renderbuffer", "")
)
void(
"FramebufferTexture2D",
"",
GLenum.IN("target", ""),
GLenum.IN("attachment", ""),
GLenum.IN("textarget", ""),
GLuint.IN("texture", ""),
GLint.IN("level", "")
)
void(
"FrontFace",
"",
GLenum.IN("mode", "")
)
void(
"GenBuffers",
"",
AutoSize("buffers")..GLsizei.IN("n", ""),
ReturnParam..GLuint_p.OUT("buffers", "")
)
void(
"GenerateMipmap",
"",
GLenum.IN("target", "")
)
void(
"GenFramebuffers",
"",
AutoSize("framebuffers")..GLsizei.IN("n", ""),
ReturnParam..GLuint_p.OUT("framebuffers", "")
)
void(
"GenRenderbuffers",
"",
AutoSize("renderbuffers")..GLsizei.IN("n", ""),
ReturnParam..GLuint_p.OUT("renderbuffers", "")
)
void(
"GenTextures",
"",
AutoSize("textures")..GLsizei.IN("n", ""),
ReturnParam..GLuint_p.OUT("textures", "")
)
void(
"GetActiveAttrib",
"",
GLuint.IN("program", ""),
GLuint.IN("index", ""),
AutoSize("name")..GLsizei.IN("bufSize", ""),
Check(1)..nullable..GLsizei_p.OUT("length", ""),
Check(1)..GLint_p.OUT("size", ""),
Check(1)..GLenum_p.OUT("type", ""),
Return(
"length",
"glGetProgrami(program, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH)"
)..GLcharASCII_p.OUT("name", "")
)
void(
"GetActiveUniform",
"",
GLuint.IN("program", ""),
GLuint.IN("index", ""),
AutoSize("name")..GLsizei.IN("bufSize", ""),
Check(1)..nullable..GLsizei_p.OUT("length", ""),
Check(1)..GLint_p.OUT("size", ""),
Check(1)..GLenum_p.OUT("type", ""),
Return(
"length",
"glGetProgrami(program, GL_ACTIVE_UNIFORM_MAX_LENGTH)"
)..GLcharASCII_p.OUT("name", "")
)
void(
"GetAttachedShaders",
"",
GLuint.IN("program", ""),
AutoSize("shaders")..GLsizei.IN("maxCount", ""),
Check(1)..nullable..GLsizei_p.OUT("count", ""),
GLuint_p.OUT("shaders", "")
)
GLint(
"GetAttribLocation",
"",
GLuint.IN("program", ""),
const..GLcharASCII_p.IN("name", "")
)
void(
"GetBooleanv",
"",
GLenum.IN("pname", ""),
ReturnParam..Check(1)..GLboolean_p.OUT("data", "")
)
void(
"GetBufferParameteriv",
"",
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
ReturnParam..Check(1)..GLint_p.OUT("params", "")
)
GLenum(
"GetError",
""
)
void(
"GetFloatv",
"",
GLenum.IN("pname", ""),
ReturnParam..Check(1)..GLfloat_p.OUT("data", "")
)
void(
"GetFramebufferAttachmentParameteriv",
"",
GLenum.IN("target", ""),
GLenum.IN("attachment", ""),
GLenum.IN("pname", ""),
ReturnParam..Check(1)..GLint_p.OUT("params", "")
)
void(
"GetIntegerv",
"",
GLenum.IN("pname", ""),
ReturnParam..Check(1)..GLint_p.OUT("data", "")
)
void(
"GetProgramiv",
"",
GLuint.IN("program", ""),
GLenum.IN("pname", ""),
ReturnParam..Check(1)..GLint_p.OUT("params", "")
)
void(
"GetProgramInfoLog",
"",
GLuint.IN("program", ""),
AutoSize("infoLog")..GLsizei.IN("bufSize", ""),
Check(1)..nullable..GLsizei_p.OUT("length", ""),
Return(
"length",
"glGetProgrami(program, GL_INFO_LOG_LENGTH)",
heapAllocate = true
)..GLcharUTF8_p.OUT("infoLog", "")
)
void(
"GetRenderbufferParameteriv",
"",
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
ReturnParam..Check(1)..GLint_p.OUT("params", "")
)
void(
"GetShaderiv",
"",
GLuint.IN("shader", ""),
GLenum.IN("pname", ""),
ReturnParam..Check(1)..GLint_p.OUT("params", "")
)
void(
"GetShaderInfoLog",
"",
GLuint.IN("shader", ""),
AutoSize("infoLog")..GLsizei.IN("bufSize", ""),
Check(1)..nullable..GLsizei_p.OUT("length", ""),
Return(
"length",
"glGetShaderi(shader, GL_INFO_LOG_LENGTH)",
heapAllocate = true
)..GLcharUTF8_p.OUT("infoLog", "")
)
void(
"GetShaderPrecisionFormat",
"",
GLenum.IN("shadertype", ""),
GLenum.IN("precisiontype", ""),
Check(2)..GLint_p.OUT("range", ""),
Check(2)..GLint_p.OUT("precision", "")
)
void(
"GetShaderSource",
"",
GLuint.IN("shader", ""),
AutoSize("source")..GLsizei.IN("bufSize", ""),
Check(1)..nullable..GLsizei_p.OUT("length", ""),
Return("length", "glGetShaderi(shader, GL_SHADER_SOURCE_LENGTH)", heapAllocate = true)..GLcharUTF8_p.OUT("source", "")
)
GLubyteString(
"GetString",
"",
GLenum.IN("name", "")
)
void(
"GetTexParameterfv",
"",
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
ReturnParam..Check(1)..GLfloat_p.OUT("params", "")
)
void(
"GetTexParameteriv",
"",
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
ReturnParam..Check(1)..GLint_p.OUT("params", "")
)
void(
"GetUniformfv",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
ReturnParam..Check(1)..GLfloat_p.OUT("params", "")
)
void(
"GetUniformiv",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
ReturnParam..Check(1)..GLint_p.OUT("params", "")
)
GLint(
"GetUniformLocation",
"",
GLuint.IN("program", ""),
const..GLcharASCII_p.IN("name", "")
)
void(
"GetVertexAttribfv",
"",
GLuint.IN("index", ""),
GLenum.IN("pname", ""),
Check(4)..GLfloat_p.OUT("params", "")
)
void(
"GetVertexAttribiv",
"",
GLuint.IN("index", ""),
GLenum.IN("pname", ""),
Check(4)..GLint_p.OUT("params", "")
)
void(
"GetVertexAttribPointerv",
"",
GLuint.IN("index", ""),
GLenum.IN("pname", ""),
ReturnParam..Check(1)..void_pp.OUT("pointer", "")
)
void(
"Hint",
"",
GLenum.IN("target", ""),
GLenum.IN("mode", "")
)
GLboolean(
"IsBuffer",
"",
GLuint.IN("buffer", "")
)
GLboolean(
"IsEnabled",
"",
GLenum.IN("cap", "")
)
GLboolean(
"IsFramebuffer",
"",
GLuint.IN("framebuffer", "")
)
GLboolean(
"IsProgram",
"",
GLuint.IN("program", "")
)
GLboolean(
"IsRenderbuffer",
"",
GLuint.IN("renderbuffer", "")
)
GLboolean(
"IsShader",
"",
GLuint.IN("shader", "")
)
GLboolean(
"IsTexture",
"",
GLuint.IN("texture", "")
)
void(
"LineWidth",
"",
GLfloat.IN("width", "")
)
void(
"LinkProgram",
"",
GLuint.IN("program", "")
)
void(
"PixelStorei",
"",
GLenum.IN("pname", ""),
GLint.IN("param", "")
)
void(
"PolygonOffset",
"",
GLfloat.IN("factor", ""),
GLfloat.IN("units", "")
)
void(
"ReadPixels",
"",
GLint.IN("x", ""),
GLint.IN("y", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLenum.IN("format", ""),
GLenum.IN("type", ""),
PIXEL_PACK_BUFFER..MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT
)..void_p.OUT("pixels", "")
)
void(
"ReleaseShaderCompiler",
""
)
void(
"RenderbufferStorage",
"",
GLenum.IN("target", ""),
GLenum.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", "")
)
void(
"SampleCoverage",
"",
GLfloat.IN("value", ""),
GLboolean.IN("invert", "")
)
void(
"Scissor",
"",
GLint.IN("x", ""),
GLint.IN("y", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", "")
)
void(
"ShaderBinary",
"",
AutoSize("shaders")..GLsizei.IN("count", ""),
const..GLuint_p.IN("shaders", ""),
GLenum.IN("binaryformat", ""),
const..void_p.IN("binary", ""),
AutoSize("binary")..GLsizei.IN("length", "")
)
void(
"ShaderSource",
"",
GLuint.IN("shader", ""),
AutoSize("string", "length")..GLsizei.IN("count", ""),
PointerArray(GLcharUTF8_p, "string", "length")..const..GLcharUTF8_p_const_p.IN("string", ""),
nullable..const..GLint_p.IN("length", "")
)
void(
"StencilFunc",
"",
GLenum.IN("func", ""),
GLint.IN("ref", ""),
GLuint.IN("mask", "")
)
void(
"StencilFuncSeparate",
"",
GLenum.IN("face", ""),
GLenum.IN("func", ""),
GLint.IN("ref", ""),
GLuint.IN("mask", "")
)
void(
"StencilMask",
"",
GLuint.IN("mask", "")
)
void(
"StencilMaskSeparate",
"",
GLenum.IN("face", ""),
GLuint.IN("mask", "")
)
void(
"StencilOp",
"",
GLenum.IN("fail", ""),
GLenum.IN("zfail", ""),
GLenum.IN("zpass", "")
)
void(
"StencilOpSeparate",
"",
GLenum.IN("face", ""),
GLenum.IN("sfail", ""),
GLenum.IN("dpfail", ""),
GLenum.IN("dppass", "")
)
void(
"TexImage2D",
"",
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLint.IN("border", ""),
GLenum.IN("format", ""),
GLenum.IN("type", ""),
PIXEL_UNPACK_BUFFER..MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT
)..nullable..const..void_p.IN("pixels", "")
)
void(
"TexParameterf",
"",
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
GLfloat.IN("param", "")
)
void(
"TexParameterfv",
"",
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(1)..const..GLfloat_p.IN("params", "")
)
void(
"TexParameteri",
"",
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
GLint.IN("param", "")
)
void(
"TexParameteriv",
"",
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(1)..const..GLint_p.IN("params", "")
)
void(
"TexSubImage2D",
"",
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLint.IN("yoffset", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLenum.IN("format", ""),
GLenum.IN("type", ""),
PIXEL_UNPACK_BUFFER..MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT
)..const..void_p.IN("pixels", "")
)
void(
"Uniform1f",
"",
GLint.IN("location", ""),
GLfloat.IN("v0", "")
)
void(
"Uniform1fv",
"",
GLint.IN("location", ""),
AutoSize("value")..GLsizei.IN("count", ""),
const..GLfloat_p.IN("value", "")
)
void(
"Uniform1i",
"",
GLint.IN("location", ""),
GLint.IN("v0", "")
)
void(
"Uniform1iv",
"",
GLint.IN("location", ""),
AutoSize("value")..GLsizei.IN("count", ""),
const..GLint_p.IN("value", "")
)
void(
"Uniform2f",
"",
GLint.IN("location", ""),
GLfloat.IN("v0", ""),
GLfloat.IN("v1", "")
)
void(
"Uniform2fv",
"",
GLint.IN("location", ""),
AutoSize(2, "value")..GLsizei.IN("count", ""),
const..GLfloat_p.IN("value", "")
)
void(
"Uniform2i",
"",
GLint.IN("location", ""),
GLint.IN("v0", ""),
GLint.IN("v1", "")
)
void(
"Uniform2iv",
"",
GLint.IN("location", ""),
AutoSize(2, "value")..GLsizei.IN("count", ""),
const..GLint_p.IN("value", "")
)
void(
"Uniform3f",
"",
GLint.IN("location", ""),
GLfloat.IN("v0", ""),
GLfloat.IN("v1", ""),
GLfloat.IN("v2", "")
)
void(
"Uniform3fv",
"",
GLint.IN("location", ""),
AutoSize(3, "value")..GLsizei.IN("count", ""),
const..GLfloat_p.IN("value", "")
)
void(
"Uniform3i",
"",
GLint.IN("location", ""),
GLint.IN("v0", ""),
GLint.IN("v1", ""),
GLint.IN("v2", "")
)
void(
"Uniform3iv",
"",
GLint.IN("location", ""),
AutoSize(3, "value")..GLsizei.IN("count", ""),
const..GLint_p.IN("value", "")
)
void(
"Uniform4f",
"",
GLint.IN("location", ""),
GLfloat.IN("v0", ""),
GLfloat.IN("v1", ""),
GLfloat.IN("v2", ""),
GLfloat.IN("v3", "")
)
void(
"Uniform4fv",
"",
GLint.IN("location", ""),
AutoSize(4, "value")..GLsizei.IN("count", ""),
const..GLfloat_p.IN("value", "")
)
void(
"Uniform4i",
"",
GLint.IN("location", ""),
GLint.IN("v0", ""),
GLint.IN("v1", ""),
GLint.IN("v2", ""),
GLint.IN("v3", "")
)
void(
"Uniform4iv",
"",
GLint.IN("location", ""),
AutoSize(4, "value")..GLsizei.IN("count", ""),
const..GLint_p.IN("value", "")
)
void(
"UniformMatrix2fv",
"",
GLint.IN("location", ""),
AutoSize(2 x 2, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("value", "")
)
void(
"UniformMatrix3fv",
"",
GLint.IN("location", ""),
AutoSize(3 x 3, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("value", "")
)
void(
"UniformMatrix4fv",
"",
GLint.IN("location", ""),
AutoSize(4 x 4, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("value", "")
)
void(
"UseProgram",
"",
GLuint.IN("program", "")
)
void(
"ValidateProgram",
"",
GLuint.IN("program", "")
)
void(
"VertexAttrib1f",
"",
GLuint.IN("index", ""),
GLfloat.IN("x", "")
)
void(
"VertexAttrib1fv",
"",
GLuint.IN("index", ""),
Check(1)..const..GLfloat_p.IN("v", "")
)
void(
"VertexAttrib2f",
"",
GLuint.IN("index", ""),
GLfloat.IN("x", ""),
GLfloat.IN("y", "")
)
void(
"VertexAttrib2fv",
"",
GLuint.IN("index", ""),
Check(2)..const..GLfloat_p.IN("v", "")
)
void(
"VertexAttrib3f",
"",
GLuint.IN("index", ""),
GLfloat.IN("x", ""),
GLfloat.IN("y", ""),
GLfloat.IN("z", "")
)
void(
"VertexAttrib3fv",
"",
GLuint.IN("index", ""),
Check(3)..const..GLfloat_p.IN("v", "")
)
void(
"VertexAttrib4f",
"",
GLuint.IN("index", ""),
GLfloat.IN("x", ""),
GLfloat.IN("y", ""),
GLfloat.IN("z", ""),
GLfloat.IN("w", "")
)
void(
"VertexAttrib4fv",
"",
GLuint.IN("index", ""),
Check(4)..const..GLfloat_p.IN("v", "")
)
void(
"VertexAttribPointer",
"",
GLuint.IN("index", ""),
GLint.IN("size", ""),
GLenum.IN("type", ""),
GLboolean.IN("normalized", ""),
GLsizei.IN("stride", ""),
ARRAY_BUFFER..MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT
)..const..void_p.IN("pointer", "")
)
void(
"Viewport",
"",
GLint.IN("x", ""),
GLint.IN("y", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", "")
)
}
|
bsd-3-clause
|
01f58597b90203adeed8c72d3fa8938a
| 16.574561 | 120 | 0.582252 | 2.542422 | false | false | false | false |
bsmr-java/lwjgl3
|
modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/ARB_gpu_shader_int64.kt
|
1
|
6280
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl.templates
import org.lwjgl.generator.*
import org.lwjgl.opengl.*
val ARB_gpu_shader_int64 = "ARBGPUShaderInt64".nativeClassGL("ARB_gpu_shader_int64") {
documentation =
"""
Native bindings to the $registryLink extension.
The extension introduces the following features for all shader types:
${ul(
"""
support for 64-bit scalar and vector integer data types, including uniform API, uniform buffer object, transform feedback, and shader input and
output support;
""",
"new built-in functions to pack and unpack 64-bit integer types into a two-component 32-bit integer vector;",
"new built-in functions to convert double-precision floating-point values to or from their 64-bit integer bit encodings;",
"vector relational functions supporting comparisons of vectors of 64-bit integer types; and",
"common functions abs, sign, min, max, clamp, and mix supporting arguments of 64-bit integer types."
)}
Requires ${GL40.link} and GLSL 4.00.
"""
IntConstant(
"Returned by the {@code type} parameter of GetActiveAttrib, GetActiveUniform, and GetTransformFeedbackVarying.",
"INT64_ARB"..0x140E,
"UNSIGNED_INT64_ARB"..0x140F,
"INT64_VEC2_ARB"..0x8FE9,
"INT64_VEC3_ARB"..0x8FEA,
"INT64_VEC4_ARB"..0x8FEB,
"UNSIGNED_INT64_VEC2_ARB"..0x8FF5,
"UNSIGNED_INT64_VEC3_ARB"..0x8FF6,
"UNSIGNED_INT64_VEC4_ARB"..0x8FF7
)
var args = arrayOf(
GLuint.IN("program", "the program object"),
GLint.IN("location", "the location of the uniform variable to be modified"),
GLint64.IN("x", "the uniform x value"),
GLint64.IN("y", "the uniform y value"),
GLint64.IN("z", "the uniform z value"),
GLint64.IN("w", "the uniform w value")
)
val autoSizes = arrayOf(
AutoSize(1, "value"),
AutoSize(2, "value"),
AutoSize(3, "value"),
AutoSize(4, "value")
)
val autoSizeDoc = "the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array."
for (i in 1..4) {
val glslType = if ( i == 1) "int64_t" else "i64vec$i"
val valueDoc = "a pointer to an array of {@code count} values that will be used to update the specified $glslType variable"
// Uniform{1,2,3,4}i64ARB
void(
"Uniform${i}i64ARB",
"Specifies the value of an $glslType uniform variable for the current program object.",
*args.copyOfRange(1, 2 + i)
)
// Uniform{1,2,3,4}i64vARB
void(
"Uniform${i}i64vARB",
"Specifies the value of a single $glslType uniform variable or a $glslType uniform variable array for the current program object.",
args[1],
autoSizes[i - 1]..GLsizei.IN("count", autoSizeDoc),
const..GLint64_p.IN("value", valueDoc)
)
// ProgramUniform{1,2,3,4}i64ARB
void(
"ProgramUniform${i}i64ARB",
"Specifies the value of an $glslType uniform variable for the specified program object.",
*args.copyOfRange(0, 2 + i)
)
// ProgramUniform{1,2,3,4}i64vARB
void(
"ProgramUniform${i}i64vARB",
"Specifies the value of a single $glslType uniform variable or a $glslType uniform variable array for the specified program object.",
args[0],
args[1],
autoSizes[i - 1]..GLsizei.IN("count", autoSizeDoc),
const..GLint64_p.IN("value", valueDoc)
)
}
args[2] = GLuint64.IN("x", "the uniform x value")
args[3] = GLuint64.IN("y", "the uniform y value")
args[4] = GLuint64.IN("z", "the uniform z value")
args[5] = GLuint64.IN("w", "the uniform w value")
for (i in 1..4) {
val glslType = if ( i == 1) "uint64_t" else "u64vec$i"
val valueDoc = "a pointer to an array of {@code count} values that will be used to update the specified $glslType variable"
// Uniform{1,2,3,4}ui64ARB
void(
"Uniform${i}ui64ARB",
"Specifies the value of an $glslType uniform variable for the current program object.",
*args.copyOfRange(1, 2 + i)
)
// Uniform{1,2,3,4}ui64vARB
void(
"Uniform${i}ui64vARB",
"Specifies the value of a single $glslType uniform variable or a $glslType uniform variable array for the current program object.",
args[1],
autoSizes[i - 1]..GLsizei.IN("count", autoSizeDoc),
const..GLuint64_p.IN("value", valueDoc)
)
// ProgramUniform{1,2,3,4}ui64ARB
void(
"ProgramUniform${i}ui64ARB",
"Specifies the value of an $glslType uniform variable for the current program object.",
*args.copyOfRange(0, 2 + i)
)
// ProgramUniform{1,2,3,4}ui64vARB
void(
"ProgramUniform${i}ui64vARB",
"Specifies the value of a single $glslType uniform variable or a $glslType uniform variable array for the specified program object.",
args[0],
args[1],
autoSizes[i - 1]..GLsizei.IN("count", autoSizeDoc),
const..GLuint64_p.IN("value", valueDoc)
)
}
void(
"GetUniformi64vARB",
"Returns the int64_t value(s) of a uniform variable.",
GLuint.IN("program", "the program object to be queried"),
GLint.IN("location", "the location of the uniform variable to be queried"),
ReturnParam..Check(1)..GLint64_p.OUT("params", "the value of the specified uniform variable")
)
void(
"GetUniformui64vARB",
"Returns the uint64_t value(s) of a uniform variable.",
GLuint.IN("program", "the program object to be queried"),
GLint.IN("location", "the location of the uniform variable to be queried"),
ReturnParam..Check(1)..GLuint64_p.OUT("params", "the value of the specified uniform variable")
)
void(
"GetnUniformi64vARB",
"Robust version of #GetUniformi64vARB().",
GLuint.IN("program", "the program object to be queried"),
GLint.IN("location", "the location of the uniform variable to be queried"),
AutoSize("params")..GLsizei.IN("bufSize", "the maximum number of values to write in {@code params}"),
ReturnParam..GLint64_p.OUT("params", "the value of the specified uniform variable")
)
void(
"GetnUniformui64vARB",
"Robust version of #GetUniformui64vARB().",
GLuint.IN("program", "the program object to be queried"),
GLint.IN("location", "the location of the uniform variable to be queried"),
AutoSize("params")..GLsizei.IN("bufSize", "the maximum number of values to write in {@code params}"),
ReturnParam..GLuint64_p.OUT("params", "the value of the specified uniform variable")
)
}
|
bsd-3-clause
|
3cf406c01cf600aa428789ff05e2c51a
| 33.510989 | 168 | 0.695701 | 3.184584 | false | false | false | false |
bsmr-java/lwjgl3
|
modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/NV_bindless_texture.kt
|
1
|
13408
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl.templates
import org.lwjgl.generator.*
import org.lwjgl.opengl.*
val NV_bindless_texture = "NVBindlessTexture".nativeClassGL("NV_bindless_texture", postfix = NV) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension allows OpenGL applications to access texture objects in
shaders without first binding each texture to one of a limited number of
texture image units. Using this extension, an application can query a
64-bit unsigned integer texture handle for each texture that it wants to
access and then use that handle directly in GLSL or assembly-based
shaders. The ability to access textures without having to bind and/or
re-bind them is similar to the capability provided by the
NV_shader_buffer_load extension that allows shaders to access buffer
objects without binding them. In both cases, these extensions
significantly reduce the amount of API and internal GL driver overhead
needed to manage resource bindings.
This extension also provides similar capability for the image load, store,
and atomic functionality provided by OpenGL 4.2, OpenGL ES 3.1 and the
ARB_shader_image_load_store and EXT_shader_image_load_store extensions,
where a texture can be accessed without first binding it to an image unit.
An image handle can be extracted from a texture object using an API with a
set of parameters similar to those for BindImageTextureEXT.
This extension adds no new data types to GLSL. Instead, it uses existing
sampler and image data types and allows them to be populated with texture
and image handles. This extension does permit sampler and image data
types to be used in more contexts than in unextended GLSL 4.00. In
particular, sampler and image types may be used as shader inputs/outputs,
temporary variables, and uniform block members, and may be assigned to by
shader code. Constructors are provided to convert 64-bit unsigned integer
values to and from sampler and image data types. Additionally, new APIs
are provided to load values for sampler and image uniforms with 64-bit
handle inputs. The use of existing integer-based Uniform* APIs is still
permitted, in which case the integer specified will identify a texture
image or image unit. For samplers and images with values specified as
texture image or image units, the GL implemenation will translate the unit
number to an internal handle as required.
To access texture or image resources using handles, the handles must first
be made resident. Accessing a texture or image by handle without first
making it resident can result in undefined results, including program
termination. Since the amount of texture memory required by an
application may exceed the amount of memory available to the system, this
extension provides API calls allowing applications to manage overall
texture memory consumption by making a texture resident and non-resident
as required.
Requires ${GL40.core}.
"""
GLuint64(
"GetTextureHandleNV",
"""
Creates a texture handle using the current state of the texture named {@code texture}, including any embedded sampler state. See
#GetTextureSamplerHandleNV() for details.
""",
GLuint.IN("texture", "the texture object")
)
GLuint64(
"GetTextureSamplerHandleNV",
"""
Creates a texture handle using the current non-sampler state from the texture named {@code texture} and the sampler state from the sampler object
{@code sampler}. In both cases, a 64-bit unsigned integer handle is returned. The error GL11#INVALID_VALUE is generated if {@code texture} is zero or is
not the name of an existing texture object or if {@code sampler} is zero or is not the name of an existing sampler object. The error
GL11#INVALID_OPERATION is generated if the texture object {@code texture} is not complete. If an error occurs, a handle of zero is returned.
The error GL11#INVALID_OPERATION is generated if the border color (taken from the embedded sampler for GetTextureHandleNV or from the {@code sampler}
for GetTextureSamplerHandleNV) is not one of the following allowed values. If the texture's base internal format is signed or unsigned integer, allowed
values are (0,0,0,0), (0,0,0,1), (1,1,1,0), and (1,1,1,1). If the base internal format is not integer, allowed values are (0.0,0.0,0.0,0.0),
(0.0,0.0,0.0,1.0), (1.0,1.0,1.0,0.0), and (1.0,1.0,1.0,1.0).
The handle for each texture or texture/sampler pair is unique; the same handle will be returned if GetTextureHandleNV is called multiple times for the
same texture or if GetTextureSamplerHandleNV is called multiple times for the same texture/sampler pair.
When a texture object is referenced by one or more texture handles, the texture parameters of the object may not be changed, and the size and format of
the images in the texture object may not be re-specified. The error GL11#INVALID_OPERATION is generated if the functions TexImage*, CopyTexImage*,
CompressedTexImage*, TexBuffer*, or TexParameter* are called to modify a texture object referenced by one or more texture handles. The contents of the
images in a texture object may still be updated via commands such as TexSubImage*, CopyTexSubImage*, and CompressedTexSubImage*, and by rendering to a
framebuffer object, even if the texture object is referenced by one or more texture handles.
The error GL11#INVALID_OPERATION is generated by GL15#BufferData() if it is called to modify a buffer object bound to a buffer texture while that
texture object is referenced by one or more texture handles. The contents of the buffer object may still be updated via buffer update commands such as
GL15#BufferSubData() and MapBuffer*, or via the texture update commands, even if the buffer is bound to a texture while that buffer texture object is
referenced by one or more texture handles.
When a sampler object is referenced by one or more texture handles, the sampler parameters of the object may not be changed. The error
GL11#INVALID_OPERATION is generated when calling SamplerParameter* functions to modify a sampler object referenced by one or more texture handles.
""",
GLuint.IN("texture", "the texture object"),
GLuint.IN("sampler", "the sampler object")
)
void(
"MakeTextureHandleResidentNV",
"""
Make a texture handle resident, so that it is accessible to shaders for texture mapping operations.
While the texture handle is resident, it may be used in texture mapping operations. If a shader attempts to perform a texture mapping operation using a
handle that is not resident, the results of that operation are undefined and may lead to application termination. When a texture handle is resident, the
texture it references is also considered resident for the purposes of the GL11#AreTexturesResident() command. The error GL11#INVALID_OPERATION is
generated if {@code handle} is not a valid texture handle, or if {@code handle} is already resident in the current GL context.
""",
GLuint64.IN("handle", "the texture handle")
)
void(
"MakeTextureHandleNonResidentNV",
"""
Makes a texture handle inaccessible to shaders.
The error GL11#INVALID_OPERATION is generated if {@code handle} is not a valid texture handle, or if {@code handle} is not resident in the current GL
context.
""",
GLuint64.IN("handle", "the texture handle")
)
GLuint64(
"GetImageHandleNV",
"""
Creates and returns an image handle for level {@code level} of the texture named {@code texture}. If {@code layered} is GL11#TRUE, a handle is created
for the entire texture level. If {@code layered} is GL11#FALSE, a handle is created for only the layer {@code layer} of the texture level.
{@code format} specifies a format used to interpret the texels of the image when used for image loads, stores, and atomics, and has the same meaning as
the {@code format} parameter of BindImageTextureEXT(). A 64-bit unsigned integer handle is returned if the command succeeds; otherwise, zero is returned.
The error GL11#INVALID_VALUE is generated by GetImageHandleNV if:
${ul(
"{@code texture} is zero or not the name of an existing texture object;",
"the image for the texture level {@code level} doesn't exist (i.e., has a size of zero in {@code texture}); or",
"{@code layered} is FALSE and {@code layer} is greater than or equal to the number of layers in the image at level {@code level}."
)}
The error GL11#INVALID_OPERATION is generated by GetImageHandleNV if:
${ul(
"the texture object {@code texture} is not complete (section 3.9.14);",
"""
{@code layered} is TRUE and the texture is not a three-dimensional, one-dimensional array, two dimensional array, cube map, or cube map array
texture.
"""
)}
When a texture object is referenced by one or more image handles, the texture parameters of the object may not be changed, and the size and format of
the images in the texture object may not be re-specified. The error GL11#INVALID_OPERATION is generated when calling TexImage*, CopyTexImage*,
CompressedTexImage*, TexBuffer*, or TexParameter* functions while a texture object is referenced by one or more image handles. The contents of the
images in a texture object may still be updated via commands such as TexSubImage*, CopyTexSubImage*, and CompressedTexSubImage*, and by rendering to a
framebuffer object, even if the texture object is referenced by one or more image handles.
The error GL11#INVALID_OPERATION is generated by GL15#BufferData() if it is called to modify a buffer object bound to a buffer texture while that texture
object is referenced by one or more image handles. The contents of the buffer object may still be updated via buffer update commands such as
GL15#BufferSubData() and MapBuffer*, or via the texture update commands, even if the buffer is bound to a texture while that buffer texture object is
referenced by one or more image handles.
The handle returned for each combination of {@code texture}, {@code level}, {@code layered}, {@code layer}, and {@code format} is unique; the same
handle will be returned if GetImageHandleNV is called multiple times with the same parameters.
""",
GLuint.IN("texture", "the texture object"),
GLint.IN("level", "the texture level"),
GLboolean.IN("layered", "the layered flag"),
GLint.IN("layer", "the texture layer"),
GLenum.IN("format", "the texture format")
)
void(
"MakeImageHandleResidentNV",
"""
Makes an image handle resident, so that it is accessible to shaders for image loads, stores, and atomic operations.
{@code access} specifies whether the texture bound to the image handle will be treated as GL15#READ_ONLY, GL15#WRITE_ONLY, or GL15#READ_WRITE. If a
shader reads from an image handle made resident as GL15#WRITE_ONLY, or writes to an image handle made resident as GL15#READ_ONLY, the results of that
shader operation are undefined and may lead to application termination. The error GL11#INVALID_OPERATION is generated if {@code handle} is not a valid
image handle, or if {@code handle} is already resident in the current GL context.
While the image handle is resident, it may be used in image load, store, and atomic operations. If a shader attempts to perform an image operation using
a handle that is not resident, the results of that operation are undefined and may lead to application termination. When an image handle is resident,
the texture it references is not necessarily considered resident for the purposes of the GL11#AreTexturesResident() command.
""",
GLuint64.IN("handle", "the image handle"),
GLenum.IN("access", "the access type", "GL15#READ_ONLY GL15#WRITE_ONLY GL15#READ_WRITE")
)
void(
"MakeImageHandleNonResidentNV",
"Makes an image handle inaccessible to shaders.",
GLuint64.IN("handle", "the image handle")
)
val location = GLint.IN("location", "the uniform location")
val UniformHandleui64NV = void(
"UniformHandleui64NV",
"Loads a 64-bit unsigned integer handle into a uniform location corresponding to sampler or image variable types.",
location,
GLuint64.IN("value", "the handle value")
)
val UniformHandleui64vNV = void(
"UniformHandleui64vNV",
"Loads {@code count} 64-bit unsigned integer handles into a uniform location corresponding to sampler or image variable types.",
location,
AutoSize("values")..GLsizei.IN("count", "the number of handles to load"),
const..GLuint64_p.IN("values", "a buffer from which to load the handles")
)
void(
"ProgramUniformHandleui64NV",
"DSA version of #UniformHandleui64NV().",
GLuint.IN("program", "the program object"),
location,
UniformHandleui64NV["value"]
)
void(
"ProgramUniformHandleui64vNV",
"DSA version of #UniformHandleui64vNV().",
GLuint.IN("program", "the program object"),
location,
UniformHandleui64vNV["count"],
UniformHandleui64vNV["values"]
)
GLboolean(
"IsTextureHandleResidentNV",
"Returns GL11#TRUE if the specified texture handle is resident in the current context.",
GLuint64.IN("handle", "the texture handle")
)
GLboolean(
"IsImageHandleResidentNV",
"Returns GL11#TRUE if the specified image handle is resident in the current context.",
GLuint64.IN("handle", "the image handle")
)
}
|
bsd-3-clause
|
31dab0edb6594fcb513e73b9c1198043
| 52 | 155 | 0.760292 | 4.080341 | false | false | false | false |
EventFahrplan/EventFahrplan
|
app/src/test/java/nerd/tuxmobil/fahrplan/congress/wiki/WikiSessionUtilsTest.kt
|
1
|
1617
|
package nerd.tuxmobil.fahrplan.congress.wiki
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class WikiSessionUtilsTest {
@Test
fun linksContainWikiLinkWithEmptyString() {
assertThat("".containsWikiLink()).isFalse
}
@Test
fun linksContainWikiLinkWithSimple2017WikiLink() {
val wikiLink = "https://events.ccc.de/congress/2017/wiki/index.php/Session:Tor_relays_operators_meetup"
assertThat(wikiLink.containsWikiLink()).isTrue
}
@Test
fun linksContainWikiLinkWithSimple2018WikiLink() {
val wikiLink = "https://events.ccc.de/congress/2018/wiki/index.php/Session:Advanced_Bondage_Workshop_-_Day_2"
assertThat(wikiLink.containsWikiLink()).isTrue
}
@Test
fun linksContainWikiLinkWithWikiHtmlLink() {
val wikiLink = "<a href=\"https://events.ccc.de/congress/2017/wiki/index.php/Session:Tor_relays_operators_meetup\">https://events.ccc.de/congress/2017/wiki/index.php/Session:Tor_relays_operators_meetup</a>"
assertThat(wikiLink.containsWikiLink()).isTrue
}
@Test
fun linksContainWikiLinkWithVariousHtmlLinks() {
val variousLinks = "<a href=\"https://events.ccc.de/congress/2017/wiki/index.php/Projects:Junghackertag\">https://events.ccc.de/congress/2017/wiki/index.php/Projects:Junghackertag</a><br><a href=\"https://events.ccc.de/congress/2017/wiki/index.php/Session:Koordinierungstreffen_Junghackertag\">https://events.ccc.de/congress/2017/wiki/index.php/Session:Koordinierungstreffen_Junghackertag</a>"
assertThat(variousLinks.containsWikiLink()).isTrue
}
}
|
apache-2.0
|
6b6eef750f0f5f2f6427750b24628ca2
| 42.702703 | 401 | 0.736549 | 3.569536 | false | true | false | false |
InfiniteSoul/ProxerAndroid
|
src/main/kotlin/me/proxer/app/anime/resolver/Mp4UploadStreamResolver.kt
|
1
|
2342
|
package me.proxer.app.anime.resolver
import io.reactivex.Single
import me.proxer.app.MainApplication.Companion.GENERIC_USER_AGENT
import me.proxer.app.exception.StreamResolutionException
import me.proxer.app.util.extension.buildSingle
import me.proxer.app.util.extension.toBodySingle
import me.proxer.app.util.extension.toPrefixedUrlOrNull
import okhttp3.Request
/**
* @author Ruben Gees
*/
object Mp4UploadStreamResolver : StreamResolver() {
private val packedRegex = Regex("return p.*?'(.*?)',(\\d+),(\\d+),'(.*?)'")
private val urlRegex = Regex("player.src\\(\"(.*?\")\\)")
override val name = "MP4Upload"
override fun resolve(id: String): Single<StreamResolutionResult> = api.anime.link(id)
.buildSingle()
.flatMap { url ->
client.newCall(
Request.Builder()
.get()
.url(url.toPrefixedUrlOrNull() ?: throw StreamResolutionException())
.header("User-Agent", GENERIC_USER_AGENT)
.header("Connection", "close")
.build()
)
.toBodySingle()
}
.map {
val packedFunction = packedRegex.find(it) ?: throw StreamResolutionException()
val p = packedFunction.groupValues[1]
val a = packedFunction.groupValues[2].toIntOrNull() ?: throw StreamResolutionException()
val c = packedFunction.groupValues[3].toIntOrNull() ?: throw StreamResolutionException()
val k = packedFunction.groupValues[4].split("|")
if (p.isBlank() || k.size != c) {
throw StreamResolutionException()
}
val unpacked = unpack(p, a, c, k)
val urlRegexResult = urlRegex.find(unpacked) ?: throw StreamResolutionException()
val url = urlRegexResult.groupValues[1]
url.toPrefixedUrlOrNull() ?: throw StreamResolutionException()
}
.map { StreamResolutionResult.Video(it, "video/mp4") }
private fun unpack(p: String, a: Int, c: Int, k: List<String>): String {
return (c - 1 downTo 0).fold(p, { acc, next ->
if (k[next].isNotEmpty()) {
acc.replace(Regex("\\b" + next.toString(a) + "\\b"), k[next])
} else {
acc
}
})
}
}
|
gpl-3.0
|
151bc334f48cdfac29f69c358d5bb9aa
| 35.59375 | 100 | 0.585824 | 4.565302 | false | false | false | false |
REDNBLACK/advent-of-code2016
|
src/main/kotlin/day16/Advent16.kt
|
1
|
4585
|
package day16
/**
--- Day 16: Dragon Checksum ---
You're done scanning this part of the network, but you've left traces of your presence. You need to overwrite some disks with random-looking data to cover your tracks and update the local security system with a new checksum for those disks.
For the data to not be suspicious, it needs to have certain properties; purely random data will be detected as tampering. To generate appropriate random data, you'll need to use a modified dragon curve.
Start with an appropriate initial state (your puzzle input). Then, so long as you don't have enough data yet to fill the disk, repeat the following steps:
Call the data you have at this point "a".
Make a copy of "a"; call this copy "b".
Reverse the order of the characters in "b".
In "b", replace all instances of 0 with 1 and all 1s with 0.
The resulting data is "a", then a single 0, then "b".
For example, after a single step of this process,
1 becomes 100.
0 becomes 001.
11111 becomes 11111000000.
111100001010 becomes 1111000010100101011110000.
Repeat these steps until you have enough data to fill the desired disk.
Once the data has been generated, you also need to create a checksum of that data. Calculate the checksum only for the data that fits on the disk, even if you generated more data than that in the previous step.
The checksum for some given data is created by considering each non-overlapping pair of characters in the input data. If the two characters match (00 or 11), the next checksum character is a 1. If the characters do not match (01 or 10), the next checksum character is a 0. This should produce a new string which is exactly half as long as the original. If the length of the checksum is even, repeat the process until you end up with a checksum with an odd length.
For example, suppose we want to fill a disk of length 12, and when we finally generate a string of at least length 12, the first 12 characters are 110010110100. To generate its checksum:
Consider each pair: 11, 00, 10, 11, 01, 00.
These are same, same, different, same, different, same, producing 110101.
The resulting string has length 6, which is even, so we repeat the process.
The pairs are 11 (same), 01 (different), 01 (different).
This produces the checksum 100, which has an odd length, so we stop.
Therefore, the checksum for 110010110100 is 100.
Combining all of these steps together, suppose you want to fill a disk of length 20 using an initial state of 10000:
Because 10000 is too short, we first use the modified dragon curve to make it longer.
After one round, it becomes 10000011110 (11 characters), still too short.
After two rounds, it becomes 10000011110010000111110 (23 characters), which is enough.
Since we only need 20, but we have 23, we get rid of all but the first 20 characters: 10000011110010000111.
Next, we start calculating the checksum; after one round, we have 0111110101, which 10 characters long (even), so we continue.
After two rounds, we have 01100, which is 5 characters long (odd), so we are done.
In this example, the correct checksum would therefore be 01100.
The first disk you have to fill has length 272. Using the initial state in your puzzle input, what is the correct checksum?
--- Part Two ---
The second disk you have to fill has length 35651584. Again using the initial state in your puzzle input, what is the correct checksum for this disk?
*/
fun main(args: Array<String>) {
println("1".dragonCurve() == "100")
println("0".dragonCurve() == "001")
println("11111".dragonCurve() == "11111000000")
println("111100001010".dragonCurve() == "1111000010100101011110000")
println("110010110100".checkSum() == "100")
println("10000".dragonCurve(20).checkSum() == "01100")
println("01110110101001000".dragonCurve(272).checkSum())
println("01110110101001000".dragonCurve(35651584).checkSum())
}
fun String.dragonCurve(length: Int? = null): String = reversed()
.map { bit -> if (bit == '0') '1' else '0' }
.joinToString("")
.let { it -> this + '0' + it }
.let { if (length != null && it.length < length) it.dragonCurve(length) else it }
.let { if (length != null) it.substring(0, length) else it }
fun String.checkSum(): String = (0 until length step 2)
.map { this[it] to getOrElse(it + 1, { Char.MIN_SURROGATE }) }
.filter { it.first != Char.MIN_SURROGATE && it.second != Char.MIN_SURROGATE }
.map { if (it.first == it.second) '1' else '0' }
.joinToString("")
.let { if (it.length % 2 == 0) it.checkSum() else it }
|
mit
|
03347cd47c649816128f143e2fec7de8
| 54.914634 | 463 | 0.726499 | 3.840034 | false | false | false | false |
JetBrains-Research/big
|
src/main/kotlin/org/jetbrains/bio/MMBRomBufferFactory.kt
|
2
|
722
|
package org.jetbrains.bio
import com.indeed.util.mmap.MMapBuffer
import java.nio.ByteOrder
import java.nio.channels.FileChannel
import java.nio.file.Path
class MMBRomBufferFactory(
val path: Path,
order: ByteOrder
) : RomBufferFactory {
private var memBuffer = MMapBuffer(path, FileChannel.MapMode.READ_ONLY, order)
override var order = order
set(value) {
if (value != field) {
memBuffer.close()
memBuffer = MMapBuffer(path, FileChannel.MapMode.READ_ONLY, value)
field = value
}
}
override fun create(): RomBuffer = MMBRomBuffer(memBuffer)
override fun close() {
memBuffer.close()
}
}
|
mit
|
42084d8d9c56f46d104a36552e71b245
| 23.931034 | 82 | 0.630194 | 4.079096 | false | false | false | false |
ZieIony/Carbon
|
samples/src/main/java/tk/zielony/carbonsamples/SamplesActivity.kt
|
1
|
4803
|
package tk.zielony.carbonsamples
import android.content.Context
import android.os.Bundle
import android.view.Menu
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import carbon.dialog.MultiSelectDialog
import carbon.internal.DebugOverlay
import carbon.widget.MenuStrip
import carbon.widget.Toolbar
import java.util.*
abstract class SamplesActivity : AppCompatActivity() {
var debugEnabled = false
var debugOptions = arrayOf("bounds", "grid", "hit rects", "margins", "paddings", "rulers", "text sizes")
private val overlay by lazy {
DebugOverlay(this).apply {
isDrawBoundsEnabled = false
isDrawGridEnabled = false
isDrawHitRectsEnabled = false
isDrawMarginsEnabled = false
isDrawPaddingsEnabled = false
isDrawRulersEnabled = false
isDrawTextSizesEnabled = false
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
javaClass.getAnnotation(SampleAnnotation::class.java)?.let {
if (it.layoutId != 0)
setContentView(it.layoutId)
if (it.titleId != 0)
title = getString(it.titleId)
}
if (this !is SampleListActivity && this !is ColorsActivity && this !is CodeActivity && this !is AboutActivity) {
val preferences = getSharedPreferences("samples", Context.MODE_PRIVATE)
preferences.edit().putString(RECENTLY_USED, javaClass.name).apply()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
javaClass.getAnnotation(SampleAnnotation::class.java)?.let {
if (it.menuId != 0)
menuInflater.inflate(it.menuId, menu)
}
return super.onCreateOptionsMenu(menu)
}
fun initToolbar() {
val toolbar = findViewById<Toolbar>(R.id.toolbar)
toolbar?.title = title
toolbar?.setIconVisible(toolbar.icon != null)
toolbar?.setOnMenuItemClicked { view, item, position ->
when (item.id) {
R.id.debug -> debugClicked()
R.id.enabled -> enabledClicked(item as MenuStrip.CheckableItem)
}
}
}
private fun debugClicked() {
val listDialog = MultiSelectDialog<String>(this@SamplesActivity)
listDialog.setItems(debugOptions)
listDialog.setTitle("Debug options")
val initialItems = ArrayList<String>()
if (overlay.isDrawBoundsEnabled)
initialItems.add("bounds")
if (overlay.isDrawGridEnabled)
initialItems.add("grid")
if (overlay.isDrawHitRectsEnabled)
initialItems.add("hit rects")
if (overlay.isDrawMarginsEnabled)
initialItems.add("margins")
if (overlay.isDrawPaddingsEnabled)
initialItems.add("paddings")
if (overlay.isDrawRulersEnabled)
initialItems.add("rulers")
if (overlay.isDrawTextSizesEnabled)
initialItems.add("text sizes")
listDialog.selectedItems = initialItems
listDialog.show()
listDialog.setOnDismissListener { dialogInterface ->
val selectedItems = listDialog.selectedItems
overlay.isDrawBoundsEnabled = selectedItems.contains("bounds")
overlay.isDrawGridEnabled = selectedItems.contains("grid")
overlay.isDrawHitRectsEnabled = selectedItems.contains("hit rects")
overlay.isDrawMarginsEnabled = selectedItems.contains("margins")
overlay.isDrawPaddingsEnabled = selectedItems.contains("paddings")
overlay.isDrawRulersEnabled = selectedItems.contains("rulers")
overlay.isDrawTextSizesEnabled = selectedItems.contains("text sizes")
if (!debugEnabled && selectedItems.isNotEmpty()) {
overlay.show()
debugEnabled = true
} else if (debugEnabled && selectedItems.isEmpty()) {
overlay.dismiss()
debugEnabled = false
}
}
}
private fun enabledClicked(item: MenuStrip.CheckableItem) {
val views = ArrayList<View>()
views.add(window.decorView.rootView)
while (views.isNotEmpty()) {
val v = views.removeAt(0)
if (v.id == R.id.toolbar)
continue
v.isEnabled = item.isChecked
if (v is ViewGroup) {
for (i in 0 until v.childCount)
views.add(v.getChildAt(i))
}
}
}
companion object {
const val RECENTLY_USED = "recentlyUsed"
}
}
|
apache-2.0
|
5f908b6ba7ed32cd4a3a7d0483644531
| 35.664122 | 120 | 0.630439 | 4.861336 | false | false | false | false |
WangDaYeeeeee/GeometricWeather
|
app/src/main/java/wangdaye/com/geometricweather/common/basic/livedata/BusLiveData.kt
|
1
|
2478
|
package wangdaye.com.geometricweather.common.basic.livedata
import android.os.Handler
import android.os.Looper
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import wangdaye.com.geometricweather.common.bus.MyObserverWrapper
import java.util.*
class BusLiveData<T> constructor(
private val mainHandler: Handler
) : MutableLiveData<T>() {
companion object {
const val START_VERSION = -1
}
private val wrapperMap = HashMap<Observer<in T>, MyObserverWrapper<T>>()
internal var version = START_VERSION
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
runOnMainThread {
innerObserver(owner,
MyObserverWrapper(this, observer, version)
)
}
}
fun observeStickily(owner: LifecycleOwner, observer: Observer<in T>) {
runOnMainThread {
innerObserver(owner,
MyObserverWrapper(this, observer, START_VERSION)
)
}
}
private fun innerObserver(owner: LifecycleOwner, wrapper: MyObserverWrapper<T>) {
wrapperMap[wrapper.observer] = wrapper
super.observe(owner, wrapper)
}
override fun observeForever(observer: Observer<in T>) {
runOnMainThread {
innerObserverForever(
MyObserverWrapper(this, observer, version)
)
}
}
fun observeStickilyForever(observer: Observer<in T>) {
runOnMainThread {
innerObserverForever(
MyObserverWrapper(this, observer, START_VERSION)
)
}
}
private fun innerObserverForever(wrapper: MyObserverWrapper<T>) {
wrapperMap[wrapper.observer] = wrapper
super.observeForever(wrapper)
}
override fun removeObserver(observer: Observer<in T>) {
runOnMainThread {
val wrapper = wrapperMap.remove(observer)
if (wrapper != null) {
super.removeObserver(wrapper)
}
}
}
override fun setValue(value: T) {
version ++
super.setValue(value)
}
override fun postValue(value: T) {
runOnMainThread { setValue(value) }
}
private fun runOnMainThread(r: Runnable) {
if (Looper.getMainLooper().thread === Thread.currentThread()) {
r.run()
} else {
mainHandler.post(r)
}
}
}
|
lgpl-3.0
|
abf7a29563dbccaa7e09199522673aab
| 26.853933 | 85 | 0.619451 | 4.793037 | false | false | false | false |
walleth/walleth
|
app/src/main/java/org/walleth/enhancedlist/EnhancedListAdapter.kt
|
1
|
2331
|
package org.walleth.enhancedlist
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.toList
class EnhancedListViewHolder(view: View) : RecyclerView.ViewHolder(view)
class EnhancedListAdapter<T : ListItem>(
@LayoutRes
private val layout: Int,
private val bind: (entry: T, view: View) -> Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
var list: List<T> = mutableListOf()
var displayList: List<T> = mutableListOf()
override fun getItemCount() = displayList.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EnhancedListViewHolder {
val inflate = LayoutInflater.from(parent.context).inflate(layout, parent, false)
return EnhancedListViewHolder(inflate)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val item = displayList[position]
bind.invoke(item, holder.itemView)
}
suspend fun filter(newList: List<T>,
filter: suspend (t: T) -> Boolean,
onChange: suspend () -> Unit,
areEqual: (t1: T, t2: T) -> Boolean) {
if (list.size != newList.size || !list.containsAll(newList)) {
onChange.invoke()
}
list = newList
val newDisplayList = newList
.asFlow()
.filter { filter(it) }
.filter { !it.deleted }
.toList()
val diff = DiffUtil.calculateDiff(object : DiffUtil.Callback() {
override fun getOldListSize() = displayList.size
override fun getNewListSize() = newDisplayList.size
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) = displayList[oldItemPosition] == newDisplayList[newItemPosition]
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) = areEqual(displayList[oldItemPosition], newDisplayList[newItemPosition])
})
diff.dispatchUpdatesTo(this)
displayList = newDisplayList
}
}
|
gpl-3.0
|
a0d464c38a05eed8250b6b60085f07d7
| 33.80597 | 158 | 0.66967 | 4.866388 | false | false | false | false |
zlyne0/colonization
|
core/src/promitech/colonization/screen/ff/FoundingFatherInfoPanel.kt
|
1
|
1556
|
package promitech.colonization.screen.ff
import com.badlogic.gdx.scenes.scene2d.ui.Image
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable
import com.badlogic.gdx.utils.Align
import net.sf.freecol.common.model.player.FoundingFather
import promitech.colonization.GameResources
import promitech.colonization.ui.resources.Messages
internal class FoundingFatherInfoPanel(val panelSkin : Skin) : Table() {
val nameLabel = Label("", panelSkin)
val ffImage = Image()
val description = object : Label("", panelSkin) {
override fun getPrefWidth() : Float {
return ffImage.width * 1.5f
}
}
var foundingFather : FoundingFather? = null
init {
nameLabel.setWrap(true)
description.setWrap(true)
add(nameLabel).colspan(2).align(Align.center).pad(10f).expandX().fillX().row()
add(ffImage).align(Align.left or Align.top).pad(10f)
add(description).top().pad(10f)
}
fun update(ff : FoundingFather) {
foundingFather = ff
nameLabel.setText(
Messages.msgName(ff) + " (" + Messages.msg(ff.type.msgKey()) + ")"
)
val frame = GameResources.instance.getFrame(ff.getId() + ".image")
ffImage.setDrawable(TextureRegionDrawable(frame.texture))
val descriptionStr = Messages.msgDescription(ff) +
"\r\n\r\n" +
"[" + Messages.msg(ff.getId() + ".birthAndDeath") + "] " + Messages.msg(ff.getId() + ".text")
description.setText(descriptionStr)
invalidateHierarchy()
}
}
|
gpl-2.0
|
c9e00df7463a979cbe8797bcf25391cb
| 28.942308 | 96 | 0.737147 | 3.182004 | false | false | false | false |
auth0/Auth0.Android
|
auth0/src/main/java/com/auth0/android/authentication/AuthenticationAPIClient.kt
|
1
|
35314
|
package com.auth0.android.authentication
import androidx.annotation.VisibleForTesting
import com.auth0.android.Auth0
import com.auth0.android.Auth0Exception
import com.auth0.android.request.*
import com.auth0.android.request.internal.*
import com.auth0.android.request.internal.GsonAdapter.Companion.forMap
import com.auth0.android.request.internal.GsonAdapter.Companion.forMapOf
import com.auth0.android.result.Challenge
import com.auth0.android.result.Credentials
import com.auth0.android.result.DatabaseUser
import com.auth0.android.result.UserProfile
import com.google.gson.Gson
import okhttp3.HttpUrl.Companion.toHttpUrl
import java.io.IOException
import java.io.Reader
import java.security.PublicKey
/**
* API client for Auth0 Authentication API.
* ```
* val auth0 = Auth0("YOUR_CLIENT_ID", "YOUR_DOMAIN")
* val client = AuthenticationAPIClient(auth0)
* ```
*
* @see [Auth API docs](https://auth0.com/docs/auth-api)
*/
public class AuthenticationAPIClient @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal constructor(
private val auth0: Auth0,
private val factory: RequestFactory<AuthenticationException>,
private val gson: Gson
) {
/**
* Creates a new API client instance providing Auth0 account info.
*
* Example usage:
*
* ```
* val auth0 = Auth0("YOUR_CLIENT_ID", "YOUR_DOMAIN")
* val client = AuthenticationAPIClient(auth0)
* ```
* @param auth0 account information
*/
public constructor(auth0: Auth0) : this(
auth0,
RequestFactory<AuthenticationException>(auth0.networkingClient, createErrorAdapter()),
GsonProvider.gson
)
public val clientId: String
get() = auth0.clientId
public val baseURL: String
get() = auth0.getDomainUrl()
/**
* Log in a user with email/username and password for a connection/realm.
* It will use the password-realm grant type for the `/oauth/token` endpoint
* The default scope used is 'openid profile email'.
*
* Example usage:
*
* ```
* client
* .login("{username or email}", "{password}", "{database connection name}")
* .validateClaims() //mandatory
* .start(object : Callback<Credentials, AuthenticationException> {
* override fun onSuccess(result: Credentials) { }
* override fun onFailure(error: AuthenticationException) { }
* })
*```
*
* @param usernameOrEmail of the user depending of the type of DB connection
* @param password of the user
* @param realmOrConnection realm to use in the authorize flow or the name of the database to authenticate with.
* @return a request to configure and start that will yield [Credentials]
*/
public fun login(
usernameOrEmail: String,
password: String,
realmOrConnection: String
): AuthenticationRequest {
val parameters = ParameterBuilder.newAuthenticationBuilder()
.set(USERNAME_KEY, usernameOrEmail)
.set(PASSWORD_KEY, password)
.setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD_REALM)
.setRealm(realmOrConnection)
.asDictionary()
return loginWithToken(parameters)
}
/**
* Log in a user with email/username and password using the password grant and the default directory.
* The default scope used is 'openid profile email'.
*
* Example usage:
*
* ```
* client.login("{username or email}", "{password}")
* .validateClaims() //mandatory
* .start(object: Callback<Credentials, AuthenticationException> {
* override fun onSuccess(result: Credentials) { }
* override fun onFailure(error: AuthenticationException) { }
* })
*```
*
* @param usernameOrEmail of the user
* @param password of the user
* @return a request to configure and start that will yield [Credentials]
*/
public fun login(usernameOrEmail: String, password: String): AuthenticationRequest {
val requestParameters = ParameterBuilder.newAuthenticationBuilder()
.set(USERNAME_KEY, usernameOrEmail)
.set(PASSWORD_KEY, password)
.setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORD)
.asDictionary()
return loginWithToken(requestParameters)
}
/**
* Log in a user using the One Time Password code after they have received the 'mfa_required' error.
* The MFA token tells the server the username or email, password, and realm values sent on the first request.
*
* Requires your client to have the **MFA OTP** Grant Type enabled. See [Client Grant Types](https://auth0.com/docs/clients/client-grant-types) to learn how to enable it.
*
* Example usage:
*
*```
* client.loginWithOTP("{mfa token}", "{one time password}")
* .validateClaims() //mandatory
* .start(object : Callback<Credentials, AuthenticationException> {
* override fun onFailure(error: AuthenticationException) { }
* override fun onSuccess(result: Credentials) { }
* })
*```
*
* @param mfaToken the token received in the previous [.login] response.
* @param otp the one time password code provided by the resource owner, typically obtained from an
* MFA application such as Google Authenticator or Guardian.
* @return a request to configure and start that will yield [Credentials]
*/
public fun loginWithOTP(mfaToken: String, otp: String): AuthenticationRequest {
val parameters = ParameterBuilder.newBuilder()
.setGrantType(ParameterBuilder.GRANT_TYPE_MFA_OTP)
.set(MFA_TOKEN_KEY, mfaToken)
.set(ONE_TIME_PASSWORD_KEY, otp)
.asDictionary()
return loginWithToken(parameters)
}
/**
* Log in a user using an Out Of Band authentication code after they have received the 'mfa_required' error.
* The MFA token tells the server the username or email, password, and realm values sent on the first request.
*
* Requires your client to have the **MFA OOB** Grant Type enabled. See [Client Grant Types](https://auth0.com/docs/clients/client-grant-types) to learn how to enable it.
*
* Example usage:
*
*```
* client.loginWithOOB("{mfa token}", "{out of band code}", "{binding code}")
* .validateClaims() //mandatory
* .start(object : Callback<Credentials, AuthenticationException> {
* override fun onFailure(error: AuthenticationException) { }
* override fun onSuccess(result: Credentials) { }
* })
*```
*
* @param mfaToken the token received in the previous [.login] response.
* @param oobCode the out of band code received in the challenge response.
* @param bindingCode the code used to bind the side channel (used to deliver the challenge) with the main channel you are using to authenticate.
* This is usually an OTP-like code delivered as part of the challenge message.
* @return a request to configure and start that will yield [Credentials]
*/
public fun loginWithOOB(
mfaToken: String,
oobCode: String,
bindingCode: String? = null
): AuthenticationRequest {
val parameters = ParameterBuilder.newBuilder()
.setGrantType(ParameterBuilder.GRANT_TYPE_MFA_OOB)
.set(MFA_TOKEN_KEY, mfaToken)
.set(OUT_OF_BAND_CODE_KEY, oobCode)
.set(BINDING_CODE_KEY, bindingCode)
.asDictionary()
return loginWithToken(parameters)
}
/**
* Log in a user using a multi-factor authentication Recovery Code after they have received the 'mfa_required' error.
* The MFA token tells the server the username or email, password, and realm values sent on the first request.
*
* Requires your client to have the **MFA** Grant Type enabled. See [Client Grant Types](https://auth0.com/docs/clients/client-grant-types) to learn how to enable it.
*
* Example usage:
*
*```
* client.loginWithRecoveryCode("{mfa token}", "{recovery code}")
* .validateClaims() //mandatory
* .start(object : Callback<Credentials, AuthenticationException> {
* override fun onFailure(error: AuthenticationException) { }
* override fun onSuccess(result: Credentials) { }
* })
*```
*
* @param mfaToken the token received in the previous [.login] response.
* @param recoveryCode the recovery code provided by the end-user.
* @return a request to configure and start that will yield [Credentials]. It might also include a [recoveryCode] field,
* which your application must display to the end-user to be stored securely for future use.
*/
public fun loginWithRecoveryCode(
mfaToken: String,
recoveryCode: String
): AuthenticationRequest {
val parameters = ParameterBuilder.newBuilder()
.setGrantType(ParameterBuilder.GRANT_TYPE_MFA_RECOVERY_CODE)
.set(MFA_TOKEN_KEY, mfaToken)
.set(RECOVERY_CODE_KEY, recoveryCode)
.asDictionary()
return loginWithToken(parameters)
}
/**
* Request a challenge for multi-factor authentication (MFA) based on the challenge types supported by the application and user.
* The challenge type is how the user will get the challenge and prove possession. Supported challenge types include: "otp" and "oob".
*
* Example usage:
*
*```
* client.multifactorChallenge("{mfa token}", "{challenge type}", "{authenticator id}")
* .start(object : Callback<Challenge, AuthenticationException> {
* override fun onFailure(error: AuthenticationException) { }
* override fun onSuccess(result: Challenge) { }
* })
*```
*
* @param mfaToken the token received in the previous [.login] response.
* @param challengeType A whitespace-separated list of the challenges types accepted by your application.
* Accepted challenge types are oob or otp. Excluding this parameter means that your client application
* accepts all supported challenge types.
* @param authenticatorId The ID of the authenticator to challenge.
* @return a request to configure and start that will yield [Challenge]
*/
public fun multifactorChallenge(
mfaToken: String,
challengeType: String? = null,
authenticatorId: String? = null
): Request<Challenge, AuthenticationException> {
val parameters = ParameterBuilder.newBuilder()
.setClientId(clientId)
.set(MFA_TOKEN_KEY, mfaToken)
.set(CHALLENGE_TYPE_KEY, challengeType)
.set(AUTHENTICATOR_ID_KEY, authenticatorId)
.asDictionary()
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(MFA_PATH)
.addPathSegment(CHALLENGE_PATH)
.build()
val challengeAdapter: JsonAdapter<Challenge> = GsonAdapter(
Challenge::class.java, gson
)
return factory.post(url.toString(), challengeAdapter)
.addParameters(parameters)
}
/**
* Log in a user using a token obtained from a Native Social Identity Provider, such as Facebook, using ['\oauth\token' endpoint](https://auth0.com/docs/api/authentication#token-exchange-for-native-social)
* The default scope used is 'openid profile email'.
*
* Example usage:
*
* ```
* client.loginWithNativeSocialToken("{subject token}", "{subject token type}")
* .validateClaims() //mandatory
* .start(object: Callback<Credentials, AuthenticationException> {
* override fun onSuccess(result: Credentials) { }
* override fun onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param token the subject token, typically obtained through the Identity Provider's SDK
* @param tokenType the subject token type that is associated with this Identity Provider. e.g. 'http://auth0.com/oauth/token-type/facebook-session-access-token'
* @return a request to configure and start that will yield [Credentials]
*/
public fun loginWithNativeSocialToken(token: String, tokenType: String): AuthenticationRequest {
val parameters = ParameterBuilder.newAuthenticationBuilder()
.setGrantType(ParameterBuilder.GRANT_TYPE_TOKEN_EXCHANGE)
.setClientId(clientId)
.set(SUBJECT_TOKEN_KEY, token)
.set(SUBJECT_TOKEN_TYPE_KEY, tokenType)
.asDictionary()
return loginWithToken(parameters)
}
/**
* Log in a user using a phone number and a verification code received via SMS (Part of passwordless login flow)
* The default scope used is 'openid profile email'.
*
* Your Application must have the **Passwordless OTP** Grant Type enabled.
*
* Example usage:
* ```
* client.loginWithPhoneNumber("{phone number}", "{code}", "{passwordless connection name}")
* .validateClaims() //mandatory
* .start(object: Callback<Credentials, AuthenticationException> {
* override fun onSuccess(result: Credentials) { }
* override fun onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param phoneNumber where the user received the verification code
* @param verificationCode sent by Auth0 via SMS
* @param realmOrConnection to end the passwordless authentication on
* @return a request to configure and start that will yield [Credentials]
*/
@JvmOverloads
public fun loginWithPhoneNumber(
phoneNumber: String,
verificationCode: String,
realmOrConnection: String = SMS_CONNECTION
): AuthenticationRequest {
val parameters = ParameterBuilder.newAuthenticationBuilder()
.setClientId(clientId)
.set(USERNAME_KEY, phoneNumber)
.setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORDLESS_OTP)
.set(ONE_TIME_PASSWORD_KEY, verificationCode)
.setRealm(realmOrConnection)
.asDictionary()
return loginWithToken(parameters)
}
/**
* Log in a user using an email and a verification code received via Email (Part of passwordless login flow).
* The default scope used is 'openid profile email'.
*
* Your Application must have the **Passwordless OTP** Grant Type enabled.
*
* Example usage:
* ```
* client.loginWithEmail("{email}", "{code}", "{passwordless connection name}")
* .validateClaims() //mandatory
* .start(object: Callback<Credentials, AuthenticationException> {
* override fun onSuccess(result: Credentials) { }
* override fun onFailure(error: AuthenticationException) { }
* })
*```
*
* @param email where the user received the verification code
* @param verificationCode sent by Auth0 via Email
* @param realmOrConnection to end the passwordless authentication on
* @return a request to configure and start that will yield [Credentials]
*/
@JvmOverloads
public fun loginWithEmail(
email: String,
verificationCode: String,
realmOrConnection: String = EMAIL_CONNECTION
): AuthenticationRequest {
val parameters = ParameterBuilder.newAuthenticationBuilder()
.setClientId(clientId)
.set(USERNAME_KEY, email)
.setGrantType(ParameterBuilder.GRANT_TYPE_PASSWORDLESS_OTP)
.set(ONE_TIME_PASSWORD_KEY, verificationCode)
.setRealm(realmOrConnection)
.asDictionary()
return loginWithToken(parameters)
}
/**
* Returns the information of the user associated with the given access_token.
*
* Example usage:
* ```
* client.userInfo("{access_token}")
* .start(object: Callback<UserProfile, AuthenticationException> {
* override fun onSuccess(result: UserProfile) { }
* override fun onFailure(error: AuthenticationException) { }
* })
*```
*
* @param accessToken used to fetch it's information
* @return a request to start
*/
public fun userInfo(accessToken: String): Request<UserProfile, AuthenticationException> {
return profileRequest()
.addHeader(HEADER_AUTHORIZATION, "Bearer $accessToken")
}
/**
* Creates a user in a DB connection using ['/dbconnections/signup' endpoint](https://auth0.com/docs/api/authentication#signup)
*
* Example usage:
* ```
* client.createUser("{email}", "{password}", "{username}", "{database connection name}")
* .start(object: Callback<DatabaseUser, AuthenticationException> {
* override fun onSuccess(result: DatabaseUser) { }
* override fun onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param email of the user and must be non null
* @param password of the user and must be non null
* @param username of the user and must be non null
* @param connection of the database to create the user on
* @param userMetadata to set upon creation of the user
* @return a request to start
*/
@JvmOverloads
public fun createUser(
email: String,
password: String,
username: String? = null,
connection: String,
userMetadata: Map<String, String>? = null
): Request<DatabaseUser, AuthenticationException> {
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(DB_CONNECTIONS_PATH)
.addPathSegment(SIGN_UP_PATH)
.build()
val parameters = ParameterBuilder.newBuilder()
.set(USERNAME_KEY, username)
.set(EMAIL_KEY, email)
.set(PASSWORD_KEY, password)
.setConnection(connection)
.setClientId(clientId)
.asDictionary()
val databaseUserAdapter: JsonAdapter<DatabaseUser> = GsonAdapter(
DatabaseUser::class.java, gson
)
val post = factory.post(url.toString(), databaseUserAdapter)
.addParameters(parameters) as BaseRequest<DatabaseUser, AuthenticationException>
userMetadata?.let { post.addParameter(USER_METADATA_KEY, userMetadata) }
return post
}
/**
* Creates a user in a DB connection using ['/dbconnections/signup' endpoint](https://auth0.com/docs/api/authentication#signup)
* and then logs in the user.
* The default scope used is 'openid profile email'.
*
* Example usage:
*
* ```
* client.signUp("{email}", "{password}", "{username}", "{database connection name}")
* .validateClaims() //mandatory
* .start(object: Callback<Credentials, AuthenticationException> {
* override fun onSuccess(result: Credentials) { }
* override fun onFailure(error: AuthenticationException) { }
* })
*```
*
* @param email of the user and must be non null
* @param password of the user and must be non null
* @param username of the user and must be non null
* @param connection of the database to sign up with
* @param userMetadata to set upon creation of the user
* @return a request to configure and start that will yield [Credentials]
*/
@JvmOverloads
public fun signUp(
email: String,
password: String,
username: String? = null,
connection: String,
userMetadata: Map<String, String>? = null
): SignUpRequest {
val createUserRequest = createUser(email, password, username, connection, userMetadata)
val authenticationRequest = login(email, password, connection)
return SignUpRequest(createUserRequest, authenticationRequest)
}
/**
* Request a reset password using ['/dbconnections/change_password'](https://auth0.com/docs/api/authentication#change-password)
*
* Example usage:
*
* ```
* client.resetPassword("{email}", "{database connection name}")
* .start(object: Callback<Void?, AuthenticationException> {
* override fun onSuccess(result: Void?) { }
* override fun onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param email of the user to request the password reset. An email will be sent with the reset instructions.
* @param connection of the database to request the reset password on
* @return a request to configure and start
*/
public fun resetPassword(
email: String,
connection: String
): Request<Void?, AuthenticationException> {
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(DB_CONNECTIONS_PATH)
.addPathSegment(CHANGE_PASSWORD_PATH)
.build()
val parameters = ParameterBuilder.newBuilder()
.set(EMAIL_KEY, email)
.setClientId(clientId)
.setConnection(connection)
.asDictionary()
return factory.post(url.toString())
.addParameters(parameters)
}
/**
* Request the revoke of a given refresh_token. Once revoked, the refresh_token cannot be used to obtain new tokens.
* Your Auth0 Application Type should be set to 'Native' and Token Endpoint Authentication Method must be set to 'None'.
*
* Example usage:
*
* ```
* client.revokeToken("{refresh_token}")
* .start(object: Callback<Void?, AuthenticationException> {
* override fun onSuccess(result: Void?) { }
* override fun onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param refreshToken the token to revoke
* @return a request to start
*/
public fun revokeToken(refreshToken: String): Request<Void?, AuthenticationException> {
val parameters = ParameterBuilder.newBuilder()
.setClientId(clientId)
.set(TOKEN_KEY, refreshToken)
.asDictionary()
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(OAUTH_PATH)
.addPathSegment(REVOKE_PATH)
.build()
return factory.post(url.toString())
.addParameters(parameters)
}
/**
* Requests new Credentials using a valid Refresh Token. The received token will have the same audience and scope as first requested.
*
* This method will use the /oauth/token endpoint with the 'refresh_token' grant, and the response will include an id_token and an access_token if 'openid' scope was requested when the refresh_token was obtained.
* Additionally, if the application has Refresh Token Rotation configured, a new one-time use refresh token will also be included in the response.
*
* The scope of the newly received Access Token can be reduced sending the scope parameter with this request.
*
* Example usage:
* ```
* client.renewAuth("{refresh_token}")
* .addParameter("scope", "openid profile email")
* .start(object: Callback<Credentials, AuthenticationException> {
* override fun onSuccess(result: Credentials) { }
* override fun onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param refreshToken used to fetch the new Credentials.
* @return a request to start
*/
public fun renewAuth(refreshToken: String): Request<Credentials, AuthenticationException> {
val parameters = ParameterBuilder.newBuilder()
.setClientId(clientId)
.setRefreshToken(refreshToken)
.setGrantType(ParameterBuilder.GRANT_TYPE_REFRESH_TOKEN)
.asDictionary()
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(OAUTH_PATH)
.addPathSegment(TOKEN_PATH)
.build()
val credentialsAdapter = GsonAdapter(
Credentials::class.java, gson
)
return factory.post(url.toString(), credentialsAdapter)
.addParameters(parameters)
}
/**
* Start a passwordless flow with an [Email](https://auth0.com/docs/api/authentication#get-code-or-link).
*
* Your Application must have the **Passwordless OTP** Grant Type enabled.
*
* Example usage:
* ```
* client.passwordlessWithEmail("{email}", PasswordlessType.CODE, "{passwordless connection name}")
* .start(object: Callback<Void?, AuthenticationException> {
* override onSuccess(result: Void?) { }
* override onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param email that will receive a verification code to use for login
* @param passwordlessType indicate whether the email should contain a code, link or magic link (android & iOS)
* @param connection the passwordless connection to start the flow with.
* @return a request to configure and start
*/
@JvmOverloads
public fun passwordlessWithEmail(
email: String,
passwordlessType: PasswordlessType,
connection: String = EMAIL_CONNECTION
): Request<Void?, AuthenticationException> {
val parameters = ParameterBuilder.newBuilder()
.set(EMAIL_KEY, email)
.setSend(passwordlessType)
.setConnection(connection)
.asDictionary()
return passwordless()
.addParameters(parameters)
}
/**
* Start a passwordless flow with a [SMS](https://auth0.com/docs/api/authentication#get-code-or-link)
*
* Your Application requires to have the **Passwordless OTP** Grant Type enabled.
*
* Example usage:
* ```
* client.passwordlessWithSms("{phone number}", PasswordlessType.CODE, "{passwordless connection name}")
* .start(object: Callback<Void?, AuthenticationException> {
* override fun onSuccess(result: Void?) { }
* override fun onFailure(error: AuthenticationException) { }
* })
* ```
*
* @param phoneNumber where an SMS with a verification code will be sent
* @param passwordlessType indicate whether the SMS should contain a code, link or magic link (android & iOS)
* @param connection the passwordless connection to start the flow with.
* @return a request to configure and start
*/
@JvmOverloads
public fun passwordlessWithSMS(
phoneNumber: String,
passwordlessType: PasswordlessType,
connection: String = SMS_CONNECTION
): Request<Void?, AuthenticationException> {
val parameters = ParameterBuilder.newBuilder()
.set(PHONE_NUMBER_KEY, phoneNumber)
.setSend(passwordlessType)
.setConnection(connection)
.asDictionary()
return passwordless()
.addParameters(parameters)
}
/**
* Start a custom passwordless flow
*
* @return a request to configure and start
*/
private fun passwordless(): Request<Void?, AuthenticationException> {
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(PASSWORDLESS_PATH)
.addPathSegment(START_PATH)
.build()
val parameters = ParameterBuilder.newBuilder()
.setClientId(clientId)
.asDictionary()
return factory.post(url.toString())
.addParameters(parameters)
}
/**
* Fetch the user's profile after it's authenticated by a login request.
* If the login request fails, the returned request will fail
*
* @param authenticationRequest that will authenticate a user with Auth0 and return a [Credentials]
* @return a [ProfileRequest] that first logs in and then fetches the profile
*/
public fun getProfileAfter(authenticationRequest: AuthenticationRequest): ProfileRequest {
return ProfileRequest(authenticationRequest, profileRequest())
}
/**
* Fetch the token information from Auth0, using the authorization_code grant type
* The authorization code received from the Auth0 server and the code verifier used
* to generate the challenge sent to the /authorize call must be provided.
*
* Example usage:
*
* ```
* client
* .token("authorization code", "code verifier", "redirect_uri")
* .start(object: Callback<Credentials, AuthenticationException> {...})
* ```
*
* @param authorizationCode the authorization code received from the /authorize call.
* @param codeVerifier the code verifier used to generate the code challenge sent to /authorize.
* @param redirectUri the uri sent to /authorize as the 'redirect_uri'.
* @return a request to obtain access_token by exchanging an authorization code.
*/
public fun token(
authorizationCode: String,
codeVerifier: String,
redirectUri: String
): Request<Credentials, AuthenticationException> {
val parameters = ParameterBuilder.newBuilder()
.setClientId(clientId)
.setGrantType(ParameterBuilder.GRANT_TYPE_AUTHORIZATION_CODE)
.set(OAUTH_CODE_KEY, authorizationCode)
.set(REDIRECT_URI_KEY, redirectUri)
.set("code_verifier", codeVerifier)
.asDictionary()
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(OAUTH_PATH)
.addPathSegment(TOKEN_PATH)
.build()
val credentialsAdapter: JsonAdapter<Credentials> = GsonAdapter(
Credentials::class.java, gson
)
val request = factory.post(url.toString(), credentialsAdapter)
request.addParameters(parameters)
return request
}
/**
* Creates a new Request to obtain the JSON Web Keys associated with the Auth0 account under the given domain.
* Only supports RSA keys used for signatures (Public Keys).
*
* @return a request to obtain the JSON Web Keys associated with this Auth0 account.
*/
public fun fetchJsonWebKeys(): Request<Map<String, PublicKey>, AuthenticationException> {
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(WELL_KNOWN_PATH)
.addPathSegment(JWKS_FILE_PATH)
.build()
val jwksAdapter: JsonAdapter<Map<String, PublicKey>> = forMapOf(
PublicKey::class.java, gson
)
return factory.get(url.toString(), jwksAdapter)
}
/**
* Helper function to make a request to the /oauth/token endpoint.
*/
private fun loginWithToken(parameters: Map<String, String>): AuthenticationRequest {
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(OAUTH_PATH)
.addPathSegment(TOKEN_PATH)
.build()
val requestParameters = ParameterBuilder.newBuilder()
.setClientId(clientId)
.addAll(parameters)
.asDictionary()
val credentialsAdapter: JsonAdapter<Credentials> = GsonAdapter(
Credentials::class.java, gson
)
val request = BaseAuthenticationRequest(factory.post(url.toString(), credentialsAdapter), clientId, baseURL)
request.addParameters(requestParameters)
return request
}
private fun profileRequest(): Request<UserProfile, AuthenticationException> {
val url = auth0.getDomainUrl().toHttpUrl().newBuilder()
.addPathSegment(USER_INFO_PATH)
.build()
val userProfileAdapter: JsonAdapter<UserProfile> = GsonAdapter(
UserProfile::class.java, gson
)
return factory.get(url.toString(), userProfileAdapter)
}
private companion object {
private const val SMS_CONNECTION = "sms"
private const val EMAIL_CONNECTION = "email"
private const val USERNAME_KEY = "username"
private const val PASSWORD_KEY = "password"
private const val EMAIL_KEY = "email"
private const val PHONE_NUMBER_KEY = "phone_number"
private const val OAUTH_CODE_KEY = "code"
private const val REDIRECT_URI_KEY = "redirect_uri"
private const val TOKEN_KEY = "token"
private const val MFA_TOKEN_KEY = "mfa_token"
private const val ONE_TIME_PASSWORD_KEY = "otp"
private const val OUT_OF_BAND_CODE_KEY = "oob_code"
private const val BINDING_CODE_KEY = "binding_code"
private const val CHALLENGE_TYPE_KEY = "challenge_type"
private const val AUTHENTICATOR_ID_KEY = "authenticator_id"
private const val RECOVERY_CODE_KEY = "recovery_code"
private const val SUBJECT_TOKEN_KEY = "subject_token"
private const val SUBJECT_TOKEN_TYPE_KEY = "subject_token_type"
private const val USER_METADATA_KEY = "user_metadata"
private const val SIGN_UP_PATH = "signup"
private const val DB_CONNECTIONS_PATH = "dbconnections"
private const val CHANGE_PASSWORD_PATH = "change_password"
private const val PASSWORDLESS_PATH = "passwordless"
private const val START_PATH = "start"
private const val OAUTH_PATH = "oauth"
private const val TOKEN_PATH = "token"
private const val USER_INFO_PATH = "userinfo"
private const val REVOKE_PATH = "revoke"
private const val MFA_PATH = "mfa"
private const val CHALLENGE_PATH = "challenge"
private const val HEADER_AUTHORIZATION = "Authorization"
private const val WELL_KNOWN_PATH = ".well-known"
private const val JWKS_FILE_PATH = "jwks.json"
private fun createErrorAdapter(): ErrorAdapter<AuthenticationException> {
val mapAdapter = forMap(GsonProvider.gson)
return object : ErrorAdapter<AuthenticationException> {
override fun fromRawResponse(
statusCode: Int,
bodyText: String,
headers: Map<String, List<String>>
): AuthenticationException {
return AuthenticationException(bodyText, statusCode)
}
@Throws(IOException::class)
override fun fromJsonResponse(
statusCode: Int,
reader: Reader
): AuthenticationException {
val values = mapAdapter.fromJson(reader)
return AuthenticationException(values, statusCode)
}
override fun fromException(cause: Throwable): AuthenticationException {
return AuthenticationException(
"Something went wrong",
Auth0Exception("Something went wrong", cause)
)
}
}
}
}
init {
val auth0UserAgent = auth0.auth0UserAgent
factory.setAuth0ClientInfo(auth0UserAgent.value)
}
}
|
mit
|
d1bc32ae961dd0f69b1148b263219297
| 41.702539 | 216 | 0.64221 | 4.712303 | false | false | false | false |
Maccimo/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinFunctionProcessor.kt
|
2
|
12386
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.rename
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Pass
import com.intellij.psi.*
import com.intellij.psi.search.SearchScope
import com.intellij.refactoring.listeners.RefactoringElementListener
import com.intellij.refactoring.rename.*
import com.intellij.refactoring.util.CommonRefactoringUtil
import com.intellij.refactoring.util.RefactoringUtil
import com.intellij.usageView.UsageInfo
import com.intellij.util.SmartList
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.refactoring.*
import org.jetbrains.kotlin.idea.references.KtReference
import org.jetbrains.kotlin.idea.search.declarationsSearch.findDeepestSuperMethodsKotlinAware
import org.jetbrains.kotlin.idea.search.declarationsSearch.findDeepestSuperMethodsNoWrapping
import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachOverridingMethod
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.liftToExpected
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.DescriptorUtils
class RenameKotlinFunctionProcessor : RenameKotlinPsiProcessor() {
private val javaMethodProcessorInstance = RenameJavaMethodProcessor()
override fun canProcessElement(element: PsiElement): Boolean {
return element is KtNamedFunction || (element is KtLightMethod && element.kotlinOrigin is KtNamedFunction) || element is FunctionWithSupersWrapper
}
override fun isToSearchInComments(psiElement: PsiElement) = KotlinRefactoringSettings.instance.RENAME_SEARCH_IN_COMMENTS_FOR_METHOD
override fun setToSearchInComments(element: PsiElement, enabled: Boolean) {
KotlinRefactoringSettings.instance.RENAME_SEARCH_IN_COMMENTS_FOR_METHOD = enabled
}
override fun isToSearchForTextOccurrences(element: PsiElement) = KotlinRefactoringSettings.instance.RENAME_SEARCH_FOR_TEXT_FOR_METHOD
override fun setToSearchForTextOccurrences(element: PsiElement, enabled: Boolean) {
KotlinRefactoringSettings.instance.RENAME_SEARCH_FOR_TEXT_FOR_METHOD = enabled
}
private fun getJvmName(element: PsiElement): String? {
val descriptor = (element.unwrapped as? KtFunction)?.unsafeResolveToDescriptor() as? FunctionDescriptor ?: return null
return DescriptorUtils.getJvmName(descriptor)
}
protected fun processFoundReferences(
element: PsiElement,
allReferences: Collection<PsiReference>
): Collection<PsiReference> {
return when {
getJvmName(element) == null -> allReferences
element is KtElement -> allReferences.filterIsInstance<KtReference>()
element is KtLightElement<*, *> -> allReferences.filterNot { it is KtReference }
else -> emptyList()
}
}
override fun findCollisions(
element: PsiElement,
newName: String,
allRenames: Map<out PsiElement, String>,
result: MutableList<UsageInfo>
) {
val declaration = element.unwrapped as? KtNamedFunction ?: return
checkConflictsAndReplaceUsageInfos(element, allRenames, result)
result += SmartList<UsageInfo>().also { collisions ->
checkRedeclarations(declaration, newName, collisions)
checkOriginalUsagesRetargeting(declaration, newName, result, collisions)
checkNewNameUsagesRetargeting(declaration, newName, collisions)
}
}
class FunctionWithSupersWrapper(
val originalDeclaration: KtNamedFunction,
val supers: List<PsiElement>
) : KtLightElement<KtNamedFunction, KtNamedFunction>, PsiNamedElement by originalDeclaration {
override val kotlinOrigin: KtNamedFunction
get() = originalDeclaration
override val clsDelegate: KtNamedFunction
get() = originalDeclaration
}
private fun substituteForExpectOrActual(element: PsiElement?) =
(element?.namedUnwrappedElement as? KtNamedDeclaration)?.liftToExpected()
override fun substituteElementToRename(element: PsiElement, editor: Editor?): PsiElement? {
substituteForExpectOrActual(element)?.let { return it }
val wrappedMethod = wrapPsiMethod(element) ?: return element
val deepestSuperMethods = findDeepestSuperMethodsKotlinAware(wrappedMethod)
val substitutedJavaElement = when {
deepestSuperMethods.isEmpty() -> return element
wrappedMethod.isConstructor || deepestSuperMethods.size == 1 || element !is KtNamedFunction -> {
javaMethodProcessorInstance.substituteElementToRename(wrappedMethod, editor)
}
else -> {
val chosenElements = checkSuperMethods(element, null, KotlinBundle.message("text.rename.as.part.of.phrase"))
if (chosenElements.size > 1) FunctionWithSupersWrapper(element, chosenElements) else wrappedMethod
}
}
if (substitutedJavaElement is KtLightMethod && element is KtDeclaration) {
return substitutedJavaElement.kotlinOrigin as? KtNamedFunction
}
val canRename = try {
PsiElementRenameHandler.canRename(element.project, editor, substitutedJavaElement)
} catch (e: CommonRefactoringUtil.RefactoringErrorHintException) {
false
}
return if (canRename) substitutedJavaElement else element
}
override fun substituteElementToRename(element: PsiElement, editor: Editor, renameCallback: Pass<PsiElement>) {
fun preprocessAndPass(substitutedJavaElement: PsiElement) {
val elementToProcess = if (substitutedJavaElement is KtLightMethod && element is KtDeclaration) {
substitutedJavaElement.kotlinOrigin as? KtNamedFunction
} else {
substitutedJavaElement
}
renameCallback.pass(elementToProcess)
}
substituteForExpectOrActual(element)?.let { return preprocessAndPass(it) }
val wrappedMethod = wrapPsiMethod(element)
val deepestSuperMethods = if (wrappedMethod != null) {
findDeepestSuperMethodsKotlinAware(wrappedMethod)
} else {
findDeepestSuperMethodsNoWrapping(element)
}
when {
deepestSuperMethods.isEmpty() -> preprocessAndPass(element)
wrappedMethod != null && (wrappedMethod.isConstructor || element !is KtNamedFunction) -> {
javaMethodProcessorInstance.substituteElementToRename(wrappedMethod, editor, Pass(::preprocessAndPass))
}
else -> {
val declaration = element.unwrapped as? KtNamedFunction ?: return
checkSuperMethodsWithPopup(declaration, deepestSuperMethods.toList(), editor) {
preprocessAndPass(if (it.size > 1) FunctionWithSupersWrapper(declaration, it) else wrappedMethod ?: element)
}
}
}
}
override fun createRenameDialog(
project: Project,
element: PsiElement,
nameSuggestionContext: PsiElement?,
editor: Editor?
): RenameDialog {
val elementForDialog = (element as? FunctionWithSupersWrapper)?.originalDeclaration ?: element
return object : RenameDialog(project, elementForDialog, nameSuggestionContext, editor) {
override fun createRenameProcessor(newName: String) =
RenameProcessor(getProject(), element, newName, isSearchInComments, isSearchInNonJavaFiles)
}
}
override fun prepareRenaming(element: PsiElement, newName: String, allRenames: MutableMap<PsiElement, String>, scope: SearchScope) {
super.prepareRenaming(element, newName, allRenames, scope)
if (element is KtLightMethod && getJvmName(element) == null) {
(element.kotlinOrigin as? KtNamedFunction)?.let { allRenames[it] = newName }
}
if (element is FunctionWithSupersWrapper) {
allRenames.remove(element)
}
val originalName = (element.unwrapped as? KtNamedFunction)?.name ?: return
for (declaration in ((element as? FunctionWithSupersWrapper)?.supers ?: listOf(element))) {
val psiMethod = wrapPsiMethod(declaration) ?: continue
allRenames[declaration] = newName
val baseName = psiMethod.name
val newBaseName = if (KotlinTypeMapper.InternalNameMapper.demangleInternalName(baseName) == originalName) {
KotlinTypeMapper.InternalNameMapper.mangleInternalName(
newName,
KotlinTypeMapper.InternalNameMapper.getModuleNameSuffix(baseName)!!
)
} else newName
if (psiMethod.containingClass != null) {
psiMethod.forEachOverridingMethod(scope) {
val overrider = (it as? PsiMirrorElement)?.prototype as? PsiMethod ?: it
if (overrider is SyntheticElement) return@forEachOverridingMethod true
val overriderName = overrider.name
val newOverriderName = RefactoringUtil.suggestNewOverriderName(overriderName, baseName, newBaseName)
if (newOverriderName != null) {
RenameUtil.assertNonCompileElement(overrider)
allRenames[overrider] = newOverriderName
}
return@forEachOverridingMethod true
}
}
}
ForeignUsagesRenameProcessor.prepareRenaming(element, newName, allRenames, scope)
}
override fun renameElement(element: PsiElement, newName: String, usages: Array<UsageInfo>, listener: RefactoringElementListener?) {
val simpleUsages = ArrayList<UsageInfo>(usages.size)
val ambiguousImportUsages = SmartList<UsageInfo>()
val simpleImportUsages = SmartList<UsageInfo>()
ForeignUsagesRenameProcessor.processAll(element, newName, usages, fallbackHandler = { usage ->
if (usage is LostDefaultValuesInOverridingFunctionUsageInfo) {
usage.apply()
return@processAll
}
when (usage.importState()) {
ImportState.AMBIGUOUS -> ambiguousImportUsages += usage
ImportState.SIMPLE -> simpleImportUsages += usage
ImportState.NOT_IMPORT -> {
if (!renameMangledUsageIfPossible(usage, element, newName)) {
simpleUsages += usage
}
}
}
})
element.ambiguousImportUsages = ambiguousImportUsages
val usagesToRename = if (simpleImportUsages.isEmpty()) simpleUsages else simpleImportUsages + simpleUsages
RenameUtil.doRenameGenericNamedElement(element, newName, usagesToRename.toTypedArray(), listener)
usages.forEach { (it as? KtResolvableCollisionUsageInfo)?.apply() }
(element.unwrapped as? KtNamedDeclaration)?.let(::dropOverrideKeywordIfNecessary)
}
private fun wrapPsiMethod(element: PsiElement?): PsiMethod? = when (element) {
is PsiMethod -> element
is KtNamedFunction, is KtSecondaryConstructor -> runReadAction {
LightClassUtil.getLightClassMethod(element as KtFunction)
}
else -> throw IllegalStateException("Can't be for element $element there because of canProcessElement()")
}
override fun findReferences(
element: PsiElement,
searchScope: SearchScope,
searchInCommentsAndStrings: Boolean
): Collection<PsiReference> {
val references = super.findReferences(element, searchScope, searchInCommentsAndStrings)
return processFoundReferences(element, references)
}
}
|
apache-2.0
|
bc039b4d3410ca4f523e4015f7820226
| 46.274809 | 154 | 0.698369 | 5.531934 | false | false | false | false |
k9mail/k-9
|
app/core/src/main/java/com/fsck/k9/job/MailSyncWorkerManager.kt
|
2
|
3207
|
package com.fsck.k9.job
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.workDataOf
import com.fsck.k9.Account
import com.fsck.k9.Clock
import com.fsck.k9.K9
import java.util.concurrent.TimeUnit
import timber.log.Timber
class MailSyncWorkerManager(private val workManager: WorkManager, val clock: Clock) {
fun cancelMailSync(account: Account) {
Timber.v("Canceling mail sync worker for %s", account)
val uniqueWorkName = createUniqueWorkName(account.uuid)
workManager.cancelUniqueWork(uniqueWorkName)
}
fun scheduleMailSync(account: Account) {
if (isNeverSyncInBackground()) return
getSyncIntervalIfEnabled(account)?.let { syncIntervalMinutes ->
Timber.v("Scheduling mail sync worker for %s", account)
Timber.v(" sync interval: %d minutes", syncIntervalMinutes)
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresStorageNotLow(true)
.build()
val lastSyncTime = account.lastSyncTime
Timber.v(" last sync time: %tc", lastSyncTime)
val initialDelay = calculateInitialDelay(lastSyncTime, syncIntervalMinutes)
Timber.v(" initial delay: %d ms", initialDelay)
val data = workDataOf(MailSyncWorker.EXTRA_ACCOUNT_UUID to account.uuid)
val mailSyncRequest = PeriodicWorkRequestBuilder<MailSyncWorker>(syncIntervalMinutes, TimeUnit.MINUTES)
.setInitialDelay(initialDelay, TimeUnit.MILLISECONDS)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, INITIAL_BACKOFF_DELAY_MINUTES, TimeUnit.MINUTES)
.setConstraints(constraints)
.setInputData(data)
.addTag(MAIL_SYNC_TAG)
.build()
val uniqueWorkName = createUniqueWorkName(account.uuid)
workManager.enqueueUniquePeriodicWork(uniqueWorkName, ExistingPeriodicWorkPolicy.REPLACE, mailSyncRequest)
}
}
private fun isNeverSyncInBackground() = K9.backgroundOps == K9.BACKGROUND_OPS.NEVER
private fun getSyncIntervalIfEnabled(account: Account): Long? {
val intervalMinutes = account.automaticCheckIntervalMinutes
if (intervalMinutes <= Account.INTERVAL_MINUTES_NEVER) {
return null
}
return intervalMinutes.toLong()
}
private fun calculateInitialDelay(lastSyncTime: Long, syncIntervalMinutes: Long): Long {
val now = clock.time
val nextSyncTime = lastSyncTime + (syncIntervalMinutes * 60L * 1000L)
return if (lastSyncTime > now || nextSyncTime <= now) {
0L
} else {
nextSyncTime - now
}
}
private fun createUniqueWorkName(accountUuid: String): String {
return "$MAIL_SYNC_TAG:$accountUuid"
}
companion object {
const val MAIL_SYNC_TAG = "MailSync"
private const val INITIAL_BACKOFF_DELAY_MINUTES = 5L
}
}
|
apache-2.0
|
e2b40d1e25c0900b9010f1b5a0a9fd7e
| 35.862069 | 118 | 0.683193 | 4.75816 | false | false | false | false |
futurice/freesound-android
|
app/src/main/java/com/futurice/freesound/arch/mvi/LoggingTransitionObserver.kt
|
1
|
820
|
package com.futurice.freesound.arch.mvi
import timber.log.Timber
class LoggingTransitionObserver : TransitionObserver {
override fun onTransition(tag: String, transitionEvent: TransitionEvent) {
when (transitionEvent) {
is TransitionEvent.Event -> Timber.d("MVI|$tag| Event => $transitionEvent")
is TransitionEvent.Action -> Timber.d("MVI|$tag| Action => $transitionEvent")
is TransitionEvent.Result -> Timber.d("MVI|$tag| Result => $transitionEvent")
is TransitionEvent.Reduce -> Timber.d("MVI|$tag| Reduce => $transitionEvent")
is TransitionEvent.State -> Timber.d("MVI|$tag| State => $transitionEvent")
is TransitionEvent.Error -> Timber.e(transitionEvent.throwable, "MVI|$tag| Fatal Error => $transitionEvent")
}
}
}
|
apache-2.0
|
9094b1d1e9b1346d52f7c16f69b15adf
| 47.235294 | 120 | 0.669512 | 4.059406 | false | false | false | false |
mdaniel/intellij-community
|
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/ArtifactOutputPackagingElementEntityImpl.kt
|
1
|
10951
|
package com.intellij.workspaceModel.storage.bridgeEntities.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.SoftLinkable
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent
import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ArtifactOutputPackagingElementEntityImpl: ArtifactOutputPackagingElementEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java, PackagingElementEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val parentEntity: CompositePackagingElementEntity?
get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this)
@JvmField var _artifact: ArtifactId? = null
override val artifact: ArtifactId?
get() = _artifact
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ArtifactOutputPackagingElementEntityData?): ModifiableWorkspaceEntityBase<ArtifactOutputPackagingElementEntity>(), ArtifactOutputPackagingElementEntity.Builder {
constructor(): this(ArtifactOutputPackagingElementEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ArtifactOutputPackagingElementEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field ArtifactOutputPackagingElementEntity#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var parentEntity: CompositePackagingElementEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity
} else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override var artifact: ArtifactId?
get() = getEntityData().artifact
set(value) {
checkModificationAllowed()
getEntityData().artifact = value
changedProperty.add("artifact")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override fun getEntityData(): ArtifactOutputPackagingElementEntityData = result ?: super.getEntityData() as ArtifactOutputPackagingElementEntityData
override fun getEntityClass(): Class<ArtifactOutputPackagingElementEntity> = ArtifactOutputPackagingElementEntity::class.java
}
}
class ArtifactOutputPackagingElementEntityData : WorkspaceEntityData<ArtifactOutputPackagingElementEntity>(), SoftLinkable {
var artifact: ArtifactId? = null
override fun getLinks(): Set<PersistentEntityId<*>> {
val result = HashSet<PersistentEntityId<*>>()
val optionalLink_artifact = artifact
if (optionalLink_artifact != null) {
result.add(optionalLink_artifact)
}
return result
}
override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
val optionalLink_artifact = artifact
if (optionalLink_artifact != null) {
index.index(this, optionalLink_artifact)
}
}
override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
// TODO verify logic
val mutablePreviousSet = HashSet(prev)
val optionalLink_artifact = artifact
if (optionalLink_artifact != null) {
val removedItem_optionalLink_artifact = mutablePreviousSet.remove(optionalLink_artifact)
if (!removedItem_optionalLink_artifact) {
index.index(this, optionalLink_artifact)
}
}
for (removed in mutablePreviousSet) {
index.remove(this, removed)
}
}
override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean {
var changed = false
var artifact_data_optional = if (artifact != null) {
val artifact___data = if (artifact!! == oldLink) {
changed = true
newLink as ArtifactId
}
else {
null
}
artifact___data
}
else {
null
}
if (artifact_data_optional != null) {
artifact = artifact_data_optional
}
return changed
}
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ArtifactOutputPackagingElementEntity> {
val modifiable = ArtifactOutputPackagingElementEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ArtifactOutputPackagingElementEntity {
val entity = ArtifactOutputPackagingElementEntityImpl()
entity._artifact = artifact
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ArtifactOutputPackagingElementEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ArtifactOutputPackagingElementEntityData
if (this.artifact != other.artifact) return false
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ArtifactOutputPackagingElementEntityData
if (this.artifact != other.artifact) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + artifact.hashCode()
return result
}
}
|
apache-2.0
|
e6c2ec0f0f9e196fb1d8f33e44b13d6f
| 40.961686 | 220 | 0.645603 | 6.201019 | false | false | false | false |
MRylander/RylandersRealm
|
src/main/kotlin/rylandersrealm/Environment/Location.kt
|
1
|
5467
|
/*
* Copyright 2017 Michael S Rylander
*
* 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 rylandersrealm.Environment
import com.google.common.base.MoreObjects
import org.slf4j.LoggerFactory
import rylandersrealm.Invalid
import rylandersrealm.Player.Player
import rylandersrealm.Unknown
import rylandersrealm.target.Entrance
import rylandersrealm.target.Targetable
import java.util.concurrent.atomic.AtomicInteger
//TODO add locationName to us instead of 'room'
class Location(private val description: String = "default description", private val targets: MutableList<Targetable> = mutableListOf()) {
private val LOG = LoggerFactory.getLogger(this::class.java)
private val targetCounter = AtomicInteger()
//TODO combine entrances and targets... probably
val entrances = mutableListOf<Entrance>()
/**
* @return A [Targetable] when there is exactly one valid target with a matching name, otherwise
* [Invalid.TARGETABLE] will be returned.
*/
fun findTargetableByString(target: String): Targetable {
val targetsFound = (targets + entrances).filter { target.toLowerCase().contains(it.name.toLowerCase()) }
return handTargets(targetsFound, target)
}
/**
* @return A [Targetable] when there is exactly one valid target with a matching target number, otherwise
* [Invalid.TARGETABLE] will be returned.
*/
fun findTargetableByTargetNumber(targetNumber:Int): Targetable{
val targetsFound = (targets + entrances).filter { it.targetNumber == targetNumber}
return handTargets(targetsFound, targetNumber.toString())
}
private fun handTargets(targets: Collection<Targetable>, searchString: String): Targetable {
LOG.debug("targetFound=$targets")
return when {
targets.size == 1 -> targets.first()
targets.isEmpty() -> {
LOG.debug("Could not find '$searchString', valid targets are: $targets")
Invalid.TARGETABLE
}
else -> {
LOG.debug("Too many valid targets found for '$searchString', valid targets are: $targets")
Invalid.TARGETABLE
}
}
}
fun addTarget(targetable: Targetable): Location {
targets.add(targetable)
targetable.targetNumber = targetCounter.incrementAndGet()
return this
}
@Deprecated("old - might be removed or added to getRoomDescription")
fun getDescription(): String {
val stringBuilder = StringBuilder(description)
stringBuilder.append("\nThere is ")
for (target in targets) {
stringBuilder.append("\n a ${target.name}")
}
return stringBuilder.toString()
}
fun getDescription(player: Player): String {
return "${getEntryDescription(player)} ${getRoomDescription()} ${getExitDescription(player)}"
}
fun getRoomDescription(): String {
return description.trim()
}
fun addEntrance(entrance: Entrance) {
if (entrance != Unknown.ENTRANCE) {
entrances.add(entrance)
entrance.targetNumber = targetCounter.incrementAndGet()
} else {
LOG.warn("Attempted to add an 'Unknown Entrance' to a location.")
}
}
fun getEntryDescription(player: Player): String {
return if (player.lastEntranceUsed != Unknown.ENTRANCE) {
"You entered the room via a ${player.lastEntranceUsed.name}[${player.lastEntranceUsed.targetNumber}] to the ${player.lastEntranceUsed.orientation}."
} else {
"You have no idea how you got here."
}
}
fun getExitDescription(player: Player): String {
val exits: List<Entrance?> = entrances - player.lastEntranceUsed
val description = if (exits.size > 0) {
exits.foldIndexed(StringBuilder(),
{ index, stringBuilder, exit ->
stringBuilder.append(when (index) {
0 -> "There is another ${exit?.name}[${exits.first()?.targetNumber}] to the ${exit?.orientation}"
in 1 until exits.lastIndex -> ", a ${exit?.name}[${exit?.targetNumber}] to the ${exit?.orientation}"
exits.lastIndex -> ", and a ${exit?.name}[${exit?.targetNumber}] to the ${exit?.orientation}."
else -> throw IndexOutOfBoundsException("$index, not in exits list of size ${exits.size}.")
})
})
} else {
StringBuilder("There are no other entrances.")
}
// handles case if there is only one exit.
if (!description.endsWith(".")) {
description.append(".")
}
return description.toString()
}
override fun toString(): String {
return MoreObjects.toStringHelper(this)
.add("description", description)
.toString()
}
}
|
apache-2.0
|
c5afb73e01c03b9c66c9fc6618d877cd
| 38.338129 | 160 | 0.638376 | 4.609612 | false | false | false | false |
Doctoror/PainlessMusicPlayer
|
presentation/src/main/java/com/doctoror/fuckoffmusicplayer/presentation/library/albums/AlbumsFragment.kt
|
2
|
3956
|
/*
* Copyright (C) 2016 Yaroslav Mytkalyk
*
* 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.doctoror.fuckoffmusicplayer.presentation.library.albums
import android.content.res.Configuration
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import com.bumptech.glide.Glide
import com.doctoror.fuckoffmusicplayer.R
import com.doctoror.fuckoffmusicplayer.domain.albums.AlbumsProvider
import com.doctoror.fuckoffmusicplayer.domain.queue.QueueProviderAlbums
import com.doctoror.fuckoffmusicplayer.presentation.library.LibraryListFragment
import com.doctoror.fuckoffmusicplayer.presentation.widget.SpacesItemDecoration
import dagger.android.support.AndroidSupportInjection
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
class AlbumsFragment : LibraryListFragment() {
@Inject
lateinit var albumClickHandler: AlbumClickHandler
@Inject
lateinit var albumsProvider: AlbumsProvider
@Inject
lateinit var queueProvider: QueueProviderAlbums
private var recyclerView: RecyclerView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AndroidSupportInjection.inject(this)
}
override fun obtainConfig() = Config(
canShowEmptyView = true,
dataSource = { albumsProvider.load(it, Schedulers.io()) },
emptyMessage = getText(R.string.No_albums_found),
recyclerAdapter = createRecyclerAdapter()
)
override fun setupRecyclerView(recyclerView: RecyclerView) {
this.recyclerView = recyclerView
applyLayoutManager(recyclerView)
recyclerView.addItemDecoration(SpacesItemDecoration(
resources.getDimensionPixelSize(R.dimen.album_grid_spacing)))
}
private fun createRecyclerAdapter(): AlbumsRecyclerAdapter {
val context = activity ?: throw IllegalStateException("Activity is null")
val adapter = AlbumsRecyclerAdapter(context, Glide.with(this))
adapter.setOnAlbumClickListener(object : AlbumsRecyclerAdapter.OnAlbumClickListener {
override fun onAlbumClick(position: Int, id: Long, album: String) {
[email protected](position, id, album)
}
override fun onAlbumDeleteClick(id: Long, name: String?) {
[email protected](id, name)
}
})
return adapter
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
recyclerView?.let { applyLayoutManager(it) }
}
private fun applyLayoutManager(recyclerView: RecyclerView) {
recyclerView.layoutManager = GridLayoutManager(activity,
resources.getInteger(R.integer.albums_grid_columns))
}
private fun onAlbumDeleteClick(albumId: Long, name: String?) {
val context = activity ?: throw IllegalStateException("Activity is null")
val fragmentManager = fragmentManager
?: throw IllegalStateException("FragmentManager is null")
DeleteAlbumDialogFragment.show(context, fragmentManager, albumId, name)
}
private fun onAlbumClick(position: Int, albumId: Long,
albumName: String?) {
albumClickHandler.onAlbumClick(albumId, albumName) { getItemView(position) }
}
}
|
apache-2.0
|
f74a90c610ef715dce56a606e536fcae
| 38.168317 | 93 | 0.726997 | 5.097938 | false | true | false | false |
WhisperSystems/Signal-Android
|
app/src/main/java/org/thoughtcrime/securesms/keyboard/emoji/EmojiPageModelExtensions.kt
|
1
|
951
|
package org.thoughtcrime.securesms.keyboard.emoji
import org.thoughtcrime.securesms.components.emoji.EmojiPageModel
import org.thoughtcrime.securesms.components.emoji.EmojiPageViewGridAdapter
import org.thoughtcrime.securesms.components.emoji.RecentEmojiPageModel
import org.thoughtcrime.securesms.components.emoji.parsing.EmojiTree
import org.thoughtcrime.securesms.emoji.EmojiCategory
import org.thoughtcrime.securesms.emoji.EmojiSource
import org.thoughtcrime.securesms.util.MappingModel
fun EmojiPageModel.toMappingModels(): List<MappingModel<*>> {
val emojiTree: EmojiTree = EmojiSource.latest.emojiTree
return displayEmoji.map {
val isTextEmoji = EmojiCategory.EMOTICONS.key == key || (RecentEmojiPageModel.KEY == key && emojiTree.getEmoji(it.value, 0, it.value.length) == null)
if (isTextEmoji) {
EmojiPageViewGridAdapter.EmojiTextModel(key, it)
} else {
EmojiPageViewGridAdapter.EmojiModel(key, it)
}
}
}
|
gpl-3.0
|
ba3f924c4aa8546e6719d6f70c2900ab
| 40.347826 | 153 | 0.802313 | 4.264574 | false | false | false | false |
square/picasso
|
picasso/src/main/java/com/squareup/picasso3/FileRequestHandler.kt
|
1
|
1973
|
/*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.picasso3
import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import androidx.exifinterface.media.ExifInterface
import com.squareup.picasso3.BitmapUtils.decodeStream
import com.squareup.picasso3.Picasso.LoadedFrom.DISK
import java.io.FileNotFoundException
internal class FileRequestHandler(context: Context) : ContentStreamRequestHandler(context) {
override fun canHandleRequest(data: Request): Boolean {
val uri = data.uri
return uri != null && ContentResolver.SCHEME_FILE == uri.scheme
}
override fun load(
picasso: Picasso,
request: Request,
callback: Callback
) {
var signaledCallback = false
try {
val requestUri = checkNotNull(request.uri)
val source = getSource(requestUri)
val bitmap = decodeStream(source, request)
val exifRotation = getExifOrientation(requestUri)
signaledCallback = true
callback.onSuccess(Result.Bitmap(bitmap, DISK, exifRotation))
} catch (e: Exception) {
if (!signaledCallback) {
callback.onError(e)
}
}
}
override fun getExifOrientation(uri: Uri): Int {
val path = uri.path ?: throw FileNotFoundException("path == null, uri: $uri")
return ExifInterface(path).getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL
)
}
}
|
apache-2.0
|
024a9a8905daeb468ee424b39ea1beda
| 32.440678 | 92 | 0.727319 | 4.326754 | false | false | false | false |
austinv11/D4JBot
|
src/main/kotlin/com/austinv11/d4j/bot/command/impl/UpdateCommand.kt
|
1
|
4063
|
package com.austinv11.d4j.bot.command.impl
import com.austinv11.d4j.bot.JAR_PATH
import com.austinv11.d4j.bot.LOGGER
import com.austinv11.d4j.bot.command.CommandExecutor
import com.austinv11.d4j.bot.command.Executor
import com.austinv11.d4j.bot.command.context
import com.austinv11.d4j.bot.extensions.buffer
import com.austinv11.d4j.bot.extensions.embed
import com.austinv11.d4j.bot.restart
import reactor.core.publisher.Mono
import java.io.File
import java.util.concurrent.TimeUnit
const val DOWNLOAD_URL = "https://jitpack.io/com/github/austinv11/D4JBot/-SNAPSHOT/D4JBot--SNAPSHOT-all.jar"
class UpdateCommand() : CommandExecutor() {
override val name: String = "update"
override val aliases: Array<String> = arrayOf("upgrade")
@Executor("Updates the bot to the latest version.", requiresOwner = true)
fun execute() {
LOGGER.info("Updating...")
val context = context
val channel = context.channel
val message = buffer {
val msg = channel.sendMessage(context.embed.withDesc("Updating the bot, please wait...").build())
return@buffer msg
}
channel.typingStatus = true
val currJar = File(JAR_PATH)
val temp = File.createTempFile("bot", ".jar")
currJar.renameTo(temp)
Mono.create<Boolean> {
try {
ProcessBuilder("wget", DOWNLOAD_URL).inheritIO().start().waitFor(5, TimeUnit.MINUTES)
it.success(true)
} catch (e: Exception) {
it.error(e)
}
}.doOnError({ true }, {
channel.typingStatus = false
LOGGER.warn("Unable to update!")
temp.renameTo(currJar)
buffer { message.edit(context.embed.withDesc("Update Failed!").build()) }
it.printStackTrace()
throw it
}).subscribe {
channel.typingStatus = false
LOGGER.info("Updated! Restarting...")
buffer { message.edit(context.embed.withDesc("Updated!").build()) }
temp.delete()
restart()
}
// DOWNLOAD_URL.download(currJar)
// .doOnError({ true }, {
// channel.typingStatus = false
// LOGGER.warn("Unable to update!")
// temp.renameTo(currJar)
// buffer { message.edit(context.embed.withDesc("Update Failed!").build()) }
// it.printStackTrace()
// throw it
// }).subscribe {
// channel.typingStatus = false
// LOGGER.info("Updated! Restarting...")
// buffer { message.edit(context.embed.withDesc("Updated!").build()) }
// temp.delete()
// restart()
// }
// DOWNLOAD_URL.httpDownload().destination { _, _ -> currJar }
// .responseString { request, response, result ->
// result.fold({ d ->
// LOGGER.info("Updated! Restarting...")
// buffer { message.edit(context.embed.withDesc("Updated!").build()) }
// temp.delete()
// restart()
// }, { err ->
// LOGGER.warn("Unable to update!")
// temp.renameTo(currJar)
// err.printStackTrace()
// throw err
// })
// temp.delete()
// channel.typingStatus = false
// }.timeout(5 * 60 * 1000)
// .timeoutRead(5 * 60 * 1000)
// .progress { readBytes, totalBytes ->
// val percentage = "%.2f".format((readBytes.toDouble()/totalBytes.toDouble()) * 100.toDouble()) + "%"
// try { message.edit(context.embed.withDesc("$percentage done").build()) } catch (e: RateLimitException) {}
// LOGGER.info("$percentage done")
// }
}
}
|
gpl-3.0
|
3e7a2d7a8145199a3021cfadf84c0929
| 39.63 | 127 | 0.528673 | 4.364125 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateConstructorFromSuperTypeCallActionFactory.kt
|
4
|
2811
|
// 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.createCallable
import com.intellij.psi.PsiClass
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ConstructorInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo
import org.jetbrains.kotlin.idea.refactoring.canRefactor
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtSuperTypeCallEntry
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.types.Variance
object CreateConstructorFromSuperTypeCallActionFactory : CreateCallableMemberFromUsageFactory<KtSuperTypeCallEntry>() {
override fun getElementOfInterest(diagnostic: Diagnostic): KtSuperTypeCallEntry? {
return diagnostic.psiElement.getStrictParentOfType<KtSuperTypeCallEntry>()
}
override fun createCallableInfo(element: KtSuperTypeCallEntry, diagnostic: Diagnostic): CallableInfo? {
val typeReference = element.calleeExpression.typeReference ?: return null
val project = element.project
val superType = typeReference.analyze()[BindingContext.TYPE, typeReference] ?: return null
val superClassDescriptor = superType.constructor.declarationDescriptor as? ClassDescriptor ?: return null
if (superClassDescriptor.kind != ClassKind.CLASS) return null
val targetClass = DescriptorToSourceUtilsIde.getAnyDeclaration(project, superClassDescriptor) ?: return null
if (!(targetClass.canRefactor() && (targetClass is KtClass || targetClass is PsiClass))) return null
val anyType = superClassDescriptor.builtIns.nullableAnyType
val parameters = element.valueArguments.map {
ParameterInfo(
it.getArgumentExpression()?.let { expression -> TypeInfo(expression, Variance.IN_VARIANCE) } ?: TypeInfo(
anyType,
Variance.IN_VARIANCE
),
it.getArgumentName()?.asName?.asString()
)
}
return ConstructorInfo(parameters, targetClass)
}
}
|
apache-2.0
|
c4e141cf6b05ee6f4b11d4a182dbad57
| 53.057692 | 158 | 0.778015 | 5.395393 | false | false | false | false |
GunoH/intellij-community
|
plugins/devkit/devkit-kotlin-tests/testData/inspections/unsafeReturnStatementVisitor/UnsafeVisitReturnStatementUsedInJavaRecursiveElementWalkingVisitor.kt
|
2
|
3105
|
import com.intellij.psi.*
class UnsafeVisitReturnStatementUsedInJavaRecursiveElementWalkingVisitor {
fun methodUsingUnsafeVisitReturnStatementAndNoSafeMethodsPresent(element: PsiElement) {
element.accept(<warning descr="Recursive visitors with 'visitReturnStatement' most probably should specifically process anonymous/local classes ('visitClass') and lambda expressions ('visitLambdaExpression')">object</warning> : JavaRecursiveElementWalkingVisitor() {
override fun visitReturnStatement(statement: PsiReturnStatement) {
// do something
}
})
}
fun methodUsingUnsafeVisitReturnStatementButVisitClassPresent(element: PsiElement) {
element.accept(<warning descr="Recursive visitors with 'visitReturnStatement' most probably should specifically process anonymous/local classes ('visitClass') and lambda expressions ('visitLambdaExpression')">object</warning> : JavaRecursiveElementWalkingVisitor() {
override fun visitReturnStatement(statement: PsiReturnStatement) {
// do something
}
override fun visitClass(aClass: PsiClass) {
// do something
}
})
}
fun methodUsingUnsafeVisitReturnStatementButVisitLambdaExpressionPresent(element: PsiElement) {
element.accept(<warning descr="Recursive visitors with 'visitReturnStatement' most probably should specifically process anonymous/local classes ('visitClass') and lambda expressions ('visitLambdaExpression')">object</warning> : JavaRecursiveElementWalkingVisitor() {
override fun visitReturnStatement(statement: PsiReturnStatement) {
// do something
}
override fun visitLambdaExpression(expression: PsiLambdaExpression) {
// do something
}
})
}
}
class <warning descr="Recursive visitors with 'visitReturnStatement' most probably should specifically process anonymous/local classes ('visitClass') and lambda expressions ('visitLambdaExpression')">UnsafeVisitReturnStatementWalkingVisitor</warning> : JavaRecursiveElementWalkingVisitor() {
override fun visitReturnStatement(statement: PsiReturnStatement) {
// do something
}
}
class <warning descr="Recursive visitors with 'visitReturnStatement' most probably should specifically process anonymous/local classes ('visitClass') and lambda expressions ('visitLambdaExpression')">UnsafeVisitReturnStatementWalkingVisitorWithVisitLambdaExpression</warning> : JavaRecursiveElementWalkingVisitor() {
override fun visitReturnStatement(statement: PsiReturnStatement) {
// do something
}
override fun visitLambdaExpression(expression: PsiLambdaExpression) {
// do something
}
}
class <warning descr="Recursive visitors with 'visitReturnStatement' most probably should specifically process anonymous/local classes ('visitClass') and lambda expressions ('visitLambdaExpression')">UnsafeVisitReturnStatementWalkingVisitorWithVisitClass</warning> : JavaRecursiveElementWalkingVisitor() {
override fun visitReturnStatement(statement: PsiReturnStatement) {
// do something
}
override fun visitClass(aClass: PsiClass) {
// do something
}
}
|
apache-2.0
|
162e70904aebb53c26c0c721e8199169
| 49.901639 | 316 | 0.784219 | 5.814607 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/refactorings/rename.k2/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinRenameTargetProvider.kt
|
3
|
1962
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.rename
import com.intellij.model.Symbol
import com.intellij.model.psi.PsiSymbolService
import com.intellij.openapi.project.Project
import com.intellij.refactoring.rename.api.RenameTarget
import com.intellij.refactoring.rename.symbol.SymbolRenameTargetFactory
import org.jetbrains.kotlin.psi.*
internal class KotlinRenameTargetProvider : SymbolRenameTargetFactory {
override fun renameTarget(project: Project, symbol: Symbol): RenameTarget? {
val psiElement = PsiSymbolService.getInstance().extractElementFromSymbol(symbol)
val declaration = when (psiElement) {
is KtConstructor<*> -> psiElement.getContainingClassOrObject()
is KtNamedDeclaration -> psiElement
else -> null
}
if (declaration == null || !isRenameable(declaration)) return null
return KotlinNamedDeclarationRenameUsage.create(declaration)
}
/**
* Right now we want to restrict renaming to local declarations because we cannot properly
* rename declarations in Java (yet). Those restrictions will be lifted eventually.
*/
private fun isRenameable(psiElement: KtNamedDeclaration): Boolean = when {
!psiElement.isWritable -> false
psiElement is KtProperty && psiElement.isLocal -> true
psiElement is KtFunction && psiElement.isLocal -> true
psiElement is KtClass && psiElement.isLocal -> true
psiElement is KtParameter -> parameterIsRenameable(psiElement)
else -> false
}
private fun parameterIsRenameable(parameter: KtParameter): Boolean {
val parentFunction = (parameter.parent as? KtParameterList)?.parent as? KtFunction ?: return false
return parentFunction.isLocal || parentFunction is KtNamedFunction && parentFunction.isTopLevel
}
}
|
apache-2.0
|
7dcea4ba29f7d51ca255cc3c984074f3
| 40.744681 | 120 | 0.732926 | 5.274194 | false | false | false | false |
GunoH/intellij-community
|
java/execution/impl/src/com/intellij/execution/ui/DefaultJreSelector.kt
|
2
|
6991
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.ui
import com.intellij.application.options.ModuleDescriptionsComboBox
import com.intellij.application.options.ModulesComboBox
import com.intellij.execution.ExecutionBundle
import com.intellij.execution.configurations.JavaParameters
import com.intellij.execution.util.JavaParametersUtil
import com.intellij.java.JavaBundle
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.component1
import com.intellij.openapi.util.component2
import com.intellij.ui.EditorTextField
import com.intellij.ui.EditorTextFieldWithBrowseButton
import com.intellij.util.concurrency.NonUrgentExecutor
import org.jetbrains.annotations.Nls
import java.util.concurrent.Callable
import java.util.function.Consumer
abstract class DefaultJreSelector {
companion object {
@JvmStatic
fun projectSdk(project: Project): DefaultJreSelector = ProjectSdkSelector(project)
@JvmStatic
fun fromModuleDependencies(moduleComboBox: ModulesComboBox, productionOnly: Boolean): DefaultJreSelector
= SdkFromModuleDependencies(moduleComboBox, ModulesComboBox::getSelectedModule, {productionOnly})
@JvmStatic
fun fromModuleDependencies(moduleComboBox: ModuleDescriptionsComboBox, productionOnly: Boolean): DefaultJreSelector
= SdkFromModuleDependencies(moduleComboBox, ModuleDescriptionsComboBox::getSelectedModule, {productionOnly})
@JvmStatic
fun fromModuleDependencies(moduleComboBox: ModuleClasspathCombo, productionOnly: Boolean): DefaultJreSelector
= SdkFromModuleDependencies(moduleComboBox, ModuleClasspathCombo::getSelectedModule, {productionOnly})
@JvmStatic
fun fromSourceRootsDependencies(moduleComboBox: ModulesComboBox, classSelector: EditorTextFieldWithBrowseButton): DefaultJreSelector
= SdkFromSourceRootDependencies(moduleComboBox, ModulesComboBox::getSelectedModule, classSelector.childComponent)
@JvmStatic
fun fromSourceRootsDependencies(moduleComboBox: ModuleDescriptionsComboBox, classSelector: EditorTextFieldWithBrowseButton): DefaultJreSelector
= SdkFromSourceRootDependencies(moduleComboBox, ModuleDescriptionsComboBox::getSelectedModule, classSelector.childComponent)
@JvmStatic
fun fromSourceRootsDependencies(moduleComboBox: ModuleClasspathCombo, classSelector: EditorTextField): DefaultJreSelector
= SdkFromSourceRootDependencies(moduleComboBox, ModuleClasspathCombo::getSelectedModule, classSelector)
}
abstract fun getNameAndDescription(): Pair<String?, String>
open fun getVersion(): String? = null
open fun addChangeListener(listener: Runnable) {
}
open fun isValid(): Boolean = true
@Nls
fun getDescriptionString(): String {
val (name, description) = getNameAndDescription()
return " (${name ?: JavaBundle.message("no.jre.description")} - $description)"
}
class ProjectSdkSelector(val project: Project): DefaultJreSelector() {
override fun getNameAndDescription(): Pair<String?, String> = Pair.create(ProjectRootManager.getInstance(project).projectSdkName, "project SDK")
override fun getVersion(): String? = ProjectRootManager.getInstance(project).projectSdk?.versionString
override fun isValid(): Boolean = !project.isDisposed
}
open class SdkFromModuleDependencies<T: ComboBox<*>>(private val moduleComboBox: T, val getSelectedModule: (T) -> Module?, val productionOnly: () -> Boolean): DefaultJreSelector() {
override fun getNameAndDescription(): Pair<String?, String> {
val moduleNotSpecified = ExecutionBundle.message("module.not.specified")
val module = getSelectedModule(moduleComboBox) ?: return Pair.create(null, moduleNotSpecified)
val productionOnly = productionOnly()
val jdkToRun = JavaParameters.getJdkToRunModule(module, productionOnly)
val moduleJdk = ModuleRootManager.getInstance(module).sdk
if (moduleJdk == null || jdkToRun == null) {
return Pair.create(null, moduleNotSpecified)
}
if (moduleJdk.homeDirectory == jdkToRun.homeDirectory) {
return Pair.create(moduleJdk.name, ExecutionBundle.message("sdk.of.0.module", module.name))
}
return Pair.create(jdkToRun.name, ExecutionBundle.message("newest.sdk.from.0.module.1.choice.0.1.test.dependencies", module.name, if (productionOnly) 0 else 1))
}
override fun getVersion(): String? {
val module = getSelectedModule(moduleComboBox) ?: return null
return JavaParameters.getJdkToRunModule(module, productionOnly())?.versionString
}
override fun addChangeListener(listener: Runnable) {
moduleComboBox.addActionListener { listener.run() }
}
override fun isValid(): Boolean = when (val module = getSelectedModule(moduleComboBox)) {
null -> true
else -> !module.isDisposed
}
}
class SdkFromSourceRootDependencies<T: ComboBox<*>>(moduleComboBox: T, getSelectedModule: (T) -> Module?, private val classSelector: EditorTextField)
: SdkFromModuleDependencies<T>(moduleComboBox, getSelectedModule,
{ classSelector.getClientProperty(PRODUCTION_CACHED) as Boolean? == true }) {
init {
classSelector.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
ReadAction.nonBlocking(Callable {
isClassInProductionSources(moduleComboBox, getSelectedModule, classSelector)
}).expireWhen { !classSelector.isVisible }
.finishOnUiThread(ModalityState.defaultModalityState(), Consumer {
classSelector.putClientProperty(PRODUCTION_CACHED, it)
classSelector.invalidate()
classSelector.repaint()
}).submit(NonUrgentExecutor.getInstance())
}
})
}
override fun addChangeListener(listener: Runnable) {
super.addChangeListener(listener)
classSelector.addDocumentListener(object : DocumentListener {
override fun documentChanged(e: DocumentEvent) {
listener.run()
}
})
}
}
}
private fun <T: ComboBox<*>> isClassInProductionSources(moduleSelector: T, getSelectedModule: (T) -> Module?, classSelector: EditorTextField): Boolean {
val module = getSelectedModule(moduleSelector) ?: return false
return JavaParametersUtil.isClassInProductionSources(classSelector.text, module) ?: false
}
private const val PRODUCTION_CACHED = "production.cached"
|
apache-2.0
|
8fbf362e0193ddeb1d3341164ddc7c31
| 47.548611 | 183 | 0.767558 | 4.972262 | false | false | false | false |
CzBiX/v2ex-android
|
app/src/main/kotlin/com/czbix/v2ex/ui/settings/PrefsFragment.kt
|
1
|
4769
|
package com.czbix.v2ex.ui.settings
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.preference.*
import com.czbix.v2ex.BuildConfig
import com.czbix.v2ex.R
import com.czbix.v2ex.common.UserState
import com.czbix.v2ex.db.Member
import com.czbix.v2ex.inject.Injectable
import com.czbix.v2ex.ui.DebugActivity
import com.czbix.v2ex.ui.LoginActivity
import com.czbix.v2ex.ui.autoCleared
import com.czbix.v2ex.util.MiscUtils
import javax.inject.Inject
class PrefsFragment : PreferenceFragmentCompat(), Preference.OnPreferenceClickListener, Injectable {
private var isLogin: Boolean = false
private var nightModePref: ListPreference by autoCleared()
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private val settingsViewModel: SettingsViewModel by viewModels {
viewModelFactory
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.pref_general)
initGeneral()
initUser()
}
private fun initUser() {
isLogin = UserState.isLoggedIn()
val user = findPreference<PreferenceCategory>(PREF_KEY_CATEGORY_USER)
if (!isLogin) {
preferenceScreen.removePreference(user)
return
}
val infoPref = findPreference<Preference>(PREF_KEY_USER_INFO)!!
val logoutPref = findPreference<Preference>(PREF_KEY_LOGOUT)!!
infoPref.summary = UserState.username
infoPref.setOnPreferenceClickListener {
MiscUtils.openUrl(requireActivity(), Member.buildUrlFromName(
UserState.username!!))
false
}
logoutPref.onPreferenceClickListener = this
}
private fun initGeneral() {
val general = findPreference<PreferenceCategory>(PREF_KEY_CATEGORY_GENERAL)!!
val debugPref = findPreference<Preference>(PREF_KEY_DEBUG)!!
val loginPref = findPreference<Preference>(PREF_KEY_LOGIN)!!
nightModePref = findPreference(PREF_KEY_NIGHT_MODE)!!
if (BuildConfig.DEBUG) {
debugPref.onPreferenceClickListener = this
} else {
general.removePreference(debugPref)
general.removePreference(findPreference(PREF_KEY_ENABLE_FORCE_TOUCH))
}
if (UserState.isLoggedIn()) {
general.removePreference(loginPref)
} else {
loginPref.onPreferenceClickListener = this
}
nightModePref.preferenceDataStore = NightModeStore()
nightModePref.value = settingsViewModel.nightMode
findPreference<Preference>(PREF_KEY_VERSION)!!.summary =
"%s(%d) by CzBiX".format(BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
REQ_LOGIN -> if (resultCode == Activity.RESULT_OK) {
requireActivity().recreate()
}
}
super.onActivityResult(requestCode, resultCode, data)
}
override fun onPreferenceClick(preference: Preference): Boolean {
when (preference.key) {
PREF_KEY_LOGIN -> {
startActivityForResult(Intent(activity, LoginActivity::class.java), 0)
return true
}
PREF_KEY_LOGOUT -> {
UserState.logout()
requireActivity().recreate()
return true
}
PREF_KEY_DEBUG -> {
startActivity(Intent(activity, DebugActivity::class.java))
return true
}
}
return false
}
inner class NightModeStore : PreferenceDataStore() {
override fun getString(key: String?, defValue: String?): String? {
return settingsViewModel.nightMode
}
override fun putString(key: String?, value: String?) {
settingsViewModel.setNightMode(value!!)
}
}
companion object {
private const val PREF_KEY_CATEGORY_GENERAL = "general"
private const val PREF_KEY_CATEGORY_USER = "user"
private const val PREF_KEY_USER_INFO = "user_info"
private const val PREF_KEY_LOGIN = "login"
private const val PREF_KEY_NIGHT_MODE = "night_mode"
private const val PREF_KEY_DEBUG = "debug"
private const val PREF_KEY_LOGOUT = "logout"
private const val PREF_KEY_ENABLE_FORCE_TOUCH = "enable_force_touch"
private const val PREF_KEY_VERSION = "version"
private const val REQ_LOGIN = 0
}
}
|
apache-2.0
|
e229e17bdf3242b5f867e7b1ac3c2396
| 33.309353 | 100 | 0.652757 | 4.792965 | false | false | false | false |
inorichi/mangafeed
|
app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsMainController.kt
|
2
|
4502
|
package eu.kanade.tachiyomi.ui.setting
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import androidx.appcompat.widget.SearchView
import androidx.preference.PreferenceScreen
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction
import eu.kanade.tachiyomi.ui.setting.search.SettingsSearchController
import eu.kanade.tachiyomi.util.preference.iconRes
import eu.kanade.tachiyomi.util.preference.iconTint
import eu.kanade.tachiyomi.util.preference.onClick
import eu.kanade.tachiyomi.util.preference.preference
import eu.kanade.tachiyomi.util.preference.titleRes
import eu.kanade.tachiyomi.util.system.getResourceColor
class SettingsMainController : SettingsController() {
override fun setupPreferenceScreen(screen: PreferenceScreen) = screen.apply {
titleRes = R.string.label_settings
val tintColor = context.getResourceColor(R.attr.colorAccent)
preference {
iconRes = R.drawable.ic_tune_24dp
iconTint = tintColor
titleRes = R.string.pref_category_general
onClick { navigateTo(SettingsGeneralController()) }
}
preference {
iconRes = R.drawable.ic_palette_24dp
iconTint = tintColor
titleRes = R.string.pref_category_appearance
onClick { navigateTo(SettingsAppearanceController()) }
}
preference {
iconRes = R.drawable.ic_library_outline_24dp
iconTint = tintColor
titleRes = R.string.pref_category_library
onClick { navigateTo(SettingsLibraryController()) }
}
preference {
iconRes = R.drawable.ic_chrome_reader_mode_24dp
iconTint = tintColor
titleRes = R.string.pref_category_reader
onClick { navigateTo(SettingsReaderController()) }
}
preference {
iconRes = R.drawable.ic_get_app_24dp
iconTint = tintColor
titleRes = R.string.pref_category_downloads
onClick { navigateTo(SettingsDownloadController()) }
}
preference {
iconRes = R.drawable.ic_sync_24dp
iconTint = tintColor
titleRes = R.string.pref_category_tracking
onClick { navigateTo(SettingsTrackingController()) }
}
preference {
iconRes = R.drawable.ic_browse_outline_24dp
iconTint = tintColor
titleRes = R.string.browse
onClick { navigateTo(SettingsBrowseController()) }
}
preference {
iconRes = R.drawable.ic_settings_backup_restore_24dp
iconTint = tintColor
titleRes = R.string.label_backup
onClick { navigateTo(SettingsBackupController()) }
}
preference {
iconRes = R.drawable.ic_security_24dp
iconTint = tintColor
titleRes = R.string.pref_category_security
onClick { navigateTo(SettingsSecurityController()) }
}
preference {
iconRes = R.drawable.ic_code_24dp
iconTint = tintColor
titleRes = R.string.pref_category_advanced
onClick { navigateTo(SettingsAdvancedController()) }
}
}
private fun navigateTo(controller: SettingsController) {
router.pushController(controller.withFadeTransaction())
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
// Inflate menu
inflater.inflate(R.menu.settings_main, menu)
// Initialize search option.
val searchItem = menu.findItem(R.id.action_search)
val searchView = searchItem.actionView as SearchView
searchView.maxWidth = Int.MAX_VALUE
// Change hint to show global search.
searchView.queryHint = applicationContext?.getString(R.string.action_search_settings)
searchItem.setOnActionExpandListener(
object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(item: MenuItem?): Boolean {
preferences.lastSearchQuerySearchSettings().set("") // reset saved search query
router.pushController(SettingsSearchController().withFadeTransaction())
return true
}
override fun onMenuItemActionCollapse(item: MenuItem?): Boolean {
return true
}
}
)
}
}
|
apache-2.0
|
cd7e9199d431ac693cc5fe8bcb6ac886
| 37.478632 | 99 | 0.642825 | 5.110102 | false | false | false | false |
code-disaster/lwjgl3
|
modules/lwjgl/llvm/src/templates/kotlin/llvm/templates/ClangCompilationDatabase.kt
|
4
|
3874
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package llvm.templates
import llvm.*
import org.lwjgl.generator.*
val ClangCompilationDatabase = "ClangCompilationDatabase".nativeClass(
Module.LLVM,
prefixConstant = "CX",
prefixMethod = "clang_",
binding = CLANG_BINDING_DELEGATE
) {
nativeImport("clang-c/CXCompilationDatabase.h")
EnumConstant(
"""
Error codes for Compilation Database
({@code CXCompilationDatabase_Error})
""",
"CompilationDatabase_NoError".enum("No error occurred", "0"),
"CompilationDatabase_CanNotLoadDatabase".enum("Database can not be loaded")
)
CXCompilationDatabase(
"CompilationDatabase_fromDirectory",
"""
Creates a compilation database from the database found in directory buildDir. For example, CMake can output a compile_commands.json which can be used
to build the database.
It must be freed by {@code clang_CompilationDatabase_dispose}.
""",
charASCII.const.p("BuildDir", ""),
Check(1)..CXCompilationDatabase_Error.p("ErrorCode", "")
)
void(
"CompilationDatabase_dispose",
"Free the given compilation database",
CXCompilationDatabase("database", "")
)
CXCompileCommands(
"CompilationDatabase_getCompileCommands",
"Find the compile commands used for a file. The compile commands must be freed by {@code clang_CompileCommands_dispose}.",
CXCompilationDatabase("database", ""),
charASCII.const.p("CompleteFileName", "")
)
CXCompileCommands(
"CompilationDatabase_getAllCompileCommands",
"Get all the compile commands in the given compilation database.",
CXCompilationDatabase("database", "")
)
void(
"CompileCommands_dispose",
"Free the given CompileCommands",
CXCompileCommands("commands", "")
)
unsigned_int(
"CompileCommands_getSize",
"Get the number of CompileCommand we have for a file",
CXCompileCommands("commands", "")
)
CXCompileCommand(
"CompileCommands_getCommand",
"""
Get the I'th CompileCommand for a file
Note : 0 <= i <clang_CompileCommands_getSize(CXCompileCommands)
""",
CXCompileCommands("commands", ""),
unsigned_int("I", "")
)
CXString(
"CompileCommand_getDirectory",
"Get the working directory where the CompileCommand was executed from",
CXCompileCommand("command", "")
)
CXString(
"CompileCommand_getFilename",
"Get the filename associated with the CompileCommand.",
CXCompileCommand("command", "")
)
unsigned_int(
"CompileCommand_getNumArgs",
"Get the number of arguments in the compiler invocation.",
CXCompileCommand("command", "")
)
CXString(
"CompileCommand_getArg",
"""
Get the I'th argument value in the compiler invocations
Invariant :
${ul(
"argument 0 is the compiler executable"
)}
""",
CXCompileCommand("command", ""),
unsigned_int("I", "")
)
unsigned_int(
"CompileCommand_getNumMappedSources",
"Get the number of source mappings for the compiler invocation.",
CXCompileCommand("command", "")
)
CXString(
"CompileCommand_getMappedSourcePath",
"Get the I'th mapped source path for the compiler invocation.",
CXCompileCommand("command", ""),
unsigned_int("I", "")
)
CXString(
"CompileCommand_getMappedSourceContent",
"Get the I'th mapped source content for the compiler invocation.",
CXCompileCommand("command", ""),
unsigned_int("I", "")
)
}
|
bsd-3-clause
|
419441de0af4d3829939fb4f03e9e4c8
| 25.006711 | 157 | 0.622612 | 4.782716 | false | false | false | false |
ClearVolume/scenery
|
src/main/kotlin/graphics/scenery/BufferUtils.kt
|
2
|
2566
|
package graphics.scenery
import java.nio.*
/**
* Buffer utilities class
*
* @author Ulrik Günther <[email protected]>
*/
class BufferUtils {
/**
* Buffer utilities companion class, for allocating various kinds of buffers and filling them in one go.
*/
companion object {
private const val SIZE_FLOAT = java.lang.Float.BYTES
private const val SIZE_INT = java.lang.Integer.BYTES
/**
* Allocates a new direct [FloatBuffer] with a capacity of [num] floats.
*/
@JvmStatic fun allocateFloat(num: Int): FloatBuffer {
return ByteBuffer.allocateDirect(SIZE_FLOAT * num).order(ByteOrder.nativeOrder()).asFloatBuffer()
}
/**
* Allocates a new direct [FloatBuffer] with a capacity to fit [array], and fills it with the members
* of [array] and returns the flipped buffer.
*/
@JvmStatic fun allocateFloatAndPut(array: FloatArray): FloatBuffer {
val b = ByteBuffer.allocateDirect(SIZE_FLOAT * array.size).order(ByteOrder.nativeOrder()).asFloatBuffer()
(b.put(array) as Buffer).flip()
return b
}
/**
* Allocates a new direct [IntBuffer] with a capacity of [num] ints.
*/
@JvmStatic fun allocateInt(num: Int): IntBuffer {
return ByteBuffer.allocateDirect(SIZE_INT * num).order(ByteOrder.nativeOrder()).asIntBuffer()
}
/**
* Allocates a new direct [IntBuffer] with a capacity to fit [array], and fills it with the members
* of [array] and returns the flipped buffer.
*/
@JvmStatic fun allocateIntAndPut(array: IntArray): IntBuffer {
val b = ByteBuffer.allocateDirect(SIZE_INT * array.size).order(ByteOrder.nativeOrder()).asIntBuffer()
(b.put(array) as Buffer).flip()
return b
}
/**
* Allocates a new direct [ByteBuffer] with a capacity of [num] bytes.
*/
@JvmStatic fun allocateByte(num: Int): ByteBuffer {
return ByteBuffer.allocateDirect(num).order(ByteOrder.nativeOrder())
}
/**
* Allocates a new direct [ByteBuffer] with a capacity to fit [array], and fills it with the members
* of [array] and returns the flipped buffer.
*/
@JvmStatic fun allocateByteAndPut(array: ByteArray): ByteBuffer {
val b = ByteBuffer.allocateDirect(array.size).order(ByteOrder.nativeOrder())
b.put(array).flip()
return b
}
}
}
|
lgpl-3.0
|
ae86fb9ead5184adfa5cfac1b4175861
| 34.136986 | 117 | 0.610136 | 4.689214 | false | false | false | false |
syrop/GPS-Texter
|
texter/src/main/kotlin/pl/org/seva/texter/history/HistoryAdapter.kt
|
1
|
3751
|
/*
* Copyright (C) 2017 Wiktor Nizio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.texter.history
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import pl.org.seva.texter.R
import pl.org.seva.texter.data.SmsLocation
import pl.org.seva.texter.movement.getSpeedString
class HistoryAdapter(private val context: Context, private val values: List<SmsLocation>) :
RecyclerView.Adapter<HistoryAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HistoryAdapter.ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.adapter_history, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val location = values[position]
@SuppressLint("DefaultLocale")
val distanceStr = String.format("%.2f", location.distance) + location.sign + " km"
holder.distance.text = distanceStr
val hours = location.minutes / 60
val minutes = location.minutes % 60
val builder = StringBuilder(hours.toString() + ":")
if (minutes < 10) {
builder.append("0")
}
builder.append(minutes)
holder.time.text = builder.toString()
holder.speed.text = getSpeedString(
location.speed,
context.getString(R.string.speed_unit))
}
override fun getItemCount() = values.size
class DividerItemDecoration(context: Context) : RecyclerView.ItemDecoration() {
private val divider: Drawable
init {
val styledAttributes = context.obtainStyledAttributes(ATTRS)
divider = checkNotNull(styledAttributes.getDrawable(0))
styledAttributes.recycle()
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
val left = parent.paddingLeft
val right = parent.width - parent.paddingRight
repeat (parent.childCount) {
val child = parent.getChildAt(it)
val params = child.layoutParams as RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin
val bottom = top + divider.intrinsicHeight
divider.setBounds(left, top, right, bottom)
divider.draw(c)
}
}
companion object {
private val ATTRS = intArrayOf(android.R.attr.listDivider)
}
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val distance: TextView = view.findViewById(R.id.distance)
val time: TextView = view.findViewById(R.id.time)
val speed: TextView = view.findViewById(R.id.speed)
}
}
|
gpl-3.0
|
651aa0a414eac9090b93d01195a13f42
| 34.056075 | 98 | 0.679286 | 4.535671 | false | false | false | false |
kymjs/oschina-gam
|
app/src/main/java/org/kymjs/oschina/ui/MainActivity.kt
|
1
|
6133
|
package org.kymjs.oschina.ui
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.support.v4.widget.DrawerLayout
import android.view.KeyEvent
import android.view.View
import android.view.animation.Animation
import android.widget.ImageView
import android.widget.TextView
import org.kymjs.kjframe.KJActivity
import org.kymjs.kjframe.ui.BindView
import org.kymjs.kjframe.ui.KJActivityStack
import org.kymjs.kjframe.ui.SupportFragment
import org.kymjs.oschina.R
import org.kymjs.oschina.ui.fragment.FriendGroup
import org.kymjs.oschina.ui.fragment.MainSlidMenu
import org.kymjs.oschina.ui.fragment.Topic
import org.kymjs.oschina.ui.widget.menu.MaterialMenuDrawable
import org.kymjs.oschina.ui.widget.menu.MaterialMenuIcon
import org.kymjs.oschina.utils.KJAnimations
import rx.functions.Action1
/**
* 应用主界面
*/
public class MainActivity : KJActivity() {
@BindView(id = R.id.drawer_layout)
private val drawerLayout: DrawerLayout? = null
@BindView(id = R.id.titlebar_text_title, click = true)
public val tvTitle: TextView? = null
@BindView(id = R.id.titlebar_text_exittip, click = true)
public var tvDoubleClickTip: TextView? = null
@BindView(id = R.id.titlebar_img_back, click = true)
private val imgBack: ImageView? = null
private var materialMenuIcon: MaterialMenuIcon? = null
private var content1: SupportFragment = Topic()
private var content2: SupportFragment = FriendGroup()
private var menuFragment: MainSlidMenu? = null
private var titleBarHeight: Float = 0f
private var isOpen: Boolean = false;
private var isOnKeyBacking: Boolean = false
protected val mMainLoopHandler: Handler = Handler(Looper.getMainLooper())
/**
* 响应侧滑菜单MainSlidMenu中的item点击事件
*/
public val changeContentSubscribers: Action1<Int> = Action1() { tag ->
when (tag) {
1 -> changeFragment(content1)
2 -> changeFragment(content2)
}
}
public fun menuIsOpen(): Boolean = isOpen
override fun setRootView() {
setContentView(R.layout.activity_main)
}
override fun initData() {
titleBarHeight = getResources().getDimension(R.dimen.titlebar_height)
}
override fun initWidget() {
materialMenuIcon = MaterialMenuIcon(this, Color.WHITE, MaterialMenuDrawable.Stroke.THIN)
drawerLayout?.setDrawerListener(DrawerLayoutStateListener());
menuFragment = getSupportFragmentManager().findFragmentById(R.id.main_menu) as MainSlidMenu?;
changeFragment(content1)
}
override fun widgetClick(v: View?) {
when (v?.getId()) {
R.id.titlebar_img_back -> changeMenuState()
R.id.titlebar_text_title -> changeMenuState()
}
}
fun changeMenuState() {
if (isOpen) {
drawerLayout?.closeDrawers()
} else {
drawerLayout?.openDrawer(menuFragment?.rootView)
}
}
fun changeFragment(targetFragment: SupportFragment) {
drawerLayout?.closeDrawers()
changeFragment(R.id.main_content, targetFragment)
targetFragment.onResume();
}
inner class DrawerLayoutStateListener : DrawerLayout.SimpleDrawerListener() {
override fun onDrawerSlide(drawerView: View?, slideOffset: Float) {
materialMenuIcon?.setTransformationOffset(
MaterialMenuDrawable.AnimationState.BURGER_ARROW,
if (isOpen) {
2 - slideOffset
} else {
slideOffset
})
}
override fun onDrawerOpened(drawerView: View?) {
isOpen = true
}
override fun onDrawerClosed(drawerView: View?) {
isOpen = false
}
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
materialMenuIcon?.syncState(savedInstanceState)
}
override fun onSaveInstanceState(outState: Bundle?) {
materialMenuIcon?.onSaveInstanceState(outState)
super.onSaveInstanceState(outState)
}
/**
* 取消退出
*/
private fun cancleExit() {
val anim = KJAnimations.getTranslateAnimation(0f, 0f, -titleBarHeight, 0f, 300)
tvTitle?.startAnimation(anim)
val anim2 = KJAnimations.getTranslateAnimation(0f, 0f, 0f, -titleBarHeight, 300)
anim2.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
}
override fun onAnimationRepeat(animation: Animation) {
}
override fun onAnimationEnd(animation: Animation) {
tvDoubleClickTip?.setVisibility(View.GONE)
}
})
tvDoubleClickTip?.startAnimation(anim2)
}
/**
* 显示退出提示
*/
private fun showExitTip() {
tvDoubleClickTip?.setVisibility(View.VISIBLE)
val anim = KJAnimations.getTranslateAnimation(0f, 0f, 0f, -titleBarHeight, 300)
tvTitle?.startAnimation(anim)
val anim2 = KJAnimations.getTranslateAnimation(0f, 0f, -titleBarHeight, 0f, 300)
tvDoubleClickTip?.startAnimation(anim2)
}
private val onBackTimeRunnable = object : Runnable {
override fun run() {
isOnKeyBacking = false
cancleExit()
}
}
override fun onKeyDown(keyCode: Int, event: android.view.KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (isOnKeyBacking) {
mMainLoopHandler.removeCallbacks(onBackTimeRunnable)
isOnKeyBacking = false
// UIHelper.toHome(aty);
KJActivityStack.create().AppExit(aty)
} else {
isOnKeyBacking = true
showExitTip()
mMainLoopHandler.postDelayed(onBackTimeRunnable, 2000)
}
return true
} else {
return super.onKeyDown(keyCode, event)
}
}
}
|
apache-2.0
|
c56a5fe0ff8e91ac615adb36d6d10ef8
| 31.508021 | 101 | 0.652081 | 4.382841 | false | false | false | false |
dhis2/dhis2-android-sdk
|
core/src/main/java/org/hisp/dhis/android/core/trackedentity/search/TrackedEntityInstanceQueryCallFactory.kt
|
1
|
5571
|
/*
* 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.trackedentity.search
import dagger.Reusable
import java.text.ParseException
import java.util.concurrent.Callable
import javax.inject.Inject
import org.hisp.dhis.android.core.arch.api.executors.internal.APICallExecutor
import org.hisp.dhis.android.core.arch.helpers.CollectionsHelper
import org.hisp.dhis.android.core.event.EventStatus
import org.hisp.dhis.android.core.maintenance.D2Error
import org.hisp.dhis.android.core.maintenance.D2ErrorCode
import org.hisp.dhis.android.core.maintenance.D2ErrorComponent
import org.hisp.dhis.android.core.systeminfo.DHISVersion
import org.hisp.dhis.android.core.systeminfo.DHISVersionManager
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstance
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityInstanceService
@Reusable
internal class TrackedEntityInstanceQueryCallFactory @Inject constructor(
private val service: TrackedEntityInstanceService,
private val mapper: SearchGridMapper,
private val apiCallExecutor: APICallExecutor,
private val dhisVersionManager: DHISVersionManager
) {
fun getCall(query: TrackedEntityInstanceQueryOnline): Callable<List<TrackedEntityInstance>> {
return Callable { queryTrackedEntityInstances(query) }
}
@Throws(D2Error::class)
private fun queryTrackedEntityInstances(query: TrackedEntityInstanceQueryOnline): List<TrackedEntityInstance> {
val uidsStr =
if (query.uids() == null) null else CollectionsHelper.joinCollectionWithSeparator(query.uids(), ";")
val orgUnitModeStr = if (query.orgUnitMode() == null) null else query.orgUnitMode().toString()
val assignedUserModeStr = if (query.assignedUserMode() == null) null else query.assignedUserMode().toString()
val enrollmentStatus = if (query.enrollmentStatus() == null) null else query.enrollmentStatus().toString()
val eventStatus = getEventStatus(query)
val orgUnits =
if (query.orgUnits().isEmpty()) null
else CollectionsHelper.joinCollectionWithSeparator(query.orgUnits(), ";")
val searchGridCall = service.query(
uidsStr,
orgUnits,
orgUnitModeStr,
query.program(),
query.programStage(),
query.formattedProgramStartDate(),
query.formattedProgramEndDate(),
enrollmentStatus,
query.formattedIncidentStartDate(),
query.formattedIncidentEndDate(),
query.followUp(),
query.formattedEventStartDate(),
query.formattedEventEndDate(),
eventStatus,
query.trackedEntityType(),
query.query(),
query.attribute(),
query.filter(),
assignedUserModeStr,
query.formattedLastUpdatedStartDate(),
query.formattedLastUpdatedEndDate(),
query.order(),
query.paging(),
query.page(),
query.pageSize()
)
return try {
val searchGrid = apiCallExecutor.executeObjectCallWithErrorCatcher(
searchGridCall,
TrackedEntityInstanceQueryErrorCatcher()
)
mapper.transform(searchGrid)
} catch (pe: ParseException) {
throw D2Error.builder()
.errorCode(D2ErrorCode.SEARCH_GRID_PARSE)
.errorComponent(D2ErrorComponent.SDK)
.errorDescription("Search Grid mapping exception")
.originalException(pe)
.build()
}
}
private fun getEventStatus(query: TrackedEntityInstanceQueryOnline): String? {
return if (query.eventStatus() == null) {
null
} else if (!dhisVersionManager.isGreaterThan(DHISVersion.V2_33) && query.eventStatus() == EventStatus.ACTIVE) {
EventStatus.VISITED.toString()
} else {
query.eventStatus().toString()
}
}
}
|
bsd-3-clause
|
eecd27b55956b232dac60e72f9b7106c
| 44.663934 | 119 | 0.70131 | 4.790198 | false | false | false | false |
drakelord/wire
|
wire-schema/src/test/java/com/squareup/wire/schema/ProtoFileTest.kt
|
1
|
4016
|
/*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire.schema
import com.google.common.collect.ImmutableList
import com.squareup.wire.schema.internal.parser.ExtendElement
import com.squareup.wire.schema.internal.parser.FieldElement
import com.squareup.wire.schema.internal.parser.MessageElement
import com.squareup.wire.schema.internal.parser.OptionElement
import com.squareup.wire.schema.internal.parser.ProtoFileElement
import com.squareup.wire.schema.internal.parser.RpcElement
import com.squareup.wire.schema.internal.parser.ServiceElement
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class ProtoFileTest {
internal var location = Location.get("file.proto")
@Test
fun roundTripToElement() {
val element1 = MessageElement(
location = location.at(11, 1),
name = "Message1",
documentation = "Some comments about Message1"
)
val element2 = MessageElement(
location = location.at(12, 1),
name = "Message2",
fields = listOf(
FieldElement(
location = location.at(13, 3),
type = "string",
name = "field",
tag = 1
)
)
)
val extend1 = ExtendElement(
location = location.at(16, 1),
name = "Extend1"
)
val extend2 = ExtendElement(
location = location.at(17, 1),
name = "Extend2"
)
val option1 = OptionElement.create("kit", OptionElement.Kind.STRING, "kat")
val option2 = OptionElement.create("foo", OptionElement.Kind.STRING, "bar")
val service1 = ServiceElement(
location = location.at(19, 1),
name = "Service1",
rpcs = listOf(
RpcElement(
location = location.at(20, 3),
name = "MethodA",
requestType = "Message2",
responseType = "Message1",
options = listOf(
OptionElement.create("methodoption", OptionElement.Kind.NUMBER, 1)
)
)
))
val service2 = ServiceElement(
location = location.at(24, 1),
name = "Service2"
)
val fileElement = ProtoFileElement(
location = location,
packageName = "example.simple",
imports = ImmutableList.of("example.thing"),
publicImports = ImmutableList.of("example.other"),
types = ImmutableList.of(element1, element2),
services = ImmutableList.of(service1, service2),
extendDeclarations = ImmutableList.of(extend1, extend2),
options = ImmutableList.of(option1, option2)
)
val file = ProtoFile.get(fileElement)
val expected = """
|// file.proto
|package example.simple;
|
|import "example.thing";
|import public "example.other";
|
|option kit = "kat";
|option foo = "bar";
|
|// Some comments about Message1
|message Message1 {}
|message Message2 {
| string field = 1;
|}
|
|extend Extend1 {}
|extend Extend2 {}
|
|service Service1 {
| rpc MethodA (Message2) returns (Message1) {
| option methodoption = 1;
| };
|}
|service Service2 {}
|""".trimMargin()
assertThat(file.toSchema()).isEqualTo(expected)
assertThat(file.toElement()).isEqualToComparingFieldByField(fileElement)
}
}
|
apache-2.0
|
5228369bd7528aa10ea7b7aaa89cdc9c
| 31.92623 | 86 | 0.617281 | 4.299786 | false | false | false | false |
dkandalov/katas
|
kotlin/src/katas/kotlin/equality/equality.kt
|
1
|
4131
|
package katas.kotlin.equality
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
enum class Color {
Red, Orange, Yellow, Green, Blue, Indigo, Violet
}
// Based on http://www.artima.com/pins1ed/object-equality.html
class EqualityTest {
// naive equals which breaks symmetry
@Test fun a() {
open class Point(val x: Int, val y: Int) {
override fun hashCode() = 41 * (41 + x) + y
override fun equals(other: Any?) = if (other is Point) x == other.x && y == other.y else false
}
class ColoredPoint(x: Int, y: Int, val color: Color) : Point(x, y) {
override fun equals(other: Any?) =
if (other is ColoredPoint) color == other.color && super.equals(other) else false
}
val p = Point(1, 2)
val red = ColoredPoint(1, 2, Color.Red)
assertTrue(p == red)
assertFalse(red == p) // Broken symmetry.
}
// making equality more general (and breaking transitivity)
@Test fun b() {
open class Point(val x: Int, val y: Int) {
override fun hashCode() = 41 * (41 + x) + y
override fun equals(other: Any?) =
if (other is Point) x == other.x && y == other.y else false
}
class ColoredPoint(x: Int, y: Int, val color: Color) : Point(x, y) {
override fun equals(other: Any?) =
if (other is ColoredPoint) color == other.color && super.equals(other)
else if (other is Point) other == this
else false
}
val p = Point(1, 2)
val red = ColoredPoint(1, 2, Color.Red)
val blue = ColoredPoint(1, 2, Color.Blue)
assertTrue(red == p)
assertTrue(p == blue)
assertFalse(red == blue) // Broken transitivity.
}
// strict equality
@Test fun c() {
open class Point(val x: Int, val y: Int) {
override fun hashCode() = 41 * (41 + x) + y
override fun equals(other: Any?) =
if (other?.javaClass?.kotlin == Point::class && other is Point) x == other.x && y == other.y else false
}
class ColoredPoint(x: Int, y: Int, val color: Color) : Point(x, y) {
override fun equals(other: Any?) =
if (other is ColoredPoint) color == other.color && super.equals(other) else false
}
val p = Point(1, 2)
val red = ColoredPoint(1, 2, Color.Red)
val anonP = object : Point(1, 2) {
override fun toString() = "$x,$y"
}
assertTrue(p == p)
assertFalse(p == red)
assertFalse(red == p)
assertFalse(p == anonP) // This is arguably too strict.
}
// a bit less strict equals with canEqual function
@Test fun d() {
open class Point(val x: Int, val y: Int) {
override fun hashCode() = 41 * (41 + x) + y
override fun equals(other: Any?) =
if (other is Point) other.canEqual(this) && this.x == other.x && this.y == other.y else false
open fun canEqual(other: Any) = other is Point
}
class ColoredPoint(x: Int, y: Int, val color: Color) : Point(x, y) {
override fun equals(other: Any?) =
if (other is ColoredPoint) color == other.color && super.equals(other) else false
override fun canEqual(other: Any) = other is ColoredPoint
}
val p = Point(1, 2)
val red = ColoredPoint(1, 2, Color.Red)
val anonP = object : Point(1, 2) {
override fun toString() = "$x,$y"
}
assertTrue(p == p)
assertFalse(p == red)
assertFalse(red == p)
assertTrue(p == anonP)
}
private fun assertEqualityProperties(x: Any?, y: Any?, z: Any?, y2: Any?) {
// reflective
assertTrue(x == x)
// symmetric
assertTrue(x == y)
assertTrue(y == x)
assertFalse(x == y2)
assertFalse(y2 == x)
// transitive
assertTrue(x == y)
assertTrue(y == z)
assertTrue(x == z)
}
}
|
unlicense
|
cf74791aa3f4dd45bd6de497b3969cf8
| 34.307692 | 119 | 0.539579 | 3.800368 | false | true | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/jvm-debugger/test/testData/stepping/custom/smartStepIntoFunWithDefaultArgs.kt
|
9
|
544
|
package smartStepIntoFunWithDefaultArgs
fun Int.foo(a: Int = 1) {
val a = 1
}
fun Int.foo(a: String, b: Int = 1) {
val a = 1
}
fun bar() = 1
fun main(args: Array<String>) {
// SMART_STEP_INTO_BY_INDEX: 2
// RESUME: 1
//Breakpoint!
bar().foo(2)
// SMART_STEP_INTO_BY_INDEX: 2
// RESUME: 1
//Breakpoint!
bar().foo()
// SMART_STEP_INTO_BY_INDEX: 2
// RESUME: 1
//Breakpoint!
bar().foo("1", 2)
// SMART_STEP_INTO_BY_INDEX: 2
// RESUME: 1
//Breakpoint!
bar().foo("1")
}
|
apache-2.0
|
34742ca2c2e2053bf152164e7ca63d87
| 15.484848 | 39 | 0.536765 | 2.893617 | false | false | false | false |
dahlstrom-g/intellij-community
|
platform/execution-impl/src/com/intellij/execution/runToolbar/components/TrimmedMiddleLabel.kt
|
3
|
1556
|
// 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.execution.runToolbar.components
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.util.text.StringUtil
import java.awt.Graphics
import java.awt.Graphics2D
import javax.swing.JLabel
open class TrimmedMiddleLabel : JLabel() {
private val magicConst = 5
override fun paintComponent(g: Graphics) {
val fm = getFontMetrics(font)
g as Graphics2D
UISettings.setupAntialiasing(g)
val textW = fm.stringWidth(text)
var availableWidth = width - insets.right - insets.left
var x = insets.left
icon?.let {
x += iconTextGap + it.iconWidth
availableWidth -= x
}
val ellipsisWidth = fm.stringWidth(StringUtil.ELLIPSIS)
if (availableWidth <= 0 || textW <= availableWidth + (icon?.let { 0 } ?: magicConst) || width < ellipsisWidth) {
super.paintComponent(g)
}
else {
var offsetY = fm.ascent
icon?.let {
icon.paintIcon(this, g, insets.left, 0)
offsetY += (it.iconWidth / 2) - fm.height/2
}
val charArray = text.toCharArray()
val stringLength = charArray.size
var w = 0
val avW = availableWidth - ellipsisWidth
for (nChars in 0 until stringLength) {
w += fm.charWidth(charArray[nChars])
if (w > avW) {
g.drawString(StringUtil.trimMiddle(text, nChars - 1), x, offsetY)
return
}
}
}
}
}
|
apache-2.0
|
471ac110e1a71dbd5db0fd74e29efeb5
| 30.14 | 158 | 0.65874 | 3.909548 | false | false | false | false |
cdietze/klay
|
tripleklay/src/main/kotlin/tripleklay/util/Colors.kt
|
1
|
3335
|
package tripleklay.util
import klay.core.Color
/**
* Utilities and constants for colors.
*/
object Colors {
/** Named versions of commonly used colors. */
val WHITE = Color.rgb(255, 255, 255)
val LIGHT_GRAY = Color.rgb(192, 192, 192)
val GRAY = Color.rgb(128, 128, 128)
val DARK_GRAY = Color.rgb(64, 64, 64)
val BLACK = Color.rgb(0, 0, 0)
val RED = Color.rgb(255, 0, 0)
val PINK = Color.rgb(255, 175, 175)
val ORANGE = Color.rgb(255, 200, 0)
val YELLOW = Color.rgb(255, 255, 0)
val GREEN = Color.rgb(0, 255, 0)
val MAGENTA = Color.rgb(255, 0, 255)
val CYAN = Color.rgb(0, 255, 255)
val BLUE = Color.rgb(0, 0, 255)
/**
* Blends two colors.
* @return a color halfway between the two colors.
*/
fun blend(c1: Int, c2: Int): Int {
return Color.rgb(Color.red(c1) + Color.red(c2) shr 1,
Color.green(c1) + Color.green(c2) shr 1,
Color.blue(c1) + Color.blue(c2) shr 1)
}
/**
* Blends two colors proportionally.
* @param p1 The percentage of the first color to use, from 0.0f to 1.0f inclusive.
*/
fun blend(c1: Int, c2: Int, p1: Float): Int {
val p2 = 1 - p1
return Color.rgb((Color.red(c1) * p1 + Color.red(c2) * p2) as Int,
(Color.green(c1) * p1 + Color.green(c2) * p2) as Int,
(Color.blue(c1) * p1 + Color.blue(c2) * p2) as Int)
}
/**
* Creates a new darkened version of the given color. This is implemented by composing a new
* color consisting of the components of the original color, each multiplied by the dark factor.
* The alpha channel is copied from the original.
*/
fun darker(color: Int, darkFactor: Float = DARK_FACTOR): Int {
return Color.argb(Color.alpha(color),
maxOf((Color.red(color) * darkFactor).toInt(), 0),
maxOf((Color.green(color) * darkFactor).toInt(), 0),
maxOf((Color.blue(color) * darkFactor).toInt(), 0))
}
/**
* Creates a new brightened version of the given color. This is implemented by composing a new
* color consisting of the components of the original color, each multiplied by 10/7, with
* exceptions for zero-valued components. The alpha channel is copied from the original.
*/
fun brighter(color: Int): Int {
val a = Color.alpha(color)
var r = Color.red(color)
var g = Color.green(color)
var b = Color.blue(color)
// black is a special case the just goes to dark gray
if (r == 0 && g == 0 && b == 0) return Color.argb(a, MIN_BRIGHT, MIN_BRIGHT, MIN_BRIGHT)
// bump each component up to the minumum, unless it is absent
if (r != 0) r = maxOf(MIN_BRIGHT, r)
if (g != 0) g = maxOf(MIN_BRIGHT, g)
if (b != 0) b = maxOf(MIN_BRIGHT, b)
// scale
return Color.argb(a,
minOf((r * BRIGHT_FACTOR).toInt(), 255),
minOf((g * BRIGHT_FACTOR).toInt(), 255),
minOf((b * BRIGHT_FACTOR).toInt(), 255))
}
private val DARK_FACTOR = 0.7f
private val BRIGHT_FACTOR = 1 / DARK_FACTOR
private val MIN_BRIGHT = 3 // (int)(1.0 / (1.0 - DARK_FACTOR));
}
/**
* Creates a new darkened version of the given color with the default DARK_FACTOR.
*/
|
apache-2.0
|
a007d48c15d40c641006a7b1cbb0ff9a
| 36.47191 | 100 | 0.584708 | 3.389228 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/idea/tests/testData/multiplatform/overrideExpect/common/common.kt
|
9
|
510
|
expect class <!LINE_MARKER("descr='Has actuals in jvm module'")!>Expect<!>
interface <!LINE_MARKER("descr='Is implemented by Derived Click or press ... to navigate'")!>Base<!> {
fun <!LINE_MARKER("descr='Is implemented in Derived'")!>expectInReturnType<!>(): Expect
fun expectInArgument(e: Expect)
fun Expect.expectInReceiver()
val <!LINE_MARKER("descr='Is implemented in Derived'")!>expectVal<!>: Expect
var <!LINE_MARKER("descr='Is implemented in Derived'")!>expectVar<!>: Expect
}
|
apache-2.0
|
95d92282a0364d38e7bc633caa6bbeab
| 38.230769 | 103 | 0.686275 | 4.322034 | false | false | false | false |
DreierF/MyTargets
|
app/src/main/java/de/dreier/mytargets/base/fragments/SelectItemFragmentBase.kt
|
1
|
3782
|
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.base.fragments
import android.os.Bundle
import android.os.Parcelable
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.evernote.android.state.State
import de.dreier.mytargets.base.adapters.ListAdapterBase
import de.dreier.mytargets.shared.models.IIdProvider
import de.dreier.mytargets.utils.SingleSelectorBundler
import de.dreier.mytargets.utils.multiselector.ItemBindingHolder
import de.dreier.mytargets.utils.multiselector.OnItemClickListener
import de.dreier.mytargets.utils.multiselector.SelectableViewHolder
import de.dreier.mytargets.utils.multiselector.SingleSelector
/**
* Base class for handling single item selection
*
* @param <T> Model of the item which is managed within the fragment.
</T> */
abstract class SelectItemFragmentBase<T, U : ListAdapterBase<out ItemBindingHolder<*>, T>> :
FragmentBase(), OnItemClickListener<T> where T : IIdProvider, T : Parcelable {
/**
* Adapter for the fragment's RecyclerView
*/
protected lateinit var adapter: U
/**
* Selector which manages the item selection
*/
@State(SingleSelectorBundler::class)
var selector = SingleSelector()
/**
* Set to true when items are expanded when they are clicked and
* selected only after hitting them the second time.
*/
protected var useDoubleClickSelection = false
/**
* {@inheritDoc}
*/
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
selector.selectable = true
}
/**
* Searches the recyclerView's adapter for the given item and sets it as selected.
* If the position is not visible on the screen it is scrolled into view.
*
* @param recyclerView RecyclerView instance
* @param item Currently selected item
*/
protected open fun selectItem(recyclerView: RecyclerView, item: T) {
selector.setSelected(item.id, true)
recyclerView.post {
val manager = recyclerView.layoutManager as LinearLayoutManager
val first = manager.findFirstCompletelyVisibleItemPosition()
val last = manager.findLastCompletelyVisibleItemPosition()
val position = adapter.getItemPosition(item)
if (first > position || last < position) {
recyclerView.scrollToPosition(position)
}
}
}
/**
* {@inheritDoc}
*/
override fun onClick(holder: SelectableViewHolder<T>, item: T?) {
val alreadySelected = selector.isSelected(holder.itemIdentifier)
selector.setSelected(holder, true)
if (alreadySelected || !useDoubleClickSelection) {
saveItem()
navigationController.finish()
}
}
/**
* Returns the selected item to the calling activity. The item is retrieved by calling onSave().
*/
protected fun saveItem() {
navigationController.setResultSuccess(onSave())
}
/**
* Gets the item that has been selected by the user
*
* @return The selected item
*/
protected open fun onSave(): T {
return adapter.getItemById(selector.getSelectedId()!!)!!
}
}
|
gpl-2.0
|
0e41099dc58ad045b825eda98a82c188
| 33.072072 | 100 | 0.698043 | 4.88 | false | false | false | false |
github/codeql
|
java/ql/test/kotlin/library-tests/modifiers/modifiers.kt
|
1
|
715
|
open class X {
private val a = 1
protected val b = 2
internal val c = 3
val d = 4 // public by default
protected class Nested {
public val e: Int = 5
}
fun fn1(): Any {
return object {
fun fn() {}
}
}
fun fn2() {
fun fnLocal() {}
fnLocal()
}
fun fn3() {
class localClass {}
}
inline fun fn4(noinline f: () -> Unit) { }
inline fun fn5(crossinline f: () -> Unit) { }
inline fun <reified T> fn6(x: T) {}
}
class Y<in T1, out T2> {
fun foo(t: T1) : T2 = null!!
}
public class LateInit {
private lateinit var test0: LateInit
fun fn() {
lateinit var test1: LateInit
}
}
|
mit
|
af512130eb5cab9b4801dd2cbc55461c
| 16.463415 | 49 | 0.499301 | 3.4375 | false | false | false | false |
github/codeql
|
java/ql/test/kotlin/library-tests/properties/properties.kt
|
1
|
2145
|
abstract class properties(val constructorProp: Int, var mutableConstructorProp: Int, extractorArg: Int) {
var modifiableInt = 1
val immutableInt = 2
val typedProp: Int = 3
abstract val abstractTypeProp: Int
val initialisedInInit: Int
init {
initialisedInInit = 4
}
val useConstructorArg = extractorArg
val five: Int
get() = 5
val six
get() = 6
var getSet
get() = modifiableInt
set(v) { modifiableInt = v }
val defaultGetter = 7
get
var varDefaultGetter = 8
get
var varDefaultSetter = 9
set
var varDefaultGetterSetter = 10
get
set
var overrideGetter = 11
get() = 12
var overrideGetterUseField = 13
get() = field + 1
val useField = 14
get() = field + 1
lateinit var lateInitVar: String
private val privateProp = 15
protected val protectedProp = 16
public val publicProp = 17
internal val internalProp = 18
fun useProps(): Int {
return 0 +
constructorProp +
mutableConstructorProp +
modifiableInt +
immutableInt +
typedProp +
abstractTypeProp +
initialisedInInit +
useConstructorArg +
five +
six +
getSet +
defaultGetter +
varDefaultGetter +
varDefaultSetter +
varDefaultGetterSetter +
overrideGetter +
overrideGetterUseField +
useField +
privateProp +
protectedProp +
publicProp +
internalProp +
constVal
}
}
const val constVal = 15
class C<T> {
val prop = 1
fun fn() {
val c = C<String>()
println(c.prop)
}
}
val Int.x : Int
get() = 5
val Double.x : Int
get() = 5
class A {
private var data: Int = 0
fun setData(p: Int) {
data = p
}
}
class B {
private var data: Int = 5
get() = 42
fun setData(p: Int) {
data = p
}
}
|
mit
|
e02f83d50e87798c41613c3178f29350
| 20.887755 | 105 | 0.521212 | 4.506303 | false | false | false | false |
pflammertsma/cryptogram
|
app/src/main/java/com/pixplicity/cryptogram/views/HintView.kt
|
1
|
5612
|
package com.pixplicity.cryptogram.views
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.Typeface
import androidx.appcompat.widget.AppCompatTextView
import android.text.TextPaint
import android.util.AttributeSet
import com.pixplicity.cryptogram.R
import com.pixplicity.cryptogram.events.PuzzleEvent
import com.pixplicity.cryptogram.models.Puzzle
import com.pixplicity.cryptogram.utils.EventProvider
import com.pixplicity.cryptogram.utils.StyleUtils
import com.squareup.otto.Subscribe
class HintView : AppCompatTextView {
private var mPuzzle: Puzzle? = null
private var mCharsPerRow = 1
private var mMinBoxW: Float = 0.toFloat()
private var mBoxW: Float = 0.toFloat()
private var mCharH: Float = 0.toFloat()
private var mCharW: Float = 0.toFloat()
private lateinit var mTextPaint: TextPaint
constructor(context: Context) : super(context) {
init(context, null, 0)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(context, attrs, 0)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(context, attrs, defStyleAttr)
}
private fun init(context: Context, attrs: AttributeSet?, defStyleAttr: Int) {
val res = context.resources
mTextPaint = TextPaint()
mTextPaint.color = currentTextColor
mTextPaint.isAntiAlias = true
mTextPaint.typeface = Typeface.MONOSPACE
// Compute size of each box
mMinBoxW = StyleUtils.getSize(res, R.dimen.puzzle_box_width).toFloat()
mTextPaint.textSize = StyleUtils.getSize(res, R.dimen.puzzle_hint_size).toFloat()
// Compute size of a single char (assumes monospaced font!)
val bounds = Rect()
mTextPaint.getTextBounds("M", 0, 1, bounds)
mCharW = bounds.width().toFloat()
mCharH = bounds.height().toFloat()
if (isInEditMode) {
mPuzzle = Puzzle()
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
EventProvider.bus.register(this)
}
override fun onDetachedFromWindow() {
EventProvider.bus.unregister(this)
super.onDetachedFromWindow()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val widthMode = MeasureSpec.getMode(widthMeasureSpec)
val widthSize = MeasureSpec.getSize(widthMeasureSpec)
val heightMode = MeasureSpec.getMode(heightMeasureSpec)
val heightSize = MeasureSpec.getSize(heightMeasureSpec)
val desiredWidth = suggestedMinimumWidth
val width: Int
//Measure Width
if (widthMode == MeasureSpec.EXACTLY) {
//Must be this size
width = widthSize
} else if (widthMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
width = Math.min(desiredWidth, widthSize)
} else {
//Be whatever you want
width = desiredWidth
}
// Pack the most number of characters in the bar
val innerBox = width - paddingLeft
for (i in 1..25) {
mCharsPerRow = Math.ceil((26f / i).toDouble()).toInt()
mBoxW = (innerBox / mCharsPerRow).toFloat()
if (mBoxW >= mMinBoxW) {
break
}
}
val desiredHeight = drawChars(null, width)
val height: Int
//Measure Height
if (heightMode == MeasureSpec.EXACTLY) {
//Must be this size
height = heightSize
} else if (heightMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
height = Math.min(desiredHeight, heightSize)
} else {
//Be whatever you want
height = desiredHeight
}
setMeasuredDimension(width, height)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
drawChars(canvas, this.width - paddingRight)
}
private fun drawChars(canvas: Canvas?, width: Int): Int {
var desiredHeight = paddingTop
mPuzzle?.let {
// Compute the height that works for this width
val offsetY = mCharH / 2
val offsetX = mBoxW / 2 - mCharW / 2
var x = paddingLeft.toFloat()
// First row
var y = paddingTop + mCharH
var c = 'A'
for (i in 0..25) {
if (i % mCharsPerRow == 0) {
x = paddingLeft.toFloat()
if (i > 0) {
// Another row
y += mCharH + offsetY
}
} else {
// Box width
x += mBoxW
}
if (canvas != null) {
val chr = c.toString()
// Check if it's been mapped already
if (it.isUserCharInput(c)) {
mTextPaint.alpha = 96
} else {
mTextPaint.alpha = 255
}
// Draw the character
canvas.drawText(chr, x + offsetX, y, mTextPaint)
}
c++
}
desiredHeight = y.toInt()
}
desiredHeight += paddingBottom
return desiredHeight
}
@Subscribe
fun onPuzzleProgress(event: PuzzleEvent.PuzzleProgressEvent) {
mPuzzle = event.puzzle
requestLayout()
}
}
|
mit
|
8079cb2560877393e1d5b6865814ba0b
| 30.52809 | 113 | 0.57876 | 4.796581 | false | false | false | false |
tateisu/SubwayTooter
|
app/src/main/java/jp/juggler/subwaytooter/EventReceiver.kt
|
1
|
1704
|
package jp.juggler.subwaytooter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import jp.juggler.subwaytooter.notification.TrackingType
import jp.juggler.subwaytooter.notification.onNotificationDeleted
import jp.juggler.subwaytooter.table.NotificationTracking
import jp.juggler.util.LogCategory
import jp.juggler.util.launchMain
import jp.juggler.util.notEmpty
class EventReceiver : BroadcastReceiver() {
companion object {
internal val log = LogCategory("EventReceiver")
const val ACTION_NOTIFICATION_DELETE = "notification_delete"
}
override fun onReceive(context: Context, intent: Intent?) {
when (val action = intent?.action) {
Intent.ACTION_BOOT_COMPLETED,
Intent.ACTION_MY_PACKAGE_REPLACED,
-> {
App1.prepare(context.applicationContext, action)
NotificationTracking.resetPostAll()
}
ACTION_NOTIFICATION_DELETE -> intent.data?.let { uri ->
val dbId = uri.getQueryParameter("db_id")?.toLongOrNull()
val type = TrackingType.parseStr(uri.getQueryParameter("type"))
val typeName = type.typeName
val id = uri.getQueryParameter("notificationId")?.notEmpty()
log.d("Notification deleted! db_id=$dbId,type=$type,id=$id")
if (dbId != null) {
launchMain {
onNotificationDeleted(dbId, typeName)
}
}
}
else -> log.e("onReceive: unsupported action $action")
}
}
}
|
apache-2.0
|
9ad0a8c550ed3a6b488c2abee0b007c0
| 35.043478 | 79 | 0.612676 | 4.982456 | false | false | false | false |
paplorinc/intellij-community
|
python/testSrc/com/jetbrains/python/console/IPythonConsoleParsingTest.kt
|
3
|
2473
|
// 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.console
import com.intellij.lang.ASTFactory
import com.intellij.lang.LanguageASTFactory
import com.intellij.openapi.application.PathManager
import com.intellij.testFramework.ParsingTestCase
import com.jetbrains.python.*
import com.jetbrains.python.psi.impl.PythonASTFactory
/**
* Test parsing that is specific for IPython console.
*
* For the details see:
* https://ipython.readthedocs.io/en/stable/interactive/python-ipython-diff.html
*/
class IPythonConsoleParsingTest : ParsingTestCase(
"psi",
"py",
true,
PyConsoleParsingDefinition(true)
) {
override fun setUp() {
super.setUp()
registerExtensionPoint(PythonDialectsTokenSetContributor.EP_NAME, PythonDialectsTokenSetContributor::class.java)
registerExtension(PythonDialectsTokenSetContributor.EP_NAME, PythonTokenSetContributor())
addExplicitExtension<ASTFactory>(LanguageASTFactory.INSTANCE, PythonLanguage.getInstance(), PythonASTFactory())
PythonDialectsTokenSetProvider.reset()
}
override fun getTestDataPath() = "${PathManager.getHomePath()}/community/python/testData/console/ipython"
fun testHelp1() = doTestInternal()
fun testHelp2() = doTestInternal()
fun testHelp3() = doTestInternal()
fun testHelpObjectPrefix() = doTestInternal()
fun testHelpObjectSuffix() = doTestInternal()
fun testHelpObjectVerbosePrefix() = doTestInternal()
fun testHelpObjectVerboseSuffix() = doTestInternal()
fun testHelpWildcards() = doTestInternal()
fun testHelpError() = doTestInternal(false)
fun testShell1() = doTestInternal()
fun testShell2() = doTestInternal()
fun testShell3() = doTestInternal()
fun testShell4() = doTestInternal()
fun testShell5() = doTestInternal()
fun testShell6() = doTestInternal()
fun testShellAssignment1() = doTestInternal()
fun testShellAssignment2() = doTestInternal()
fun testShellExpansion() = doTestInternal()
fun testShellError() = doTestInternal(false)
fun testMagic1() = doTestInternal()
fun testMagic2() = doTestInternal()
fun testMagic3() = doTestInternal()
fun testMagicAssignment() = doTestInternal()
fun testMagicError() = doTestInternal(false)
fun testMagicMultiline() = doTestInternal()
private fun doTestInternal(ensureNoErrorElements: Boolean = true) = doTest(true, ensureNoErrorElements)
}
|
apache-2.0
|
abf9799cc70582cc2af1e2f949fdd4e1
| 27.755814 | 140 | 0.767085 | 4.256454 | false | true | false | false |
paplorinc/intellij-community
|
platform/platform-api/src/com/intellij/util/ui/LafIconLookup.kt
|
1
|
1795
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.ui
import com.intellij.icons.AllIcons
import com.intellij.openapi.util.IconLoader
import javax.swing.Icon
/**
* @author Konstantin Bulenkov
*/
object LafIconLookup {
@JvmStatic
@JvmOverloads
fun getIcon(name: String, selected: Boolean = false, focused: Boolean = false, enabled: Boolean = true, editable: Boolean = false, pressed: Boolean = false): Icon {
return findIcon(name, selected = selected, focused = focused, enabled = enabled, editable = editable, pressed = pressed, isThrowErrorIfNotFound = true)
?: AllIcons.Actions.Stub
}
fun findIcon(name: String, selected: Boolean = false, focused: Boolean = false, enabled: Boolean = true, editable: Boolean = false, pressed: Boolean = false, isThrowErrorIfNotFound: Boolean = false): Icon? {
var key = name
if (editable) key += "Editable"
if (selected) key += "Selected"
when {
pressed -> key += "Pressed"
focused -> key += "Focused"
!enabled -> key += "Disabled"
}
// For Mac blue theme and other LAFs use default directory icons
val dir = when {
UIUtil.isUnderDefaultMacTheme() -> if (UIUtil.isGraphite()) "graphite/" else ""
UIUtil.isUnderWin10LookAndFeel() -> "win10/"
UIUtil.isUnderDarcula() -> "darcula/"
UIUtil.isUnderIntelliJLaF() -> "intellij/"
else -> ""
}
return IconLoader.findLafIcon(dir + key, LafIconLookup::class.java, isThrowErrorIfNotFound)
}
@JvmStatic
fun getDisabledIcon(name: String): Icon = getIcon(name, enabled = false)
@JvmStatic
fun getSelectedIcon(name: String): Icon = findIcon(name, selected = true) ?: getIcon(name)
}
|
apache-2.0
|
d9408a19dab93bb80959b74b205fa16f
| 38.021739 | 209 | 0.689136 | 4.051919 | false | false | false | false |
paplorinc/intellij-community
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/GroovyTransformationsBundle.kt
|
6
|
1428
|
/*
* 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.
*/
@file:JvmName(name = "GroovyTransformationsBundle")
package org.jetbrains.plugins.groovy.transformations
import com.intellij.CommonBundle
import com.intellij.reference.SoftReference
import org.jetbrains.annotations.PropertyKey
import java.lang.ref.Reference
import java.util.*
const val BUNDLE: String = "org.jetbrains.plugins.groovy.transformations.GroovyTransformationsBundle"
fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = CommonBundle.message(getBundle(), key, *params)
private var ourBundle: Reference<ResourceBundle>? = null
private fun getBundle(): ResourceBundle {
var bundle = SoftReference.dereference(ourBundle)
if (bundle == null) {
bundle = ResourceBundle.getBundle(BUNDLE)!!
ourBundle = SoftReference<ResourceBundle>(bundle)
}
return bundle
}
|
apache-2.0
|
cce470ba35599cb1a2482ba5c45e50b4
| 33.02381 | 140 | 0.769608 | 4.262687 | false | false | false | false |
indianpoptart/RadioControl
|
RadioControl/app/src/main/java/com/nikhilparanjape/radiocontrol/services/PersistenceService.kt
|
1
|
4669
|
package com.nikhilparanjape.radiocontrol.services
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import com.nikhilparanjape.radiocontrol.R
import com.nikhilparanjape.radiocontrol.receivers.ConnectivityReceiver
import com.nikhilparanjape.radiocontrol.utilities.Utilities
/**
* Created by admin on 7/9/2017.
*
* @author Nikhil Paranjape
*
* @description This class allows RadioControl to keep itself awake in the background.
*/
class PersistenceService : Service() {
private val myConnectivityReceiver = ConnectivityReceiver()
var context: Context = this
override fun onCreate() {
super.onCreate()
Log.i(TAG, getString(R.string.log_persistence_created))
createNotificationChannel()
val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
registerReceiver(myConnectivityReceiver, filter)
createNotification(1)
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
Log.i(TAG, getString(R.string.log_persistence_started))
createNotification(2)
return START_STICKY
}
private fun createNotification(id: Int){
Log.i(TAG, "Notification Created")
val filter = IntentFilter()
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
val getPrefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(applicationContext)
try {
applicationContext.registerReceiver(myConnectivityReceiver, filter)
} catch (e: Exception) {
Log.e(TAG, "Registration Failed")
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && getPrefs.getInt("isActive", 0) == 1) {
Utilities.scheduleJob(context)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val builder = Notification.Builder(this, "persistence")
.setContentTitle("Persistence")
.setSmallIcon(R.drawable.ic_memory_24px)
.setContentText("This keeps RadioControl functioning in the background")
.setAutoCancel(true)
val notification = builder.build()
startForeground(1, notification)
} else {
//Run this code if the device is older (With a probably better OS :))
@Suppress("DEPRECATION") //For backwards compatibility
val builder = NotificationCompat.Builder(this)
.setContentTitle("Persistence")
.setSmallIcon(R.drawable.ic_memory_24px)
.setContentText("This keeps RadioControl functioning in the background")
.setPriority(NotificationCompat.PRIORITY_MIN)
.setAutoCancel(true)
val notification = builder.build()
startForeground(id, notification)
}
}
private fun createNotificationChannel() {
Log.i("RadioControl-persist", "Notification channel created")
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Persistence"
val description = getString(R.string.persistence_description)
val importance = NotificationManager.IMPORTANCE_MIN
val channel = NotificationChannel("persistence", name, importance)
channel.description = description
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager?.createNotificationChannel(channel)
}
}
override fun onBind(intent: Intent): IBinder? {
Log.i(TAG, getString(R.string.log_persistence_bound))
return null
}
override fun onDestroy() {
unregisterReceiver(myConnectivityReceiver)
super.onDestroy()
}
companion object {
private const val TAG = "RadioControl-Persist"
/*private const val PRIVATE_PREF = "prefs"*/
}
}
|
gpl-3.0
|
fbc60403c23f60b29cd3dc6711a16ef7
| 36.908333 | 108 | 0.655815 | 5.170543 | false | false | false | false |
allotria/intellij-community
|
platform/dvcs-impl/src/com/intellij/dvcs/ignore/IgnoredToExcludedSynchronizer.kt
|
1
|
11732
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.dvcs.ignore
import com.intellij.CommonBundle
import com.intellij.ProjectTopics
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.ide.projectView.actions.MarkExcludeRootAction
import com.intellij.ide.util.PropertiesComponent
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.roots.OrderEnumerator
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.FilesProcessorImpl
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.VcsConfiguration
import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.IGNORED_TO_EXCLUDE_NOT_FOUND
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.ignore.lang.IgnoreFileType
import com.intellij.openapi.vcs.changes.shelf.ShelveChangesManager
import com.intellij.openapi.vcs.changes.ui.SelectFilesDialog
import com.intellij.openapi.vcs.ignore.IgnoredToExcludedSynchronizerConstants.ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotifications
import java.util.*
private val LOG = logger<IgnoredToExcludedSynchronizer>()
private val excludeAction = object : MarkExcludeRootAction() {
fun exclude(module: Module, dirs: Collection<VirtualFile>) = runInEdt { modifyRoots(module, dirs.toTypedArray()) }
}
// Not internal service. Can be used directly in related modules.
@Service
class IgnoredToExcludedSynchronizer(project: Project) : VcsIgnoredHolderUpdateListener, FilesProcessorImpl(project, project) {
override val askedBeforeProperty = ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY
override val doForCurrentProjectProperty: String? = null
init {
project.messageBus.connect(this).subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) = updateNotificationState()
})
}
private fun updateNotificationState() {
if (synchronizationTurnOff()) return
// in case if the project roots changed (e.g. by build tools) then the directories shown in notification can be outdated.
// filter directories which excluded or containing source roots and expire notification if needed.
val fileIndex = ProjectFileIndex.getInstance(project)
val sourceRoots = getProjectSourceRoots(project)
val acquiredFiles = acquireValidFiles()
LOG.debug("updateNotificationState, acquiredFiles", acquiredFiles)
val filesToRemove = acquiredFiles
.asSequence()
.filter { file -> fileIndex.isExcluded(file) || sourceRoots.contains(file) }
.toList()
LOG.debug("updateNotificationState, filesToRemove", filesToRemove)
if (removeFiles(filesToRemove)) {
EditorNotifications.getInstance(project).updateAllNotifications()
}
}
fun isNotEmpty() = !isFilesEmpty()
fun clearFiles(files: Collection<VirtualFile>) = removeFiles(files)
fun getValidFiles() = with(ChangeListManager.getInstance(project)) { acquireValidFiles().filter(this::isIgnoredFile) }
fun muteForCurrentProject() {
setForCurrentProject(false)
PropertiesComponent.getInstance(project).setValue(askedBeforeProperty, true)
clearFiles()
}
fun mutedForCurrentProject() = wasAskedBefore() && !needDoForCurrentProject()
override fun doActionOnChosenFiles(files: Collection<VirtualFile>) {
if (files.isEmpty()) return
markIgnoredAsExcluded(project, files)
}
override fun doFilterFiles(files: Collection<VirtualFile>) = files.filter(VirtualFile::isValid)
override fun rememberForAllProjects() {}
override fun rememberForCurrentProject() {
VcsConfiguration.getInstance(project).MARK_IGNORED_AS_EXCLUDED = true
}
override fun needDoForCurrentProject() = VcsConfiguration.getInstance(project).MARK_IGNORED_AS_EXCLUDED
override fun updateFinished(ignoredPaths: Collection<FilePath>, isFullRescan: Boolean) {
ProgressManager.checkCanceled()
if (synchronizationTurnOff()) return
if (!isFullRescan) return
if (!VcsConfiguration.getInstance(project).MARK_IGNORED_AS_EXCLUDED && wasAskedBefore()) return
processIgnored(ignoredPaths)
}
private fun processIgnored(ignoredPaths: Collection<FilePath>) {
val ignoredDirs =
determineIgnoredDirsToExclude(project, ignoredPaths)
if (allowShowNotification()) {
processFiles(ignoredDirs)
val editorNotifications = EditorNotifications.getInstance(project)
FileEditorManager.getInstance(project).openFiles
.forEach { openFile ->
if (openFile.fileType is IgnoreFileType) {
editorNotifications.updateNotifications(openFile)
}
}
}
else if (needDoForCurrentProject()) {
doActionOnChosenFiles(doFilterFiles(ignoredDirs))
}
}
}
private fun markIgnoredAsExcluded(project: Project, files: Collection<VirtualFile>) {
val ignoredDirsByModule =
files
.groupBy { ModuleUtil.findModuleForFile(it, project) }
//if the directory already excluded then ModuleUtil.findModuleForFile return null and this will filter out such directories from processing.
.filterKeys(Objects::nonNull)
for ((module, ignoredDirs) in ignoredDirsByModule) {
excludeAction.exclude(module!!, ignoredDirs)
}
}
private fun getProjectSourceRoots(project: Project): Set<VirtualFile> = runReadAction {
OrderEnumerator.orderEntries(project).withoutSdk().withoutLibraries().sources().usingCache().roots.toHashSet()
}
private fun containsShelfDirectoryOrUnderIt(filePath: FilePath, shelfPath: String) =
FileUtil.isAncestor(shelfPath, filePath.path, false) ||
FileUtil.isAncestor(filePath.path, shelfPath, false)
private fun determineIgnoredDirsToExclude(project: Project, ignoredPaths: Collection<FilePath>): List<VirtualFile> {
val sourceRoots = getProjectSourceRoots(project)
val fileIndex = ProjectFileIndex.getInstance(project)
val shelfPath = ShelveChangesManager.getShelfPath(project)
return ignoredPaths
.asSequence()
.filter(FilePath::isDirectory)
//shelf directory usually contains in project and excluding it prevents local history to work on it
.filterNot { containsShelfDirectoryOrUnderIt(it, shelfPath) }
.mapNotNull(FilePath::getVirtualFile)
.filterNot { runReadAction { fileIndex.isExcluded(it) } }
//do not propose to exclude if there is a source root inside
.filterNot { ignored -> sourceRoots.contains(ignored) }
.toList()
}
private fun selectFilesToExclude(project: Project, ignoredDirs: List<VirtualFile>): Collection<VirtualFile> {
val dialog = IgnoredToExcludeSelectDirectoriesDialog(project, ignoredDirs)
if (!dialog.showAndGet()) return emptyList()
return dialog.selectedFiles
}
private fun allowShowNotification() = Registry.`is`("vcs.propose.add.ignored.directories.to.exclude", true)
private fun synchronizationTurnOff() = !Registry.`is`("vcs.enable.add.ignored.directories.to.exclude", true)
class IgnoredToExcludeNotificationProvider : EditorNotifications.Provider<EditorNotificationPanel>() {
companion object {
private val KEY: Key<EditorNotificationPanel> = Key.create("IgnoredToExcludeNotificationProvider")
}
override fun getKey(): Key<EditorNotificationPanel> = KEY
private fun canCreateNotification(project: Project, file: VirtualFile) =
file.fileType is IgnoreFileType &&
with(project.service<IgnoredToExcludedSynchronizer>()) {
!synchronizationTurnOff() &&
allowShowNotification() &&
!mutedForCurrentProject() &&
isNotEmpty()
}
private fun showIgnoredAction(project: Project) {
val allFiles = project.service<IgnoredToExcludedSynchronizer>().getValidFiles()
if (allFiles.isEmpty()) return
val userSelectedFiles = selectFilesToExclude(project, allFiles)
if (userSelectedFiles.isEmpty()) return
with(project.service<IgnoredToExcludedSynchronizer>()) {
markIgnoredAsExcluded(project, userSelectedFiles)
clearFiles(userSelectedFiles)
}
}
private fun muteAction(project: Project) = Runnable {
project.service<IgnoredToExcludedSynchronizer>().muteForCurrentProject()
EditorNotifications.getInstance(project).updateNotifications(this@IgnoredToExcludeNotificationProvider)
}
override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? {
if (!canCreateNotification(project, file)) return null
return EditorNotificationPanel(fileEditor).apply {
icon(AllIcons.General.Information)
text = message("ignore.to.exclude.notification.message")
createActionLabel(message("ignore.to.exclude.notification.action.view")) { showIgnoredAction(project) }
createActionLabel(message("ignore.to.exclude.notification.action.mute"), muteAction(project))
createActionLabel(message("ignore.to.exclude.notification.action.details")) {
BrowserUtil.browse("https://www.jetbrains.com/help/idea/content-roots.html#folder-categories") }
}
}
}
internal class CheckIgnoredToExcludeAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = e.project != null
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val changeListManager = ChangeListManager.getInstance(project)
changeListManager.invokeAfterUpdateWithModal(false, ActionsBundle.message("action.CheckIgnoredAndNotExcludedDirectories.progress")) {
val dirsToExclude = determineIgnoredDirsToExclude(project, changeListManager.ignoredFilePaths)
if (dirsToExclude.isEmpty()) {
VcsNotifier.getInstance(project)
.notifyMinorInfo(IGNORED_TO_EXCLUDE_NOT_FOUND, "", message("ignore.to.exclude.no.directories.found"))
}
else {
val userSelectedFiles = selectFilesToExclude(project, dirsToExclude)
if (userSelectedFiles.isNotEmpty()) {
markIgnoredAsExcluded(project, userSelectedFiles)
}
}
}
}
}
// do not use SelectFilesDialog.init because it doesn't provide clear statistic: what exactly dialog shown/closed, action clicked
private class IgnoredToExcludeSelectDirectoriesDialog(
project: Project?,
files: List<VirtualFile>
) : SelectFilesDialog(project, files, message("ignore.to.exclude.notification.notice"), null, true, true) {
init {
title = message("ignore.to.exclude.view.dialog.title")
selectedFiles = files
setOKButtonText(message("ignore.to.exclude.view.dialog.exclude.action"))
setCancelButtonText(CommonBundle.getCancelButtonText())
init()
}
}
|
apache-2.0
|
57e213285f5a5e6aabf69e61691a5375
| 40.75089 | 146 | 0.777617 | 4.6928 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.