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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/tv/account/JamiGuidedStepFragment.kt | 1 | 5738 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package cx.ring.tv.account
import android.content.Context
import android.graphics.drawable.Drawable
import net.jami.mvp.RootPresenter
import androidx.leanback.app.GuidedStepSupportFragment
import javax.inject.Inject
import android.os.Bundle
import androidx.leanback.widget.GuidedAction
import android.text.InputType
import android.view.View
import androidx.annotation.StringRes
abstract class JamiGuidedStepFragment<T : RootPresenter<in V>, in V> : GuidedStepSupportFragment() {
@Inject
lateinit var presenter: T
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//Be sure to do the injection in onCreateView method
presenter.bindView(this as V)
initPresenter(presenter)
}
override fun onDestroyView() {
super.onDestroyView()
presenter.unbindView()
}
protected fun initPresenter(presenter: T) {}
companion object {
fun addAction(context: Context, actions: MutableList<GuidedAction>, id: Long, @StringRes title: Int) {
actions.add(GuidedAction.Builder(context)
.id(id)
.title(title)
.build())
}
fun addAction(context: Context, actions: MutableList<GuidedAction>, id: Long, title: String = "", desc: String = "") {
actions.add(GuidedAction.Builder(context)
.id(id)
.title(title)
.description(desc)
.build())
}
fun addAction(
context: Context,
actions: MutableList<GuidedAction>,
id: Long,
title: String?,
desc: String? = "",
next: Boolean = true
) {
actions.add(GuidedAction.Builder(context)
.id(id)
.title(title)
.description(desc)
.hasNext(next)
.build())
}
fun addDisabledAction(
context: Context,
actions: MutableList<GuidedAction>,
id: Long,
title: String?,
desc: String?
) {
actions.add(GuidedAction.Builder(context)
.id(id)
.title(title)
.description(desc)
.enabled(false)
.build())
}
protected fun addDisabledAction(
context: Context,
actions: MutableList<GuidedAction>,
id: Long,
title: String?,
desc: String?,
icon: Drawable? = null
) {
actions.add(GuidedAction.Builder(context)
.id(id)
.title(title)
.description(desc)
.enabled(false)
.icon(icon)
.build())
}
fun addDisabledNonFocusableAction(
context: Context,
actions: MutableList<GuidedAction>,
id: Long,
title: String? = "",
desc: String? = "",
icon: Drawable? = null
) {
actions.add(GuidedAction.Builder(context)
.id(id)
.title(title)
.description(desc)
.enabled(false)
.focusable(false)
.icon(icon)
.build())
}
fun addDisabledAction(context: Context, actions: MutableList<GuidedAction>, id: Long,
title: String?,
desc: String?,
icon: Drawable?,
next: Boolean
) {
actions.add(GuidedAction.Builder(context)
.id(id)
.title(title)
.description(desc)
.enabled(false)
.icon(icon)
.hasNext(next)
.build())
}
fun addEditTextAction(
context: Context, actions: MutableList<GuidedAction>, id: Long,
@StringRes title: Int, @StringRes desc: Int): GuidedAction {
return GuidedAction.Builder(context)
.id(id)
.title(title)
.editTitle("")
.description(desc)
.inputType(InputType.TYPE_CLASS_TEXT)
.editable(true)
.build()
.apply { actions.add(this) }
}
fun addPasswordAction(context: Context, actions: MutableList<GuidedAction>, id: Long,
title: String?, desc: String?, editdesc: String? = "") {
actions.add(GuidedAction.Builder(context)
.id(id)
.title(title)
.description(desc)
.editDescription(editdesc)
.descriptionEditInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD)
.descriptionEditable(true)
.build())
}
}
} | gpl-3.0 | 68057de9bdede9b3b7e85e3daedcd85b | 31.982759 | 126 | 0.545835 | 4.870968 | false | false | false | false |
wiryls/HomeworkCollectionOfMYLS | 2017.AndroidApplicationDevelopment/ODES/app/src/main/java/com/myls/odes/fragment/DormPickFragment.kt | 1 | 3246 | package com.myls.odes.fragment
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import com.myls.odes.R
import com.myls.odes.activity.MainActivity
import com.myls.odes.application.AnApplication
import com.myls.odes.data.RoomInfo
import com.myls.odes.data.UserList
import com.myls.odes.utility.Storage
import kotlinx.android.synthetic.main.fragment_dorm_pick.*
import kotlinx.android.synthetic.main.item_dormitory.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
class DormPickFragment : DialogFragment()
{
private lateinit var saver: Storage
private lateinit var roomi: RoomInfo
private lateinit var userl: UserList
private lateinit var user: UserList.User
override fun onCreateView
(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?)
= inflater.inflate(R.layout.fragment_dorm_pick, container, false)!!
override fun onActivityCreated(savedInstanceState: Bundle?)
= super.onActivityCreated(savedInstanceState).also {
(activity.application as AnApplication).let {
saver = it.saver
userl = it.userlist
roomi = it.roominfo
user = userl.list.firstOrNull()
?: return@let post(MainActivity.InvalidDataEvent("UserList is empty"))
}
onUpdateDormLayout()
}
private fun onUpdateDormLayout() {
dorm_list.adapter = DormInfoArrayAdapter()
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onDormUpdatedEvent(event: DormApplFragment.RoomUpdatedEvent) {
if (event.done)
onUpdateDormLayout()
}
override fun onStart() {
super.onStart()
EVENT_BUS.register(this)
}
override fun onStop() {
EVENT_BUS.unregister(this)
super.onStop()
}
private inner class DormInfoArrayAdapter:
ArrayAdapter<Pair<String, Int>>(context, R.layout.item_dormitory, roomi.info.toList()),
View.OnClickListener
{
override fun getView(position: Int, convertView: View?, parent: ViewGroup?) =
(convertView?:View.inflate(this.context, R.layout.item_dormitory, null)!!).also {
val item = getItem(position)
it.item_desc .text = getString(R.string.desc_fmt_building).format(item.first)
it.item_value.text = getString(R.string.desc_fmt_rest).format(item.second)
it.setOnClickListener(this)
it.tag = item.first
}
override fun onClick(view: View) {
with(this@DormPickFragment) {
user.dorm.pick = view.tag as String
saver.put(userl)
post(DormApplFragment.UserDormUpdatedEvent(user.dorm))
dismiss()
}
}
}
companion object {
private val TAG = DormPickFragment::class.java.canonicalName!!
private val EVENT_BUS = EventBus.getDefault()
private fun <T> post(data: T) = EVENT_BUS.post(data)
fun create() = DormPickFragment()
}
}
| mit | c59c41d6bf510ace3b3a6447e44d628b | 32.8125 | 95 | 0.669131 | 4.199224 | false | false | false | false |
hendraanggrian/picasso-transformations | buildSrc/src/dependencies/hendraanggrian.kt | 1 | 390 | const val VERSION_BANNERBAR = VERSION_ANDROIDX
const val VERSION_PREFY = "0.2"
fun Dependencies.hendraanggrian(module: String, version: String) = "com.hendraanggrian:$module:$version"
fun Dependencies.hendraanggrian(repo: String, module: String, version: String) = "com.hendraanggrian.$repo:$module:$version"
fun Plugins.hendraanggrian(module: String) = id("com.hendraanggrian.$module")
| mit | 7f223431f063012bb66cb7b36300a3b7 | 47.75 | 124 | 0.779487 | 3.9 | false | false | false | false |
cretz/asmble | compiler/src/main/kotlin/asmble/io/ByteReader.kt | 1 | 5996 | package asmble.io
import asmble.util.toUnsignedBigInt
import asmble.util.toUnsignedLong
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.math.BigInteger
abstract class ByteReader {
abstract val isEof: Boolean
// Slices the next set off as its own and moves the position up that much
abstract fun read(amount: Int): ByteReader
abstract fun readByte(): Byte
abstract fun readBytes(amount: Int? = null): ByteArray
fun readUInt32(): Long {
return ((readByte().toInt() and 0xff) or
((readByte().toInt() and 0xff) shl 8) or
((readByte().toInt() and 0xff) shl 16) or
((readByte().toInt() and 0xff) shl 24)).toUnsignedLong()
}
fun readUInt64(): BigInteger {
return ((readByte().toLong() and 0xff) or
((readByte().toLong() and 0xff) shl 8) or
((readByte().toLong() and 0xff) shl 16) or
((readByte().toLong() and 0xff) shl 24) or
((readByte().toLong() and 0xff) shl 32) or
((readByte().toLong() and 0xff) shl 40) or
((readByte().toLong() and 0xff) shl 48) or
((readByte().toLong() and 0xff) shl 56)).toUnsignedBigInt()
}
fun readVarInt7() = readSignedLeb128().let {
if (it < Byte.MIN_VALUE.toLong() || it > Byte.MAX_VALUE.toLong()) throw IoErr.InvalidLeb128Number()
it.toByte()
}
fun readVarInt32() = readSignedLeb128().let {
if (it < Int.MIN_VALUE.toLong() || it > Int.MAX_VALUE.toLong()) throw IoErr.InvalidLeb128Number()
it.toInt()
}
fun readVarInt64() = readSignedLeb128(9)
fun readVarUInt1() = readUnsignedLeb128().let {
if (it != 1 && it != 0) throw IoErr.InvalidLeb128Number()
it == 1
}
fun readVarUInt7() = readUnsignedLeb128().let {
if (it > 255) throw IoErr.InvalidLeb128Number()
it.toShort()
}
fun readVarUInt32() = readUnsignedLeb128().toUnsignedLong()
protected fun readUnsignedLeb128(maxCount: Int = 4): Int {
// Taken from Android source, Apache licensed
var result = 0
var cur: Int
var count = 0
do {
cur = readByte().toInt() and 0xff
result = result or ((cur and 0x7f) shl (count * 7))
count++
} while (cur and 0x80 == 0x80 && count <= maxCount)
if (cur and 0x80 == 0x80) throw IoErr.InvalidLeb128Number()
// Result can't have used more than ceil(result/7)
if (cur != 0 && count - 1 > (result.toUnsignedLong() + 6) / 7) throw IoErr.InvalidLeb128Number()
return result
}
private fun readSignedLeb128(maxCount: Int = 4): Long {
// Taken from Android source, Apache licensed
var result = 0L
var cur: Int
var count = 0
var signBits = -1L
do {
cur = readByte().toInt() and 0xff
result = result or ((cur and 0x7f).toLong() shl (count * 7))
signBits = signBits shl 7
count++
} while (cur and 0x80 == 0x80 && count <= maxCount)
if (cur and 0x80 == 0x80) throw IoErr.InvalidLeb128Number()
// Check for 64 bit invalid, taken from Apache/MIT licensed:
// https://github.com/paritytech/parity-wasm/blob/2650fc14c458c6a252c9dc43dd8e0b14b6d264ff/src/elements/primitives.rs#L351
// TODO: probably need 32 bit checks too, but meh, not in the suite
if (count > maxCount && maxCount == 9) {
if (cur and 0b0100_0000 == 0b0100_0000) {
if ((cur or 0b1000_0000).toByte() != (-1).toByte()) throw IoErr.InvalidLeb128Number()
} else if (cur != 0) {
throw IoErr.InvalidLeb128Number()
}
}
if ((signBits shr 1) and result != 0L) result = result or signBits
return result
}
class InputStream(val ins: java.io.InputStream) : ByteReader() {
private var nextByte: Byte? = null
private var sawEof = false
override val isEof: Boolean get() {
if (!sawEof && nextByte == null) {
val b = ins.read()
if (b == -1) sawEof = true else nextByte = b.toByte()
}
return sawEof && nextByte == null
}
override fun read(amount: Int) = ByteReader.InputStream(ByteArrayInputStream(readBytes(amount)))
override fun readByte(): Byte {
nextByte?.let { nextByte = null; return it }
val b = ins.read()
if (b >= 0) return b.toByte()
sawEof = true
throw IoErr.UnexpectedEnd()
}
override fun readBytes(amount: Int?): ByteArray {
// If we have the amount, we create a byte array for reading that
// otherwise we read until the end
if (amount != null) {
val ret = ByteArray(amount)
var remaining = amount
if (nextByte != null) {
ret[0] = nextByte!!
nextByte = null
remaining--
}
while (remaining > 0) {
val off = amount - remaining
val read = ins.read(ret, off, remaining)
if (read == -1) {
sawEof = true
throw IoErr.UnexpectedEnd()
}
remaining -= read
}
return ret
} else {
val out = ByteArrayOutputStream()
if (nextByte != null) {
out.write(nextByte!!.toInt())
nextByte = null
}
val buf = ByteArray(8192)
while (true) {
val r = ins.read(buf)
if (r == -1) break
out.write(buf, 0, r)
}
sawEof = true
return out.toByteArray()
}
}
}
} | mit | 8bf3383570e0bfd466dbfa615bd4befb | 35.567073 | 131 | 0.532855 | 4.166782 | false | false | false | false |
gradle/gradle | .teamcity/src/main/kotlin/util/AdHocPerformanceScenario.kt | 2 | 4906 | package util
import common.Arch
import common.JvmVendor
import common.Os
import common.applyPerformanceTestSettings
import common.buildToolGradleParameters
import common.checkCleanM2AndAndroidUserHome
import common.gradleWrapper
import common.individualPerformanceTestArtifactRules
import common.killGradleProcessesStep
import common.performanceTestCommandLine
import common.removeSubstDirOnWindows
import common.substDirOnWindows
import jetbrains.buildServer.configs.kotlin.v2019_2.BuildType
import jetbrains.buildServer.configs.kotlin.v2019_2.ParameterDisplay
import jetbrains.buildServer.configs.kotlin.v2019_2.ParametrizedWithType
abstract class AdHocPerformanceScenario(os: Os, arch: Arch = Arch.AMD64) : BuildType({
val id = "Util_Performance_AdHocPerformanceScenario${os.asName()}${arch.asName()}"
name = "AdHoc Performance Scenario - ${os.asName()} ${arch.asName()}"
id(id)
applyPerformanceTestSettings(os = os, arch = arch, timeout = 420)
artifactRules = individualPerformanceTestArtifactRules
params {
text(
"performance.baselines",
"",
display = ParameterDisplay.PROMPT,
allowEmpty = true,
description = "The baselines you want to run performance tests against. Empty means default baseline."
)
text(
"testProject",
"",
display = ParameterDisplay.PROMPT,
allowEmpty = false,
description = "The test project to use. E.g. largeJavaMultiProject"
)
param("channel", "adhoc")
param("checks", "all")
text("runs", "10", display = ParameterDisplay.PROMPT, allowEmpty = false)
text("warmups", "3", display = ParameterDisplay.PROMPT, allowEmpty = false)
text(
"scenario",
"",
display = ParameterDisplay.PROMPT,
allowEmpty = false,
description = "Which performance test to run. Should be the fully qualified class name dot (unrolled) method name. E.g. org.gradle.performance.regression.java.JavaUpToDatePerformanceTest.up-to-date assemble (parallel true)"
)
text("testJavaVersion", "8", display = ParameterDisplay.PROMPT, allowEmpty = false, description = "The java version to run the performance tests, e.g. 8/11/17")
select(
"testJavaVendor",
JvmVendor.openjdk.name,
display = ParameterDisplay.PROMPT,
description = "The java vendor to run the performance tests",
options = JvmVendor.values().map { it.displayName to it.name }
)
when (os) {
Os.WINDOWS -> {
profilerParam("jprofiler")
param("env.JPROFILER_HOME", "C:\\Program Files\\jprofiler\\jprofiler11.1.4")
}
else -> {
profilerParam("async-profiler")
param("env.FG_HOME_DIR", "/opt/FlameGraph")
param("env.PATH", "%env.PATH%:/opt/swift/4.2.3/usr/bin:/opt/swift/4.2.4-RELEASE-ubuntu18.04/usr/bin")
param("env.HP_HOME_DIR", "/opt/honest-profiler")
}
}
param("env.PERFORMANCE_DB_PASSWORD_TCAGENT", "%performance.db.password.tcagent%")
param("additional.gradle.parameters", "")
}
steps {
killGradleProcessesStep(os)
substDirOnWindows(os)
gradleWrapper {
name = "GRADLE_RUNNER"
workingDir = os.perfTestWorkingDir
gradleParams = (
performanceTestCommandLine(
"clean performance:%testProject%PerformanceAdHocTest --tests \"%scenario%\"",
"%performance.baselines%",
"""--warmups %warmups% --runs %runs% --checks %checks% --channel %channel% --profiler %profiler% %additional.gradle.parameters%""",
os,
"%testJavaVersion%",
"%testJavaVendor%",
) + buildToolGradleParameters(isContinue = false)
).joinToString(separator = " ")
}
removeSubstDirOnWindows(os)
checkCleanM2AndAndroidUserHome(os)
}
})
private
fun ParametrizedWithType.profilerParam(defaultProfiler: String) {
text(
"profiler",
defaultProfiler,
display = ParameterDisplay.PROMPT,
allowEmpty = false,
description = "Command line option for the performance test task to enable profiling. For example `async-profiler`, `async-profiler-heap`, `async-profiler-all` or `jfr`. Use `none` for benchmarking only."
)
}
object AdHocPerformanceScenarioLinux : AdHocPerformanceScenario(Os.LINUX)
object AdHocPerformanceScenarioWindows : AdHocPerformanceScenario(Os.WINDOWS)
object AdHocPerformanceScenarioMacOS : AdHocPerformanceScenario(Os.MACOS, Arch.AMD64)
object AdHocPerformanceScenarioMacM1 : AdHocPerformanceScenario(Os.MACOS, Arch.AARCH64)
| apache-2.0 | 9d3f15edde92ce34acf5e3e1e5e00f79 | 42.035088 | 235 | 0.648186 | 4.52583 | false | true | false | false |
j-selby/kotgb | core/src/main/kotlin/net/jselby/kotgb/cpu/interpreter/instructions/alu/Bitwise.kt | 1 | 3324 | package net.jselby.kotgb.cpu.interpreter.instructions.alu
import net.jselby.kotgb.Gameboy
import net.jselby.kotgb.cpu.CPU
import net.jselby.kotgb.cpu.Registers
import net.jselby.kotgb.cpu.interpreter.instructions.getN
import kotlin.experimental.and
import kotlin.experimental.or
import kotlin.experimental.xor
import kotlin.reflect.KMutableProperty1
/**
* Bitwise operations allow for operations between the bits of two values.
*/
/**
* -- XORs. --
*/
/**
* Helper to XOR something into A.
*/
fun regXOR(registers : Registers, yVal : Short) {
val xVal = registers.a
val result = yVal xor xVal
registers.a = result
registers.f = 0
registers.flagZ = registers.a.toInt() == 0
}
/**
* **0xA8 ~ 0xAF** - *XOR X* - Xor X with a into a
*/
val x_XOR : (CPU, Registers, Gameboy, KMutableProperty1<Registers, Short>) -> (Int) = {
_, registers, _, target ->
regXOR(registers, target.get(registers))
/*Cycles: */ 4
}
/**
* **0xAE** - *XOR (hl)* - Xor \*hl with a into a
*/
val xAE : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
// TODO: Check that this is correct
regXOR(registers, gb.ram.readByte(registers.hl.toLong() and 0xFFFF))
/*Cycles: */ 8
}
/**
* **0xEE** - *XOR #* - Xor # with a into a
*/
val xEE : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
regXOR(registers, getN(registers, gb))
/*Cycles: */ 8
}
/**
* -- ORs. --
*/
/**
* Helper to OR something into A.
*/
fun regOR(registers : Registers, yVal : Short) {
val xVal = registers.a
val result = yVal or xVal
registers.a = result
registers.f = 0
registers.flagZ = registers.a.toInt() == 0
}
/**
* **0xB0 ~ 0xB7** - *OR X* - Or X with a into a
*/
val x_OR : (CPU, Registers, Gameboy, KMutableProperty1<Registers, Short>) -> (Int) = {
_, registers, _, target ->
regOR(registers, target.get(registers))
/*Cycles: */ 4
}
/**
* **0xB6** - *OR (hl)* - Or *hl with a into a
*/
val xB6 : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
regOR(registers, (gb.ram.readShort(registers.hl.toLong() and 0xFFFF).toInt() and 0xFFFF).toShort())
/*Cycles: */ 8
}
/**
* **0xF6** - *OR #* - or # with a into a
*/
val xF6 : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
regOR(registers, getN(registers, gb))
/*Cycles: */ 8
}
/**
* -- ANDs. --
*/
/**
* Helper to AND something into A.
*/
fun regAND(registers : Registers, yVal : Short) {
val xVal = registers.a
val result = xVal and yVal
registers.a = result
registers.f = 0
registers.flagZ = registers.a.toInt() == 0
registers.flagH = true
}
/**
* **0xB0 ~ 0xB7** - *AND X* - AND X with a into a
*/
val x_AND : (CPU, Registers, Gameboy, KMutableProperty1<Registers, Short>) -> (Int) = {
_, registers, _, target ->
regAND(registers, target.get(registers))
/*Cycles: */ 4
}
/**
* **0xA6** - *AND (hl)* - And (hl) with a into a
*/
val xA6 : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
regAND(registers, gb.ram.readShort(registers.hl.toLong() and 0xFFFF))
/*Cycles: */ 8
}
/**
* **0xE6** - *AND #* - And # with a into a
*/
val xE6 : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
regAND(registers, getN(registers, gb))
/*Cycles: */ 8
} | mit | 720b1506bb712d250319b9b824876951 | 20.590909 | 103 | 0.593863 | 3.005425 | false | false | false | false |
hblanken/Tower-v3.2.1 | Android/src/org/droidplanner/android/fragments/widget/TowerWidgets.kt | 1 | 3986 | package org.droidplanner.android.fragments.widget
import android.app.DialogFragment
import android.app.Fragment
import android.support.annotation.IdRes
import android.support.annotation.StringRes
import org.droidplanner.android.R
import org.droidplanner.android.fragments.widget.diagnostics.FullWidgetDiagnostics
import org.droidplanner.android.fragments.widget.diagnostics.MiniWidgetDiagnostics
import org.droidplanner.android.fragments.widget.telemetry.MiniWidgetFlightTimer
import org.droidplanner.android.fragments.widget.telemetry.MiniWidgetGeoInfo
import org.droidplanner.android.fragments.widget.telemetry.MiniWidgetAttitudeSpeedInfo
import org.droidplanner.android.fragments.widget.video.FullWidgetSoloLinkVideo
import org.droidplanner.android.fragments.widget.video.MiniWidgetSoloLinkVideo
import org.droidplanner.android.fragments.widget.video.WidgetVideoPreferences
/**
* Created by Fredia Huya-Kouadio on 8/25/15.
*/
public enum class TowerWidgets(@IdRes val idRes: Int, @StringRes val labelResId: Int, @StringRes val descriptionResId: Int, val prefKey: String) {
FLIGHT_TIMER(R.id.tower_widget_flight_timer, R.string.label_widget_flight_timer, R.string.description_widget_flight_timer, "pref_widget_flight_timer"){
override fun getMinimizedFragment() = MiniWidgetFlightTimer()
override fun isEnabledByDefault() = true
},
VEHICLE_DIAGNOSTICS(R.id.tower_widget_vehicle_diagnostics, R.string.label_widget_vehicle_diagnostics, R.string.description_widget_vehicle_diagnostics, "pref_widget_vehicle_diagnostics") {
override fun getMinimizedFragment() = MiniWidgetDiagnostics()
override fun canMaximize() = true
override fun getMaximizedFragment() = FullWidgetDiagnostics()
},
SOLO_VIDEO(R.id.tower_widget_solo_video, R.string.label_widget_solo_video, R.string.description_widget_solo_video, "pref_widget_solo_video") {
override fun canMaximize() = true
override fun isEnabledByDefault() = true
override fun getMinimizedFragment() = MiniWidgetSoloLinkVideo()
override fun getMaximizedFragment() = FullWidgetSoloLinkVideo()
override fun hasPreferences() = true
override fun getPrefFragment() = WidgetVideoPreferences()
},
ATTITUDE_SPEED_INFO(R.id.tower_widget_attitude_speed_info, R.string.label_widget_attitude_speed_info, R.string.description_widget_attitude_speed_info, "pref_widget_attitude_speed_info") {
override fun getMinimizedFragment() = MiniWidgetAttitudeSpeedInfo()
override fun isEnabledByDefault() = true
},
GEO_INFO(R.id.tower_widget_geo_info, R.string.label_widget_geo_info, R.string.description_widget_geo_info, "pref_widget_geo_info"){
override fun getMinimizedFragment() = MiniWidgetGeoInfo()
}
;
abstract fun getMinimizedFragment(): TowerWidget
open fun canMaximize() = false
open fun isEnabledByDefault() = false
open fun getMaximizedFragment(): TowerWidget? = null
open fun hasPreferences() = false
open fun getPrefFragment(): DialogFragment? = null
companion object {
@JvmStatic fun getWidgetById(@IdRes id: Int): TowerWidgets? {
return when (id) {
FLIGHT_TIMER.idRes -> FLIGHT_TIMER
ATTITUDE_SPEED_INFO.idRes -> ATTITUDE_SPEED_INFO
SOLO_VIDEO.idRes -> SOLO_VIDEO
VEHICLE_DIAGNOSTICS.idRes -> VEHICLE_DIAGNOSTICS
GEO_INFO.idRes -> GEO_INFO
else -> null
}
}
@JvmStatic fun getWidgetByPrefKey(prefKey: String): TowerWidgets? {
return when (prefKey) {
FLIGHT_TIMER.prefKey -> FLIGHT_TIMER
ATTITUDE_SPEED_INFO.prefKey -> ATTITUDE_SPEED_INFO
SOLO_VIDEO.prefKey -> SOLO_VIDEO
VEHICLE_DIAGNOSTICS.prefKey -> VEHICLE_DIAGNOSTICS
GEO_INFO.prefKey -> GEO_INFO
else -> null
}
}
}
} | gpl-3.0 | d7d7bf3713e87acdfb3f94b5f7016cd4 | 39.683673 | 191 | 0.713246 | 4.244941 | false | false | false | false |
FWDekker/intellij-randomness | src/main/kotlin/com/fwdekker/randomness/template/TemplateActionLoader.kt | 1 | 4108 | package com.fwdekker.randomness.template
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.impl.DynamicActionConfigurationCustomizer
/**
* Registers and unregisters actions for the user's [Template]s so that they can be inserted using shortcuts.
*/
object TemplateActionLoader : DynamicActionConfigurationCustomizer {
/**
* Shorthand to return all the user's stored [Template]s.
*/
private val templates: List<Template>
get() = TemplateSettings.default.state.templates
/**
* Registers the actions for all [Template]s in the user's [TemplateSettings].
*
* @param actionManager the manager to register actions through
*/
override fun registerActions(actionManager: ActionManager) {
templates.forEach { registerAction(actionManager, it) }
}
/**
* Unregisters the actions of all [Template]s in the user's [TemplateSettings].
*
* @param actionManager the manager to unregister actions through
*/
override fun unregisterActions(actionManager: ActionManager) {
templates.forEach { unregisterAction(actionManager, it) }
}
/**
* Registers, unregisters, and updates actions as appropriate for a transition from [oldList] to [newList].
*
* @param oldList the list of stored [Template]s before storing [newList]
* @param newList the list of stored [Template]s after storing them
*/
fun updateActions(oldList: Set<Template>, newList: Set<Template>) {
val actionManager = ActionManager.getInstance()
val newUuids = newList.map { it.uuid }
oldList.filterNot { it.uuid in newUuids }.forEach {
if (actionManager.getAction(it.actionId) != null)
actionManager.unregisterAction(it.actionId)
}
newList.forEach {
if (actionManager.getAction(it.actionId) == null)
registerAction(actionManager, it)
else
replaceAction(actionManager, it)
}
}
/**
* Returns all variant actions belonging to [template].
*
* @param template the template to get actions for
* @return all variant actions belonging to [template]
*/
private fun getActions(template: Template) =
mapOf(
template.actionId to TemplateInsertAction(template, array = false, repeat = false),
"${template.actionId}.array" to TemplateInsertAction(template, array = true, repeat = false),
"${template.actionId}.repeat" to TemplateInsertAction(template, array = false, repeat = true),
"${template.actionId}.repeat.array" to TemplateInsertAction(template, array = true, repeat = true),
"${template.actionId}.settings" to TemplateSettingsAction(template)
)
/**
* Registers the actions associated with [template].
*
* @param actionManager the manager to register actions through
* @param template the [Template] to register actions for
*/
private fun registerAction(actionManager: ActionManager, template: Template) =
getActions(template).forEach { (actionId, action) ->
actionManager.registerAction(actionId, action)
actionManager.replaceAction(actionId, action)
}
/**
* Unregisters the actions associated with [template].
*
* @param actionManager the manager to unregister actions through
* @param template the [Template] to unregister actions for
*/
private fun unregisterAction(actionManager: ActionManager, template: Template) =
getActions(template).forEach { (actionId, _) -> actionManager.unregisterAction(actionId) }
/**
* Replaces the actions associated with [template].
*
* @param actionManager the manager to replace actions through
* @param template the [Template] to replace actions for
*/
private fun replaceAction(actionManager: ActionManager, template: Template) =
getActions(template).forEach { (actionId, action) -> actionManager.replaceAction(actionId, action) }
}
| mit | a0dacfc8ba33db5ec8999533d73c8af0 | 38.12381 | 111 | 0.676241 | 5.015873 | false | false | false | false |
snxamdf/study-android-login | app/src/androidTest/java/HttpRequest.kt | 1 | 5800 | import android.os.Build
import android.support.annotation.RequiresApi
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.URL
import java.net.URLConnection
import java.util.*
class HttpRequest {
fun asdf() {
if ("" == "adsf") {
}
val b = if (1 == 2) "a" else "b"
return
}
enum class METHOD {
POST, GET
}
companion object {
@JvmStatic fun main(args: Array<String>) {
val params = HashMap<String, String>()
params.put("1", "1")
params.put("2", "2")
sendGet("www.baidu.com", params)
}
fun sendGet(url: String, params: Map<String, String>): String {
return send(url, params, METHOD.GET)!!
}
fun sendPost(url: String, params: Map<String, String>): String {
return send(url, params, METHOD.POST)!!
}
fun send(url: String, params: Map<String, String>, method: METHOD): String? {
val sb = StringBuffer()
var i = 0
for ((key, value) in params) {
if (i > 0) {
sb.append("&")
}
i++
sb.append(key).append("=").append(value)
}
if (method == METHOD.POST) {
return sendPost(url, sb.toString())
} else if (method == METHOD.GET) {
return sendGet(url, sb.toString())
}
return null
}
/**
* 向指定URL发送GET方法的请求
* @param url 发送请求的URL
* *
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* *
* @return URL 所代表远程资源的响应结果
*/
private fun sendGet(url: String, param: String): String {
val result = StringBuffer()
var `in`: BufferedReader? = null
try {
val urlNameString = url + "?" + param
// 打开和URL之间的连接
val connection = getURLConnection(urlNameString)
// 建立实际的连接
connection.connect()
// 获取所有响应头字段
val map = connection.headerFields
// 遍历所有的响应头字段
for (key in map.keys) {
println(key + "--->" + map[key])
}
// 定义 BufferedReader输入流来读取URL的响应
`in` = BufferedReader(InputStreamReader(connection.getInputStream()))
`in`.forEachLine {
result.append(it)
}
} catch (e: Exception) {
println("发送GET请求出现异常!" + e)
e.printStackTrace()
} finally {
try {
if (`in` != null) {
`in`.close()
}
} catch (e2: Exception) {
e2.printStackTrace()
}
}// 使用finally块来关闭输入流
return result.toString()
}
/**
* 向指定 URL 发送POST方法的请求
* @param url 发送请求的 URL
* *
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* *
* @return 所代表远程资源的响应结果
*/
private fun sendPost(url: String, param: String): String {
var out: PrintWriter? = null
var `in`: BufferedReader? = null
val result = StringBuffer()
try {
// 打开和URL之间的连接
val connection = getURLConnection(url)
// 发送POST请求必须设置如下两行
connection.doOutput = true
connection.doInput = true
// 获取URLConnection对象对应的输出流
out = PrintWriter(connection.getOutputStream())
// 发送请求参数
out.print(param)
// flush输出流的缓冲
out.flush()
// 定义BufferedReader输入流来读取URL的响应
`in` = BufferedReader(InputStreamReader(connection.getInputStream()))
`in`.forEachLine {
result.append(it)
}
} catch (e: Exception) {
println("发送 POST 请求出现异常!" + e)
e.printStackTrace()
} finally {
try {
if (out != null) {
out.close()
}
if (`in` != null) {
`in`.close()
}
} catch (ex: IOException) {
ex.printStackTrace()
}
}//使用finally块来关闭输出流、输入流
return result.toString()
}
@Throws(IOException::class)
private fun getURLConnection(url: String): URLConnection {
val realUrl = URL(url)
// 打开和URL之间的连接
val connection = realUrl.openConnection()
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*")
connection.setRequestProperty("connection", "Keep-Alive")
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)")
connection.connectTimeout = 1000 * 5
connection.readTimeout = 1000 * 5
return connection
}
}
}
| apache-2.0 | 83c562ef012a23c288be670c24a88537 | 30.654762 | 113 | 0.466341 | 4.572657 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/views/Error404View.kt | 1 | 1353 | package net.perfectdreams.loritta.morenitta.website.views
import kotlinx.html.DIV
import kotlinx.html.div
import kotlinx.html.h1
import kotlinx.html.img
import kotlinx.html.p
import kotlinx.html.style
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.morenitta.LorittaBot
class Error404View(
loritta: LorittaBot,
locale: BaseLocale,
path: String
) : NavbarView(
loritta,
locale,
path
) {
override fun getTitle() = "404"
override fun DIV.generateContent() {
div(classes = "odd-wrapper") {
style = "text-align: center;"
div(classes = "media single-column") {
div(classes = "media-body") {
div {
style = "text-align: center;"
img(src = "https://loritta.website/assets/img/fanarts/l4.png") {
width = "175"
}
h1 {
+ locale["website.error404.title"]
}
for (str in locale.getList("website.error404.description")) {
p {
+ str
}
}
}
}
}
}
}
} | agpl-3.0 | 0f8c275c35cd26747ae884383fd363ed | 26.08 | 88 | 0.479675 | 4.797872 | false | false | false | false |
appnexus/mobile-sdk-android | tests/TrackerTestApp/app/src/main/java/appnexus/com/trackertestapp/InterstitialActivity.kt | 1 | 4343 | package appnexus.com.trackertestapp
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.webkit.WebView
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.test.espresso.idling.CountingIdlingResource
import appnexus.com.trackertestapp.utility.Utils
import com.appnexus.opensdk.*
import com.appnexus.opensdk.utils.Settings
class InterstitialActivity : AppCompatActivity(), AdListener, AppEventListener {
var isAdCollapsed: Boolean = false
var isAdExpanded: Boolean = false
var idlingResource: CountingIdlingResource = CountingIdlingResource("Interstitial Load Counter", true)
val interstitial_id: Int = 1235
lateinit var interstitial: InterstitialAdView
var autoDismiss: Int = -1
override fun onAdClicked(p0: AdView?) {
Toast.makeText(this, "Ad Clicked", Toast.LENGTH_LONG).show()
}
override fun onAdClicked(p0: AdView?, p1: String?) {
Toast.makeText(this, "Ad Clicked with URL", Toast.LENGTH_LONG).show()
}
override fun onAdExpanded(p0: AdView?) {
Toast.makeText(this, "Ad Expanded", Toast.LENGTH_LONG).show()
isAdExpanded = true
}
override fun onAdCollapsed(p0: AdView?) {
Toast.makeText(this, "Ad Collapsed", Toast.LENGTH_LONG).show()
isAdCollapsed = true
// if (!idlingResource.isIdleNow)
// idlingResource.decrement()
}
override fun onAdRequestFailed(p0: AdView?, p1: ResultCode?) {
Toast.makeText(this, "Ad Failed: " + p1?.message, Toast.LENGTH_LONG).show()
println(p1?.message)
if (!idlingResource.isIdleNow)
idlingResource.decrement()
}
override fun onLazyAdLoaded(adView: AdView?) {
}
override fun onAdLoaded(ad: AdView?) {
Toast.makeText(this, "AdLoaded", Toast.LENGTH_LONG).show()
if (!idlingResource.isIdleNow)
idlingResource.decrement()
showAd()
}
private fun showAd() {
// if (layout.childCount > 0)
// layout.removeAllViews()
// layout.addView(interstitial)
interstitial.showWithAutoDismissDelay(autoDismiss)
// idlingResource.increment()
}
override fun onAdLoaded(p0: NativeAdResponse?) {
Toast.makeText(this, "Native Ad Loaded", Toast.LENGTH_LONG).show()
if (!idlingResource.isIdleNow)
idlingResource.decrement()
}
lateinit var layout: LinearLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_banner)
layout = findViewById(R.id.linearLayout)
Settings.getSettings().debug_mode = true
Settings.getSettings().useHttps = true
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
}
fun triggerAdLoad(placement: String?, useHttps: Boolean = true, autoDismiss: Int = -1, closeButtonDelay: Int = 1, creativeId: Int? = null, bgTask: Boolean = false) {
SDKSettings.enableBackgroundThreading(bgTask)
Handler(Looper.getMainLooper()).post {
this.autoDismiss = 10
interstitial = InterstitialAdView(this)
interstitial.id = interstitial_id
interstitial.placementID = if (placement == null) "17982237" else placement
interstitial.adListener = this
interstitial.closeButtonDelay = 5
interstitial.clickThroughAction = ANClickThroughAction.RETURN_URL
if(creativeId != null) {
val utils = Utils()
utils.setForceCreativeId(creativeId, interstitial = interstitial);
}
interstitial.loadAd()
idlingResource.increment()
}
}
fun performClickAd(){
interstitial.performClick()
}
fun removeInterstitialAd(){
interstitial.removeAllViews()
interstitial.destroy()
}
override fun onDestroy() {
super.onDestroy()
if (interstitial != null){
interstitial.destroy()
}
}
override fun onAppEvent(adView: AdView?, name: String?, data: String?) {
println("AppEvent: " + name + ", DATA: " + data)
}
}
| apache-2.0 | bc727642089fd52570b47d226811181d | 32.152672 | 169 | 0.658301 | 4.557188 | false | false | false | false |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/acupuncture/model.kt | 1 | 17501 | package at.cpickl.gadsu.acupuncture
import at.cpickl.gadsu.global.GadsuException
import at.cpickl.gadsu.tcm.model.Element
import at.cpickl.gadsu.tcm.model.Meridian
import at.cpickl.gadsu.tcm.model.UnpairedMeridian
import com.google.common.base.Splitter
import com.google.common.collect.ComparisonChain
import gadsu.generated.Acupuncts
import java.util.HashMap
import java.util.LinkedList
import java.util.Objects
import java.util.regex.Pattern
var disableAcupunctVerification = false
data class Acupunct(
val coordinate: AcupunctCoordinate,
val germanName: String,
val chineseName: String,
val note: String,
val localisation: String,
val indications: List<String>,
/**
* Always in the same ordered as its natural sort order.
* Always only contains 0 or 1 ElementPoint.
*/
val flags: List<AcupunctFlag>
) :
Comparable<Acupunct> {
companion object {
private val acupunctByCoordinate = HashMap<AcupunctCoordinate, Acupunct>()
private val coordinatesByLabel = HashMap<String, AcupunctCoordinate>()
private val byMeridian = HashMap<Meridian, MutableList<Acupunct>>()
private val all = LinkedList<Acupunct>()
fun build(
meridian: Meridian,
number: Int,
germanName: String,
chineseName: String,
note: String,
localisation: String,
joinedIndications: String,
flags: List<AcupunctFlag>
): Acupunct {
val indications = Splitter.on(",").trimResults().split(joinedIndications).toList()
val coordinate = AcupunctCoordinate(meridian, number)
coordinatesByLabel.put(coordinate.label, coordinate)
return Acupunct(coordinate, germanName, chineseName, note, localisation, indications, flags).apply {
acupunctByCoordinate.put(coordinate, this)
if (!byMeridian.contains(meridian)) byMeridian.put(meridian, LinkedList<Acupunct>())
byMeridian[meridian]!!.add(this)
all.add(this)
}
}
fun coordinateByLabel(label: String) = coordinatesByLabel[label]
fun byCoordinate(coordinate: AcupunctCoordinate) = acupunctByCoordinate[coordinate]
fun byLabel(label: String): Acupunct? {
val coordinate = coordinateByLabel(label) ?: return null
return acupunctByCoordinate[coordinate]
}
fun allForMeridian(meridian: Meridian): List<Acupunct> {
return byMeridian[meridian] ?: throw IllegalStateException("This sucks. Acupunct loading is cripled, as not yet loaded for meridian $meridian!")
}
fun all(): List<Acupunct> {
// this is kind of a hack... needs complete rework this acupunct stuff...
Acupuncts.enforceEagerLoading()
return all
}
}
init {
if (!disableAcupunctVerification) {
verifyFlags()
}
}
val isMarinaportant: Boolean by lazy { flags.contains(AcupunctFlag.Marinaportant) }
// delegation is not working properly due to mismatching Comparable<T> interfaces
val meridian: Meridian = coordinate.meridian
val number: Int = coordinate.number
// move to and delegate by AcupunctCoordinate??
val titleLong: String get() = "${meridian.labelLong} $number"
/** Lu1, Bl12, ... */
val titleShort: String get() = "${meridian.labelShort}$number"
val elementFlag: AcupunctFlag.ElementPoint? = flags.filterIsInstance(AcupunctFlag.ElementPoint::class.java).firstOrNull()
override fun equals(other: Any?): Boolean {
if (other !is Acupunct) {
return false
}
return this.coordinate == other.coordinate
}
override fun hashCode() = this.coordinate.hashCode()
override fun compareTo(other: Acupunct) = this.coordinate.compareTo(other.coordinate)
override fun toString() = coordinate.label
fun verifyFlags() {
if (flags.sorted() != flags) {
throw GadsuException("$this: Flags must be in precise order! Was: ${flags.joinToString()}, but should be: ${flags.sorted().joinToString()}")
}
if (flags.filter { it is AcupunctFlag.ElementPoint }.size > 1) {
throw GadsuException("$this: Flags must only contain 0 or 1 element point, but was: " + flags.joinToString(", "))
}
}
}
data class AcupunctCoordinate(
val meridian: Meridian,
val number: Int
) : Comparable<AcupunctCoordinate> {
companion object {
// MINOR #118 be more precise when it comes to acupunct coordinages (there is no Lu99!)
private val regexp = Pattern.compile("((Lu)|(Di)|(Ma)|(MP)|(He)|(Due)|(Bl)|(Ni)|(Pk)|(3E)|(Gb)|(Le))[1-9][0-9]?")
fun isPotentialLabel(potent: String) = regexp.matcher(potent).matches()
/** Just a synonym. */
fun byLabel(label: String) = Acupunct.coordinateByLabel(label)
}
/** E.g. "Lu1", "3E21, "Due14" */
val label = meridian.labelShort + number
override fun compareTo(other: AcupunctCoordinate): Int {
return ComparisonChain.start()
.compare(this.meridian, other.meridian)
.compare(this.number, other.number)
.result()
}
override fun equals(other: Any?): Boolean {
if (other !is AcupunctCoordinate) {
return false
}
return Objects.equals(this.meridian, other.meridian) &&
this.number == other.number
}
override fun hashCode() = Objects.hash(meridian, number)
}
interface AcupunctFlagCallback<T> {
companion object {
val LABELIZE: AcupunctFlagCallback<String> = AcupunctFlagStringCallback.INSTANCE
val LABELIZE_SHORT: AcupunctFlagCallback<String> = AcupunctFlagStringShortCallback.INSTANCE
}
fun onMarinaportant(flag: AcupunctFlag.Marinaportant): T
fun onOrientation(flag: AcupunctFlag.Orientation): T
fun onBoPoint(flag: AcupunctFlag.BoPoint): T
fun onElementPoint(flag: AcupunctFlag.ElementPoint): T
fun onYuPoint(flag: AcupunctFlag.YuPoint): T
fun onOriginalPoint(flag: AcupunctFlag.OriginalPoint): T
fun onNexusPoint(flag: AcupunctFlag.NexusPoint): T
fun onMasterPoint(flag: AcupunctFlag.MasterPoint): T
fun onKeyPoint(flag: AcupunctFlag.KeyPoint): T
fun onTonePoint(flag: AcupunctFlag.TonePoint): T
fun onSedatePoint(flag: AcupunctFlag.SedatePoint): T
fun onJingPoint(flag: AcupunctFlag.JingPoint): T
fun onEntryPoint(flag: AcupunctFlag.EntryPoint): T
}
open class AcupunctFlagStringCallback private constructor() : AcupunctFlagCallback<String> {
companion object {
val INSTANCE = AcupunctFlagStringCallback()
}
override fun onMarinaportant(flag: AcupunctFlag.Marinaportant) = flag.label
override fun onOrientation(flag: AcupunctFlag.Orientation) = flag.label
override fun onBoPoint(flag: AcupunctFlag.BoPoint) = "${flag.label} ${flag.meridian.labelShort}"
override fun onYuPoint(flag: AcupunctFlag.YuPoint) = "${flag.label} ${flag.meridian.labelShort}"
override fun onElementPoint(flag: AcupunctFlag.ElementPoint) = flag.element.label + "punkt"
override fun onOriginalPoint(flag: AcupunctFlag.OriginalPoint) = flag.label
override fun onNexusPoint(flag: AcupunctFlag.NexusPoint) = flag.label
override fun onMasterPoint(flag: AcupunctFlag.MasterPoint) = flag.label
override fun onKeyPoint(flag: AcupunctFlag.KeyPoint) = "${flag.label} ${flag.meridianx.label}"
override fun onTonePoint(flag: AcupunctFlag.TonePoint) = flag.label
override fun onSedatePoint(flag: AcupunctFlag.SedatePoint) = flag.label
override fun onJingPoint(flag: AcupunctFlag.JingPoint) = flag.label
override fun onEntryPoint(flag: AcupunctFlag.EntryPoint) = "${flag.label} ${flag.meridian.labelShort}"
}
open class AcupunctFlagStringShortCallback private constructor() : AcupunctFlagCallback<String> {
companion object {
val INSTANCE = AcupunctFlagStringShortCallback()
}
override fun onMarinaportant(flag: AcupunctFlag.Marinaportant) = flag.labelShort
override fun onOrientation(flag: AcupunctFlag.Orientation) = flag.labelShort
override fun onBoPoint(flag: AcupunctFlag.BoPoint) = "${flag.labelShort} ${flag.meridian.labelShort}"
override fun onYuPoint(flag: AcupunctFlag.YuPoint) = "${flag.labelShort} ${flag.meridian.labelShort}"
override fun onElementPoint(flag: AcupunctFlag.ElementPoint) = flag.element.label
override fun onOriginalPoint(flag: AcupunctFlag.OriginalPoint) = flag.labelShort
override fun onNexusPoint(flag: AcupunctFlag.NexusPoint) = flag.labelShort
override fun onMasterPoint(flag: AcupunctFlag.MasterPoint) = flag.labelShort
override fun onKeyPoint(flag: AcupunctFlag.KeyPoint) = "${flag.labelShort} ${flag.meridianx.label}"
override fun onTonePoint(flag: AcupunctFlag.TonePoint) = flag.labelShort
override fun onSedatePoint(flag: AcupunctFlag.SedatePoint) = flag.labelShort
override fun onJingPoint(flag: AcupunctFlag.JingPoint) = flag.labelShort
override fun onEntryPoint(flag: AcupunctFlag.EntryPoint) = "${flag.labelShort} ${flag.meridian.labelShort}"
}
@Suppress("unused")
sealed class AcupunctFlag(
val label: String,
val labelShort: String,
private val compareWeight: Int,
val renderShortLabel: Boolean = true
) : Comparable<AcupunctFlag> {
abstract fun <T> onFlagType(callback: AcupunctFlagCallback<T>): T
open protected fun additionalCompareTo(other: AcupunctFlag): Int {
return 0
}
// ! kontrindiziert bei schwangerschaft
// ? erfahrungsstelle (marina) =??= verbindungspunkt (DTV) fuer zb Lu? oder nase
// ? RIM?
// notfallpunkt
// akutpunkt, zb Ma34
// https://en.renmai.at/index.php?m=meridiane&style=0&page=28
// https://www.renmai.at/index.php?m=meridiane&style=0&page=28
override fun compareTo(other: AcupunctFlag): Int {
if (this.compareWeight == other.compareWeight) {
return additionalCompareTo(other)
}
return this.compareWeight - other.compareWeight
}
/** Important for marina. */
// =================================================================================================================
object Marinaportant : AcupunctFlag("Wichtig", "!!!", 0, renderShortLabel = false) {
override fun <T> onFlagType(callback: AcupunctFlagCallback<T>) = callback.onMarinaportant(this)
override fun toString() = "Marinaportant"
}
/** Helpful for orientation. */
// =================================================================================================================
object Orientation : AcupunctFlag("Orientation", "Ort", 1) {
override fun <T> onFlagType(callback: AcupunctFlagCallback<T>) = callback.onOrientation(this)
override fun toString() = "Orientation"
}
/** Alarmpunkt, japan. "bo", chin. "mu" */
// con ab = sammlungspunkt lt dtv atlas
// =================================================================================================================
class BoPoint private constructor(val meridian: Meridian) : AcupunctFlag("Bopunkt", "BO", 2) {
companion object {
val Lung = BoPoint(Meridian.Lung)
val LargeIntestine = BoPoint(Meridian.LargeIntestine)
val Stomach = BoPoint(Meridian.Stomach)
val Spleen = BoPoint(Meridian.Spleen)
val Heart = BoPoint(Meridian.Heart)
val SmallIntestine = BoPoint(Meridian.SmallIntestine)
val UrinaryBladder = BoPoint(Meridian.UrinaryBladder)
val Kidney = BoPoint(Meridian.Kidney)
val Pericardium = BoPoint(Meridian.Pericardium)
val TripleBurner = BoPoint(Meridian.TripleBurner)
val GallBladder = BoPoint(Meridian.GallBladder)
}
override fun <T> onFlagType(callback: AcupunctFlagCallback<T>) = callback.onBoPoint(this)
override fun toString() = "BoPoint[meridian=$meridian]"
}
/** Zustimmungspunkt japan. "yu", chin. "shu" */
// =================================================================================================================
class YuPoint private constructor(val meridian: Meridian) : AcupunctFlag("Yupunkt", "YU", 3) {
companion object {
val Lung = YuPoint(Meridian.Lung)
val LargeIntestine = YuPoint(Meridian.LargeIntestine)
val Stomach = YuPoint(Meridian.Stomach)
val Spleen = YuPoint(Meridian.Spleen)
val Heart = YuPoint(Meridian.Heart)
val SmallIntestine = YuPoint(Meridian.SmallIntestine)
val UrinaryBladder = YuPoint(Meridian.UrinaryBladder)
val Kidney = YuPoint(Meridian.Kidney)
val Pericardium = YuPoint(Meridian.Pericardium)
val TripleBurner = YuPoint(Meridian.TripleBurner)
val GallBladder = YuPoint(Meridian.GallBladder)
}
override fun <T> onFlagType(callback: AcupunctFlagCallback<T>) = callback.onYuPoint(this)
override fun toString() = "YuPoint[meridian=$meridian]"
}
/** Wandlungsphasen Zuordnung. */
// =================================================================================================================
class ElementPoint private constructor(val element: Element) : AcupunctFlag("Element", "5E", 4, renderShortLabel = false) {
companion object {
val Wood = ElementPoint(Element.Wood)
val Fire = ElementPoint(Element.Fire)
val Earth = ElementPoint(Element.Earth)
val Metal = ElementPoint(Element.Metal)
val Water = ElementPoint(Element.Water)
}
override fun <T> onFlagType(callback: AcupunctFlagCallback<T>) = callback.onElementPoint(this)
override fun toString() = "ElementPoint[element=$element]"
}
/** Quellpunkt / yuan / ORIG, ursprungsqi */
// =================================================================================================================
object OriginalPoint : AcupunctFlag("Quellpunkt", "ORIG", 5) {
override fun <T> onFlagType(callback: AcupunctFlagCallback<T>) = callback.onOriginalPoint(this)
override fun toString() = "OriginalPoint"
}
/** Durchgangspunkt / luo / NEX(orien) */
// NEX=verknuepfungspunkt; zb mit KG!!!
// =================================================================================================================
object NexusPoint : AcupunctFlag("Durchgangspunkt", "NEX", 6) {
override fun <T> onFlagType(callback: AcupunctFlagCallback<T>) = callback.onNexusPoint(this)
override fun toString() = "NexusPoint"
}
/** Meisterpunkt fuer meridian (gefaesssystem) / ba hui xue */
// =================================================================================================================
object MasterPoint : AcupunctFlag("Meisterpunkt", "MAST", 7) {
override fun <T> onFlagType(callback: AcupunctFlagCallback<T>) = callback.onMasterPoint(this)
override fun toString() = "MasterPoint"
}
/** Schluesselpunkt (oeffnungspunkt) / ba mai jiao hui xue */
// =================================================================================================================
class KeyPoint private constructor(val meridianx: UnpairedMeridian) : AcupunctFlag("Schlüsselpunkt", "KEY", 8) {
companion object {
val ChongMai = KeyPoint(UnpairedMeridian.ChongMai)
}
override fun <T> onFlagType(callback: AcupunctFlagCallback<T>) = callback.onKeyPoint(this)
override fun toString() = "KeyPoint[meridianx=$meridianx]"
}
/** Tonisierungspunkt / bu punkt */
// =================================================================================================================
object TonePoint : AcupunctFlag("Tonisierungspunkt", "TON", 9) {
override fun <T> onFlagType(callback: AcupunctFlagCallback<T>) = callback.onTonePoint(this)
override fun toString() = "TonePoint"
}
/** Sedierungspunkt / xie punkt */
// =================================================================================================================
object SedatePoint : AcupunctFlag("Sedierungspunkt", "SED", 10) {
override fun <T> onFlagType(callback: AcupunctFlagCallback<T>) = callback.onSedatePoint(this)
override fun toString() = "SedatePoint"
}
/** brunnenpunkt / jing*/
// =================================================================================================================
object JingPoint : AcupunctFlag("Brunnenpunkt", "JING", 11) {
override fun <T> onFlagType(callback: AcupunctFlagCallback<T>) = callback.onJingPoint(this)
override fun toString() = "JingPoint"
}
/** Eintrittspunkt */
// =================================================================================================================
class EntryPoint private constructor(val meridian: Meridian) : AcupunctFlag("Eintrittspunkt", "EIN", 12) {
companion object {
val Heart = EntryPoint(Meridian.Heart)
}
override fun <T> onFlagType(callback: AcupunctFlagCallback<T>) = callback.onEntryPoint(this)
override fun toString() = "EntryPoint[meridian=$meridian]"
}
}
| apache-2.0 | ce181eca75f1700a9e1faeff471691c7 | 44.454545 | 156 | 0.614629 | 3.970054 | false | false | false | false |
eugeis/ee | ee-system/src/main/kotlin/ee/system/dev/Maven.kt | 1 | 3583 | package ee.system.dev
import ee.common.ext.exists
import ee.task.ExecConfig
import ee.task.Result
import ee.task.exec
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import java.util.concurrent.TimeUnit
open class Maven : MavenBase {
companion object {
val EMPTY = MavenBase.EMPTY
}
val mvn: Path
val defaultParams: Map<String, String>
val defaultFlags: List<String>
val defaultProfiles: List<String>
val defaultCommandSuffix: String
constructor(home: Path = Paths.get(""), plugins: MutableList<String> = arrayListOf(),
defaultParams: MutableMap<String, String> = hashMapOf(), defaultFlags: List<String> = arrayListOf(),
defaultProfiles: List<String> = arrayListOf(), defaultCommandSuffix: String = "") : super("maven", home,
plugins) {
mvn = home.resolve("bin/mvn")
this.defaultParams = defaultParams
this.defaultFlags = defaultFlags
this.defaultProfiles = defaultProfiles
this.defaultCommandSuffix = defaultCommandSuffix
}
override fun build(buildHome: Path, request: BuildRequest, output: (String) -> Unit): Result {
val command = command(BuildRequest(tasks = ArrayList(request.tasks), params = HashMap(request.params),
flags = ArrayList(request.flags), profiles = ArrayList(request.profiles)))
val ret = buildHome.exec(
ExecConfig(home = buildHome, cmd = command, wait = true, timeout = 10, timeoutUnit = TimeUnit.MINUTES),
output = output)
return Result(ok = (ret == 0))
}
fun command(request: BuildRequest): List<String> {
val ret = arrayListOf<String>()
ret.add(mvn.toString())
prepareTasks(request)
ret.addAll(request.tasks)
defaultParams.fillParams(ret)
request.params.fillParams(ret)
defaultFlags.fillFlags(ret)
request.flags.fillFlags(ret)
defaultProfiles.fillProfiles(ret)
request.profiles.fillProfiles(ret)
if (defaultCommandSuffix.isNotBlank()) {
ret.add(defaultCommandSuffix)
}
return ret
}
private fun prepareTasks(request: BuildRequest) {
convertPluginTasks(request)
val tasks = request.tasks
if (tasks.isEmpty()) {
request.task("install")
} else {
if (tasks.remove("build")) {
request.task("install")
}
if (!tasks.contains("test")) {
request.flag("skipTests")
} else if (tasks.size > 1) {
tasks.remove("test")
}
}
}
private fun convertPluginTasks(request: BuildRequest) {
val tasks = ArrayList(request.tasks)
request.tasks.clear()
tasks.forEach { task ->
val plugin = plugins.find { task.endsWith(it, true) }
if (plugin != null) {
request.tasks.add(if (task == plugin) "$plugin:$task" else "$plugin:${task.substring(0,
task.length - plugin.length)}")
} else {
request.tasks.add(task)
}
}
}
fun Map<String, String>.fillParams(to: MutableList<String>) {
to.addAll(this.map { "-D${it.key}=${it.value}" })
}
fun List<String>.fillFlags(to: MutableList<String>) {
to.addAll(map { "-D$it" })
}
fun List<String>.fillProfiles(to: MutableList<String>) {
to.addAll(map { "-P$it" })
}
override fun supports(buildHome: Path): Boolean = buildHome.resolve("pom.xml").exists()
}
| apache-2.0 | 7844279c4de85f2b44a70f77a93af215 | 31.572727 | 115 | 0.607033 | 4.185748 | false | false | false | false |
cliffano/swaggy-jenkins | clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/PipelineActivity.kt | 1 | 2886 | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import org.openapitools.model.PipelineActivityartifacts
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
*
* @param propertyClass
* @param artifacts
* @param durationInMillis
* @param estimatedDurationInMillis
* @param enQueueTime
* @param endTime
* @param id
* @param organization
* @param pipeline
* @param result
* @param runSummary
* @param startTime
* @param state
* @param type
* @param commitId
*/
data class PipelineActivity(
@Schema(example = "null", description = "")
@field:JsonProperty("_class") val propertyClass: kotlin.String? = null,
@field:Valid
@Schema(example = "null", description = "")
@field:JsonProperty("artifacts") val artifacts: kotlin.collections.List<PipelineActivityartifacts>? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("durationInMillis") val durationInMillis: kotlin.Int? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("estimatedDurationInMillis") val estimatedDurationInMillis: kotlin.Int? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("enQueueTime") val enQueueTime: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("endTime") val endTime: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("id") val id: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("organization") val organization: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("pipeline") val pipeline: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("result") val result: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("runSummary") val runSummary: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("startTime") val startTime: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("state") val state: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("type") val type: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("commitId") val commitId: kotlin.String? = null
) {
}
| mit | 0fc634d2afe4781d1bc5ac750187321b | 32.952941 | 111 | 0.708247 | 4.128755 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/observation/sync/ObservationFetchWorker.kt | 1 | 2246 | package mil.nga.giat.mage.observation.sync
import android.content.Context
import android.util.Log
import androidx.hilt.work.HiltWorker
import androidx.work.*
import androidx.work.PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import mil.nga.giat.mage.data.observation.ObservationRepository
import mil.nga.giat.mage.sdk.utils.UserUtility
import java.util.*
import java.util.concurrent.TimeUnit
@HiltWorker
class ObservationFetchWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val observationRepository: ObservationRepository
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
// Check token
if (UserUtility.getInstance(applicationContext).isTokenExpired) {
Log.d(LOG_NAME, "Token expired, turn off observation fetch worker.")
return Result.failure();
}
Log.d(LOG_NAME, "Fetching observations.")
// Fetch observations
// TODO would be nice to know if we got back a 401, in that case we should turn off
observationRepository.fetch(notify = true)
return Result.success()
}
companion object {
private val LOG_NAME = ObservationFetchWorker::class.java.simpleName
private const val OBSERVATION_FETCH_WORK= "mil.nga.mage.OBSERVATION_FETCH_WORK"
private fun workRequest(): PeriodicWorkRequest {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
return PeriodicWorkRequestBuilder<ObservationFetchWorker>(MIN_PERIODIC_INTERVAL_MILLIS, TimeUnit.MILLISECONDS)
.setConstraints(constraints)
.build()
}
fun beginWork(context: Context): UUID {
val request = workRequest()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(OBSERVATION_FETCH_WORK, ExistingPeriodicWorkPolicy.KEEP, request)
return request.id
}
fun stopWork(context: Context) {
WorkManager.getInstance(context).cancelUniqueWork(OBSERVATION_FETCH_WORK);
}
}
} | apache-2.0 | 63c0eb37ebfe599c4cbb731d43f984ba | 35.241935 | 136 | 0.701692 | 4.861472 | false | false | false | false |
wangjiegulu/AndroidKotlinBucket | example/src/main/kotlin/com/wangjie/androidkotlinbucket/example/MainActivity.kt | 1 | 1914 | package com.wangjie.androidkotlinbucket.example
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import com.wangjie.androidkotlinbucket.example.base.BaseActivity
import com.wangjie.androidkotlinbucket.library._pick
import com.wangjie.androidkotlinbucket.library._presenter
class MainActivity : BaseActivity(), MainViewer {
private val tv: TextView by _pick(R.id.activity_main_tv)
override val presenter: MainPresenter by _presenter { MainPresenter(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
tv.text = "inject succeed"
// _click(onClickListener, R.id.activity_main_test_a_btn)
arrayOf(R.id.activity_main_test_a_btn)
.forEach { findViewById(it).setOnClickListener(onClickListener) }
arrayOf(tv)
.forEach { it.setOnClickListener(onClickListener) }
}
val onClickListener: (View) -> Unit = {
when (it.id) {
R.id.activity_main_tv,
R.id.activity_main_test_a_btn -> presenter.test()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true
}
return super.onOptionsItemSelected(item)
}
}
| apache-2.0 | b66793f7dbeffed112a3422704676796 | 31.440678 | 81 | 0.679206 | 4.359909 | false | true | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/ide/inspections/fixes/SubstituteTextFix.kt | 3 | 2262 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.fixes
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.SmartPointerManager
/**
* Fix that removes the given range from the document and places a text onto its place.
* @param fixName The name to use for the fix instead of the default one to better fit the inspection.
* @param file
* @param range The range *inside element* that will be removed from the document.
* @param substitution The text that will be placed starting from `range.startOffset`. If `null`, no text will be inserted.
*/
class SubstituteTextFix private constructor(
private val fixName: String = "Substitute",
file: PsiFile,
range: TextRange,
private val substitution: String?
) : LocalQuickFix {
private val fileWithRange = SmartPointerManager.getInstance(file.project)
.createSmartPsiFileRangePointer(file, range)
override fun getName(): String = fixName
override fun getFamilyName() = "Substitute one text to another"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val file = fileWithRange.containingFile ?: return
val range = fileWithRange.range ?: return
val document = PsiDocumentManager.getInstance(project).getDocument(file)
document?.deleteString(range.startOffset, range.endOffset)
if (substitution != null) {
document?.insertString(range.startOffset, substitution)
}
}
companion object {
fun delete(fixName: String, file: PsiFile, range: TextRange) =
SubstituteTextFix(fixName, file, range, null)
fun insert(fixName: String, file: PsiFile, offsetInElement: Int, text: String) =
SubstituteTextFix(fixName, file, TextRange(offsetInElement, offsetInElement), text)
fun replace(fixName: String, file: PsiFile, range: TextRange, text: String) =
SubstituteTextFix(fixName, file, range, text)
}
}
| mit | fa57ec1ef64c9cbc2bd5b2b215e039c8 | 39.392857 | 123 | 0.729443 | 4.606925 | false | false | false | false |
nestlabs/connectedhomeip | src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/attestation/AttestationTestFragment.kt | 2 | 1243 | package com.google.chip.chiptool.attestation
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.chip.chiptool.R
import kotlinx.android.synthetic.main.attestation_test_fragment.view.*
/** Fragment for launching external attestation apps */
class AttestationTestFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.attestation_test_fragment, container, false).apply {
attestationText.text = context.getString(R.string.attestation_fetching_status)
val appIntent = AttestationAppLauncher.getAttestationIntent(requireContext())
if (appIntent != null) {
AttestationAppLauncher
.getLauncher(this@AttestationTestFragment) { result ->
attestationText.text = result
}
.launch(appIntent)
} else {
attestationText.text = context.getString(R.string.attestation_app_not_found)
}
}
}
companion object {
@JvmStatic
fun newInstance(): AttestationTestFragment = AttestationTestFragment()
}
}
| apache-2.0 | 4465ef40b201ebbd3cef438ac2f57e32 | 31.710526 | 89 | 0.729686 | 4.088816 | false | true | false | false |
square/leakcanary | shark/src/main/java/shark/internal/ObjectArrayReferenceReader.kt | 2 | 1890 | package shark.internal
import shark.HeapObject.HeapObjectArray
import shark.internal.Reference.LazyDetails
import shark.internal.ReferenceLocationType.ARRAY_ENTRY
import shark.ValueHolder
internal class ObjectArrayReferenceReader : ReferenceReader<HeapObjectArray> {
override fun read(source: HeapObjectArray): Sequence<Reference> {
if (source.isSkippablePrimitiveWrapperArray) {
// primitive wrapper arrays aren't interesting.
// That also means the wrapped size isn't added to the dominator tree, so we need to
// add that back when computing shallow size in ShallowSizeCalculator.
// Another side effect is that if the wrapped primitive is referenced elsewhere, we might
// double count its size.
return emptySequence()
}
val graph = source.graph
val record = source.readRecord()
val arrayClassId = source.arrayClassId
return record.elementIds.asSequence().filter { objectId ->
objectId != ValueHolder.NULL_REFERENCE && graph.objectExists(objectId)
}.mapIndexed { index, elementObjectId ->
Reference(
valueObjectId = elementObjectId,
isLowPriority = false,
lazyDetailsResolver = {
LazyDetails(
name = index.toString(),
locationClassObjectId = arrayClassId,
locationType = ARRAY_ENTRY,
isVirtual = false,
matchedLibraryLeak = null
)
}
)
}
}
internal companion object {
private val skippablePrimitiveWrapperArrayTypes = setOf(
Boolean::class,
Char::class,
Float::class,
Double::class,
Byte::class,
Short::class,
Int::class,
Long::class
).map { it.javaObjectType.name + "[]" }
internal val HeapObjectArray.isSkippablePrimitiveWrapperArray: Boolean
get() = arrayClassName in skippablePrimitiveWrapperArrayTypes
}
}
| apache-2.0 | 75cd44cff308938fe1d1e344d098425e | 33.363636 | 95 | 0.684656 | 4.921875 | false | false | false | false |
toastkidjp/Jitte | todo/src/main/java/jp/toastkid/todo/view/board/BoardFragment.kt | 1 | 4924 | /*
* Copyright (c) 2019 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.todo.view.board
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.children
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import jp.toastkid.lib.AppBarViewModel
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.todo.R
import jp.toastkid.todo.databinding.AppBarBoardBinding
import jp.toastkid.todo.databinding.FragmentTaskBoardBinding
import jp.toastkid.todo.model.TodoTask
import jp.toastkid.todo.view.addition.TaskAdditionDialogFragmentUseCase
import jp.toastkid.todo.view.addition.TaskAdditionDialogFragmentViewModel
import jp.toastkid.todo.view.item.menu.ItemMenuPopup
import jp.toastkid.todo.view.item.menu.ItemMenuPopupActionUseCase
import jp.toastkid.todo.view.list.TaskListFragmentViewModel
/**
* @author toastkidjp
*/
class BoardFragment : Fragment() {
private lateinit var binding: FragmentTaskBoardBinding
private lateinit var appBarBinding: AppBarBoardBinding
private var taskAdditionDialogFragmentUseCase: TaskAdditionDialogFragmentUseCase? = null
private var taskAddingUseCase: TaskAddingUseCase? = null
private var taskClearUseCase: TaskClearUseCase? = null
private val tasks = mutableListOf<TodoTask>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_task_board, container, false)
appBarBinding = DataBindingUtil.inflate(inflater, R.layout.app_bar_board, container, false)
appBarBinding.fragment = this
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
var popup: ItemMenuPopup? = null
val viewModel = ViewModelProvider(this).get(TaskListFragmentViewModel::class.java)
viewModel
.showMenu
.observe(viewLifecycleOwner, Observer { event ->
event.getContentIfNotHandled()?.let {
popup?.show(it.first, it.second)
}
})
taskAdditionDialogFragmentUseCase =
TaskAdditionDialogFragmentUseCase(
this,
ViewModelProvider(this).get(TaskAdditionDialogFragmentViewModel::class.java)
) {
val firstOrNull = tasks.firstOrNull { task -> task.lastModified == it.lastModified }
if (firstOrNull == null) {
it.id = tasks.size + 1
taskAddingUseCase?.invoke(it)
return@TaskAdditionDialogFragmentUseCase
}
tasks.remove(firstOrNull)
removeTask(firstOrNull)
taskAddingUseCase?.invoke(firstOrNull)
}
popup = ItemMenuPopup(
view.context,
ItemMenuPopupActionUseCase(
{ taskAdditionDialogFragmentUseCase?.invoke(it) },
::removeTask
)
)
taskAddingUseCase = TaskAddingUseCase(
PreferenceApplier(view.context).color,
tasks,
binding.board,
BoardItemViewFactory(layoutInflater) { parent, showTask ->
popup.show(parent, showTask)
}
)
activity?.let {
val viewModelProvider = ViewModelProvider(it)
viewModelProvider.get(AppBarViewModel::class.java).replace(appBarBinding.root)
taskClearUseCase = TaskClearUseCase(
tasks,
viewModelProvider.get(ContentViewModel::class.java),
taskAddingUseCase
) { binding.board.removeAllViews() }
}
taskAddingUseCase?.invoke(makeSampleTask())
}
private fun makeSampleTask() = SampleTaskMaker().invoke()
private fun removeTask(task: TodoTask) {
tasks.remove(task)
binding.board.children
.firstOrNull { it.tag == task.id }
?.also { binding.board.removeView(it) }
}
fun addTask() {
taskAdditionDialogFragmentUseCase?.invoke()
}
fun clearTasks() {
taskClearUseCase?.invoke()
}
} | epl-1.0 | ff28dd7067cb69b9c127371fa54cddda | 34.178571 | 104 | 0.648253 | 5.210582 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/lang/refactoring/introduceVariable/RsNameSuggestions.kt | 1 | 3573 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.refactoring.introduceVariable
import com.intellij.psi.PsiElement
import com.intellij.psi.codeStyle.NameUtil
import org.rust.ide.inspections.toSnakeCase
import org.rust.ide.utils.CallInfo
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.ancestorOrSelf
import org.rust.lang.core.psi.ext.ancestorStrict
import org.rust.lang.core.psi.ext.descendantsOfType
import org.rust.lang.core.resolve.hitOnFalse
import org.rust.lang.core.types.ty.TyInteger
import org.rust.lang.core.types.ty.TyAdt
import org.rust.lang.core.types.ty.TyTraitObject
import org.rust.lang.core.types.ty.TyTypeParameter
import org.rust.lang.core.types.type
import org.rust.lang.refactoring.isValidRustVariableIdentifier
class SuggestedNames(
val default: String,
val all: LinkedHashSet<String>
)
/**
* This suggests names for an expression about to be bound to a local variable
*
* If the type is resolved and nominal, suggest it.
* If its an argument to a function call, suggest the name of the argument in the function definition.
* If its a function call suggest the name of the function and the enclosing name space (if any).
* If the expression is in a struct literal (Foo {x: 5, y: 6}) suggest the tag for the expression as a name
* If a name is already bound in the local scope do not suggest it.
*/
fun RsExpr.suggestedNames(): SuggestedNames {
val names = LinkedHashSet<String>()
val type = type
when (type) {
is TyInteger -> names.addName("i")
is TyTypeParameter -> names.addName(type.name)
is TyAdt -> names.addName(type.item.name)
is TyTraitObject -> names.addName(type.trait.element.name)
}
val parent = this.parent
if (parent is RsValueArgumentList) {
val call = parent.ancestorStrict<RsCallExpr>()?.let { CallInfo.resolve(it) }
if (call != null) {
val paramName = call.parameters
.getOrNull(parent.exprList.indexOf(this))
?.pattern
names.addName(paramName)
}
}
if (this is RsCallExpr) {
nameForCall(this).forEach { names.addName(it) }
}
if (parent is RsStructLiteralField) {
names.addName(parent.identifier.text)
}
val usedNames = findNamesInLocalScope(this)
names.removeAll(usedNames)
return SuggestedNames(names.firstOrNull() ?: "x", names)
}
private val uselessNames = listOf("new", "default")
private fun LinkedHashSet<String>.addName(name: String?) {
if (name == null || name in uselessNames || !isValidRustVariableIdentifier(name)) return
NameUtil.getSuggestionsByName(name, "", "", false, false, false)
.filter { it !in uselessNames && IntroduceVariableTestmarks.invalidNamePart.hitOnFalse(isValidRustVariableIdentifier(it)) }
.mapTo(this) { it.toSnakeCase(false) }
}
private fun nameForCall(expr: RsCallExpr): List<String> {
val pathElement = expr.expr
if (pathElement is RsPathExpr) {
val path = pathElement.path
//path.path.identifier gives us the x's out of: Xxx::<T>::yyy
return listOf(path.identifier, path.path?.identifier)
.filterNotNull().map(PsiElement::getText)
}
return listOf(pathElement.text)
}
private fun findNamesInLocalScope(expr: PsiElement): List<String> {
val blockScope = expr.ancestorOrSelf<RsBlock>()
val letDecls = blockScope?.descendantsOfType<RsLetDecl>().orEmpty()
return letDecls.mapNotNull { it.pat?.text }
}
| mit | 52f5ed3e06f42865b606a4cb107aeabb | 35.090909 | 131 | 0.709488 | 3.879479 | false | false | false | false |
google/horologist | compose-layout/src/main/java/com/google/android/horologist/compose/paging/Items.kt | 1 | 3740 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.compose.paging
import android.annotation.SuppressLint
import android.os.Parcel
import android.os.Parcelable
import androidx.compose.runtime.Composable
import androidx.paging.compose.LazyPagingItems
import androidx.wear.compose.material.ScalingLazyListItemScope
import androidx.wear.compose.material.ScalingLazyListScope
import com.google.android.horologist.compose.navscaffold.ExperimentalHorologistComposeLayoutApi
/**
* Adds the [LazyPagingItems] and their content to the scope. The range from 0 (inclusive) to
* [LazyPagingItems.itemCount] (exclusive) always represents the full range of presentable items,
* because every event from [PagingDataDiffer] will trigger a recomposition.
*
* Code from https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:paging/paging-compose/src/main/java/androidx/paging/compose/LazyPagingItems.kt
*
* @sample androidx.paging.compose.samples.ItemsDemo
*
* @param items the items received from a [Flow] of [PagingData].
* @param key a factory of stable and unique keys representing the item. Using the same key
* for multiple items in the list is not allowed. Type of the key should be saveable
* via Bundle on Android. If null is passed the position in the list will represent the key.
* When you specify the key the scroll position will be maintained based on the key, which
* means if you add/remove items before the current visible item the item with the given key
* will be kept as the first visible one.
* @param itemContent the content displayed by a single item. In case the item is `null`, the
* [itemContent] method should handle the logic of displaying a placeholder instead of the main
* content displayed by an item which is not `null`.
*/
@ExperimentalHorologistComposeLayoutApi
public fun <T : Any> ScalingLazyListScope.items(
items: LazyPagingItems<T>,
key: ((item: T) -> Any)? = null,
itemContent: @Composable ScalingLazyListItemScope.(value: T?) -> Unit
) {
val keyFn: ((index: Int) -> Any)? = if (key == null) {
null
} else {
{ index ->
val item = items.peek(index)
if (item == null) {
PagingPlaceholderKey(index)
} else {
key(item)
}
}
}
items(
count = items.itemCount,
key = keyFn
) { index ->
itemContent(items[index])
}
}
@SuppressLint("BanParcelableUsage")
private data class PagingPlaceholderKey(private val index: Int) : Parcelable {
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(index)
}
override fun describeContents(): Int {
return 0
}
companion object {
@Suppress("unused")
@JvmField
val CREATOR: Parcelable.Creator<PagingPlaceholderKey> =
object : Parcelable.Creator<PagingPlaceholderKey> {
override fun createFromParcel(parcel: Parcel) = PagingPlaceholderKey(parcel.readInt())
override fun newArray(size: Int) = arrayOfNulls<PagingPlaceholderKey?>(size)
}
}
}
| apache-2.0 | 2c73198f7b807e126a0166dd85525f1d | 38.787234 | 167 | 0.71016 | 4.4 | false | false | false | false |
fython/PackageTracker | mobile/src/main/kotlin/com/spreada/utils/chinese/ZHConverter.kt | 1 | 4983 | package com.spreada.utils.chinese
import java.io.BufferedReader
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.util.HashMap
import java.util.HashSet
import java.util.Properties
class ZHConverter private constructor(propertyFile: String) {
private val charMap = Properties()
private val conflictingSets = HashSet<Any>()
init {
val inputStream: InputStream? = javaClass.getResourceAsStream(propertyFile)
if (inputStream != null) {
var reader: BufferedReader? = null
try {
reader = BufferedReader(InputStreamReader(inputStream))
charMap.load(reader)
} catch (e: FileNotFoundException) {
} catch (e: IOException) {
// TODO Auto-generated catch block
e.printStackTrace()
} finally {
try {
reader?.close()
inputStream.close()
} catch (e: IOException) {
}
}
}
initializeHelper()
}
private fun initializeHelper() {
val stringPossibilities = HashMap<String, Int>()
var iter: Iterator<*> = charMap.keys.iterator()
while (iter.hasNext()) {
val key = iter.next() as String
if (key.isNotEmpty()) {
for (i in 0 until key.length) {
val keySubstring = key.substring(0, i + 1)
if (stringPossibilities.containsKey(keySubstring)) {
val integer = stringPossibilities[keySubstring] as Int
stringPossibilities[keySubstring] = integer + 1
} else {
stringPossibilities[keySubstring] = 1
}
}
}
}
iter = stringPossibilities.keys.iterator()
while (iter.hasNext()) {
val key = iter.next()
if (stringPossibilities[key]!!.toInt() > 1) {
conflictingSets.add(key)
}
}
}
fun convert(inStr: String): String {
val outString = StringBuilder()
val stackString = StringBuilder()
for (i in 0 until inStr.length) {
val c = inStr[i]
val key = "" + c
stackString.append(key)
when {
conflictingSets.contains(stackString.toString()) -> {
}
charMap.containsKey(stackString.toString()) -> {
outString.append(charMap[stackString.toString()])
stackString.setLength(0)
}
else -> {
val sequence = stackString.subSequence(0, stackString.length - 1)
stackString.delete(0, stackString.length - 1)
flushStack(outString, StringBuilder(sequence))
}
}
}
flushStack(outString, stackString)
return outString.toString()
}
private fun flushStack(outString: StringBuilder, stackString: StringBuilder) {
while (stackString.isNotEmpty()) {
if (charMap.containsKey(stackString.toString())) {
outString.append(charMap[stackString.toString()])
stackString.setLength(0)
} else {
outString.append("" + stackString[0])
stackString.delete(0, 1)
}
}
}
internal fun parseOneChar(c: String): String {
return if (charMap.containsKey(c)) charMap[c] as String else c
}
companion object {
const val TRADITIONAL = 0
const val SIMPLIFIED = 1
private const val NUM_OF_CONVERTERS = 2
private val converters = arrayOfNulls<ZHConverter>(NUM_OF_CONVERTERS)
private val propertyFiles = arrayOfNulls<String>(2)
init {
propertyFiles[TRADITIONAL] = "zh2Hant.properties"
propertyFiles[SIMPLIFIED] = "zh2Hans.properties"
}
/**
*
* @param converterType 0 for traditional and 1 for simplified
* @return
*/
fun getInstance(converterType: Int): ZHConverter? {
if (converterType in 0..(NUM_OF_CONVERTERS - 1)) {
if (converters[converterType] == null) {
synchronized(ZHConverter::class.java) {
if (converters[converterType] == null) {
converters[converterType] = ZHConverter(propertyFiles[converterType]!!)
}
}
}
return converters[converterType]
} else {
return null
}
}
fun convert(text: String, converterType: Int): String {
val instance = getInstance(converterType)
return instance!!.convert(text)
}
}
}
| gpl-3.0 | 019cf9175c888bce762cda99728575fd | 32 | 99 | 0.533012 | 4.978022 | false | false | false | false |
shaeberling/euler | kotlin/src/com/s13g/aoc/aoc2020/Day24.kt | 1 | 1689 | package com.s13g.aoc.aoc2020
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import com.s13g.aoc.XY
import com.s13g.aoc.addTo
/**
* --- Day 24: Lobby Layout ---
* https://adventofcode.com/2020/day/24
*/
class Day24 : Solver {
// Ordered from shortest to longest key!
private val directions = mapOf(
"w" to XY(-2, 0),
"e" to XY(2, 0),
"ne" to XY(1, 1),
"nw" to XY(-1, 1),
"se" to XY(1, -1),
"sw" to XY(-1, -1))
override fun solve(lines: List<String>): Result {
var tiles = mutableSetOf<XY>()
for (line in lines) processLine(line).apply { if (this !in tiles) tiles.add(this) else tiles.remove(this) }
val resultA = tiles.size
for (i in 1..100) {
val newTiles = mutableSetOf<XY>()
val min = XY(tiles.map { it.x }.min()!!, tiles.map { it.y }.min()!!)
val max = XY(tiles.map { it.x }.max()!!, tiles.map { it.y }.max()!!)
for (x in min.x - 2..max.x + 2) {
for (y in min.y - 2..max.y + 2) {
val count = directions.values.count { XY(x + it.x, y + it.y) in tiles }
val pos = XY(x, y)
if ((pos in tiles && (count != 0 && count <= 2)) || (pos !in tiles && count == 2)) {
newTiles.add(pos)
}
}
}
tiles = newTiles
}
return Result("$resultA", "${tiles.size}")
}
private fun processLine(line: String): XY {
val pos = XY(0, 0)
var idx = 0
while (idx < line.length) {
for (d in directions.keys) { // LinkedHashMap keeps order of keys!
if (line.startsWith(d, idx)) {
pos.addTo(directions[d]!!)
idx += d.length
break;
}
}
}
return pos
}
}
| apache-2.0 | df907d45a88eb128503689838087313f | 27.627119 | 111 | 0.530491 | 3.110497 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/ui/preferences/PreferenceViewModel.kt | 1 | 2875 | /*
* Copyright 2022, Lawnchair
*
* 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 app.lawnchair.ui.preferences
import android.app.Application
import android.content.Intent
import androidx.core.content.ContextCompat
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import app.lawnchair.icons.CustomAdaptiveIconDrawable
import app.lawnchair.ossnotices.getOssLibraries
import com.android.launcher3.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.stateIn
private val iconPackIntents = listOf(
Intent("com.novalauncher.THEME"),
Intent("org.adw.launcher.icons.ACTION_PICK_ICON"),
Intent("com.dlto.atom.launcher.THEME"),
Intent("android.intent.action.MAIN").addCategory("com.anddoes.launcher.THEME")
)
class PreferenceViewModel(private val app: Application) : AndroidViewModel(app), PreferenceInteractor {
override val iconPacks = flow {
val pm = app.packageManager
val iconPacks = iconPackIntents
.flatMap { pm.queryIntentActivities(it, 0) }
.associateBy { it.activityInfo.packageName }
.mapTo(mutableSetOf()) { (_, info) ->
IconPackInfo(
info.loadLabel(pm).toString(),
info.activityInfo.packageName,
CustomAdaptiveIconDrawable.wrapNonNull(info.loadIcon(pm))
)
}
val lawnchairIcon = CustomAdaptiveIconDrawable.wrapNonNull(
ContextCompat.getDrawable(app, R.drawable.ic_launcher_home)!!
)
val defaultIconPack = IconPackInfo(
name = app.getString(R.string.system_icons),
packageName = "",
icon = lawnchairIcon
)
val withSystemIcons = listOf(defaultIconPack) + iconPacks.sortedBy { it.name }
emit(withSystemIcons)
}
.flowOn(Dispatchers.Default)
.stateIn(viewModelScope, SharingStarted.Lazily, listOf())
override val ossLibraries = flow {
val ossLibraries = app.getOssLibraries(thirdPartyLicenseMetadataId = R.raw.third_party_license_metadata)
emit(ossLibraries)
}
.flowOn(Dispatchers.Default)
.stateIn(viewModelScope, SharingStarted.Lazily, null)
}
| gpl-3.0 | e62f36415350ca6f647f919e0ebd4182 | 37.851351 | 112 | 0.705391 | 4.423077 | false | false | false | false |
Ekito/koin | koin-projects/koin-test/src/test/kotlin/org/koin/test/CheckModulesTest.kt | 1 | 10242 | package org.koin.test
import org.junit.Assert.fail
import org.junit.Rule
import org.junit.Test
import org.koin.core.logger.Level
import org.koin.core.parameter.parametersOf
import org.koin.core.qualifier.named
import org.koin.core.scope.Scope
import org.koin.dsl.koinApplication
import org.koin.dsl.module
import org.koin.test.check.checkModules
import org.koin.test.mock.MockProviderRule
import org.mockito.Mockito
class CheckModulesTest {
@get:Rule
val mockProvider = MockProviderRule.create { clazz ->
Mockito.mock(clazz.java)
}
@Test
fun `check a scoped module`() {
koinApplication {
printLogger(Level.DEBUG)
modules(
module {
scope(named("scope")) {
scoped { Simple.ComponentA() }
scoped { Simple.ComponentB(get()) }
}
}
)
}.checkModules()
}
@Test
fun `check a scoped module and ext deps - failed `() {
try {
koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single { Simple.ComponentB(get()) }
scope(named("scope")) {
scoped { Simple.ComponentA() }
}
}
)
}.checkModules()
fail()
} catch (e: Throwable) {
e.printStackTrace()
}
}
@Test
fun `check a scoped module and ext scope - failed`() {
try {
koinApplication {
printLogger(Level.DEBUG)
modules(
module {
scope(named("scope2")) {
scoped { Simple.ComponentB(get()) }
}
scope(named("scope1")) {
scoped { Simple.ComponentA() }
}
}
)
}.checkModules()
fail()
} catch (e: Throwable) {
e.printStackTrace()
}
}
@Test
fun `check a scoped module and ext scope - create scope`() {
koinApplication {
printLogger(Level.DEBUG)
modules(
module {
scope(named("scope2")) {
scoped {
val a = getScope("scopei1").get<Simple.ComponentA>()
Simple.ComponentB(a)
}
}
scope(named("scope1")) {
scoped { Simple.ComponentA() }
}
}
)
}.checkModules {
koin.createScope("scopei1", named("scope1"))
}
}
@Test
fun `check a scoped module and ext scope - inject scope`() {
koinApplication {
printLogger(Level.DEBUG)
modules(
module {
scope(named("scope2")) {
scoped { (scope1: Scope) -> Simple.ComponentB(scope1.get()) }
}
scope(named("scope1")) {
scoped { Simple.ComponentA() }
}
}
)
}.checkModules {
create<Simple.ComponentB> { parametersOf(koin.createScope("scopei1", named("scope1"))) }
}
}
@Test
fun `check a simple module`() {
koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single { Simple.ComponentA() }
}
)
}.checkModules()
}
@Test
fun `check a module with link`() {
koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single { Simple.ComponentA() }
single { Simple.ComponentB(get()) }
}
)
}.checkModules()
}
@Test
fun `check a broken module`() {
try {
koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single { Simple.ComponentB(get()) }
}
)
}.checkModules()
fail("should not pass with borken definitions")
} catch (e: Exception) {
e.printStackTrace()
}
}
@Test
fun `check a module with params`() {
koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single { (s: String) -> Simple.MyString(s) }
single(UpperCase) { (s: String) -> Simple.MyString(s.toUpperCase()) }
}
)
}.checkModules {
create<Simple.MyString> { parametersOf("param") }
create<Simple.MyString>(UpperCase) { qualifier -> parametersOf(qualifier.toString()) }
}
}
@Test
fun `check a module with params using create method with KClass`() {
koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single { (s: String) -> Simple.MyString(s) }
single(UpperCase) { (s: String) -> Simple.MyString(s.toUpperCase()) }
}
)
}.checkModules {
create(Simple.MyString::class) { parametersOf("param") }
create(Simple.MyString::class, UpperCase) { qualifier ->
parametersOf(qualifier.toString())
}
}
}
@Test
fun `check a module with params - auto`() {
koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single { (s: String) -> Simple.MyString(s) }
single { (a: Simple.ComponentA) -> Simple.ComponentB(a) }
}
)
}.checkModules()
}
@Test
fun `check a module with params - default value`() {
val id = "_ID_"
var injectedValue: String? = null
koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single { (s: String) ->
injectedValue = s
Simple.MyString(s)
}
}
)
}.checkModules {
defaultValue(id)
}
assert(injectedValue == id)
}
@Test
fun `check a module with params - added default value in graph`() {
val id = "_ID_"
var _id = ""
val app = koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single {
_id = get()
Simple.MyString(_id)
}
}
)
}
app.checkModules {
defaultValue(id)
}
assert(id == _id)
}
@Test
fun `check a module with params - default value in graph`() {
var _value: String? = null
val app = koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single {
_value = get()
Simple.MyString(_value!!)
}
}
)
}
app.checkModules()
assert(_value == "")
}
@Test
fun `check a module with complex params - default mocked value in graph`() {
var _a: Simple.ComponentA? = null
val app = koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single {
_a = get()
Simple.ComponentB(_a!!)
}
}
)
}
app.checkModules {
defaultValue<Simple.ComponentA>()
}
assert(_a != null)
}
@Test
fun `check a module with params - default value object`() {
val a = Simple.ComponentA()
var injectedValue: Simple.ComponentA? = null
koinApplication {
printLogger(Level.DEBUG)
modules(
module {
single { (a: Simple.ComponentA) ->
injectedValue = a
Simple.ComponentB(a)
}
}
)
}.checkModules {
defaultValue(a)
}
assert(injectedValue == a)
}
@Test
fun `check a module with params - auto scope`() {
koinApplication {
printLogger(Level.DEBUG)
modules(
module {
scope<Simple.ComponentA> {
scoped { Simple.ComponentB(get()) }
}
}
)
}.checkModules()
}
@Test
fun `check a module with params - auto scope - error`() {
try {
koinApplication {
printLogger(Level.DEBUG)
modules(
module {
scope<Simple.ComponentA> {
scoped { Simple.ComponentC(get()) }
}
}
)
}.checkModules()
fail()
} catch (e: Exception) {
e.printStackTrace()
}
}
@Test
fun `check with qualifier`() {
koinApplication {
printLogger(Level.DEBUG)
modules(module {
single(named("test")) { Simple.ComponentA() }
})
}.checkModules()
}
@Test
fun `check a module with property`() {
koinApplication {
printLogger(Level.DEBUG)
properties(hashMapOf("aValue" to "value"))
modules(
module {
single { Simple.MyString(getProperty("aValue")) }
}
)
}.checkModules()
}
} | apache-2.0 | 3d7e79f212e4c4b82bf56a2cdcaa7a3a | 26.758808 | 100 | 0.425893 | 5.276662 | false | true | false | false |
jdm64/GenesisChess-Android | app/src/main/java/com/chess/genesis/activity/GameListPage.kt | 1 | 13095 | /* GenesisChess, an Android chess application
* Copyright 2022, Justin Madru ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://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.chess.genesis.activity
import android.content.*
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.foundation.shape.*
import androidx.compose.material.*
import androidx.compose.material.icons.*
import androidx.compose.material.icons.filled.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.ui.platform.*
import androidx.compose.ui.res.*
import androidx.compose.ui.text.font.*
import androidx.compose.ui.unit.*
import androidx.navigation.*
import androidx.paging.*
import androidx.paging.compose.*
import com.chess.genesis.R
import com.chess.genesis.data.*
import com.chess.genesis.db.*
import com.chess.genesis.net.*
import com.chess.genesis.util.*
import kotlinx.coroutines.*
class NewGameState {
var show = mutableStateOf(false)
var name = mutableStateOf("Untitled")
var type = mutableStateOf(Enums.GENESIS_CHESS)
var opp = mutableStateOf(Enums.INVITE_OPPONENT)
var color = mutableStateOf(Enums.RANDOM_OPP)
}
class EditGameState {
var show = mutableStateOf(false)
var name = mutableStateOf("")
lateinit var data: LocalGameEntity
}
class ImportGameState {
var show = mutableStateOf(false)
var id = mutableStateOf("")
}
fun onLoadGame(data: LocalGameEntity, nav: NavHostController, context: Context) {
nav.navigate("board/" + data.gameid)
}
fun onNewGame(data: NewGameState, nav: NavHostController, context: Context) {
data.show.value = false
Dispatchers.IO.dispatch(Dispatchers.IO) {
if (data.opp.value == Enums.INVITE_OPPONENT) {
val playAs = Enums.OppToPlayAs(data.opp.value)
ZeroMQClient.bind(context) { client ->
client.createInvite(
data.type.value,
playAs
)
}
} else {
val newGame = LocalGameDao.get(context).newLocalGame(data)
Dispatchers.Main.dispatch(Dispatchers.Main) {
onLoadGame(newGame, nav, context)
}
}
}
}
fun onDeleteGame(state: EditGameState, context: Context) {
state.show.value = false
Dispatchers.IO.dispatch(Dispatchers.IO) {
LocalGameDao.get(context).delete(state.data)
}
}
fun onUpdateGame(state: EditGameState, context: Context) {
state.show.value = false
Dispatchers.IO.dispatch(Dispatchers.IO) {
val data = state.data
data.name = state.name.value
LocalGameDao.get(context).update(data)
}
}
fun onEditGame(state: MutableState<EditGameState>, data: LocalGameEntity) {
state.value.data = data
state.value.name.value = data.name
state.value.show.value = true
}
fun onImportGame(state: MutableState<ImportGameState>, context: Context) {
state.value.show.value = false
Dispatchers.IO.dispatch(Dispatchers.IO) {
ZeroMQClient.bind(context) { client -> client.joinInvite(state.value.id.value) }
}
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun GameListPage(nav: NavHostController) {
val newGameState = remember { mutableStateOf(NewGameState()) }
val sheetState = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)
val scaffoldState = rememberScaffoldState()
val coroutineScope = rememberCoroutineScope()
val importState = remember { mutableStateOf(ImportGameState()) }
ModalBottomSheetLayout(
sheetElevation = 16.dp,
sheetShape = RoundedCornerShape(32.dp),
sheetState = sheetState,
sheetContent = { ListMenu(sheetState, importState) })
{
Scaffold(
scaffoldState = scaffoldState,
topBar = {
TopAppBar {
Image(
modifier = Modifier
.fillMaxWidth()
.height(26.dp),
painter = painterResource(R.drawable.genesischess),
contentDescription = "Genesis Chess"
)
}
},
bottomBar = {
TopAppBar {
Row(
modifier = Modifier.fillMaxWidth(1f),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
IconButton(onClick = { coroutineScope.launch { sheetState.show() } }) {
Icon(
Icons.Filled.Menu,
"menu",
Modifier.size(30.dp)
)
}
IconButton(onClick = {
newGameState.value.show.value = true
}) {
Icon(
Icons.Filled.Add,
"New Game",
Modifier.size(30.dp)
)
}
}
}
},
content = { LocalGameList(nav) },
)
}
showNewGameDialog(newGameState, nav)
showImportInviteDialog(importState)
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun ListMenu(sheetState: ModalBottomSheetState, importState: MutableState<ImportGameState>) {
val ctx = LocalContext.current
val scope = rememberCoroutineScope()
Column {
ListItem(
modifier = Modifier.clickable(onClick = {
scope.launch {
importState.value.show.value = true
sheetState.hide()
}
}),
icon = { Icon(Icons.Filled.Email, "Import Invite Game") },
text = { Text("Import Invite Game") }
)
ListItem(
modifier = Modifier.clickable(onClick = {
scope.launch {
ctx.startActivity(Intent(ctx, SettingsPage::class.java))
sheetState.hide()
}
}),
icon = { Icon(Icons.Filled.Settings, "Settings") },
text = { Text("Settings") }
)
}
}
@Composable
fun LocalGameList(nav: NavHostController) {
val context = LocalContext.current
val pager = remember { Pager(PagingConfig(10)) { LocalGameDao.get(context).allGames } }
val lazyItems = pager.flow.collectAsLazyPagingItems()
val editState = remember { mutableStateOf(EditGameState()) }
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(bottom = 8.dp)
) {
items(lazyItems) { gamedata ->
if (gamedata != null) {
LocalGameItem(gamedata, editState, nav)
}
}
}
showEditGameDialog(editState)
}
@Composable
fun showEditGameDialog(editState: MutableState<EditGameState>) {
if (!editState.value.show.value) {
return
}
val context = LocalContext.current
AlertDialog(onDismissRequest = { editState.value.show.value = false },
title = {
Text(text = "Edit", fontWeight = FontWeight.Bold, fontSize = 20.sp)
},
text = {
Column {
Text("Game Name:", modifier = Modifier.padding(bottom = 4.dp))
TextField(
value = editState.value.name.value,
onValueChange = { editState.value.name.value = it })
}
},
buttons = {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
Button(colors = ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.error),
onClick = { onDeleteGame(editState.value, context) }
) {
Text("Delete")
}
OutlinedButton(onClick = { editState.value.show.value = false }) {
Text("Cancel")
}
Button(colors = ButtonDefaults.buttonColors(),
onClick = { onUpdateGame(editState.value, context) }) {
Text("Rename")
}
}
}
)
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun LocalGameItem(
data: LocalGameEntity,
state: MutableState<EditGameState>,
nav: NavHostController
) {
val type = Enums.GameType(data.gametype)
val opponent = Enums.OpponentType(data.opponent)
val time = PrettyDate(data.stime).agoFormat()
val details = "type: $type opponent: $opponent"
val ctx = LocalContext.current
Card(
modifier = Modifier
.padding(16.dp, 16.dp, 16.dp, 0.dp)
.fillMaxWidth()
.combinedClickable(onClick = { onLoadGame(data, nav, ctx) },
onLongClick = { onEditGame(state, data) }),
elevation = 8.dp,
content = {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(end = 4.dp)
) {
Button(onClick = {}, modifier = Modifier.padding(start = 4.dp)) {
Text(data.lastMoveTo(), fontSize = 20.sp)
}
Column(modifier = Modifier.padding(start = 8.dp)) {
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = data.name,
fontWeight = FontWeight.Bold,
fontSize = 18.sp
)
Text(time, fontSize = 12.sp)
}
Text(
details,
fontSize = 14.sp,
fontStyle = FontStyle.Italic
)
}
}
}
)
}
@Composable
fun showNewGameDialog(data: MutableState<NewGameState>, nav: NavHostController) {
val state = data.value
if (!state.show.value) {
return
}
val ctx = LocalContext.current
AlertDialog(onDismissRequest = { state.show.value = false },
title = { Text(text = "New Game", fontWeight = FontWeight.Bold, fontSize = 20.sp) },
text = {
Column {
Text("Game Type:", fontWeight = FontWeight.Bold)
Row(verticalAlignment = Alignment.CenterVertically) {
RadioButton(
selected = state.type.value == Enums.GENESIS_CHESS,
onClick = {
state.type.value = Enums.GENESIS_CHESS
},
modifier = Modifier.size(36.dp)
)
Text("Genesis")
Spacer(modifier = Modifier.width(6.dp))
RadioButton(
selected = state.type.value == Enums.REGULAR_CHESS,
onClick = {
state.type.value = Enums.REGULAR_CHESS
},
modifier = Modifier.size(36.dp)
)
Text("Regular")
}
Text(
"Opponent Type:",
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(top = 8.dp)
)
Row(verticalAlignment = Alignment.CenterVertically) {
RadioButton(
selected = state.opp.value == Enums.INVITE_OPPONENT,
onClick = {
state.opp.value = Enums.INVITE_OPPONENT
},
modifier = Modifier.size(36.dp)
)
Text("Invite")
Spacer(modifier = Modifier.width(6.dp))
RadioButton(
selected = state.opp.value == Enums.HUMAN_OPPONENT,
onClick = {
state.opp.value = Enums.HUMAN_OPPONENT
},
modifier = Modifier.size(36.dp)
)
Text("Local")
Spacer(modifier = Modifier.width(6.dp))
RadioButton(
selected = state.opp.value == Enums.CPU_OPPONENT,
onClick = {
state.opp.value = Enums.CPU_OPPONENT
},
modifier = Modifier.size(36.dp)
)
Text("Computer")
}
Text(
"Play as Color:",
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(top = 8.dp)
)
Row(verticalAlignment = Alignment.CenterVertically) {
RadioButton(
enabled = state.opp.value != Enums.HUMAN_OPPONENT,
selected = state.color.value == Enums.RANDOM_OPP,
onClick = {
state.color.value = Enums.RANDOM_OPP
},
modifier = Modifier.size(36.dp)
)
Text("Random")
Spacer(modifier = Modifier.width(6.dp))
RadioButton(
enabled = state.opp.value != Enums.HUMAN_OPPONENT,
selected = state.color.value == Enums.BLACK_OPP,
onClick = {
state.color.value = Enums.BLACK_OPP
},
modifier = Modifier.size(36.dp)
)
Text("White")
Spacer(modifier = Modifier.width(6.dp))
RadioButton(
enabled = state.opp.value != Enums.HUMAN_OPPONENT,
selected = state.color.value == Enums.WHITE_OPP,
onClick = {
state.color.value = Enums.WHITE_OPP
},
modifier = Modifier.size(36.dp)
)
Text("Black")
}
Text(
"Name:",
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(top = 8.dp)
)
Spacer(modifier = Modifier.height(8.dp))
TextField(
value = state.name.value,
onValueChange = { state.name.value = it })
}
},
buttons = {
Row(
Modifier
.fillMaxWidth()
.padding(8.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
TextButton(onClick = { state.show.value = false }) {
Text("Cancel")
}
TextButton(onClick = { onNewGame(state, nav, ctx) }) {
Text("Create")
}
}
}
)
}
@Composable
fun showImportInviteDialog(state: MutableState<ImportGameState>) {
if (!state.value.show.value) {
return
}
val context = LocalContext.current
AlertDialog(onDismissRequest = { state.value.show.value = false },
title = {
Text(
text = "Import Invite Game",
fontWeight = FontWeight.Bold,
fontSize = 20.sp
)
},
text = {
Column {
Text("Enter Game ID:", fontWeight = FontWeight.Bold)
Spacer(modifier = Modifier.height(8.dp))
TextField(
value = state.value.id.value,
onValueChange = { state.value.id.value = it })
}
},
buttons = {
Row(
Modifier
.fillMaxWidth()
.padding(8.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
TextButton(onClick = { state.value.show.value = false }) {
Text("Cancel")
}
TextButton(onClick = { onImportGame(state, context) }) {
Text("Import")
}
}
}
)
}
| apache-2.0 | 48cb9ea6d9d69a953e80688c2781c233 | 25.561866 | 94 | 0.665598 | 3.434304 | false | false | false | false |
FredJul/TaskGame | TaskGame/src/main/java/net/fred/taskgame/utils/Constants.kt | 1 | 1363 | /*
* Copyright (c) 2012-2017 Frederic Julian
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package net.fred.taskgame.utils
interface Constants {
companion object {
val ACTION_GOOGLE_NOW = "com.google.android.gm.action.AUTO_SEND"
val EXTRA_TASK_ID = "task_id"
val EXTRA_TASK = "task"
val EXTRA_CATEGORY = "category"
val EXTRA_WIDGET_ID = "widget_id"
// Custom intent actions
val ACTION_DONE = "action_done"
val ACTION_SNOOZE = "action_snooze"
val ACTION_POSTPONE = "action_postpone"
val ACTION_WIDGET = "action_widget"
val ACTION_WIDGET_SHOW_LIST = "action_widget_show_list"
val ACTION_NOTIFICATION_CLICK = "action_notification_click"
}
}
| gpl-3.0 | b28a104ea99796204a50e6e708ff3ba5 | 35.837838 | 81 | 0.685987 | 3.962209 | false | false | false | false |
OurFriendIrony/MediaNotifier | app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/db/artist/ArtistDatabase.kt | 1 | 10597 | package uk.co.ourfriendirony.medianotifier.db.artist
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.util.Log
import uk.co.ourfriendirony.medianotifier.db.Database
import uk.co.ourfriendirony.medianotifier.db.PropertyHelper
import uk.co.ourfriendirony.medianotifier.general.Constants
import uk.co.ourfriendirony.medianotifier.general.Helper
import uk.co.ourfriendirony.medianotifier.mediaitem.MediaItem
import uk.co.ourfriendirony.medianotifier.mediaitem.artist.Artist
import uk.co.ourfriendirony.medianotifier.mediaitem.artist.Release
import java.util.*
class ArtistDatabase(context: Context) : Database {
private val context: Context
private val dbWritable: SQLiteDatabase
override fun add(item: MediaItem) {
for (release in item.children) {
insertRelease(release, true)
}
insert(item)
}
override fun update(item: MediaItem) {
for (release in item.children) {
insertRelease(release, false)
}
insert(item)
}
private fun insert(artist: MediaItem) {
val dbRow = ContentValues()
dbRow.put(ArtistDatabaseDefinition.ID, artist.id)
dbRow.put(ArtistDatabaseDefinition.SUBID, artist.subId)
dbRow.put(ArtistDatabaseDefinition.TITLE, Helper.cleanTitle(artist.title!!))
dbRow.put(ArtistDatabaseDefinition.SUBTITLE, artist.subtitle)
dbRow.put(ArtistDatabaseDefinition.EXTERNAL_URL, artist.externalLink)
dbRow.put(ArtistDatabaseDefinition.RELEASE_DATE, Helper.dateToString(artist.releaseDate))
dbRow.put(ArtistDatabaseDefinition.DESCRIPTION, artist.description)
Log.d("[DB INSERT]", "Artist: $dbRow")
dbWritable.replace(ArtistDatabaseDefinition.TABLE_ARTISTS, null, dbRow)
}
private fun insertRelease(release: MediaItem, isNew: Boolean) {
val currentWatchedStatus = getWatchedStatus(release)
val dbRow = ContentValues()
dbRow.put(ArtistDatabaseDefinition.ID, release.id)
dbRow.put(ArtistDatabaseDefinition.SUBID, release.subId)
dbRow.put(ArtistDatabaseDefinition.TITLE, Helper.cleanTitle(release.title!!))
dbRow.put(ArtistDatabaseDefinition.SUBTITLE, release.subtitle)
dbRow.put(ArtistDatabaseDefinition.RELEASE_DATE, Helper.dateToString(release.releaseDate))
dbRow.put(ArtistDatabaseDefinition.DESCRIPTION, release.description)
if (markPlayedIfReleased(isNew, release)) {
dbRow.put(ArtistDatabaseDefinition.PLAYED, Constants.DB_TRUE)
} else {
dbRow.put(ArtistDatabaseDefinition.PLAYED, currentWatchedStatus)
}
Log.d("[DB INSERT]", "Release: $dbRow")
dbWritable.replace(ArtistDatabaseDefinition.TABLE_RELEASES, null, dbRow)
}
override fun getWatchedStatus(mediaItem: MediaItem): String {
val args = arrayOf(mediaItem.id, mediaItem.subId)
val cursor = dbWritable.rawQuery(GET_RELEASE_WATCHED_STATUS, args)
var playedStatus = Constants.DB_FALSE
cursor.use { c ->
while (c.moveToNext()) {
playedStatus = getColumnValue(c, ArtistDatabaseDefinition.PLAYED)
}
}
return playedStatus
}
override fun getWatchedStatusAsBoolean(mediaItem: MediaItem): Boolean {
val args = arrayOf(mediaItem.id, mediaItem.subId)
val cursor = dbWritable.rawQuery(GET_RELEASE_WATCHED_STATUS, args)
var playedStatus = Constants.DB_FALSE
cursor.use { c ->
while (c.moveToNext()) {
playedStatus = getColumnValue(c, ArtistDatabaseDefinition.PLAYED)
}
}
return Constants.DB_TRUE == playedStatus
}
override fun deleteAll() {
dbWritable.execSQL("DELETE FROM " + ArtistDatabaseDefinition.TABLE_ARTISTS + ";")
dbWritable.execSQL("DELETE FROM " + ArtistDatabaseDefinition.TABLE_RELEASES + ";")
}
override fun delete(id: String) {
dbWritable.execSQL("DELETE FROM " + ArtistDatabaseDefinition.TABLE_ARTISTS + " WHERE " + ArtistDatabaseDefinition.ID + "=\"" + id + "\";")
dbWritable.execSQL("DELETE FROM " + ArtistDatabaseDefinition.TABLE_RELEASES + " WHERE " + ArtistDatabaseDefinition.ID + "=\"" + id + "\";")
}
private fun buildSubItemFromDB(cursor: Cursor): MediaItem {
return Release(cursor)
}
private fun buildItemFromDB(cursor: Cursor): MediaItem {
// TODO: When building an mediaItem, we're currently pulling all children back from the DB to display to the user.
// TODO: Sometimes we just want to display all the tvshows, and pulling all children for all shows is pretty excessive.
val id = getColumnValue(cursor, ArtistDatabaseDefinition.ID)
val releases: MutableList<MediaItem> = ArrayList()
dbWritable.rawQuery(SELECT_RELEASES_BY_ID, arrayOf(id)).use { subCursor ->
while (subCursor.moveToNext()) {
releases.add(buildSubItemFromDB(subCursor))
}
}
return Artist(cursor, releases)
}
override fun countUnplayedReleased(): Int {
return countUnplayed(COUNT_UNWATCHED_RELEASES_RELEASED)
}
private fun countUnplayed(countQuery: String): Int {
val offset =
"date('now','-" + PropertyHelper.getNotificationDayOffsetArtist(context) + " days')"
val query = Helper.replaceTokens(countQuery, "@OFFSET@", offset)
val cursor = dbWritable.rawQuery(query, null)
cursor.moveToFirst()
val count = cursor.getInt(0)
cursor.close()
return count
}
override val unplayedReleased: List<MediaItem>
get() = getUnplayed(GET_UNWATCHED_RELEASES_RELEASED, "UNWATCHED RELEASED")
override val unplayedTotal: List<MediaItem>
get() = getUnplayed(GET_UNWATCHED_RELEASES_TOTAL, "UNWATCHED TOTAL")
override fun getUnplayed(getQuery: String?, logTag: String?): List<MediaItem> {
val offset =
"date('now','-" + PropertyHelper.getNotificationDayOffsetArtist(context) + " days')"
val query = Helper.replaceTokens(getQuery!!, "@OFFSET@", offset)
val mediaItems: MutableList<MediaItem> = ArrayList()
dbWritable.rawQuery(query, null).use { cursor ->
while (cursor.moveToNext()) {
val mediaItem = buildSubItemFromDB(cursor)
mediaItems.add(mediaItem)
}
}
return mediaItems
}
override fun readAllItems(): List<MediaItem> {
val mediaItems: MutableList<MediaItem> = ArrayList()
dbWritable.rawQuery(SELECT_ARTISTS, null).use { cursor ->
while (cursor.moveToNext()) {
mediaItems.add(buildItemFromDB(cursor))
}
}
return mediaItems
}
override fun readAllParentItems(): List<MediaItem> {
val mediaItems: MutableList<MediaItem> = ArrayList()
dbWritable.rawQuery(SELECT_ARTISTS, null).use { cursor ->
while (cursor.moveToNext()) {
mediaItems.add(Artist(cursor))
}
}
return mediaItems
}
override fun readChildItems(id: String): List<MediaItem> {
val mediaItems: MutableList<MediaItem> = ArrayList()
val args = arrayOf(id)
dbWritable.rawQuery(SELECT_RELEASES_BY_ID, args).use { cursor ->
while (cursor.moveToNext()) {
mediaItems.add(buildSubItemFromDB(cursor))
}
}
return mediaItems
}
override fun updatePlayedStatus(mediaItem: MediaItem, playedStatus: String?) {
val values = ContentValues()
values.put(ArtistDatabaseDefinition.PLAYED, playedStatus)
val where: String =
ArtistDatabaseDefinition.ID + "=? and " + ArtistDatabaseDefinition.SUBID + "=?"
val whereArgs = arrayOf(mediaItem.id, mediaItem.subId)
dbWritable.update(ArtistDatabaseDefinition.TABLE_RELEASES, values, where, whereArgs)
}
override fun markPlayedIfReleased(isNew: Boolean, mediaItem: MediaItem): Boolean {
return isNew && alreadyReleased(mediaItem) && PropertyHelper.getMarkWatchedIfAlreadyReleased(
context
)
}
// TODO: This is a lazy and unneeded implementation. It should be removed
override val coreType: String
get() = "Artist"
private fun alreadyReleased(mediaItem: MediaItem): Boolean {
return if (mediaItem.releaseDate == null) {
true
} else mediaItem.releaseDate!! < Date()
}
private fun getColumnValue(cursor: Cursor, field: String): String {
val idx = cursor.getColumnIndex(field)
return cursor.getString(idx)
}
companion object {
private const val SELECT_ARTISTS =
"SELECT * FROM " + ArtistDatabaseDefinition.TABLE_ARTISTS + " ORDER BY " + ArtistDatabaseDefinition.TITLE + " ASC;"
private const val SELECT_RELEASES_BY_ID =
"SELECT * FROM " + ArtistDatabaseDefinition.TABLE_RELEASES + " WHERE " + ArtistDatabaseDefinition.ID + "=? ORDER BY " + ArtistDatabaseDefinition.RELEASE_DATE + " ASC;"
private const val GET_RELEASE_WATCHED_STATUS =
"SELECT " + ArtistDatabaseDefinition.PLAYED + " FROM " + ArtistDatabaseDefinition.TABLE_RELEASES + " WHERE " + ArtistDatabaseDefinition.ID + "=? AND " + ArtistDatabaseDefinition.SUBID + "=?;"
private const val COUNT_UNWATCHED_RELEASES_RELEASED =
"SELECT COUNT(*) FROM " + ArtistDatabaseDefinition.TABLE_RELEASES + " " +
"WHERE " + ArtistDatabaseDefinition.PLAYED + "=" + Constants.DB_FALSE + " AND " + ArtistDatabaseDefinition.RELEASE_DATE + " <= @OFFSET@;"
private const val GET_UNWATCHED_RELEASES_RELEASED = "SELECT * " +
"FROM " + ArtistDatabaseDefinition.TABLE_RELEASES + " " +
"WHERE " + ArtistDatabaseDefinition.PLAYED + "=" + Constants.DB_FALSE + " AND " + ArtistDatabaseDefinition.RELEASE_DATE + " <= @OFFSET@ ORDER BY " + ArtistDatabaseDefinition.RELEASE_DATE + " ASC;"
private const val GET_UNWATCHED_RELEASES_TOTAL = "SELECT * " +
"FROM " + ArtistDatabaseDefinition.TABLE_RELEASES + " " +
"WHERE " + ArtistDatabaseDefinition.PLAYED + "=" + Constants.DB_FALSE + " AND " + ArtistDatabaseDefinition.RELEASE_DATE + " != '' ORDER BY " + ArtistDatabaseDefinition.RELEASE_DATE + " ASC;"
}
init {
dbWritable = ArtistDatabaseDefinition(context).writableDatabase
this.context = context
}
} | apache-2.0 | e3ec1e40b119effc50225332da587618 | 44.290598 | 212 | 0.665566 | 4.520904 | false | false | false | false |
wuan/rest-demo-jersey-kotlin | src/test/java/com/tngtech/demo/weather/resources/RootResourceIntegrationTest.kt | 1 | 1814 | package com.tngtech.demo.weather.resources
import com.mercateo.common.rest.schemagen.types.ObjectWithSchema
import com.mercateo.common.rest.schemagen.types.WithId
import com.tngtech.demo.weather.domain.Station
import com.tngtech.demo.weather.repositories.StationRepository
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.annotation.DirtiesContext
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner
import org.assertj.core.api.Assertions.assertThat
@RunWith(SpringJUnit4ClassRunner::class)
@SpringBootTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class RootResourceIntegrationTest {
@Autowired
private lateinit var stationRepository: StationRepository
@Autowired
private lateinit var rootResource: RootResource
@Before
@Throws(Exception::class)
fun setUp() {
stationRepository.addStation(WithId.create(Station(name = "ABC", latitude = 49.0, longitude = 11.0)))
stationRepository.addStation(WithId.create(Station(name = "DEF", latitude = 49.0, longitude = 11.0)))
stationRepository.addStation(WithId.create(Station(name = "GHI", latitude = 49.0, longitude = 11.0)))
stationRepository.addStation(WithId.create(Station(name = "JKL", latitude = 55.0, longitude = 11.0)))
}
@Test
fun callingRootResourceShouldReturnAvailableLinks() {
val root = rootResource.root
assertThat(root.schema.getByRel(WeatherRel.STATIONS)).isPresent()
assertThat(root.schema.getByRel(WeatherRel.QUERY)).isPresent()
assertThat(root.schema.getByRel(WeatherRel.STATISTICS)).isPresent()
}
} | apache-2.0 | 1babc409e1902a2caf32cebb79664f22 | 38.456522 | 109 | 0.77398 | 3.986813 | false | true | false | false |
adelnizamutdinov/headphone-reminder | app/src/main/kotlin/common/lifecycle/lifecycle.kt | 1 | 2274 | package common.lifecycle
import android.app.Activity
import android.app.Application
import android.os.Bundle
import common.rx.emit
import common.rx.finally
import common.rx.last
import rx.Observable
import rx.Subscriber
import java.util.*
interface Lifecycle
data class Create(val savedInstanceState: Bundle?) : Lifecycle
object Start : Lifecycle
object Resume : Lifecycle
object Pause : Lifecycle
object Stop : Lifecycle
data class SaveInstanceState(val outState: Bundle) : Lifecycle
data class Destroy(val isFinishing: Boolean) : Lifecycle
val lifecycleCache: HashMap<Activity, Observable<Lifecycle>> = hashMapOf()
fun lifecycleImpl(a: Activity): Observable<Lifecycle> =
lifecycleCache[a] ?: Observable.create(onSubscribe(a)).share().apply {
lifecycleCache.put(a, this)
}
fun onSubscribe(a: Activity): (Subscriber<in Lifecycle>) -> Unit =
{ sub ->
val alc = object : Application.ActivityLifecycleCallbacks {
fun Activity.emit(l: Lifecycle): Unit =
when (a) {
this -> sub.emit(l)
else -> Unit
}
fun Activity.last(l: Lifecycle): Unit =
when (a) {
this -> sub.last(l)
else -> Unit
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?): Unit =
activity.emit(Create(savedInstanceState))
override fun onActivityStarted(activity: Activity): Unit =
activity.emit(Start)
override fun onActivityResumed(activity: Activity): Unit =
activity.emit(Resume)
override fun onActivityPaused(activity: Activity): Unit =
activity.emit(Pause)
override fun onActivityStopped(activity: Activity): Unit =
activity.emit(Stop)
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle): Unit =
activity.emit(SaveInstanceState(outState))
override fun onActivityDestroyed(activity: Activity): Unit =
activity.last(Destroy(activity.isFinishing))
}
val app = a.application
sub.finally {
app.unregisterActivityLifecycleCallbacks(alc)
lifecycleCache -= a
}
app.registerActivityLifecycleCallbacks(alc)
} | mit | 322488d85ce9363b05a3575c5a412386 | 28.166667 | 95 | 0.670185 | 4.807611 | false | false | false | false |
Balthair94/PokedexMVP | app/src/main/java/baltamon/mx/pokedexmvp/pokemones/RVAdapterPokemones.kt | 1 | 1340 | package baltamon.mx.pokedexmvp.pokemones
import android.content.Context
import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import baltamon.mx.pokedexmvp.R
import baltamon.mx.pokedexmvp.extensions.inflate
import baltamon.mx.pokedexmvp.extensions.showToast
import baltamon.mx.pokedexmvp.models.NamedAPIResource
import baltamon.mx.pokedexmvp.pokemon_detail.PokemonDetailActivity
import baltamon.mx.pokedexmvp.viewholders.CVViewHolder
/**
* Created by Baltazar Rodriguez on 02/07/2017.
*/
private const val INTENT_POKEMON_NAME = "pokemon_name"
class RVAdapterPokemones(val pokemones: ArrayList<NamedAPIResource>,
val context: Context): RecyclerView.Adapter<CVViewHolder>() {
override fun onBindViewHolder(holder: CVViewHolder, position: Int) {
holder.textView.text = pokemones[position].name
holder.cv.setOnClickListener {
val intent = Intent(context, PokemonDetailActivity::class.java)
intent.putExtra(INTENT_POKEMON_NAME, pokemones[position].name)
context.startActivity(intent)
}
}
override fun getItemCount(): Int = pokemones.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CVViewHolder =
CVViewHolder(parent.inflate(R.layout.item_title))
} | mit | d69a5a2347edab15216fd3a42d71c5fc | 36.25 | 86 | 0.755224 | 4.294872 | false | false | false | false |
SecUSo/privacy-friendly-app-example | app/src/main/java/org/secuso/privacyfriendlyexample/ui/HelpActivity.kt | 1 | 2563 | /*
This file is part of Privacy Friendly App Example.
Privacy Friendly App Example 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 any later version.
Privacy Friendly App Example 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 Privacy Friendly App Example. If not, see <http://www.gnu.org/licenses/>.
*/
package org.secuso.privacyfriendlyexample.ui
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_help.*
import org.secuso.privacyfriendlyexample.R
import org.secuso.privacyfriendlyexample.ui.adapter.ExpandableListAdapter
import java.util.*
import kotlin.collections.LinkedHashMap
/**
* Class structure taken from tutorial at http://www.journaldev.com/9942/android-expandablelistview-example-tutorial
* last access 27th October 2016
* @author Christopher Beckmann (Kamuno), Karola Marky (yonjuni)
*/
class HelpActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_help)
val expandableListDetail = buildData()
val expandableListTitleGeneral = expandableListDetail.keys.toList()
generalExpandableListView.setAdapter(ExpandableListAdapter(this, expandableListTitleGeneral, expandableListDetail))
overridePendingTransition(0, 0)
}
/**
* ID of the menu item it belongs to
*/
override val navigationDrawerID: Int = R.id.nav_help
private fun buildData(): LinkedHashMap<String, List<String>> {
val expandableListDetail = LinkedHashMap<String, List<String>>()
expandableListDetail[getString(R.string.help_whatis)] = Collections.singletonList(getString(R.string.help_whatis_answer))
expandableListDetail[getString(R.string.help_feature_one)] = Collections.singletonList(getString(R.string.help_feature_one_answer))
expandableListDetail[getString(R.string.help_privacy)] = Collections.singletonList(getString(R.string.help_privacy_answer))
expandableListDetail[getString(R.string.help_permission)] = Collections.singletonList(getString(R.string.help_permission_answer))
return expandableListDetail
}
}
| gpl-3.0 | 2ca5bff1f7ad8830fe003f14fa7753d4 | 39.68254 | 139 | 0.76824 | 4.480769 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/formatter/RsFormattingModelBuilder.kt | 4 | 2027 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.formatter
import com.intellij.formatting.*
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.codeStyle.CodeStyleSettings
import org.rust.ide.formatter.blocks.RsFmtBlock
import org.rust.ide.formatter.blocks.RsMacroArgFmtBlock
import org.rust.ide.formatter.blocks.RsMultilineStringLiteralBlock
import org.rust.lang.core.psi.RS_RAW_LITERALS
import org.rust.lang.core.psi.RS_STRING_LITERALS
import org.rust.lang.core.psi.RsElementTypes.*
class RsFormattingModelBuilder : FormattingModelBuilder {
override fun getRangeAffectingIndent(file: PsiFile?, offset: Int, elementAtOffset: ASTNode?): TextRange? = null
override fun createModel(element: PsiElement, settings: CodeStyleSettings): FormattingModel {
val ctx = RsFmtContext.create(settings)
val block = createBlock(element.node, null, Indent.getNoneIndent(), null, ctx)
/** / com.intellij.formatting.FormattingModelDumper.dumpFormattingModel(block, 2, System.err) // */
return FormattingModelProvider.createFormattingModelForPsiFile(element.containingFile, block, settings)
}
companion object {
fun createBlock(
node: ASTNode,
alignment: Alignment?,
indent: Indent?,
wrap: Wrap?,
ctx: RsFmtContext
): ASTBlock {
val type = node.elementType
if (type == MACRO_DEFINITION_BODY || type == MACRO_ARGUMENT) {
return RsMacroArgFmtBlock(node, alignment, indent, wrap, ctx)
}
if ((type in RS_STRING_LITERALS || type in RS_RAW_LITERALS) && node.textContains('\n')) {
return RsMultilineStringLiteralBlock(node, alignment, indent, wrap)
}
return RsFmtBlock(node, alignment, indent, wrap, ctx)
}
}
}
| mit | 1890f8b2664a1dd78b407b0264dcce23 | 37.980769 | 115 | 0.698569 | 4.35914 | false | false | false | false |
drimachine/grakmat | src/main/kotlin/org/drimachine/grakmat/ast/DSL.kt | 1 | 1533 | /*
* Copyright (c) 2016 Drimachine.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drimachine.grakmat.ast
import java.util.*
fun astNode(name: String): Node = Node(name, "", arrayListOf<Node>())
fun astNode(name: String, value: String): Node = Node(name, value, arrayListOf<Node>())
fun astNode(name: String, children: ChildrenDSL.() -> Unit): Node {
val childrenDSL = ChildrenDSL()
childrenDSL.children()
return Node(name, "", childrenDSL.list)
}
fun astNode(name: String, value: String, children: ChildrenDSL.() -> Unit): Node {
val childrenDSL = ChildrenDSL()
childrenDSL.children()
return Node(name, value, childrenDSL.list)
}
fun astNode(name: String, children: List<Node>): Node = Node(name, "", children)
fun astNode(name: String, value: String, children: List<Node>): Node = Node(name, value, children)
class ChildrenDSL {
val list: ArrayList<Node> = arrayListOf()
fun add(node: Node) { list += node }
operator fun Node.unaryPlus() { list += this }
}
| apache-2.0 | 294936f9918c046ada3f06482826d3dd | 31.617021 | 98 | 0.705806 | 3.80397 | false | false | false | false |
http4k/http4k | http4k-template/core/src/main/kotlin/org/http4k/template/Templates.kt | 1 | 1722 | package org.http4k.template
import org.http4k.core.ContentType
import org.http4k.core.ContentType.Companion.TEXT_HTML
import org.http4k.core.Response
import org.http4k.core.Status
import org.http4k.core.Status.Companion.OK
import org.http4k.core.with
import org.http4k.lens.Header.CONTENT_TYPE
typealias TemplateRenderer = (ViewModel) -> String
/**
* Supported template implementations for templating engine implementations
*/
interface Templates {
/**
* Loads and caches templates from the compiled classpath
*
* @param baseClasspathPackage the root package to load from (defaults to root)
*/
fun CachingClasspath(baseClasspathPackage: String = ""): TemplateRenderer
/**
* Load and caches templates from a file path
*
* @param baseTemplateDir the root path to load templates from
*/
fun Caching(baseTemplateDir: String = "./"): TemplateRenderer
/**
* Hot-reloads (no-caching) templates from a file path
*
* @param baseTemplateDir the root path to load templates from
*/
fun HotReload(baseTemplateDir: String = "./"): TemplateRenderer
}
/**
* Compose a TemplateRenderer with another, so you can fall back.
*/
fun TemplateRenderer.then(that: TemplateRenderer): TemplateRenderer = {
try {
this(it)
} catch (e: ViewNotFound) {
that(it)
}
}
/**
* Convenience method for generating a Response from a view model.
*/
fun TemplateRenderer.renderToResponse(viewModel: ViewModel,
status: Status = OK,
contentType: ContentType = TEXT_HTML): Response =
Response(status).with(CONTENT_TYPE of contentType).body(invoke(viewModel))
| apache-2.0 | c83085d18e0027ee488ea2eb65dc4442 | 29.210526 | 87 | 0.683508 | 4.315789 | false | false | false | false |
vitoling/HiWeather | src/main/kotlin/com/vito/work/weather/domain/beans/api/LocationData.kt | 1 | 1905 | package com.vito.work.weather.domain.beans.api
import com.fasterxml.jackson.databind.ObjectMapper
import java.io.StringWriter
import java.util.*
/**
* Created by lingzhiyuan.
* Date : 16/4/1.
* Time : 下午6:39.
* Description:
*
*/
class LocationData {
companion object {
// 省份
val LOCATION_INFO_TYPE_ZERO: Int = 0
// 城市
val LOCATION_INFO_TYPE_ONE: Int = 1
// 区县
val LOCATION_INFO_TYPE_TWO: Int = 2
}
}
data class LocationInfo(
var id: String = "",
var value: HashMap<Long, String> = HashMap(),
var py: HashMap<Long, String> = HashMap(),
var defval: Long = 0L,
var ishot: HashMap<Long, Int> = HashMap()
)
/**
* 对于 LOCATION_INFO 的区域信息转换器
* 将获取到的区域信息 JSON 数据通过 OBJECT MAPPER 转换成对应的对象
* 由于 data 的结构为 List , 且获取的 JSON 信息中只有一个对象有效, 因此只对其中一个元素进行转换
* */
fun locationInfoParser(type: Int, data: String): LocationInfo? {
// 有效信息的位置
var infoIndex: Int = 1
// 根据数据接口不同判断有效信息所在的元素
when (type) {
LocationData.LOCATION_INFO_TYPE_ZERO -> infoIndex = 1
LocationData.LOCATION_INFO_TYPE_ONE, LocationData.LOCATION_INFO_TYPE_TWO -> infoIndex = 0
}
val mapper = ObjectMapper()
val list = mapper.readValue(data, Array<Any>::class.java)
var locationInfo: LocationInfo?
val writer = StringWriter()
mapper.writeValue(writer, list[infoIndex])
val tempData: String = writer.toString()
try {
locationInfo = mapper.readValue(tempData, LocationInfo::class.java)
} catch (ex: Exception) {
// 转换失败则跳过
locationInfo = null
}
return locationInfo
}
| gpl-3.0 | 1902e742c278da05343268c2d2e6638a | 24.238806 | 97 | 0.613838 | 3.472279 | false | false | false | false |
hschroedl/FluentAST | core/src/main/kotlin/at.hschroedl.fluentast/ast/expression/ArrayAccess.kt | 1 | 895 | package at.hschroedl.fluentast.ast.expression
import org.eclipse.jdt.core.dom.AST
import org.eclipse.jdt.core.dom.ArrayAccess
/**
* A wrapper class for [ArrayAccess]. Subclass of [FluentExpression]
*
*
* Using JDT:
* ~~~ java
* val exp = ast.newArrayAccess()
* exp.array = array.build(ast)
* exp.index = index.build(ast)
* ~~~
*
* Using Fluentast:
* ~~~ java
* exp().build(ast);
* ~~~
*
* @constructor takes a [FluentExpression] as array and a [FluentExpression] as index
*
* @see ArrayAccess
*/
class FluentArrayAccess internal constructor(private val array: FluentExpression,
private val index: FluentExpression) : FluentExpression() {
override fun build(ast: AST): ArrayAccess {
val exp = ast.newArrayAccess()
exp.array = array.build(ast)
exp.index = index.build(ast)
return exp
}
}
| apache-2.0 | 5dbec5cc50911b77075b959c0c82ebd9 | 23.189189 | 104 | 0.639106 | 3.74477 | false | false | false | false |
cemrich/zapp | app/src/main/java/de/christinecoenen/code/zapp/app/livestream/repository/ProgramInfoCache.kt | 1 | 1059 | package de.christinecoenen.code.zapp.app.livestream.repository
import de.christinecoenen.code.zapp.app.livestream.api.model.Channel
import de.christinecoenen.code.zapp.app.livestream.model.LiveShow
import timber.log.Timber
import java.util.*
/**
* Cache for currently running show on any channel.
*/
internal class ProgramInfoCache {
private val shows: MutableMap<Channel, LiveShow> = EnumMap(Channel::class.java)
fun save(channel: Channel, show: LiveShow) {
shows[channel] = show
}
/**
* @return currently running show or null in case of cache miss
*/
fun getShow(channel: Channel): LiveShow? {
val show = shows[channel]
return when {
show == null -> {
Timber.d("cache miss: %s", channel)
null
}
show.endTime == null -> {
Timber.d("cache miss: %s, no show end time", channel)
null
}
show.endTime!!.isBeforeNow -> {
Timber.d("cache miss: %s, show too old", channel)
shows.remove(channel)
null
}
else -> {
Timber.d("cache hit: %s - %s", channel, show.title)
show
}
}
}
}
| mit | 29bd307299d12bfb0f26388377fb9974 | 21.0625 | 80 | 0.668555 | 3.228659 | false | false | false | false |
rock3r/detekt | detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/internal/ValidatableConfiguration.kt | 1 | 4247 | package io.gitlab.arturbosch.detekt.api.internal
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Notification
interface ValidatableConfiguration {
fun validate(baseline: Config, excludePatterns: Set<Regex>): List<Notification>
}
/**
* Known existing properties on rule's which my be absent in the default-detekt-config.yml.
*
* We need to predefine them as the user may not have already declared an 'config'-block
* in the configuration and we want to validate the config by default.
*/
val DEFAULT_PROPERTY_EXCLUDES = setOf(
".*>.*>excludes",
".*>.*>includes",
".*>.*>active",
".*>.*>autoCorrect",
"build>weights.*"
).joinToString(",")
private val DEPRECATED_PROPERTIES = setOf(
"complexity>LongParameterList>threshold" to "Use 'functionThreshold' and 'constructorThreshold' instead",
"empty-blocks>EmptyFunctionBlock>ignoreOverriddenFunctions" to "Use 'ignoreOverridden' instead",
"naming>FunctionParameterNaming>ignoreOverriddenFunctions" to "Use 'ignoreOverridden' instead",
"naming>MemberNameEqualsClassName>ignoreOverriddenFunction" to "Use 'ignoreOverridden' instead"
).map { (first, second) -> first.toRegex() to second }
@Suppress("UNCHECKED_CAST", "ComplexMethod")
fun validateConfig(
config: Config,
baseline: Config,
excludePatterns: Set<Regex> = CommaSeparatedPattern(DEFAULT_PROPERTY_EXCLUDES).mapToRegex()
): List<Notification> {
require(baseline != Config.empty) { "Cannot validate configuration based on an empty baseline config." }
require(baseline is YamlConfig) {
val yamlConfigClass = YamlConfig::class.simpleName
val actualClass = baseline.javaClass.simpleName
"Only supported baseline config is the $yamlConfigClass. Actual type is $actualClass"
}
if (config == Config.empty) {
return emptyList()
}
val notifications = mutableListOf<Notification>()
fun testKeys(current: Map<String, Any>, base: Map<String, Any>, parentPath: String?) {
for (prop in current.keys) {
val propertyPath = "${if (parentPath == null) "" else "$parentPath>"}$prop"
val matchedDeprecation = DEPRECATED_PROPERTIES
.find { (regex, _) -> regex.matches(propertyPath) }
val isDeprecated = matchedDeprecation != null
val isExcluded = excludePatterns.any { it.matches(propertyPath) }
if (isDeprecated) {
notifications.add(propertyIsDeprecated(propertyPath, matchedDeprecation!!.second))
}
if (isDeprecated || isExcluded) {
continue
}
if (!base.contains(prop)) {
notifications.add(propertyDoesNotExists(propertyPath))
}
val next = current[prop] as? Map<String, Any>
val nextBase = base[prop] as? Map<String, Any>
when {
next == null && nextBase != null -> notifications.add(nestedConfigurationExpected(propertyPath))
base.contains(prop) && next != null && nextBase == null ->
notifications.add(unexpectedNestedConfiguration(propertyPath))
next != null && nextBase != null -> testKeys(next, nextBase, propertyPath)
}
}
}
when (config) {
is YamlConfig -> testKeys(config.properties, baseline.properties, null)
is ValidatableConfiguration -> notifications.addAll(config.validate(baseline, excludePatterns))
else -> error("Unsupported config type for validation: '${config::class}'.")
}
return notifications
}
internal fun propertyDoesNotExists(prop: String): Notification =
SimpleNotification("Property '$prop' is misspelled or does not exist.")
internal fun nestedConfigurationExpected(prop: String): Notification =
SimpleNotification("Nested config expected for '$prop'.")
internal fun unexpectedNestedConfiguration(prop: String): Notification =
SimpleNotification("Unexpected nested config for '$prop'.")
internal fun propertyIsDeprecated(prop: String, deprecationDescription: String): Notification =
SimpleNotification("Property '$prop' is deprecated. $deprecationDescription.", Notification.Level.Warning)
| apache-2.0 | f3b6e9b0304a3a74577dc15b08cf8fdc | 39.447619 | 112 | 0.68307 | 4.687638 | false | true | false | false |
BrianLusina/MovieReel | app/src/main/kotlin/com/moviereel/utils/listeners/EndlessRecyclerViewScrollListener.kt | 1 | 4806 | package com.moviereel.utils.listeners
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.StaggeredGridLayoutManager
/**
* @author lusinabrian on 21/07/17.
* @Notes Endless RecyclerViewScrollListener class. Will be used to implement lazy loading of
* views
* Ref :https://guides.codepath.com/android/Endless-Scrolling-with-AdapterViews-and-RecyclerView
*/
abstract class EndlessRecyclerViewScrollListener : RecyclerView.OnScrollListener {
// The minimum amount of items to have below your current scroll position
// before loading more.
private var visibleThreshold = 5
// The current offset index of data you have loaded
private var currentPage = 0
// The total number of items in the dataset after the last load
private var previousTotalItemCount = 0
// True if we are still waiting for the last set of data to load.
private var loading = true
// Sets the starting page index
private val startingPageIndex = 0
lateinit var mLayoutManager: RecyclerView.LayoutManager
constructor(layoutManager: LinearLayoutManager) {
this.mLayoutManager = layoutManager
}
constructor(layoutManager: GridLayoutManager) {
this.mLayoutManager = layoutManager
visibleThreshold *= layoutManager.spanCount
}
constructor(layoutManager: StaggeredGridLayoutManager) {
this.mLayoutManager = layoutManager
visibleThreshold *= layoutManager.spanCount
}
fun getLastVisibleItem(lastVisibleItemPositions: IntArray): Int {
var maxSize = 0
for (i in lastVisibleItemPositions.indices) {
if (i == 0) {
maxSize = lastVisibleItemPositions[i]
} else if (lastVisibleItemPositions[i] > maxSize) {
maxSize = lastVisibleItemPositions[i]
}
}
return maxSize
}
// This happens many times a second during a scroll, so be wary of the code you place here.
// We are given a few useful parameters to help us work out if we need to load some more data,
// but first we check if we are waiting for the previous load to finish.
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
var lastVisibleItemPosition = 0
var totalItemCount = mLayoutManager.itemCount
when (mLayoutManager) {
is StaggeredGridLayoutManager -> {
val lastVisibleItemPositions = (mLayoutManager as StaggeredGridLayoutManager).findLastVisibleItemPositions(null)
// get maximum element within the list
lastVisibleItemPosition = getLastVisibleItem(lastVisibleItemPositions)
}
is GridLayoutManager -> {
lastVisibleItemPosition = (mLayoutManager as GridLayoutManager).findLastVisibleItemPosition()
}
is LinearLayoutManager -> {
lastVisibleItemPosition = (mLayoutManager as LinearLayoutManager).findLastVisibleItemPosition()
}
}
// If the total item count is zero and the previous isn't, assume the
// list is invalidated and should be reset back to initial state
if (totalItemCount < previousTotalItemCount) {
this.currentPage = this.startingPageIndex
this.previousTotalItemCount = totalItemCount
if (totalItemCount == 0) {
this.loading = true
}
}
// If it’s still loading, we check to see if the dataset count has
// changed, if so we conclude it has finished loading and update the current page
// number and total item count.
if (loading && totalItemCount > previousTotalItemCount) {
loading = false
previousTotalItemCount = totalItemCount
}
// If it isn’t currently loading, we check to see if we have breached
// the visibleThreshold and need to reload more data.
// If we do need to reload some more data, we execute onLoadMore to fetch the data.
// threshold should reflect how many total columns there are too
if (!loading && lastVisibleItemPosition + visibleThreshold > totalItemCount) {
currentPage++
onLoadMore(currentPage, totalItemCount, recyclerView)
loading = true
}
}
// Call this method whenever performing new searches
fun resetState() {
this.currentPage = this.startingPageIndex
this.previousTotalItemCount = 0
this.loading = true
}
// Defines the process for actually loading more data based on page
abstract fun onLoadMore(page: Int, totalItemsCount: Int, recyclerView: RecyclerView)
} | mit | f08610ebc711b46fb912ef467aa8e447 | 40.405172 | 128 | 0.680133 | 5.583721 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/widget/StatBar.kt | 1 | 1756 | package com.boardgamegeek.ui.widget
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.core.view.updateLayoutParams
import com.boardgamegeek.R
import java.text.NumberFormat
class StatBar @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : FrameLayout(context, attrs, defStyle) {
init {
LayoutInflater.from(context).inflate(R.layout.widget_stat_bar, this)
layoutParams = LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
minimumHeight = resources.getDimensionPixelSize(R.dimen.stat_bar_height)
}
fun setBar(id: Int, progress: Double, max: Double) {
findViewById<TextView>(R.id.textView).text = String.format(context.resources.getString(id), FORMAT.format(progress))
findViewById<TextView>(R.id.valueView).updateLayoutParams<LinearLayout.LayoutParams> {
width = 0
height = ViewGroup.LayoutParams.MATCH_PARENT
weight = (progress * 1000).toInt().toFloat()
}
findViewById<TextView>(R.id.noValueView).updateLayoutParams<LinearLayout.LayoutParams> {
width = 0
height = ViewGroup.LayoutParams.MATCH_PARENT
weight = ((max - progress) * 1000).toInt().toFloat()
}
}
fun colorize(@ColorInt color: Int) {
findViewById<View>(R.id.valueView).setBackgroundColor(color)
}
companion object {
private val FORMAT = NumberFormat.getInstance()
}
}
| gpl-3.0 | 7a55ec4363c44515b404b76c38debb13 | 35.583333 | 124 | 0.714692 | 4.479592 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/data/GlobalKeyRegistry.kt | 1 | 3125 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.data
import org.spongepowered.api.data.Key
import org.spongepowered.api.data.value.Value
import java.util.function.Supplier
/**
* Represents the global registry of [Key]s.
*/
interface GlobalKeyRegistry : KeyRegistry<GlobalKeyRegistration<*,*>> {
/**
* Gets the [GlobalKeyRegistration] for the given [Key], if present.
*
* @param key The key to get the registration for
* @return The global key registration, if present
*/
override operator fun <V : Value<E>, E : Any> get(key: Key<V>): GlobalKeyRegistration<V, E>?
/**
* Gets the [GlobalKeyRegistration] for the given [Key], if present.
*
* @param key The key to get the registration for
* @return The global key registration, if present
*/
override operator fun <V : Value<E>, E : Any> get(key: Supplier<out Key<V>>): GlobalKeyRegistration<V, E>? = get(key.get())
/**
* Gets the registration or registers the given [Key].
*
* @param key The key to register
* @return The global key registration
*/
fun <V : Value<E>, E : Any> getOrRegister(key: Key<V>): GlobalKeyRegistration<V, E>
/**
* Gets the registration or registers the given [Key].
*
* @param key The key to register
* @return The global key registration
*/
fun <V : Value<E>, E : Any> getOrRegister(key: Supplier<out Key<V>>): GlobalKeyRegistration<V, E> = getOrRegister(key.get())
/**
* Registers the given [Key].
*
* @param key The key to register
* @return The global key registration
*/
fun <V : Value<E>, E : Any> register(key: Key<V>): GlobalKeyRegistration<V, E>
/**
* Registers a provider for the given [Key].
*
* @param key The key to register
* @return The global key registration
*/
fun <V : Value<E>, E : Any> registerProvider(
key: Key<V>, fn: DataProviderBuilder<V, E>.(key: Key<V>) -> Unit
): GlobalKeyRegistration<V, E> = this.register(key).addProvider(fn)
/**
* Registers a provider for the given [Key].
*
* @param key The key to register
* @return The global key registration
*/
fun <V : Value<E>, E : Any> registerProvider(
key: Supplier<out Key<V>>, fn: DataProviderBuilder<V, E>.(key: Key<V>) -> Unit
): GlobalKeyRegistration<V, E> = this.register(key).addProvider(fn)
/**
* Registers the given [Key].
*
* @param key The key to register
* @return The global key registration
*/
fun <V : Value<E>, E : Any> register(key: Supplier<out Key<V>>): GlobalKeyRegistration<V, E> = register(key.get())
/**
* The implementation of this registry.
*/
companion object : GlobalKeyRegistry by LanternGlobalKeyRegistry()
}
| mit | 56685fd7c91f89568527027aa2ce97d8 | 32.244681 | 128 | 0.63328 | 3.801703 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/integration/common/reporting/InProcessReportingServer.kt | 1 | 7280 | // Copyright 2022 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.integration.common.reporting
import io.grpc.Channel
import java.io.File
import java.security.SecureRandom
import java.util.logging.Logger
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
import org.wfanet.measurement.api.v2alpha.CertificatesGrpcKt.CertificatesCoroutineStub as PublicKingdomCertificatesCoroutineStub
import org.wfanet.measurement.api.v2alpha.DataProvidersGrpcKt.DataProvidersCoroutineStub as PublicKingdomDataProvidersCoroutineStub
import org.wfanet.measurement.api.v2alpha.EventGroupMetadataDescriptorsGrpcKt.EventGroupMetadataDescriptorsCoroutineStub as PublicKingdomEventGroupMetadataDescriptorsCoroutineStub
import org.wfanet.measurement.api.v2alpha.EventGroupsGrpcKt.EventGroupsCoroutineStub as PublicKingdomEventGroupsCoroutineStub
import org.wfanet.measurement.api.v2alpha.MeasurementConsumersGrpcKt.MeasurementConsumersCoroutineStub as PublicKingdomMeasurementConsumersCoroutineStub
import org.wfanet.measurement.api.v2alpha.MeasurementsGrpcKt.MeasurementsCoroutineStub as PublicKingdomMeasurementsCoroutineStub
import org.wfanet.measurement.common.crypto.tink.loadPrivateKey
import org.wfanet.measurement.common.grpc.testing.GrpcTestServerRule
import org.wfanet.measurement.common.grpc.withVerboseLogging
import org.wfanet.measurement.common.readByteString
import org.wfanet.measurement.common.testing.chainRulesSequentially
import org.wfanet.measurement.config.reporting.EncryptionKeyPairConfig
import org.wfanet.measurement.config.reporting.MeasurementConsumerConfig
import org.wfanet.measurement.integration.common.reporting.identity.withMetadataPrincipalIdentities
import org.wfanet.measurement.internal.reporting.MeasurementsGrpcKt.MeasurementsCoroutineStub as InternalMeasurementsCoroutineStub
import org.wfanet.measurement.internal.reporting.ReportingSetsGrpcKt.ReportingSetsCoroutineStub as InternalReportingSetsCoroutineStub
import org.wfanet.measurement.internal.reporting.ReportsGrpcKt.ReportsCoroutineStub as InternalReportsCoroutineStub
import org.wfanet.measurement.reporting.deploy.common.server.ReportingDataServer
import org.wfanet.measurement.reporting.deploy.common.server.ReportingDataServer.Companion.toList
import org.wfanet.measurement.reporting.service.api.v1alpha.EventGroupsService
import org.wfanet.measurement.reporting.service.api.v1alpha.InMemoryEncryptionKeyPairStore
import org.wfanet.measurement.reporting.service.api.v1alpha.ReportingSetsService
import org.wfanet.measurement.reporting.service.api.v1alpha.ReportsService
/** TestRule that starts and stops all Reporting Server gRPC services. */
class InProcessReportingServer(
private val reportingServerDataServices: ReportingDataServer.Services,
private val publicKingdomChannel: Channel,
private val encryptionKeyPairConfig: EncryptionKeyPairConfig,
private val signingPrivateKeyDir: File,
private val measurementConsumerConfig: MeasurementConsumerConfig,
private val verboseGrpcLogging: Boolean = true,
) : TestRule {
private val publicKingdomMeasurementConsumersClient by lazy {
PublicKingdomMeasurementConsumersCoroutineStub(publicKingdomChannel)
}
private val publicKingdomMeasurementsClient by lazy {
PublicKingdomMeasurementsCoroutineStub(publicKingdomChannel)
}
private val publicKingdomCertificatesClient by lazy {
PublicKingdomCertificatesCoroutineStub(publicKingdomChannel)
}
private val publicKingdomDataProvidersClient by lazy {
PublicKingdomDataProvidersCoroutineStub(publicKingdomChannel)
}
private val publicKingdomEventGroupsClient by lazy {
PublicKingdomEventGroupsCoroutineStub(publicKingdomChannel)
}
private val publicKingdomEventGroupMetadataDescriptorsClient by lazy {
PublicKingdomEventGroupMetadataDescriptorsCoroutineStub(publicKingdomChannel)
}
private val internalApiChannel by lazy { internalDataServer.channel }
private val internalMeasurementsClient by lazy {
InternalMeasurementsCoroutineStub(internalApiChannel)
}
private val internalReportingSetsClient by lazy {
InternalReportingSetsCoroutineStub(internalApiChannel)
}
private val internalReportsClient by lazy { InternalReportsCoroutineStub(internalApiChannel) }
private val internalDataServer =
GrpcTestServerRule(logAllRequests = verboseGrpcLogging) {
logger.info("Building Reporting Server's internal Data services")
reportingServerDataServices.toList().forEach {
addService(it.withVerboseLogging(verboseGrpcLogging))
}
}
private val publicApiServer =
GrpcTestServerRule(logAllRequests = verboseGrpcLogging) {
logger.info("Building Reporting Server's public API services")
val encryptionKeyPairStore =
InMemoryEncryptionKeyPairStore(
encryptionKeyPairConfig.principalKeyPairsList.associateBy(
{ it.principal },
{
it.keyPairsList.map { keyPair ->
Pair(
signingPrivateKeyDir.resolve(keyPair.publicKeyFile).readByteString(),
loadPrivateKey(signingPrivateKeyDir.resolve(keyPair.privateKeyFile))
)
}
}
)
)
listOf(
EventGroupsService(
publicKingdomEventGroupsClient,
publicKingdomEventGroupMetadataDescriptorsClient,
encryptionKeyPairStore
)
.withMetadataPrincipalIdentities(measurementConsumerConfig),
ReportingSetsService(internalReportingSetsClient)
.withMetadataPrincipalIdentities(measurementConsumerConfig),
ReportsService(
internalReportsClient,
internalReportingSetsClient,
internalMeasurementsClient,
publicKingdomDataProvidersClient,
publicKingdomMeasurementConsumersClient,
publicKingdomMeasurementsClient,
publicKingdomCertificatesClient,
encryptionKeyPairStore,
SecureRandom(),
signingPrivateKeyDir
)
.withMetadataPrincipalIdentities(measurementConsumerConfig)
)
.forEach { addService(it.withVerboseLogging(verboseGrpcLogging)) }
}
/** Provides a gRPC channel to the Reporting Server's public API. */
val publicApiChannel: Channel
get() = publicApiServer.channel
override fun apply(statement: Statement, description: Description): Statement {
return chainRulesSequentially(internalDataServer, publicApiServer).apply(statement, description)
}
companion object {
private val logger: Logger = Logger.getLogger(this::class.java.name)
}
}
| apache-2.0 | faee42ab2d68326cf831ef571aa89df2 | 47.85906 | 179 | 0.794918 | 5.286855 | false | true | false | false |
chandilsachin/DietTracker | app/src/main/java/com/chandilsachin/diettracker/other/AddFoodPresenter.kt | 1 | 1355 | package com.chandilsachin.diettracker.other
import android.os.Bundle
import com.ne1c.rainbowmvp.base.BaseActivity
/**
* Created by Sachin Chandil on 29/04/2017.
*/
class AddFoodPresenter {
@Throws(java.io.IOException::class)
fun readFoodItemsFile(context: android.content.Context): java.util.ArrayList<com.chandilsachin.diettracker.database.Food> {
val list = java.util.ArrayList<com.chandilsachin.diettracker.database.Food>()
try {
val jsonArray: org.json.JSONArray
jsonArray = com.chandilsachin.diettracker.io.JSONReader.readJsonFileToArrayFromAssets(context.assets, "food_Items.json")
for (i in 0..jsonArray.length() - 1) {
val `object` = jsonArray.getJSONObject(i)
val fact = `object`.getJSONObject("facts")
val food = com.chandilsachin.diettracker.database.Food(`object`.getString("food_name"), `object`.getString("food_desc"), fact.getDouble("protein"),
fact.getDouble("carbs"), fact.getDouble("fat"), fact.getDouble("calories"))
list.add(food)
}
} catch (e: org.json.JSONException) {
e.printStackTrace()
}
return list
}
companion object {
val TAG = com.chandilsachin.diettracker.other.AddFoodPresenter::class.java.name
}
}
| gpl-3.0 | fb46a6856fe1cf6c6d8f30f825f0cf1c | 36.638889 | 163 | 0.648708 | 4.195046 | false | false | false | false |
iYaroslav/PosPrinter | example/src/main/java/io/github/iyaroslav/posprinter/App.kt | 1 | 1034 | package io.github.iyaroslav.posprinter
import android.app.Application
import android.content.Context
import com.google.android.gms.analytics.HitBuilders
/**
* Created by Yaroslav on 04.07.15.
* Copyright 2015 LeeryBit LLC.
*/
class App : Application() {
val tracker: AnalyticsTrackers by lazy {
AnalyticsTrackers(this)
}
override fun onCreate() {
super.onCreate()
val preferences = getSharedPreferences(APP_REFERENCES_KEY, Context.MODE_PRIVATE)
var launchesCount = preferences.getInt(REFERENCES_LAUNCHES, 0)
val action = if (launchesCount == 0) "first_launch" else "launch_app"
tracker.send(HitBuilders.EventBuilder()
.setCategory("app")
.setAction(action)
.setValue(launchesCount.toLong())
.build())
val editor = preferences.edit()
editor.putInt(REFERENCES_LAUNCHES, ++launchesCount)
editor.apply()
}
companion object {
const val APP_REFERENCES_KEY = "APP_PREFERENCES"
private const val REFERENCES_LAUNCHES = "count_of_launches"
}
}
| apache-2.0 | a118b30b32b2bd9c94b62f68472b5ca0 | 24.85 | 84 | 0.705996 | 3.992278 | false | false | false | false |
crunchersaspire/worshipsongs-android | app/src/main/java/org/worshipsongs/preference/ColorPickerPreference.kt | 3 | 9653 | package org.worshipsongs.preference
import android.content.Context
import android.content.res.TypedArray
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.preference.Preference
import androidx.preference.PreferenceViewHolder
/**
* @author: Madasamy
* @version: 3.3.x
*/
class ColorPickerPreference : Preference, Preference.OnPreferenceClickListener, ColorPickerDialog.OnColorChangedListener
{
internal var mView: View? = null
internal var mDialog: ColorPickerDialog? = null
private var mValue = Color.BLACK
private var mDensity = 0f
private var mAlphaSliderEnabled = false
private var mHexValueEnabled = false
private//30dip
val previewBitmap: Bitmap
get()
{
val d = (mDensity * 31).toInt()
val color = mValue
val bm = Bitmap.createBitmap(d, d, Bitmap.Config.ARGB_8888)
val w = bm.width
val h = bm.height
var c = color
for (i in 0 until w)
{
for (j in i until h)
{
c = if (i <= 1 || j <= 1 || i >= w - 2 || j >= h - 2) Color.GRAY else color
bm.setPixel(i, j, c)
if (i != j)
{
bm.setPixel(j, i, c)
}
}
}
return bm
}
constructor(context: Context) : super(context)
{
init(context, null)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
{
init(context, attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
{
init(context, attrs)
}
private fun init(context: Context, attrs: AttributeSet?)
{
mDensity = context.resources.displayMetrics.density
onPreferenceClickListener = this
if (attrs != null)
{
mAlphaSliderEnabled = attrs.getAttributeBooleanValue(null, "alphaSlider", false)
mHexValueEnabled = attrs.getAttributeBooleanValue(null, "hexValue", false)
}
}
/**
* Method edited by
*
* @author Anna Berkovitch
* added functionality to accept hex string as defaultValue
* and to properly persist resources reference string, such as @color/someColor
* previously persisted 0
*/
override fun onGetDefaultValue(a: TypedArray, index: Int): Any
{
val colorInt: Int
val mHexDefaultValue = a.getString(index)
if (mHexDefaultValue != null && mHexDefaultValue.startsWith("#"))
{
colorInt = convertToColorInt(mHexDefaultValue)
return colorInt
} else
{
return a.getColor(index, Color.BLACK)
}
}
override fun onSetInitialValue(restoreValue: Boolean, defaultValue: Any?)
{
onColorChanged(if (restoreValue) getPersistedInt(mValue) else defaultValue as Int)
}
override fun onBindViewHolder(holder: PreferenceViewHolder)
{
super.onBindViewHolder(holder)
mView = holder.itemView
setPreviewColor()
}
private fun setPreviewColor()
{
if (mView == null) return
val iView = ImageView(context)
val widgetFrameView = mView!!.findViewById<View>(android.R.id.widget_frame) as LinearLayout
?: return
widgetFrameView.visibility = View.VISIBLE
widgetFrameView.setPadding(widgetFrameView.paddingLeft, widgetFrameView.paddingTop, (mDensity * 8).toInt(), widgetFrameView.paddingBottom)
// remove already create preview image
val count = widgetFrameView.childCount
if (count > 0)
{
widgetFrameView.removeViews(0, count)
}
widgetFrameView.addView(iView)
widgetFrameView.minimumWidth = 0
iView.setBackgroundDrawable(AlphaPatternDrawable((5 * mDensity).toInt()))
iView.setImageBitmap(previewBitmap)
}
override fun onColorChanged(color: Int)
{
if (isPersistent)
{
persistInt(color)
}
mValue = color
setPreviewColor()
try
{
onPreferenceChangeListener.onPreferenceChange(this, color)
} catch (e: NullPointerException)
{
}
}
override fun onPreferenceClick(preference: Preference): Boolean
{
showDialog(null)
return false
}
protected fun showDialog(state: Bundle?)
{
mDialog = ColorPickerDialog(context, mValue)
mDialog!!.setOnColorChangedListener(this)
if (mAlphaSliderEnabled)
{
mDialog!!.alphaSliderVisible = true
}
if (mHexValueEnabled)
{
mDialog!!.hexValueEnabled = true
}
if (state != null)
{
mDialog!!.onRestoreInstanceState(state)
}
mDialog!!.show()
}
/**
* Toggle Alpha Slider visibility (by default it's disabled)
*
* @param enable
*/
fun setAlphaSliderEnabled(enable: Boolean)
{
mAlphaSliderEnabled = enable
}
/**
* Toggle Hex Value visibility (by default it's disabled)
*
* @param enable
*/
fun setHexValueEnabled(enable: Boolean)
{
mHexValueEnabled = enable
}
override fun onSaveInstanceState(): Parcelable
{
val superState = super.onSaveInstanceState()
if (mDialog == null || !mDialog!!.isShowing)
{
return superState
}
val myState = SavedState(superState)
myState.dialogBundle = mDialog!!.onSaveInstanceState()
return myState
}
override fun onRestoreInstanceState(state: Parcelable?)
{
if (state == null || state !is SavedState)
{
// Didn't save state for us in onSaveInstanceState
super.onRestoreInstanceState(state)
return
}
val myState = state as SavedState?
super.onRestoreInstanceState(myState!!.superState)
showDialog(myState.dialogBundle)
}
private class SavedState : Preference.BaseSavedState
{
internal var dialogBundle: Bundle? = null
constructor(source: Parcel) : super(source)
{
dialogBundle = source.readBundle()
}
override fun writeToParcel(dest: Parcel, flags: Int)
{
super.writeToParcel(dest, flags)
dest.writeBundle(dialogBundle)
}
constructor(superState: Parcelable) : super(superState)
{
}
override fun describeContents(): Int
{
return 0
}
companion object CREATOR : Parcelable.Creator<SavedState>
{
override fun createFromParcel(parcel: Parcel): SavedState
{
return SavedState(parcel)
}
override fun newArray(size: Int): Array<SavedState?>
{
return arrayOfNulls(size)
}
}
}
companion object
{
/**
* For custom purposes. Not used by ColorPickerPreferrence
*
* @param color
* @author Unknown
*/
fun convertToARGB(color: Int): String
{
var alpha = Integer.toHexString(Color.alpha(color))
var red = Integer.toHexString(Color.red(color))
var green = Integer.toHexString(Color.green(color))
var blue = Integer.toHexString(Color.blue(color))
if (alpha.length == 1)
{
alpha = "0$alpha"
}
if (red.length == 1)
{
red = "0$red"
}
if (green.length == 1)
{
green = "0$green"
}
if (blue.length == 1)
{
blue = "0$blue"
}
return "#$alpha$red$green$blue"
}
/**
* Method currently used by onGetDefaultValue method to
* convert hex string provided in android:defaultValue to color integer.
*
* @param color
* @return A string representing the hex value of color,
* without the alpha value
* @author Charles Rosaaen
*/
fun convertToRGB(color: Int): String
{
var red = Integer.toHexString(Color.red(color))
var green = Integer.toHexString(Color.green(color))
var blue = Integer.toHexString(Color.blue(color))
if (red.length == 1)
{
red = "0$red"
}
if (green.length == 1)
{
green = "0$green"
}
if (blue.length == 1)
{
blue = "0$blue"
}
return "#$red$green$blue"
}
/**
* For custom purposes. Not used by ColorPickerPreferrence
*
* @param argb
* @throws NumberFormatException
* @author Unknown
*/
@Throws(IllegalArgumentException::class)
fun convertToColorInt(argb: String): Int
{
var argb = argb
if (!argb.startsWith("#"))
{
argb = "#$argb"
}
return Color.parseColor(argb)
}
}
}
| gpl-3.0 | b48c2070155feb56d27c811c59b4e44b | 25.302452 | 146 | 0.55879 | 4.937596 | false | false | false | false |
Mauin/detekt | detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/naming/VariableMinLength.kt | 1 | 1601 | package io.gitlab.arturbosch.detekt.rules.naming
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.identifierName
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.resolve.calls.util.isSingleUnderscore
/**
* Reports when very short variable names are used.
*
* @configuration minimumVariableNameLength - maximum name length (default: 1)
* @author Marvin Ramin, Niklas Baudy
*/
class VariableMinLength(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(javaClass.simpleName,
Severity.Style,
"Variable names should not be shorter than the minimum defined in the configuration.",
debt = Debt.FIVE_MINS)
private val minimumVariableNameLength =
valueOrDefault(MINIMUM_VARIABLE_NAME_LENGTH, DEFAULT_MINIMUM_VARIABLE_NAME_LENGTH)
override fun visitProperty(property: KtProperty) {
if (property.isSingleUnderscore) {
return
}
if (property.identifierName().length < minimumVariableNameLength) {
report(CodeSmell(
issue,
Entity.from(property),
message = "Variable names should be at least $minimumVariableNameLength characters long."))
}
}
companion object {
const val MINIMUM_VARIABLE_NAME_LENGTH = "minimumVariableNameLength"
private const val DEFAULT_MINIMUM_VARIABLE_NAME_LENGTH = 1
}
}
| apache-2.0 | f1f10b2cac07ee2240e36ebea2feab77 | 33.804348 | 96 | 0.78326 | 3.904878 | false | true | false | false |
qaware/kubepad | src/main/kotlin/de/qaware/cloud/nativ/kpad/launchpad/LaunchpadEvent.kt | 1 | 3499 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 QAware GmbH, Munich, Germany
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.qaware.cloud.nativ.kpad.launchpad
import de.qaware.cloud.nativ.kpad.launchpad.LaunchpadMK2.Color
import javax.inject.Qualifier
/**
* The data class for any trigger event we send to the Launchpad.
*/
data class LaunchpadEvent constructor(val switch: Switch?,
val switchable: LaunchpadMK2.Switchable?,
val text: String?,
val color: Color) {
constructor(switch: Switch, switchable: LaunchpadMK2.Switchable?, color: Color = Color.NONE) : this(switch, switchable, null, color)
constructor(text: String, color: Color) : this(null, null, text, color)
/**
* Switch ON or OFF.
*/
enum class Switch {
ON, OFF
}
@Qualifier
@Target(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
annotation class Light
@Qualifier
@Target(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
annotation class Text
@Qualifier
@Target(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
annotation class Blink
@Qualifier
@Target(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
annotation class Pulse
@Qualifier
@Target(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
annotation class Reset
companion object {
/**
* Factory method for light events.
*/
fun light(switch: Switch, switchable: LaunchpadMK2.Switchable?, color: Color = Color.NONE) = LaunchpadEvent(switch, switchable, color)
/**
* Factory method for text events.
*/
fun text(message: String, color: Color) = LaunchpadEvent(message, color)
/**
* Factory method for reset events.
*/
fun reset() = LaunchpadEvent(Switch.OFF, null, null, Color.NONE)
}
} | mit | 83e986ff0b0f991fead9f96b5ce8aafd | 38.325843 | 142 | 0.707059 | 4.709287 | false | false | false | false |
TeamAmaze/AmazeFileManager | app/src/main/java/com/amaze/filemanager/asynchronous/handlers/FileHandler.kt | 1 | 4131 | /*
* Copyright (C) 2014-2020 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.asynchronous.handlers
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.amaze.filemanager.adapters.RecyclerAdapter
import com.amaze.filemanager.filesystem.CustomFileObserver
import com.amaze.filemanager.filesystem.HybridFile
import com.amaze.filemanager.ui.fragments.MainFragment
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File
import java.lang.ref.WeakReference
class FileHandler(
mainFragment: MainFragment,
private val listView: RecyclerView,
private val useThumbs: Boolean
) : Handler(
Looper.getMainLooper()
) {
private val mainFragment: WeakReference<MainFragment> = WeakReference(mainFragment)
private val log: Logger = LoggerFactory.getLogger(FileHandler::class.java)
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
val main = mainFragment.get() ?: return
val mainFragmentViewModel = main.mainFragmentViewModel ?: return
val elementsList = main.elementsList ?: return
if (main.activity == null) {
return
}
val path = msg.obj as? String
when (msg.what) {
CustomFileObserver.GOBACK -> {
main.goBack()
}
CustomFileObserver.NEW_ITEM -> {
if (path == null) {
log.error("Path is empty for file")
return
}
val fileCreated = HybridFile(
mainFragmentViewModel.openMode,
"${main.currentPath}/$path"
)
val newElement = fileCreated.generateLayoutElement(main.requireContext(), useThumbs)
main.elementsList?.add(newElement)
}
CustomFileObserver.DELETED_ITEM -> {
val index = elementsList.withIndex().find {
File(it.value.desc).name == path
}?.index
if (index != null) {
main.elementsList?.removeAt(index)
}
}
else -> {
super.handleMessage(msg)
return
}
}
if (listView.visibility == View.VISIBLE) {
if (elementsList.size == 0) {
// no item left in list, recreate views
main.reloadListElements(
true,
mainFragmentViewModel.results,
!mainFragmentViewModel.isList
)
} else {
val itemList = main.elementsList ?: listOf()
// we already have some elements in list view, invalidate the adapter
(listView.adapter as RecyclerAdapter).setItems(listView, itemList)
}
} else {
// there was no list view, means the directory was empty
main.loadlist(main.currentPath, true, mainFragmentViewModel.openMode, true)
}
main.currentPath?.let {
main.mainActivityViewModel?.evictPathFromListCache(it)
}
main.computeScroll()
}
}
| gpl-3.0 | 7cef6e374cc2ec993dd6c445c7738616 | 36.899083 | 107 | 0.623336 | 4.78679 | false | false | false | false |
EricssonResearch/scott-eu | gateway/backend/src/main/kotlin/eu/scottproject/wp10/gw/backend/Main.kt | 1 | 2528 | package eu.scottproject.wp10.gw.backend
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import eu.scottproject.wp10.gw.api.GatewayDiscoveryService
import org.zeromq.ZContext
import org.zeromq.ZMQ
import java.util.*
/**
* TBD
*
* @version $version-stub$
* @since FIXME
*/
const val PULL_PORT = 5557
const val CONNECT_ADDR = "tcp://127.0.0.1:$PULL_PORT"
fun main(args: Array<String>) {
println("Registering Gateway Discovery Services")
val serviceLoader = ServiceLoader.load(GatewayDiscoveryService::class.java)
serviceLoader.forEach {
println("Found service: ${it.javaClass.canonicalName}")
}
val providers = serviceLoader.mapNotNull { it.marshallingProviders }.flatMap { it.entries }
if (providers.isEmpty()) {
println("No JARs have been placed on the classpath with a ServiceLoader definition for\n" +
"\tsvc-sample/src/main/resources/META-INF/services/eu.scottproject.wp10.gw.api.GatewayDiscoveryService")
System.exit(-1);
}
// Select the first service that can (un)marshall messages of type "sample"
val simpleProvider = providers.first { it.key == "sample" }.value
println("Pulling from $CONNECT_ADDR")
val mapper = ObjectMapper().registerKotlinModule()
ZContext().use { context ->
// Socket to talk to clients
val socket = context.createSocket(ZMQ.DEALER)
// only one node binds, the rest connect
socket.connect(CONNECT_ADDR)
while (!Thread.currentThread().isInterrupted) {
// Block until a message is received
val reply = socket.recv(0)
val rcvMessage = String(reply, ZMQ.CHARSET)
// Uncomment the line below if you want to see raw JSON
// println("Received: '$rcvMessage'")
// show how Jackson can automatically map the JSON to a Kotlin class
val msg = mapper.readValue<WorkerMessage>(reply)
println("Worker number: ${msg.num}")
simpleProvider.fromBytes(reply).ifPresent {
println("Unmarshalling by the loaded service: $it")
}
// ZMQ.DEALER mode allows us to use the socket bidirectionally w/o blocking
// but has limits on buffers (1000 msg approx)
val response = "{\"id\": 1, \"status\": \"SUCCESS\"}";
socket.send(response.toByteArray(ZMQ.CHARSET), 0)
}
}
}
| apache-2.0 | 7af7dc409e89b82069970bddd47e62dc | 37.30303 | 120 | 0.662975 | 4.164745 | false | false | false | false |
SpineEventEngine/core-java | buildSrc/src/main/kotlin/io/spine/internal/gradle/fs/LazyTempPath.kt | 2 | 4097 | /*
* Copyright 2022, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* 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 io.spine.internal.gradle.fs
import java.io.File
import java.net.URI
import java.nio.file.FileSystem
import java.nio.file.Files.createTempDirectory
import java.nio.file.LinkOption
import java.nio.file.Path
import java.nio.file.WatchEvent
import java.nio.file.WatchKey
import java.nio.file.WatchService
/**
* A path to a temporary folder, which is not created until it is really used.
*
* After the first usage, the instances of this type delegate all calls to the internally
* created instance of [Path] created with [createTempDirectory].
*/
@Suppress("TooManyFunctions")
class LazyTempPath(private val prefix: String) : Path {
private val delegate: Path by lazy { createTempDirectory(prefix) }
override fun compareTo(other: Path): Int = delegate.compareTo(other)
override fun iterator(): MutableIterator<Path> = delegate.iterator()
override fun register(
watcher: WatchService,
events: Array<out WatchEvent.Kind<*>>,
vararg modifiers: WatchEvent.Modifier?
): WatchKey = delegate.register(watcher, events, *modifiers)
override fun register(watcher: WatchService, vararg events: WatchEvent.Kind<*>?): WatchKey =
delegate.register(watcher, *events)
override fun getFileSystem(): FileSystem = delegate.fileSystem
override fun isAbsolute(): Boolean = delegate.isAbsolute
override fun getRoot(): Path = delegate.root
override fun getFileName(): Path = delegate.fileName
override fun getParent(): Path = delegate.parent
override fun getNameCount(): Int = delegate.nameCount
override fun getName(index: Int): Path = delegate.getName(index)
override fun subpath(beginIndex: Int, endIndex: Int): Path =
delegate.subpath(beginIndex, endIndex)
override fun startsWith(other: Path): Boolean = delegate.startsWith(other)
override fun startsWith(other: String): Boolean = delegate.startsWith(other)
override fun endsWith(other: Path): Boolean = delegate.endsWith(other)
override fun endsWith(other: String): Boolean = delegate.endsWith(other)
override fun normalize(): Path = delegate.normalize()
override fun resolve(other: Path): Path = delegate.resolve(other)
override fun resolve(other: String): Path = delegate.resolve(other)
override fun resolveSibling(other: Path): Path = delegate.resolveSibling(other)
override fun resolveSibling(other: String): Path = delegate.resolveSibling(other)
override fun relativize(other: Path): Path = delegate.relativize(other)
override fun toUri(): URI = delegate.toUri()
override fun toAbsolutePath(): Path = delegate.toAbsolutePath()
override fun toRealPath(vararg options: LinkOption?): Path = delegate.toRealPath(*options)
override fun toFile(): File = delegate.toFile()
override fun toString(): String = delegate.toString()
}
| apache-2.0 | 7a19e3e52a0eb69c8b3fb3cd9f8a97d6 | 36.587156 | 96 | 0.74225 | 4.542129 | false | false | false | false |
arturbosch/detekt | detekt-core/src/test/kotlin/io/gitlab/arturbosch/detekt/core/suppressors/AnnotationSuppressorSpec.kt | 1 | 8946 | package io.gitlab.arturbosch.detekt.core.suppressors
import io.github.detekt.test.utils.compileContentForTest
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.findFunctionByName
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class AnnotationSuppressorSpec : Spek({
describe("AnnotationSuppressorFactory") {
it("Factory returns null if ignoreAnnotated is not set") {
val suppressor = annotationSuppressorFactory(buildConfigAware(/* empty */))
assertThat(suppressor).isNull()
}
it("Factory returns null if ignoreAnnotated is set to empty") {
val suppressor = annotationSuppressorFactory(
buildConfigAware("ignoreAnnotated" to emptyList<String>())
)
assertThat(suppressor).isNull()
}
it("Factory returns not null if ignoreAnnotated is set to a not empty list") {
val suppressor = annotationSuppressorFactory(
buildConfigAware("ignoreAnnotated" to listOf("Composable"))
)
assertThat(suppressor).isNotNull()
}
}
describe("AnnotationSuppressor") {
val suppressor by memoized {
annotationSuppressorFactory(buildConfigAware("ignoreAnnotated" to listOf("Composable")))!!
}
it("If KtElement is null it returns false") {
assertThat(suppressor(buildFinding(element = null))).isFalse()
}
context("If annotation is at file level") {
val root by memoized {
compileContentForTest(
"""
@file:Composable
class OneClass {
fun function(parameter: String) {
val a = 0
}
}
fun topLevelFunction() = Unit
""".trimIndent()
)
}
it("If reports root it returns true") {
assertThat(suppressor(buildFinding(element = root))).isTrue()
}
it("If reports class it returns true") {
val ktClass = root.findChildByClass(KtClass::class.java)!!
assertThat(suppressor(buildFinding(element = ktClass))).isTrue()
}
it("If reports function in class it returns true") {
val ktFunction = root.findChildByClass(KtClass::class.java)!!
.findFunctionByName("function")!!
assertThat(suppressor(buildFinding(element = ktFunction))).isTrue()
}
it("If reports parameter in function in class it returns true") {
val ktParameter = root.findChildByClass(KtClass::class.java)!!
.findFunctionByName("function")!!
.findDescendantOfType<KtParameter>()!!
assertThat(suppressor(buildFinding(element = ktParameter))).isTrue()
}
it("If reports top level function it returns true") {
val ktFunction = root.findChildByClass(KtFunction::class.java)!!
assertThat(suppressor(buildFinding(element = ktFunction))).isTrue()
}
}
context("If annotation is at function level") {
val root by memoized {
compileContentForTest(
"""
class OneClass {
@Composable
fun function(parameter: String) {
val a = 0
}
}
fun topLevelFunction() = Unit
""".trimIndent()
)
}
it("If reports root it returns false") {
assertThat(suppressor(buildFinding(element = root))).isFalse()
}
it("If reports class it returns false") {
val ktClass = root.findChildByClass(KtClass::class.java)!!
assertThat(suppressor(buildFinding(element = ktClass))).isFalse()
}
it("If reports function in class it returns true") {
val ktFunction = root.findChildByClass(KtClass::class.java)!!
.findFunctionByName("function")!!
assertThat(suppressor(buildFinding(element = ktFunction))).isTrue()
}
it("If reports parameter in function in class it returns true") {
val ktParameter = root.findChildByClass(KtClass::class.java)!!
.findFunctionByName("function")!!
.findDescendantOfType<KtParameter>()!!
assertThat(suppressor(buildFinding(element = ktParameter))).isTrue()
}
it("If reports top level function it returns false") {
val ktFunction = root.findChildByClass(KtFunction::class.java)!!
assertThat(suppressor(buildFinding(element = ktFunction))).isFalse()
}
}
context("If there is not annotations") {
val root by memoized {
compileContentForTest(
"""
class OneClass {
fun function(parameter: String) {
val a = 0
}
}
fun topLevelFunction() = Unit
""".trimIndent()
)
}
it("If reports root it returns false") {
assertThat(suppressor(buildFinding(element = root))).isFalse()
}
it("If reports class it returns false") {
val ktClass = root.findChildByClass(KtClass::class.java)!!
assertThat(suppressor(buildFinding(element = ktClass))).isFalse()
}
it("If reports function in class it returns false") {
val ktFunction = root.findChildByClass(KtClass::class.java)!!
.findFunctionByName("function")!!
assertThat(suppressor(buildFinding(element = ktFunction))).isFalse()
}
it("If reports parameter in function in class it returns false") {
val ktParameter = root.findChildByClass(KtClass::class.java)!!
.findFunctionByName("function")!!
.findDescendantOfType<KtParameter>()!!
assertThat(suppressor(buildFinding(element = ktParameter))).isFalse()
}
it("If reports top level function it returns false") {
val ktFunction = root.findChildByClass(KtFunction::class.java)!!
assertThat(suppressor(buildFinding(element = ktFunction))).isFalse()
}
}
context("If there are other annotations") {
val root by memoized {
compileContentForTest(
"""
@file:A
@B
class OneClass {
@Composable
fun function(@C parameter: String) {
@D
val a = 0
}
}
@E
fun topLevelFunction() = Unit
""".trimIndent()
)
}
it("If reports root it returns false") {
assertThat(suppressor(buildFinding(element = root))).isFalse()
}
it("If reports class it returns false") {
val ktClass = root.findChildByClass(KtClass::class.java)!!
assertThat(suppressor(buildFinding(element = ktClass))).isFalse()
}
it("If reports function in class it returns true") {
val ktFunction = root.findChildByClass(KtClass::class.java)!!
.findFunctionByName("function")!!
assertThat(suppressor(buildFinding(element = ktFunction))).isTrue()
}
it("If reports parameter in function in class it returns true") {
val ktParameter = root.findChildByClass(KtClass::class.java)!!
.findFunctionByName("function")!!
.findDescendantOfType<KtParameter>()!!
assertThat(suppressor(buildFinding(element = ktParameter))).isTrue()
}
it("If reports top level function it returns false") {
val ktFunction = root.findChildByClass(KtFunction::class.java)!!
assertThat(suppressor(buildFinding(element = ktFunction))).isFalse()
}
}
}
})
| apache-2.0 | 974b07f53e97d4cc3eab177b475a3f3a | 35.514286 | 102 | 0.533982 | 5.831812 | false | false | false | false |
arturbosch/detekt | detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/internal/Suppressions.kt | 1 | 2266 | package io.gitlab.arturbosch.detekt.api.internal
import io.gitlab.arturbosch.detekt.api.RuleId
import io.gitlab.arturbosch.detekt.api.RuleSetId
import org.jetbrains.kotlin.psi.KtAnnotated
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
/**
* Checks if this psi element is suppressed by @Suppress or @SuppressWarnings annotations.
* If this element cannot have annotations, the first annotative parent is searched.
*/
fun KtElement.isSuppressedBy(id: String, aliases: Set<String>, ruleSetId: RuleSetId? = null): Boolean =
this is KtAnnotated && this.isSuppressedBy(id, aliases, ruleSetId) ||
findAnnotatedSuppressedParent(id, aliases, ruleSetId)
private fun KtElement.findAnnotatedSuppressedParent(
id: String,
aliases: Set<String>,
ruleSetId: RuleSetId? = null
): Boolean {
val parent = getStrictParentOfType<KtAnnotated>()
var suppressed = false
if (parent != null && parent !is KtFile) {
suppressed = if (parent.isSuppressedBy(id, aliases, ruleSetId)) {
true
} else {
parent.findAnnotatedSuppressedParent(id, aliases, ruleSetId)
}
}
return suppressed
}
private val detektSuppressionPrefixRegex = Regex("(?i)detekt([.:])")
private const val QUOTES = "\""
private val suppressionAnnotations = setOf("Suppress", "SuppressWarnings")
/**
* Checks if this kt element is suppressed by @Suppress or @SuppressWarnings annotations.
*/
fun KtAnnotated.isSuppressedBy(id: RuleId, aliases: Set<String>, ruleSetId: RuleSetId? = null): Boolean {
val acceptedSuppressionIds = mutableSetOf(id, "ALL", "all", "All")
if (ruleSetId != null) {
acceptedSuppressionIds.addAll(listOf(ruleSetId, "$ruleSetId.$id", "$ruleSetId:$id"))
}
acceptedSuppressionIds.addAll(aliases)
return annotationEntries
.find { it.typeReference?.text in suppressionAnnotations }
?.run {
valueArguments
.map { it.getArgumentExpression()?.text }
.map { it?.replace(detektSuppressionPrefixRegex, "") }
.map { it?.replace(QUOTES, "") }
.find { it in acceptedSuppressionIds }
} != null
}
| apache-2.0 | 450604e88388e9638c59cb94dd19db6e | 37.40678 | 105 | 0.695057 | 4.391473 | false | false | false | false |
ExMCL/ExMCL | ExMCL Game Output Manager/src/main/kotlin/com/n9mtq4/exmcl/gameoutmanager/GameOutputManager.kt | 1 | 4069 | /*
* MIT License
*
* Copyright (c) 2016 Will (n9Mtq4) Bresnahan
*
* 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.
*/
@file:JvmName("GameOutputManager")
package com.n9mtq4.exmcl.gameoutmanager
import com.n9mtq4.exmcl.api.hooks.events.PreDefinedSwingComponent
import com.n9mtq4.exmcl.api.hooks.events.PreDefinedSwingHookEvent
import com.n9mtq4.exmcl.api.hooks.events.swinguserinterface.PostSUIShowGameOutputTab
import com.n9mtq4.exmcl.api.tabs.events.LowLevelCreateTabEvent
import com.n9mtq4.exmcl.api.tabs.events.SafeForLowLevelTabCreationEvent
import com.n9mtq4.kotlin.extlib.pstAndUnit
import com.n9mtq4.logwindow.BaseConsole
import com.n9mtq4.logwindow.annotation.ListensFor
import com.n9mtq4.logwindow.events.EnableEvent
import com.n9mtq4.logwindow.listener.EnableListener
import com.n9mtq4.logwindow.listener.GenericListener
import net.minecraft.launcher.ui.tabs.GameOutputTab
import net.minecraft.launcher.ui.tabs.LauncherTabPanel
import java.awt.Component
import javax.swing.JTabbedPane
import javax.swing.SwingUtilities
/**
* Created by will on 2/14/16 at 7:43 PM.
*
* @author Will "n9Mtq4" Bresnahan
*/
class GameOutputManager : EnableListener, GenericListener {
private lateinit var parent: BaseConsole
private var tabSafe = false
private var added = false
private val gameOutputTabs: JTabbedPane by lazy { JTabbedPane() }
private lateinit var launcherTabPanel: LauncherTabPanel
override fun onEnable(e: EnableEvent) {
this.parent = e.baseConsole
}
@Suppress("unused", "UNUSED_PARAMETER")
@ListensFor
fun listenForShowGameOutputTab(e: PostSUIShowGameOutputTab, baseConsole: BaseConsole) {
fireNewGameOutputTab()
}
@Suppress("unused", "UNUSED_PARAMETER")
@ListensFor(SafeForLowLevelTabCreationEvent::class)
fun listenForTabSafe(e: SafeForLowLevelTabCreationEvent, baseConsole: BaseConsole) {
this.tabSafe = true
}
@Suppress("unused", "UNUSED_PARAMETER")
@ListensFor(PreDefinedSwingHookEvent::class)
fun listenForLauncherTabPanel(e: PreDefinedSwingHookEvent, baseConsole: BaseConsole) {
if (e.type == PreDefinedSwingComponent.LAUNCHER_TAB_PANEL) launcherTabPanel = e.component as LauncherTabPanel
}
private fun fireNewGameOutputTab() {
if (!added) {
addGameOutputTabs()
added = true
}
for (i in 0..launcherTabPanel.tabCount - 1) {
val tab = launcherTabPanel.getComponentAt(i)
if (tab is GameOutputTab) addNewTab(i, launcherTabPanel.getTitleAt(i), tab)
}
}
private fun addNewTab(index: Int, title: String, component: Component) {
SwingUtilities.invokeLater {
launcherTabPanel.removeTabAt(index)
gameOutputTabs.add(cropTabName(title), component)
gameOutputTabs.selectedComponent = component // select the game output. this is the default behavior of vanilla launcher
}
}
private fun addGameOutputTabs() = SwingUtilities.invokeLater {
pstAndUnit {
parent.pushEvent(LowLevelCreateTabEvent("Game Output", gameOutputTabs, parent))
}
}
private fun cropTabName(title: String) = title.substring(title.indexOf("(") + 1, title.indexOf(")"))
}
| mit | 5672dc2beb9e872f90169f34cd66e4d7 | 37.028037 | 123 | 0.781273 | 3.736455 | false | false | false | false |
lindelea/lindale | app/src/main/java/org/lindelin/lindale/supports/helpers.kt | 1 | 1815 | package org.lindelin.lindale.supports
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.BitmapFactory
import android.util.Base64
import android.view.animation.DecelerateInterpolator
import android.webkit.WebView
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.Toast
import kotlinx.android.synthetic.main.fragment_home.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import java.net.URL
fun ImageView.setImageFromUrl(url: String?) {
url?.let {
doAsync {
val imageUrl = URL(it)
val connection = imageUrl.openConnection()
connection.connectTimeout = 6000
connection.doInput = true
connection.useCaches = true
connection.connect()
val imgBit = connection.getInputStream()
val bmp = BitmapFactory.decodeStream(imgBit)
imgBit.close()
uiThread {
setImageBitmap(bmp)
}
}
}
}
@SuppressLint("SetJavaScriptEnabled")
fun WebView.loadHtmlString(html: String) {
settings.javaScriptEnabled = true
val encodedHtml = Base64.encodeToString(html.toByteArray(), Base64.NO_PADDING)
loadData(encodedHtml, "text/html", "base64")
}
fun ProgressBar.onProgressChanged(percentage: Int) {
val animation = ObjectAnimator.ofInt(this, "progress", percentage)
animation.duration = 500
animation.interpolator = DecelerateInterpolator()
animation.start()
}
fun short_message(context: Context, message: String) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
fun long_message(context: Context, message: String) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
} | mit | ec1b977831e0b251b2f47c7ba331cc3a | 30.310345 | 82 | 0.716804 | 4.448529 | false | false | false | false |
lambdasoup/watchlater | app/src/main/java/com/lambdasoup/watchlater/viewmodel/AddViewModel.kt | 1 | 19399 | /*
* Copyright (c) 2015 - 2021
*
* Maximilian Hille <[email protected]>
* Juliane Lehmann <[email protected]>
*
* This file is part of Watch Later.
*
* Watch Later 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.
*
* Watch Later 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 Watch Later. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lambdasoup.watchlater.viewmodel
import android.accounts.Account
import android.content.Intent
import android.net.Uri
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import com.lambdasoup.tea.Cmd
import com.lambdasoup.tea.Sub
import com.lambdasoup.tea.Tea
import com.lambdasoup.tea.times
import com.lambdasoup.watchlater.data.AccountRepository
import com.lambdasoup.watchlater.data.AccountRepository.AuthTokenResult
import com.lambdasoup.watchlater.data.YoutubeRepository
import com.lambdasoup.watchlater.data.YoutubeRepository.AddVideoResult
import com.lambdasoup.watchlater.data.YoutubeRepository.ErrorType
import com.lambdasoup.watchlater.data.YoutubeRepository.Playlists
import com.lambdasoup.watchlater.data.YoutubeRepository.Playlists.Playlist
import com.lambdasoup.watchlater.data.YoutubeRepository.PlaylistsResult
import com.lambdasoup.watchlater.data.YoutubeRepository.VideoInfoResult
import com.lambdasoup.watchlater.data.YoutubeRepository.Videos
import com.lambdasoup.watchlater.util.EventSource
import com.lambdasoup.watchlater.util.VideoIdParser
import com.lambdasoup.watchlater.viewmodel.AddViewModel.Msg.ChangePlaylist
import com.lambdasoup.watchlater.viewmodel.AddViewModel.Msg.ClearPlaylists
import com.lambdasoup.watchlater.viewmodel.AddViewModel.Msg.OnAccount
import com.lambdasoup.watchlater.viewmodel.AddViewModel.Msg.OnAccountPermissionGranted
import com.lambdasoup.watchlater.viewmodel.AddViewModel.Msg.OnAddVideoResult
import com.lambdasoup.watchlater.viewmodel.AddViewModel.Msg.OnInsertTokenResult
import com.lambdasoup.watchlater.viewmodel.AddViewModel.Msg.OnPlaylistResult
import com.lambdasoup.watchlater.viewmodel.AddViewModel.Msg.OnPlaylistsTokenResult
import com.lambdasoup.watchlater.viewmodel.AddViewModel.Msg.OnTargetPlaylist
import com.lambdasoup.watchlater.viewmodel.AddViewModel.Msg.OnVideoInfoResult
import com.lambdasoup.watchlater.viewmodel.AddViewModel.Msg.OnVideoInfoTokenResult
import com.lambdasoup.watchlater.viewmodel.AddViewModel.Msg.SelectPlaylist
import com.lambdasoup.watchlater.viewmodel.AddViewModel.Msg.SetAccount
import com.lambdasoup.watchlater.viewmodel.AddViewModel.Msg.SetPermissionNeeded
import com.lambdasoup.watchlater.viewmodel.AddViewModel.Msg.SetVideoUri
import com.lambdasoup.watchlater.viewmodel.AddViewModel.Msg.WatchLater
import com.lambdasoup.watchlater.viewmodel.AddViewModel.VideoInfo.ErrorType.InvalidVideoId
import com.lambdasoup.watchlater.viewmodel.AddViewModel.VideoInfo.ErrorType.Network
import com.lambdasoup.watchlater.viewmodel.AddViewModel.VideoInfo.ErrorType.NoAccount
import com.lambdasoup.watchlater.viewmodel.AddViewModel.VideoInfo.ErrorType.Other
import com.lambdasoup.watchlater.viewmodel.AddViewModel.VideoInfo.ErrorType.Youtube
class AddViewModel(
private val accountRepository: AccountRepository,
private val youtubeRepository: YoutubeRepository,
private val videoIdParser: VideoIdParser,
) : ViewModel() {
private val getVideoInfo = Cmd.task<Msg, String, String, VideoInfoResult> { videoId, token ->
youtubeRepository.getVideoInfo(videoId, token)
}
private val getAuthToken = Cmd.task<Msg, AuthTokenResult> {
accountRepository.getAuthToken()
}
private val getPlaylists = Cmd.task<Msg, String, PlaylistsResult> {
youtubeRepository.getPlaylists(it)
}
private val addVideo =
Cmd.task<Msg, String, String, Playlist, AddVideoResult> { videoId, token, playlist ->
youtubeRepository.addVideo(videoId = videoId, token = token, playlist = playlist)
}
private val invalidateAuthToken =
Cmd.event<Msg, String> { accountRepository.invalidateToken(it) }
private val onAccountPermissionGranted = Sub.create<Unit, Msg>()
private val accountObserver: Observer<Account?> =
Observer { account -> accountSubscription.submit(account) }
private val accountSubscription = Sub.create<Account?, Msg>(
bind = {
accountRepository.get().observeForever(accountObserver)
},
unbind = {
accountRepository.get().removeObserver(accountObserver)
}
)
private val playlistObserver: Observer<Playlist?> = Observer { playlistSubscription.submit(it) }
private val playlistSubscription = Sub.create<Playlist?, Msg>(
bind = {
youtubeRepository.targetPlaylist.observeForever(playlistObserver)
},
unbind = {
youtubeRepository.targetPlaylist.removeObserver(playlistObserver)
}
)
override fun onCleared() {
super.onCleared()
tea.clear()
}
private val initialModel = Model(
videoId = null,
videoAdd = VideoAdd.Idle,
videoInfo = VideoInfo.Progress,
account = null,
permissionNeeded = null,
tokenRetried = false,
targetPlaylist = null,
playlistSelection = null,
)
val events = EventSource<Event>()
val model = MutableLiveData<Model>(initialModel)
private val tea = Tea(
init = initialModel * Cmd.none(),
view = model::postValue,
update = ::update,
subscriptions = ::subscriptions,
)
private fun update(model: Model, msg: Msg): Pair<Model, Cmd<Msg>> =
when (msg) {
is WatchLater -> {
if (model.account == null) {
model.copy(videoAdd = VideoAdd.Error(VideoAdd.ErrorType.NoAccount)) *
Cmd.none()
} else if (model.permissionNeeded != null && model.permissionNeeded) {
model.copy(videoAdd = VideoAdd.Error(VideoAdd.ErrorType.NoPermission)) *
Cmd.none()
} else if (model.targetPlaylist == null) {
model.copy(videoAdd = VideoAdd.Error(VideoAdd.ErrorType.NoPlaylistSelected)) *
Cmd.none()
} else {
model.copy(videoAdd = VideoAdd.Progress) *
getAuthToken {
OnInsertTokenResult(
it,
msg.videoId,
model.targetPlaylist
)
}
}
}
is SetAccount -> model.copy(videoAdd = VideoAdd.Idle) *
Cmd.event<Msg> {
accountRepository.put(msg.account)
youtubeRepository.setPlaylist(null)
}
is ChangePlaylist ->
if (model.account == null) {
model.copy(videoAdd = VideoAdd.Error(VideoAdd.ErrorType.NoAccount)) *
Cmd.none()
} else {
model * getAuthToken { OnPlaylistsTokenResult(it) }
}
is OnPlaylistsTokenResult -> when (msg.result) {
is AuthTokenResult.Error ->
model.copy(videoAdd = VideoAdd.Error(msg.result.errorType.toVideoAddErrorType())) * Cmd.none()
is AuthTokenResult.AuthToken ->
model * getPlaylists(msg.result.token) {
OnPlaylistResult(
it,
msg.result.token
)
}
is AuthTokenResult.HasIntent ->
model.copy(videoAdd = VideoAdd.HasIntent(msg.result.intent)) *
Cmd.event<Msg> { events.submit(Event.OpenAuthIntent(msg.result.intent)) }
}
is SetVideoUri -> {
val videoId = videoIdParser.parseVideoId(msg.uri)
if (videoId != null) {
model.copy(videoId = videoId) *
getAuthToken { token -> OnVideoInfoTokenResult(token, videoId) }
} else {
model.copy(
videoId = null,
videoInfo = VideoInfo.Error(InvalidVideoId),
) * Cmd.none()
}
}
is OnVideoInfoTokenResult -> when (msg.result) {
is AuthTokenResult.Error ->
model.copy(videoInfo = VideoInfo.Error(msg.result.errorType.toVideoInfoErrorType())) * Cmd.none()
is AuthTokenResult.AuthToken ->
model * getVideoInfo(msg.videoId, msg.result.token) { OnVideoInfoResult(it) }
is AuthTokenResult.HasIntent ->
model.copy(videoAdd = VideoAdd.HasIntent(msg.result.intent)) *
Cmd.event<Msg> { events.submit(Event.OpenAuthIntent(msg.result.intent)) }
}
is OnVideoInfoResult -> when (msg.result) {
is VideoInfoResult.VideoInfo ->
model.copy(videoInfo = VideoInfo.Loaded(msg.result.item)) * Cmd.none()
is VideoInfoResult.Error ->
model.copy(videoInfo = VideoInfo.Error(Youtube(msg.result.type))) * Cmd.none()
}
is SetPermissionNeeded -> {
// only reset add state when permission state changes to positive
val oldValue = model.permissionNeeded
val videoAdd = if (oldValue != null && oldValue && !msg.permissionNeeded) {
VideoAdd.Idle
} else {
model.videoAdd
}
model.copy(
permissionNeeded = msg.permissionNeeded,
videoAdd = videoAdd,
) * Cmd.none()
}
is OnAccount -> model.copy(account = msg.account) *
// in case we did not have an account yet, trigger video info load
if (model.videoInfo is VideoInfo.Error && msg.account != null && model.videoId != null) {
getAuthToken { OnVideoInfoTokenResult(it, model.videoId) }
} else {
Cmd.none()
}
is OnInsertTokenResult -> when (msg.result) {
is AuthTokenResult.Error ->
model.copy(videoAdd = VideoAdd.Error(msg.result.errorType.toVideoAddErrorType())) * Cmd.none()
is AuthTokenResult.AuthToken ->
model * addVideo(msg.videoId, msg.result.token, msg.targetPlaylist) {
OnAddVideoResult(it, msg.videoId, msg.targetPlaylist)
}
is AuthTokenResult.HasIntent ->
model.copy(videoAdd = VideoAdd.HasIntent(msg.result.intent)) *
Cmd.event<Msg> { events.submit(Event.OpenAuthIntent(msg.result.intent)) }
}
is OnAddVideoResult -> when (msg.result) {
is AddVideoResult.Success -> model.copy(videoAdd = VideoAdd.Success) * Cmd.none()
is AddVideoResult.Error ->
when (msg.result.type) {
ErrorType.InvalidToken -> {
if (model.tokenRetried) {
model.copy(
videoAdd = VideoAdd.Error(VideoAdd.ErrorType.Other(msg.result.type.name))
) * Cmd.none()
} else {
model.copy(tokenRetried = true) * Cmd.batch(
invalidateAuthToken(msg.result.token),
getAuthToken {
OnInsertTokenResult(
it,
msg.videoId,
msg.targetPlaylist
)
}
)
}
}
ErrorType.Network ->
model.copy(videoAdd = VideoAdd.Error(VideoAdd.ErrorType.Network)) * Cmd.none()
else ->
model.copy(
videoAdd = VideoAdd.Error(VideoAdd.ErrorType.Other(msg.result.type.name))
) * Cmd.none()
}
}
is OnPlaylistResult ->
when (msg.result) {
is PlaylistsResult.Error -> when (msg.result.type) {
ErrorType.InvalidToken -> {
if (model.tokenRetried) {
model.copy(
videoAdd = VideoAdd.Error(VideoAdd.ErrorType.Other(msg.result.type.name))
) * Cmd.none()
} else {
model.copy(tokenRetried = true) * Cmd.batch(
invalidateAuthToken(msg.token),
getAuthToken { OnPlaylistsTokenResult(it) }
)
}
}
ErrorType.Network ->
model.copy(videoAdd = VideoAdd.Error(VideoAdd.ErrorType.Network)) * Cmd.none()
else ->
model.copy(
videoAdd = VideoAdd.Error(VideoAdd.ErrorType.Other(msg.result.type.name))
) * Cmd.none()
}
is PlaylistsResult.Ok -> {
model.copy(playlistSelection = msg.result.playlists) * Cmd.none()
}
}
is OnAccountPermissionGranted -> model.copy(videoAdd = VideoAdd.Idle) * Cmd.none()
is OnTargetPlaylist -> model.copy(targetPlaylist = msg.playlist) * Cmd.none()
is SelectPlaylist -> model.copy(playlistSelection = null, videoAdd = VideoAdd.Idle) *
Cmd.event<Msg> { youtubeRepository.setPlaylist(msg.playlist) }
is ClearPlaylists -> model.copy(playlistSelection = null) * Cmd.none()
}
@Suppress("UNUSED_PARAMETER")
private fun subscriptions(model: Model) =
Sub.batch(
accountSubscription { OnAccount(it) },
onAccountPermissionGranted { OnAccountPermissionGranted },
playlistSubscription { OnTargetPlaylist(it) },
)
data class Model(
val videoId: String?,
val videoAdd: VideoAdd,
val videoInfo: VideoInfo,
val account: Account?,
val permissionNeeded: Boolean?,
val tokenRetried: Boolean,
val targetPlaylist: Playlist?,
val playlistSelection: Playlists?,
)
sealed class Msg {
data class WatchLater(val videoId: String) : Msg()
data class SetAccount(val account: Account) : Msg()
data class OnAccount(val account: Account?) : Msg()
data class OnTargetPlaylist(val playlist: Playlist?) : Msg()
object OnAccountPermissionGranted : Msg()
object ChangePlaylist : Msg()
data class OnPlaylistResult(
val result: PlaylistsResult,
val token: String,
) : Msg()
object ClearPlaylists : Msg()
data class SelectPlaylist(val playlist: Playlist?) : Msg()
data class SetVideoUri(val uri: Uri) : Msg()
data class SetPermissionNeeded(val permissionNeeded: Boolean) : Msg()
data class OnVideoInfoResult(val result: VideoInfoResult) : Msg()
data class OnInsertTokenResult(
val result: AuthTokenResult,
val videoId: String,
val targetPlaylist: Playlist,
) : Msg()
data class OnPlaylistsTokenResult(
val result: AuthTokenResult,
) : Msg()
data class OnVideoInfoTokenResult(
val result: AuthTokenResult,
val videoId: String,
) : Msg()
data class OnAddVideoResult(
val result: AddVideoResult,
val videoId: String,
val targetPlaylist: Playlist,
) : Msg()
}
sealed class Event {
data class OpenAuthIntent(val intent: Intent) : Event()
}
fun onAccountPermissionGranted() {
onAccountPermissionGranted.submit(Unit)
}
fun setAccount(account: Account) {
tea.ui(SetAccount(account))
}
fun setVideoUri(uri: Uri) {
tea.ui(SetVideoUri(uri))
}
fun setPermissionNeeded(needsPermission: Boolean) {
tea.ui(SetPermissionNeeded(needsPermission))
}
fun watchLater(videoId: String) {
tea.ui(WatchLater(videoId))
}
fun changePlaylist() {
tea.ui(ChangePlaylist)
}
fun selectPlaylist(playlist: Playlist) {
tea.ui(SelectPlaylist(playlist))
}
fun clearPlaylists() {
tea.ui(ClearPlaylists)
}
sealed class VideoAdd {
object Idle : VideoAdd()
object Progress : VideoAdd()
object Success : VideoAdd()
data class Error(val error: ErrorType) : VideoAdd()
data class HasIntent(val intent: Intent) : VideoAdd()
sealed interface ErrorType {
data class Other(val msg: String) : ErrorType
object NoAccount : ErrorType
object NoPermission : ErrorType
object NoPlaylistSelected : ErrorType
object Network : ErrorType
}
}
sealed class VideoInfo {
object Progress : VideoInfo()
data class Loaded(val data: Videos.Item) : VideoInfo()
data class Error(val error: ErrorType) : VideoInfo()
sealed interface ErrorType {
data class Youtube(val error: YoutubeRepository.ErrorType) : ErrorType
object NoAccount : ErrorType
object InvalidVideoId : ErrorType
object Network : ErrorType
data class Other(val msg: String) : ErrorType
}
}
private fun AccountRepository.ErrorType.toVideoAddErrorType() = when (this) {
is AccountRepository.ErrorType.Network -> VideoAdd.ErrorType.Network
is AccountRepository.ErrorType.AccountRemoved -> VideoAdd.ErrorType.NoAccount
is AccountRepository.ErrorType.Other -> VideoAdd.ErrorType.Other(msg)
}
private fun AccountRepository.ErrorType.toVideoInfoErrorType() = when (this) {
is AccountRepository.ErrorType.Network -> Network
is AccountRepository.ErrorType.AccountRemoved -> NoAccount
is AccountRepository.ErrorType.Other -> Other(msg)
}
}
| gpl-3.0 | b33e744904f98990469757ffa343a111 | 40.71828 | 117 | 0.589566 | 4.974103 | false | false | false | false |
antoniolg/Bandhook-Kotlin | app/src/main/java/com/antonioleiva/bandhookkotlin/ui/screens/detail/AlbumsFragment.kt | 1 | 3203 | /*
* Copyright (C) 2016 Alexey Verein
*
* 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.antonioleiva.bandhookkotlin.ui.screens.detail
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.antonioleiva.bandhookkotlin.ui.activity.ViewAnkoComponent
import com.antonioleiva.bandhookkotlin.ui.adapter.BaseAdapter
import com.antonioleiva.bandhookkotlin.ui.adapter.ImageTitleAdapter
import com.antonioleiva.bandhookkotlin.ui.custom.AutofitRecyclerView
import com.antonioleiva.bandhookkotlin.ui.custom.autoFitRecycler
import com.antonioleiva.bandhookkotlin.ui.entity.ImageTitle
import com.antonioleiva.bandhookkotlin.ui.fragment.AlbumsFragmentContainer
import com.antonioleiva.bandhookkotlin.ui.screens.style
import org.jetbrains.anko.AnkoContext
class AlbumsFragment : Fragment() {
var albumsFragmentContainer: AlbumsFragmentContainer? = null
private set
private var component: Component? = null
var adapter: ImageTitleAdapter? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
component = container?.let { Component(container) }
return component?.inflate()?.setup()
}
private fun View.setup(): View {
component?.recycler?.let {
adapter = ImageTitleAdapter { item ->
albumsFragmentContainer?.getAlbumsPresenter()?.onAlbumClicked(item)
}
it.adapter = adapter
}
return this
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is AlbumsFragmentContainer) {
albumsFragmentContainer = context
}
}
override fun onDetach() {
super.onDetach()
albumsFragmentContainer = null
}
private class Component(override val view: ViewGroup) : ViewAnkoComponent<ViewGroup> {
lateinit var recycler: RecyclerView
override fun createView(ui: AnkoContext<ViewGroup>) = with(ui) {
recycler = autoFitRecycler().apply(AutofitRecyclerView::style)
recycler
}
}
fun findViewByItemId(id: String): View? {
return adapter?.findPositionById(id)?.let {
val holder = component?.recycler?.findViewHolderForLayoutPosition(it)
as BaseAdapter.BaseViewHolder<ImageTitleAdapter.Component>
return holder.ui.image
}
}
fun showAlbums(albums: List<ImageTitle>) {
adapter?.items = albums
}
} | apache-2.0 | 76083c3f95e570c8298f84d7ee47fa90 | 33.085106 | 116 | 0.715891 | 4.752226 | false | false | false | false |
yh-kim/gachi-android | Gachi/app/src/main/kotlin/com/pickth/gachi/view/main/fragments/chat/adapter/ChatAdapter.kt | 1 | 1389 | package com.pickth.gachi.view.main.fragments.chat.adapter
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.pickth.gachi.R
import com.pickth.gachi.util.OnItemClickListener
import com.pickth.gachi.view.gachi.Gachi
/**
* Created by yonghoon on 2017-07-23.
* Mail : [email protected]
*/
class ChatAdapter: RecyclerView.Adapter<ChatViewHolder>(), ChatAdapterContract.View, ChatAdapterContract.Model {
val itemList: ArrayList<Gachi> = ArrayList()
var mOnItemClickListener: OnItemClickListener?= null
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ChatViewHolder {
val itemView = LayoutInflater
.from(parent?.context)
.inflate(R.layout.item_chat, parent, false)
return ChatViewHolder(itemView, mOnItemClickListener)
}
override fun onBindViewHolder(holder: ChatViewHolder?, position: Int) {
holder?.onBind(getItem(position), position)
}
override fun getItemCount(): Int = itemList.size
override fun setItemClickListener(clickListener: OnItemClickListener) {
mOnItemClickListener = clickListener
}
override fun getItem(position: Int): Gachi = itemList[position]
override fun addItem(item: Gachi) {
itemList.add(item)
notifyItemInserted(itemCount - 1)
}
} | apache-2.0 | 96e44315b910374155cfe8cdd9d5f8d0 | 30.590909 | 112 | 0.727142 | 4.4377 | false | false | false | false |
olonho/carkot | server/src/main/java/algorithm/PrettyPrinting.kt | 1 | 600 | package algorithm
import RouteMetricRequest
fun fromIntToDirection(value: Int): String {
return when (value) {
0 -> "FORWARD"
1 -> "BACKWARD"
2 -> "LEFT"
3 -> "RIGHT"
else -> throw IllegalArgumentException("Error parsing Direction from Int: got value = $value")
}
}
fun RouteMetricRequest.toString(): String {
var res = emptyArray<String>()
for (i in distances.indices) {
val dist = distances[i].toString()
val dir = fromIntToDirection(directions[i])
res += "($dist, $dir)"
}
return res.joinToString("; ")
} | mit | 534adf2e95bec6dbf4ef3390ea4cfa9d | 23.04 | 102 | 0.603333 | 4.137931 | false | false | false | false |
whoww/SneakPeek | app/src/main/java/de/sneakpeek/adapter/StudiosAdapter.kt | 1 | 2384 | package de.sneakpeek.adapter
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import de.sneakpeek.R
import de.sneakpeek.data.StudioPredictions
import de.sneakpeek.view.FastScroll
import java.text.Collator
import java.util.*
import kotlin.collections.HashMap
class StudiosAdapter(private var studios: List<StudioPredictions>) : FastScroll.FastScrollRecyclerViewInterface,
RecyclerView.Adapter<StudiosAdapter.MovieViewHolder>() {
private var mMapIndex: HashMap<Char, Int> = HashMap()
override fun getMapIndex(): HashMap<Char, Int> = mMapIndex
private fun calculateIndexesForName(items: List<String>): HashMap<Char, Int> {
val indexMap = LinkedHashMap<Char, Int>()
items.map { it[0] }.mapIndexed { index, character ->
if (!indexMap.containsKey(character)) {
indexMap.put(character, index)
} }
return indexMap
}
fun addAll(studios: List<StudioPredictions>) {
val collator = Collator.getInstance(Locale.GERMAN)
collator.strength = Collator.SECONDARY // a == A, a < Ä
this.studios = studios.sortedWith(kotlin.Comparator { studio1, studio2 -> collator.compare(studio1.studioTitle, studio2.studioTitle) })
this.mMapIndex = calculateIndexesForName(this.studios.map { it.studioTitle.capitalize() })
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.layout_studio_list_element, parent, false)
return MovieViewHolder(itemView)
}
override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
val studioPrediction = studios[position]
holder.studios.text = studioPrediction.studioTitle
holder.title.text = TextUtils.join("\n", studioPrediction.movies)
}
override fun getItemCount(): Int {
return studios.size
}
class MovieViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var title: TextView = itemView.findViewById(R.id.studio_list_item_title) as TextView
var studios: TextView = itemView.findViewById(R.id.studio_list_item_studio) as TextView
}
}
| mit | 01b4cec5c3149304fc9ace978281948f | 35.661538 | 143 | 0.720101 | 4.340619 | false | false | false | false |
Kotlin/kotlin-koans | src/i_introduction/_3_Default_Arguments/n03DefaultArguments.kt | 2 | 839 | package i_introduction._3_Default_Arguments
import util.TODO
import util.doc2
fun todoTask3(): Nothing = TODO(
"""
Task 3.
Several overloaded 'foo' functions in the class 'JavaCode3' can be replaced with one function in Kotlin.
Change the declaration of the function 'foo' in a way that makes the code using 'foo' compile.
You have to add 'foo' parameters and implement its body.
Uncomment the commented code and make it compile.
""",
documentation = doc2(),
references = { name: String -> JavaCode3().foo(name); foo(name) })
fun foo(name: String): String = todoTask3()
fun task3(): String {
todoTask3()
// return (foo("a") +
// foo("b", number = 1) +
// foo("c", toUpperCase = true) +
// foo(name = "d", number = 2, toUpperCase = true))
} | mit | de22f22c8e0f5a4b58bd9a7b6d98c7d9 | 32.6 | 112 | 0.618594 | 3.884259 | false | false | false | false |
mibac138/ArgParser | example/command-system/src/example/cmd/HelpCommand.kt | 1 | 1237 | package example.cmd
import com.github.mibac138.argparser.binder.MethodBinder
import com.github.mibac138.argparser.parser.Parser
import com.github.mibac138.argparser.reader.ArgumentReader
import com.github.mibac138.argparser.reader.readUntilChar
import com.github.mibac138.argparser.syntax.SyntaxElement
/**
* Created by mibac138 on 09-07-2017.
*/
class HelpCommand(registry: CommandRegistry) : BoundCommand() {
override val name = "help"
override val description = "I'm here to help you. Type \"help <command>\" to get any command's description"
override val parser = CommandParser(registry)
override val method = MethodBinder.bindMethod(this::printHelp)
fun printHelp(cmd: Command? = null) {
if (cmd == null)
println("To get help for a command type \"help <command>\"")
else {
println("Help for command '${cmd.name}'")
println(cmd.description)
}
}
}
class CommandParser(private val registry: CommandRegistry) : Parser {
override val supportedTypes: Set<Class<*>> = setOf(Command::class.java)
override fun parse(input: ArgumentReader, syntax: SyntaxElement): Command? {
return registry.getCommand(input.readUntilChar(' '))
}
} | mit | 1c4b7d438979221589f4d2746637c8dd | 35.411765 | 111 | 0.707357 | 4.096026 | false | false | false | false |
JavaProphet/JASM | src/main/java/com/protryon/jasm/instruction/instructions/Tableswitch.kt | 1 | 2236 | package com.protryon.jasm.instruction.instructions
import com.protryon.jasm.Constant
import com.protryon.jasm.Method
import com.protryon.jasm.instruction.Instruction
import com.protryon.jasm.instruction.psuedoinstructions.Label
import com.shapesecurity.functional.F
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.IOException
import java.util.ArrayList
class Tableswitch : Instruction() {
var default: Label? = null
var low: Int = 0
var high: Int = 0
var offsets: Array<Label>? = null
override val isControl: Boolean
get() = true
override fun name(): String {
return "Tableswitch"
}
override fun opcode(): Int {
return 170
}
@Throws(IOException::class)
override fun read(wide: Boolean, constants: ArrayList<Constant<*>>, method: Method, labelMaker: (Int)->Label, pc: Int, inputStream: DataInputStream) {
val currentOffset = pc % 4
val toRead = 3 - currentOffset
inputStream.read(ByteArray(toRead)) // padding
default = labelMaker.invoke(pc + inputStream.readInt())
low = inputStream.readInt()
high = inputStream.readInt()
val count = high - low + 1
if (count < 0) {
throw UnsupportedOperationException("invalid tableswitch")
}
offsets = Array(count) {
labelMaker.invoke(pc + inputStream.readInt())
}
}
@Throws(IOException::class)
override fun write(wide: Boolean, out: DataOutputStream, labelIndexer: (Label)->Int, constantIndexer: (Constant<*>) -> Int, pc: Int) {
val currentOffset = pc % 4
val toWrite = 3 - currentOffset
out.write(ByteArray(toWrite))
out.writeInt(labelIndexer.invoke(default!!) - pc)
out.writeInt(low)
out.writeInt(high)
for (offset in offsets!!) {
out.writeInt(labelIndexer.invoke(offset) - pc)
}
}
override fun pushes(): Int {
return 0
}
override fun pops(): Int {
// index
return 1
}
override fun toString(): String {
return "Tableswitch"
}
override fun fromString(str: String): Instruction {
error("unsupported")
}
}
| gpl-3.0 | 1ef901cb7841ea9d1dfa137ef2225fa7 | 27.316456 | 154 | 0.634168 | 4.401575 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/talk/TalkReplyViewModel.kt | 1 | 1708 | package org.wikipedia.talk
import android.os.Bundle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.*
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.discussiontools.ThreadItem
import org.wikipedia.page.PageTitle
import org.wikipedia.util.Resource
import org.wikipedia.util.SingleLiveData
class TalkReplyViewModel(bundle: Bundle) : ViewModel() {
val pageTitle = bundle.getParcelable<PageTitle>(TalkReplyActivity.EXTRA_PAGE_TITLE)!!
val topic = bundle.getParcelable<ThreadItem>(TalkReplyActivity.EXTRA_TOPIC)
val isNewTopic = topic == null
val postReplyData = SingleLiveData<Resource<Long>>()
fun postReply(subject: String, body: String) {
viewModelScope.launch(CoroutineExceptionHandler { _, throwable ->
postReplyData.postValue(Resource.Error(throwable))
}) {
val token = ServiceFactory.get(pageTitle.wikiSite).getToken().query?.csrfToken()!!
val response = if (topic != null) {
ServiceFactory.get(pageTitle.wikiSite).postTalkPageTopicReply(pageTitle.prefixedText, topic.id, body, token)
} else {
ServiceFactory.get(pageTitle.wikiSite).postTalkPageTopic(pageTitle.prefixedText, subject, body, token)
}
postReplyData.postValue(Resource.Success(response.result!!.newRevId))
}
}
class Factory(val bundle: Bundle) : ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return TalkReplyViewModel(bundle) as T
}
}
}
| apache-2.0 | 14740342a91b91d239138dbf0f9e7aa9 | 40.658537 | 124 | 0.716042 | 4.603774 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/activity/UserSelectorActivity.kt | 1 | 7009 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.activity
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.LoaderManager
import android.support.v4.content.Loader
import android.text.TextUtils.isEmpty
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import android.widget.ListView
import kotlinx.android.synthetic.main.activity_user_selector.*
import kotlinx.android.synthetic.main.layout_list_with_empty_view.*
import org.mariotaku.ktextension.Bundle
import org.mariotaku.ktextension.isNotNullOrEmpty
import org.mariotaku.ktextension.set
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.adapter.SimpleParcelableUsersAdapter
import de.vanita5.twittnuker.app.TwittnukerApplication
import de.vanita5.twittnuker.constant.IntentConstants.*
import de.vanita5.twittnuker.loader.CacheUserSearchLoader
import de.vanita5.twittnuker.model.ParcelableUser
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.util.EditTextEnterHandler
import de.vanita5.twittnuker.util.ParseUtils
import de.vanita5.twittnuker.util.view.SimpleTextWatcher
class UserSelectorActivity : BaseActivity(), OnItemClickListener, LoaderManager.LoaderCallbacks<List<ParcelableUser>> {
private lateinit var adapter: SimpleParcelableUsersAdapter
private val accountKey: UserKey?
get() = intent.getParcelableExtra<UserKey>(EXTRA_ACCOUNT_KEY)
private var loaderInitialized: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val accountKey = this.accountKey ?: run {
finish()
return
}
setContentView(R.layout.activity_user_selector)
val enterHandler = EditTextEnterHandler.attach(editScreenName, object : EditTextEnterHandler.EnterListener {
override fun onHitEnter(): Boolean {
val screenName = ParseUtils.parseString(editScreenName.text)
searchUser(accountKey, screenName, false)
return true
}
override fun shouldCallListener(): Boolean {
return true
}
}, true)
enterHandler.addTextChangedListener(object : SimpleTextWatcher {
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
searchUser(accountKey, s.toString(), true)
}
})
screenNameConfirm.setOnClickListener {
val screenName = ParseUtils.parseString(editScreenName.text)
searchUser(accountKey, screenName, false)
}
if (savedInstanceState == null) {
editScreenName.setText(intent.getStringExtra(EXTRA_SCREEN_NAME))
}
adapter = SimpleParcelableUsersAdapter(this, requestManager = requestManager)
listView.adapter = adapter
listView.onItemClickListener = this
showSearchHint()
}
override fun onItemClick(view: AdapterView<*>, child: View, position: Int, id: Long) {
val list = view as ListView
val user = adapter.getItem(position - list.headerViewsCount) ?: return
val data = Intent()
data.setExtrasClassLoader(TwittnukerApplication::class.java.classLoader)
data.putExtra(EXTRA_USER, user)
data.putExtra(EXTRA_EXTRAS, intent.getBundleExtra(EXTRA_EXTRAS))
setResult(Activity.RESULT_OK, data)
finish()
}
override fun onCreateLoader(id: Int, args: Bundle): Loader<List<ParcelableUser>> {
val accountKey = args.getParcelable<UserKey>(EXTRA_ACCOUNT_KEY)
val query = args.getString(EXTRA_QUERY)
val fromCache = args.getBoolean(EXTRA_FROM_CACHE)
if (!fromCache) {
showProgress()
}
return CacheUserSearchLoader(this, accountKey, query, !fromCache, true, true)
}
override fun onLoaderReset(loader: Loader<List<ParcelableUser>>) {
adapter.setData(null, true)
}
override fun onLoadFinished(loader: Loader<List<ParcelableUser>>, data: List<ParcelableUser>?) {
progressContainer.visibility = View.GONE
listContainer.visibility = View.VISIBLE
adapter.setData(data, true)
loader as CacheUserSearchLoader
if (data.isNotNullOrEmpty()) {
showList()
} else if (loader.query.isEmpty()) {
showSearchHint()
} else {
showNotFound()
}
}
private fun searchUser(accountKey: UserKey, query: String, fromCache: Boolean) {
if (isEmpty(query)) {
showSearchHint()
return
}
val args = Bundle {
this[EXTRA_ACCOUNT_KEY] = accountKey
this[EXTRA_QUERY] = query
this[EXTRA_FROM_CACHE] = fromCache
}
if (loaderInitialized) {
supportLoaderManager.initLoader(0, args, this)
loaderInitialized = true
} else {
supportLoaderManager.restartLoader(0, args, this)
}
}
private fun showProgress() {
progressContainer.visibility = View.VISIBLE
listContainer.visibility = View.GONE
}
private fun showSearchHint() {
progressContainer.visibility = View.GONE
listContainer.visibility = View.VISIBLE
emptyView.visibility = View.VISIBLE
listView.visibility = View.GONE
emptyIcon.setImageResource(R.drawable.ic_info_search)
emptyText.text = getText(R.string.search_hint_users)
}
private fun showNotFound() {
progressContainer.visibility = View.GONE
listContainer.visibility = View.VISIBLE
emptyView.visibility = View.VISIBLE
listView.visibility = View.GONE
emptyIcon.setImageResource(R.drawable.ic_info_search)
emptyText.text = getText(R.string.search_hint_users)
}
private fun showList() {
progressContainer.visibility = View.GONE
listContainer.visibility = View.VISIBLE
listView.visibility = View.VISIBLE
emptyView.visibility = View.GONE
}
} | gpl-3.0 | 76265e2a89d3e3b31bba917cfdcc0518 | 36.287234 | 119 | 0.688829 | 4.666445 | false | false | false | false |
06needhamt/LINQ-For-Java | src/linq/lamdba/DefaultLambdaFunctions.kt | 1 | 9863 | /*
The MIT License (MIT)
Copyright (c) 2016 Tom Needham
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package linq.lamdba
import linq.lamdba.exceptions.DivisionByZeroException
/**
* Created by Tom Needham on 03/03/2016.
*/
open class DefaultLambdaFunctions {
companion object Functors {
@JvmStatic()
fun Test(i: Int) : Boolean {
return i == 10
}
@JvmStatic()
fun InRange(a: Int, b: Int) : Boolean{
return a <= b
}
@JvmStatic()
fun LessThan(a: Int, b: Int) : Boolean{
return a < b
}
@JvmStatic()
fun MoreThan(a: Int, b: Int) : Boolean{
return a > b
}
@JvmStatic()
fun LessThanOrEqual(a: Int, b: Int) : Boolean{
return a <= b
}
@JvmStatic()
fun MoreThanOrEqual(a: Int, b: Int) : Boolean{
return a >= b
}
@JvmStatic()
fun Equal(a: Int, b: Int) : Boolean{
return a == b
}
@JvmStatic()
fun NotEqual(a: Int, b: Int) : Boolean{
return a != b
}
@JvmStatic()
fun LeftShift(a: Int, b: Int) : Int{
return a.shl(b)
}
@JvmStatic()
fun SignedRightShift(a: Int, b: Int) : Int{
return a.shr(b)
}
@JvmStatic()
fun UnsignedShiftRight(a: Int, b: Int) : Int{
return a.ushr(b)
}
@JvmStatic()
fun Add(a: Int, b: Int) : Int{
return a + b
}
@JvmStatic()
fun Subtract(a: Int, b: Int) : Int{
return a - b
}
@JvmStatic()
fun Multiply(a: Int, b: Int) : Int{
return a * b
}
@JvmStatic()
fun Divide(a: Int, b: Int) : Int{
if(b == 0)
throw DivisionByZeroException();
return a / b
}
@JvmStatic()
fun And(a: Int, b: Int) : Int{
return a.and(b)
}
@JvmStatic()
fun Or(a: Int, b: Int) : Int{
return a.or(b)
}
@JvmStatic()
fun Mod(a: Int, b: Int) : Int{
return a.mod(b)
}
@JvmStatic()
fun Xor(a: Int, b: Int) : Int{
return a.xor(b)
}
@JvmStatic()
fun Pow(a: Int, b: Int) : Int{
return Math.pow(a.toDouble(),b.toDouble()).toInt()
}
@JvmStatic()
fun InRange(a: Short, b: Short) : Boolean{
return a <= b
}
@JvmStatic()
fun LessThan(a: Short, b: Short) : Boolean{
return a < b
}
@JvmStatic()
fun MoreThan(a: Short, b: Short) : Boolean{
return a > b
}
@JvmStatic()
fun LessThanOrEqual(a: Short, b: Short) : Boolean{
return a <= b
}
@JvmStatic()
fun MoreThanOrEqual(a: Short, b: Short) : Boolean{
return a >= b
}
@JvmStatic()
fun Equal(a: Short, b: Short) : Boolean{
return a == b
}
@JvmStatic()
fun NotEqual(a: Short, b: Short) : Boolean{
return a != b
}
@JvmStatic()
fun Add(a: Short, b: Short) : Short{
return (a + b).toShort()
}
@JvmStatic()
fun Subtract(a: Short, b: Short) : Short{
return (a - b).toShort()
}
@JvmStatic()
fun Multiply(a: Short, b: Short) : Short{
return (a * b).toShort()
}
@JvmStatic()
fun Divide(a: Short, b: Short) : Short{
if((b == 0.toShort()))
throw DivisionByZeroException();
return (a / b).toShort()
}
@JvmStatic()
fun Mod(a: Short, b: Short) : Short{
return (a.mod(b)).toShort()
}
@JvmStatic()
fun Pow(a: Short, b: Short) : Short{
return Math.pow(a.toDouble(),b.toDouble()).toShort()
}
@JvmStatic()
fun InRange(a: Long, b: Long) : Boolean{
return a <= b
}
@JvmStatic()
fun LessThan(a: Long, b: Long) : Boolean{
return a < b
}
@JvmStatic()
fun MoreThan(a: Long, b: Long) : Boolean{
return a > b
}
@JvmStatic()
fun LessThanOrEqual(a: Long, b: Long) : Boolean{
return a <= b
}
@JvmStatic()
fun MoreThanOrEqual(a: Long, b: Long) : Boolean{
return a >= b
}
@JvmStatic()
fun Equal(a: Long, b: Long) : Boolean{
return a == b
}
@JvmStatic()
fun NotEqual(a: Long, b: Long) : Boolean{
return a != b
}
@JvmStatic()
fun LeftShift(a: Long, b: Long) : Long{
return a.shl(b.toInt())
}
@JvmStatic()
fun SignedRightShift(a: Long, b: Long) : Long{
return a.shr(b.toInt())
}
@JvmStatic()
fun UnsignedShiftRight(a: Long, b: Long) : Long{
return a.ushr(b.toInt())
}
@JvmStatic()
fun Add(a: Long, b: Long) : Long{
return a + b
}
@JvmStatic()
fun Subtract(a: Long, b: Long) : Long{
return a - b
}
@JvmStatic()
fun Multiply(a: Long, b: Long) : Long{
return a * b
}
@JvmStatic()
fun Divide(a: Long, b: Long) : Long{
if(b == 0L)
throw DivisionByZeroException();
return a / b
}
@JvmStatic()
fun And(a: Long, b: Long) : Long{
return a.and(b)
}
@JvmStatic()
fun Or(a: Long, b: Long) : Long{
return a.or(b)
}
@JvmStatic()
fun Mod(a: Long, b: Long) : Long{
return a.mod(b)
}
@JvmStatic()
fun Xor(a: Long, b: Long) : Long{
return a.xor(b)
}
@JvmStatic()
fun Pow(a: Long, b: Long) : Long{
return Math.pow(a.toDouble(),b.toDouble()).toLong()
}
@JvmStatic()
fun InRange(a: Float, b: Float) : Boolean{
return a <= b
}
@JvmStatic()
fun LessThan(a: Float, b: Float) : Boolean{
return a < b
}
@JvmStatic()
fun MoreThan(a: Float, b: Float) : Boolean{
return a > b
}
@JvmStatic()
fun LessThanOrEqual(a: Float, b: Float) : Boolean{
return a <= b
}
@JvmStatic()
fun MoreThanOrEqual(a: Float, b: Float) : Boolean{
return a >= b
}
@JvmStatic()
fun Equal(a: Float, b: Float) : Boolean{
return a == b
}
@JvmStatic()
fun NotEqual(a: Float, b: Float) : Boolean{
return a != b
}
@JvmStatic()
fun Add(a: Float, b: Float) : Float{
return a + b
}
@JvmStatic()
fun Subtract(a: Float, b: Float) : Float{
return a - b
}
@JvmStatic()
fun Multiply(a: Float, b: Float) : Float{
return a * b
}
@JvmStatic()
fun Divide(a: Float, b: Float) : Float{
if(b == 0.0f)
throw DivisionByZeroException();
return a / b
}
@JvmStatic()
fun Mod(a: Float, b: Float) : Float{
return a.mod(b)
}
@JvmStatic()
fun Pow(a: Float, b: Float) : Float{
return Math.pow(a.toDouble(),b.toDouble()).toFloat()
}
@JvmStatic()
fun InRange(a: Double, b: Double) : Boolean{
return a <= b
}
@JvmStatic()
fun LessThan(a: Double, b: Double) : Boolean{
return a < b
}
@JvmStatic()
fun MoreThan(a: Double, b: Double) : Boolean{
return a > b
}
@JvmStatic()
fun LessThanOrEqual(a: Double, b: Double) : Boolean{
return a <= b
}
@JvmStatic()
fun MoreThanOrEqual(a: Double, b: Double) : Boolean{
return a >= b
}
@JvmStatic()
fun Equal(a: Double, b: Double) : Boolean{
return a == b
}
@JvmStatic()
fun NotEqual(a: Double, b: Double) : Boolean{
return a != b
}
@JvmStatic()
fun Add(a: Double, b: Double) : Double{
return a + b
}
@JvmStatic()
fun Subtract(a: Double, b: Double) : Double{
return a - b
}
@JvmStatic()
fun Multiply(a: Double, b: Double) : Double{
return a * b
}
@JvmStatic()
fun Divide(a: Double, b: Double) : Double{
if(b == 0.0)
throw DivisionByZeroException();
return a / b
}
@JvmStatic()
fun Mod(a: Double, b: Double) : Double{
return a.mod(b)
}
@JvmStatic()
fun Pow(a: Double, b: Double) : Double{
return Math.pow(a,b)
}
}
}
| mit | 609e788154a8cefd54ab35f05663a6dc | 26.170799 | 71 | 0.490216 | 3.845224 | false | false | false | false |
AndroidX/androidx | benchmark/benchmark-macro/src/androidTest/java/androidx/benchmark/macro/perfetto/PerfettoTraceProcessorTest.kt | 3 | 5372 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.benchmark.macro.perfetto
import androidx.benchmark.Shell
import androidx.benchmark.macro.createTempFileFromAsset
import androidx.benchmark.perfetto.PerfettoHelper.Companion.isAbiSupported
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import java.net.ConnectException
import java.net.HttpURLConnection
import java.net.URL
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeFalse
import org.junit.Assume.assumeTrue
import org.junit.Test
import org.junit.runner.RunWith
@SmallTest
@RunWith(AndroidJUnit4::class)
class PerfettoTraceProcessorTest {
@Test
fun shellPath() {
assumeTrue(isAbiSupported())
val shellPath = PerfettoTraceProcessor.shellPath
val out = Shell.executeScriptCaptureStdout("$shellPath --version")
assertTrue(
"expect to get Perfetto version string, saw: $out",
out.contains("Perfetto v")
)
}
@Test
fun getJsonMetrics_tracePathWithSpaces() {
assumeTrue(isAbiSupported())
assertFailsWith<IllegalArgumentException> {
PerfettoTraceProcessor.runServer("/a b") { }
}
}
@Test
fun getJsonMetrics_metricWithSpaces() {
assumeTrue(isAbiSupported())
assertFailsWith<IllegalArgumentException> {
PerfettoTraceProcessor.runServer(
createTempFileFromAsset(
"api31_startup_cold",
".perfetto-trace"
).absolutePath
) {
getTraceMetrics("a b")
}
}
}
@Test
fun validateAbiNotSupportedBehavior() {
assumeFalse(isAbiSupported())
assertFailsWith<IllegalStateException> {
PerfettoTraceProcessor.shellPath
}
assertFailsWith<IllegalStateException> {
PerfettoTraceProcessor.runServer(
createTempFileFromAsset(
"api31_startup_cold",
".perfetto-trace"
).absolutePath
) {
getTraceMetrics("ignored_metric")
}
}
}
@Test
fun querySlices() {
// check known slice content is queryable
assumeTrue(isAbiSupported())
val traceFile = createTempFileFromAsset("api31_startup_cold", ".perfetto-trace")
PerfettoTraceProcessor.runServer(traceFile.absolutePath) {
assertEquals(
expected = listOf(
Slice(
name = "activityStart",
ts = 186975009436431,
dur = 29580628
)
),
actual = querySlices("activityStart")
)
assertEquals(
expected = listOf(
Slice(
name = "activityStart",
ts = 186975009436431,
dur = 29580628
),
Slice(
name = "activityResume",
ts = 186975039764298,
dur = 6570418
)
),
actual = querySlices("activityStart", "activityResume")
.sortedBy { it.ts }
)
}
}
@Test
fun validateTraceProcessorBinariesExist() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val suffixes = listOf("aarch64")
val entries = suffixes.map { "trace_processor_shell_$it" }.toSet()
val assets = context.assets.list("") ?: emptyArray()
assertTrue(
"Expected to find $entries",
assets.toSet().containsAll(entries)
)
}
@Test
fun runServerShouldHandleStartAndStopServer() {
assumeTrue(isAbiSupported())
// This method will return true if the server status endpoint returns 200 (that is also
// the only status code being returned).
fun isRunning(): Boolean = try {
val url = URL("http://localhost:${PerfettoTraceProcessor.PORT}/")
with(url.openConnection() as HttpURLConnection) {
return@with responseCode == 200
}
} catch (e: ConnectException) {
false
}
// Check server is not running
assertTrue(!isRunning())
PerfettoTraceProcessor.runServer {
// Check server is running
assertTrue(isRunning())
}
// Check server is not running
assertTrue(!isRunning())
}
} | apache-2.0 | c6f2a89489f2f9c73c02846c81bd4704 | 30.982143 | 95 | 0.592889 | 5.30306 | false | true | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/refactoring/convertStruct/RsConvertToTupleProcessor.kt | 3 | 6194 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring.convertStruct
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.usageView.BaseUsageViewDescriptor
import com.intellij.usageView.UsageInfo
import com.intellij.usageView.UsageViewDescriptor
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.RsElementTypes.COMMA
import org.rust.lang.core.psi.ext.*
class RsConvertToTupleProcessor(
project: Project,
val element: RsFieldsOwner,
private val convertUsages: Boolean = true
) : BaseRefactoringProcessor(project) {
private val rsPsiFactory = RsPsiFactory(project)
private val fieldDeclList = element.blockFields!!.namedFieldDeclList
override fun findUsages(): Array<UsageInfo> {
if (!convertUsages) return arrayOf()
var usages = ReferencesSearch
.search(element)
.asSequence()
.map { UsageInfo(it) }
usages += fieldDeclList
.mapIndexed { index, rsNamedFieldDecl ->
ProgressManager.checkCanceled()
ReferencesSearch
.search(rsNamedFieldDecl)
// Other references will be handled from main struct usages
.filter { it.element.parent is RsDotExpr }
.map { MyUsageInfo(it, index) }
}.flatten()
return usages
.toList()
.toTypedArray()
}
private class MyUsageInfo(psiReference: PsiReference, val position: Int) : UsageInfo(psiReference)
override fun performRefactoring(usages: Array<out UsageInfo>) {
for (usage in usages) {
val element = usage.element ?: continue
when (val usageParent = element.parent) {
is RsDotExpr ->
usage.element!!.replace(
rsPsiFactory
.createExpression("a.${(usage as MyUsageInfo).position}")
.descendantOfTypeStrict<RsFieldLookup>()!!
)
is RsPatStruct -> {
val patternFieldMap = usageParent.patFieldList
.map { it.kind }
.associate { kind ->
when (kind) {
is RsPatFieldKind.Full -> kind.fieldName to kind.pat.text
is RsPatFieldKind.Shorthand -> kind.fieldName to kind.binding.text
}
}
val text = "let ${usageParent.path.text}" +
fieldDeclList.joinToString(", ", "(", ") = 0;") {
patternFieldMap[it.identifier.text] ?: "_ "
}
val patternPsiElement = rsPsiFactory
.createStatement(text)
.descendantOfTypeStrict<RsPatTupleStruct>()!!
usageParent.replace(patternPsiElement)
}
is RsStructLiteral -> {
if (usageParent.structLiteralBody.dotdot != null) {
val text = "let a = ${usageParent.path.text}{" +
usageParent.structLiteralBody.structLiteralFieldList.joinToString(",") {
"${fieldDeclList.indexOfFirst { inner -> inner.identifier.textMatches(it.identifier!!) }}:${
it.expr?.text
?: it.identifier!!.text
}"
} + ", ..${usageParent.structLiteralBody.expr!!.text}};"
val newElement = rsPsiFactory
.createStatement(text)
.descendantOfTypeStrict<RsStructLiteral>()!!
usageParent.replace(newElement)
} else {
//map to restore order of fields
val valuesMap = usageParent.structLiteralBody.structLiteralFieldList
.associate { it.identifier!!.text to (it.expr?.text ?: it.identifier!!.text) }
val text = "let a = ${usageParent.path.text}" +
fieldDeclList.joinToString(", ", "(", ");") { valuesMap[it.identifier.text] ?: "_ " }
val newElement = rsPsiFactory
.createStatement(text)
.descendantOfTypeStrict<RsCallExpr>()!!
usageParent.replace(newElement)
}
}
}
}
val types = fieldDeclList
.mapNotNull { "${it.text.substring(0, it.identifier.startOffsetInParent)}${it.typeReference?.text}" }
.joinToString(",", "(", ")")
val newTuplePsiElement = rsPsiFactory.createStruct("struct A$types;")
val blockFields = element.blockFields ?: return
val tupleFields = newTuplePsiElement.tupleFields ?: return
val whereClause = (element as? RsStructItem)?.whereClause
if (whereClause == null) {
blockFields.replace(tupleFields)
} else {
element.addAfter(tupleFields, whereClause.getPrevNonWhitespaceSibling())
(blockFields.prevSibling as? PsiWhiteSpace)?.delete()
blockFields.delete()
whereClause.lastChild.takeIf { it.elementType == COMMA }?.delete()
}
if (element is RsStructItem) element.addAfter(rsPsiFactory.createSemicolon(), element.lastChild)
}
override fun getCommandName(): String = "Converting ${element.name} to tuple"
override fun createUsageViewDescriptor(usages: Array<UsageInfo>): UsageViewDescriptor =
BaseUsageViewDescriptor(element)
override fun getRefactoringId(): String = "refactoring.convertToTuple"
}
| mit | ff9e2df89bbaab6d00eb3a88cda25665 | 42.314685 | 124 | 0.560058 | 5.520499 | false | false | false | false |
ryan652/EasyCrypt | appKotlin/src/main/java/com/pvryan/easycryptsample/action/FragmentAsymmetricFile.kt | 1 | 15182 | /*
* Copyright 2018 Priyank Vasa
* 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.pvryan.easycryptsample.action
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.pvryan.easycrypt.ECKeys
import com.pvryan.easycrypt.ECResultListener
import com.pvryan.easycrypt.asymmetric.ECAsymmetric
import com.pvryan.easycrypt.asymmetric.ECRSAKeyPairListener
import com.pvryan.easycrypt.asymmetric.ECVerifiedListener
import com.pvryan.easycrypt.symmetric.ECSymmetric
import com.pvryan.easycryptsample.R
import com.pvryan.easycryptsample.extensions.*
import com.transitionseverywhere.TransitionManager
import kotlinx.android.synthetic.main.fragment_asymmetric_file.*
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.support.v4.onUiThread
import java.io.File
import java.security.KeyPair
import java.security.interfaces.RSAPrivateKey
import java.security.interfaces.RSAPublicKey
import java.security.spec.InvalidKeySpecException
@SuppressLint("SetTextI18n")
class FragmentAsymmetricFile : Fragment(), AnkoLogger, ECResultListener {
private val _rCEncrypt = 2
private val _rCDecrypt = 3
private val _rCSign = 4
private val _rCVerify = 5
private val eCryptAsymmetric = ECAsymmetric()
private val eCryptSymmetric = ECSymmetric()
private val eCryptKeys = ECKeys()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_asymmetric_file, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val clipboard = activity?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
rlPublicKeyTitleF.setOnLongClickListener {
val data = ClipData.newPlainText("result", tvPublicKeyF.text)
clipboard.primaryClip = data
view.snackLong("Public key copied to clipboard")
true
}
rlPrivateKeyTitleF.setOnLongClickListener {
val data = ClipData.newPlainText("result", tvPrivateKeyF.text)
clipboard.primaryClip = data
view.snackLong("Secure private key copied to clipboard")
true
}
buttonSelectEncryptF.setOnClickListener {
if (edPasswordF.text.toString() == "") {
view.snackLong("Password cannot be empty")
return@setOnClickListener
}
selectFile(_rCEncrypt)
}
buttonSelectDecryptF.setOnClickListener {
if (edPasswordF.text.toString() == "") {
view.snackLong("Password cannot be empty")
return@setOnClickListener
}
if (tvPrivateKeyF.text == "") {
view.snackLong("Encrypt first to generate private key")
return@setOnClickListener
}
selectFile(_rCDecrypt)
}
buttonSignF.setOnClickListener {
if (edPasswordF.text.toString() == "") {
view.snackLong("Password cannot be empty")
return@setOnClickListener
}
selectFile(_rCSign)
}
buttonVerifyF.setOnClickListener {
if (tvPublicKeyF.text == "") {
view.snackLong("Sign first to generate public key")
return@setOnClickListener
}
selectFile(_rCVerify)
}
rlPrivateKeyTitleF.setOnClickListener {
if (tvPrivateKeyF.visibility == View.GONE) {
bExpandCollapsePrivateF.animate().rotation(180f).setDuration(200).start()
tvPrivateKeyF.show()
} else {
bExpandCollapsePrivateF.animate().rotation(0f).setDuration(200).start()
tvPrivateKeyF.gone()
}
TransitionManager.beginDelayedTransition(rlPrivateKeyTitleF.parent as ViewGroup)
}
rlPublicKeyTitleF.setOnClickListener {
if (tvPublicKeyF.visibility == View.GONE) {
bExpandCollapsePublicF.animate().rotation(180f).setDuration(200).start()
tvPublicKeyF.show()
} else {
bExpandCollapsePublicF.animate().rotation(0f).setDuration(200).start()
tvPublicKeyF.gone()
}
TransitionManager.beginDelayedTransition(rlPublicKeyTitleF.parent as ViewGroup)
}
}
private fun selectFile(requestCode: Int) {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "*/*"
startActivityForResult(intent, requestCode)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK) {
val fis = context?.contentResolver?.openInputStream(data?.data)
val password = edPasswordF.text.toString()
when (requestCode) {
_rCEncrypt -> {
progressBarF.show()
tvStatus.text = getString(R.string.tv_status_encrypting)
eCryptKeys.genRSAKeyPair(object : ECRSAKeyPairListener {
override fun onGenerated(keyPair: KeyPair) {
val publicKey = keyPair.public as RSAPublicKey
onUiThread { tvPublicKeyF.text = publicKey.encoded.toBase64String() }
val privateKey = keyPair.private as RSAPrivateKey
// Symmetrically encrypt private key
eCryptSymmetric.encrypt(privateKey.encoded.toBase64String(),
password, object : ECResultListener {
override fun <T> onSuccess(result: T) {
onUiThread { tvPrivateKeyF.text = result as String }
eCryptAsymmetric.encrypt(fis, publicKey,
this@FragmentAsymmetricFile)
}
override fun onFailure(message: String, e: Exception) {
onUiThread {
progressBarF.hide()
tvStatus.text = getString(R.string.tv_status_idle)
tvPrivateKeyF.text = "Error while encrypting private key. $message"
container.snackLong("Error while encrypting private key. $message")
}
}
})
}
override fun onFailure(message: String, e: Exception) {
onUiThread {
progressBarF.hide()
tvStatus.text = getString(R.string.tv_status_idle)
container.snackLong("Error: $message")
}
}
})
}
_rCDecrypt -> {
tvStatus.text = getString(R.string.tv_status_decrypting)
// Decrypt private key
eCryptSymmetric.decrypt(tvPrivateKeyF.text, password, object : ECResultListener {
override fun <T> onSuccess(result: T) {
try {
val privateKey = eCryptKeys.genRSAPrivateKeyFromBase64(result as String)
// Decrypt user file
eCryptAsymmetric.decrypt(fis, privateKey, this@FragmentAsymmetricFile)
progressBarF.show()
} catch (e: IllegalArgumentException) {
onFailure("Not a valid base64 string", e)
} catch (e: InvalidKeySpecException) {
onFailure("Not a valid private key", e)
}
}
override fun onFailure(message: String, e: Exception) {
onUiThread {
tvStatus.text = getString(R.string.tv_status_idle)
container.snackLong("Error while decrypting private key. $message")
}
}
})
}
_rCSign -> {
tvStatus.text = getString(R.string.tv_status_signing)
progressBarF.show()
val sigFile = File(Environment.getExternalStorageDirectory(),
"ECryptSample/sample.sig")
if (sigFile.exists()) sigFile.delete()
eCryptKeys.genRSAKeyPair(object : ECRSAKeyPairListener {
override fun onGenerated(keyPair: KeyPair) {
onUiThread {
tvPublicKeyF.text = (keyPair.public as RSAPublicKey).encoded.toBase64String()
}
val privateKey = keyPair.private as RSAPrivateKey
// Encrypt private key
eCryptSymmetric.encrypt(privateKey.encoded.toBase64String(),
password, object : ECResultListener {
override fun <T> onSuccess(result: T) {
eCryptAsymmetric.sign(fis,
privateKey,
this@FragmentAsymmetricFile,
sigFile)
onUiThread { tvPrivateKeyF.text = result as String }
}
override fun onFailure(message: String, e: Exception) {
onUiThread {
progressBarF.hide()
tvStatus.text = getString(R.string.tv_status_idle)
tvPrivateKeyF.text = "Error while encrypting private key. $message"
container.snackLong("Error while encrypting private key. $message")
}
}
})
}
override fun onFailure(message: String, e: Exception) {
onUiThread {
progressBarF.hide()
tvStatus.text = getString(R.string.tv_status_idle)
container.snackLong("Failed to generate RSA key pair. Try again.")
}
}
})
}
_rCVerify -> {
progressBarF.show()
tvStatus.text = getString(R.string.tv_status_verifying)
try {
val publicKey = eCryptKeys.genRSAPublicKeyFromBase64(tvPublicKeyF.text.toString())
eCryptAsymmetric.verify(fis, publicKey,
File(Environment.getExternalStorageDirectory(), "ECryptSample/sample.sig"),
object : ECVerifiedListener {
override fun onSuccess(verified: Boolean) {
onUiThread {
progressBarF.hide()
if (verified) tvResultF.text = getString(R.string.msg_valid)
else tvResultF.text = getString(R.string.msg_invalid)
tvStatus.text = getString(R.string.tv_status_idle)
}
}
override fun onFailure(message: String, e: Exception) {
onUiThread {
progressBarF.hide()
tvStatus.text = getString(R.string.tv_status_idle)
container.snackLong("Error: $message")
}
}
})
} catch (e: IllegalArgumentException) {
container.snackLong("Not a valid base64 string")
tvStatus.text = getString(R.string.tv_status_idle)
} catch (e: InvalidKeySpecException) {
container.snackLong("Not a valid private key")
tvStatus.text = getString(R.string.tv_status_idle)
}
}
}
}
}
private var maxSet = false
override fun onProgress(newBytes: Int, bytesProcessed: Long, totalBytes: Long) {
if (totalBytes > -1) {
onUiThread {
if (!maxSet) {
progressBarF.isIndeterminate = false
progressBarF.max = (totalBytes / 1024).toInt()
maxSet = true
}
progressBarF.progress = (bytesProcessed / 1024).toInt()
}
}
}
override fun <T> onSuccess(result: T) {
onUiThread {
progressBarF.hide()
tvStatus.text = getString(R.string.tv_status_idle)
tvResultF.text = resources.getString(
R.string.success_result_to_file,
(result as File).absolutePath)
}
}
override fun onFailure(message: String, e: Exception) {
onUiThread {
progressBarF.hide()
tvStatus.text = getString(R.string.tv_status_idle)
container.snackLong("Error: $message")
}
}
companion object {
fun newInstance(): Fragment = FragmentAsymmetricFile()
}
}
| apache-2.0 | 30c091b19c0dcbb00012072a4d182f60 | 43.784661 | 109 | 0.517652 | 5.650167 | false | false | false | false |
robfletcher/keiko | keiko-test-common/src/main/kotlin/com/netflix/spinnaker/assertj/assertj.kt | 1 | 2322 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.assertj
import org.assertj.core.api.AbstractAssert
import org.assertj.core.api.Assert
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.IntegerAssert
import org.assertj.core.api.IterableAssert
import org.assertj.core.api.MapAssert
import org.assertj.core.api.SoftAssertions
import java.lang.reflect.Field
import kotlin.reflect.KProperty1
private val actualField: Field = AbstractAssert::class.java
.getDeclaredField("actual")
.apply { isAccessible = true }
@Suppress("UNCHECKED_CAST")
private val <ACTUAL>
Assert<*, ACTUAL>.actual: ACTUAL
get() = actualField.get(this) as ACTUAL
/**
* Alias for [Assert#isInstanceOf] using Kotlin's reified generics.
*/
inline fun <reified T> Assert<*, *>.isA(): Assert<*, *> =
isInstanceOf(T::class.java)
fun Assert<*, *>.asInteger() = run {
isA<Int>()
IntegerAssert(actual as Int)
}
fun Assert<*, *>.asMap() = run {
isA<Map<*, *>>()
MapAssert(actual as Map<Any, Any>)
}
fun Assert<*, *>.asIterable() = run {
isA<Iterable<*>>()
IterableAssert(actual as Iterable<Any>)
}
// fun <SELF : Assert<*, ACTUAL>, ACTUAL, PROP>
// SELF.get(
// getter: KFunction1<ACTUAL, PROP>
// ): Assert<*, PROP> =
// assertThat(getter.invoke(actual))
// .`as`(getter.name) as Assert<*, PROP>
fun <SELF : Assert<*, ACTUAL>, ACTUAL, PROP>
SELF.get(
property: KProperty1<ACTUAL, PROP>
): Assert<*, PROP> =
assertThat(property.get(actual))
.`as`(property.name) as Assert<*, PROP>
/**
* Basically the same as [SoftAssertions#assertSoftly] except [SoftAssertions]
* is the _receiver_ of [block] not a parameter to it.
*/
fun softly(block: SoftAssertions.() -> Unit) {
SoftAssertions.assertSoftly(block)
}
| apache-2.0 | 4e4829e3cd1fe57d59e71708a2587242 | 28.392405 | 78 | 0.709733 | 3.622465 | false | false | false | false |
androidx/androidx | room/room-compiler/src/test/test-data/kotlinCodeGen/collectionParameterAdapter_string.kt | 3 | 6524 | import android.database.Cursor
import androidx.room.RoomDatabase
import androidx.room.RoomSQLiteQuery
import androidx.room.RoomSQLiteQuery.Companion.acquire
import androidx.room.util.appendPlaceholders
import androidx.room.util.getColumnIndexOrThrow
import androidx.room.util.newStringBuilder
import androidx.room.util.query
import java.lang.Class
import java.lang.StringBuilder
import javax.`annotation`.processing.Generated
import kotlin.Int
import kotlin.String
import kotlin.Suppress
import kotlin.collections.List
import kotlin.collections.Set
import kotlin.jvm.JvmStatic
@Generated(value = ["androidx.room.RoomProcessor"])
@Suppress(names = ["UNCHECKED_CAST", "DEPRECATION"])
public class MyDao_Impl(
__db: RoomDatabase,
) : MyDao {
private val __db: RoomDatabase
init {
this.__db = __db
}
public override fun listOfString(arg: List<String>): MyEntity {
val _stringBuilder: StringBuilder = newStringBuilder()
_stringBuilder.append("SELECT * FROM MyEntity WHERE string IN (")
val _inputSize: Int = arg.size
appendPlaceholders(_stringBuilder, _inputSize)
_stringBuilder.append(")")
val _sql: String = _stringBuilder.toString()
val _argCount: Int = 0 + _inputSize
val _statement: RoomSQLiteQuery = acquire(_sql, _argCount)
var _argIndex: Int = 1
for (_item: String in arg) {
_statement.bindString(_argIndex, _item)
_argIndex++
}
__db.assertNotSuspendingTransaction()
val _cursor: Cursor = query(__db, _statement, false, null)
try {
val _cursorIndexOfString: Int = getColumnIndexOrThrow(_cursor, "string")
val _result: MyEntity
if (_cursor.moveToFirst()) {
val _tmpString: String
_tmpString = _cursor.getString(_cursorIndexOfString)
_result = MyEntity(_tmpString)
} else {
error("Cursor was empty, but expected a single item.")
}
return _result
} finally {
_cursor.close()
_statement.release()
}
}
public override fun nullableListOfString(arg: List<String>?): MyEntity {
val _stringBuilder: StringBuilder = newStringBuilder()
_stringBuilder.append("SELECT * FROM MyEntity WHERE string IN (")
val _inputSize: Int = if (arg == null) 1 else arg.size
appendPlaceholders(_stringBuilder, _inputSize)
_stringBuilder.append(")")
val _sql: String = _stringBuilder.toString()
val _argCount: Int = 0 + _inputSize
val _statement: RoomSQLiteQuery = acquire(_sql, _argCount)
var _argIndex: Int = 1
if (arg == null) {
_statement.bindNull(_argIndex)
} else {
for (_item: String in arg) {
_statement.bindString(_argIndex, _item)
_argIndex++
}
}
__db.assertNotSuspendingTransaction()
val _cursor: Cursor = query(__db, _statement, false, null)
try {
val _cursorIndexOfString: Int = getColumnIndexOrThrow(_cursor, "string")
val _result: MyEntity
if (_cursor.moveToFirst()) {
val _tmpString: String
_tmpString = _cursor.getString(_cursorIndexOfString)
_result = MyEntity(_tmpString)
} else {
error("Cursor was empty, but expected a single item.")
}
return _result
} finally {
_cursor.close()
_statement.release()
}
}
public override fun listOfNullableString(arg: List<String?>): MyEntity {
val _stringBuilder: StringBuilder = newStringBuilder()
_stringBuilder.append("SELECT * FROM MyEntity WHERE string IN (")
val _inputSize: Int = arg.size
appendPlaceholders(_stringBuilder, _inputSize)
_stringBuilder.append(")")
val _sql: String = _stringBuilder.toString()
val _argCount: Int = 0 + _inputSize
val _statement: RoomSQLiteQuery = acquire(_sql, _argCount)
var _argIndex: Int = 1
for (_item: String? in arg) {
if (_item == null) {
_statement.bindNull(_argIndex)
} else {
_statement.bindString(_argIndex, _item)
}
_argIndex++
}
__db.assertNotSuspendingTransaction()
val _cursor: Cursor = query(__db, _statement, false, null)
try {
val _cursorIndexOfString: Int = getColumnIndexOrThrow(_cursor, "string")
val _result: MyEntity
if (_cursor.moveToFirst()) {
val _tmpString: String
_tmpString = _cursor.getString(_cursorIndexOfString)
_result = MyEntity(_tmpString)
} else {
error("Cursor was empty, but expected a single item.")
}
return _result
} finally {
_cursor.close()
_statement.release()
}
}
public override fun setOfString(arg: Set<String>): MyEntity {
val _stringBuilder: StringBuilder = newStringBuilder()
_stringBuilder.append("SELECT * FROM MyEntity WHERE string IN (")
val _inputSize: Int = arg.size
appendPlaceholders(_stringBuilder, _inputSize)
_stringBuilder.append(")")
val _sql: String = _stringBuilder.toString()
val _argCount: Int = 0 + _inputSize
val _statement: RoomSQLiteQuery = acquire(_sql, _argCount)
var _argIndex: Int = 1
for (_item: String in arg) {
_statement.bindString(_argIndex, _item)
_argIndex++
}
__db.assertNotSuspendingTransaction()
val _cursor: Cursor = query(__db, _statement, false, null)
try {
val _cursorIndexOfString: Int = getColumnIndexOrThrow(_cursor, "string")
val _result: MyEntity
if (_cursor.moveToFirst()) {
val _tmpString: String
_tmpString = _cursor.getString(_cursorIndexOfString)
_result = MyEntity(_tmpString)
} else {
error("Cursor was empty, but expected a single item.")
}
return _result
} finally {
_cursor.close()
_statement.release()
}
}
public companion object {
@JvmStatic
public fun getRequiredConverters(): List<Class<*>> = emptyList()
}
} | apache-2.0 | ff5df70d14d2b7ca0592f6a0cd7d7c60 | 36.716763 | 84 | 0.584457 | 4.854167 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/staggeredgrid/LazyStaggeredGridMeasureResult.kt | 3 | 5297 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.lazy.staggeredgrid
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
/**
* Information about layout state of individual item in lazy staggered grid.
* @see [LazyStaggeredGridLayoutInfo]
*/
@ExperimentalFoundationApi
sealed interface LazyStaggeredGridItemInfo {
/**
* Relative offset from the start of the staggered grid.
*/
val offset: IntOffset
/**
* Index of the item.
*/
val index: Int
/**
* Column (for vertical staggered grids) or row (for horizontal staggered grids) that the item
* is in.
*/
val lane: Int
/**
* Key of the item passed in [LazyStaggeredGridScope.items]
*/
val key: Any
/**
* Item size in pixels. If item contains multiple layouts, the size is calculated as a sum of
* their sizes.
*/
val size: IntSize
}
/**
* Information about layout state of lazy staggered grids.
* Can be retrieved from [LazyStaggeredGridState.layoutInfo].
*/
// todo(b/182882362): expose more information about layout state
@ExperimentalFoundationApi
sealed interface LazyStaggeredGridLayoutInfo {
/**
* Orientation of the staggered grid.
*/
val orientation: Orientation
/**
* The list of [LazyStaggeredGridItemInfo] per each visible item ordered by index.
*/
val visibleItemsInfo: List<LazyStaggeredGridItemInfo>
/**
* The total count of items passed to staggered grid.
*/
val totalItemsCount: Int
/**
* Layout viewport (content + content padding) size in pixels.
*/
val viewportSize: IntSize
/**
* The start offset of the layout's viewport in pixels. You can think of it as a minimum offset
* which would be visible. Can be negative if non-zero [beforeContentPadding]
* was applied as the content displayed in the content padding area is still visible.
*
* You can use it to understand what items from [visibleItemsInfo] are fully visible.
*/
val viewportStartOffset: Int
/**
* The end offset of the layout's viewport in pixels. You can think of it as a maximum offset
* which would be visible. It is the size of the lazy grid layout minus [beforeContentPadding].
*
* You can use it to understand what items from [visibleItemsInfo] are fully visible.
*/
val viewportEndOffset: Int
/**
* Content padding in pixels applied before the items in scroll direction.
*/
val beforeContentPadding: Int
/**
* Content padding in pixels applied after the items in scroll direction.
*/
val afterContentPadding: Int
}
@OptIn(ExperimentalFoundationApi::class)
internal fun LazyStaggeredGridLayoutInfo.findVisibleItem(
itemIndex: Int
): LazyStaggeredGridItemInfo? {
if (visibleItemsInfo.isEmpty()) {
return null
}
if (itemIndex !in visibleItemsInfo.first().index..visibleItemsInfo.last().index) {
return null
}
val index = visibleItemsInfo.binarySearch { it.index - itemIndex }
return visibleItemsInfo.getOrNull(index)
}
@OptIn(ExperimentalFoundationApi::class)
internal class LazyStaggeredGridMeasureResult(
val firstVisibleItemIndices: IntArray,
val firstVisibleItemScrollOffsets: IntArray,
val consumedScroll: Float,
val measureResult: MeasureResult,
val canScrollForward: Boolean,
val canScrollBackward: Boolean,
val isVertical: Boolean,
override val totalItemsCount: Int,
override val visibleItemsInfo: List<LazyStaggeredGridItemInfo>,
override val viewportSize: IntSize,
override val viewportStartOffset: Int,
override val viewportEndOffset: Int,
override val beforeContentPadding: Int,
override val afterContentPadding: Int
) : LazyStaggeredGridLayoutInfo, MeasureResult by measureResult {
override val orientation: Orientation =
if (isVertical) Orientation.Vertical else Orientation.Horizontal
}
@OptIn(ExperimentalFoundationApi::class)
internal object EmptyLazyStaggeredGridLayoutInfo : LazyStaggeredGridLayoutInfo {
override val visibleItemsInfo: List<LazyStaggeredGridItemInfo> = emptyList()
override val totalItemsCount: Int = 0
override val viewportSize: IntSize = IntSize.Zero
override val viewportStartOffset: Int = 0
override val viewportEndOffset: Int = 0
override val beforeContentPadding: Int = 0
override val afterContentPadding: Int = 0
override val orientation: Orientation = Orientation.Vertical
} | apache-2.0 | 56abeb6623e60914f2cafd77ae01d812 | 31.906832 | 99 | 0.72475 | 4.802357 | false | false | false | false |
sebasjm/deepdiff | src/main/kotlin/diff/CustomJson.kt | 1 | 2545 | package diff
import com.fasterxml.jackson.annotation.JsonAutoDetect
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.PropertyAccessor
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.*
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.ser.BeanSerializerBuilder
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier
import com.fasterxml.jackson.databind.ser.PropertyWriter
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import com.fasterxml.jackson.module.kotlin.KotlinModule
import diff.patch.Coordinate
import diff.patch.Patch
/**
* Created by sebasjm on 28/06/17.
*/
object CustomJson {
val writer: ObjectWriter
val niceWriter: ObjectWriter
val reader: ObjectMapper
init {
val mapper = ObjectMapper()
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE)
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS)
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
mapper.registerModule(KotlinModule())
val module = SimpleModule()
module.setSerializerModifier(object : BeanSerializerModifier() {
override fun updateBuilder(config: SerializationConfig?, beanDesc: BeanDescription?, builder: BeanSerializerBuilder): BeanSerializerBuilder {
builder.filterId = "filtered"
return super.updateBuilder(config, beanDesc, builder)
}
})
module.addSerializer(object: StdSerializer<Coordinate<*,*>>(Coordinate::class.java){
override fun serialize(value: Coordinate<*, *>?, gen: JsonGenerator?, provider: SerializerProvider?) {
gen?.writeString(value?.name)
}
})
mapper.registerModule(module)
val ignorableFieldNames = arrayOf("position")
val filters = SimpleFilterProvider()
.addFilter("filtered",SimpleBeanPropertyFilter.serializeAllExcept(*ignorableFieldNames))
writer = mapper
.setFilterProvider(filters)
.writer()
niceWriter = mapper
.setFilterProvider(filters)
.writerWithDefaultPrettyPrinter()
reader = mapper
}
}
| apache-2.0 | 64a67694230b4bead739f1ef62c59a84 | 35.357143 | 153 | 0.72888 | 4.951362 | false | true | false | false |
mantono/REST-in-Peace | src/main/kotlin/com.mantono.webserver/responseSender.kt | 1 | 1387 | package com.mantono.webserver
import com.mantono.webserver.rest.HeaderField
import com.mantono.webserver.rest.Response
import com.mantono.webserver.rest.ResponseCode
import java.io.PrintStream
import java.net.Socket
private const val EOL: String = "\r\n"
fun send(socket: Socket, response: Response): Int
{
val socketOut = socket.getOutputStream()
val streamOut = PrintStream(socketOut, true)
printResponse(streamOut, response)
streamOut.flush()
socketOut.flush()
val size = response.header[HeaderField.CONTENT_LENGTH]
return Integer.parseInt(size ?: "-1")
}
private fun printResponse(streamOut: PrintStream, response: Response)
{
streamOut.append(parseResponseCode(response.responseCode))
streamOut.append(parseHeader(response.header))
streamOut.append(response.body.toString())
streamOut.append(EOL)
}
private fun parseResponseCode(responseCode: ResponseCode): CharSequence
{
val responseCodeData = StringBuilder()
responseCodeData.append("HTTP/1.1 ")
responseCodeData.append("" + responseCode.code)
responseCodeData.append(" " + responseCode.description)
responseCodeData.append(EOL)
return responseCodeData
}
private fun parseHeader(header: ResponseHeader): CharSequence
{
val headerData = StringBuilder()
for ((field, value) in header.fields)
{
headerData.append(field.getName() + ": " + value + EOL)
}
headerData.append(EOL + EOL)
return headerData
} | mit | 12d10bdc3f9a844bd9065707bde0b795 | 27.326531 | 71 | 0.782264 | 3.529262 | false | false | false | false |
Sylvilagus/SylvaBBSClient | SylvaBBSClient/app/src/main/java/com/sylva/sylvabbsclient/api/IAnimationApi.kt | 1 | 547 | package com.sylva.sylvabbsclient.api
import android.view.View
/**
* Created by sylva on 2016/3/19.
*/
interface IAnimationApi {
fun zoomIn(target:View,interval:Int=500)
fun zoomOut(target:View,interval:Int=500)
fun slideFromLeft(target: View,interval: Int=500)
fun slideFromRight(target: View,interval: Int=500)
fun slideFromBottom(target: View,interval: Int=500)
fun slideFromTop(target: View,interval: Int=500)
fun rotate2DClockWise(target: View,angle:Int)
fun rotate2DAntiClockWise(target: View,angle: Int)
} | apache-2.0 | c1b2e69111c7b6a89e8b9980c992ef62 | 31.235294 | 55 | 0.744059 | 3.180233 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/GL15.kt | 1 | 12798 | /*
* 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 BUFFER_OBJECT_TARGETS =
"""
GL15#ARRAY_BUFFER GL15#ELEMENT_ARRAY_BUFFER GL21#PIXEL_PACK_BUFFER GL21#PIXEL_UNPACK_BUFFER GL30#TRANSFORM_FEEDBACK_BUFFER
GL31#UNIFORM_BUFFER GL31#TEXTURE_BUFFER GL31#COPY_READ_BUFFER GL31#COPY_WRITE_BUFFER GL40#DRAW_INDIRECT_BUFFER GL42#ATOMIC_COUNTER_BUFFER
GL43#DISPATCH_INDIRECT_BUFFER GL43#SHADER_STORAGE_BUFFER ARBIndirectParameters#PARAMETER_BUFFER_ARB
"""
val BUFFER_OBJECT_PARAMETERS =
"""
GL15#BUFFER_SIZE GL15#BUFFER_USAGE GL15#BUFFER_ACCESS GL15#BUFFER_MAPPED GL30#BUFFER_ACCESS_FLAGS GL30#BUFFER_MAP_LENGTH GL30#BUFFER_MAP_OFFSET
GL44#BUFFER_IMMUTABLE_STORAGE GL44#BUFFER_STORAGE_FLAGS
"""
val QUERY_TARGETS =
"""
GL15#SAMPLES_PASSED GL30#PRIMITIVES_GENERATED GL30#TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN GL33#TIME_ELAPSED GL33#TIMESTAMP
GL33#ANY_SAMPLES_PASSED GL43#ANY_SAMPLES_PASSED_CONSERVATIVE
"""
val GL15 = "GL15".nativeClassGL("GL15") {
documentation =
"""
The core OpenGL 1.5 functionality.
Extensions promoted to core in this release:
${ul(
registryLinkTo("ARB", "vertex_buffer_object"),
registryLinkTo("ARB", "occlusion_query"),
registryLinkTo("EXT", "shadow_funcs")
)}
"""
IntConstant(
"New token names.",
"FOG_COORD_SRC"..0x8450,
"FOG_COORD"..0x8451,
"CURRENT_FOG_COORD"..0x8453,
"FOG_COORD_ARRAY_TYPE"..0x8454,
"FOG_COORD_ARRAY_STRIDE"..0x8455,
"FOG_COORD_ARRAY_POINTER"..0x8456,
"FOG_COORD_ARRAY"..0x8457,
"FOG_COORD_ARRAY_BUFFER_BINDING"..0x889D,
"SRC0_RGB"..0x8580,
"SRC1_RGB"..0x8581,
"SRC2_RGB"..0x8582,
"SRC0_ALPHA"..0x8588,
"SRC1_ALPHA"..0x8589,
"SRC2_ALPHA"..0x858A
)
// ARB_vertex_buffer_object
IntConstant(
"""
Accepted by the {@code target} parameters of BindBuffer, BufferData, BufferSubData, MapBuffer, UnmapBuffer, GetBufferSubData,
GetBufferParameteriv, and GetBufferPointerv.
""",
"ARRAY_BUFFER"..0x8892,
"ELEMENT_ARRAY_BUFFER"..0x8893
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.",
"ARRAY_BUFFER_BINDING"..0x8894,
"ELEMENT_ARRAY_BUFFER_BINDING"..0x8895,
"VERTEX_ARRAY_BUFFER_BINDING"..0x8896,
"NORMAL_ARRAY_BUFFER_BINDING"..0x8897,
"COLOR_ARRAY_BUFFER_BINDING"..0x8898,
"INDEX_ARRAY_BUFFER_BINDING"..0x8899,
"TEXTURE_COORD_ARRAY_BUFFER_BINDING"..0x889A,
"EDGE_FLAG_ARRAY_BUFFER_BINDING"..0x889B,
"SECONDARY_COLOR_ARRAY_BUFFER_BINDING"..0x889C,
"FOG_COORDINATE_ARRAY_BUFFER_BINDING"..0x889D,
"WEIGHT_ARRAY_BUFFER_BINDING"..0x889E
)
IntConstant(
"Accepted by the {@code pname} parameter of GetVertexAttribiv.",
"VERTEX_ATTRIB_ARRAY_BUFFER_BINDING"..0x889F
)
val BUFFER_OBJECT_USAGE_HINTS = IntConstant(
"Accepted by the {@code usage} parameter of BufferData.",
"STREAM_DRAW"..0x88E0,
"STREAM_READ"..0x88E1,
"STREAM_COPY"..0x88E2,
"STATIC_DRAW"..0x88E4,
"STATIC_READ"..0x88E5,
"STATIC_COPY"..0x88E6,
"DYNAMIC_DRAW"..0x88E8,
"DYNAMIC_READ"..0x88E9,
"DYNAMIC_COPY"..0x88EA
).javaDocLinks
val BUFFER_OBJECT_ACCESS_POLICIES = IntConstant(
"Accepted by the {@code access} parameter of MapBuffer.",
"READ_ONLY"..0x88B8,
"WRITE_ONLY"..0x88B9,
"READ_WRITE"..0x88BA
).javaDocLinks
IntConstant(
"Accepted by the {@code pname} parameter of GetBufferParameteriv.",
"BUFFER_SIZE"..0x8764,
"BUFFER_USAGE"..0x8765,
"BUFFER_ACCESS"..0x88BB,
"BUFFER_MAPPED"..0x88BC
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBufferPointerv.",
"BUFFER_MAP_POINTER"..0x88BD
)
void(
"BindBuffer",
"Binds a named buffer object.",
GLenum.IN("target", "the target to which the buffer object is bound", BUFFER_OBJECT_TARGETS),
GLuint.IN("buffer", "the name of a buffer object")
)
void(
"DeleteBuffers",
"Deletes named buffer objects.",
AutoSize("buffers")..GLsizei.IN("n", "the number of buffer objects to be deleted"),
SingleValue("buffer")..const..GLuint_p.IN("buffers", "an array of buffer objects to be deleted")
)
void(
"GenBuffers",
"Generates buffer object names.",
AutoSize("buffers")..GLsizei.IN("n", "the number of buffer object names to be generated"),
ReturnParam..GLuint_p.OUT("buffers", "a buffer in which the generated buffer object names are stored")
)
GLboolean(
"IsBuffer",
"Determines if a name corresponds to a buffer object.",
GLuint.IN("buffer", "a value that may be the name of a buffer object")
)
void(
"BufferData",
"""
Creates and initializes a buffer object's data store.
{@code usage} is a hint to the GL implementation as to how a buffer object's data store will be accessed. This enables the GL implementation to make
more intelligent decisions that may significantly impact buffer object performance. It does not, however, constrain the actual usage of the data store.
{@code usage} can be broken down into two parts: first, the frequency of access (modification and usage), and second, the nature of that access. The
frequency of access may be one of these:
${ul(
"<em>STREAM</em> - The data store contents will be modified once and used at most a few times.",
"<em>STATIC</em> - The data store contents will be modified once and used many times.",
"<em>DYNAMIC</em> - The data store contents will be modified repeatedly and used many times."
)}
The nature of access may be one of these:
${ul(
"<em>DRAW</em> - The data store contents are modified by the application, and used as the source for GL drawing and image specification commands.",
"<em>READ</em> - The data store contents are modified by reading data from the GL, and used to return that data when queried by the application.",
"<em>COPY</em> - The data store contents are modified by reading data from the GL, and used as the source for GL drawing and image specification commands."
)}
""",
GLenum.IN("target", "the target buffer object", BUFFER_OBJECT_TARGETS),
AutoSize("data")..GLsizeiptr.IN("size", "the size in bytes of the buffer object's new data store"),
optional..MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..const..void_p.IN("data", "a pointer to data that will be copied into the data store for initialization, or $NULL if no data is to be copied"),
GLenum.IN("usage", "the expected usage pattern of the data store", BUFFER_OBJECT_USAGE_HINTS)
)
void(
"BufferSubData",
"Updates a subset of a buffer object's data store.",
GLenum.IN("target", "the target buffer object", BUFFER_OBJECT_TARGETS),
GLintptr.IN("offset", "the offset into the buffer object's data store where data replacement will begin, measured in bytes"),
AutoSize("data")..GLsizeiptr.IN("size", "the size in bytes of the data store region being replaced"),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..const..void_p.IN("data", "a pointer to the new data that will be copied into the data store")
)
void(
"GetBufferSubData",
"Returns a subset of a buffer object's data store.",
GLenum.IN("target", "the target buffer object", BUFFER_OBJECT_TARGETS),
GLintptr.IN("offset", "the offset into the buffer object's data store from which data will be returned, measured in bytes"),
AutoSize("data")..GLsizeiptr.IN("size", "the size in bytes of the data store region being returned"),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..void_p.IN("data", "a pointer to the location where buffer object data is returned")
)
(MapPointer("glGetBufferParameteri(target, GL_BUFFER_SIZE)")..void_p)(
"MapBuffer",
"""
Maps a buffer object's data store.
<b>LWJGL note</b>: This method comes in 3 flavors:
${ol(
"#MapBuffer(int, int) - Calls #GetBufferParameteri() to retrieve the buffer size and a new ByteBuffer instance is always returned.",
"#MapBuffer(int, int, ByteBuffer) - Calls #GetBufferParameteri() to retrieve the buffer size and the {@code old_buffer} parameter is reused if not null.",
"#MapBuffer(int, int, long, ByteBuffer) - The buffer size is explicitly specified and the {@code old_buffer} parameter is reused if not null. This is the most efficient method."
)}
""",
GLenum.IN("target", "the target buffer object being mapped", BUFFER_OBJECT_TARGETS),
GLenum.IN(
"access",
"the access policy, indicating whether it will be possible to read from, write to, or both read from and write to the buffer object's mapped data store",
BUFFER_OBJECT_ACCESS_POLICIES
)
)
GLboolean(
"UnmapBuffer",
"""
Relinquishes the mapping of a buffer object and invalidates the pointer to its data store.
Returns TRUE unless data values in the buffer’s data store have become corrupted during the period that the buffer was mapped. Such corruption can be
the result of a screen resolution change or other window system-dependent event that causes system heaps such as those for high-performance graphics
memory to be discarded. GL implementations must guarantee that such corruption can occur only during the periods that a buffer’s data store is mapped.
If such corruption has occurred, UnmapBuffer returns FALSE, and the contents of the buffer’s data store become undefined.
""",
GLenum.IN("target", "the target buffer object being unmapped", BUFFER_OBJECT_TARGETS)
)
void(
"GetBufferParameteriv",
"Returns the value of a buffer object parameter.",
GLenum.IN("target", "the target buffer object", BUFFER_OBJECT_TARGETS),
GLenum.IN("pname", "the symbolic name of a buffer object parameter", BUFFER_OBJECT_PARAMETERS),
Check(1)..ReturnParam..GLint_p.OUT("params", "the requested parameter")
)
void(
"GetBufferPointerv",
"Returns the pointer to a mapped buffer object's data store.",
GLenum.IN("target", "the target buffer object", BUFFER_OBJECT_TARGETS),
GLenum.IN("pname", "the pointer to be returned", "GL15#BUFFER_MAP_POINTER"),
Check(1)..ReturnParam..void_pp.OUT("params", "the pointer value specified by {@code pname}")
)
// ARB_occlusion_query
IntConstant(
"Accepted by the {@code target} parameter of BeginQuery, EndQuery, and GetQueryiv.",
"SAMPLES_PASSED"..0x8914
)
val QUERY_PARAMETERS = IntConstant(
"Accepted by the {@code pname} parameter of GetQueryiv.",
"QUERY_COUNTER_BITS"..0x8864,
"CURRENT_QUERY"..0x8865
).javaDocLinks
val QUERY_OBJECT_PARAMETERS = IntConstant(
"Accepted by the {@code pname} parameter of GetQueryObjectiv and GetQueryObjectuiv.",
"QUERY_RESULT"..0x8866,
"QUERY_RESULT_AVAILABLE"..0x8867
).javaDocLinks
void(
"GenQueries",
"Generates query object names.",
AutoSize("ids")..GLsizei.IN("n", "the number of query object names to be generated"),
ReturnParam..GLuint_p.OUT("ids", "a buffer in which the generated query object names are stored")
)
void(
"DeleteQueries",
"Deletes named query objects.",
AutoSize("ids")..GLsizei.IN("n", "the number of query objects to be deleted"),
SingleValue("id")..const..GLuint_p.IN("ids", "an array of query objects to be deleted")
)
GLboolean(
"IsQuery",
"Determine if a name corresponds to a query object.",
GLuint.IN("id", "a value that may be the name of a query object")
)
void(
"BeginQuery",
"Creates a query object and makes it active.",
GLenum.IN("target", "the target type of query object established", QUERY_TARGETS),
GLuint.IN("id", "the name of a query object")
)
ReferenceGL("glBeginQuery")..void(
"EndQuery",
"Marks the end of the sequence of commands to be tracked for the active query specified by {@code target}.",
GLenum.IN("target", "the query object target", QUERY_TARGETS)
)
void(
"GetQueryiv",
"Returns parameters of a query object target.",
GLenum.IN("target", "the query object target", QUERY_TARGETS),
GLenum.IN("pname", "the symbolic name of a query object target parameter", QUERY_PARAMETERS),
Check(1)..ReturnParam..GLint_p.OUT("params", "the requested data")
)
void(
"GetQueryObjectiv",
"Returns the integer value of a query object parameter.",
GLuint.IN("id", "the name of a query object"),
GLenum.IN("pname", "the symbolic name of a query object parameter", QUERY_OBJECT_PARAMETERS),
Check(1)..ReturnParam..GLint_p.OUT("params", "the requested data")
)
void(
"GetQueryObjectuiv",
"Unsigned version of #GetQueryObjectiv().",
GLuint.IN("id", "the name of a query object"),
GLenum.IN("pname", "the symbolic name of a query object parameter", QUERY_OBJECT_PARAMETERS),
Check(1)..ReturnParam..GLuint_p.OUT("params", "the requested data")
)
} | bsd-3-clause | b1a2451b9c0d856b83f9f044d30035a6 | 33.953552 | 180 | 0.721388 | 3.434094 | false | false | false | false |
wealthfront/magellan | magellan-sample-advanced/src/main/java/com/wealthfront/magellan/sample/advanced/api/ApiClient.kt | 1 | 2409 | package com.wealthfront.magellan.sample.advanced.api
import com.wealthfront.magellan.sample.advanced.R
import com.wealthfront.magellan.sample.advanced.cerealcollection.CerealDetails
import com.wealthfront.magellan.sample.advanced.cerealcollection.CerealStatus
import com.wealthfront.magellan.sample.advanced.cerealcollection.CerealStatus.ACTIVE
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.mock.BehaviorDelegate
import retrofit2.mock.MockRetrofit
import retrofit2.mock.NetworkBehavior
import java.util.concurrent.TimeUnit
class ApiClient constructor(private val retrofit: BehaviorDelegate<ApiContract>) : ApiContract {
val ALL_CEREALS = listOf(
CerealDetails(
R.string.monster_cereals_title,
R.string.monster_cereals_description,
CerealStatus.LIMITED
),
CerealDetails(
R.string.dunk_a_balls_title,
R.string.dunk_a_balls_description,
CerealStatus.DISCONTINUED
),
CerealDetails(
R.string.cornflakes_title,
R.string.cornflakes_description,
ACTIVE
),
CerealDetails(
R.string.oreo_os_title,
R.string.oreo_os_description,
ACTIVE
)
)
companion object {
@JvmStatic
fun buildClient(): ApiClient {
val retrofit = getRetrofit()
val delegate = getMockRetrofit(retrofit).create(ApiContract::class.java)
return ApiClient(delegate)
}
private fun getRetrofit(): Retrofit {
val okHttpClient = OkHttpClient().newBuilder().build()
return Retrofit.Builder()
.baseUrl("http://example.com")
.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
.client(okHttpClient)
.build()
}
private fun getMockRetrofit(retrofit: Retrofit): MockRetrofit {
val networkBehavior = NetworkBehavior.create()
networkBehavior.setDelay(2500, TimeUnit.MILLISECONDS)
networkBehavior.setVariancePercent(20)
networkBehavior.setErrorPercent(0)
networkBehavior.setFailurePercent(0)
return MockRetrofit.Builder(retrofit)
.networkBehavior(networkBehavior)
.build()
}
}
override fun getCollection(): Observable<List<CerealDetails>> {
return retrofit.returningResponse(ALL_CEREALS).getCollection()
}
}
| apache-2.0 | bddf7c595ad61728bc3de26c1962f6fb | 31.12 | 96 | 0.741802 | 4.294118 | false | false | false | false |
inorichi/tachiyomi-extensions | src/en/dynasty/src/eu/kanade/tachiyomi/extension/en/dynasty/DynastySeries.kt | 1 | 969 | package eu.kanade.tachiyomi.extension.en.dynasty
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.SManga
import okhttp3.Request
import org.jsoup.nodes.Document
class DynastySeries : DynastyScans() {
override val name = "Dynasty-Series"
override val searchPrefix = "series"
override fun popularMangaInitialUrl() = "$baseUrl/series?view=cover"
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
return GET("$baseUrl/search?q=$query&classes%5B%5D=Series&sort=&page=$page", headers)
}
override fun mangaDetailsParse(document: Document): SManga {
val manga = SManga.create()
manga.thumbnail_url = baseUrl + document.select("div.span2 > img").attr("src")
parseHeader(document, manga)
parseGenres(document, manga)
parseDescription(document, manga)
return manga
}
}
| apache-2.0 | 0f8b5a790e0315bb4ccb555198632dca | 32.413793 | 93 | 0.719298 | 4.088608 | false | false | false | false |
Shockah/Godwit | core/src/pl/shockah/godwit/geom/polygon/BasicTriangulator.kt | 1 | 3466 | package pl.shockah.godwit.geom.polygon
import pl.shockah.godwit.geom.Triangle
import pl.shockah.godwit.geom.Vec2
/*
* code taken from Slick2D - http://slick.ninjacave.com/
*/
class BasicTriangulator : Triangulator {
companion object {
private const val EPSILON = 0.0000000001f
}
override fun triangulate(points: List<Vec2>): List<Triangle>? {
val process = Process(points)
return if (process.triangulate()) process.tris else null
}
inner class Process(
val points: List<Vec2>
) {
val tris: MutableList<Triangle> = mutableListOf()
private var tried: Boolean = false
val triangleCount: Int
get() {
if (!tried)
triangulate()
return tris.size / 3
}
fun triangulate(): Boolean {
tried = true
return process(points, tris)
}
private fun area(contour: List<Vec2>): Float {
val n = contour.size
var A = 0f
var p = n - 1
var q = 0
while (q < n) {
val contourP = contour[p]
val contourQ = contour[q]
A += contourP.x * contourQ.y - contourQ.x * contourP.y
p = q++
}
return A * 0.5f
}
private fun insideTriangle(Ax: Double, Ay: Double, Bx: Double, By: Double, Cx: Double, Cy: Double, Px: Double, Py: Double): Boolean {
val ax: Double = Cx - Bx
val ay: Double = Cy - By
val bx: Double = Ax - Cx
val by: Double = Ay - Cy
val cx: Double = Bx - Ax
val cy: Double = By - Ay
val apx: Double = Px - Ax
val apy: Double = Py - Ay
val bpx: Double = Px - Bx
val bpy: Double = Py - By
val cpx: Double = Px - Cx
val cpy: Double = Py - Cy
val cCROSSap: Double = cx * apy - cy * apx
val bCROSScp: Double = bx * cpy - by * cpx
val aCROSSbp: Double = ax * bpy - ay * bpx
return aCROSSbp >= 0f && bCROSScp >= 0f && cCROSSap >= 0f
}
private fun snip(contour: List<Vec2>, u: Int, v: Int, w: Int, n: Int, V: IntArray): Boolean {
var p: Int = 0
val Ax: Double = contour[V[u]].x.toDouble()
val Ay: Double = contour[V[u]].y.toDouble()
val Bx: Double = contour[V[v]].x.toDouble()
val By: Double = contour[V[v]].y.toDouble()
val Cx: Double = contour[V[w]].x.toDouble()
val Cy: Double = contour[V[w]].y.toDouble()
var Px: Double
var Py: Double
if (EPSILON > (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax))
return false
while (p < n) {
if (p == u || p == v || p == w) {
p++
continue
}
Px = contour[V[p]].x.toDouble()
Py = contour[V[p]].y.toDouble()
if (insideTriangle(Ax, Ay, Bx, By, Cx, Cy, Px, Py))
return false
p++
}
return true
}
private fun process(contour: List<Vec2>, result: MutableList<Triangle>): Boolean {
result.clear()
val n = contour.size
if (n < 3)
return false
val V = IntArray(n)
if (0f < area(contour)) {
for (v in 0 until n) {
V[v] = v
}
} else {
for (v in 0 until n) {
V[v] = n - 1 - v
}
}
var nv = n
var count = 2 * nv
var v = nv - 1
while (nv > 2) {
if (0 >= count--)
return false
var u = v
if (nv <= u)
u = 0
v = u + 1
if (nv <= v)
v = 0
var w = v + 1
if (nv <= w)
w = 0
if (snip(contour, u, v, w, nv, V)) {
val a: Int = V[u]
val b: Int = V[v]
val c: Int = V[w]
var s: Int = v
var t: Int = v + 1
result.add(Triangle(contour[a], contour[b], contour[c]))
while (t < nv) {
V[s] = V[t]
s++
t++
}
nv--
count = 2 * nv
}
}
return true
}
}
} | apache-2.0 | 7d3c23eb8d3b23534c6e4029655d537d | 20.943038 | 135 | 0.55251 | 2.613876 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/general/net/ChangeableBaseUrlInterceptor.kt | 1 | 1259 | package com.intfocus.template.general.net
/**
* ****************************************************
* author jameswong
* created on: 18/01/17 上午10:25
* e-mail: [email protected]
* name:
* desc:
* ****************************************************
*/
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
/** An interceptor that allows runtime changes to the URL hostname. */
class ChangeableBaseUrlInterceptor : Interceptor {
@Volatile private var host: HttpUrl? = null
fun setHost(url: String) {
this.host = HttpUrl.parse(url)
}
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val newRequest = host?.let {
val newUrl = chain.request().url().newBuilder()
.scheme(it.scheme())
.host(it.url().toURI().host)
.port(it.port())
.build()
return@let chain.request().newBuilder()
.url(newUrl)
.build()
}
return if(newRequest!=null){
chain.proceed(newRequest)
}else{
chain.proceed(chain.request())
}
}
}
| gpl-3.0 | 82647e3831508efbf38d35dec7002104 | 26.282609 | 71 | 0.523506 | 4.580292 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/user/CountryStatisticsDao.kt | 1 | 2375 | package de.westnordost.streetcomplete.data.user
import android.database.sqlite.SQLiteDatabase.CONFLICT_IGNORE
import android.database.sqlite.SQLiteOpenHelper
import androidx.core.content.contentValuesOf
import de.westnordost.streetcomplete.data.user.CountryStatisticsTable.Columns.COUNTRY_CODE
import de.westnordost.streetcomplete.data.user.CountryStatisticsTable.Columns.RANK
import de.westnordost.streetcomplete.data.user.CountryStatisticsTable.Columns.SUCCEEDED
import de.westnordost.streetcomplete.data.user.CountryStatisticsTable.NAME
import javax.inject.Inject
import de.westnordost.streetcomplete.ktx.*
import javax.inject.Singleton
/** Stores how many quests the user solved in which country */
@Singleton class CountryStatisticsDao @Inject constructor(private val dbHelper: SQLiteOpenHelper) {
private val db get() = dbHelper.writableDatabase
fun getCountryWithBiggestSolvedCount(): CountryStatistics? {
return db.queryOne(NAME, orderBy = "$SUCCEEDED DESC") {
CountryStatistics(it.getString(COUNTRY_CODE), it.getInt(SUCCEEDED), it.getIntOrNull(RANK))
}
}
fun getAll(): List<CountryStatistics> {
return db.query(NAME) {
CountryStatistics(it.getString(COUNTRY_CODE), it.getInt(SUCCEEDED), it.getIntOrNull(RANK))
}
}
fun clear() {
db.delete(NAME, null, null)
}
fun replaceAll(countriesStatistics: Collection<CountryStatistics>) {
db.transaction {
db.delete(NAME, null, null)
for (statistics in countriesStatistics) {
db.insert(NAME, null, contentValuesOf(
COUNTRY_CODE to statistics.countryCode,
SUCCEEDED to statistics.solvedCount,
RANK to statistics.rank
))
}
}
}
fun addOne(countryCode: String) {
// first ensure the row exists
db.insertWithOnConflict(NAME, null, contentValuesOf(
COUNTRY_CODE to countryCode,
SUCCEEDED to 0
), CONFLICT_IGNORE)
// then increase by one
db.execSQL("UPDATE $NAME SET $SUCCEEDED = $SUCCEEDED + 1 WHERE $COUNTRY_CODE = ?", arrayOf(countryCode))
}
fun subtractOne(countryCode: String) {
db.execSQL("UPDATE $NAME SET $SUCCEEDED = $SUCCEEDED - 1 WHERE $COUNTRY_CODE = ?", arrayOf(countryCode))
}
} | gpl-3.0 | f6a40bbe65b6f0743faa601802da92b0 | 36.714286 | 112 | 0.688842 | 4.64775 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerConfig.kt | 1 | 2984 | package eu.kanade.tachiyomi.ui.reader.viewer.pager
import com.f2prateek.rx.preferences.Preference
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.util.addTo
import rx.subscriptions.CompositeSubscription
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
/**
* Configuration used by pager viewers.
*/
class PagerConfig(private val viewer: PagerViewer, preferences: PreferencesHelper = Injekt.get()) {
private val subscriptions = CompositeSubscription()
var imagePropertyChangedListener: (() -> Unit)? = null
var tappingEnabled = true
private set
var longTapEnabled = true
private set
var volumeKeysEnabled = false
private set
var volumeKeysInverted = false
private set
var usePageTransitions = false
private set
var imageScaleType = 1
private set
var imageZoomType = ZoomType.Left
private set
var imageCropBorders = false
private set
var doubleTapAnimDuration = 500
private set
init {
preferences.readWithTapping()
.register({ tappingEnabled = it })
preferences.readWithLongTap()
.register({ longTapEnabled = it })
preferences.pageTransitions()
.register({ usePageTransitions = it })
preferences.imageScaleType()
.register({ imageScaleType = it }, { imagePropertyChangedListener?.invoke() })
preferences.zoomStart()
.register({ zoomTypeFromPreference(it) }, { imagePropertyChangedListener?.invoke() })
preferences.cropBorders()
.register({ imageCropBorders = it }, { imagePropertyChangedListener?.invoke() })
preferences.doubleTapAnimSpeed()
.register({ doubleTapAnimDuration = it })
preferences.readWithVolumeKeys()
.register({ volumeKeysEnabled = it })
preferences.readWithVolumeKeysInverted()
.register({ volumeKeysInverted = it })
}
fun unsubscribe() {
subscriptions.unsubscribe()
}
private fun <T> Preference<T>.register(
valueAssignment: (T) -> Unit,
onChanged: (T) -> Unit = {}
) {
asObservable()
.doOnNext(valueAssignment)
.skip(1)
.distinctUntilChanged()
.doOnNext(onChanged)
.subscribe()
.addTo(subscriptions)
}
private fun zoomTypeFromPreference(value: Int) {
imageZoomType = when (value) {
// Auto
1 -> when (viewer) {
is L2RPagerViewer -> ZoomType.Left
is R2LPagerViewer -> ZoomType.Right
else -> ZoomType.Center
}
// Left
2 -> ZoomType.Left
// Right
3 -> ZoomType.Right
// Center
else -> ZoomType.Center
}
}
enum class ZoomType {
Left, Center, Right
}
}
| apache-2.0 | fa2c753eb2721446b4536050939812bc | 25.40708 | 99 | 0.605898 | 5.100855 | false | false | false | false |
Heiner1/AndroidAPS | medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/GetHistoryPageCarelinkMessageBody.kt | 1 | 1176 | package info.nightscout.androidaps.plugins.pump.medtronic.comm.message
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil
import kotlin.experimental.and
/**
* Created by geoff on 6/2/16.
*/
class GetHistoryPageCarelinkMessageBody : CarelinkLongMessageBody {
// public boolean wasLastFrame = false;
// public int frameNumber = 0;
// public byte[] frame = new byte[] {};
constructor(frameData: ByteArray?) {
init(frameData)
}
constructor(pageNum: Int) {
init(pageNum)
}
override val length: Int
get() = data!!.size
fun init(pageNum: Int) {
val numArgs: Byte = 1
super.init(byteArrayOf(numArgs, pageNum.toByte()))
}
val frameNumber: Int
get() = if (data!!.size > 0) {
(data!![0] and 0x7f.toByte()).toInt()
} else 255
fun wasLastFrame(): Boolean {
return (data!![0] and 0x80.toByte()).toInt() != 0
}
val frameData: ByteArray
get() {
return if (data == null) {
byteArrayOf()
} else {
ByteUtil.substring(data!!, 1, data!!.size - 1)
}
}
} | agpl-3.0 | a49871aea7be1feb51ddbd76bfb2a7a8 | 24.042553 | 70 | 0.577381 | 4 | false | false | false | false |
Heiner1/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetExtendedBolusCancel.kt | 1 | 917 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.danars.encryption.BleEncryption
class DanaRSPacketBolusSetExtendedBolusCancel(
injector: HasAndroidInjector
) : DanaRSPacket(injector) {
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__SET_EXTENDED_BOLUS_CANCEL
aapsLogger.debug(LTag.PUMPCOMM, "Cancel extended bolus")
}
override fun handleMessage(data: ByteArray) {
val result = intFromBuff(data, 0, 1)
@Suppress("LiftReturnOrAssignment")
if (result == 0) {
aapsLogger.debug(LTag.PUMPCOMM, "Result OK")
failed = false
} else {
aapsLogger.error("Result Error: $result")
failed = true
}
}
override val friendlyName: String = "BOLUS__SET_EXTENDED_BOLUS_CANCEL"
} | agpl-3.0 | 10a4c039334f502ca49aca81694baacc | 30.655172 | 84 | 0.683751 | 4.585 | false | false | false | false |
saletrak/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/di/modules/PresentersModule.kt | 1 | 3458 | package io.github.feelfreelinux.wykopmobilny.di.modules
import dagger.Module
import dagger.Provides
import io.github.feelfreelinux.wykopmobilny.api.entries.EntriesApi
import io.github.feelfreelinux.wykopmobilny.api.mywykop.MyWykopApi
import io.github.feelfreelinux.wykopmobilny.api.stream.StreamApi
import io.github.feelfreelinux.wykopmobilny.api.tag.TagApi
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.add.AddEntryPresenter
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.edit.EditEntryPresenter
import io.github.feelfreelinux.wykopmobilny.ui.modules.loginscreen.LoginScreenPresenter
import io.github.feelfreelinux.wykopmobilny.ui.modules.mainnavigation.MainNavigationPresenter
import io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.entry.EntryDetailPresenter
import io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.feed.hot.HotPresenter
import io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.feed.tag.TagPresenter
import io.github.feelfreelinux.wykopmobilny.ui.modules.notifications.notificationsservice.WykopNotificationsJobPresenter
import io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist.hashtags.HashTagsNotificationsListPresenter
import io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist.notification.NotificationsListPresenter
import io.github.feelfreelinux.wykopmobilny.utils.rx.SubscriptionHelperApi
import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi
@Module
class PresentersModule {
@Provides
fun provideLoginPresenter(userManagerApi : UserManagerApi) = LoginScreenPresenter(userManagerApi)
@Provides
fun provideMainNavigationPresenter(subscriptionHelperApi: SubscriptionHelperApi, userManagerApi: UserManagerApi, myWykopApi: MyWykopApi)
= MainNavigationPresenter(subscriptionHelperApi, userManagerApi, myWykopApi)
@Provides
fun provideHotPresenter(subscriptionHelperApi: SubscriptionHelperApi, streamApi: StreamApi)
= HotPresenter(subscriptionHelperApi, streamApi)
@Provides
fun provideTagPresenter(subscriptionHelperApi: SubscriptionHelperApi, tagApi: TagApi)
= TagPresenter(subscriptionHelperApi, tagApi)
@Provides
fun provideEntryDetailPresenter(subscriptionHelperApi: SubscriptionHelperApi, entriesApi: EntriesApi)
= EntryDetailPresenter(subscriptionHelperApi, entriesApi)
@Provides
fun provideAddEntryPresenter(subscriptionHelperApi: SubscriptionHelperApi, entriesApi: EntriesApi)
= AddEntryPresenter(subscriptionHelperApi, entriesApi)
@Provides
fun provideEditEntryPresenter(subscriptionHelperApi: SubscriptionHelperApi, entriesApi: EntriesApi)
= EditEntryPresenter(subscriptionHelperApi, entriesApi)
@Provides
fun provideNotificationsListPresenter(subscriptionHelperApi: SubscriptionHelperApi, myWykopApi: MyWykopApi)
= NotificationsListPresenter(subscriptionHelperApi, myWykopApi)
@Provides
fun provideHashTagsNotificationListPresenter(subscriptionHelperApi: SubscriptionHelperApi, myWykopApi: MyWykopApi)
= HashTagsNotificationsListPresenter(subscriptionHelperApi, myWykopApi)
@Provides
fun provideWykopNoticationsJobPresenter(subscriptionHelperApi: SubscriptionHelperApi, myWykopApi: MyWykopApi, userManagerApi: UserManagerApi)
= WykopNotificationsJobPresenter(subscriptionHelperApi, myWykopApi, userManagerApi)
} | mit | e08ae04f8602aeb5e7483dee2f5eac95 | 54.790323 | 145 | 0.837478 | 5.100295 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/base/resources/src/org/jetbrains/kotlin/idea/KotlinIconProvider.kt | 3 | 7548 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea
import com.intellij.ide.IconProvider
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.util.Iconable
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parentOfType
import com.intellij.ui.RowIcon
import com.intellij.util.PlatformIcons
import org.jetbrains.kotlin.analysis.decompiled.light.classes.KtLightClassForDecompiledDeclarationBase
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.classes.KtLightClassForSourceDeclaration
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.idea.KotlinIcons.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.utils.addToStdlib.ifTrue
import javax.swing.Icon
abstract class KotlinIconProvider : IconProvider(), DumbAware {
protected abstract fun isMatchingExpected(declaration: KtDeclaration): Boolean
private fun Icon.addExpectActualMarker(element: PsiElement): Icon {
val declaration = (element as? KtNamedDeclaration) ?: return this
val additionalIcon = when {
isExpectDeclaration(declaration) -> EXPECT
isMatchingExpected(declaration) -> ACTUAL
else -> return this
}
return RowIcon(2).apply {
setIcon(this@addExpectActualMarker, 0)
setIcon(additionalIcon, 1)
}
}
private tailrec fun isExpectDeclaration(declaration: KtDeclaration): Boolean {
if (declaration.hasExpectModifier()) {
return true
}
val containingDeclaration = declaration.containingClassOrObject ?: return false
return isExpectDeclaration(containingDeclaration)
}
override fun getIcon(psiElement: PsiElement, flags: Int): Icon? {
if (psiElement is KtFile) {
if (psiElement.isScript()) {
return when {
psiElement.name.endsWith(".gradle.kts") -> GRADLE_SCRIPT
else -> SCRIPT
}
}
val mainClass = getSingleClass(psiElement)
return if (mainClass != null) getIcon(mainClass, flags) else FILE
}
val result = psiElement.getBaseIcon()
if (flags and Iconable.ICON_FLAG_VISIBILITY > 0 && result != null && (psiElement is KtModifierListOwner && psiElement !is KtClassInitializer)) {
val list = psiElement.modifierList
val visibilityIcon = getVisibilityIcon(list)
val withExpectedActual: Icon = try {
result.addExpectActualMarker(psiElement)
} catch (indexNotReady: IndexNotReadyException) {
result
}
return createRowIcon(withExpectedActual, visibilityIcon)
}
return result
}
companion object {
fun isSingleClassFile(file: KtFile) = getSingleClass(file) != null
fun getSingleClass(file: KtFile): KtClassOrObject? =
getMainClass(file)?.takeIf {
file.declarations
.filterNot { it.isPrivate() || it is KtTypeAlias }
.size == 1
}
fun getMainClass(file: KtFile): KtClassOrObject? {
val classes = file.declarations.filterNot { it.isPrivate() }.filterIsInstance<KtClassOrObject>()
if (classes.size == 1 && StringUtil.getPackageName(file.name) == classes[0].name) {
return classes[0]
}
return null
}
private fun createRowIcon(baseIcon: Icon, visibilityIcon: Icon): RowIcon {
val rowIcon = RowIcon(2)
rowIcon.setIcon(baseIcon, 0)
rowIcon.setIcon(visibilityIcon, 1)
return rowIcon
}
fun getVisibilityIcon(list: KtModifierList?): Icon {
if (list != null) {
if (list.hasModifier(KtTokens.PRIVATE_KEYWORD)) {
return PlatformIcons.PRIVATE_ICON
}
if (list.hasModifier(KtTokens.PROTECTED_KEYWORD)) {
return PlatformIcons.PROTECTED_ICON
}
if (list.hasModifier(KtTokens.INTERNAL_KEYWORD)) {
return PlatformIcons.PACKAGE_LOCAL_ICON
}
}
return PlatformIcons.PUBLIC_ICON
}
fun PsiElement.getBaseIcon(): Icon? = when (this) {
is KtPackageDirective -> PlatformIcons.PACKAGE_ICON
is KtFile, is KtLightClassForFacade -> FILE
is KtLightClassForSourceDeclaration -> navigationElement.getBaseIcon()
is KtNamedFunction -> when {
receiverTypeReference != null ->
if (KtPsiUtil.isAbstract(this)) ABSTRACT_EXTENSION_FUNCTION else EXTENSION_FUNCTION
getStrictParentOfType<KtNamedDeclaration>() is KtClass ->
if (KtPsiUtil.isAbstract(this)) PlatformIcons.ABSTRACT_METHOD_ICON else PlatformIcons.METHOD_ICON
else ->
FUNCTION
}
is KtConstructor<*> -> PlatformIcons.METHOD_ICON
is KtLightMethod -> when(val u = unwrapped) {
is KtProperty -> if (!u.hasBody()) PlatformIcons.ABSTRACT_METHOD_ICON else PlatformIcons.METHOD_ICON
else -> PlatformIcons.METHOD_ICON
}
is KtFunctionLiteral -> LAMBDA
is KtClass -> when {
isInterface() -> INTERFACE
isEnum() -> ENUM
isAnnotation() -> ANNOTATION
this is KtEnumEntry && getPrimaryConstructorParameterList() == null -> ENUM
else -> if (isAbstract()) ABSTRACT_CLASS else CLASS
}
is KtObjectDeclaration -> OBJECT
is KtParameter -> {
if (KtPsiUtil.getClassIfParameterIsProperty(this) != null) {
if (isMutable) FIELD_VAR else FIELD_VAL
} else
PARAMETER
}
is KtProperty -> if (isVar) FIELD_VAR else FIELD_VAL
is KtClassInitializer -> CLASS_INITIALIZER
is KtTypeAlias -> TYPE_ALIAS
is KtAnnotationEntry -> {
(shortName?.asString() == JvmFileClassUtil.JVM_NAME_SHORT).ifTrue {
val grandParent = parent.parent
if (grandParent is KtPropertyAccessor) {
grandParent.parentOfType<KtProperty>()?.getBaseIcon()
} else {
grandParent.getBaseIcon()
}
}
}
is PsiClass -> (this is KtLightClassForDecompiledDeclarationBase).ifTrue {
val origin = (this as? KtLightClass)?.kotlinOrigin
//TODO (light classes for decompiled files): correct presentation
if (origin != null) origin.getBaseIcon() else CLASS
}
else -> unwrapped?.takeIf { it != this }?.getBaseIcon()
}
}
}
| apache-2.0 | d257e1868d4ff42c7f3bb20320947d84 | 41.886364 | 158 | 0.61672 | 5.465605 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/storage/driver/testutil/RamDiskTestUtils.kt | 1 | 1235 | /*
* 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
*/
@file:Suppress("EXPERIMENTAL_API_USAGE")
package arcs.core.storage.driver.testutil
import arcs.core.crdt.CrdtData
import arcs.core.storage.StorageKey
import arcs.core.storage.driver.RamDisk
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.sendBlocking
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
/** Suspends until the [RamDisk] contains a value for the provided [storageKey]. */
suspend fun RamDisk.waitUntilSet(storageKey: StorageKey) = callbackFlow<Unit> {
val listener: ((StorageKey, Any?) -> Unit) = listener@{ changedKey, data ->
if (changedKey != storageKey || data == null) return@listener
sendBlocking(Unit)
}
addListener(listener)
val startValue = memory.get<CrdtData>(storageKey)
if (startValue?.data != null) send(Unit)
awaitClose { runBlocking { removeListener(listener) } }
}.first()
| bsd-3-clause | 860cff850c7acc2ac48adab4ae9d2041 | 33.305556 | 96 | 0.760324 | 4.075908 | false | false | false | false |
shibafu528/SperMaster | app/src/main/kotlin/info/shibafu528/spermaster/model/Tag.kt | 1 | 2107 | package info.shibafu528.spermaster.model
import android.provider.BaseColumns
import com.activeandroid.Model
import com.activeandroid.annotation.Column
import com.activeandroid.annotation.Table
import com.activeandroid.query.Select
/**
* [Ejaculation]に0..n個紐付けることの出来るタグのデータモデル。
*
* Created by shibafu on 15/07/05.
*/
public @Table(name = "Tags", id = BaseColumns._ID) class Tag() : Model() {
/** 表示名。しかし、ユーザ入力とのマッチングにもそのまま使われます。 */
@Column(name = "Name") public var name: String = ""
/**
* 新規のタグを作成します。
* @param name タグの表示名
*/
constructor(name: String) : this() {
this.name = name
}
override fun toString(): String {
return name
}
companion object {
/**
* ユーザ入力のタグをパースし、DBに問い合わせて既存データであればそれを取得、存在しない場合は新規作成します。
* 保存と更新は行いません。
* @param inputTags ユーザによって入力されたタグ。`"tag1, tag2, tag3"`のような記法を期待し処理します。
* @return タグデータ
*/
public fun parseInputTags(inputTags: String) : List<Tag> =
inputTags.split(',' , ';', '、')
.map { it.trim() }
.filterNot { "".equals(it) }
.map { Select().from(Tag::class.java)
.where("Name = ?", it)
.executeSingle() ?: Tag(it) }
}
}
public @Table(name = "TagMap", id = BaseColumns._ID) class TagMap() : Model() {
@Column(name = "EjaculationId", notNull = true, index = true)
public var ejaculation: Ejaculation? = null
@Column(name = "TagId", notNull = true, index = true)
public var tag: Tag? = null
constructor(ejaculation: Ejaculation, tag: Tag) : this() {
this.ejaculation = ejaculation
this.tag = tag
}
}
| mit | b62c8de18efce61a076cfaac6018e7ce | 29.362069 | 79 | 0.575241 | 3.184448 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/mysite/dynamiccards/quickstart/QuickStartListItemDecoration.kt | 1 | 936 | package org.wordpress.android.ui.mysite.dynamiccards.quickstart
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
data class QuickStartListItemDecoration(
val itemHorizontalSpacing: Int,
val edgeHorizontalSpacing: Int
) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
val itemPosition: Int = parent.getChildAdapterPosition(view)
val itemCount = state.itemCount
val isFirst = itemPosition == 0
val isLast = itemCount > 0 && itemPosition == itemCount - 1
outRect.set(
if (isFirst) edgeHorizontalSpacing else itemHorizontalSpacing,
0,
if (isLast) edgeHorizontalSpacing else itemHorizontalSpacing,
0
)
}
}
| gpl-2.0 | 6e5f9b9391cfc083f588784d2e43da13 | 38 | 109 | 0.694444 | 4.875 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/code-insight/override-implement-k2/src/org/jetbrains/kotlin/idea/core/overrideImplement/KtOverrideMembersHandler.kt | 1 | 6006 | // 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.core.overrideImplement
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.lifetime.KtLifetimeOwner
import org.jetbrains.kotlin.analysis.api.lifetime.KtLifetimeToken
import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtClassKind
import org.jetbrains.kotlin.analysis.api.symbols.KtClassOrObjectSymbol
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithModality
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.idea.KtIconProvider.getIcon
import org.jetbrains.kotlin.idea.core.util.KotlinIdeaCoreBundle
import org.jetbrains.kotlin.name.StandardClassIds
import org.jetbrains.kotlin.psi.KtClassOrObject
@ApiStatus.Internal
open class KtOverrideMembersHandler : KtGenerateMembersHandler(false) {
@OptIn(KtAllowAnalysisOnEdt::class)
override fun collectMembersToGenerate(classOrObject: KtClassOrObject): Collection<KtClassMember> {
return allowAnalysisOnEdt {
analyze(classOrObject) {
collectMembers(classOrObject)
}
}
}
fun KtAnalysisSession.collectMembers(classOrObject: KtClassOrObject): List<KtClassMember> {
val classOrObjectSymbol = classOrObject.getClassOrObjectSymbol()
return getOverridableMembers(classOrObjectSymbol).map { (symbol, bodyType, containingSymbol) ->
KtClassMember(
KtClassMemberInfo(
symbol,
symbol.render(renderOption),
getIcon(symbol),
containingSymbol?.classIdIfNonLocal?.asSingleFqName()?.toString() ?: containingSymbol?.name?.asString(),
containingSymbol?.let { getIcon(it) },
),
bodyType,
preferConstructorParameter = false,
)
}
}
@OptIn(ExperimentalStdlibApi::class)
private fun KtAnalysisSession.getOverridableMembers(classOrObjectSymbol: KtClassOrObjectSymbol): List<OverrideMember> {
return buildList {
classOrObjectSymbol.getMemberScope().getCallableSymbols().forEach { symbol ->
if (!symbol.isVisibleInClass(classOrObjectSymbol)) return@forEach
val implementationStatus = symbol.getImplementationStatus(classOrObjectSymbol) ?: return@forEach
if (!implementationStatus.isOverridable) return@forEach
val intersectionSymbols = symbol.getIntersectionOverriddenSymbols()
val symbolsToProcess = if (intersectionSymbols.size <= 1) {
listOf(symbol)
} else {
val nonAbstractMembers = intersectionSymbols.filter { (it as? KtSymbolWithModality)?.modality != Modality.ABSTRACT }
// If there are non-abstract members, we only want to show override for these non-abstract members. Otherwise, show any
// abstract member to override.
nonAbstractMembers.ifEmpty {
listOf(intersectionSymbols.first())
}
}
val hasNoSuperTypesExceptAny = classOrObjectSymbol.superTypes.singleOrNull()?.isAny == true
for (symbolToProcess in symbolsToProcess) {
val originalOverriddenSymbol = symbolToProcess.originalOverriddenSymbol
val containingSymbol = originalOverriddenSymbol?.originalContainingClassForOverride
val bodyType = when {
classOrObjectSymbol.classKind == KtClassKind.INTERFACE && containingSymbol?.classIdIfNonLocal == StandardClassIds.Any -> {
if (hasNoSuperTypesExceptAny) {
// If an interface does not extends any other interfaces, FE1.0 simply skips members of `Any`. So we mimic
// the same behavior. See idea/testData/codeInsight/overrideImplement/noAnyMembersInInterface.kt
continue
} else {
BodyType.NoBody
}
}
(originalOverriddenSymbol as? KtSymbolWithModality)?.modality == Modality.ABSTRACT ->
BodyType.FromTemplate
symbolsToProcess.size > 1 ->
BodyType.QualifiedSuper
else ->
BodyType.Super
}
// Ideally, we should simply create `KtClassMember` here and remove the intermediate `OverrideMember` data class. But
// that doesn't work because this callback function is holding a read lock and `symbol.render(renderOption)` requires
// the write lock.
// Hence, we store the data in an intermediate `OverrideMember` data class and do the rendering later in the `map` call.
add(OverrideMember(symbolToProcess, bodyType, containingSymbol, token))
}
}
}
}
private data class OverrideMember(
val symbol: KtCallableSymbol,
val bodyType: BodyType,
val containingSymbol: KtClassOrObjectSymbol?,
override val token: KtLifetimeToken
) : KtLifetimeOwner
override fun getChooserTitle() = KotlinIdeaCoreBundle.message("override.members.handler.title")
override fun getNoMembersFoundHint() = KotlinIdeaCoreBundle.message("override.members.handler.no.members.hint")
} | apache-2.0 | 8e4b569e023f65da5012f4b2786814d8 | 52.633929 | 146 | 0.650017 | 5.976119 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/gradle/gradle/src/org/jetbrains/kotlin/idea/gradle/configuration/ResolveModulesPerSourceSetInMppBuildIssue.kt | 1 | 3203 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.gradle.configuration
import com.intellij.build.issue.BuildIssue
import com.intellij.build.issue.BuildIssueQuickFix
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.service.project.ExternalProjectRefreshCallback
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.project.Project
import com.intellij.pom.Navigatable
import org.jetbrains.kotlin.idea.gradle.KotlinIdeaGradleBundle
import org.jetbrains.plugins.gradle.settings.GradleProjectSettings
import org.jetbrains.plugins.gradle.settings.GradleSettings
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.util.concurrent.CompletableFuture
class ResolveModulesPerSourceSetInMppBuildIssue(
private val projectRefresher: ProjectRefresher = ReimportGradleProjectRefresher
) : BuildIssue {
interface ProjectRefresher {
operator fun invoke(project: Project): CompletableFuture<*>
}
private val quickFix = object: BuildIssueQuickFix {
override val id: String = "MppNotResolveModulePerSourceSetBuildIssue.QuickFix"
override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> {
runWriteAction {
project.gradleProjectSettings.forEach { it.isResolveModulePerSourceSet = true }
}
return projectRefresher(project)
}
}
override val title: String
get() = KotlinIdeaGradleBundle.message("configuration.is.resolve.module.per.source.set")
override val description: String =
"Kotlin Multiplatform Projects require resolving modules per source set\n" +
" - <a href=\"${quickFix.id}\">Fix and re-import project</a>\n"
override val quickFixes: List<BuildIssueQuickFix> = listOf(quickFix)
override fun getNavigatable(project: Project): Navigatable? = null
}
private object ReimportGradleProjectRefresher: ResolveModulesPerSourceSetInMppBuildIssue.ProjectRefresher {
override fun invoke(project: Project): CompletableFuture<*> = CompletableFuture<Nothing>().apply {
ExternalSystemUtil.refreshProjects(ImportSpecBuilder(project, GradleConstants.SYSTEM_ID).callback(
object : ExternalProjectRefreshCallback {
override fun onSuccess(externalProject: DataNode<ProjectData>?) {
complete(null)
}
override fun onFailure(errorMessage: String, errorDetails: String?) {
completeExceptionally(RuntimeException(errorMessage))
}
}
))
}
}
private val Project.gradleProjectSettings: List<GradleProjectSettings>
get() = GradleSettings.getInstance(this).linkedProjectsSettings.toList()
| apache-2.0 | 4ccef87a2f3675a19a289700885cf8d4 | 44.757143 | 158 | 0.756166 | 5.374161 | false | false | false | false |
omegasoft7/KAndroid | kandroid/src/main/java/com/pawegio/kandroid/KFragment.kt | 1 | 1117 | package com.pawegio.kandroid
import android.app.Activity
import android.app.Fragment
import android.content.SharedPreferences
import android.preference.PreferenceManager
import android.widget.Toast
import android.support.v4.app.Fragment as SupportFragment
/**
* @author pawegio
*/
suppress("UNCHECKED_CAST")
public fun Fragment.getActivity<T : Activity>(): T = getActivity() as T
public fun Fragment.getDefaultSharedPreferences(): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity())
public fun Fragment.toast(text: CharSequence): Unit = getActivity().toast(text)
public fun Fragment.longToast(text: CharSequence): Unit = getActivity().longToast(text)
suppress("UNCHECKED_CAST")
public fun SupportFragment.getActivity<T : Activity>(): T = getActivity() as T
public fun SupportFragment.getDefaultSharedPreferences(): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity())
public fun SupportFragment.toast(text: CharSequence): Unit = getActivity().toast(text)
public fun SupportFragment.longToast(text: CharSequence): Unit = getActivity().longToast(text) | apache-2.0 | 0b83938b686fc2023890ed4c7ef77b95 | 37.551724 | 138 | 0.811996 | 4.877729 | false | false | false | false |
hermantai/samples | android/udacity-kotlin/AboutMe/app/src/main/java/com/gmail/htaihm/aboutme/MainActivity.kt | 1 | 1313 | package com.gmail.htaihm.aboutme
import android.content.Context
import androidx.databinding.DataBindingUtil
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import com.gmail.htaihm.aboutme.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
// Instance of MyName data class.
private val myName: MyName = MyName("Herman Tai")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.myName = myName
binding.doneButton.setOnClickListener {
addNickname(it)
}
}
private fun addNickname(view: View) {
binding.apply {
myName?.nickname = nicknameEdit.text.toString()
invalidateAll()
nicknameEdit.visibility = View.GONE
doneButton.visibility = View.GONE
nicknameText.visibility = View.VISIBLE
}
// Hide the keyboard.
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
| apache-2.0 | dc8790337580c8de1adf988343be9a3c | 30.261905 | 86 | 0.708302 | 4.845018 | false | false | false | false |
byu-oit/android-byu-suite-v2 | app/src/main/java/edu/byu/suite/features/testingCenter/controller/ScheduleFragment.kt | 2 | 3651 | package edu.byu.suite.features.testingCenter.controller
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import edu.byu.suite.R
import edu.byu.suite.features.testingCenter.model.hours.CenterHour
import edu.byu.suite.features.testingCenter.model.hours.Hours
import edu.byu.suite.features.testingCenter.service.TestingCenterScheduleClient
import edu.byu.support.ByuClickListener
import edu.byu.support.ByuViewHolder
import edu.byu.support.activity.ByuActivity
import edu.byu.support.adapter.ByuRecyclerAdapter
import edu.byu.support.fragment.ByuRecyclerViewFragment
import edu.byu.support.retrofit.ByuSuccessCallback
import edu.byu.support.utils.*
import kotlinx.android.synthetic.main.testing_center_list_item_hours.view.*
import retrofit2.Call
import retrofit2.Response
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by cwoodfie on 7/28/16
*/
class ScheduleFragment: ByuRecyclerViewFragment() {
companion object {
private val DATE_FORMAT = SimpleDateFormat("MMM dd yyyy", Locale.US)
}
private val adapter = HoursAdapter()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = super.onCreateView(inflater, container, savedInstanceState)
setAdapter(adapter)
loadHours()
return view
}
private fun loadHours() {
enqueueCall(TestingCenterScheduleClient().getApi(activity).getHours(), object: ByuSuccessCallback<Hours>(activity as? ByuActivity) {
override fun onSuccess(call: Call<Hours>, response: Response<Hours>) {
val today = Date().getDayOfWeek()
val hours = response.body()
val centerHours = hours?.centerHours?.sorted()
// Set the opening and closing times for each day based on which CenterHourChange it is contained in
centerHours?.forEach { hour ->
val date = hour.day?.getNextDateWithDayName()
// If the name of the day given to us by the service is valid, hour.day gets set to the day name followed by the date (e.g. "Thursday, May 24, 2018")
// otherwise it is set to just the name returned by the service without the date
hour.day = (if (hour.day == today) getString(R.string.today) else hour.day) + (date?.let { ", " + DATE_FORMAT.format(date) } ?: "")
hours.centerHourChange?.forEach { change ->
if (date?.isBetween(change.beginDate, change.endDate).orFalse()) {
hour.doorsOpen = change.doorsOpen
hour.doorsClose = change.doorsClose
hour.centerCloses = change.centerCloses
}
}
}
adapter.list = centerHours
}
})
}
private inner class HoursAdapter: ByuRecyclerAdapter<CenterHour>(null) {
private val format = SimpleDateFormat("h:mm a", Locale.US)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ByuViewHolder<CenterHour> {
return ScheduleViewHolder(activity?.inflate(parent, R.layout.testing_center_list_item_hours))
}
private inner class ScheduleViewHolder(view: View?): ByuViewHolder<CenterHour>(view) {
private val date = view?.date
private val openTime = view?.open_time
private val doorsCloseTime = view?.doors_close_time
private val centerCloseTime = view?.center_close_time
override fun bind(data: CenterHour, listener: ByuClickListener<CenterHour>?) {
date?.text = data.day
openTime?.text = formatHoursDate(data.doorsOpen)
doorsCloseTime?.text = formatHoursDate(data.doorsClose)
centerCloseTime?.text = formatHoursDate(data.centerCloses)
}
}
private fun formatHoursDate(date: Date?): String {
return date?.let { format.format(it) } ?: getString(R.string.closed)
}
}
}
| apache-2.0 | 79d3a7dc1ad2ec59182208b654c7d344 | 36.639175 | 154 | 0.750205 | 3.710366 | false | true | false | false |
GunoH/intellij-community | plugins/full-line/python/src/org/jetbrains/completion/full/line/python/formatters/WhitespaceFormatter.kt | 2 | 1343 | package org.jetbrains.completion.full.line.python.formatters
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.completion.full.line.language.ElementFormatter
import org.jetbrains.completion.full.line.language.formatters.CodeFormatterBase
class WhitespaceFormatter : ElementFormatter {
private var skip = false
override fun condition(element: PsiElement): Boolean = element is PsiWhiteSpace || skip
override fun filter(element: PsiElement): Boolean? = null
override fun format(element: PsiElement): String {
if (skip) {
skip = false
return ""
}
if (element.prevSibling is PsiComment) {
return ""
}
return if (isNewLine(element.text)) {
fixEmptyLines(element.text)
}
else {
if ("\\" in element.text) {
skip = true
}
" "
}
}
private fun isNewLine(text: String): Boolean {
return text.matches(Regex("\\n\\s*"))
}
private fun fixEmptyLines(text: String): String {
val char = CodeFormatterBase.TABULATION.first()
var occurrences = 0
for (ch in text.reversed()) {
if (ch == char) {
occurrences++
}
else {
break
}
}
return "\n" + "\t".repeat(occurrences / CodeFormatterBase.TABULATION.length)
}
}
| apache-2.0 | f485f43f4dd5441cf868b126d31dab0a | 22.982143 | 89 | 0.660462 | 4.132308 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/changenumber/ChangeNumberEnterPhoneNumberFragment.kt | 2 | 7587 | package org.thoughtcrime.securesms.components.settings.app.changenumber
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.ScrollView
import android.widget.Spinner
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.navigation.fragment.findNavController
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import org.thoughtcrime.securesms.LoggingFragment
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.LabeledEditText
import org.thoughtcrime.securesms.components.settings.app.changenumber.ChangeNumberUtil.getViewModel
import org.thoughtcrime.securesms.components.settings.app.changenumber.ChangeNumberViewModel.ContinueStatus
import org.thoughtcrime.securesms.registration.fragments.CountryPickerFragment
import org.thoughtcrime.securesms.registration.fragments.CountryPickerFragmentArgs
import org.thoughtcrime.securesms.registration.util.RegistrationNumberInputController
import org.thoughtcrime.securesms.util.Dialogs
import org.thoughtcrime.securesms.util.navigation.safeNavigate
private const val OLD_NUMBER_COUNTRY_SELECT = "old_number_country"
private const val NEW_NUMBER_COUNTRY_SELECT = "new_number_country"
class ChangeNumberEnterPhoneNumberFragment : LoggingFragment(R.layout.fragment_change_number_enter_phone_number) {
private lateinit var scrollView: ScrollView
private lateinit var oldNumberCountrySpinner: Spinner
private lateinit var oldNumberCountryCode: LabeledEditText
private lateinit var oldNumber: LabeledEditText
private lateinit var newNumberCountrySpinner: Spinner
private lateinit var newNumberCountryCode: LabeledEditText
private lateinit var newNumber: LabeledEditText
private lateinit var viewModel: ChangeNumberViewModel
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
viewModel = getViewModel(this)
val toolbar: Toolbar = view.findViewById(R.id.toolbar)
toolbar.setTitle(R.string.ChangeNumberEnterPhoneNumberFragment__change_number)
toolbar.setNavigationOnClickListener { findNavController().navigateUp() }
view.findViewById<View>(R.id.change_number_enter_phone_number_continue).setOnClickListener {
onContinue()
}
scrollView = view.findViewById(R.id.change_number_enter_phone_number_scroll)
oldNumberCountrySpinner = view.findViewById(R.id.change_number_enter_phone_number_old_number_spinner)
oldNumberCountryCode = view.findViewById(R.id.change_number_enter_phone_number_old_number_country_code)
oldNumber = view.findViewById(R.id.change_number_enter_phone_number_old_number_number)
val oldController = RegistrationNumberInputController(
requireContext(),
oldNumberCountryCode,
oldNumber,
oldNumberCountrySpinner,
false,
object : RegistrationNumberInputController.Callbacks {
override fun onNumberFocused() {
scrollView.postDelayed({ scrollView.smoothScrollTo(0, oldNumber.bottom) }, 250)
}
override fun onNumberInputNext(view: View) {
newNumberCountryCode.requestFocus()
}
override fun onNumberInputDone(view: View) = Unit
override fun onPickCountry(view: View) {
val arguments: CountryPickerFragmentArgs = CountryPickerFragmentArgs.Builder().setResultKey(OLD_NUMBER_COUNTRY_SELECT).build()
findNavController().safeNavigate(R.id.action_enterPhoneNumberChangeFragment_to_countryPickerFragment, arguments.toBundle())
}
override fun setNationalNumber(number: String) {
viewModel.setOldNationalNumber(number)
}
override fun setCountry(countryCode: Int) {
viewModel.setOldCountry(countryCode)
}
}
)
newNumberCountrySpinner = view.findViewById(R.id.change_number_enter_phone_number_new_number_spinner)
newNumberCountryCode = view.findViewById(R.id.change_number_enter_phone_number_new_number_country_code)
newNumber = view.findViewById(R.id.change_number_enter_phone_number_new_number_number)
val newController = RegistrationNumberInputController(
requireContext(),
newNumberCountryCode,
newNumber,
newNumberCountrySpinner,
true,
object : RegistrationNumberInputController.Callbacks {
override fun onNumberFocused() {
scrollView.postDelayed({ scrollView.smoothScrollTo(0, newNumber.bottom) }, 250)
}
override fun onNumberInputNext(view: View) = Unit
override fun onNumberInputDone(view: View) {
onContinue()
}
override fun onPickCountry(view: View) {
val arguments: CountryPickerFragmentArgs = CountryPickerFragmentArgs.Builder().setResultKey(NEW_NUMBER_COUNTRY_SELECT).build()
findNavController().safeNavigate(R.id.action_enterPhoneNumberChangeFragment_to_countryPickerFragment, arguments.toBundle())
}
override fun setNationalNumber(number: String) {
viewModel.setNewNationalNumber(number)
}
override fun setCountry(countryCode: Int) {
viewModel.setNewCountry(countryCode)
}
}
)
parentFragmentManager.setFragmentResultListener(OLD_NUMBER_COUNTRY_SELECT, this) { _, bundle ->
viewModel.setOldCountry(bundle.getInt(CountryPickerFragment.KEY_COUNTRY_CODE), bundle.getString(CountryPickerFragment.KEY_COUNTRY))
}
parentFragmentManager.setFragmentResultListener(NEW_NUMBER_COUNTRY_SELECT, this) { _, bundle ->
viewModel.setNewCountry(bundle.getInt(CountryPickerFragment.KEY_COUNTRY_CODE), bundle.getString(CountryPickerFragment.KEY_COUNTRY))
}
viewModel.getLiveOldNumber().observe(viewLifecycleOwner, oldController::updateNumber)
viewModel.getLiveNewNumber().observe(viewLifecycleOwner, newController::updateNumber)
}
private fun onContinue() {
if (TextUtils.isEmpty(oldNumberCountryCode.text)) {
Toast.makeText(context, getString(R.string.ChangeNumberEnterPhoneNumberFragment__you_must_specify_your_old_number_country_code), Toast.LENGTH_LONG).show()
return
}
if (TextUtils.isEmpty(oldNumber.text)) {
Toast.makeText(context, getString(R.string.ChangeNumberEnterPhoneNumberFragment__you_must_specify_your_old_phone_number), Toast.LENGTH_LONG).show()
return
}
if (TextUtils.isEmpty(newNumberCountryCode.text)) {
Toast.makeText(context, getString(R.string.ChangeNumberEnterPhoneNumberFragment__you_must_specify_your_new_number_country_code), Toast.LENGTH_LONG).show()
return
}
if (TextUtils.isEmpty(newNumber.text)) {
Toast.makeText(context, getString(R.string.ChangeNumberEnterPhoneNumberFragment__you_must_specify_your_new_phone_number), Toast.LENGTH_LONG).show()
return
}
when (viewModel.canContinue()) {
ContinueStatus.CAN_CONTINUE -> findNavController().safeNavigate(R.id.action_enterPhoneNumberChangeFragment_to_changePhoneNumberConfirmFragment)
ContinueStatus.INVALID_NUMBER -> {
Dialogs.showAlertDialog(
context, getString(R.string.RegistrationActivity_invalid_number), String.format(getString(R.string.RegistrationActivity_the_number_you_specified_s_is_invalid), viewModel.number.e164Number)
)
}
ContinueStatus.OLD_NUMBER_DOESNT_MATCH -> {
MaterialAlertDialogBuilder(requireContext())
.setMessage(R.string.ChangeNumberEnterPhoneNumberFragment__the_phone_number_you_entered_doesnt_match_your_accounts)
.setPositiveButton(android.R.string.ok, null)
.show()
}
}
}
}
| gpl-3.0 | 4c293dd1e32d4cedcfc0430787030d4b | 42.354286 | 198 | 0.76038 | 4.578757 | false | false | false | false |
ktorio/ktor | ktor-http/common/src/io/ktor/http/content/OutgoingContent.kt | 1 | 4536 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.http.content
import io.ktor.http.*
import io.ktor.util.*
import io.ktor.utils.io.*
import kotlinx.coroutines.*
import kotlin.coroutines.*
/**
* A subject of pipeline when body of HTTP message is `null`
*/
public object NullBody
/**
* Information about the content to be sent to the peer, recognized by a client or server engine
*/
public sealed class OutgoingContent {
/**
* Specifies [ContentType] for this resource.
*/
public open val contentType: ContentType? get() = null
/**
* Specifies content length in bytes for this resource.
*
* If null, the resources will be sent as `Transfer-Encoding: chunked`
*/
public open val contentLength: Long? get() = null
/**
* Status code to set when sending this content
*/
public open val status: HttpStatusCode?
get() = null
/**
* Headers to set when sending this content
*/
public open val headers: Headers
get() = Headers.Empty
private var extensionProperties: Attributes? = null
/**
* Gets an extension property for this content
*/
public open fun <T : Any> getProperty(key: AttributeKey<T>): T? = extensionProperties?.getOrNull(key)
/**
* Sets an extension property for this content
*/
public open fun <T : Any> setProperty(key: AttributeKey<T>, value: T?) {
when {
value == null && extensionProperties == null -> return
value == null -> extensionProperties?.remove(key)
else -> (extensionProperties ?: Attributes()).also { extensionProperties = it }.put(key, value)
}
}
/**
* Trailers to set when sending this content, will be ignored if request is not in HTTP2 mode
*/
public open fun trailers(): Headers? = null
/**
* Variant of a [OutgoingContent] without a payload
*/
public abstract class NoContent : OutgoingContent()
/**
* Variant of a [OutgoingContent] with payload read from [ByteReadChannel]
*
*/
public abstract class ReadChannelContent : OutgoingContent() {
/**
* Provides [ByteReadChannel] for the content
*/
public abstract fun readFrom(): ByteReadChannel
/**
* Provides [ByteReadChannel] for the given range of the content
*/
@OptIn(DelicateCoroutinesApi::class)
public open fun readFrom(range: LongRange): ByteReadChannel = if (range.isEmpty()) {
ByteReadChannel.Empty
} else {
GlobalScope.writer(Dispatchers.Unconfined, autoFlush = true) {
val source = readFrom()
source.discard(range.start)
val limit = range.endInclusive - range.start + 1
source.copyTo(channel, limit)
}.channel
}
}
/**
* Variant of a [OutgoingContent] with payload written to [ByteWriteChannel]
*/
public abstract class WriteChannelContent : OutgoingContent() {
/**
* Receives [channel] provided by the engine and writes all data to it
*/
public abstract suspend fun writeTo(channel: ByteWriteChannel)
}
/**
* Variant of a [OutgoingContent] with payload represented as [ByteArray]
*/
public abstract class ByteArrayContent : OutgoingContent() {
/**
* Provides [ByteArray] which engine will send to peer
*/
public abstract fun bytes(): ByteArray
}
/**
* Variant of a [OutgoingContent] for upgrading an HTTP connection
*/
public abstract class ProtocolUpgrade : OutgoingContent() {
final override val status: HttpStatusCode
get() = HttpStatusCode.SwitchingProtocols
/**
* Upgrades an HTTP connection
* @param input is a [ByteReadChannel] for an upgraded connection
* @param output is a [ByteWriteChannel] for an upgraded connection
* @param engineContext is a [CoroutineContext] to execute non-blocking code, such as parsing or processing
* @param userContext is a [CoroutineContext] to execute user-provided callbacks or code potentially blocking
*/
public abstract suspend fun upgrade(
input: ByteReadChannel,
output: ByteWriteChannel,
engineContext: CoroutineContext,
userContext: CoroutineContext
): Job
}
}
| apache-2.0 | 9eb23363dd602b6fcca864698460bb0c | 31.170213 | 118 | 0.62963 | 5.028825 | false | false | false | false |
onnerby/musikcube | src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/shared/model/BaseSlidingWindow.kt | 2 | 3262 | package io.casey.musikcube.remote.ui.shared.model
import androidx.recyclerview.widget.RecyclerView
import com.simplecityapps.recyclerview_fastscroll.interfaces.OnFastScrollStateChangeListener
import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView
import io.casey.musikcube.remote.service.websocket.model.IMetadataProxy
import io.casey.musikcube.remote.service.websocket.model.ITrack
import io.casey.musikcube.remote.util.Debouncer
import io.reactivex.disposables.CompositeDisposable
abstract class BaseSlidingWindow(
private val recyclerView: FastScrollRecyclerView,
private val metadataProxy: IMetadataProxy) : ITrackListSlidingWindow
{
private var scrollState = RecyclerView.SCROLL_STATE_IDLE
private var fastScrollerActive = false
protected var disposables = CompositeDisposable()
protected var loadedListener: ITrackListSlidingWindow.OnMetadataLoadedListener? = null
protected var connected = false
protected class CacheEntry {
internal var value: ITrack? = null
internal var dirty: Boolean = false
}
final override var count = 0
protected set(count) {
field = count
invalidate()
notifyAdapterChanged()
notifyMetadataLoaded(0, 0)
}
override fun pause() {
connected = false
recyclerView.removeOnScrollListener(recyclerViewScrollListener)
disposables.dispose()
disposables = CompositeDisposable()
}
override fun resume() {
disposables.add(metadataProxy.observePlayQueue()
.subscribe({ requery() }, { /* error */ }))
recyclerView.setOnFastScrollStateChangeListener(fastScrollStateChangeListener)
recyclerView.addOnScrollListener(recyclerViewScrollListener)
connected = true
fastScrollerActive = false
}
override fun setOnMetadataLoadedListener(loadedListener: ITrackListSlidingWindow.OnMetadataLoadedListener) {
this.loadedListener = loadedListener
}
protected abstract fun invalidate()
protected abstract fun getPageAround(index: Int)
protected fun notifyAdapterChanged() =
adapterChangedDebouncer.call()
protected fun notifyMetadataLoaded(offset: Int, count: Int) =
loadedListener?.onMetadataLoaded(offset, count)
protected fun scrolling(): Boolean =
scrollState != RecyclerView.SCROLL_STATE_IDLE || fastScrollerActive
private val recyclerViewScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
scrollState = newState
if (!scrolling()) {
notifyAdapterChanged()
}
}
}
private val fastScrollStateChangeListener = object: OnFastScrollStateChangeListener {
override fun onFastScrollStop() {
fastScrollerActive = false
requery()
}
override fun onFastScrollStart() {
fastScrollerActive = true
}
}
private val adapterChangedDebouncer = object : Debouncer<String>(50) {
override fun onDebounced(last: String?) {
recyclerView.adapter?.notifyDataSetChanged()
}
}
}
| bsd-3-clause | 7ee954b4820fb772a279f26cb7f5005f | 34.075269 | 112 | 0.707235 | 5.510135 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/EXT_external_objects.kt | 4 | 13042 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val EXT_memory_object = "EXTMemoryObject".nativeClassGL("EXT_memory_object", postfix = EXT) {
documentation =
"""
Native bindings to the ${registryLink("EXT_external_objects")} extension.
The Vulkan API introduces the concept of explicit memory objects and reusable synchronization objects. This extension brings those concepts to the
OpenGL API via two new object types:
${ul(
"Memory objects",
"Semaphores"
)}
Rather than allocating memory as a response to object allocation, memory allocation and binding are two separate operations in Vulkan. This extension
allows an OpenGL application to import a Vulkan memory object, and to bind textures and/or buffer objects to it.
No methods to import memory objects are defined here. Separate platform-specific extensions are defined for this purpose.
Semaphores are synchronization primitives that can be waited on and signaled only by the GPU, or in GL terms, in the GL server. They are similar in
concept to GL's "sync" objects and EGL's "EGLSync" objects, but different enough that compatibilities between the two are difficult to derive.
Rather than attempt to map Vulkan semaphores on to GL/EGL sync objects to achieve interoperability, this extension introduces a new object, GL
semaphores, that map directly to the semantics of Vulkan semaphores. To achieve full image and buffer memory coherence with a Vulkan driver, the
commands that manipulate semaphores also allow external usage information to be imported and exported.
Requires ${GL42.core} or ${ARB_texture_storage.link}.
"""
IntConstant(
"""
Accepted by the {@code pname} parameter of TexParameter{ifx}{v}, TexParameterI{i ui}v, TextureParameter{if}{v}, TextureParameterI{i ui}v,
GetTexParameter{if}v, GetTexParameterI{i ui}v, GetTextureParameter{if}v, and GetTextureParameterI{i ui}v.
""",
"TEXTURE_TILING_EXT"..0x9580
)
IntConstant(
"Accepted by the {@code pname} parameter of #MemoryObjectParameterivEXT(), and #GetMemoryObjectParameterivEXT().",
"DEDICATED_MEMORY_OBJECT_EXT"..0x9581
)
IntConstant(
"Accepted by the {@code pname} parameter of GetInternalFormativ or GetInternalFormati64v.",
"NUM_TILING_TYPES_EXT"..0x9582,
"TILING_TYPES_EXT"..0x9583
)
IntConstant(
"""
Returned in the {@code params} parameter of GetInternalFormativ or GetInternalFormati64v when the {@code pname} parameter is #TILING_TYPES_EXT,
returned in the {@code params} parameter of GetTexParameter{if}v, GetTexParameterI{i ui}v, GetTextureParameter{if}v, and GetTextureParameterI{i ui}v
when the {@code pname} parameter is #TEXTURE_TILING_EXT, and accepted by the {@code params} parameter of TexParameter{ifx}{v}, TexParameterI{i ui}v,
TextureParameter{if}{v}, TextureParameterI{i ui}v when the {@code pname} parameter is #TEXTURE_TILING_EXT.
""",
"OPTIMAL_TILING_EXT"..0x9584,
"LINEAR_TILING_EXT"..0x9585
)
IntConstant(
"""
Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetFloatv, GetIntegerv, GetInteger64v, #GetUnsignedBytevEXT(), and the
{@code target} parameter of GetBooleani_v, GetIntegeri_v,GetFloati_v, GetDoublei_v, GetInteger64i_v, and #GetUnsignedBytei_vEXT().
""",
"NUM_DEVICE_UUIDS_EXT"..0x9596,
"DEVICE_UUID_EXT"..0x9597,
"DRIVER_UUID_EXT"..0x9598
)
IntConstant(
"Constant values.",
"UUID_SIZE_EXT".."16"
)
void(
"GetUnsignedBytevEXT",
"",
GLenum("pname", ""),
Unsafe..GLubyte.p("data", "")
)
void(
"GetUnsignedBytei_vEXT",
"",
GLenum("target", ""),
GLuint("index", ""),
Unsafe..GLubyte.p("data", "")
)
void(
"DeleteMemoryObjectsEXT",
"",
AutoSize("memoryObjects")..GLsizei("n", ""),
SingleValue("memoryObject")..GLuint.const.p("memoryObjects", "")
)
GLboolean(
"IsMemoryObjectEXT",
"",
GLuint("memoryObject", "")
)
void(
"CreateMemoryObjectsEXT",
"",
AutoSize("memoryObjects")..GLsizei("n", ""),
ReturnParam..GLuint.p("memoryObjects", "")
)
void(
"MemoryObjectParameterivEXT",
"",
GLuint("memoryObject", ""),
GLenum("pname", ""),
SingleValue("param")..Check(1)..GLint.const.p("params", "")
)
void(
"GetMemoryObjectParameterivEXT",
"",
GLuint("memoryObject", ""),
GLenum("pname", ""),
ReturnParam..Check(1)..GLint.p("params", "")
)
void(
"TexStorageMem2DEXT",
"",
GLenum("target", ""),
GLsizei("levels", ""),
GLenum("internalFormat", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLuint("memory", ""),
GLuint64("offset", "")
)
void(
"TexStorageMem2DMultisampleEXT",
"",
GLenum("target", ""),
GLsizei("samples", ""),
GLenum("internalFormat", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLboolean("fixedSampleLocations", ""),
GLuint("memory", ""),
GLuint64("offset", "")
)
void(
"TexStorageMem3DEXT",
"",
GLenum("target", ""),
GLsizei("levels", ""),
GLenum("internalFormat", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLsizei("depth", ""),
GLuint("memory", ""),
GLuint64("offset", "")
)
void(
"TexStorageMem3DMultisampleEXT",
"",
GLenum("target", ""),
GLsizei("samples", ""),
GLenum("internalFormat", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLsizei("depth", ""),
GLboolean("fixedSampleLocations", ""),
GLuint("memory", ""),
GLuint64("offset", "")
)
void(
"BufferStorageMemEXT",
"",
GLenum("target", ""),
GLsizeiptr("size", ""),
GLuint("memory", ""),
GLuint64("offset", "")
)
DependsOn("hasDSA(ext)")..void(
"TextureStorageMem2DEXT",
"",
GLuint("texture", ""),
GLsizei("levels", ""),
GLenum("internalFormat", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLuint("memory", ""),
GLuint64("offset", "")
)
DependsOn("hasDSA(ext)")..void(
"TextureStorageMem2DMultisampleEXT",
"",
GLuint("texture", ""),
GLsizei("samples", ""),
GLenum("internalFormat", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLboolean("fixedSampleLocations", ""),
GLuint("memory", ""),
GLuint64("offset", "")
)
DependsOn("hasDSA(ext)")..void(
"TextureStorageMem3DEXT",
"",
GLuint("texture", ""),
GLsizei("levels", ""),
GLenum("internalFormat", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLsizei("depth", ""),
GLuint("memory", ""),
GLuint64("offset", "")
)
DependsOn("hasDSA(ext)")..void(
"TextureStorageMem3DMultisampleEXT",
"",
GLuint("texture", ""),
GLsizei("samples", ""),
GLenum("internalFormat", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLsizei("depth", ""),
GLboolean("fixedSampleLocations", ""),
GLuint("memory", ""),
GLuint64("offset", "")
)
DependsOn("hasDSA(ext)")..void(
"NamedBufferStorageMemEXT",
"",
GLuint("buffer", ""),
GLsizeiptr("size", ""),
GLuint("memory", ""),
GLuint64("offset", "")
)
void(
"TexStorageMem1DEXT",
"",
GLenum("target", ""),
GLsizei("levels", ""),
GLenum("internalFormat", ""),
GLsizei("width", ""),
GLuint("memory", ""),
GLuint64("offset", "")
)
DependsOn("hasDSA(ext)")..void(
"TextureStorageMem1DEXT",
"",
GLuint("texture", ""),
GLsizei("levels", ""),
GLenum("internalFormat", ""),
GLsizei("width", ""),
GLuint("memory", ""),
GLuint64("offset", "")
)
}
val EXT_semaphore = "EXTSemaphore".nativeClassGL("EXT_semaphore", postfix = EXT) {
documentation =
"""
Native bindings to the ${registryLink("EXT_external_objects")} extension.
The Vulkan API introduces the concept of explicit memory objects and reusable synchronization objects. This extension brings those concepts to the
OpenGL API via two new object types:
${ul(
"Memory objects",
"Semaphores"
)}
Rather than allocating memory as a response to object allocation, memory allocation and binding are two separate operations in Vulkan. This extension
allows an OpenGL application to import a Vulkan memory object, and to bind textures and/or buffer objects to it.
No methods to import memory objects are defined here. Separate platform-specific extensions are defined for this purpose.
Semaphores are synchronization primitives that can be waited on and signaled only by the GPU, or in GL terms, in the GL server. They are similar in
concept to GL's "sync" objects and EGL's "EGLSync" objects, but different enough that compatibilities between the two are difficult to derive.
Rather than attempt to map Vulkan semaphores on to GL/EGL sync objects to achieve interoperability, this extension introduces a new object, GL
semaphores, that map directly to the semantics of Vulkan semaphores. To achieve full image and buffer memory coherence with a Vulkan driver, the
commands that manipulate semaphores also allow external usage information to be imported and exported.
"""
IntConstant(
"""
Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetFloatv, GetIntegerv, GetInteger64v, #GetUnsignedBytevEXT(), and the
{@code target} parameter of GetBooleani_v, GetIntegeri_v,GetFloati_v, GetDoublei_v, GetInteger64i_v, and #GetUnsignedBytei_vEXT().
""",
"NUM_DEVICE_UUIDS_EXT"..0x9596,
"DEVICE_UUID_EXT"..0x9597,
"DRIVER_UUID_EXT"..0x9598
)
IntConstant(
"Constant values.",
"UUID_SIZE_EXT".."16"
)
IntConstant(
"Accepted by the {@code dstLayouts} parameter of #SignalSemaphoreEXT() and the {@code srcLayouts} parameter of #WaitSemaphoreEXT().",
"LAYOUT_GENERAL_EXT"..0x958D,
"LAYOUT_COLOR_ATTACHMENT_EXT"..0x958E,
"LAYOUT_DEPTH_STENCIL_ATTACHMENT_EXT"..0x958F,
"LAYOUT_DEPTH_STENCIL_READ_ONLY_EXT"..0x9590,
"LAYOUT_SHADER_READ_ONLY_EXT"..0x9591,
"LAYOUT_TRANSFER_SRC_EXT"..0x9592,
"LAYOUT_TRANSFER_DST_EXT"..0x9593,
"LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_EXT"..0x9530,
"LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_EXT"..0x9531
)
reuse(EXT_memory_object, "GetUnsignedBytevEXT")
reuse(EXT_memory_object, "GetUnsignedBytei_vEXT")
void(
"GenSemaphoresEXT",
"",
AutoSize("semaphores")..GLsizei("n", ""),
ReturnParam..GLuint.p("semaphores", "")
)
void(
"DeleteSemaphoresEXT",
"",
AutoSize("semaphores")..GLsizei("n", ""),
SingleValue("semaphore")..GLuint.const.p("semaphores", "")
)
GLboolean(
"IsSemaphoreEXT",
"",
GLuint("semaphore", "")
)
void(
"SemaphoreParameterui64vEXT",
"",
GLuint("semaphore", ""),
GLenum("pname", ""),
SingleValue("param")..Check(1)..GLuint64.const.p("params", "")
)
void(
"GetSemaphoreParameterui64vEXT",
"",
GLuint("semaphore", ""),
GLenum("pname", ""),
ReturnParam..Check(1)..GLuint64.p("params", "")
)
void(
"WaitSemaphoreEXT",
"",
GLuint("semaphore", ""),
AutoSize("buffers")..GLuint("numBufferBarriers", ""),
GLuint.const.p("buffers", ""),
AutoSize("textures", "srcLayouts")..GLuint("numTextureBarriers", ""),
GLuint.const.p("textures", ""),
GLenum.const.p("srcLayouts", "")
)
void(
"SignalSemaphoreEXT",
"",
GLuint("semaphore", ""),
AutoSize("buffers")..GLuint("numBufferBarriers", ""),
GLuint.const.p("buffers", ""),
AutoSize("textures", "dstLayouts")..GLuint("numTextureBarriers", ""),
GLuint.const.p("textures", ""),
GLenum.const.p("dstLayouts", "")
)
} | bsd-3-clause | 9cbf8eee01ed98a75587c8632a15d6a4 | 29.617371 | 157 | 0.583883 | 4.52376 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.