repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
google/intellij-community | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/findUsages/KotlinFindUsagesSupport.kt | 2 | 3272 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.findUsages
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiConstructorCall
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.Processor
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
interface KotlinFindUsagesSupport {
companion object {
fun getInstance(project: Project): KotlinFindUsagesSupport = project.service()
val KtParameter.isDataClassComponentFunction: Boolean
get() = getInstance(project).isDataClassComponentFunction(this)
fun processCompanionObjectInternalReferences(
companionObject: KtObjectDeclaration,
referenceProcessor: Processor<PsiReference>
): Boolean =
getInstance(companionObject.project).processCompanionObjectInternalReferences(companionObject, referenceProcessor)
fun getTopMostOverriddenElementsToHighlight(target: PsiElement): List<PsiElement> =
getInstance(target.project).getTopMostOverriddenElementsToHighlight(target)
fun tryRenderDeclarationCompactStyle(declaration: KtDeclaration): String? =
getInstance(declaration.project).tryRenderDeclarationCompactStyle(declaration)
fun PsiReference.isConstructorUsage(ktClassOrObject: KtClassOrObject): Boolean {
fun isJavaConstructorUsage(): Boolean {
val call = element.getNonStrictParentOfType<PsiConstructorCall>()
return call == element.parent && call?.resolveConstructor()?.containingClass?.navigationElement == ktClassOrObject
}
return isJavaConstructorUsage() || getInstance(ktClassOrObject.project).isKotlinConstructorUsage(this, ktClassOrObject)
}
fun getSuperMethods(declaration: KtDeclaration, ignore: Collection<PsiElement>?) : List<PsiElement> =
getInstance(declaration.project).getSuperMethods(declaration, ignore)
fun sourcesAndLibraries(delegate: GlobalSearchScope, project: Project): GlobalSearchScope =
getInstance(project).sourcesAndLibraries(delegate, project)
}
fun processCompanionObjectInternalReferences(companionObject: KtObjectDeclaration, referenceProcessor: Processor<PsiReference>): Boolean
fun isDataClassComponentFunction(element: KtParameter): Boolean
fun getTopMostOverriddenElementsToHighlight(target: PsiElement): List<PsiElement>
fun tryRenderDeclarationCompactStyle(declaration: KtDeclaration): String?
fun isKotlinConstructorUsage(psiReference: PsiReference, ktClassOrObject: KtClassOrObject): Boolean
fun getSuperMethods(declaration: KtDeclaration, ignore: Collection<PsiElement>?) : List<PsiElement>
fun sourcesAndLibraries(delegate: GlobalSearchScope, project: Project): GlobalSearchScope
}
| apache-2.0 | d8bc3ecd7a0bb752842e23fc8839c8c7 | 47.835821 | 158 | 0.77934 | 5.593162 | false | false | false | false |
fluidsonic/fluid-json | coding/sources-jvm/implementations/AbstractJsonDecoderCodec.kt | 1 | 1291 | package io.fluidsonic.json
import java.lang.reflect.*
import kotlin.reflect.*
public abstract class AbstractJsonDecoderCodec<Value : Any, in Context : JsonCodingContext>(
private val additionalProviders: List<JsonCodecProvider<Context>> = emptyList(),
decodableType: JsonCodingType<Value>? = null
) : JsonDecoderCodec<Value, Context> {
@Suppress("UNCHECKED_CAST")
final override val decodableType: JsonCodingType<Value> = decodableType
?: JsonCodingType.of((this::class.java.genericSuperclass as ParameterizedType).actualTypeArguments[0]) as JsonCodingType<Value>
override fun <ActualValue : Any> decoderCodecForType(decodableType: JsonCodingType<ActualValue>): JsonDecoderCodec<ActualValue, Context>? {
var codec = super.decoderCodecForType(decodableType)
if (codec != null) {
return codec
}
for (provider in additionalProviders) {
codec = provider.decoderCodecForType(decodableType)
if (codec != null) {
return codec
}
}
return null
}
override fun <ActualValue : Any> encoderCodecForClass(encodableClass: KClass<ActualValue>): JsonEncoderCodec<ActualValue, Context>? {
for (provider in additionalProviders) {
val codec = provider.encoderCodecForClass(encodableClass)
if (codec != null) {
return codec
}
}
return null
}
}
| apache-2.0 | a10e860bbeac92b251a2293e3d745692 | 28.340909 | 140 | 0.754454 | 3.984568 | false | false | false | false |
allotria/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/GuiRobotHolder.kt | 10 | 937 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testGuiFramework.impl
import org.fest.swing.core.Robot
import org.fest.swing.core.SmartWaitRobot
object GuiRobotHolder {
@Volatile
private var myRobot: Robot? = null
val robot: Robot
get() {
if(myRobot == null)
synchronized(this) {
if(myRobot == null) initializeRobot()
}
return myRobot ?: throw IllegalStateException("Cannot initialize the robot")
}
private fun initializeRobot() {
if (myRobot != null) releaseRobot()
myRobot = SmartWaitRobot() // acquires ScreenLock
}
fun releaseRobot() {
if(myRobot != null) {
synchronized(this){
if (myRobot != null){
myRobot!!.cleanUpWithoutDisposingWindows() // releases ScreenLock
myRobot = null
}
}
}
}
} | apache-2.0 | 0dcd38ef0189197f606c45eabbcbf7b9 | 26.588235 | 140 | 0.652081 | 4.317972 | false | false | false | false |
mrbublos/vkm | app/src/main/java/vkm/vkm/PagerActivity.kt | 1 | 5984 | package vkm.vkm
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.view.View
import android.widget.BaseAdapter
import android.widget.ListView
import android.widget.SeekBar
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.lifecycle.Observer
import kotlinx.android.synthetic.main.pager_activity.*
import kotlinx.android.synthetic.main.pager_activity.view.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import vkm.vkm.utils.Composition
import vkm.vkm.utils.HttpUtils
import vkm.vkm.utils.db.Db
class PagerActivity : AppCompatActivity(), ServiceConnection {
var musicPlayer: MusicPlayService? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
HttpUtils.loadProxies(Db.instance(applicationContext).proxyDao())
DownloadManager.initialize(Db.instance(applicationContext).tracksDao())
savedInstanceState?.let {
State.currentSearchTab = it.getInt("currentSearchTab")
State.currentHistoryTab = it.getString("currentHistoryTab") ?: ""
}
setContentView(R.layout.pager_activity)
pager.adapter = PagerAdapter(supportFragmentManager)
pager.currentItem = 0
bindService(Intent(applicationContext, MusicPlayService::class.java), this, Context.BIND_AUTO_CREATE)
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
outState?.putInt("currentSearchTab", State.currentSearchTab)
outState?.putString("currentHistoryTab", State.currentHistoryTab)
HttpUtils.storeProxies(Db.instance(applicationContext).proxyDao())
}
override fun onDestroy() {
super.onDestroy()
HttpUtils.storeProxies(Db.instance(applicationContext).proxyDao())
unbindService(this)
}
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
musicPlayer = (service as MusicPlayService.MusicPlayerController).getService()
setupMusicService()
}
private fun setupMusicService() {
nextTrack.setOnClickListener { musicPlayer?.next() }
pause.setOnClickListener {
if (musicPlayer?.isPlaying() == true) {
musicPlayer?.pause()
} else {
musicPlayer?.play(musicPlayer?.displayedComposition?.value)
}
}
trackPlayingProgress.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
if (!fromUser) { return }
val duration = musicPlayer?.trackLength ?: 0
musicPlayer?.skipTo((progress * duration / 100).toInt())
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {}
override fun onStopTrackingTouch(seekBar: SeekBar?) {}
})
musicPlayer?.state?.observe(this, Observer { state ->
when (state) {
"playing" -> onPlayerPlay()
"stopped" -> onPlayerStop()
"paused" -> onPlayerPause()
else -> refreshList()
}
})
musicPlayer?.progress?.observe(this, Observer {
GlobalScope.launch(Dispatchers.Main) {
currentTrackPlaying.trackPlayingProgress.progress = it.toInt()
}
})
musicPlayer?.displayedComposition?.observe(this, Observer {
GlobalScope.launch(Dispatchers.Main) {
currentTrackPlaying?.name?.text = it.name
currentTrackPlaying?.name?.isSelected = true
currentTrackPlaying?.artist?.text = it.artist
currentTrackPlaying?.artist?.isSelected = true
}
})
}
private fun refreshList() {
GlobalScope.launch(Dispatchers.Main) {
((findViewById<ListView>(R.id.resultList))?.adapter as BaseAdapter?)?.notifyDataSetChanged()
}
}
private val onPlayerPlay: () -> Unit = {
GlobalScope.launch(Dispatchers.Main) {
currentTrackPlaying.visibility = View.VISIBLE
pause.setImageDrawable(applicationContext.getDrawable(R.drawable.ic_pause_player))
refreshList()
}
}
private val onPlayerStop: () -> Unit = {
GlobalScope.launch(Dispatchers.Main) {
currentTrackPlaying.visibility = View.VISIBLE
pause.setImageDrawable(applicationContext.getDrawable(R.drawable.ic_play_player))
refreshList()
}
}
private val onPlayerPause: () -> Unit = {
GlobalScope.launch(Dispatchers.Main) {
currentTrackPlaying.visibility = View.VISIBLE
pause.setImageDrawable(applicationContext.getDrawable(R.drawable.ic_play_player))
refreshList()
}
}
fun playNewTrack(list: List<Composition>, track: Composition) {
musicPlayer?.stop()
val newPlayList = mutableListOf<Composition>()
newPlayList.addAll(list)
musicPlayer?.playList = newPlayList
musicPlayer?.play(track)
refreshList()
}
override fun onServiceDisconnected(name: ComponentName?) {
musicPlayer = null
}
}
class PagerAdapter(fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) {
// Order: Search, History, Settings
override fun getItem(position: Int): Fragment {
return when (position % 3) {
1 -> HistoryFragment()
2 -> SettingsFragment()
else -> SearchFragment()
}
}
override fun getCount(): Int = 3
}
| gpl-3.0 | a7e1c961925ea126a223b26932655933 | 33.994152 | 109 | 0.66143 | 5.084112 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/compiler/asJava/lightClasses/nullabilityAnnotations/FileFacade.kt | 9 | 941 | // FileFacadeKt
import org.jetbrains.annotations.NotNull
import org.jetbrains.annotations.Nullable
fun notNull(a: String): String = ""
fun nullable(a: String?): String? = ""
@NotNull fun notNullWithNN(): String = ""
@Nullable fun notNullWithN(): String = ""
@Nullable fun nullableWithN(): String? = ""
@NotNull fun nullableWithNN(): String? = ""
val nullableVal: String? = { "" }()
var nullableVar: String? = { "" }()
val notNullVal: String = { "" }()
var notNullVar: String = { "" }()
val notNullValWithGet: String
@[Nullable] get() = ""
var notNullVarWithGetSet: String
@[Nullable] get() = ""
@[Nullable] set(v) {}
val nullableValWithGet: String?
@[NotNull] get() = ""
var nullableVarWithGetSet: String?
@NotNull get() = ""
@NotNull set(v) {}
private val privateNn: String = { "" }()
private val privateN: String? = { "" }()
private fun privateFun(a: String, b: String?): String? = null
// FIR_COMPARISON | apache-2.0 | 5353ac55e23270d5922e41edd279c59a | 23.789474 | 61 | 0.649309 | 3.472325 | false | false | false | false |
fabmax/kool | kool-core/src/jvmMain/kotlin/de/fabmax/kool/platform/gl/CompiledShader.kt | 1 | 17788 | package de.fabmax.kool.platform.gl
import de.fabmax.kool.pipeline.*
import de.fabmax.kool.pipeline.drawqueue.DrawCommand
import de.fabmax.kool.platform.Lwjgl3Context
import de.fabmax.kool.scene.MeshInstanceList
import de.fabmax.kool.scene.geometry.IndexedVertexList
import de.fabmax.kool.scene.geometry.PrimitiveType
import de.fabmax.kool.scene.geometry.Usage
import de.fabmax.kool.util.logE
import org.lwjgl.opengl.GL33.*
import org.lwjgl.system.MemoryStack
import org.lwjgl.system.MemoryUtil
class CompiledShader(val prog: Int, pipeline: Pipeline, val renderBackend: GlRenderBackend, val ctx: Lwjgl3Context) {
private val pipelineId = pipeline.pipelineHash.toLong()
private val attributes = mutableMapOf<String, VertexLayout.VertexAttribute>()
private val instanceAttributes = mutableMapOf<String, VertexLayout.VertexAttribute>()
private val uniformLocations = mutableMapOf<String, List<Int>>()
private val uboLayouts = mutableMapOf<String, ExternalBufferLayout>()
private val instances = mutableMapOf<Long, ShaderInstance>()
init {
pipeline.layout.vertices.bindings.forEach { bnd ->
bnd.vertexAttributes.forEach { attr ->
when (bnd.inputRate) {
InputRate.VERTEX -> attributes[attr.attribute.name] = attr
InputRate.INSTANCE -> instanceAttributes[attr.attribute.name] = attr
}
}
}
pipeline.layout.descriptorSets.forEach { set ->
set.descriptors.forEach { desc ->
when (desc) {
is UniformBuffer -> {
val blockIndex = glGetUniformBlockIndex(prog, desc.name)
if (blockIndex == GL_INVALID_INDEX) {
// descriptor does not describe an actual UBO but plain old uniforms...
desc.uniforms.forEach { uniformLocations[it.name] = listOf(glGetUniformLocation(prog, it.name)) }
} else {
setupUboLayout(desc, blockIndex)
}
}
is TextureSampler1d -> {
uniformLocations[desc.name] = getUniformLocations(desc.name, desc.arraySize)
}
is TextureSampler2d -> {
uniformLocations[desc.name] = getUniformLocations(desc.name, desc.arraySize)
}
is TextureSampler3d -> {
uniformLocations[desc.name] = getUniformLocations(desc.name, desc.arraySize)
}
is TextureSamplerCube -> {
uniformLocations[desc.name] = getUniformLocations(desc.name, desc.arraySize)
}
}
}
}
pipeline.layout.pushConstantRanges.forEach { pcr ->
pcr.pushConstants.forEach { pc ->
// in WebGL push constants are mapped to regular uniforms
uniformLocations[pc.name] = listOf(glGetUniformLocation(prog, pc.name))
}
}
}
private fun setupUboLayout(desc: UniformBuffer, blockIndex: Int) {
val bufferSize = glGetActiveUniformBlocki(prog, blockIndex, GL_UNIFORM_BLOCK_DATA_SIZE)
val indices = IntArray(desc.uniforms.size)
val offsets = IntArray(desc.uniforms.size)
MemoryStack.stackPush().use { stack ->
val uniformNames = desc.uniforms.map {
if (it.length > 1) { MemoryUtil.memASCII("${it.name}[0]") } else { MemoryUtil.memASCII(it.name) }
}.toTypedArray()
val namePointers = stack.pointers(*uniformNames)
glGetUniformIndices(prog, namePointers, indices)
glGetActiveUniformsiv(prog, indices, GL_UNIFORM_OFFSET, offsets)
}
val sortedOffsets = offsets.sorted()
val bufferPositions = Array(desc.uniforms.size) { i ->
val off = offsets[i]
val nextOffI = sortedOffsets.indexOf(off) + 1
val nextOff = if (nextOffI < sortedOffsets.size) sortedOffsets[nextOffI] else bufferSize
BufferPosition(off, nextOff - off)
}
glUniformBlockBinding(prog, blockIndex, desc.binding)
uboLayouts[desc.name] = ExternalBufferLayout(desc.uniforms, bufferPositions, bufferSize)
}
private fun getUniformLocations(name: String, arraySize: Int): List<Int> {
val locations = mutableListOf<Int>()
if (arraySize > 1) {
for (i in 0 until arraySize) {
locations += glGetUniformLocation(prog, "$name[$i]")
}
} else {
locations += glGetUniformLocation(prog, name)
}
return locations
}
fun use() {
glUseProgram(prog)
attributes.values.forEach { attr ->
for (i in 0 until attr.attribute.props.nSlots) {
val location = attr.location + i
glEnableVertexAttribArray(location)
glVertexAttribDivisor(location, 0)
}
}
instanceAttributes.values.forEach { attr ->
for (i in 0 until attr.attribute.props.nSlots) {
val location = attr.location + i
glEnableVertexAttribArray(location)
glVertexAttribDivisor(location, 1)
}
}
}
fun unUse() {
attributes.values.forEach { attr ->
for (i in 0 until attr.attribute.props.nSlots) {
glDisableVertexAttribArray(attr.location + i)
}
}
instanceAttributes.values.forEach { attr ->
for (i in 0 until attr.attribute.props.nSlots) {
glDisableVertexAttribArray(attr.location + i)
}
}
}
fun bindInstance(cmd: DrawCommand): ShaderInstance? {
val pipelineInst = cmd.pipeline!!
val inst = instances.getOrPut(pipelineInst.pipelineInstanceId) {
ShaderInstance(cmd.geometry, cmd.mesh.instances, pipelineInst)
}
return if (inst.bindInstance(cmd)) { inst } else { null }
}
fun destroyInstance(pipeline: Pipeline) {
instances.remove(pipeline.pipelineInstanceId)?.let {
it.destroyInstance()
ctx.engineStats.pipelineInstanceDestroyed(pipelineId)
}
}
fun isEmpty(): Boolean = instances.isEmpty()
fun destroy() {
ctx.engineStats.pipelineDestroyed(pipelineId)
glDeleteProgram(prog)
}
inner class ShaderInstance(var geometry: IndexedVertexList, val instances: MeshInstanceList?, val pipeline: Pipeline) {
private val pushConstants = mutableListOf<PushConstantRange>()
private val ubos = mutableListOf<UniformBuffer>()
private val textures1d = mutableListOf<TextureSampler1d>()
private val textures2d = mutableListOf<TextureSampler2d>()
private val textures3d = mutableListOf<TextureSampler3d>()
private val texturesCube = mutableListOf<TextureSamplerCube>()
private val mappings = mutableListOf<MappedUniform>()
private val attributeBinders = mutableListOf<AttributeOnLocation>()
private val instanceAttribBinders = mutableListOf<AttributeOnLocation>()
private var dataBufferF: BufferResource? = null
private var dataBufferI: BufferResource? = null
private var indexBuffer: BufferResource? = null
private var instanceBuffer: BufferResource? = null
private var uboBuffers = mutableListOf<BufferResource>()
private var buffersSet = false
private var nextTexUnit = GL_TEXTURE0
var numIndices = 0
var indexType = 0
var primitiveType = 0
init {
pipeline.layout.descriptorSets.forEach { set ->
set.descriptors.forEach { desc ->
when (desc) {
is UniformBuffer -> mapUbo(desc)
is TextureSampler1d -> mapTexture1d(desc)
is TextureSampler2d -> mapTexture2d(desc)
is TextureSampler3d -> mapTexture3d(desc)
is TextureSamplerCube -> mapTextureCube(desc)
}
}
}
pipeline.layout.pushConstantRanges.forEach { pc ->
mapPushConstants(pc)
}
ctx.engineStats.pipelineInstanceCreated(pipelineId)
}
private fun mapPushConstants(pc: PushConstantRange) {
pushConstants.add(pc)
pc.pushConstants.forEach { mappings += MappedUniform.mappedUniform(it, uniformLocations[it.name]!![0]) }
}
private fun mapUbo(ubo: UniformBuffer) {
ubos.add(ubo)
val uboLayout = uboLayouts[ubo.name]
if (uboLayout != null) {
mappings += MappedUbo(ubo, uboLayout)
} else {
ubo.uniforms.forEach {
val location = uniformLocations[it.name]
if (location != null) {
mappings += MappedUniform.mappedUniform(it, location[0])
} else {
logE { "Uniform location not present for uniform ${ubo.name}.${it.name}" }
}
}
}
}
private fun mapTexture1d(tex: TextureSampler1d) {
textures1d.add(tex)
uniformLocations[tex.name]?.let { locs ->
mappings += MappedUniformTex1d(tex, nextTexUnit, locs)
nextTexUnit += locs.size
}
}
private fun mapTexture2d(tex: TextureSampler2d) {
textures2d.add(tex)
uniformLocations[tex.name]?.let { locs ->
mappings += MappedUniformTex2d(tex, nextTexUnit, locs)
nextTexUnit += locs.size
}
}
private fun mapTexture3d(tex: TextureSampler3d) {
textures3d.add(tex)
uniformLocations[tex.name]?.let { locs ->
mappings += MappedUniformTex3d(tex, nextTexUnit, locs)
nextTexUnit += locs.size
}
}
private fun mapTextureCube(cubeMap: TextureSamplerCube) {
texturesCube.add(cubeMap)
uniformLocations[cubeMap.name]?.let { locs ->
mappings += MappedUniformTexCube(cubeMap, nextTexUnit, locs)
nextTexUnit += locs.size
}
}
fun bindInstance(drawCmd: DrawCommand): Boolean {
if (geometry !== drawCmd.geometry) {
geometry = drawCmd.geometry
destroyBuffers()
}
// call onUpdate callbacks
for (i in pipeline.onUpdate.indices) {
pipeline.onUpdate[i].invoke(drawCmd)
}
for (i in pushConstants.indices) {
pushConstants[i].onUpdate?.invoke(pushConstants[i], drawCmd)
}
for (i in ubos.indices) {
ubos[i].onUpdate?.invoke(ubos[i], drawCmd)
}
for (i in textures1d.indices) {
textures1d[i].onUpdate?.invoke(textures1d[i], drawCmd)
}
for (i in textures2d.indices) {
textures2d[i].onUpdate?.invoke(textures2d[i], drawCmd)
}
for (i in textures3d.indices) {
textures3d[i].onUpdate?.invoke(textures3d[i], drawCmd)
}
for (i in texturesCube.indices) {
texturesCube[i].onUpdate?.invoke(texturesCube[i], drawCmd)
}
// update buffers (vertex data, instance data, UBOs)
checkBuffers()
// bind uniform values
var uniformsValid = true
for (i in mappings.indices) {
uniformsValid = uniformsValid && mappings[i].setUniform(ctx)
}
if (uniformsValid) {
// bind vertex data
indexBuffer?.bind()
attributeBinders.forEach { it.vbo.bindAttribute(it.loc) }
instanceAttribBinders.forEach { it.vbo.bindAttribute(it.loc) }
}
return uniformsValid
}
private fun destroyBuffers() {
attributeBinders.clear()
instanceAttribBinders.clear()
dataBufferF?.delete(ctx)
dataBufferI?.delete(ctx)
indexBuffer?.delete(ctx)
instanceBuffer?.delete(ctx)
uboBuffers.forEach { it.delete(ctx) }
dataBufferF = null
dataBufferI = null
indexBuffer = null
instanceBuffer = null
buffersSet = false
uboBuffers.clear()
}
fun destroyInstance() {
destroyBuffers()
pushConstants.clear()
ubos.clear()
textures1d.clear()
textures2d.clear()
textures3d.clear()
texturesCube.clear()
mappings.clear()
}
private fun checkBuffers() {
val md = geometry
if (indexBuffer == null) {
indexBuffer = BufferResource(GL_ELEMENT_ARRAY_BUFFER)
mappings.filterIsInstance<MappedUbo>().forEach { mappedUbo ->
val uboBuffer = BufferResource(GL_UNIFORM_BUFFER)
uboBuffers += uboBuffer
mappedUbo.uboBuffer = uboBuffer
}
}
var hasIntData = false
if (dataBufferF == null) {
dataBufferF = BufferResource(GL_ARRAY_BUFFER)
for (vertexAttrib in md.vertexAttributes) {
if (vertexAttrib.type.isInt) {
hasIntData = true
} else {
val stride = md.byteStrideF
val offset = md.attributeByteOffsets[vertexAttrib]!! / 4
attributeBinders += attributes.makeAttribBinders(vertexAttrib, dataBufferF!!, stride, offset)
}
}
}
if (hasIntData && dataBufferI == null) {
dataBufferI = BufferResource(GL_ARRAY_BUFFER)
for (vertexAttrib in md.vertexAttributes) {
if (vertexAttrib.type.isInt) {
attributes[vertexAttrib.name]?.let { attr ->
val vbo = VboBinder(dataBufferI!!, vertexAttrib.type.byteSize / 4,
md.byteStrideI, md.attributeByteOffsets[vertexAttrib]!! / 4, GL_INT)
attributeBinders += AttributeOnLocation(vbo, attr.location)
}
}
}
}
val instanceList = instances
if (instanceList != null) {
var instBuf = instanceBuffer
var isNewlyCreated = false
if (instBuf == null) {
instBuf = BufferResource(GL_ARRAY_BUFFER)
instanceBuffer = instBuf
isNewlyCreated = true
for (instanceAttrib in instanceList.instanceAttributes) {
val stride = instanceList.strideBytesF
val offset = instanceList.attributeOffsets[instanceAttrib]!! / 4
instanceAttribBinders += instanceAttributes.makeAttribBinders(instanceAttrib, instanceBuffer!!, stride, offset)
}
}
if (instanceList.hasChanged || isNewlyCreated) {
instBuf.setData(instanceList.dataF, instanceList.usage.glUsage(), ctx)
renderBackend.afterRenderActions += { instanceList.hasChanged = false }
}
}
if (!md.isBatchUpdate && (md.hasChanged || !buffersSet)) {
val usage = md.usage.glUsage()
indexType = GL_UNSIGNED_INT
indexBuffer?.setData(md.indices, usage, ctx)
primitiveType = pipeline.layout.vertices.primitiveType.glElemType()
numIndices = md.numIndices
dataBufferF?.setData(md.dataF, usage, ctx)
dataBufferI?.setData(md.dataI, usage, ctx)
// fixme: data buffers should be bound to mesh, not to shader instance
// if mesh is rendered multiple times (e.g. by additional shadow passes), clearing
// hasChanged flag early results in buffers not being updated
renderBackend.afterRenderActions += { md.hasChanged = false }
buffersSet = true
}
}
}
private fun Map<String, VertexLayout.VertexAttribute>.makeAttribBinders(attr: Attribute, buffer: BufferResource, stride: Int, offset: Int): List<AttributeOnLocation> {
val binders = mutableListOf<AttributeOnLocation>()
get(attr.name)?.let { vertAttr ->
for (i in 0 until attr.props.nSlots) {
val off = offset + attr.props.glAttribSize * i
val vbo = VboBinder(buffer, attr.props.glAttribSize, stride, off, GL_FLOAT)
binders += AttributeOnLocation(vbo, vertAttr.location + i)
}
}
return binders
}
private fun PrimitiveType.glElemType(): Int {
return when (this) {
PrimitiveType.LINES -> GL_LINES
PrimitiveType.POINTS -> GL_POINTS
PrimitiveType.TRIANGLES -> GL_TRIANGLES
}
}
private fun Usage.glUsage(): Int {
return when (this) {
Usage.DYNAMIC -> GL_DYNAMIC_DRAW
Usage.STATIC -> GL_STATIC_DRAW
}
}
private data class AttributeOnLocation(val vbo: VboBinder, val loc: Int)
} | apache-2.0 | 2f8ae0df45336c3a027a9359c5f4b619 | 39.707094 | 171 | 0.562683 | 4.877434 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/reactive/nodes/Button.kt | 1 | 759 | package com.cout970.reactive.nodes
import com.cout970.reactive.core.RBuilder
import com.cout970.reactive.core.RDescriptor
import org.liquidengine.legui.component.Button
import org.liquidengine.legui.component.Component
data class ButtonDescriptor(private val text: String) : RDescriptor {
override fun mapToComponent(): Component = Button().apply { textState.text = text; }
}
class ButtonBuilder(var text: String = "") : RBuilder() {
override fun toDescriptor(): RDescriptor = ButtonDescriptor(text)
}
fun RBuilder.button(text: String = "", key: String? = null, block: ButtonBuilder.() -> Unit = {}) =
+ButtonBuilder(text).apply(block).build(key)
fun ButtonBuilder.style(func: Button.() -> Unit) {
deferred = { (it as Button).func() }
} | gpl-3.0 | a55f842db6771007a15c28f7afc08eef | 32.043478 | 99 | 0.731225 | 3.795 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/dialogs/YearPickerDialog.kt | 1 | 2130 | package io.github.feelfreelinux.wykopmobilny.ui.dialogs
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.Window
import io.github.feelfreelinux.wykopmobilny.R
import kotlinx.android.synthetic.main.year_picker.view.*
import java.util.Calendar
class YearPickerDialog : androidx.fragment.app.DialogFragment() {
companion object {
const val RESULT_CODE = 167
const val EXTRA_YEAR = "EXTRA_YEAR"
fun newInstance(selectedYear: Int = 0): YearPickerDialog {
val intent = YearPickerDialog()
val arguments = Bundle()
arguments.putInt(EXTRA_YEAR, selectedYear)
intent.arguments = arguments
return intent
}
}
private val currentYear = Calendar.getInstance().get(Calendar.YEAR)
private var yearSelection = currentYear
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialogBuilder = AlertDialog.Builder(context)
val argumentYear = arguments!!.getInt(EXTRA_YEAR)
yearSelection = if (argumentYear == 0) currentYear else argumentYear
val dialogView = View.inflate(context, R.layout.year_picker, null)
dialogBuilder.apply {
setPositiveButton(android.R.string.ok) { _, _ ->
val data = Intent()
data.putExtra(EXTRA_YEAR, yearSelection)
targetFragment?.onActivityResult(targetRequestCode, RESULT_CODE, data)
}
setView(dialogView)
}
val newDialog = dialogBuilder.create()
newDialog.window?.requestFeature(Window.FEATURE_NO_TITLE)
dialogView.apply {
yearPicker.minValue = 2006
yearPicker.maxValue = currentYear
yearPicker.value = yearSelection
yearTextView.text = yearSelection.toString()
yearPicker.setOnValueChangedListener { _, _, year ->
yearSelection = year
yearTextView.text = year.toString()
}
}
return newDialog
}
} | mit | 70a1d655481d9970a0ecb2594b244cc1 | 34.516667 | 86 | 0.653521 | 4.919169 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/script/ScriptConfigurationManager.kt | 1 | 6432 | // 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.core.script
import com.intellij.openapi.components.service
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.io.URLUtil
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.core.script.configuration.CompositeScriptConfigurationManager
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.UserDataProperty
import org.jetbrains.kotlin.scripting.definitions.ScriptDependenciesProvider
import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationResult
import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper
import org.jetbrains.kotlin.utils.addToStdlib.cast
import java.io.File
import java.nio.file.Path
import kotlin.io.path.isDirectory
import kotlin.io.path.isRegularFile
import kotlin.io.path.notExists
import kotlin.io.path.pathString
import kotlin.script.experimental.api.asSuccess
import kotlin.script.experimental.api.makeFailureResult
// NOTE: this service exists exclusively because ScriptDependencyManager
// cannot be registered as implementing two services (state would be duplicated)
class IdeScriptDependenciesProvider(project: Project) : ScriptDependenciesProvider(project) {
override fun getScriptConfigurationResult(file: KtFile): ScriptCompilationConfigurationResult? {
val configuration = getScriptConfiguration(file)
val reports = IdeScriptReportSink.getReports(file)
if (configuration == null && reports.isNotEmpty()) {
return makeFailureResult(reports)
}
return configuration?.asSuccess(reports)
}
override fun getScriptConfiguration(file: KtFile): ScriptCompilationConfigurationWrapper? {
return ScriptConfigurationManager.getInstance(project).getConfiguration(file)
}
}
/**
* Facade for loading and caching Kotlin script files configuration.
*
* This service also starts indexing of new dependency roots and runs highlighting
* of opened files when configuration will be loaded or updated.
*/
interface ScriptConfigurationManager {
fun loadPlugins()
/**
* Get cached configuration for [file] or load it.
* May return null even configuration was loaded but was not yet applied.
*/
fun getConfiguration(file: KtFile): ScriptCompilationConfigurationWrapper?
@Deprecated("Use getScriptClasspath(KtFile) instead")
fun getScriptClasspath(file: VirtualFile): List<VirtualFile>
/**
* @see [getConfiguration]
*/
fun getScriptClasspath(file: KtFile): List<VirtualFile>
/**
* Check if configuration is already cached for [file] (in cache or FileAttributes).
* The result may be true, even cached configuration is considered out-of-date.
*
* Supposed to be used to switch highlighting off for scripts without configuration
* to avoid all file being highlighted in red.
*/
fun hasConfiguration(file: KtFile): Boolean
/**
* returns true when there is no configuration and highlighting should be suspended
*/
fun isConfigurationLoadingInProgress(file: KtFile): Boolean
/**
* Update caches that depends on script definitions and do update if necessary
*/
fun updateScriptDefinitionReferences()
///////////////
// classpath roots info:
fun getScriptSdk(file: VirtualFile): Sdk?
fun getFirstScriptsSdk(): Sdk?
fun getScriptDependenciesClassFilesScope(file: VirtualFile): GlobalSearchScope
fun getAllScriptsDependenciesClassFilesScope(): GlobalSearchScope
fun getAllScriptDependenciesSourcesScope(): GlobalSearchScope
fun getAllScriptsDependenciesClassFiles(): Collection<VirtualFile>
fun getAllScriptDependenciesSources(): Collection<VirtualFile>
companion object {
fun getServiceIfCreated(project: Project): ScriptConfigurationManager? = project.serviceIfCreated()
@JvmStatic
fun getInstance(project: Project): ScriptConfigurationManager = project.service()
@JvmStatic
fun compositeScriptConfigurationManager(project: Project) =
getInstance(project).cast<CompositeScriptConfigurationManager>()
fun toVfsRoots(roots: Iterable<File>): List<VirtualFile> = roots.mapNotNull { classpathEntryToVfs(it.toPath()) }
// TODO: report this somewhere, but do not throw: assert(res != null, { "Invalid classpath entry '$this': exists: ${exists()}, is directory: $isDirectory, is file: $isFile" })
fun classpathEntryToVfs(path: Path): VirtualFile? = when {
path.notExists() -> null
path.isDirectory() -> StandardFileSystems.local()?.findFileByPath(path.pathString)
path.isRegularFile() -> StandardFileSystems.jar()?.findFileByPath(path.pathString + URLUtil.JAR_SEPARATOR)
else -> null
}
@TestOnly
fun updateScriptDependenciesSynchronously(file: PsiFile) {
// TODO: review the usages of this method
defaultScriptingSupport(file.project).updateScriptDependenciesSynchronously(file)
}
private fun defaultScriptingSupport(project: Project) =
compositeScriptConfigurationManager(project).default
@TestOnly
fun clearCaches(project: Project) {
defaultScriptingSupport(project).updateScriptDefinitionsReferences()
}
fun clearManualConfigurationLoadingIfNeeded(file: VirtualFile) {
if (file.LOAD_CONFIGURATION_MANUALLY == true) {
file.LOAD_CONFIGURATION_MANUALLY = null
}
}
fun markFileWithManualConfigurationLoading(file: VirtualFile) {
file.LOAD_CONFIGURATION_MANUALLY = true
}
fun isManualConfigurationLoading(file: VirtualFile): Boolean = file.LOAD_CONFIGURATION_MANUALLY ?: false
private var VirtualFile.LOAD_CONFIGURATION_MANUALLY: Boolean? by UserDataProperty(Key.create<Boolean>("MANUAL_CONFIGURATION_LOADING"))
}
}
| apache-2.0 | dc07f85b925914df1436dc4f5de12603 | 41.039216 | 183 | 0.744869 | 5.178744 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/GradleConfiguratorTest.kt | 1 | 27348 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeInsight.gradle
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.Notification
import com.intellij.notification.Notifications
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.task.TaskData
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.roots.DependencyScope
import com.intellij.openapi.roots.ExternalLibraryDescriptor
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.StringUtil
import com.intellij.testFramework.runInEdtAndWait
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.configuration.*
import org.jetbrains.kotlin.idea.configuration.notifications.LAST_BUNDLED_KOTLIN_COMPILER_VERSION_PROPERTY_NAME
import org.jetbrains.kotlin.idea.configuration.notifications.showNewKotlinCompilerAvailableNotificationIfNeeded
import org.jetbrains.kotlin.idea.gradleJava.configuration.KotlinGradleModuleConfigurator
import org.jetbrains.kotlin.idea.gradleJava.configuration.KotlinJsGradleModuleConfigurator
import org.jetbrains.kotlin.idea.gradleJava.configuration.KotlinWithGradleConfigurator
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.plugins.gradle.execution.test.runner.GradleTestTasksProvider
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverUtil
import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions
import org.jetbrains.plugins.gradle.util.GradleConstants
import org.junit.Ignore
import org.junit.Test
import java.util.concurrent.atomic.AtomicInteger
class GradleConfiguratorTest : KotlinGradleImportingTestCase() {
@Test
fun testProjectWithModule() {
val propertyKey = LAST_BUNDLED_KOTLIN_COMPILER_VERSION_PROPERTY_NAME
val propertiesComponent = PropertiesComponent.getInstance()
val kotlinVersion = KotlinPluginLayout.instance.standaloneCompilerVersion
val notificationText = KotlinBundle.message(
"kotlin.external.compiler.updates.notification.content.0",
kotlinVersion.kotlinVersion
)
val counter = AtomicInteger(0)
val myDisposable = Disposer.newDisposable()
try {
val connection = myProject.messageBus.connect(myDisposable)
connection.subscribe(Notifications.TOPIC, object : Notifications {
override fun notify(notification: Notification) {
counter.incrementAndGet()
assertEquals(notificationText, notification.content)
}
})
propertiesComponent.unsetValue(propertyKey)
assertFalse(propertiesComponent.isValueSet(propertyKey))
connection.deliverImmediately()
assertEquals(0, counter.get())
importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
// Create not configured build.gradle for project
myProject.guessProjectDir()!!.createChildData(null, "build.gradle")
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val moduleGroup = module.toModuleGroup()
// We have a Kotlin runtime in build.gradle but not in the classpath, so it doesn't make sense
// to suggest configuring it
assertEquals(ConfigureKotlinStatus.BROKEN, findGradleModuleConfigurator().getStatus(moduleGroup))
// Don't offer the JS configurator if the JVM configuration exists but is broken
assertEquals(ConfigureKotlinStatus.BROKEN, findJsGradleModuleConfigurator().getStatus(moduleGroup))
}
}
assertEquals(
IdeKotlinVersion.get("1.3.70"),
findLatestExternalKotlinCompilerVersion(myProject)
)
val expectedCountAfter = if (kotlinVersion.isRelease) 1 else 0
connection.deliverImmediately() // the first notification from import action
assertEquals(expectedCountAfter, counter.get())
showNewKotlinCompilerAvailableNotificationIfNeeded(myProject)
connection.deliverImmediately()
showNewKotlinCompilerAvailableNotificationIfNeeded(myProject)
showNewKotlinCompilerAvailableNotificationIfNeeded(myProject)
connection.deliverImmediately()
assertEquals(expectedCountAfter, counter.get())
if (kotlinVersion.isRelease) {
assertTrue(propertiesComponent.isValueSet(propertyKey))
} else {
assertFalse(propertiesComponent.isValueSet(propertyKey))
}
} finally {
propertiesComponent.unsetValue(propertyKey)
Disposer.dispose(myDisposable)
}
}
@Test
fun testConfigure10() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.0.6"), collector)
checkFiles(files)
}
}
}
@Test
fun testConfigureKotlinWithPluginsBlock() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.0.6"), collector)
checkFiles(files)
}
}
}
@Test
fun testConfigureKotlinDevVersion() {
val files = importProjectFromTestData()
runInEdtAndWait {
myTestFixture.project.executeWriteCommand("") {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.60-dev-286"), collector)
checkFiles(files)
}
}
}
@Test
fun testConfigureGradleKtsKotlinDevVersion() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.60-dev-286"), collector)
checkFiles(files)
}
}
}
@Test
@TargetVersions("4.4+")
fun testConfigureJvmWithBuildGradle() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.40"), collector)
checkFiles(files)
}
}
}
@Test
@TargetVersions("4.4+")
fun testConfigureJvmWithBuildGradleKts() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.40"), collector)
checkFiles(files)
}
}
}
@Test
@TargetVersions("4.4+")
fun testConfigureJvmEAPWithBuildGradle() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.40-eap-62"), collector)
checkFiles(files)
}
}
}
@Test
@TargetVersions("4.4+")
fun testConfigureJvmEAPWithBuildGradleKts() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.40-eap-62"), collector)
checkFiles(files)
}
}
}
@Test
@TargetVersions("4.4+")
fun testConfigureJsWithBuildGradle() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findJsGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.40"), collector)
checkFiles(files)
}
}
}
@Test
@TargetVersions("4.4+")
fun testConfigureJsWithBuildGradleKts() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findJsGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.40"), collector)
checkFiles(files)
}
}
}
@Test
@TargetVersions("4.4+")
fun testConfigureJsEAPWithBuildGradle() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findJsGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.40-eap-62"), collector)
checkFiles(files)
}
}
}
@Test
@TargetVersions("4.4+")
fun testConfigureJsEAPWithBuildGradleKts() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findJsGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.2.40-eap-62"), collector)
checkFiles(files)
}
}
}
private fun findGradleModuleConfigurator(): KotlinGradleModuleConfigurator {
return KotlinProjectConfigurator.EP_NAME.findExtensionOrFail(KotlinGradleModuleConfigurator::class.java)
}
private fun findJsGradleModuleConfigurator(): KotlinJsGradleModuleConfigurator {
return KotlinProjectConfigurator.EP_NAME.findExtensionOrFail(KotlinJsGradleModuleConfigurator::class.java)
}
@Test
fun testConfigureGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
myTestFixture.project.executeWriteCommand("") {
val module = ModuleManager.getInstance(myProject).findModuleByName("project.app")!!
val configurator = findGradleModuleConfigurator()
val collector = createConfigureKotlinNotificationCollector(myProject)
configurator.configureWithVersion(myProject, listOf(module), IdeKotlinVersion.get("1.1.2"), collector)
checkFiles(files)
}
}
}
@Test
fun testListNonConfiguredModules() {
importProjectFromTestData()
runReadAction {
val configurator = findGradleModuleConfigurator()
val (modules, ableToRunConfigurators) = getConfigurationPossibilitiesForConfigureNotification(myProject)
assertTrue(ableToRunConfigurators.any { it is KotlinGradleModuleConfigurator })
assertTrue(ableToRunConfigurators.any { it is KotlinJsGradleModuleConfigurator })
val moduleNames = modules.map { it.baseModule.name }
assertSameElements(moduleNames, "project.app")
val moduleNamesFromConfigurator = getCanBeConfiguredModules(myProject, configurator).map { it.name }
assertSameElements(moduleNamesFromConfigurator, "project.app")
val moduleNamesWithKotlinFiles = getCanBeConfiguredModulesWithKotlinFiles(myProject, configurator).map { it.name }
assertSameElements(moduleNamesWithKotlinFiles, "project.app")
}
}
@Test
fun testListNonConfiguredModulesConfigured() {
importProjectFromTestData()
runReadAction {
assertEmpty(getConfigurationPossibilitiesForConfigureNotification(myProject).first)
}
}
@Test
fun testListNonConfiguredModulesConfiguredWithImplementation() {
importProjectFromTestData()
runReadAction {
assertEmpty(getConfigurationPossibilitiesForConfigureNotification(myProject).first)
}
}
@Test
fun testListNonConfiguredModulesConfiguredOnlyTest() {
importProjectFromTestData()
runReadAction {
assertEmpty(getConfigurationPossibilitiesForConfigureNotification(myProject).first)
}
}
@Ignore
@Test
fun testTestTasksAreImported() {
importProjectFromTestData()
@Suppress("DEPRECATION")
val testTasks = getTasksToRun(myTestFixture.module)
assertTrue("There should be at least one test task", testTasks.isNotEmpty())
}
@Deprecated("restored from org.jetbrains.plugins.gradle.execution.test.runner.GradleTestRunConfigurationProducer#getTasksToRun")
fun getTasksToRun(module: Module): List<String> {
for (provider in GradleTestTasksProvider.EP_NAME.extensions) {
val tasks = provider.getTasks(module)
if (!ContainerUtil.isEmpty(tasks)) {
return tasks
}
}
val externalProjectId = ExternalSystemApiUtil.getExternalProjectId(module)
?: return ContainerUtil.emptyList()
val projectPath = ExternalSystemApiUtil.getExternalProjectPath(module)
?: return ContainerUtil.emptyList()
val externalProjectInfo =
ExternalSystemUtil.getExternalProjectInfo(module.project, GradleConstants.SYSTEM_ID, projectPath)
?: return ContainerUtil.emptyList()
val tasks: List<String>
val gradlePath = GradleProjectResolverUtil.getGradlePath(module)
?: return ContainerUtil.emptyList()
val taskPrefix = if (StringUtil.endsWithChar(gradlePath, ':')) gradlePath else "$gradlePath:"
val moduleNode = GradleProjectResolverUtil.findModule(externalProjectInfo.externalProjectStructure, projectPath)
?: return ContainerUtil.emptyList()
val taskNode: DataNode<TaskData>?
val sourceSetId = StringUtil.substringAfter(externalProjectId, moduleNode.data.externalName + ':')
taskNode = if (sourceSetId == null) {
ExternalSystemApiUtil.find(
moduleNode, ProjectKeys.TASK
) { node: DataNode<TaskData> ->
node.data.isTest &&
StringUtil.equals(
"test",
node.data.name
) || StringUtil.equals(taskPrefix + "test", node.data.name)
}
} else {
ExternalSystemApiUtil.find(
moduleNode, ProjectKeys.TASK
) { node: DataNode<TaskData> ->
node.data.isTest && StringUtil.startsWith(node.data.name, sourceSetId)
}
}
if (taskNode == null) return ContainerUtil.emptyList()
val taskName = StringUtil.trimStart(taskNode.data.name, taskPrefix)
tasks = listOf(taskName)
return ContainerUtil.map(
tasks
) { task: String -> taskPrefix + task }
}
@Test
fun testAddNonKotlinLibraryGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
myTestFixture.project.executeWriteCommand("") {
KotlinWithGradleConfigurator.addKotlinLibraryToModule(
myTestFixture.module,
DependencyScope.COMPILE,
object : ExternalLibraryDescriptor("org.a.b", "lib", "1.0.0", "1.0.0") {
override fun getLibraryClassesRoots() = emptyList<String>()
})
}
checkFiles(files)
}
}
@Test
fun testAddTestLibraryGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
myTestFixture.project.executeWriteCommand("") {
KotlinWithGradleConfigurator.addKotlinLibraryToModule(
myTestFixture.module,
DependencyScope.TEST,
object : ExternalLibraryDescriptor("junit", "junit", "4.12", "4.12") {
override fun getLibraryClassesRoots() = emptyList<String>()
})
KotlinWithGradleConfigurator.addKotlinLibraryToModule(
myTestFixture.module,
DependencyScope.TEST,
object : ExternalLibraryDescriptor("org.jetbrains.kotlin", "kotlin-test", "1.1.2", "1.1.2") {
override fun getLibraryClassesRoots() = emptyList<String>()
})
}
checkFiles(files)
}
}
@Test
fun testAddLibraryGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
myTestFixture.project.executeWriteCommand("") {
KotlinWithGradleConfigurator.addKotlinLibraryToModule(
myTestFixture.module,
DependencyScope.COMPILE,
object : ExternalLibraryDescriptor("org.jetbrains.kotlin", "kotlin-reflect", "1.0.0", "1.0.0") {
override fun getLibraryClassesRoots() = emptyList<String>()
})
}
checkFiles(files)
}
}
@Test
fun testAddLanguageVersion() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeLanguageVersion(myTestFixture.module, "1.1", null, false)
}
checkFiles(files)
}
}
@Test
fun testAddLanguageVersionGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeLanguageVersion(myTestFixture.module, "1.1", null, false)
}
checkFiles(files)
}
}
@Test
fun testChangeLanguageVersion() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeLanguageVersion(myTestFixture.module, "1.1", null, false)
}
checkFiles(files)
}
}
@Test
fun testChangeLanguageVersionGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeLanguageVersion(myTestFixture.module, "1.1", null, false)
}
checkFiles(files)
}
}
@Test
fun testAddLibrary() {
val files = importProjectFromTestData()
runInEdtAndWait {
myTestFixture.project.executeWriteCommand("") {
KotlinWithGradleConfigurator.addKotlinLibraryToModule(
myTestFixture.module,
DependencyScope.COMPILE,
object : ExternalLibraryDescriptor("org.jetbrains.kotlin", "kotlin-reflect", "1.0.0", "1.0.0") {
override fun getLibraryClassesRoots() = emptyList<String>()
})
}
checkFiles(files)
}
}
@Test
fun testChangeFeatureSupport() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeFeatureConfiguration(
myTestFixture.module, LanguageFeature.InlineClasses, LanguageFeature.State.ENABLED, false
)
}
checkFiles(files)
}
}
@Test
@TargetVersions("4.7+")
fun testChangeFeatureSupportWithXFlag() = testChangeFeatureSupport()
@Test
fun testDisableFeatureSupport() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeFeatureConfiguration(
myTestFixture.module, LanguageFeature.InlineClasses, LanguageFeature.State.DISABLED, false
)
}
checkFiles(files)
}
}
@Test
@TargetVersions("4.7+")
fun testDisableFeatureSupportWithXFlag() = testDisableFeatureSupport()
@Test
fun testEnableFeatureSupport() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeFeatureConfiguration(
myTestFixture.module, LanguageFeature.InlineClasses, LanguageFeature.State.ENABLED, false
)
}
checkFiles(files)
}
}
@Test
@TargetVersions("4.7+")
@JvmName("testEnableFeatureSupportWithXFlag")
fun testEnableFeatureSupportWithXFlag() = testEnableFeatureSupport()
@Test
fun testEnableFeatureSupportToExistentArguments() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeFeatureConfiguration(
myTestFixture.module, LanguageFeature.InlineClasses, LanguageFeature.State.ENABLED, false
)
}
checkFiles(files)
}
}
@Test
fun testEnableFeatureSupportGSKWithoutFoundKotlinVersion() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeFeatureConfiguration(
myTestFixture.module, LanguageFeature.InlineClasses, LanguageFeature.State.ENABLED, false
)
}
checkFiles(files)
}
}
@TargetVersions("4.7+")
@Test
fun testEnableFeatureSupportToExistentArgumentsWithXFlag() = testEnableFeatureSupportToExistentArguments()
@Test
fun testChangeFeatureSupportGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeFeatureConfiguration(
myTestFixture.module, LanguageFeature.InlineClasses, LanguageFeature.State.DISABLED, false
)
}
checkFiles(files)
}
}
@Test
@TargetVersions("4.7+")
fun testChangeFeatureSupportGSKWithXFlag() = testChangeFeatureSupportGSK()
@Test
fun testDisableFeatureSupportGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeFeatureConfiguration(
myTestFixture.module, LanguageFeature.InlineClasses, LanguageFeature.State.DISABLED, false
)
}
checkFiles(files)
}
}
@Test
@TargetVersions("4.7+")
fun testDisableFeatureSupportGSKWithXFlag() = testDisableFeatureSupportGSK()
@Test
fun testEnableFeatureSupportGSK() {
val files = importProjectFromTestData()
runInEdtAndWait {
runWriteAction {
KotlinWithGradleConfigurator.changeFeatureConfiguration(
myTestFixture.module, LanguageFeature.InlineClasses, LanguageFeature.State.ENABLED, false
)
}
checkFiles(files)
}
}
@Test
@TargetVersions("4.7+")
fun testEnableFeatureSupportGSKWithXFlag() = testEnableFeatureSupportGSK()
@Test
@TargetVersions("4.7+")
fun testEnableFeatureSupportGSKWithNotInfixVersionCallAndXFlag() = testEnableFeatureSupportGSK()
@Test
@TargetVersions("4.7+")
fun testEnableFeatureSupportGSKWithSpecifyingPluginThroughIdAndXFlag() = testEnableFeatureSupportGSK()
override fun testDataDirName(): String = "configurator"
}
| apache-2.0 | 74d3fa14d3e2764269a4aa06ed3a5dc7 | 36.107191 | 132 | 0.647982 | 6.327626 | false | true | false | false |
ligi/SurvivalManual | android/src/main/kotlin/org/ligi/survivalmanual/functions/Hightlight.kt | 1 | 307 | package org.ligi.survivalmanual.functions
fun highLight(string: String, search: CaseInsensitiveSearch) = string.replace(search.regex) {
"<font color='red'>${it.value}</font>"
}
fun highLight(string: String, term: String?) = if (term == null) string else highLight(string, CaseInsensitiveSearch(term)) | gpl-3.0 | 79ed918aa9fd244d7e03112887236cdf | 37.5 | 123 | 0.745928 | 3.790123 | false | false | false | false |
androidx/androidx | camera/camera-camera2/src/test/java/androidx/camera/camera2/internal/compat/workaround/SupportedRepeatingSurfaceSizeTest.kt | 3 | 2453 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.internal.compat.workaround
import android.os.Build
import android.util.Size
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.ParameterizedRobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.internal.DoNotInstrument
import org.robolectric.util.ReflectionHelpers
@RunWith(ParameterizedRobolectricTestRunner::class)
@DoNotInstrument
@Config(minSdk = Build.VERSION_CODES.LOLLIPOP)
class SupportedRepeatingSurfaceSizeTest(
private val brand: String,
private val model: String,
private val result_sizes: Array<Size>,
) {
companion object {
private val input_sizes =
arrayOf(Size(176, 144), Size(208, 144), Size(320, 240), Size(352, 288), Size(400, 400))
@JvmStatic
@ParameterizedRobolectricTestRunner.Parameters(name = "brand={0}, model={1}")
fun data() = mutableListOf<Array<Any?>>().apply {
add(
arrayOf(
"Huawei",
"mha-l29",
arrayOf(Size(320, 240), Size(352, 288), Size(400, 400))
)
)
add(arrayOf("Huawei", "Not_mha-l29", input_sizes))
add(arrayOf("Not_Huawei", "mha-l29", input_sizes))
add(arrayOf("Not_Huawei", "Not_mha-l29", input_sizes))
}
}
@Before
fun setup() {
ReflectionHelpers.setStaticField(Build::class.java, "BRAND", brand)
ReflectionHelpers.setStaticField(Build::class.java, "MODEL", model)
}
@Test
fun getSurfaceSizes() {
assertThat(
SupportedRepeatingSurfaceSize().getSupportedSizes(input_sizes).asList()
).containsExactlyElementsIn(result_sizes)
}
} | apache-2.0 | aa0e3ce1b84d28b7748f4e680c46642f | 34.057143 | 99 | 0.677538 | 4.193162 | false | true | false | false |
androidx/androidx | privacysandbox/tools/tools-apicompiler/src/test/test-data/fullfeaturedsdk/output/com/mysdk/RequestConverter.kt | 3 | 909 | package com.mysdk
public object RequestConverter {
public fun fromParcelable(parcelable: ParcelableRequest): Request {
val annotatedValue = Request(
query = parcelable.query,
extraValues = parcelable.extraValues.map {
com.mysdk.InnerValueConverter.fromParcelable(it) }.toList(),
myInterface = (parcelable.myInterface as MyInterfaceStubDelegate).delegate)
return annotatedValue
}
public fun toParcelable(annotatedValue: Request): ParcelableRequest {
val parcelable = ParcelableRequest()
parcelable.query = annotatedValue.query
parcelable.extraValues = annotatedValue.extraValues.map {
com.mysdk.InnerValueConverter.toParcelable(it) }.toTypedArray()
parcelable.myInterface = MyInterfaceStubDelegate(annotatedValue.myInterface)
return parcelable
}
}
| apache-2.0 | d7ab98c22143559715032e47956e6d0d | 42.285714 | 91 | 0.685369 | 5.378698 | false | false | false | false |
androidx/androidx | fragment/fragment/src/androidTest/java/androidx/fragment/app/ControllerHostCallbacks.kt | 3 | 4632 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.fragment.app
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.testutils.runOnUiThreadRethrow
import java.io.FileDescriptor
import java.io.PrintWriter
@Suppress("DEPRECATION")
fun androidx.test.rule.ActivityTestRule<out FragmentActivity>.startupFragmentController(
viewModelStore: ViewModelStore,
savedState: Parcelable? = null
): FragmentController {
lateinit var fc: FragmentController
runOnUiThreadRethrow {
fc = FragmentController.createController(
ControllerHostCallbacks(activity, viewModelStore)
)
fc.attachHost(null)
fc.restoreSaveState(savedState)
fc.dispatchCreate()
fc.dispatchActivityCreated()
fc.noteStateNotSaved()
fc.execPendingActions()
fc.dispatchStart()
fc.dispatchResume()
fc.execPendingActions()
}
return fc
}
fun FragmentController.restart(
@Suppress("DEPRECATION")
rule: androidx.test.rule.ActivityTestRule<out FragmentActivity>,
viewModelStore: ViewModelStore,
destroyNonConfig: Boolean = true
): FragmentController {
var savedState: Parcelable? = null
rule.runOnUiThreadRethrow {
savedState = shutdown(viewModelStore, destroyNonConfig)
}
return rule.startupFragmentController(viewModelStore, savedState)
}
fun FragmentController.shutdown(
viewModelStore: ViewModelStore,
destroyNonConfig: Boolean = true
): Parcelable? {
dispatchPause()
@Suppress("DEPRECATION")
val savedState = saveAllState()
dispatchStop()
if (destroyNonConfig) {
viewModelStore.clear()
}
dispatchDestroy()
return savedState
}
class ControllerHostCallbacks(
private val activity: FragmentActivity,
private val viewModelStore: ViewModelStore
) : FragmentHostCallback<FragmentActivity>(activity), ViewModelStoreOwner {
override fun getViewModelStore(): ViewModelStore {
return viewModelStore
}
override fun onDump(
prefix: String,
fd: FileDescriptor?,
writer: PrintWriter,
args: Array<String>?
) {
}
override fun onShouldSaveFragmentState(fragment: Fragment): Boolean {
return !activity.isFinishing
}
override fun onGetLayoutInflater(): LayoutInflater {
return activity.layoutInflater.cloneInContext(activity)
}
override fun onGetHost(): FragmentActivity? {
return activity
}
override fun onSupportInvalidateOptionsMenu() {
activity.invalidateOptionsMenu()
}
override fun onStartActivityFromFragment(
fragment: Fragment,
intent: Intent,
requestCode: Int
) {
activity.startActivityFromFragment(fragment, intent, requestCode)
}
override fun onStartActivityFromFragment(
fragment: Fragment,
intent: Intent,
requestCode: Int,
options: Bundle?
) {
activity.startActivityFromFragment(fragment, intent, requestCode, options)
}
override fun onRequestPermissionsFromFragment(
fragment: Fragment,
permissions: Array<String>,
requestCode: Int
) {
throw UnsupportedOperationException()
}
override fun onShouldShowRequestPermissionRationale(permission: String): Boolean {
return ActivityCompat.shouldShowRequestPermissionRationale(
activity, permission
)
}
override fun onHasWindowAnimations() = activity.window != null
override fun onGetWindowAnimations() =
activity.window?.attributes?.windowAnimations ?: 0
override fun onFindViewById(id: Int): View? {
return activity.findViewById(id)
}
override fun onHasView(): Boolean {
val w = activity.window
return w?.peekDecorView() != null
}
} | apache-2.0 | 3a64ac6b49d38617b7c9c89da98e83ea | 28.138365 | 88 | 0.708981 | 5.09571 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/ide/projectView/impl/SelectFileAction.kt | 2 | 3805 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.projectView.impl
import com.intellij.ide.SelectInContext
import com.intellij.ide.SelectInManager
import com.intellij.ide.SelectInTarget
import com.intellij.ide.actions.SelectInContextImpl
import com.intellij.ide.impl.ProjectViewSelectInGroupTarget
import com.intellij.ide.projectView.ProjectView
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.actionSystem.PlatformDataKeys.TOOL_WINDOW
import com.intellij.openapi.actionSystem.impl.Utils
import com.intellij.openapi.keymap.KeymapUtil.getFirstKeyboardShortcutText
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.ToolWindowId.PROJECT_VIEW
private const val SELECT_CONTEXT_FILE = "SelectInProjectView"
private const val SELECT_OPENED_FILE = "SelectOpenedFileInProjectView"
internal class SelectFileAction : DumbAwareAction() {
override fun actionPerformed(event: AnActionEvent) {
when (getActionId(event)) {
SELECT_CONTEXT_FILE -> getSelector(event)?.run { target.selectIn(context, true) }
SELECT_OPENED_FILE ->
if (Registry.`is`("ide.selectIn.works.as.revealIn.when.project.view.focused")) {
ActionManager.getInstance().getAction("RevealIn")?.actionPerformed(event)
} else {
getView(event)?.selectOpenedFile?.run()
}
}
}
override fun update(event: AnActionEvent) {
val id = getActionId(event)
event.presentation.text = ActionsBundle.actionText(id)
event.presentation.description = ActionsBundle.actionDescription(id)
when (id) {
SELECT_CONTEXT_FILE -> {
event.presentation.isEnabledAndVisible = getSelector(event)?.run { target.canSelect(context) } == true
}
SELECT_OPENED_FILE -> {
val view = getView(event)
event.presentation.isEnabled = event.getData(PlatformDataKeys.LAST_ACTIVE_FILE_EDITOR) != null
event.presentation.isVisible = Utils.getOrCreateUpdateSession(event).compute(this, "isSelectEnabled",
ActionUpdateThread.EDT) { view?.isSelectOpenedFileEnabled == true }
event.project?.let { project ->
if (event.presentation.isVisible && getFirstKeyboardShortcutText(id).isEmpty()) {
val shortcut = getFirstKeyboardShortcutText("SelectIn")
if (shortcut.isNotEmpty()) {
val index = 1 + SelectInManager.getInstance(project).targetList.indexOfFirst { it is ProjectViewSelectInGroupTarget }
if (index >= 1) event.presentation.text = "${event.presentation.text} ($shortcut, $index)"
}
}
}
}
}
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
private data class Selector(val target: SelectInTarget, val context: SelectInContext)
private fun getSelector(event: AnActionEvent): Selector? {
val target = SelectInManager.findSelectInTarget(PROJECT_VIEW, event.project) ?: return null
val context = SelectInContextImpl.createContext(event) ?: return null
return Selector(target, context)
}
private fun getView(event: AnActionEvent) =
event.project?.let { ProjectView.getInstance(it) as? ProjectViewImpl }
private fun getActionId(event: AnActionEvent) =
when (event.getData(TOOL_WINDOW)?.id) {
PROJECT_VIEW -> SELECT_OPENED_FILE
else -> SELECT_CONTEXT_FILE
}
}
| apache-2.0 | 3bd4a87e49a45041d48c966adab932e1 | 45.402439 | 152 | 0.726675 | 4.551435 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/liftOut/ifToAssignment/afterRightBrace3.kt | 10 | 179 | fun test(i: Int) {
val f: () -> Boolean
<caret>if (i == 1) {
f = { true }
} else {
val g: () -> Boolean = { false }
f = { g() }
}
f()
} | apache-2.0 | 05af1375e54b8eccd46f93d61c52f53e | 17 | 40 | 0.329609 | 2.934426 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/test/testData/positionManager/classObject.kt | 13 | 851 | class A {
companion object {
init {
1 + 1 // A
val a = 1 // A
fun foo() {
1 // A\$Companion\$1
}
}
val prop = 1 // A
val prop2: Int
get() {
val a = 1 + 1 // A\$Companion
return 1 // A\$Companion
}
val prop3: Int
get() = 1 // A\$Companion
fun foo() = 1 // A\$Companion
fun foo2() {
"" // A\$Companion
val o = object {
val p = 1 // A\$Companion\$foo2\$o\$1
val p2: Int
get() {
return 1 // A\$Companion\$foo2\$o\$1
}
}
}
}
}
interface T {
companion object {
val prop = 1 // T\$Companion
}
}
| apache-2.0 | 793d08532efcf86080f477097d523fce | 18.790698 | 60 | 0.323149 | 4.364103 | false | false | false | false |
Briseus/Lurker | app/src/main/java/torille/fi/lurkforreddit/utils/NetworkHelper.kt | 1 | 1820 | package torille.fi.lurkforreddit.utils
import timber.log.Timber
import torille.fi.lurkforreddit.data.RedditService
import java.io.IOException
import java.math.BigInteger
import java.security.SecureRandom
import java.util.UUID.randomUUID
import javax.inject.Inject
import javax.inject.Singleton
/**
* Helper for creating auth calls
*/
@Singleton
class NetworkHelper @Inject
constructor(
private val store: Store,
private val authApi: RedditService.Auth
) {
@Throws(IOException::class)
fun authenticateApp(): String {
return if (store.isLoggedIn) {
Timber.d("Was logged in as user, refreshing token")
Timber.d("Using refreshtoken: " + store.refreshToken)
authApi.refreshUserToken("refresh_token", store.refreshToken).map { (accessToken) ->
Timber.d("New token: $accessToken")
store.token = accessToken
accessToken
}.doOnError { Timber.e(it) }.blockingSingle()
} else {
Timber.d("User was not logged in")
getToken()
}
}
@Throws(IOException::class)
fun getToken(): String {
val UUID = createUUID()
val grant_type = "https://oauth.reddit.com/grants/installed_client"
Timber.d("Getting token")
return authApi.getAuthToken(grant_type, UUID).map { (access_token) ->
Timber.d("Got new token $access_token")
store.token = access_token
access_token
}.doOnError { Timber.e(it) }.blockingSingle()
}
companion object {
private fun createUUID(): String {
return randomUUID().toString()
}
fun nextStateId(): String {
val random = SecureRandom()
return BigInteger(130, random).toString(32)
}
}
}
| mit | 716f78b4c3890ffab0619e65e3d89e9a | 27 | 96 | 0.622527 | 4.428224 | false | false | false | false |
jwren/intellij-community | platform/built-in-server/src/org/jetbrains/builtInWebServer/BuiltInWebServer.kt | 1 | 14529 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("HardCodedStringLiteral", "ReplaceGetOrSet")
package org.jetbrains.builtInWebServer
import com.github.benmanes.caffeine.cache.Caffeine
import com.google.common.net.InetAddresses
import com.intellij.ide.SpecialConfigFiles.USER_WEB_TOKEN
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.NotificationType
import com.intellij.notification.SingletonNotificationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.endsWithName
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.util.text.Strings
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.io.*
import com.intellij.util.io.DigestUtil.randomToken
import com.intellij.util.net.NetUtils
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.*
import io.netty.handler.codec.http.cookie.DefaultCookie
import io.netty.handler.codec.http.cookie.ServerCookieDecoder
import io.netty.handler.codec.http.cookie.ServerCookieEncoder
import org.jetbrains.ide.BuiltInServerBundle
import org.jetbrains.ide.BuiltInServerManagerImpl
import org.jetbrains.ide.HttpRequestHandler
import org.jetbrains.ide.orInSafeMode
import org.jetbrains.io.send
import java.awt.datatransfer.StringSelection
import java.io.IOException
import java.net.InetAddress
import java.net.URI
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFileAttributeView
import java.nio.file.attribute.PosixFilePermission
import java.util.*
import java.util.concurrent.TimeUnit
import javax.swing.SwingUtilities
internal val LOG = logger<BuiltInWebServer>()
private val notificationManager by lazy {
SingletonNotificationManager(BuiltInServerManagerImpl.NOTIFICATION_GROUP, NotificationType.INFORMATION)
}
private val WEB_SERVER_PATH_HANDLER_EP_NAME = ExtensionPointName.create<WebServerPathHandler>("org.jetbrains.webServerPathHandler")
class BuiltInWebServer : HttpRequestHandler() {
override fun isAccessible(request: HttpRequest): Boolean {
return BuiltInServerOptions.getInstance().builtInServerAvailableExternally ||
request.isLocalOrigin(onlyAnyOrLoopback = false, hostsOnly = true)
}
override fun isSupported(request: FullHttpRequest): Boolean = super.isSupported(request) || request.method() == HttpMethod.POST
override fun process(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): Boolean {
var hostName = getHostName(request) ?: return false
val projectName: String?
val isIpv6 = hostName[0] == '[' && hostName.length > 2 && hostName[hostName.length - 1] == ']'
if (isIpv6) {
hostName = hostName.substring(1, hostName.length - 1)
}
if (isIpv6 || InetAddresses.isInetAddress(hostName) || isOwnHostName(hostName) || hostName.endsWith(".ngrok.io")) {
if (urlDecoder.path().length < 2) {
return false
}
projectName = null
}
else {
if (hostName.endsWith(".localhost")) {
projectName = hostName.substring(0, hostName.lastIndexOf('.'))
}
else {
projectName = hostName
}
}
return doProcess(urlDecoder, request, context, projectName)
}
}
internal fun isActivatable() = Registry.`is`("ide.built.in.web.server.activatable", false)
const val TOKEN_PARAM_NAME = "_ijt"
const val TOKEN_HEADER_NAME = "x-ijt"
private val STANDARD_COOKIE by lazy {
val productName = ApplicationNamesInfo.getInstance().lowercaseProductName
val configPath = PathManager.getConfigPath()
val file = Path.of(configPath, USER_WEB_TOKEN)
var token: String? = null
if (file.exists()) {
try {
token = UUID.fromString(file.readText()).toString()
}
catch (e: Exception) {
LOG.warn(e)
}
}
if (token == null) {
token = UUID.randomUUID().toString()
file.write(token!!)
Files.getFileAttributeView(file, PosixFileAttributeView::class.java)
?.setPermissions(EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE))
}
// explicit setting domain cookie on localhost doesn't work for chrome
// http://stackoverflow.com/questions/8134384/chrome-doesnt-create-cookie-for-domain-localhost-in-broken-https
val cookie = DefaultCookie(productName + "-" + Integer.toHexString(configPath.hashCode()), token!!)
cookie.isHttpOnly = true
cookie.setMaxAge(TimeUnit.DAYS.toSeconds(365 * 10))
cookie.setPath("/")
cookie
}
// expire after access because we reuse tokens
private val tokens = Caffeine.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build<String, Boolean>()
fun acquireToken(): String {
var token = tokens.asMap().keys.firstOrNull()
if (token == null) {
token = randomToken()
tokens.put(token, java.lang.Boolean.TRUE)
}
return token
}
private fun doProcess(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext, projectNameAsHost: String?): Boolean {
val decodedPath = urlDecoder.path()
var offset: Int
var isEmptyPath: Boolean
val isCustomHost = projectNameAsHost != null
var projectName: String
if (isCustomHost) {
projectName = projectNameAsHost!!
// host mapped to us
offset = 0
isEmptyPath = decodedPath.isEmpty()
}
else {
offset = decodedPath.indexOf('/', 1)
projectName = decodedPath.substring(1, if (offset == -1) decodedPath.length else offset)
isEmptyPath = offset == -1
}
val referer = request.headers().get(HttpHeaderNames.REFERER)
val projectNameFromReferer =
if (!isCustomHost && referer != null) {
try {
val uri = URI.create(referer)
val refererPath = uri.path
if (refererPath != null && refererPath.startsWith('/')) {
val secondSlashOffset = refererPath.indexOf('/', 1)
if (secondSlashOffset > 1) refererPath.substring(1, secondSlashOffset)
else null
}
else null
}
catch (t: Throwable) {
null
}
}
else null
var candidateByDirectoryName: Project? = null
var isCandidateFromReferer = false
val project = ProjectManager.getInstance().openProjects.firstOrNull(fun(project: Project): Boolean {
if (project.isDisposed) {
return false
}
val name = project.name
if (isCustomHost) {
// domain name is case-insensitive
if (projectName.equals(name, ignoreCase = true)) {
if (!SystemInfo.isFileSystemCaseSensitive) {
// may be passed path is not correct
projectName = name
}
return true
}
}
else {
// WEB-17839 Internal web server reports 404 when serving files from project with slashes in name
if (decodedPath.regionMatches(1, name, 0, name.length, !SystemInfo.isFileSystemCaseSensitive)) {
val isEmptyPathCandidate = decodedPath.length == (name.length + 1)
if (isEmptyPathCandidate || decodedPath[name.length + 1] == '/') {
projectName = name
offset = name.length + 1
isEmptyPath = isEmptyPathCandidate
return true
}
}
}
if (candidateByDirectoryName == null && compareNameAndProjectBasePath(projectName, project)) {
candidateByDirectoryName = project
}
if (candidateByDirectoryName == null &&
projectNameFromReferer != null &&
(projectNameFromReferer == name || compareNameAndProjectBasePath(projectNameFromReferer, project))) {
candidateByDirectoryName = project
isCandidateFromReferer = true
}
return false
}) ?: candidateByDirectoryName ?: return false
if (isActivatable() && !PropertiesComponent.getInstance().getBoolean("ide.built.in.web.server.active")) {
notificationManager.notify("", BuiltInServerBundle.message("notification.content.built.in.web.server.is.deactivated"), project)
return false
}
if (isCandidateFromReferer) {
projectName = projectNameFromReferer!!
offset = 0
isEmptyPath = false
}
if (isEmptyPath) {
// we must redirect "jsdebug" to "jsdebug/" as nginx does, otherwise browser will treat it as a file instead of a directory, so, relative path will not work
redirectToDirectory(request, context.channel(), projectName, null)
return true
}
val path = toIdeaPath(decodedPath, offset)
if (path == null) {
HttpResponseStatus.BAD_REQUEST.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(context.channel(), request)
return true
}
for (pathHandler in WEB_SERVER_PATH_HANDLER_EP_NAME.extensionList) {
LOG.runAndLogException {
if (pathHandler.process(path, project, request, context, projectName, decodedPath, isCustomHost)) {
return true
}
}
}
return false
}
fun HttpRequest.isSignedRequest(): Boolean {
if (BuiltInServerOptions.getInstance().allowUnsignedRequests) {
return true
}
// we must check referrer - if html cached, browser will send request without query
val token = headers().get(TOKEN_HEADER_NAME)
?: QueryStringDecoder(uri()).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull()
?: referrer?.let { QueryStringDecoder(it).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull() }
// we don't invalidate token - allow making subsequent requests using it (it is required for our javadoc DocumentationComponent)
return token != null && tokens.getIfPresent(token) != null
}
fun validateToken(request: HttpRequest, channel: Channel, isSignedRequest: Boolean): HttpHeaders? {
if (BuiltInServerOptions.getInstance().allowUnsignedRequests) {
return EmptyHttpHeaders.INSTANCE
}
request.headers().get(HttpHeaderNames.COOKIE)?.let {
for (cookie in ServerCookieDecoder.STRICT.decode(it)) {
if (cookie.name() == STANDARD_COOKIE.name()) {
if (cookie.value() == STANDARD_COOKIE.value()) {
return EmptyHttpHeaders.INSTANCE
}
break
}
}
}
if (isSignedRequest) {
return DefaultHttpHeaders().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(STANDARD_COOKIE) + "; SameSite=strict")
}
val urlDecoder = QueryStringDecoder(request.uri())
if (!urlDecoder.path().endsWith("/favicon.ico")) {
val url = "${channel.uriScheme}://${request.host!!}${urlDecoder.path()}"
SwingUtilities.invokeAndWait {
ProjectUtil.focusProjectWindow(null, true)
if (MessageDialogBuilder
// escape - see https://youtrack.jetbrains.com/issue/IDEA-287428
.yesNo("", Strings.escapeXmlEntities(BuiltInServerBundle.message("dialog.message.page", StringUtil.trimMiddle(url, 50))))
.icon(Messages.getWarningIcon())
.yesText(BuiltInServerBundle.message("dialog.button.copy.authorization.url.to.clipboard"))
.guessWindowAndAsk()) {
CopyPasteManager.getInstance().setContents(StringSelection(url + "?" + TOKEN_PARAM_NAME + "=" + acquireToken()))
}
}
}
HttpResponseStatus.UNAUTHORIZED.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request)
return null
}
private fun toIdeaPath(decodedPath: String, offset: Int): String? {
// must be absolute path (relative to DOCUMENT_ROOT, i.e. scheme://authority/) to properly canonicalize
val path = decodedPath.substring(offset)
if (!path.startsWith('/')) {
return null
}
return FileUtil.toCanonicalPath(path, '/').substring(1)
}
fun compareNameAndProjectBasePath(projectName: String, project: Project): Boolean {
val basePath = project.basePath
return basePath != null && endsWithName(basePath, projectName)
}
fun findIndexFile(basedir: VirtualFile): VirtualFile? {
val children = basedir.children
if (children.isNullOrEmpty()) {
return null
}
for (indexNamePrefix in arrayOf("index.", "default.")) {
var index: VirtualFile? = null
val preferredName = indexNamePrefix + "html"
for (child in children) {
if (!child.isDirectory) {
val name = child.name
//noinspection IfStatementWithIdenticalBranches
if (name == preferredName) {
return child
}
else if (index == null && name.startsWith(indexNamePrefix)) {
index = child
}
}
}
if (index != null) {
return index
}
}
return null
}
fun findIndexFile(basedir: Path): Path? {
val children = basedir.directoryStreamIfExists({
val name = it.fileName.toString()
name.startsWith("index.") || name.startsWith("default.")
}) { it.toList() } ?: return null
for (indexNamePrefix in arrayOf("index.", "default.")) {
var index: Path? = null
val preferredName = "${indexNamePrefix}html"
for (child in children) {
if (!child.isDirectory()) {
val name = child.fileName.toString()
if (name == preferredName) {
return child
}
else if (index == null && name.startsWith(indexNamePrefix)) {
index = child
}
}
}
if (index != null) {
return index
}
}
return null
}
// is host loopback/any or network interface address (i.e. not custom domain)
// must be not used to check is host on local machine
internal fun isOwnHostName(host: String): Boolean {
if (NetUtils.isLocalhost(host)) {
return true
}
try {
val address = InetAddress.getByName(host)
if (host == address.hostAddress || host.equals(address.canonicalHostName, ignoreCase = true)) {
return true
}
val localHostName = InetAddress.getLocalHost().hostName
// WEB-8889
// develar.local is own host name: develar. equals to "develar.labs.intellij.net" (canonical host name)
return localHostName.equals(host, ignoreCase = true) || (host.endsWith(".local") && localHostName.regionMatches(0, host, 0, host.length - ".local".length, true))
}
catch (ignored: IOException) {
return false
}
}
| apache-2.0 | fcce85d1a6d618e7ef8c6ba719d1e5b1 | 35.141791 | 165 | 0.711887 | 4.597785 | false | false | false | false |
maxee/AppIntro | appintro/src/main/java/com/github/paolorotolo/appintro/internal/CustomFontCache.kt | 1 | 957 | package com.github.paolorotolo.appintro.internal
import android.content.Context
import android.graphics.Typeface
/**
* Custom Font Cache Implementation.
* Prevent(s) memory leaks due to Typeface objects
*/
internal object CustomFontCache {
private val TAG = LogHelper.makeLogTag(CustomFontCache::class)
private val cache = hashMapOf<String, Typeface>()
operator fun get(path: String?, ctx: Context): Typeface? {
if (path.isNullOrEmpty()) {
LogHelper.w(TAG, "Empty typeface path provided!")
return null
}
val storedTypeface = cache[path]
return if (storedTypeface != null) {
// Cache hit! Return the typeface.
storedTypeface
} else {
// Cache miss! Create the typeface and store it.
val newTypeface = Typeface.createFromAsset(ctx.assets, path)
cache[path!!] = newTypeface
newTypeface
}
}
}
| apache-2.0 | 06a0c32c700365ea20d5f2bfdcbe6d50 | 28.90625 | 72 | 0.634274 | 4.668293 | false | false | false | false |
chesslave/chesslave | backend/src/main/java/io/chesslave/eyes/BoardAnalyzer.kt | 2 | 4235 | package io.chesslave.eyes
import io.chesslave.model.Board
import io.chesslave.model.Piece
import io.chesslave.model.Square
import io.chesslave.visual.*
import io.chesslave.visual.model.BoardImage
import io.vavr.Tuple
import io.vavr.collection.HashMap
import java.awt.Color
import java.awt.Point
import java.awt.Rectangle
import java.awt.image.BufferedImage
fun analyzeBoardImage(image: BufferedImage): BoardConfiguration {
val boardRect = image.detectBoard(Point(image.width / 2, image.height / 2)) ?: throw IllegalArgumentException("Board not found")
val board = BoardImage(image.getSubimage(boardRect.x, boardRect.y, boardRect.width, boardRect.height))
val chars = detectCharacteristics(board.image)
val pieces = HashMap.ofEntries(
Tuple.of(Piece.blackPawn, cropPiece(board, Board.b7)),
Tuple.of(Piece.blackKnight, cropPiece(board, Board.g8)),
Tuple.of(Piece.blackBishop, cropPiece(board, Board.c8)),
Tuple.of(Piece.blackRook, cropPiece(board, Board.a8)),
Tuple.of(Piece.blackQueen, Images.fillOuterBackground(cropPiece(board, Board.d8), chars.whiteColor)),
Tuple.of(Piece.blackKing, cropPiece(board, Board.e8)),
Tuple.of(Piece.whitePawn, cropPiece(board, Board.b2)),
Tuple.of(Piece.whiteKnight, cropPiece(board, Board.g1)),
Tuple.of(Piece.whiteBishop, cropPiece(board, Board.c1)),
Tuple.of(Piece.whiteRook, cropPiece(board, Board.a1)),
Tuple.of(Piece.whiteQueen, Images.fillOuterBackground(cropPiece(board, Board.d1), chars.blackColor)),
Tuple.of(Piece.whiteKing, cropPiece(board, Board.e1)))
return BoardConfiguration(board, pieces, chars, false)
}
private fun detectCharacteristics(board: BufferedImage): BoardConfiguration.Characteristics {
val cellWidth = board.width / 8
val cellHeight = board.height / 8
val whiteColor = board.getRGB(cellWidth / 2, (cellHeight * 4.5).toInt())
val blackColor = board.getRGB(cellWidth / 2, (cellHeight * 3.5).toInt())
assert(whiteColor != blackColor) { "White and black cells should be different, found ${whiteColor}" }
return BoardConfiguration.Characteristics(cellWidth, cellHeight, whiteColor, blackColor)
}
private fun cropPiece(board: BoardImage, square: Square): BufferedImage {
val squareImage = board.squareImage(square).image
return Images.crop(squareImage) { it == squareImage.getRGB(0, 0) }
}
internal fun BufferedImage.detectBoard(point: Point): Rectangle? {
val square = detectSquare(point) ?: return null
val left = generateSequence(square) { detectSquare(Point(it.x - square.width, it.y)) }.last().x
val right = generateSequence(square) { detectSquare(Point(it.x + square.width, it.y)) }.last().xw
val top = generateSequence(square) { detectSquare(Point(it.x, it.y - square.height)) }.last().y
val bottom = generateSequence(square) { detectSquare(Point(it.x, it.y + square.height)) }.last().yh
val width = right - left
val height = bottom - top
val isBoard = almostEqualsLength(width / 8, square.width) && almostEqualsLength(height / 8, square.height)
return if (isBoard) Rectangle(left, top, width, height) else null
}
private val Rectangle.xw: Int get() = x + width
private val Rectangle.yh: Int get() = y + height
internal fun BufferedImage.detectSquare(point: Point): Rectangle? =
this.detectRectangle(point)?.let { rect ->
if (almostEqualsLength(rect.height, rect.width)) rect else null
}
private fun BufferedImage.detectRectangle(point: Point): Rectangle? {
if (point !in this) return null
val color = this.getColor(point)
val up = this.moveFrom(point, Movement.UP) { Colors.areSimilar(color, Color(it)) }
val down = this.moveFrom(point, Movement.DOWN) { Colors.areSimilar(color, Color(it)) }
val left = this.moveFrom(point, Movement.LEFT) { Colors.areSimilar(color, Color(it)) }
val right = this.moveFrom(point, Movement.RIGHT) { Colors.areSimilar(color, Color(it)) }
val height = down.y - up.y - 1
val width = right.x - left.x - 1
return Rectangle(left.x + 1, up.y + 1, width, height)
}
private fun almostEqualsLength(a: Int, b: Int, tolerance: Double = .1): Boolean =
Math.abs(a.toDouble() / b.toDouble() - 1) < tolerance | gpl-2.0 | 5f9efc73bde4158b520a8431823cd32b | 50.658537 | 132 | 0.717828 | 3.555835 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/variables/editor/types/toggle/ToggleVariableOptionsAdapter.kt | 1 | 2450 | package ch.rmy.android.http_shortcuts.activities.variables.editor.types.toggle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import ch.rmy.android.framework.extensions.color
import ch.rmy.android.framework.extensions.context
import ch.rmy.android.framework.ui.BaseAdapter
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.databinding.ToggleOptionBinding
import ch.rmy.android.http_shortcuts.variables.VariablePlaceholderProvider
import ch.rmy.android.http_shortcuts.variables.Variables
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.receiveAsFlow
import javax.inject.Inject
class ToggleVariableOptionsAdapter
@Inject
constructor(
private val variablePlaceholderProvider: VariablePlaceholderProvider,
) : BaseAdapter<OptionItem>() {
sealed interface UserEvent {
data class OptionClicked(val id: String) : UserEvent
}
private val userEventChannel = Channel<UserEvent>(capacity = Channel.UNLIMITED)
val userEvents: Flow<UserEvent> = userEventChannel.receiveAsFlow()
override fun createViewHolder(viewType: Int, parent: ViewGroup, layoutInflater: LayoutInflater) =
SelectOptionViewHolder(ToggleOptionBinding.inflate(layoutInflater, parent, false))
override fun bindViewHolder(holder: RecyclerView.ViewHolder, position: Int, item: OptionItem, payloads: List<Any>) {
(holder as SelectOptionViewHolder).setItem(item)
}
override fun areItemsTheSame(oldItem: OptionItem, newItem: OptionItem) =
oldItem.id == newItem.id
inner class SelectOptionViewHolder(
private val binding: ToggleOptionBinding,
) : RecyclerView.ViewHolder(binding.root) {
private val variablePlaceholderColor by lazy(LazyThreadSafetyMode.NONE) {
color(context, R.color.variable)
}
lateinit var optionId: String
private set
init {
binding.root.setOnClickListener {
userEventChannel.trySend(UserEvent.OptionClicked(optionId))
}
}
fun setItem(item: OptionItem) {
optionId = item.id
binding.toggleOptionValue.text = Variables.rawPlaceholdersToVariableSpans(
item.text,
variablePlaceholderProvider,
variablePlaceholderColor,
)
}
}
}
| mit | 9737dcd03de247799c9b7546ea32e387 | 35.029412 | 120 | 0.734694 | 4.832347 | false | false | false | false |
WYKCode/WYK-Android | app/src/main/java/college/wyk/app/ui/feed/sns/SnsFeedFragment.kt | 1 | 6258 | package college.wyk.app.ui.feed.sns
import android.os.Bundle
import android.os.Handler
import android.support.design.widget.Snackbar
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import college.wyk.app.R
import college.wyk.app.WykApplication
import college.wyk.app.commons.OnScrollListener
import college.wyk.app.commons.SubscribedFragment
import college.wyk.app.commons.inflate
import college.wyk.app.model.sns.SnsPostManager
import college.wyk.app.model.sns.SnsStack
import college.wyk.app.ui.feed.sns.adapter.SnsPostAdapter
import com.github.florent37.materialviewpager.header.MaterialViewPagerHeaderDecorator
import kotlinx.android.synthetic.main.fragment_feed_page.*
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.util.*
const val MILLIS_IN_A_MONTH = 2628000000L
class SnsFeedFragment : SubscribedFragment() {
companion object {
fun newInstance(id: String) = SnsFeedFragment().apply {
val bundle = Bundle(1)
bundle.putString("id", id)
arguments = bundle
}
}
lateinit var id: String
private var stack: SnsStack? = null
private val postManager by lazy { SnsPostManager() }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return container?.inflate(R.layout.fragment_feed_page)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
id = arguments.getString("id")
val linearLayout = LinearLayoutManager(context)
if (post_list != null) { // to let Instant Run work properly
post_list.apply {
setHasFixedSize(true)
layoutManager = linearLayout
clearOnScrollListeners()
addOnScrollListener(OnScrollListener({ requestPosts() }, linearLayout))
// use header decorator
addItemDecoration(MaterialViewPagerHeaderDecorator())
}
if (post_list.adapter == null) {
post_list.adapter = SnsPostAdapter()
}
swipe_refresh_layout.setOnRefreshListener { requestPosts(clear = true) }
swipe_refresh_layout.setProgressBackgroundColorSchemeResource(when (id) {
"CampusTV" -> R.color.campus_tv
"SA" -> R.color.sa
"MA" -> R.color.ma
else -> R.color.md_black_1000
})
swipe_refresh_layout.setColorSchemeResources(R.color.md_white_1000)
}
if (savedInstanceState != null) {
val instanceState = WykApplication.instance.snsStacks[id]
if (instanceState != null && instanceState.items.size > 0) {
if (post_list != null) {
(post_list.adapter as SnsPostAdapter).apply {
setPosts(instanceState.items)
markEnd()
}
}
} else {
requestPosts(clear = true)
}
WykApplication.instance.snsStacks.remove(id)
} else {
requestPosts() // for the first time
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
// since the size for this parcelable is too large... let's just save it into the Application singleton
this.stack?.let { WykApplication.instance.snsStacks[id] = it }
}
private fun requestPosts(clear: Boolean = false) {
if (!clear && this.stack?.noMoreUpdates ?: false) return
if (clear) this.stack?.since = Date().time
val subscription = postManager
.pullStack(id, sinceMillis = (this.stack?.since ?: Date().time) - (MILLIS_IN_A_MONTH * 6))
.subscribeOn(Schedulers.io()) // we want to request posts on the I/O thread
.observeOn(AndroidSchedulers.mainThread()) // though, we want to handle posts on the main thread
.subscribe(
{ retrievedState ->
if (post_list == null) return@subscribe
swipe_refresh_layout.isRefreshing = false
if (retrievedState.items.size == 0) {
Log.i("WYK", retrievedState.items.size.toString())
Log.i("WYK", (this.stack?.items?.size ?: -1).toString())
(post_list.adapter as SnsPostAdapter).markEnd()
this.stack?.noMoreUpdates = true
} else {
this.stack = retrievedState
(post_list.adapter as SnsPostAdapter).apply {
retrievedState.items.let {
if (clear) {
setPosts(it)
notifyDataSetChanged()
} else addPosts(it)
}
}
Log.i("WYK", retrievedState.items.size.toString())
}
},
{ e ->
swipe_refresh_layout?.isRefreshing = false
Log.e("WYK", e.message)
Log.e("WYK", e.stackTrace.joinToString(separator = "\n"))
// would crash if Snackbar is initiated while fragment is not fully initialized
activity.runOnUiThread {
// run it delayed and on ui thread then!
Handler().postDelayed({
Snackbar.make(post_list, e.message ?: "", Snackbar.LENGTH_LONG).show()
}, 5)
}
}
)
super.subscriptions.add(subscription)
}
} | mit | 2a073c327f4ffe04de31f42c8d6d023e | 38.866242 | 116 | 0.545542 | 5.059014 | false | false | false | false |
mbenz95/lpCounter | app/src/main/kotlin/benzm/yugiohlifepointcounter/util/Utils.kt | 1 | 843 | @file:JvmName("Utils")
package benzm.yugiohlifepointcounter.util
fun toStringWithSign(number: Int): String {
val str = number.toString()
if (number > 0)
return "+$number"
return str
}
fun extractChars(str: String, chars: String): String {
var result = ""
for (c in str) {
if (chars.contains(c))
result += c
}
return result
}
fun isOperation(op: String): Boolean {
return op == "+" || op == "-" || op == "x" || op == "/"
}
fun isOperation(op: Char): Boolean {
return isOperation(op.toString())
}
fun Int.toStringPrefixSign(): String {
if (this <= 0)
return this.toString()
return "+$this"
}
fun String.toIntPrefixSign(): Int {
if (this.isBlank())
return 0
if (this[0] == '+')
return this.substring(1).toInt()
return this.toInt()
} | mit | 540d322df4a7c1459a362b0f661f04d3 | 20.1 | 59 | 0.580071 | 3.469136 | false | false | false | false |
oversecio/oversec_crypto | crypto/src/main/java/io/oversec/one/crypto/UserInteractionRequiredException.kt | 1 | 569 | package io.oversec.one.crypto
import android.app.PendingIntent
open class UserInteractionRequiredException : Exception {
val pendingIntent: PendingIntent
private var mPublicKeyIds: LongArray? = null //TODO: not longer used ?!
constructor(pi: PendingIntent, pkids: List<Long>?) {
pendingIntent = pi
mPublicKeyIds = pkids?.toLongArray()
}
constructor(pi: PendingIntent, pkids: LongArray) {
pendingIntent = pi
mPublicKeyIds = pkids
}
constructor(pi: PendingIntent) {
pendingIntent = pi
}
}
| gpl-3.0 | a9118d058924923b28ff828bf212ba7d | 20.884615 | 76 | 0.673111 | 4.515873 | false | false | false | false |
RSDT/Japp | app/src/main/java/nl/rsdt/japp/jotial/maps/searching/SearchEntry.kt | 2 | 781 | package nl.rsdt.japp.jotial.maps.searching
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 29-7-2016
* Description...
*/
class SearchEntry {
var id: String? = null
private set
var infoId: Int = 0
private set
var value: String? = null
private set
class Builder {
internal var entry = SearchEntry()
fun setId(string: String): Builder {
entry.id = string
return this
}
fun setInfoId(id: Int): Builder {
entry.infoId = id
return this
}
fun setValue(value: String): Builder {
entry.value = value
return this
}
fun create(): SearchEntry {
return entry
}
}
}
| apache-2.0 | 698df3d97cdf73d180aa7c68ecec2aaa | 16.355556 | 46 | 0.519846 | 4.412429 | false | false | false | false |
serorigundam/numeri3 | app/src/main/kotlin/net/ketc/numeri/domain/entity/ClientToken.kt | 1 | 1068 | package net.ketc.numeri.domain.entity
import com.j256.ormlite.field.DatabaseField
import com.j256.ormlite.table.DatabaseTable
import net.ketc.numeri.domain.service.TwitterClient
import net.ketc.numeri.util.ormlite.Entity
import twitter4j.auth.AccessToken
/**
* Twitter user token
*/
@DatabaseTable
data class ClientToken(@DatabaseField(id = true)
override val id: Long = 0,
@DatabaseField(canBeNull = false)
val authToken: String = "",
@DatabaseField(canBeNull = false)
val authTokenSecret: String = "") : Entity<Long>
fun createClientToken(id: Long, authToken: String, authTokenSecret: String) = ClientToken(id, authToken, authTokenSecret)
fun createClientToken(authToken: AccessToken) = ClientToken(authToken.userId, authToken.token, authToken.tokenSecret)
fun TwitterClient.toClientToken(): ClientToken {
val oAuthAccessToken = twitter.oAuthAccessToken
return createClientToken(id, oAuthAccessToken.token, oAuthAccessToken.tokenSecret)
} | mit | d346151b403855b2f63b5772fc316a01 | 41.76 | 121 | 0.716292 | 4.413223 | false | false | false | false |
Litote/kmongo | kmongo-annotation-processor/target/generated-sources/kapt/test/org/litote/kmongo/model/SubData2_.kt | 1 | 1458 | package org.litote.kmongo.model
import kotlin.Int
import kotlin.String
import kotlin.Suppress
import kotlin.collections.Collection
import kotlin.collections.Map
import kotlin.reflect.KProperty1
import org.litote.kmongo.property.KPropertyPath
private val __A1: KProperty1<SubData2, Int?>
get() = SubData2::a1
class SubData2_<T>(previous: KPropertyPath<T, *>?, property: KProperty1<*, SubData2?>) :
NotAnnotatedData_<T>(previous,property) {
val a1: KPropertyPath<T, Int?>
get() = KPropertyPath(this,__A1)
companion object {
val A1: KProperty1<SubData2, Int?>
get() = __A1}
}
class SubData2_Col<T>(previous: KPropertyPath<T, *>?, property: KProperty1<*,
Collection<SubData2>?>) : NotAnnotatedData_Col<T>(previous,property) {
val a1: KPropertyPath<T, Int?>
get() = KPropertyPath(this,__A1)
@Suppress("UNCHECKED_CAST")
override fun memberWithAdditionalPath(additionalPath: String): SubData2_<T> = SubData2_(this,
customProperty(this, additionalPath))}
class SubData2_Map<T, K>(previous: KPropertyPath<T, *>?, property: KProperty1<*, Map<K, SubData2>?>)
: NotAnnotatedData_Map<T, K>(previous,property) {
val a1: KPropertyPath<T, Int?>
get() = KPropertyPath(this,__A1)
@Suppress("UNCHECKED_CAST")
override fun memberWithAdditionalPath(additionalPath: String): SubData2_<T> = SubData2_(this,
customProperty(this, additionalPath))}
| apache-2.0 | 76288dd3784cb63176c41c88d949976f | 36.384615 | 100 | 0.6893 | 3.556098 | false | false | false | false |
jmiecz/YelpBusinessExample | dal/src/test/java/net/mieczkowski/dal/services/businessLookupService/BusinessLookupServiceTest.kt | 1 | 4147 | package net.mieczkowski.dal.services.businessLookupService
import com.raizlabs.android.dbflow.config.FlowManager
import net.mieczkowski.dal.mockedData.MockedBusinessLookupData
import net.mieczkowski.dal.services.businessLookupService.models.BusinessLookupRequest
import net.mieczkowski.dal.services.businessLookupService.models.MyLocation
import net.mieczkowski.dal.tools.ServiceChecker
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.koin.dsl.module.module
import org.koin.standalone.StandAloneContext.startKoin
import org.koin.standalone.StandAloneContext.stopKoin
import org.koin.standalone.inject
import org.koin.test.KoinTest
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import java.util.ArrayList
/**
* Created by Josh Mieczkowski on 9/12/2018.
*/
@RunWith(RobolectricTestRunner::class)
class BusinessLookupServiceTest : KoinTest {
var mockServiceChecker = mock(ServiceChecker::class.java)
val businessLookupService: BusinessLookupService by inject()
@Test
fun `testing new lookup by name`() {
FlowManager.init(RuntimeEnvironment.application)
startKoin(listOf(module {
single { MockedBusinessLookupData() as BusinessContract }
factory { BusinessLookupService(get(), mockServiceChecker) }
}))
`when`(mockServiceChecker.hasInternetAccess()).thenReturn(true)
val testObs = businessLookupService.lookUpByName(BusinessLookupRequest("TEST", MyLocation(0.0, 0.0)))
.test()
testObs.awaitTerminalEvent()
testObs.assertNoErrors()
.assertValue {
assertEquals(2, it.size)
val yelpBusiness = it[0]
val businessLocation = yelpBusiness.businessLocation!!
val businessCoordinates = yelpBusiness.businessCoordinates!!
val businessDetails = yelpBusiness.businessDetails!!
val photos = listOf(
"http://s3-media3.fl.yelpcdn.com/bphoto/--8oiPVp0AsjoWHqaY1rDQ/o.jpg",
"http://s3-media2.fl.yelpcdn.com/bphoto/ybXbObsm7QGw3SGPA1_WXA/o.jpg",
"http://s3-media3.fl.yelpcdn.com/bphoto/7rZ061Wm4tRZ-iwAhkRSFA/o.jpg"
)
assertEquals("Gary Danko", yelpBusiness.name)
assertEquals("+14157492060", yelpBusiness.phone)
assertEquals("gary-danko-san-francisco", yelpBusiness.id)
assertEquals("TEST", yelpBusiness.searchKey)
assertEquals("800 N Point St", businessLocation.address1)
assertEquals("", businessLocation.address2)
assertEquals("", businessLocation.address3)
assertEquals("San Francisco", businessLocation.city)
assertEquals("CA", businessLocation.state)
assertEquals("94109", businessLocation.postalCode)
assertEquals("US", businessLocation.country)
assertEquals(37.80587, businessCoordinates.latitude, .00001)
assertEquals(-122.42058, businessCoordinates.longitude, .00001)
assertEquals(yelpBusiness.id, businessDetails.id)
assertEquals("https://s3-media4.fl.yelpcdn.com/bphoto/--8oiPVp0AsjoWHqaY1rDQ/o.jpg", businessDetails.imgUrl)
assertEquals(false, businessDetails.isClaimed)
assertEquals(false, businessDetails.isClosed)
assertEquals("https://www.yelp.com/biz/gary-danko-san-francisco", businessDetails.businessUrl)
assertEquals("\$\$\$\$", businessDetails.priceRating)
assertEquals(4.5, businessDetails.rating, .1)
assertEquals(4521, businessDetails.reviewCount)
assertEquals(photos, businessDetails.businessPhotos)
true
}
stopKoin()
}
} | apache-2.0 | b351fc08fd67f67cd0079dd250a4b483 | 43.12766 | 128 | 0.655414 | 4.572216 | false | true | false | false |
ibinti/intellij-community | platform/built-in-server/src/org/jetbrains/io/fastCgi/FastCgiDecoder.kt | 9 | 4714 | package org.jetbrains.io.fastCgi
import com.intellij.util.Consumer
import gnu.trove.TIntObjectHashMap
import io.netty.buffer.ByteBuf
import io.netty.buffer.CompositeByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.util.CharsetUtil
import org.jetbrains.io.Decoder
internal const val HEADER_LENGTH = 8
private enum class DecodeRecordState {
HEADER,
CONTENT
}
internal class FastCgiDecoder(private val errorOutputConsumer: Consumer<String>, private val responseHandler: FastCgiService) : Decoder(), Decoder.FullMessageConsumer<Void> {
private var state = DecodeRecordState.HEADER
private enum class ProtocolStatus {
REQUEST_COMPLETE,
CANT_MPX_CONN,
OVERLOADED,
UNKNOWN_ROLE
}
object RecordType {
val END_REQUEST = 3
val STDOUT = 6
val STDERR = 7
}
private var type = 0
private var id = 0
private var contentLength: Int = 0
private var paddingLength: Int = 0
private val dataBuffers = TIntObjectHashMap<ByteBuf>()
override fun messageReceived(context: ChannelHandlerContext, input: ByteBuf) {
while (true) {
when (state) {
DecodeRecordState.HEADER -> {
if (paddingLength > 0) {
if (input.readableBytes() > paddingLength) {
input.skipBytes(paddingLength)
paddingLength = 0
}
else {
paddingLength -= input.readableBytes()
input.skipBytes(input.readableBytes())
return
}
}
val buffer = getBufferIfSufficient(input, HEADER_LENGTH, context) ?: return
buffer.skipBytes(1)
type = buffer.readUnsignedByte().toInt()
id = buffer.readUnsignedShort()
contentLength = buffer.readUnsignedShort()
paddingLength = buffer.readUnsignedByte().toInt()
buffer.skipBytes(1)
state = DecodeRecordState.CONTENT
}
DecodeRecordState.CONTENT -> {
if (contentLength > 0) {
readContent(input, context, contentLength, this)
}
state = DecodeRecordState.HEADER
}
}
}
}
override fun channelInactive(context: ChannelHandlerContext) {
try {
if (!dataBuffers.isEmpty) {
dataBuffers.forEachEntry { a, buffer ->
try {
buffer.release()
}
catch (e: Throwable) {
LOG.error(e)
}
true
}
dataBuffers.clear()
}
}
finally {
super.channelInactive(context)
}
}
override fun contentReceived(buffer: ByteBuf, context: ChannelHandlerContext, isCumulateBuffer: Boolean): Void? {
when (type) {
RecordType.STDOUT -> {
var data = dataBuffers.get(id)
val sliced = if (isCumulateBuffer) buffer else buffer.slice(buffer.readerIndex(), contentLength)
when (data) {
null -> dataBuffers.put(id, sliced)
is CompositeByteBuf -> {
data.addComponent(sliced)
data.writerIndex(data.writerIndex() + sliced.readableBytes())
}
else -> {
if (sliced is CompositeByteBuf) {
data = sliced.addComponent(0, data)
data.writerIndex(data.writerIndex() + data.readableBytes())
}
else {
// must be computed here before we set data to new composite buffer
val newLength = data.readableBytes() + sliced.readableBytes()
data = context.alloc().compositeBuffer(Decoder.DEFAULT_MAX_COMPOSITE_BUFFER_COMPONENTS).addComponents(data, sliced)
data.writerIndex(data.writerIndex() + newLength)
}
dataBuffers.put(id, data)
}
}
sliced.retain()
}
RecordType.STDERR -> {
try {
errorOutputConsumer.consume(buffer.toString(buffer.readerIndex(), contentLength, CharsetUtil.UTF_8))
}
catch (e: Throwable) {
LOG.error(e)
}
}
RecordType.END_REQUEST -> {
val appStatus = buffer.readInt()
val protocolStatus = buffer.readUnsignedByte().toInt()
if (appStatus != 0 || protocolStatus != ProtocolStatus.REQUEST_COMPLETE.ordinal) {
LOG.warn("Protocol status $protocolStatus")
dataBuffers.remove(id)
responseHandler.responseReceived(id, null)
}
else if (protocolStatus == ProtocolStatus.REQUEST_COMPLETE.ordinal) {
responseHandler.responseReceived(id, dataBuffers.remove(id))
}
else {
LOG.warn("protocolStatus $protocolStatus")
}
}
else -> {
LOG.error("Unknown type $type")
}
}
return null
}
} | apache-2.0 | 983f89d19a2fd0a14bd66317d3e9f661 | 29.224359 | 174 | 0.607128 | 4.648915 | false | false | false | false |
RocketChat/Rocket.Chat.Android | app/src/main/java/chat/rocket/android/authentication/login/presentation/LoginPresenter.kt | 2 | 6826 | package chat.rocket.android.authentication.login.presentation
import chat.rocket.android.analytics.AnalyticsManager
import chat.rocket.android.analytics.event.AuthenticationEvent
import chat.rocket.android.authentication.presentation.AuthenticationNavigator
import chat.rocket.android.core.lifecycle.CancelStrategy
import chat.rocket.android.infrastructure.LocalRepository
import chat.rocket.android.server.domain.GetConnectingServerInteractor
import chat.rocket.android.server.domain.GetSettingsInteractor
import chat.rocket.android.server.domain.PublicSettings
import chat.rocket.android.server.domain.SaveAccountInteractor
import chat.rocket.android.server.domain.SaveCurrentServerInteractor
import chat.rocket.android.server.domain.TokenRepository
import chat.rocket.android.server.domain.favicon
import chat.rocket.android.server.domain.isLdapAuthenticationEnabled
import chat.rocket.android.server.domain.isPasswordResetEnabled
import chat.rocket.android.server.domain.model.Account
import chat.rocket.android.server.domain.siteName
import chat.rocket.android.server.domain.wideTile
import chat.rocket.android.server.infrastructure.RocketChatClientFactory
import chat.rocket.android.util.extension.launchUI
import chat.rocket.android.util.extensions.avatarUrl
import chat.rocket.android.util.extensions.isEmail
import chat.rocket.android.util.extensions.serverLogoUrl
import chat.rocket.android.util.retryIO
import chat.rocket.common.RocketChatException
import chat.rocket.common.RocketChatTwoFactorException
import chat.rocket.common.model.Email
import chat.rocket.common.model.Token
import chat.rocket.common.model.User
import chat.rocket.common.util.ifNull
import chat.rocket.core.RocketChatClient
import chat.rocket.core.internal.rest.login
import chat.rocket.core.internal.rest.loginWithEmail
import chat.rocket.core.internal.rest.loginWithLdap
import chat.rocket.core.internal.rest.me
import javax.inject.Inject
class LoginPresenter @Inject constructor(
private val view: LoginView,
private val strategy: CancelStrategy,
private val navigator: AuthenticationNavigator,
private val tokenRepository: TokenRepository,
private val localRepository: LocalRepository,
private val settingsInteractor: GetSettingsInteractor,
private val analyticsManager: AnalyticsManager,
private val saveCurrentServer: SaveCurrentServerInteractor,
private val saveAccountInteractor: SaveAccountInteractor,
private val factory: RocketChatClientFactory,
val serverInteractor: GetConnectingServerInteractor
) {
// TODO - we should validate the current server when opening the app, and have a nonnull get()
private var currentServer = serverInteractor.get()!!
private val token = tokenRepository.get(currentServer)
private lateinit var client: RocketChatClient
private lateinit var settings: PublicSettings
fun setupView() {
setupConnectionInfo(currentServer)
setupForgotPasswordView()
}
private fun setupConnectionInfo(serverUrl: String) {
currentServer = serverUrl
client = factory.get(currentServer)
settings = settingsInteractor.get(currentServer)
}
private fun setupForgotPasswordView() {
if (settings.isPasswordResetEnabled()) {
view.showForgotPasswordView()
}
}
fun authenticateWithUserAndPassword(usernameOrEmail: String, password: String) {
launchUI(strategy) {
view.showLoading()
try {
val token = retryIO("login") {
when {
settings.isLdapAuthenticationEnabled() ->
client.loginWithLdap(usernameOrEmail, password)
usernameOrEmail.isEmail() ->
client.loginWithEmail(usernameOrEmail, password)
else ->
client.login(usernameOrEmail, password)
}
}
val myself = retryIO("me()") { client.me() }
myself.username?.let { username ->
val user = User(
id = myself.id,
roles = myself.roles,
status = myself.status,
name = myself.name,
emails = myself.emails?.map { Email(it.address ?: "", it.verified) },
username = username,
utcOffset = myself.utcOffset
)
localRepository.saveCurrentUser(currentServer, user)
saveCurrentServer.save(currentServer)
localRepository.save(LocalRepository.CURRENT_USERNAME_KEY, username)
saveAccount(username)
saveToken(token)
analyticsManager.logLogin(
AuthenticationEvent.AuthenticationWithUserAndPassword,
true
)
view.saveSmartLockCredentials(usernameOrEmail, password)
navigator.toChatList()
}
} catch (exception: RocketChatException) {
when (exception) {
is RocketChatTwoFactorException -> {
navigator.toTwoFA(usernameOrEmail, password)
}
else -> {
analyticsManager.logLogin(
AuthenticationEvent.AuthenticationWithUserAndPassword,
false
)
exception.message?.let {
view.showMessage(it)
}.ifNull {
view.showGenericErrorMessage()
}
}
}
} finally {
view.hideLoading()
}
}
}
fun forgotPassword() = navigator.toForgotPassword()
private fun saveAccount(username: String) {
val icon = settings.favicon()?.let {
currentServer.serverLogoUrl(it)
}
val logo = settings.wideTile()?.let {
currentServer.serverLogoUrl(it)
}
val thumb = currentServer.avatarUrl(username, token?.userId, token?.authToken)
val account = Account(
serverName = settings.siteName() ?: currentServer,
serverUrl = currentServer,
serverLogoUrl = icon,
serverBackgroundImageUrl = logo,
userName = username,
userAvatarUrl = thumb,
authToken = token?.authToken,
userId = token?.userId
)
saveAccountInteractor.save(account)
}
private fun saveToken(token: Token) = tokenRepository.save(currentServer, token)
} | mit | ebe4ed4e51963d86d0c222a98c48adb8 | 41.403727 | 98 | 0.642836 | 5.283282 | false | false | false | false |
tommyettinger/SquidSetup | src/main/kotlin/com/github/czyzby/setup/data/platforms/android.kt | 1 | 8409 | package com.github.czyzby.setup.data.platforms
import com.github.czyzby.setup.data.files.SourceFile
import com.github.czyzby.setup.data.gradle.GradleFile
import com.github.czyzby.setup.data.project.Project
import com.github.czyzby.setup.views.GdxPlatform
/**
* Represents Android backend.
* @author MJ
*/
@GdxPlatform
class Android : Platform {
companion object {
const val ID = "android"
}
override val id = ID
override val isStandard = false // user should only jump through android hoops on request
override fun initiate(project: Project) {
project.rootGradle.buildDependencies.add("\"com.android.tools.build:gradle:\$androidPluginVersion\"")
project.properties["androidPluginVersion"] = project.advanced.androidPluginVersion
addGradleTaskDescription(project, "lint", "performs Android project validation.")
addCopiedFile(project, "ic_launcher-web.png")
addCopiedFile(project, "proguard-rules.pro")
addCopiedFile(project, "project.properties")
addCopiedFile(project, "res", "drawable-hdpi", "ic_launcher.png")
addCopiedFile(project, "res", "drawable-mdpi", "ic_launcher.png")
addCopiedFile(project, "res", "drawable-xhdpi", "ic_launcher.png")
addCopiedFile(project, "res", "drawable-xxhdpi", "ic_launcher.png")
addCopiedFile(project, "res", "values", "styles.xml")
project.files.add(SourceFile(projectName = "", sourceFolderPath = "", packageName = "", fileName = "local.properties",
content = "# Location of the Android SDK:\nsdk.dir=${project.basic.androidSdk}"))
project.files.add(SourceFile(projectName = ID, sourceFolderPath = "res", packageName = "values", fileName = "strings.xml",
content = """<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">${project.basic.name}</string>
</resources>
"""))
project.files.add(SourceFile(projectName = ID, sourceFolderPath = "", packageName = "", fileName = "AndroidManifest.xml",
content = """<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="${project.basic.rootPackage}">
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:isGame="true"
android:appCategory="game"
android:label="@string/app_name"
android:theme="@style/GdxTheme">
<activity
android:name="${project.basic.rootPackage}.AndroidLauncher"
android:label="@string/app_name"
android:screenOrientation="landscape"
android:configChanges="keyboard|keyboardHidden|navigation|orientation|screenSize|screenLayout">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
${project.androidPermissions.joinToString(separator = "\n") { " <uses-permission android:name=\"${it}\" />" }}
</manifest>
"""))
}
override fun createGradleFile(project: Project): GradleFile = AndroidGradleFile(project)
}
/**
* Gradle file of the Android project.
* @author MJ
*/
class AndroidGradleFile(val project: Project) : GradleFile(Android.ID) {
val plugins = mutableListOf<String>()
val srcFolders = mutableListOf("'src/main/java'")
val nativeDependencies = mutableSetOf<String>()
var latePlugin = false
init {
dependencies.add("project(':${Core.ID}')")
addDependency("com.badlogicgames.gdx:gdx-backend-android:\$gdxVersion")
addNativeDependency("com.badlogicgames.gdx:gdx-platform:\$gdxVersion:natives-armeabi-v7a")
addNativeDependency("com.badlogicgames.gdx:gdx-platform:\$gdxVersion:natives-arm64-v8a")
addNativeDependency("com.badlogicgames.gdx:gdx-platform:\$gdxVersion:natives-x86")
addNativeDependency("com.badlogicgames.gdx:gdx-platform:\$gdxVersion:natives-x86_64")
plugins.add("com.android.application")
}
fun insertLatePlugin() { latePlugin = true }
/**
* @param dependency will be added as "natives" dependency, quoted.
*/
fun addNativeDependency(dependency: String) = nativeDependencies.add("\"$dependency\"")
override fun getContent(): String = """${plugins.joinToString(separator = "\n") { "apply plugin: '$it'" }}
${if(latePlugin)"apply plugin: \'kotlin-android\'" else ""}
android {
compileSdkVersion ${project.advanced.androidSdkVersion}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = [${srcFolders.joinToString(separator = ", ")}]
aidl.srcDirs = [${srcFolders.joinToString(separator = ", ")}]
renderscript.srcDirs = [${srcFolders.joinToString(separator = ", ")}]
res.srcDirs = ['res']
assets.srcDirs = ['../assets']
jniLibs.srcDirs = ['libs']
}
}
packagingOptions {
// Preventing from license violations (more or less):
pickFirst 'META-INF/LICENSE.txt'
pickFirst 'META-INF/LICENSE'
pickFirst 'META-INF/license.txt'
pickFirst 'META-INF/LGPL2.1'
pickFirst 'META-INF/NOTICE.txt'
pickFirst 'META-INF/NOTICE'
pickFirst 'META-INF/notice.txt'
// Excluding unnecessary meta-data:
exclude 'META-INF/robovm/ios/robovm.xml'
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/dependencies.txt'
}
defaultConfig {
applicationId '${project.basic.rootPackage}'
minSdkVersion 19
targetSdkVersion ${project.advanced.androidSdkVersion}
versionCode 1
versionName "1.0"
multiDexEnabled true
}
compileOptions {
sourceCompatibility "${project.advanced.javaVersion}"
targetCompatibility "${project.advanced.javaVersion}"
${if(project.advanced.javaVersion != "1.6" && project.advanced.javaVersion != "1.7")"coreLibraryDesugaringEnabled true" else ""}
}
${if(latePlugin && project.advanced.javaVersion != "1.6" && project.advanced.javaVersion != "1.7")"kotlinOptions.jvmTarget = \"1.8\"" else ""}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
// needed for AAPT2, may be needed for other tools
google()
}
configurations { natives }
dependencies {
${if(project.advanced.javaVersion != "1.6" && project.advanced.javaVersion != "1.7")"coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'" else ""}
${joinDependencies(dependencies)}
${joinDependencies(nativeDependencies, "natives")}
}
// Called every time gradle gets executed, takes the native dependencies of
// the natives configuration, and extracts them to the proper libs/ folders
// so they get packed with the APK.
task copyAndroidNatives() {
doFirst {
file("libs/armeabi-v7a/").mkdirs()
file("libs/arm64-v8a/").mkdirs()
file("libs/x86_64/").mkdirs()
file("libs/x86/").mkdirs()
configurations.getByName("natives").copy().files.each { jar ->
def outputDir = null
if(jar.name.endsWith("natives-armeabi-v7a.jar")) outputDir = file("libs/armeabi-v7a")
if(jar.name.endsWith("natives-arm64-v8a.jar")) outputDir = file("libs/arm64-v8a")
if(jar.name.endsWith("natives-x86_64.jar")) outputDir = file("libs/x86_64")
if(jar.name.endsWith("natives-x86.jar")) outputDir = file("libs/x86")
if(outputDir != null) {
copy {
from zipTree(jar)
into outputDir
include "*.so"
}
}
}
}
}
tasks.whenTaskAdded { packageTask ->
if (packageTask.name.contains("package")) {
packageTask.dependsOn 'copyAndroidNatives'
}
}
task run(type: Exec) {
def path
def localProperties = project.file("../local.properties")
if (localProperties.exists()) {
Properties properties = new Properties()
localProperties.withInputStream { instr ->
properties.load(instr)
}
def sdkDir = properties.getProperty('sdk.dir')
if (sdkDir) {
path = sdkDir
} else {
path = "${'$'}System.env.ANDROID_HOME"
}
} else {
path = "${'$'}System.env.ANDROID_HOME"
}
def adb = path + "/platform-tools/adb"
commandLine "${'$'}adb", 'shell', 'am', 'start', '-n', '${project.basic.rootPackage}/${project.basic.rootPackage}.AndroidLauncher'
}
eclipse.project.name = appName + "-android"
"""
}
| apache-2.0 | b174ccc5dca1be83d36c04d6c756d397 | 36.878378 | 160 | 0.674872 | 3.792963 | false | false | false | false |
tangying91/profit | src/main/java/org/profit/app/seeker/StockHistorySeeker.kt | 1 | 1396 | package org.profit.app.seeker
import org.jsoup.nodes.Document
import org.profit.config.StockProperties
import org.profit.util.FileUtils
/**
* 历史数据爬取
*/
class StockHistorySeeker(code: String) : StockSeeker(code, StockProperties.historyUrl) {
/**
* 解析数据
*/
override fun handle(doc: Document) {
val sb = StringBuffer()
// 正常数据解析数据表格
val div = doc.getElementById("ctl16_contentdiv")
val table = div.getElementsByTag("table")
// 检查条件是否匹配
if (table != null) {
// 以tr每行作为一个单独对象判断
for (tr in table.select("tr")) {
val tds = tr.select("td")
val td = tds.removeClass("altertd").text()
// 過濾垃圾數據
if (td.contains("日期") || td.contains("End")) {
continue
}
// 保存數據
if (sb.isNotEmpty()) {
sb.append("\r\n").append(td)
} else {
sb.append(td)
}
}
// 寫入文件
if (sb.isNotEmpty()) {
FileUtils.writeHistory(code, sb.toString())
FileUtils.writeLog(code)
}
}
}
} | apache-2.0 | 48dc97e4b57407df1522cb86aa1265f3 | 24.204082 | 88 | 0.459438 | 3.96904 | false | false | false | false |
cketti/k-9 | app/ui/legacy/src/main/java/com/fsck/k9/account/AccountCreator.kt | 1 | 2766 | package com.fsck.k9.account
import android.content.res.Resources
import com.fsck.k9.Account.DeletePolicy
import com.fsck.k9.Preferences
import com.fsck.k9.core.R
import com.fsck.k9.mail.ConnectionSecurity
import com.fsck.k9.preferences.Protocols
/**
* Deals with logic surrounding account creation.
*
* TODO Move much of the code from com.fsck.k9.activity.setup.* into here
*/
class AccountCreator(private val preferences: Preferences, private val resources: Resources) {
fun getDefaultDeletePolicy(type: String): DeletePolicy {
return when (type) {
Protocols.IMAP -> DeletePolicy.ON_DELETE
Protocols.POP3 -> DeletePolicy.NEVER
Protocols.WEBDAV -> DeletePolicy.ON_DELETE
"demo" -> DeletePolicy.ON_DELETE
else -> throw AssertionError("Unhandled case: $type")
}
}
fun getDefaultPort(securityType: ConnectionSecurity, serverType: String): Int {
return when (serverType) {
Protocols.IMAP -> getImapDefaultPort(securityType)
Protocols.WEBDAV -> getWebDavDefaultPort(securityType)
Protocols.POP3 -> getPop3DefaultPort(securityType)
Protocols.SMTP -> getSmtpDefaultPort(securityType)
else -> throw AssertionError("Unhandled case: $serverType")
}
}
private fun getImapDefaultPort(connectionSecurity: ConnectionSecurity): Int {
return if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) 993 else 143
}
private fun getPop3DefaultPort(connectionSecurity: ConnectionSecurity): Int {
return if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) 995 else 110
}
private fun getWebDavDefaultPort(connectionSecurity: ConnectionSecurity): Int {
return if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) 443 else 80
}
private fun getSmtpDefaultPort(connectionSecurity: ConnectionSecurity): Int {
return if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) 465 else 587
}
fun pickColor(): Int {
val accounts = preferences.accounts
val usedAccountColors = accounts.map { it.chipColor }.toSet()
val accountColors = resources.getIntArray(R.array.account_colors).toList()
val availableColors = accountColors - usedAccountColors
if (availableColors.isEmpty()) {
return accountColors.random()
}
val defaultAccountColors = resources.getIntArray(R.array.default_account_colors)
return availableColors.shuffled().minByOrNull { color ->
val index = defaultAccountColors.indexOf(color)
if (index != -1) index else defaultAccountColors.size
} ?: error("availableColors must not be empty")
}
}
| apache-2.0 | c9840afa4f837956bc0b24bd5eadac42 | 39.086957 | 94 | 0.698482 | 4.57947 | false | false | false | false |
wax911/android-emojify | emojify/src/androidTest/java/io/wax911/emojify/EmojiParseTest.kt | 1 | 16143 | package io.wax911.emojify
import androidx.startup.AppInitializer
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import androidx.test.platform.app.InstrumentationRegistry
import io.wax911.emojify.initializer.EmojiInitializer
import io.wax911.emojify.model.Emoji
import io.wax911.emojify.parser.*
import io.wax911.emojify.parser.action.FitzpatrickAction
import io.wax911.emojify.util.Fitzpatrick
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumentation test, which will execute on an Android device.
*
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
@RunWith(AndroidJUnit4ClassRunner::class)
class EmojiParseTest {
private val context by lazy { InstrumentationRegistry.getInstrumentation().context }
private val emojiManager by lazy {
AppInitializer.getInstance(context)
.initializeComponent(EmojiInitializer::class.java)
}
@Before
fun testApplicationContext() {
Assert.assertNotNull(context)
}
@Before
fun testEmojiLoading() {
Assert.assertNotNull(emojiManager)
Assert.assertTrue(emojiManager.emojiList.isNotEmpty())
}
@Test
fun parseToAliases_replaces_the_emojis_by_one_of_their_aliases() {
// GIVEN
val str = "An 😀awesome 😃string with a few 😉emojis!"
// WHEN
val result = emojiManager.parseToAliases(str)
// THEN
Assert.assertEquals(
"An :grinning:awesome :smiley:string with a few :wink:emojis!",
result
)
}
@Test
@Throws(Exception::class)
fun replaceAllEmojis_replace_the_emojis_by_string() {
// GIVEN
val str = "An 😀awesome 😃string with a few 😉emojis!"
// WHEN
val result = emojiManager.replaceAllEmojis(str, ":)")
// THEN
Assert.assertEquals(
"An :)awesome :)string with a few :)emojis!",
result
)
}
@Test
fun parseToAliases_REPLACE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToAliases(str)
// THEN
Assert.assertEquals(":boy|type_6:", result)
}
@Test
fun parseToAliases_REMOVE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToAliases(str, FitzpatrickAction.REMOVE)
// THEN
Assert.assertEquals(":boy:", result)
}
@Test
fun parseToAliases_REMOVE_without_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66"
// WHEN
val result = emojiManager.parseToAliases(str, FitzpatrickAction.REMOVE)
// THEN
Assert.assertEquals(":boy:", result)
}
@Test
fun parseToAliases_IGNORE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToAliases(str, FitzpatrickAction.IGNORE)
// THEN
Assert.assertEquals(":boy:\uD83C\uDFFF", result)
}
@Test
fun parseToAliases_IGNORE_without_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66"
// WHEN
val result = emojiManager.parseToAliases(str, FitzpatrickAction.IGNORE)
// THEN
Assert.assertEquals(":boy:", result)
}
@Test
fun parseToAliases_with_long_overlapping_emoji() {
// GIVEN
val str = "\uD83D\uDC68\u200D\uD83D\uDC69\u200D\uD83D\uDC66"
// WHEN
val result = emojiManager.parseToAliases(str)
//With greedy parsing, this will give :man::woman::boy:
//THEN
Assert.assertEquals(":family_man_woman_boy:", result)
}
@Test
fun parseToAliases_continuous_non_overlapping_emojis() {
// GIVEN
val str = "\uD83D\uDC69\uD83D\uDC68\uD83D\uDC66"
// WHEN
val result = emojiManager.parseToAliases(str)
//THEN
Assert.assertEquals(":woman::man::boy:", result)
}
@Test
fun parseToHtmlDecimal_replaces_the_emojis_by_their_html_decimal_representation() {
// GIVEN
val str = "An 😀awesome 😃string with a few 😉emojis!"
// WHEN
val result = emojiManager.parseToHtmlDecimal(str)
// THEN
Assert.assertEquals(
"An 😀awesome 😃string with a few 😉emojis!",
result
)
}
@Test
fun parseToHtmlDecimal_PARSE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToHtmlDecimal(
str,
FitzpatrickAction.PARSE
)
// THEN
Assert.assertEquals("👦", result)
}
@Test
fun parseToHtmlDecimal_REMOVE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToHtmlDecimal(
str,
FitzpatrickAction.REMOVE
)
// THEN
Assert.assertEquals("👦", result)
}
@Test
fun parseToHtmlDecimal_IGNORE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToHtmlDecimal(
str,
FitzpatrickAction.IGNORE
)
// THEN
Assert.assertEquals("👦\uD83C\uDFFF", result)
}
@Test
fun parseToHtmlHexadecimal_replaces_the_emojis_by_their_htm_hex_representation() {
// GIVEN
val str = "An 😀awesome 😃string with a few 😉emojis!"
// WHEN
val result = emojiManager.parseToHtmlHexadecimal(str)
// THEN
Assert.assertEquals(
"An 😀awesome 😃string with a few 😉emojis!",
result
)
}
@Test
fun parseToHtmlHexadecimal_PARSE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToHtmlHexadecimal(
str,
FitzpatrickAction.PARSE
)
// THEN
Assert.assertEquals("👦", result)
}
@Test
fun parseToHtmlHexadecimal_REMOVE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToHtmlHexadecimal(
str,
FitzpatrickAction.REMOVE
)
// THEN
Assert.assertEquals("👦", result)
}
@Test
fun parseToHtmlHexadecimal_IGNORE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToHtmlHexadecimal(
str,
FitzpatrickAction.IGNORE
)
// THEN
Assert.assertEquals("👦\uD83C\uDFFF", result)
}
@Test
fun parseToUnicode_replaces_the_aliases_and_the_html_by_their_emoji() {
// GIVEN
val str = "An :grinning:awesome :smiley:string " + "😄with a few 😉emojis!"
// WHEN
val result = emojiManager.parseToUnicode(str)
// THEN
Assert.assertEquals("An 😀awesome 😃string 😄with a few 😉emojis!", result)
}
@Test
fun parseToUnicode_with_the_thumbs_up_emoji_replaces_the_alias_by_the_emoji() {
// GIVEN
val str = "An :+1:awesome :smiley:string " + "😄with a few :wink:emojis!"
// WHEN
val result = emojiManager.parseToUnicode(str)
// THEN
Assert.assertEquals(
"An \uD83D\uDC4Dawesome 😃string 😄with a few 😉emojis!",
result
)
}
@Test
fun parseToUnicode_with_the_thumbsdown_emoji_replaces_the_alias_by_the_emoji() {
// GIVEN
val str = "An :-1:awesome :smiley:string 😄" + "with a few :wink:emojis!"
// WHEN
val result = emojiManager.parseToUnicode(str)
// THEN
Assert.assertEquals(
"An \uD83D\uDC4Eawesome 😃string 😄with a few 😉emojis!",
result
)
}
@Test
fun parseToUnicode_with_the_thumbs_up_emoji_in_hex_replaces_the_alias_by_the_emoji() {
// GIVEN
val str = "An :+1:awesome :smiley:string 😄" + "with a few :wink:emojis!"
// WHEN
val result = emojiManager.parseToUnicode(str)
// THEN
Assert.assertEquals(
"An \uD83D\uDC4Dawesome 😃string 😄with a few 😉emojis!",
result
)
}
@Test
fun parseToUnicode_with_a_fitzpatrick_modifier() {
// GIVEN
val str = ":boy|type_6:"
// WHEN
val result = emojiManager.parseToUnicode(str)
// THEN
Assert.assertEquals("\uD83D\uDC66\uD83C\uDFFF", result)
}
@Test
fun parseToUnicode_with_an_unsupported_fitzpatrick_modifier_does_not_replace() {
// GIVEN
val str = ":grinning|type_6:"
// WHEN
val result = emojiManager.parseToUnicode(str)
// THEN
Assert.assertEquals(str, result)
}
@Test
fun getAliasCanditates_with_one_alias() {
// GIVEN
val str = "test :candidate: test"
// WHEN
val candidates = getAliasCandidates(str)
// THEN
Assert.assertEquals(1, candidates.size)
Assert.assertEquals("candidate", candidates.first().alias)
Assert.assertNull(candidates.first().fitzpatrick)
}
@Test
fun getAliasCanditates_with_one_alias_an_another_colon_after() {
// GIVEN
val str = "test :candidate: test:"
// WHEN
val candidates = getAliasCandidates(str)
// THEN
Assert.assertEquals(1, candidates.size)
Assert.assertEquals("candidate", candidates.first().alias)
Assert.assertNull(candidates.first().fitzpatrick)
}
@Test
fun getAliasCanditates_with_one_alias_an_another_colon_right_after() {
// GIVEN
val str = "test :candidate::test"
// WHEN
val candidates = getAliasCandidates(str)
// THEN
Assert.assertEquals(1, candidates.size)
Assert.assertEquals("candidate", candidates.first().alias)
Assert.assertNull(candidates.first().fitzpatrick)
}
@Test
fun getAliasCanditates_with_one_alias_an_another_colon_before_after() {
// GIVEN
val str = "test ::candidate: test"
// WHEN
val candidates = getAliasCandidates(str)
// THEN
Assert.assertEquals(1, candidates.size)
Assert.assertEquals("candidate", candidates.first().alias)
Assert.assertNull(candidates.first().fitzpatrick)
}
@Test
fun getAliasCanditates_with_two_aliases() {
// GIVEN
val str = "test :candi: :candidate: test"
// WHEN
val candidates = getAliasCandidates(str)
// THEN
Assert.assertEquals(2, candidates.size)
Assert.assertEquals("candi", candidates.first().alias)
Assert.assertNull(candidates.first().fitzpatrick)
Assert.assertEquals("candidate", candidates[1].alias)
Assert.assertNull(candidates[1].fitzpatrick)
}
@Test
fun getAliasCanditates_with_two_aliases_sharing_a_colon() {
// GIVEN
val str = "test :candi:candidate: test"
// WHEN
val candidates = getAliasCandidates(str)
// THEN
Assert.assertEquals(2, candidates.size)
Assert.assertEquals("candi", candidates.first().alias)
Assert.assertNull(candidates.first().fitzpatrick)
Assert.assertEquals("candidate", candidates[1].alias)
Assert.assertNull(candidates[1].fitzpatrick)
}
@Test
fun getAliasCanditates_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "test :candidate|type_3: test"
// WHEN
val candidates = getAliasCandidates(str)
// THEN
Assert.assertEquals(1, candidates.size)
Assert.assertEquals("candidate", candidates.first().alias)
Assert.assertEquals(Fitzpatrick.TYPE_3, candidates.first().fitzpatrick)
}
@Test
fun test_with_a_new_flag() {
val input = "Cuba has a new flag! :cu:"
val expected = "Cuba has a new flag! \uD83C\uDDE8\uD83C\uDDFA"
Assert.assertEquals(expected, emojiManager.parseToUnicode(input))
Assert.assertEquals(input, emojiManager.parseToAliases(expected))
}
@Test
fun removeAllEmojis_removes_all_the_emojis_from_the_string() {
// GIVEN
val input = "An 😀awesome 😃string 😄with " + "a \uD83D\uDC66\uD83C\uDFFFfew 😉emojis!"
// WHEN
val result = emojiManager.removeAllEmojis(input)
// THEN
val expected = "An awesome string with a few emojis!"
Assert.assertEquals(expected, result)
}
@Test
fun removeEmojis_only_removes_the_emojis_in_the_iterable_from_the_string() {
// GIVEN
val input = "An\uD83D\uDE03 awesome\uD83D\uDE04 string" + "\uD83D\uDC4D\uD83C\uDFFF with\uD83D\uDCAA\uD83C\uDFFD a few emojis!"
val emojis = ArrayList<Emoji>()
val smile = emojiManager.getForAlias("smile")
val onePlus = emojiManager.getForAlias("+1")
Assert.assertNotNull(smile)
Assert.assertNotNull(onePlus)
emojis.add(smile!!)
emojis.add(onePlus!!)
// WHEN
val result = emojiManager.removeEmojis(input, emojis)
// THEN
val expected = "An\uD83D\uDE03 awesome string with" + "\uD83D\uDCAA\uD83C\uDFFD a few emojis!"
Assert.assertEquals(expected, result)
}
@Test
fun removeAllEmojisExcept_removes_all_the_emojis_from_the_string_except_those_in_the_iterable() {
// GIVEN
val input = "An\uD83D\uDE03 awesome\uD83D\uDE04 string" + "\uD83D\uDC4D\uD83C\uDFFF with\uD83D\uDCAA\uD83C\uDFFD a few emojis!"
val emojis = ArrayList<Emoji>()
val smile = emojiManager.getForAlias("smile")
val onePlus = emojiManager.getForAlias("+1")
Assert.assertNotNull(smile)
Assert.assertNotNull(onePlus)
emojis.add(smile!!)
emojis.add(onePlus!!)
// WHEN
val result = emojiManager.removeAllEmojisExcept(input, emojis)
// THEN
val expected = "An awesome\uD83D\uDE04 string\uD83D\uDC4D\uD83C\uDFFF " + "with a few emojis!"
Assert.assertEquals(expected, result)
}
@Test
fun parseToUnicode_with_the_keycap_asterisk_emoji_replaces_the_alias_by_the_emoji() {
// GIVEN
val str = "Let's test the :keycap_asterisk: emoji and " + "its other alias :star_keycap:"
// WHEN
val result = emojiManager.parseToUnicode(str)
// THEN
Assert.assertEquals("Let's test the *⃣ emoji and its other alias *⃣", result)
}
@Test
fun parseToAliases_NG_and_nigeria() {
// GIVEN
val str = "Nigeria is 🇳🇬, NG is 🆖"
// WHEN
val result = emojiManager.parseToAliases(str)
// THEN
Assert.assertEquals("Nigeria is :ng:, NG is :squared_ng:", result)
}
@Test
fun parseToAliases_couplekiss_woman_woman() {
// GIVEN
val str = "👩❤️💋👩"
// WHEN
val result = emojiManager.parseToAliases(str)
// THEN
Assert.assertEquals(":couplekiss_woman_woman:", result)
}
@Test
fun extractEmojis() {
// GIVEN
val str = "An 😀awesome 😃string with a few 😉emojis!"
// WHEN
val result = emojiManager.extractEmojis(str)
// THEN
Assert.assertEquals("😀", result[0])
Assert.assertEquals("😃", result[1])
Assert.assertEquals("😉", result[2])
}
} | mit | 673e4f0889cf9497ae03c3a85120ca5d | 26.550775 | 135 | 0.599213 | 3.877422 | false | true | false | false |
iarchii/trade_app | app/src/main/java/xyz/thecodeside/tradeapp/helpers/ViewExtensions.kt | 1 | 826 | package xyz.thecodeside.tradeapp.helpers
import android.util.DisplayMetrics
import android.view.View
import android.widget.EditText
fun View.hide() {
this.visibility = View.GONE
}
fun View.show() {
this.visibility = View.VISIBLE
}
fun View.invisible() {
this.visibility = View.INVISIBLE
}
fun View.convertDpToPixel(dp: Int): Int{
val resources = context.resources
val metrics = resources.displayMetrics
val px = dp * (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
return px.toInt()
}
fun View.convertPixelsToDp(px: Int): Int {
val resources = context.resources
val metrics = resources.displayMetrics
val dp = px / (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
return dp.toInt()
}
fun EditText.getStringText(): String = this.text.toString() | apache-2.0 | 993be8b097c916746ab34b10e6193c0e | 23.323529 | 81 | 0.728814 | 3.859813 | false | false | false | false |
esafirm/android-image-picker | sample/src/androidTest/java/com/esafirm/sample/matchers/DrawableMatcher.kt | 2 | 803 | package com.esafirm.sample.matchers
import android.view.View
import android.widget.ImageView
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.TypeSafeMatcher
class DrawableMatcher(private val expected: Int) : TypeSafeMatcher<View>() {
override fun matchesSafely(target: View): Boolean {
val imageView = target as ImageView
if (expected == EMPTY) {
return imageView.drawable == null
}
if (expected == ANY) {
return imageView.drawable != null
}
return false
}
override fun describeTo(description: Description) {}
companion object {
const val EMPTY = -1
const val ANY = -2
}
}
fun hasDrawable(): Matcher<View> {
return DrawableMatcher(DrawableMatcher.ANY)
} | mit | 7b6000b80c18839c2a8d76d13dc897e8 | 24.125 | 76 | 0.666252 | 4.614943 | false | false | false | false |
googlemaps/codelab-places-101-android-kotlin | starter/app/src/main/java/com/google/codelabs/maps/placesdemo/MainActivity.kt | 2 | 2581 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.codelabs.maps.placesdemo
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// List the available demos
val listView = ListView(this).also {
it.layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
it.adapter = DemoAdapter(this, Demo.values())
it.onItemClickListener = AdapterView.OnItemClickListener { parent, _, position, _ ->
val demo = parent.adapter.getItem(position) as? Demo
demo?.let {
startActivity(Intent(this, demo.activity))
}
}
}
setContentView(listView)
}
private class DemoAdapter(context: Context, demos: Array<Demo>) :
ArrayAdapter<Demo>(context, R.layout.item_demo, demos) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val demoView = (convertView as? DemoItemView) ?: DemoItemView(context)
return demoView.also {
val demo = getItem(position)
it.title.setText(demo?.title ?: 0)
it.description.setText(demo?.description ?: 0)
}
}
}
private class DemoItemView(context: Context) : LinearLayout(context) {
val title: TextView by lazy { findViewById(R.id.textViewTitle) }
val description: TextView by lazy { findViewById(R.id.textViewDescription) }
init {
LayoutInflater.from(context)
.inflate(R.layout.item_demo, this)
}
}
} | apache-2.0 | 53244873695d0e3b16e7a9d46d451329 | 33.891892 | 96 | 0.652848 | 4.65045 | false | false | false | false |
vanniktech/Emoji | emoji/src/androidMain/kotlin/com/vanniktech/emoji/internal/EmojiSearchDialog.kt | 1 | 7581 | /*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.vanniktech.emoji.internal
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.content.res.ColorStateList
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.SpannableString
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.Px
import androidx.appcompat.app.AlertDialog
import androidx.core.view.ViewCompat
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.vanniktech.emoji.Emoji
import com.vanniktech.emoji.EmojiTextView
import com.vanniktech.emoji.EmojiTheming
import com.vanniktech.emoji.R
import com.vanniktech.emoji.search.SearchEmoji
import com.vanniktech.emoji.search.SearchEmojiResult
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
internal fun interface EmojiSearchDialogDelegate {
fun onSearchEmojiClick(emoji: Emoji)
}
internal class EmojiSearchDialog : DialogFragment() {
private var delegate: EmojiSearchDialogDelegate? = null
private var searchEmoji: SearchEmoji? = null
private val handler = Handler(Looper.getMainLooper())
private var future: ScheduledFuture<*>? = null
private val executorService = Executors.newSingleThreadScheduledExecutor()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val activity = requireActivity()
val dialog = AlertDialog.Builder(activity, theme)
.setView(R.layout.emoji_dialog_search)
.show()
val root = dialog.findViewById<View>(R.id.root)
val arguments = requireArguments()
val theming = arguments.parcelable<EmojiTheming>(ARG_THEMING)!!
root?.setBackgroundColor(theming.backgroundColor)
val editText = dialog.findViewById<EditText>(R.id.editText)!!
editText.setTextColor(theming.textColor)
val secondaryColor = theming.secondaryColor
editText.setCursorDrawableColor(secondaryColor)
editText.setHandlesColor(secondaryColor)
editText.highlightColor = secondaryColor
ViewCompat.setBackgroundTintList(editText, ColorStateList.valueOf(secondaryColor))
val recyclerView = dialog.findViewById<MaxHeightSearchRecyclerView>(R.id.recyclerView)
val adapter = EmojiAdapter(
theming = theming,
emojiSearchDialogDelegate = {
delegate?.onSearchEmojiClick(it)
dismiss()
},
)
recyclerView?.tint(theming)
recyclerView?.adapter = adapter
editText.addTextChangedListener(
object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
override fun afterTextChanged(s: Editable) {
val query = s.toString()
future?.cancel(true)
handler.removeCallbacksAndMessages(null)
future = executorService.schedule({
val emojis = searchEmoji?.search(query).orEmpty()
handler.post {
adapter.update(emojis, marginStart = null)
}
}, 300, TimeUnit.MILLISECONDS,)
}
},
)
editText.postDelayed({
editText.showKeyboardAndFocus()
}, 300L,)
return dialog
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
future?.cancel(true)
executorService?.shutdownNow()
handler.removeCallbacksAndMessages(null)
delegate = null
}
internal companion object {
private const val TAG = "EmojiSearchDialog"
private const val ARG_THEMING = "arg-theming"
fun show(
context: Context,
delegate: EmojiSearchDialogDelegate,
searchEmoji: SearchEmoji,
theming: EmojiTheming,
) {
EmojiSearchDialog().apply {
arguments = Bundle(1).apply {
putParcelable(ARG_THEMING, theming)
}
this.delegate = delegate
this.searchEmoji = searchEmoji
show((Utils.asActivity(context) as FragmentActivity).supportFragmentManager, TAG)
}
}
}
}
internal class EmojiAdapter(
private val theming: EmojiTheming,
private val emojiSearchDialogDelegate: EmojiSearchDialogDelegate?,
) : RecyclerView.Adapter<EmojiViewHolder>() {
@Px private var marginStart: Int? = null
private var items = emptyList<SearchEmojiResult>()
init {
setHasStableIds(true)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = EmojiViewHolder(parent)
override fun onBindViewHolder(holder: EmojiViewHolder, position: Int) {
val context = holder.textView.context
val item = items[position]
holder.textView.setTextColor(theming.textColor) // This is just in case there's a glyph shown.
holder.textView.text = item.emoji.unicode
(holder.textView.layoutParams as LinearLayout.LayoutParams).marginStart = marginStart ?: context.resources.getDimensionPixelSize(R.dimen.emoji_search_spacing)
val shortCode = item.shortcode
holder.shortCodes.text = SpannableString(shortCode).apply {
setSpan(ForegroundColorSpan(theming.textSecondaryColor), 0, shortCode.length, 0)
setSpan(ForegroundColorSpan(theming.secondaryColor), item.range.first, item.range.last + 1, 0)
}
holder.itemView.setOnClickListener {
emojiSearchDialogDelegate?.onSearchEmojiClick(item.emoji)
}
}
override fun getItemCount() = items.size
fun update(
new: List<SearchEmojiResult>,
@Px marginStart: Int?,
) {
val old = ArrayList(items)
items = new
this.marginStart = marginStart
DiffUtil.calculateDiff(DiffUtilHelper(old, items) { it.hashCode() })
.dispatchUpdatesTo(this)
}
}
internal class EmojiViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.emoji_adapter_item_emoji_search, parent, false)) {
val textView: EmojiTextView by lazy(LazyThreadSafetyMode.NONE) { itemView.findViewById(R.id.textView) }
val shortCodes: TextView by lazy(LazyThreadSafetyMode.NONE) { itemView.findViewById(R.id.shortCodes) }
}
internal class DiffUtilHelper<T>(
private val old: List<T>,
private val new: List<T>,
private val id: (T) -> Int,
) : DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
id(old[oldItemPosition]) == id(new[newItemPosition])
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
old[oldItemPosition] == new[newItemPosition]
override fun getOldListSize() = old.size
override fun getNewListSize() = new.size
}
| apache-2.0 | b7127fb7829f6392ff78c3dcf6d76dad | 33.766055 | 179 | 0.743106 | 4.562914 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/gui/components/bars/CallbackBarProvider.kt | 2 | 1404 | package com.cout970.magneticraft.systems.gui.components.bars
import com.cout970.magneticraft.misc.clamp
import com.cout970.magneticraft.misc.crafting.TimedCraftingProcess
import com.cout970.magneticraft.misc.ensureNonZero
import com.cout970.magneticraft.misc.gui.ValueAverage
val ZERO = { 0.0 }
open class CallbackBarProvider(val callback: () -> Number, val max: () -> Number,
val min: () -> Number) : IBarProvider {
override fun getLevel(): Float {
val min = min.invoke().toDouble()
val max = max.invoke().toDouble()
val value = callback.invoke().toDouble()
return clamp((value - min) / ensureNonZero(max - min), 1.0, 0.0).toFloat()
}
}
class StaticBarProvider(val minVal: Double, val maxVal: Double, callback: () -> Number)
: CallbackBarProvider(callback = callback, max = { maxVal }, min = { minVal })
fun TimedCraftingProcess.toBarProvider() = CallbackBarProvider(this::timer, this::limit, ZERO)
fun ValueAverage.toBarProvider(max: Number) = CallbackBarProvider(this::storage, { max }, ZERO)
fun CallbackBarProvider.toPercentText(prefix: String = "", postfix: String = "%"): () -> List<String> = {
listOf("$prefix${(getLevel() * 100.0).toInt()}$postfix")
}
fun CallbackBarProvider.toIntText(prefix: String = "", postfix: String = ""): () -> List<String> = {
listOf("$prefix${callback().toInt()}$postfix")
} | gpl-2.0 | 7e4411fb6330d5c16d229f24a12b3688 | 38.027778 | 105 | 0.680199 | 3.889197 | false | false | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/box/BoxAuthFlow.kt | 1 | 1552 | package com.baulsupp.okurl.services.box
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.okurl.authenticator.SimpleWebServer
import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token
import com.baulsupp.okurl.credentials.NoToken
import com.baulsupp.okurl.kotlin.queryMap
import com.baulsupp.okurl.kotlin.requestBuilder
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Response
import java.net.URLEncoder
object BoxAuthFlow {
suspend fun login(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
clientId: String,
clientSecret: String,
scopes: List<String>
): Oauth2Token {
SimpleWebServer.forCode().use { s ->
val scopesString = URLEncoder.encode(scopes.joinToString(" "), "UTF-8")
val loginUrl =
"https://account.box.com/api/oauth2/authorize?client_id=$clientId&scope=$scopesString&response_type=code&state=x&redirect_uri=${s.redirectUri}"
outputHandler.openLink(loginUrl)
val code = s.waitForCode()
val body = FormBody.Builder().add("grant_type", "authorization_code").add("code", code).add("client_id", clientId)
.add("client_secret", clientSecret).build()
val request = requestBuilder(
"https://api.box.com/oauth2/token",
NoToken
)
.post(body)
.build()
val responseMap = client.queryMap<Any>(request)
return Oauth2Token(
responseMap["access_token"] as String,
responseMap["refresh_token"] as String, clientId, clientSecret
)
}
}
}
| apache-2.0 | b3f9ad274e17838adf9fa633e86885ec | 30.673469 | 151 | 0.709407 | 4.052219 | false | false | false | false |
lttng/lttng-scope | lttng-scope-ui/src/main/kotlin/org/lttng/scope/views/timeline/widgets/xychart/XYChartFullRangeWidget.kt | 1 | 10828 | /*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.lttng.scope.views.timeline.widgets.xychart
import com.efficios.jabberwocky.common.TimeRange
import com.efficios.jabberwocky.context.ViewGroupContext
import com.efficios.jabberwocky.project.TraceProject
import com.efficios.jabberwocky.views.xychart.control.XYChartControl
import com.efficios.jabberwocky.views.xychart.model.render.XYChartRender
import javafx.application.Platform
import javafx.beans.binding.Bindings
import javafx.beans.value.ChangeListener
import javafx.collections.FXCollections
import javafx.geometry.Insets
import javafx.scene.chart.XYChart
import javafx.scene.layout.BorderPane
import javafx.scene.layout.Pane
import javafx.scene.layout.StackPane
import javafx.scene.paint.Color
import javafx.scene.shape.Rectangle
import javafx.scene.shape.StrokeLineCap
import org.lttng.scope.common.jfx.TimeAxis
import org.lttng.scope.views.timeline.NavigationAreaWidget
import org.lttng.scope.views.timeline.TimelineWidget
import org.lttng.scope.views.timeline.widgets.xychart.layer.XYChartDragHandlers
import org.lttng.scope.views.timeline.widgets.xychart.layer.XYChartScrollHandlers
import org.lttng.scope.views.timeline.widgets.xychart.layer.XYChartSelectionLayer
/**
* Widget for the timeline view showing data in a XY-Chart. The chart will
* display data representing the whole trace, and will display highlighted
* rectangles representing the current visible and selection time ranges.
*/
class XYChartFullRangeWidget(control: XYChartControl, override val weight: Int) : XYChartWidget(control), NavigationAreaWidget {
companion object {
/* Number of data poins we request to the backend */
private const val NB_DATA_POINTS = 200
private const val CHART_HEIGHT = 50.0
private val VISIBLE_RANGE_STROKE_WIDTH = 4.0
private val VISIBLE_RANGE_ARC = 5.0
private val VISIBLE_RANGE_STROKE_COLOR = Color.GRAY
private val VISIBLE_RANGE_FILL_COLOR = Color.LIGHTGRAY.deriveColor(0.0, 1.2, 1.0, 0.6)
}
override val rootNode = BorderPane()
override val selectionLayer = XYChartSelectionLayer.build(this, -10.0)
override val dragHandlers = XYChartDragHandlers(this)
override val scrollHandlers = XYChartScrollHandlers(this)
private val visibleRangeRect = object : Rectangle() {
private val projectChangeListener = object : ViewGroupContext.ProjectChangeListener(this@XYChartFullRangeWidget) {
override fun newProjectCb(newProject: TraceProject<*, *>?) {
isVisible = (newProject != null)
}
}
init {
stroke = VISIBLE_RANGE_STROKE_COLOR
strokeWidth = VISIBLE_RANGE_STROKE_WIDTH
strokeLineCap = StrokeLineCap.ROUND
fill = VISIBLE_RANGE_FILL_COLOR
arcHeight = VISIBLE_RANGE_ARC
arcWidth = VISIBLE_RANGE_ARC
y = 0.0
heightProperty().bind(Bindings.subtract(chart.heightProperty(), VISIBLE_RANGE_STROKE_WIDTH))
val initialProject = viewContext.registerProjectChangeListener(projectChangeListener)
isVisible = (initialProject != null)
}
@Suppress("ProtectedInFinal", "Unused")
protected fun finalize() {
viewContext.deregisterProjectChangeListener(projectChangeListener)
}
}
init {
/* Hide the axes in the full range chart */
with(xAxis) {
isTickLabelsVisible = false
opacity = 0.0
}
with(yAxis) {
isTickLabelsVisible = false
opacity = 0.0
}
with(chart) {
// setTitle(getName())
padding = Insets(-10.0, -10.0, -10.0, -10.0)
// setStyle("-fx-padding: 1px;")
minHeight = CHART_HEIGHT
prefHeight = CHART_HEIGHT
maxHeight = CHART_HEIGHT
}
rootNode.center = StackPane(chart,
Pane(visibleRangeRect).apply { isMouseTransparent = true },
selectionLayer)
rootNode.widthProperty().addListener { _, _, _ ->
drawSelection(viewContext.selectionTimeRange)
seekVisibleRange(viewContext.visibleTimeRange)
timelineWidgetUpdateTask.run()
}
}
override fun dispose() {
}
override fun getWidgetTimeRange() = viewContext.getCurrentProjectFullRange()
override fun mapXPositionToTimestamp(x: Double): Long {
val project = viewContext.traceProject ?: return 0L
val viewWidth = chartPlotArea.width
if (viewWidth < 1.0) return project.startTime
val posRatio = x / viewWidth
val ts = (project.startTime + posRatio * project.fullRange.duration).toLong()
/* Clamp the result to the trace project's range. */
return ts.coerceIn(project.fullRange.startTime, project.fullRange.endTime)
}
// ------------------------------------------------------------------------
// TimelineWidget
// ------------------------------------------------------------------------
override val name = control.renderProvider.providerName
override val timelineWidgetUpdateTask: TimelineWidget.TimelineWidgetUpdateTask = RedrawTask()
/** Not applicable to this widget */
override val splitPane = null
/* Not applicable to this widget */
override val timeBasedScrollPane = null
// TODO Bind the selection rectangles with the other timeline ones?
override val selectionRectangle = null
override val ongoingSelectionRectangle = null
// ------------------------------------------------------------------------
// XYChartView
// ------------------------------------------------------------------------
override fun clear() {
/* Nothing to do, the redraw task will remove all series if the trace is null. */
}
override fun seekVisibleRange(newVisibleRange: TimeRange) {
/* Needs + 10 to be properly aligned, not sure why... */
val xStart = xAxis.getDisplayPosition(newVisibleRange.startTime) + 10.0
val xEnd = xAxis.getDisplayPosition(newVisibleRange.endTime) + 10.0
if (xStart == Double.NaN || xEnd == Double.NaN) return
with(visibleRangeRect) {
x = xStart
width = xEnd - xStart
}
}
private inner class RedrawTask : TimelineWidget.TimelineWidgetUpdateTask {
private var lastTraceProject: TraceProject<*, *>? = null
override fun run() {
/* Skip redraws if we are in a project-switching operation. */
if (viewContext.listenerFreeze) return
var newTraceProject = viewContext.traceProject
if (newTraceProject == lastTraceProject) return
if (newTraceProject == null) {
/* Replace the list of series with an empty list */
Platform.runLater { chart.data = FXCollections.observableArrayList() }
} else {
val painted = repaintChart(newTraceProject)
if (!painted) {
newTraceProject = null
}
}
lastTraceProject = newTraceProject
}
/**
* Repaint the whole chart. Should only be necessary if the active trace
* changes.
*
* @return If we have produced a "real" render or not. If not, it might be
* because the trace is still being initialized, so we should not
* consider it painted.
*/
private fun repaintChart(traceProject: TraceProject<*, *>): Boolean {
val traceFullRange = TimeRange.of(traceProject.startTime, traceProject.endTime)
val renders = control.renderProvider.generateSeriesRenders(traceFullRange, NB_DATA_POINTS, null)
if (renders.isEmpty()) return false
val outSeries = mutableListOf<XYChart.Series<Number, Number>>()
for (render: XYChartRender in renders) {
val outPoints = mutableListOf<XYChart.Data<Number, Number>>()
// Width of a single bar in nanoseconds
val step = (render.data[1].x - render.data[0].x)
/*
* A data point indicates the count difference between the data
* points's timestamp and the next data point's timestamp.
*
* Hack: simulate a bar chart with an area chart here.
*/
for (renderDp: XYChartRender.DataPoint in render.data) {
outPoints.add(XYChart.Data(renderDp.x, 0.0))
outPoints.add(XYChart.Data(renderDp.x, renderDp.y))
outPoints.add(XYChart.Data(renderDp.x + step, renderDp.y))
outPoints.add(XYChart.Data(renderDp.x + step, 0.0))
}
outSeries.add(XYChart.Series(render.series.name, FXCollections.observableList(outPoints)))
}
/* Determine start and end times of the display range. */
val start = renders.map { it.range.startTime }.min()!!
val end = renders.map { it.range.endTime }.max()!!
val range = TimeRange.of(start, end)
xAxis.setTickStep(renders.first().resolutionX)
Platform.runLater {
chart.data = FXCollections.observableArrayList()
outSeries.forEach { chart.data.add(it) }
chart.createSymbols = false
with(chart.xAxis as TimeAxis) {
tickUnit = range.duration.toDouble()
lowerBound = range.startTime.toDouble()
upperBound = range.endTime.toDouble()
}
}
/*
* On project-switching, the whole project time range should be the new visible range.
*
* Unfortunately, we cannot use the normal facilities here to redraw the visible range
* rectangle because the data has not yet been rendered, so the axis does not yet
* have its real width
*
* Instead use this ugly but working hack to artificially draw a rectangle that covers
* the whole widget.
*/
Platform.runLater {
visibleRangeRect.apply {
isVisible = true
x = 10.0
width = chart.width - 10.0
}
}
return true
}
}
}
| epl-1.0 | ab2fcdaa7b761e09e3aa6dac187e7fb0 | 37.397163 | 128 | 0.615349 | 4.846911 | false | false | false | false |
robinverduijn/gradle | buildSrc/subprojects/binary-compatibility/src/main/kotlin/org/gradle/binarycompatibility/BinaryCompatibilityRepository.kt | 1 | 3842 | /*
* Copyright 2019 the original author or 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.gradle.binarycompatibility
import japicmp.model.JApiClass
import japicmp.model.JApiCompatibility
import japicmp.model.JApiMethod
import javassist.bytecode.SourceFileAttribute
import org.gradle.binarycompatibility.sources.ApiSourceFile
import org.gradle.binarycompatibility.sources.JavaSourceQueries
import org.gradle.binarycompatibility.sources.KotlinSourceQueries
import org.gradle.binarycompatibility.sources.SourcesRepository
import com.google.common.annotations.VisibleForTesting
import java.io.File
/**
* Repository of sources for binary compatibility checks.
*
* `WARN` Holds resources open for performance, must be closed after use.
*/
class BinaryCompatibilityRepository internal constructor(
private
val sources: SourcesRepository
) : AutoCloseable {
companion object {
@JvmStatic
fun openRepositoryFor(sourceRoots: List<File>, compilationClasspath: List<File>) =
BinaryCompatibilityRepository(SourcesRepository(sourceRoots, compilationClasspath))
}
@VisibleForTesting
fun emptyCaches() =
sources.close()
override fun close() =
emptyCaches()
fun isOverride(method: JApiMethod): Boolean =
apiSourceFileFor(method).let { apiSourceFile ->
when (apiSourceFile) {
is ApiSourceFile.Java -> sources.executeQuery(apiSourceFile, JavaSourceQueries.isOverrideMethod(method))
is ApiSourceFile.Kotlin -> sources.executeQuery(apiSourceFile, KotlinSourceQueries.isOverrideMethod(method))
}
}
fun isSince(version: String, member: JApiCompatibility): Boolean =
apiSourceFileFor(member).let { apiSourceFile ->
when (apiSourceFile) {
is ApiSourceFile.Java -> sources.executeQuery(apiSourceFile, JavaSourceQueries.isSince(version, member))
is ApiSourceFile.Kotlin -> sources.executeQuery(apiSourceFile, KotlinSourceQueries.isSince(version, member))
}
}
private
fun apiSourceFileFor(member: JApiCompatibility): ApiSourceFile =
member.jApiClass.let { declaringClass ->
sources.sourceFileAndSourceRootFor(declaringClass.sourceFilePath).let { (sourceFile, sourceRoot) ->
if (declaringClass.isKotlin) ApiSourceFile.Kotlin(sourceFile, sourceRoot)
else ApiSourceFile.Java(sourceFile, sourceRoot)
}
}
private
val JApiClass.sourceFilePath: String
get() = if (isKotlin) kotlinSourceFilePath else javaSourceFilePath
private
val JApiClass.javaSourceFilePath: String
get() = fullyQualifiedName
.replace(".", "/")
.replace(innerClassesPartRegex, "") + ".java"
private
val innerClassesPartRegex =
"\\$.*".toRegex()
private
val JApiClass.kotlinSourceFilePath: String
get() = "$packagePath/$bytecodeSourceFilename"
private
val JApiClass.bytecodeSourceFilename: String
get() = newClass.orNull()?.classFile?.getAttribute("SourceFile")?.let { it as? SourceFileAttribute }?.fileName
?: throw java.lang.IllegalStateException("Bytecode for $fullyQualifiedName is missing the 'SourceFile' attribute")
}
| apache-2.0 | 8502b8aab02dd260dac37d25f45a59c1 | 34.574074 | 126 | 0.713691 | 4.790524 | false | false | false | false |
chenxyu/android-banner | bannerlibrary/src/main/java/com/chenxyu/bannerlibrary/indicator/DrawableIndicator.kt | 1 | 7658 | package com.chenxyu.bannerlibrary.indicator
import android.graphics.drawable.StateListDrawable
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.chenxyu.bannerlibrary.BannerView2
import com.chenxyu.bannerlibrary.R
import com.chenxyu.bannerlibrary.extend.az
import com.chenxyu.bannerlibrary.extend.dpToPx
import com.chenxyu.bannerlibrary.extend.getDrawable2
/**
* @Author: ChenXingYu
* @CreateDate: 2020/8/19 15:49
* @Description: Drawable指示器(支持XML设置)
* @Version: 1.0
* @param overlap 指示器是否重叠在Banner上
* @param normalDrawable 默认Indicator
* @param selectedDrawable 选中Indicator
* @param margin 指示器外边距,间隔(DP)
* @param gravity 指示器的位置
*/
class DrawableIndicator(overlap: Boolean? = true,
@DrawableRes normalDrawable: Int? = R.drawable.indicator_gray,
@DrawableRes selectedDrawable: Int? = R.drawable.indicator_white,
margin: Int? = 4,
gravity: Int? = Gravity.CENTER
) : Indicator() {
/**
* 指示器集
*/
private var mIndicators: MutableList<View> = mutableListOf()
/**
* 指示器外边距,间隔(DP)
*/
var indicatorMargin: Int = 4
/**
* 指示器宽(DP)
*/
var indicatorWidth: Int = 7
/**
* 指示器高(DP)
*/
var indicatorHeight: Int = 7
/**
* 选中时指示器宽(DP)
*/
var indicatorSelectedW: Int = 7
/**
* 选中时指示器高(DP)
*/
var indicatorSelectedH: Int = 7
/**
* 默认Indicator Drawable
*/
@DrawableRes
var indicatorNormalDrawable: Int = R.drawable.indicator_gray
/**
* 选中Indicator Drawable
*/
@DrawableRes
var indicatorSelectedDrawable: Int = R.drawable.indicator_white
/**
* 默认指示器LayoutParams
*/
lateinit var normalParams: LinearLayout.LayoutParams
/**
* 选中的指示器LayoutParams
*/
lateinit var selectedParams: LinearLayout.LayoutParams
init {
overlap?.let { this.overlap = it }
normalDrawable?.let { indicatorNormalDrawable = it }
selectedDrawable?.let { indicatorSelectedDrawable = it }
margin?.let { indicatorMargin = it }
gravity?.let { indicatorGravity = it }
}
override fun registerOnPageChangeCallback(viewPager2: ViewPager2?) {
if (mVp2PageChangeCallback == null) {
mVp2PageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
toggleIndicator(null, viewPager2)
}
}
viewPager2?.registerOnPageChangeCallback(mVp2PageChangeCallback!!)
}
}
override fun addOnScrollListener(recyclerView: RecyclerView?) {
if (mRvScrollListener == null) {
mRvScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
when (newState) {
// 闲置
RecyclerView.SCROLL_STATE_IDLE -> {
toggleIndicator(recyclerView, null)
}
// 拖拽中
RecyclerView.SCROLL_STATE_DRAGGING -> {
}
// 惯性滑动中
RecyclerView.SCROLL_STATE_SETTLING -> {
toggleIndicator(recyclerView, null)
}
}
}
}
recyclerView?.addOnScrollListener(mRvScrollListener!!)
}
}
override fun initIndicator(container: LinearLayout, count: Int, orientation: Int) {
mIndicators.clear()
normalParams = LinearLayout.LayoutParams(
indicatorWidth.dpToPx(container.context),
indicatorHeight.dpToPx(container.context))
selectedParams = LinearLayout.LayoutParams(
indicatorSelectedW.dpToPx(container.context),
indicatorSelectedH.dpToPx(container.context))
if (orientation == RecyclerView.HORIZONTAL) {
normalParams.setMargins(indicatorMargin.dpToPx(container.context), 0,
indicatorMargin.dpToPx(container.context), 0)
selectedParams.setMargins(indicatorMargin.dpToPx(container.context), 0,
indicatorMargin.dpToPx(container.context), 0)
} else {
normalParams.setMargins(0, indicatorMargin.dpToPx(container.context),
0, indicatorMargin.dpToPx(container.context))
selectedParams.setMargins(0, indicatorMargin.dpToPx(container.context),
0, indicatorMargin.dpToPx(container.context))
}
repeat(count) {
val indicators = View(container.context)
val drawable = StateListDrawable()
drawable.addState(IntArray(0).plus(android.R.attr.state_selected),
container.context.getDrawable2(indicatorSelectedDrawable))
drawable.addState(IntArray(0), container.context.getDrawable2(indicatorNormalDrawable))
indicators.background = drawable
indicators.isSelected = false
indicators.layoutParams = normalParams
container.addView(indicators)
mIndicators.add(indicators)
}
mIndicators[0].isSelected = true
mIndicators[0].layoutParams = selectedParams
}
/**
* 切换指示器位置
*/
private fun toggleIndicator(recyclerView: RecyclerView?, viewPager2: ViewPager2?) {
val currentPosition = viewPager2?.currentItem ?: recyclerView?.getChildAt(0)
?.layoutParams?.az<RecyclerView.LayoutParams>()?.viewAdapterPosition
val itemCount = viewPager2?.adapter?.itemCount
?: recyclerView?.adapter?.az<BannerView2.Adapter<*, *>>()?.itemCount ?: return
for (indicator in mIndicators) {
indicator.isSelected = false
indicator.layoutParams = normalParams
}
if (isLoop) {
when (currentPosition) {
0 -> {
mIndicators[mIndicators.size - 1].isSelected = true
mIndicators[mIndicators.size - 1].layoutParams = selectedParams
return
}
itemCount.minus(1) -> {
mIndicators[0].isSelected = true
mIndicators[0].layoutParams = selectedParams
return
}
itemCount.minus(2) -> {
mIndicators[mIndicators.size - 1].isSelected = true
mIndicators[mIndicators.size - 1].layoutParams = selectedParams
return
}
}
for (i in mIndicators.indices) {
if (currentPosition == i) {
mIndicators[i - 1].isSelected = true
mIndicators[i - 1].layoutParams = selectedParams
return
}
}
} else {
currentPosition?.let {
mIndicators[it].isSelected = true
mIndicators[it].layoutParams = selectedParams
}
}
}
} | mit | 0d384ff7a93f775927407120fae783be | 34.706731 | 99 | 0.581874 | 4.970549 | false | false | false | false |
square/leakcanary | leakcanary-android-core/src/main/java/leakcanary/internal/friendly/Friendly.kt | 2 | 615 | @file:Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER", "NOTHING_TO_INLINE")
@file:JvmName("leakcanary-android-core_Friendly")
package leakcanary.internal.friendly
internal inline val mainHandler
get() = leakcanary.internal.mainHandler
internal inline fun checkMainThread() = leakcanary.internal.checkMainThread()
internal inline fun checkNotMainThread() = leakcanary.internal.checkNotMainThread()
internal inline fun <reified T : Any> noOpDelegate(): T = leakcanary.internal.noOpDelegate()
internal inline fun measureDurationMillis(block: () -> Unit) =
leakcanary.internal.measureDurationMillis(block)
| apache-2.0 | 28deda37d7b8094c6f2eb8c406ecc65f | 37.4375 | 92 | 0.798374 | 4.456522 | false | false | false | false |
CarrotCodes/Warren | src/main/kotlin/chat/willow/warren/registration/RFC1459RegistrationExtension.kt | 1 | 1014 | package chat.willow.warren.registration
import chat.willow.kale.irc.message.rfc1459.NickMessage
import chat.willow.kale.irc.message.rfc1459.PassMessage
import chat.willow.kale.irc.message.rfc1459.UserMessage
import chat.willow.warren.IMessageSink
class RFC1459RegistrationExtension(private val sink: IMessageSink, private val nickname: String, private val username: String, private val password: String? = null, private val registrationManager: IRegistrationManager): IRegistrationExtension {
override fun startRegistration() {
if (password != null) {
sink.write(PassMessage.Command(password = password))
}
sink.write(NickMessage.Command(nickname = nickname))
sink.write(UserMessage.Command(username = username, mode = "8", realname = username))
}
override fun onRegistrationSucceeded() {
registrationManager.onExtensionSuccess(this)
}
override fun onRegistrationFailed() {
registrationManager.onExtensionFailure(this)
}
}
| isc | 6de5f29d48e22e89f830dcc0a1297710 | 36.555556 | 245 | 0.747535 | 4.38961 | false | false | false | false |
jdinkla/groovy-java-ray-tracer | src/main/kotlin/net/dinkla/raytracer/objects/GeometricObject.kt | 1 | 614 | package net.dinkla.raytracer.objects
import net.dinkla.raytracer.hits.Hit
import net.dinkla.raytracer.hits.ShadowHit
import net.dinkla.raytracer.materials.IMaterial
import net.dinkla.raytracer.math.BBox
import net.dinkla.raytracer.math.Ray
open abstract class GeometricObject {
open var isShadows = true
open var material: IMaterial? = null
var isInitialized: Boolean = false
open var boundingBox: BBox = BBox()
abstract fun hit(ray: Ray, sr: Hit): Boolean
abstract fun shadowHit(ray: Ray, tmin: ShadowHit): Boolean
open fun initialize() {
isInitialized = true
}
}
| apache-2.0 | 444d065db651b014a06a0c3cbdd14958 | 22.615385 | 62 | 0.734528 | 4.066225 | false | false | false | false |
google/ksp | compiler-plugin/src/main/kotlin/com/google/devtools/ksp/DualLookupTracker.kt | 1 | 2006 | /*
* Copyright 2021 Google LLC
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp
import org.jetbrains.kotlin.incremental.LookupTrackerImpl
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.incremental.components.Position
import org.jetbrains.kotlin.incremental.components.ScopeKind
class DualLookupTracker : LookupTracker {
val symbolTracker = LookupTrackerImpl(LookupTracker.DO_NOTHING)
val classTracker = LookupTrackerImpl(LookupTracker.DO_NOTHING)
override val requiresPosition: Boolean
get() = symbolTracker.requiresPosition || classTracker.requiresPosition
override fun record(filePath: String, position: Position, scopeFqName: String, scopeKind: ScopeKind, name: String) {
symbolTracker.record(filePath, position, scopeFqName, scopeKind, name)
if (scopeKind == ScopeKind.CLASSIFIER) {
val className = scopeFqName.substringAfterLast('.')
val outerScope = scopeFqName.substringBeforeLast('.', "<anonymous>")
// DO NOT USE: ScopeKind is meaningless
classTracker.record(filePath, position, outerScope, scopeKind, className)
}
}
override fun clear() {
// Do not clear symbolTracker and classTracker.
// LookupTracker.clear() is called in repeatAnalysisIfNeeded, but we need records across all rounds.
}
}
| apache-2.0 | d31534202961b7b4590059b135c059a8 | 42.608696 | 120 | 0.742772 | 4.600917 | false | false | false | false |
talhacohen/android | app/src/main/java/com/etesync/syncadapter/ui/setup/LoginCredentials.kt | 1 | 1768 | /*
* Copyright © 2013 – 2016 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.ui.setup
import android.os.Parcel
import android.os.Parcelable
import com.etesync.syncadapter.App
import com.etesync.syncadapter.Constants
import java.net.URI
import java.net.URISyntaxException
class LoginCredentials(_uri: URI?, val userName: String, val password: String) : Parcelable {
val uri: URI?
init {
var uri = _uri
if (uri == null) {
try {
uri = URI(Constants.serviceUrl.toString())
} catch (e: URISyntaxException) {
App.log.severe("Should never happen, it's a constant")
}
}
this.uri = uri
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeSerializable(uri)
dest.writeString(userName)
dest.writeString(password)
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<*> = object : Parcelable.Creator<LoginCredentials> {
override fun createFromParcel(source: Parcel): LoginCredentials {
return LoginCredentials(
source.readSerializable() as URI,
source.readString()!!, source.readString()!!
)
}
override fun newArray(size: Int): Array<LoginCredentials?> {
return arrayOfNulls(size)
}
}
}
}
| gpl-3.0 | b96de4a08effd754228b9050b0c40726 | 27.467742 | 93 | 0.613598 | 4.757412 | false | false | false | false |
y2k/ProjectCaerus | app/src/test/kotlin/com/projectcaerus/samples/SampleTest.kt | 1 | 1480 | package com.projectcaerus.samples
import android.app.Activity
import android.content.res.ContextFactory
import android.graphics.Canvas
import com.android.internal.policy.impl.PhoneLayoutInflater
import com.projectcaerus.Size
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.mockito.Mockito
import org.mockito.stubbing.Answer
import java.io.File
import java.net.URLClassLoader
/**
* Created by y2k on 13/06/16.
*/
class SampleTest {
@Test
fun test() {
val appPath = File("../samples/hello-world/app")
val resPath = File(appPath, "src/main/res")
val classPath = File(appPath, "build/intermediates/classes/debug")
assertTrue(classPath.exists())
val loader = URLClassLoader(arrayOf(classPath.toURI().toURL()))
val context = ContextFactory().makeNoPowerMock(loader, resPath)
val mainClass = loader.loadClass("com.example.helloworld.MainActivity")
assertNotNull(mainClass)
val mainActivity = mainClass.newInstance() as Activity
mainActivity.inflater = PhoneLayoutInflater(context)
mainActivity.onCreate(null)
mainActivity.dump(Size(320, 480))
// mainActivity.dumpTo(Size(320, 480), mockCanvas())
}
private fun mockCanvas(): Canvas {
return Mockito.mock(Canvas::class.java, Answer {
println("called = " + it)
if (it.method.name == "save") 1 else null
})
}
} | gpl-3.0 | b28ea45a869b1a6c4f3128b0ef4f00fc | 29.854167 | 79 | 0.695946 | 4.099723 | false | true | false | false |
google/chromeosnavigationdemo | app/src/main/java/com/emilieroberts/chromeosnavigationdemo/MainActivity.kt | 1 | 5545 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.emilieroberts.chromeosnavigationdemo
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.google.android.material.navigation.NavigationView
class MainActivity : AppCompatActivity(),
FragmentManager.OnBackStackChangedListener,
FileBrowserFragment.FileActionsListener {
private lateinit var fileBehaviorViewModel: AdaptableDemoViewModel
private val onNavigationItemSelection: (MenuItem) -> Boolean = { item ->
//If we're in the image viewer, pop back out to the file browser
supportFragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
fileBehaviorViewModel.inPhotoViewer = false
changeFileBrowserSource(item.itemId)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fileBehaviorViewModel = ViewModelProviders.of(this).get(AdaptableDemoViewModel::class.java)
val bottomNavigationView: BottomNavigationView? = findViewById(R.id.bottomnav_main)
bottomNavigationView?.setOnNavigationItemSelectedListener(onNavigationItemSelection)
val navigationView: NavigationView? = findViewById(R.id.nav_view)
navigationView?.setNavigationItemSelectedListener(onNavigationItemSelection)
fileBehaviorViewModel.getFileSource().observe(this, Observer { updateTitle(it) })
supportFragmentManager.addOnBackStackChangedListener(this)
val fileBrowserFragment = FileBrowserFragment()
fileBrowserFragment.fileActionsListener = this
supportFragmentManager.beginTransaction().apply {
replace(R.id.file_listing_fragment, fileBrowserFragment)
commit()
}
shouldDisplayHomeUp()
}
override fun onResume() {
restoreState()
super.onResume()
}
private fun restoreState() {
if (fileBehaviorViewModel.inPhotoViewer) {
displayImage()
}
}
private fun changeFileBrowserSource(itemId: Int): Boolean {
return when (itemId) {
R.id.navigation_local -> {
fileBehaviorViewModel.setFileSource(FileStore.intToPhotoSource(R.id.navigation_local))
true
}
R.id.navigation_cloud -> {
title = getString(R.string.label_cloud)
fileBehaviorViewModel.setFileSource(FileStore.intToPhotoSource(R.id.navigation_cloud))
true
}
R.id.navigation_shared -> {
title = getString(R.string.label_shared)
fileBehaviorViewModel.setFileSource(FileStore.intToPhotoSource(R.id.navigation_shared))
true
}
else -> false
}
}
override fun onFileClick(filePosition: Int, fileId: Int) {
fileBehaviorViewModel.setCurrentPhotoId(fileId)
fileBehaviorViewModel.inPhotoViewer = true
displayImage()
}
private fun displayImage() {
supportFragmentManager.beginTransaction().apply {
replace(R.id.file_listing_fragment, ImageViewerFragment())
addToBackStack(null)
commit()
}
}
private fun updateTitle(fileSource: FileSource) {
title = when (fileSource) {
FileSource.LOCAL -> getString(R.string.label_local)
FileSource.CLOUD -> getString(R.string.label_cloud)
FileSource.SHARED -> getString(R.string.label_shared)
}
}
override fun onBackPressed() {
//If we press back, we will never be in the photo viewer
fileBehaviorViewModel.inPhotoViewer = false
super.onBackPressed()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.options_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_item_about -> {
showAboutDialog(this)
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onBackStackChanged() {
shouldDisplayHomeUp()
}
private fun shouldDisplayHomeUp() {
//Enable Up if there are entries in the back stack
supportActionBar?.setDisplayHomeAsUpEnabled(supportFragmentManager.backStackEntryCount > 0)
}
override fun onSupportNavigateUp(): Boolean {
supportFragmentManager.popBackStack()
fileBehaviorViewModel.inPhotoViewer = false
return true
}
}
| apache-2.0 | c6b08491b4874b6d32604f865b4f5ef2 | 33.440994 | 103 | 0.683499 | 5.096507 | false | false | false | false |
devmil/muzei-bingimageoftheday | app/src/main/java/de/devmil/muzei/bingimageoftheday/worker/BingImageOfTheDayWorker.kt | 1 | 8060 | package de.devmil.muzei.bingimageoftheday.worker
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.util.Log
import androidx.work.*
import com.google.android.apps.muzei.api.provider.Artwork
import com.google.android.apps.muzei.api.provider.ProviderContract
import de.devmil.common.utils.LogUtil
import de.devmil.muzei.bingimageoftheday.*
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
class BingImageOfTheDayWorker(
val context: Context,
workerParams: WorkerParameters
) : Worker(context, workerParams) {
companion object {
private const val TAG = "BingImageIfTheDayWorker"
private const val SETTINGS_NAME = "BingImageOfTheDayArtSource"
internal fun enqueueLoad() {
Log.d(TAG, "Loading enqued")
val workManager = WorkManager.getInstance()
workManager.enqueue(OneTimeWorkRequestBuilder<BingImageOfTheDayWorker>()
.setConstraints(Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build())
.build())
}
private val lockObject = Object()
private var lastArtworkUpdate: Calendar? = null
}
private fun getSharedPreferences() : SharedPreferences {
return applicationContext.getSharedPreferences("muzeiartsource_$SETTINGS_NAME", 0)
}
private fun getImageTitle(imageDate: Date): String {
val df = SimpleDateFormat("MM/dd/yyyy", Locale.US)
return "Bing: " + df.format(imageDate.time)
}
override fun doWork(): Result {
LogUtil.LOGD(TAG, "Request: Loading new Bing images")
synchronized(lockObject) {
val now = Calendar.getInstance()
val settings = Settings(applicationContext, getSharedPreferences())
val isPortrait = settings.isOrientationPortrait
val isCurrentArtworkPortrait = settings.isCurrentOrientationPortrait
val market = settings.bingMarket
val currentArtworkMarket = settings.currentBingMarket
//when there are settings changes then the request for new images
//gets overwritten
val requestOverride = market != currentArtworkMarket
|| isPortrait != isCurrentArtworkPortrait
//Check if the last update is more than 2 minutes away.
//If not then return early (exception: when settings changed that lead to an update)
lastArtworkUpdate?.let {
val millisDiff = now.timeInMillis - it.timeInMillis
val minDiff = 1000 /* seconds */ * 60 /* minutes */ * 2
if(!requestOverride && millisDiff < minDiff) {
LogUtil.LOGD(TAG, "Last update was less than 2 minutes ago => ignoring")
return Result.success()
}
}
lastArtworkUpdate = now
//Default = request the image list from Bing
var requestNewImages = true
val lastArtwork = ProviderContract.getProviderClient<BingImageOfTheDayArtProvider>(applicationContext)
.lastAddedArtwork
if (lastArtwork != null) {
LogUtil.LOGD(TAG, "Found last artwork")
val timeInMillis = lastArtwork.metadata?.toLongOrNull()
if (timeInMillis != null) {
val token = getToken(Date(timeInMillis), market, isPortrait)
LogUtil.LOGD(TAG, "Metadata is correct")
if (token == lastArtwork.token && isNewestBingImage(Date(timeInMillis))) {
//when the current artwork matches the settings and is the newest, then don't load that Bing list
LogUtil.LOGD(TAG, "We have the latest image => do nothing")
requestNewImages = false
requestNextImageUpdate(Date(timeInMillis))
}
}
}
if (requestOverride) {
LogUtil.LOGD(TAG, "Settings changed! reloading anyways!")
requestNewImages = true
}
if (!requestNewImages) {
return Result.success()
}
LogUtil.LOGD(TAG, "Reloading Bing images")
val retriever = BingImageOfTheDayMetadataRetriever(
market,
BingImageDimension.UHD,
isPortrait
)
val photosMetadata = try {
retriever.bingImageOfTheDayMetadata ?: listOf()
} catch (e: IOException) {
Log.w(TAG, "Error reading Bing response", e)
return Result.retry()
}
if (photosMetadata.isEmpty()) {
Log.w(TAG, "No photos returned from Bing API.")
return Result.failure()
}
photosMetadata.asSequence().map { metadata ->
Artwork(
token = getToken(metadata.startDate, market, isPortrait),
title = metadata.startDate?.let { getImageTitle(it) } ?: "",
byline = metadata.copyright ?: "",
persistentUri = metadata.uri,
webUri = metadata.uri,
metadata = metadata.startDate?.time.toString()
)
}.sortedByDescending { aw ->
aw.metadata?.toLongOrNull() ?: 0
}.firstOrNull()
?.let { artwork ->
Log.d(TAG, "Got artworks. Selected this one: ${artwork.title} valid on: ${Date(artwork.metadata!!.toLong())}")
requestNextImageUpdate(Date(artwork.metadata!!.toLong()))
setArtwork(artwork)
settings.isCurrentOrientationPortrait = isPortrait
settings.currentBingMarket = market
}
return Result.success()
}
}
private fun getToken(startDate: Date?, market: BingMarket, isPortrait: Boolean): String {
val result = "$startDate-$market-${if(isPortrait) "portrait" else "landscape"}"
LogUtil.LOGD(TAG, "Token: $result")
return result
}
private fun isNewestBingImage(newestBingImageDate: Date) : Boolean {
val now = Calendar.getInstance().time
val nextBingImageDate = getNextBingImageDate(newestBingImageDate)
return now < nextBingImageDate
}
private fun getNextBingImageDate(newestBingImageDate: Date): Date {
val nextBingImageDate = Calendar.getInstance()
nextBingImageDate.timeInMillis = newestBingImageDate.time
nextBingImageDate.add(Calendar.DAY_OF_YEAR, 1)
return nextBingImageDate.time
}
private fun setArtwork(artwork: Artwork) {
LogUtil.LOGD(TAG, "Setting artwork: ${artwork.metadata?.toLongOrNull()?.let { Date(it) }}, ${artwork.title}")
ProviderContract.getProviderClient<BingImageOfTheDayArtProvider>(applicationContext)
.setArtwork(artwork)
}
private fun requestNextImageUpdate(currentImageDate: Date): Calendar {
val nextBingImageDate = getNextBingImageDate(currentImageDate)
val nextUpdate = Calendar.getInstance()
nextUpdate.time = nextBingImageDate
nextUpdate.add(Calendar.MINUTE, 1)
val sdf = SimpleDateFormat("dd.MM.yyyy HH:mm:ss", Locale.US)
LogUtil.LOGD(TAG, String.format("next update: %s", sdf.format(nextUpdate.time)))
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as? AlarmManager
val updateIntent = Intent(context, UpdateReceiver::class.java)
val pendingUpdateIntent = PendingIntent.getBroadcast(context, 1, updateIntent, PendingIntent.FLAG_UPDATE_CURRENT)
alarmManager?.set(AlarmManager.RTC_WAKEUP, nextUpdate.timeInMillis, pendingUpdateIntent)
return nextUpdate
}
} | apache-2.0 | a7c1e6449bab13ee2a45af78b270f451 | 39.918782 | 126 | 0.614764 | 5.133758 | false | false | false | false |
camdenorrb/KPortals | src/main/kotlin/me/camdenorrb/kportals/portal/Portal.kt | 1 | 1444 | package me.camdenorrb.kportals.portal
import org.bukkit.util.Vector
import java.util.*
import kotlin.math.absoluteValue
import kotlin.math.max
/**
* Created by camdenorrb on 3/20/17.
*/
// TODO: Embed selection as a parameter so you don't need to calculate min/max ever again
data class Portal(
val name: String,
var toArgs: String,
val worldUUID: UUID,
var type: Type = Type.Unknown,
val selection: Selection,
val positions: Set<Vector>
) {
@delegate:Transient
val maxRadius by lazy {
val sel1 = selection.sel1 ?: return@lazy 0.0
val sel2 = selection.sel2 ?: return@lazy 0.0
val dist = sel1.clone().subtract(sel2)
max(max(dist.x.absoluteValue, dist.y.absoluteValue), dist.z.absoluteValue)
}
enum class Type {
ConsoleCommand, PlayerCommand, Unknown, Random, Bungee, World;
companion object {
fun byName(name: String, ignoreCase: Boolean = true): Type? {
return values().find { name.equals(it.name, ignoreCase) }
}
}
}
data class Selection(var sel1: Vector? = null, var sel2: Vector? = null) {
fun isSelected(): Boolean {
return sel1 != null && sel2 != null
}
fun center(): Vector? {
val sel1 = sel1 ?: return null
val sel2 = sel2 ?: return null
return sel1.clone().add(sel2).multiply(0.5)
}
}
} | mit | cddc46aa39b5efcf97f5ecfc7cdcc53a | 21.936508 | 89 | 0.604571 | 3.892183 | false | false | false | false |
gantsign/restrulz-jvm | com.gantsign.restrulz.spring.mvc/src/main/kotlin/com/gantsign/restrulz/spring/mvc/SingleReturnValueHandler.kt | 1 | 5085 | /*-
* #%L
* Restrulz
* %%
* Copyright (C) 2017 GantSign Ltd.
* %%
* 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.
* #L%
*/
package com.gantsign.restrulz.spring.mvc
import io.reactivex.Single
import org.springframework.core.MethodParameter
import org.springframework.core.ResolvableType
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.context.request.NativeWebRequest
import org.springframework.web.context.request.async.DeferredResult
import org.springframework.web.context.request.async.WebAsyncUtils
import org.springframework.web.method.support.AsyncHandlerMethodReturnValueHandler
import org.springframework.web.method.support.ModelAndViewContainer
/**
* A [AsyncHandlerMethodReturnValueHandler] implementation for [Single].
*/
class SingleReturnValueHandler : AsyncHandlerMethodReturnValueHandler {
private fun isSingle(returnType: MethodParameter): Boolean {
return Single::class.java.isAssignableFrom(returnType.parameterType)
}
private fun isSingleInResponseEntity(returnType: MethodParameter): Boolean {
if (ResponseEntity::class.java.isAssignableFrom(returnType.parameterType)) {
val resolvableType = ResolvableType.forMethodParameter(returnType)
val bodyType = resolvableType.getGeneric(0).resolve()
return bodyType != null && Single::class.java.isAssignableFrom(bodyType)
}
return false
}
override fun supportsReturnType(returnType: MethodParameter): Boolean {
return isSingle(returnType) || isSingleInResponseEntity(returnType)
}
override fun isAsyncReturnValue(returnValue: Any?, returnType: MethodParameter): Boolean {
return returnValue != null && supportsReturnType(returnType)
}
@Throws(Exception::class)
override fun handleReturnValue(returnValue: Any?,
returnType: MethodParameter,
mavContainer: ModelAndViewContainer,
webRequest: NativeWebRequest) {
// returnValue is either Single<ResponseEntity, Single<ResponseEntityConvertible>,
// Single<*>, ResponseEntity<Single<*>> or null
if (returnValue === null) {
mavContainer.isRequestHandled = true
return
}
val single: Single<*>
val responseEntity: ResponseEntity<Single<*>>?
if (returnValue is Single<*>) {
single = returnValue
responseEntity = null
} else {
if (returnValue !is ResponseEntity<*>) {
throw AssertionError("Expected ${Single::class.java.name} or ${ResponseEntity::class.java.name} but was ${returnValue::class.java.name}")
}
val body = returnValue.body
if (body === null) {
mavContainer.isRequestHandled = true
return
}
if (body !is Single<*>) {
throw AssertionError("Expected ${Single::class.java.name} but was ${body::class.java.name}")
}
single = body
@Suppress("UNCHECKED_CAST")
responseEntity = returnValue as ResponseEntity<Single<*>>?
}
val asyncManager = WebAsyncUtils.getAsyncManager(webRequest)
val deferredResult = convertToDeferredResult(responseEntity, single)
asyncManager.startDeferredResultProcessing(deferredResult, mavContainer)
}
private fun ResponseEntity<*>?.copy(body: Any): ResponseEntity<*> {
val statusCode: HttpStatus
val headers: HttpHeaders
if (this !== null) {
statusCode = this.statusCode
headers = this.headers
} else {
statusCode = HttpStatus.OK
headers = HttpHeaders()
}
return ResponseEntity(body, headers, statusCode)
}
private fun convertToDeferredResult(responseEntity: ResponseEntity<Single<*>>?,
single: Single<*>): DeferredResult<*> {
val singleResponse = single.map { returnValue ->
@Suppress("IfThenToElvis")
if (returnValue is ResponseEntity<*>) {
returnValue
} else if (returnValue is ResponseEntityConvertible<*>) {
returnValue.toResponseEntity()
} else {
responseEntity.copy(body = returnValue)
}
}
return SingleDeferredResult(single = singleResponse)
}
}
| apache-2.0 | 16d6f6fcb95d5d788b1a92038173d792 | 36.947761 | 153 | 0.656637 | 5.17294 | false | false | false | false |
rei-m/android_hyakuninisshu | state/src/main/java/me/rei_m/hyakuninisshu/state/training/store/TrainingStarterStore.kt | 1 | 2062 | /*
* Copyright (c) 2020. Rei Matsushita
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package me.rei_m.hyakuninisshu.state.training.store
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import me.rei_m.hyakuninisshu.state.core.Dispatcher
import me.rei_m.hyakuninisshu.state.core.Event
import me.rei_m.hyakuninisshu.state.core.Store
import me.rei_m.hyakuninisshu.state.training.action.StartTrainingAction
import javax.inject.Inject
/**
* 練習の開始状態を管理する.
*/
class TrainingStarterStore @Inject constructor(dispatcher: Dispatcher) : Store() {
private val _onReadyEvent = MutableLiveData<Event<String>>()
val onReadyEvent: LiveData<Event<String>> = _onReadyEvent
private val _isEmpty = MutableLiveData(false)
val isEmpty: LiveData<Boolean> = _isEmpty
private val _isFailure = MutableLiveData(false)
val isFailure: LiveData<Boolean> = _isFailure
init {
register(dispatcher.on(StartTrainingAction::class.java).subscribe {
when (it) {
is StartTrainingAction.Success -> {
_onReadyEvent.value = Event(it.questionId)
_isEmpty.value = false
_isFailure.value = false
}
is StartTrainingAction.Empty -> {
_isEmpty.value = true
_isFailure.value = false
}
is StartTrainingAction.Failure -> {
_isFailure.value = true
}
}
})
}
}
| apache-2.0 | 31f8b3a4aa57edfc607de9520ffcde7b | 35.392857 | 112 | 0.663886 | 4.420824 | false | false | false | false |
stoman/CompetitiveProgramming | problems/2021adventofcode16a/submissions/accepted/Stefan.kt | 2 | 2028 | import java.util.*
abstract class Packet(val version: Int, val type: Int, val bitCount: Int) {
fun versionSum(): Int = version + if(this is Operator) subPackets.sumOf { it.versionSum() } else 0
}
class Literal(version: Int, type: Int, bitCount: Int, val value: Int) : Packet(version, type, bitCount)
class Operator(version: Int, type: Int, bitCount: Int, val subPackets: List<Packet>) : Packet(version, type, bitCount)
fun Char.toBits(): List<Int> {
var v = lowercaseChar().digitToInt(16)
val r = mutableListOf<Int>()
repeat(4) {
r.add(v % 2)
v /= 2
}
return r.reversed()
}
fun List<Int>.parseBits(): Int {
var r = 0
for (bit in this) {
r *= 2
r += bit
}
return r
}
fun List<Int>.parsePacket(): Packet {
val version = slice(0..2).parseBits()
when (val type = slice(3..5).parseBits()) {
// Literal value.
4 -> {
val value = mutableListOf<Int>()
var i = 1
do {
i += 5
value.addAll(slice(i + 1..i + 4))
} while (get(i) == 1)
return Literal(version, type, i + 5, value.parseBits())
}
// Operator
else -> {
val subPackets = mutableListOf<Packet>()
var parsedBits = 0
when(get(6)) {
0 -> {
val subLength = slice(7..21).parseBits()
parsedBits = 22
while(parsedBits < 22 + subLength) {
val nextPacket = drop(parsedBits).parsePacket()
subPackets.add(nextPacket)
parsedBits += nextPacket.bitCount
}
}
1 -> {
val subLength = slice(7..17).parseBits()
parsedBits = 18
while(subPackets.size < subLength) {
val nextPacket = drop(parsedBits).parsePacket()
subPackets.add(nextPacket)
parsedBits += nextPacket.bitCount
}
}
}
return Operator(version, type, parsedBits, subPackets)
}
}
}
fun main() {
val packet = Scanner(System.`in`).next().flatMap { it.toBits() }.parsePacket()
println(packet.versionSum())
}
| mit | 94e8afc89a3b24d9c3a3bf9f9a2961b7 | 26.04 | 118 | 0.573964 | 3.564148 | false | false | false | false |
openMF/android-client | mifosng-android/src/main/java/com/mifos/mifosxdroid/online/savingsaccountapproval/SavingsAccountApprovalFragment.kt | 1 | 5669 | /*
* This project is licensed under the open source MPL V2.
* See https://github.com/openMF/android-client/blob/master/LICENSE.md
*/
package com.mifos.mifosxdroid.online.savingsaccountapproval
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.mifos.api.GenericResponse
import com.mifos.mifosxdroid.R
import com.mifos.mifosxdroid.core.MifosBaseActivity
import com.mifos.mifosxdroid.core.MifosBaseFragment
import com.mifos.mifosxdroid.uihelpers.MFDatePicker
import com.mifos.mifosxdroid.uihelpers.MFDatePicker.OnDatePickListener
import com.mifos.objects.accounts.loan.SavingsApproval
import com.mifos.objects.accounts.savings.DepositType
import com.mifos.utils.*
import javax.inject.Inject
/**
* @author nellyk
*/
class SavingsAccountApprovalFragment : MifosBaseFragment(), OnDatePickListener, SavingsAccountApprovalMvpView {
val LOG_TAG = javaClass.simpleName
@JvmField
@BindView(R.id.tv_approval_date)
var tvApprovalDate: TextView? = null
@JvmField
@BindView(R.id.btn_approve_savings)
var btnApproveSavings: Button? = null
@JvmField
@BindView(R.id.et_savings_approval_reason)
var etSavingsApprovalReason: EditText? = null
@JvmField
@Inject
var mSavingsAccountApprovalPresenter: SavingsAccountApprovalPresenter? = null
lateinit var rootView: View
var approvaldate: String? = null
var savingsAccountNumber = 0
var savingsAccountType: DepositType? = null
private var mfDatePicker: DialogFragment? = null
private var safeUIBlockingUtility: SafeUIBlockingUtility? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(activity as MifosBaseActivity?)!!.activityComponent.inject(this)
if (arguments != null) {
savingsAccountNumber = requireArguments().getInt(Constants.SAVINGS_ACCOUNT_NUMBER)
savingsAccountType = requireArguments().getParcelable(Constants.SAVINGS_ACCOUNT_TYPE)
}
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
activity?.actionBar?.setDisplayHomeAsUpEnabled(true)
rootView = inflater.inflate(R.layout.dialog_fragment_approve_savings, null)
ButterKnife.bind(this, rootView)
mSavingsAccountApprovalPresenter!!.attachView(this)
safeUIBlockingUtility = SafeUIBlockingUtility(activity,
getString(R.string.savings_account_approval_fragment_loading_message))
showUserInterface()
return rootView
}
override fun showUserInterface() {
mfDatePicker = MFDatePicker.newInsance(this)
tvApprovalDate!!.text = MFDatePicker.getDatePickedAsString()
approvaldate = tvApprovalDate!!.text.toString()
showApprovalDate()
}
@OnClick(R.id.btn_approve_savings)
fun onClickApproveSavings() {
if (Network.isOnline(context)) {
val savingsApproval = SavingsApproval()
savingsApproval.note = etSavingsApprovalReason!!.editableText.toString()
savingsApproval.approvedOnDate = approvaldate
initiateSavingsApproval(savingsApproval)
} else {
Toast.makeText(context,
resources.getString(R.string.error_network_not_available),
Toast.LENGTH_LONG).show()
}
}
@OnClick(R.id.tv_approval_date)
fun onClickApprovalDate() {
mfDatePicker!!.show(requireActivity().supportFragmentManager, FragmentConstants.DFRAG_DATE_PICKER)
}
override fun onDatePicked(date: String) {
tvApprovalDate!!.text = date
approvaldate = date
showApprovalDate()
}
fun showApprovalDate() {
approvaldate = DateHelper.getDateAsStringUsedForCollectionSheetPayload(approvaldate)
.replace("-", " ")
}
private fun initiateSavingsApproval(savingsApproval: SavingsApproval) {
mSavingsAccountApprovalPresenter!!.approveSavingsApplication(
savingsAccountNumber, savingsApproval)
}
override fun showSavingAccountApprovedSuccessfully(genericResponse: GenericResponse?) {
Toast.makeText(activity, "Savings Approved", Toast.LENGTH_LONG).show()
requireActivity().supportFragmentManager.popBackStack()
}
override fun showError(message: String?) {
Toast.makeText(activity, message, Toast.LENGTH_LONG).show()
}
override fun showProgressbar(b: Boolean) {
if (b) {
safeUIBlockingUtility!!.safelyBlockUI()
} else {
safeUIBlockingUtility!!.safelyUnBlockUI()
}
}
override fun onDestroyView() {
super.onDestroyView()
mSavingsAccountApprovalPresenter!!.detachView()
}
companion object {
fun newInstance(savingsAccountNumber: Int,
type: DepositType?): SavingsAccountApprovalFragment {
val savingsAccountApproval = SavingsAccountApprovalFragment()
val args = Bundle()
args.putInt(Constants.SAVINGS_ACCOUNT_NUMBER, savingsAccountNumber)
args.putParcelable(Constants.SAVINGS_ACCOUNT_TYPE, type)
savingsAccountApproval.arguments = args
return savingsAccountApproval
}
}
} | mpl-2.0 | d2cf48effc714e1c238839b914d09ded | 35.818182 | 116 | 0.712119 | 4.921007 | false | false | false | false |
danfma/kodando | kodando-mithril-router-dom/src/main/kotlin/kodando/mithril/router/dom/Link.kt | 1 | 2002 | package kodando.mithril.routing
import kodando.history.History
import kodando.mithril.*
import kodando.mithril.context.contextConsumer
import kodando.mithril.elements.a
import org.w3c.dom.events.MouseEvent
external interface LinkProps : Props {
var className: String?
var onClick: EventHandler?
var target: String?
var replace: Boolean?
var to: String
}
object LinkView : View<LinkProps> {
override fun view(vnode: VNode<LinkProps>): VNode<*>? {
val props = vnode.attrs ?: return null
val className = props.className
val children = vnode.children
return root {
contextConsumer(routerContextKey) { routerContext ->
val history = routerContext.history
val location = History.createLocation(props.to, null, null, history.location)
val href: String = history.createHref(location)
a {
if (className != null) {
this.className = className
}
this.href = href
this.onClick = handleClick(props, routerContext)
addChild(*children)
}
}
}
}
private fun handleClick(props: LinkProps, routerContext: RouterContext): EventHandlerWithArgument<MouseEvent> = { event ->
props.onClick?.invoke()
if (shouldPresentDefault(event, props)) {
event.preventDefault()
val history = routerContext.history
val replace = props.replace ?: false
val to = props.to
if (replace) {
history.replace(to)
} else {
history.push(to)
}
}
}
private fun shouldPresentDefault(event: MouseEvent, props: LinkProps): Boolean {
return !event.defaultPrevented
&& event.button == 0.toShort()
&& props.target != "_blank"
&& !isModifierEvent(event)
}
private fun isModifierEvent(event: MouseEvent): Boolean {
return event.metaKey
|| event.altKey
|| event.ctrlKey
|| event.shiftKey
}
}
fun Props.routeLink(applier: Applier<LinkProps>) {
addChild(LinkView, applier)
}
| mit | d9c22735147763d28f5b546f41bc4680 | 25 | 124 | 0.657842 | 4.170833 | false | false | false | false |
mixitconf/mixit | src/main/kotlin/mixit/MixitProperties.kt | 1 | 1298 | package mixit
import org.springframework.boot.context.properties.ConfigurationProperties
import java.math.BigDecimal
@ConfigurationProperties("mixit")
class MixitProperties {
lateinit var baseUri: String
lateinit var contact: String
lateinit var vimeoTchatUri: String
lateinit var vimeoFluxUri: String
lateinit var mixetteValue: BigDecimal
val drive = Drive()
val aes = Aes()
val googleapi = GoogleApi()
val feature = Feature()
class Drive {
val fr = DriveDocuments()
val en = DriveDocuments()
class DriveDocuments {
lateinit var sponsorform: String
lateinit var sponsor: String
lateinit var speaker: String
lateinit var press: String
}
}
class Aes {
lateinit var initvector: String
lateinit var key: String
}
class GoogleApi {
lateinit var clientid: String
lateinit var p12path: String
lateinit var user: String
lateinit var appname: String
}
class Feature {
var donation: Boolean = false
var lottery: Boolean = false
var lotteryResult: Boolean = false
var email: Boolean = false
var mixette: Boolean = false
var profilemsg: Boolean = false
}
}
| apache-2.0 | 5f67367194abda4ee82fb8c4c3236d8c | 24.45098 | 74 | 0.640986 | 4.97318 | false | false | false | false |
FarbodSalamat-Zadeh/TimetableApp | app/src/main/java/co/timetableapp/ui/exams/ExamEditActivity.kt | 1 | 9290 | /*
* Copyright 2017 Farbod Salamat-Zadeh
*
* 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 co.timetableapp.ui.exams
import android.app.Activity
import android.content.Intent
import android.support.design.widget.Snackbar
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.widget.CheckBox
import android.widget.EditText
import android.widget.NumberPicker
import android.widget.TextView
import co.timetableapp.R
import co.timetableapp.TimetableApplication
import co.timetableapp.data.handler.ExamHandler
import co.timetableapp.model.Color
import co.timetableapp.model.Exam
import co.timetableapp.model.Subject
import co.timetableapp.ui.base.ItemEditActivity
import co.timetableapp.ui.components.DateSelectorHelper
import co.timetableapp.ui.components.SubjectSelectorHelper
import co.timetableapp.ui.components.TimeSelectorHelper
import co.timetableapp.ui.subjects.SubjectEditActivity
import co.timetableapp.util.UiUtils
import co.timetableapp.util.title
import org.threeten.bp.LocalDate
import org.threeten.bp.LocalTime
/**
* Allows the user to edit an [Exam].
*
* @see ExamDetailActivity
* @see ItemEditActivity
*/
class ExamEditActivity : ItemEditActivity<Exam>() {
companion object {
private const val REQUEST_CODE_SUBJECT_DETAIL = 2
private const val NO_DURATION = -1
}
private val mDataHandler = ExamHandler(this)
private lateinit var mEditTextModule: EditText
private lateinit var mEditTextSeat: EditText
private lateinit var mEditTextRoom: EditText
private var mSubject: Subject? = null
private lateinit var mSubjectHelper: SubjectSelectorHelper
private lateinit var mExamDate: LocalDate
private lateinit var mDateHelper: DateSelectorHelper
private lateinit var mExamTime: LocalTime
private lateinit var mTimeHelper: TimeSelectorHelper
private var mExamDuration = NO_DURATION
private lateinit var mDurationText: TextView
private lateinit var mDurationDialog: AlertDialog
private var mExamIsResit: Boolean = false
private lateinit var mEditTextNotes: EditText
override fun getLayoutResource() = R.layout.activity_exam_edit
override fun getTitleRes(isNewItem: Boolean) = if (isNewItem) {
R.string.title_activity_exam_new
} else {
R.string.title_activity_exam_edit
}
override fun setupLayout() {
mEditTextModule = findViewById(R.id.editText_module) as EditText
if (!mIsNew) {
mEditTextModule.setText(mItem!!.moduleName)
}
mEditTextSeat = findViewById(R.id.editText_seat) as EditText
if (!mIsNew) {
mEditTextSeat.setText(mItem!!.seat)
}
mEditTextRoom = findViewById(R.id.editText_room) as EditText
if (!mIsNew) {
mEditTextRoom.setText(mItem!!.room)
}
mEditTextNotes = findViewById(R.id.editText_notes) as EditText
if (!mIsNew) {
mEditTextNotes.setText(mItem!!.notes)
}
setupSubjectHelper()
setupDateText()
setupTimeText()
setupDurationText()
setupResitCheckbox()
}
private fun setupSubjectHelper() {
mSubjectHelper = SubjectSelectorHelper(this, R.id.textView_subject)
mSubjectHelper.onCreateNewSubject { _, _ ->
val intent = Intent(this, SubjectEditActivity::class.java)
ActivityCompat.startActivityForResult(
this,
intent,
REQUEST_CODE_SUBJECT_DETAIL,
null
)
}
mSubjectHelper.onSubjectChange {
mSubject = it!! // exams must have related subjects - it can't be null
val color = Color(it.colorId)
UiUtils.setBarColors(
color,
this,
mToolbar!!,
findViewById(R.id.appBarLayout),
findViewById(R.id.toolbar_container)
)
}
mSubjectHelper.setup(mItem?.getRelatedSubject(this))
}
private fun setupDateText() {
mExamDate = mItem?.date ?: LocalDate.now()
mDateHelper = DateSelectorHelper(this, R.id.textView_date)
mDateHelper.setup(mExamDate) { _, date ->
mExamDate = date
mDateHelper.updateDate(mExamDate)
}
}
private fun setupTimeText() {
mExamTime = mItem?.startTime ?: LocalTime.of(9 ,0)
mTimeHelper = TimeSelectorHelper(this, R.id.textView_start_time)
mTimeHelper.setup(mExamTime) { _, time ->
mExamTime = time
mTimeHelper.updateTime(mExamTime)
}
}
private fun setupDurationText() {
mDurationText = findViewById(R.id.textView_duration) as TextView
if (!mIsNew) {
mExamDuration = mItem!!.duration
updateDurationText()
}
mDurationText.setOnClickListener {
val builder = AlertDialog.Builder(this@ExamEditActivity)
val numberPicker = NumberPicker(baseContext)
numberPicker.minValue = 10
numberPicker.maxValue = 360
numberPicker.value = if (mExamDuration == NO_DURATION) 60 else mExamDuration
val titleView = layoutInflater.inflate(R.layout.dialog_title_with_padding, null)
(titleView.findViewById(R.id.title) as TextView).setText(R.string.property_duration)
builder.setView(numberPicker)
.setCustomTitle(titleView)
.setPositiveButton(R.string.action_done) { _, _ ->
mExamDuration = numberPicker.value
updateDurationText()
mDurationDialog.dismiss()
}
mDurationDialog = builder.create()
mDurationDialog.show()
}
}
private fun updateDurationText() {
mDurationText.text = "$mExamDuration mins"
mDurationText.setTextColor(ContextCompat.getColor(baseContext, R.color.mdu_text_black))
}
private fun setupResitCheckbox() {
mExamIsResit = !mIsNew && mItem!!.resit
val checkBox = findViewById(R.id.checkBox_resit) as CheckBox
checkBox.isChecked = mExamIsResit
checkBox.setOnCheckedChangeListener { _, isChecked -> mExamIsResit = isChecked }
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_SUBJECT_DETAIL) {
if (resultCode == Activity.RESULT_OK) {
mSubject = data.getParcelableExtra<Subject>(ItemEditActivity.EXTRA_ITEM)
mSubjectHelper.updateSubject(mSubject)
}
}
}
override fun handleDoneAction() {
var newModuleName = mEditTextModule.text.toString()
newModuleName = newModuleName.title()
if (mSubject == null) {
Snackbar.make(findViewById(R.id.rootView), R.string.message_subject_required,
Snackbar.LENGTH_SHORT).show()
return
}
if (mExamDuration == -1) {
Snackbar.make(findViewById(R.id.rootView), R.string.message_exam_duration_required,
Snackbar.LENGTH_SHORT).show()
return
}
val id = if (mIsNew) mDataHandler.getHighestItemId() + 1 else mItem!!.id
val timetableId = (application as TimetableApplication).currentTimetable!!.id
mItem = Exam(
id,
timetableId,
mSubject!!.id,
newModuleName,
mExamDate,
mExamTime,
mExamDuration,
mEditTextSeat.text.toString().trim(),
mEditTextRoom.text.toString().trim(),
mExamIsResit,
mEditTextNotes.text.toString().trim()
)
if (mIsNew) {
mDataHandler.addItem(mItem!!)
} else {
mDataHandler.replaceItem(mItem!!.id, mItem!!)
}
val intent = Intent()
setResult(Activity.RESULT_OK, intent)
supportFinishAfterTransition()
}
override fun handleDeleteAction() {
AlertDialog.Builder(this)
.setTitle(R.string.delete_exam)
.setMessage(R.string.delete_confirmation)
.setPositiveButton(R.string.action_delete) { _, _ ->
mDataHandler.deleteItem(mItem!!.id)
setResult(Activity.RESULT_OK)
finish()
}
.setNegativeButton(R.string.action_cancel, null)
.show()
}
}
| apache-2.0 | fae3b20f290a72c14d3f2825c62e302d | 31.711268 | 96 | 0.634876 | 4.77635 | false | false | false | false |
tipsy/javalin | javalin/src/main/java/io/javalin/plugin/rendering/template/JavalinJte.kt | 1 | 1777 | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin.plugin.rendering.template
import gg.jte.ContentType
import gg.jte.TemplateEngine
import gg.jte.output.StringOutput
import gg.jte.resolve.DirectoryCodeResolver
import io.javalin.core.util.OptionalDependency
import io.javalin.core.util.Util
import io.javalin.http.Context
import io.javalin.http.util.ContextUtil.isLocalhost
import io.javalin.plugin.rendering.FileRenderer
import java.io.File
object JavalinJte : FileRenderer {
private var isDev: Boolean? = null // cached and easily accessible, is set on first request (can't be configured directly by end user)
@JvmField
var isDevFunction: (Context) -> Boolean = { it.isLocalhost() } // used to set isDev, will be called once
private var templateEngine: TemplateEngine? = null
private val defaultTemplateEngine: TemplateEngine by lazy { defaultJteEngine() }
@JvmStatic
fun configure(staticTemplateEngine: TemplateEngine) {
templateEngine = staticTemplateEngine
}
override fun render(filePath: String, model: Map<String, Any?>, ctx: Context): String {
Util.ensureDependencyPresent(OptionalDependency.JTE)
isDev = isDev ?: isDevFunction(ctx)
if (isDev == true && filePath.endsWith(".kte")) {
Util.ensureDependencyPresent(OptionalDependency.JTE_KOTLIN)
}
val stringOutput = StringOutput()
(templateEngine ?: defaultTemplateEngine).render(filePath, model, stringOutput)
return stringOutput.toString()
}
private fun defaultJteEngine() = TemplateEngine.create(DirectoryCodeResolver(File("src/main/jte").toPath()), ContentType.Html)
}
| apache-2.0 | 1f22b088063fe53a326baf018909bfdf | 36 | 138 | 0.737613 | 4.228571 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/charging_station_operator/AddChargingStationOperator.kt | 1 | 1166 | package de.westnordost.streetcomplete.quests.charging_station_operator
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CAR
class AddChargingStationOperator : OsmFilterQuestType<String>() {
override val elementFilter = """
nodes, ways with
amenity = charging_station
and !operator and !name and !brand
"""
override val commitMessage = "Add charging station operator"
override val wikiLink = "Tag:amenity=charging_station"
override val icon = R.drawable.ic_quest_car_charger
override val isDeleteElementEnabled = true
override val questTypeAchievements = listOf(CAR)
override fun getTitle(tags: Map<String, String>): Int = R.string.quest_charging_station_operator_title
override fun createForm() = AddChargingStationOperatorForm()
override fun applyAnswerTo(answer: String, changes: StringMapChangesBuilder) {
changes.add("operator", answer)
}
}
| gpl-3.0 | 4884e56007326a2683c29d9278054fac | 39.206897 | 106 | 0.765866 | 4.798354 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/api/util/option/OptionMaps.kt | 1 | 1721 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
@file:Suppress("UNCHECKED_CAST")
package org.lanternpowered.api.util.option
import org.lanternpowered.api.util.collections.toImmutableMap
import org.lanternpowered.api.util.collections.toImmutableSet
/**
* Base class for all the [OptionMap]s.
*/
abstract class OptionMapBase<T : OptionMapType> internal constructor(val map: MutableMap<Option<T, Any?>, Any?>) : OptionMap<T> {
override fun options(): Collection<Option<T, *>> = this.map.keys.toImmutableSet()
override operator fun <V> get(option: Option<T, V>): V {
return (this.map[option as Option<T, Any?>] ?: option.defaultValue) as V
}
override operator fun contains(option: Option<T, *>): Boolean = (option as Option<T, Any?>) in this.map
}
/**
* A unmodifiable [OptionMap].
*/
internal class UnmodifiableOptionMap<T : OptionMapType>(map: MutableMap<Option<T, Any?>, Any?>) : OptionMapBase<T>(map)
/**
* A [HashMap] backed implementation of the [OptionMap].
*
* @param T The option map type
*/
class OptionHashMap<T : OptionMapType> : OptionMapBase<T>(HashMap()), MutableOptionMap<T> {
override fun asUnmodifiable(): OptionMap<T> = UnmodifiableOptionMap(this.map)
override fun toImmutable(): OptionMap<T> = UnmodifiableOptionMap(this.map.toImmutableMap())
override operator fun <V> set(option: Option<T, V>, value: V) {
this.map[option as Option<T, Any?>] = value as Any?
}
}
| mit | d8fd744eb5d5cbbbe5c558804103e4d8 | 33.42 | 129 | 0.70308 | 3.600418 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/inspections/latex/redundancy/LatexRedundantParInspection.kt | 1 | 1423 | package nl.hannahsten.texifyidea.inspections.latex.redundancy
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import nl.hannahsten.texifyidea.inspections.TexifyRegexInspection
import nl.hannahsten.texifyidea.psi.LatexTypes
import nl.hannahsten.texifyidea.util.toTextRange
import java.util.regex.Matcher
import java.util.regex.Pattern
/**
* @author Hannah Schellekens
*/
open class LatexRedundantParInspection : TexifyRegexInspection(
inspectionDisplayName = "Redundant use of \\par",
inspectionId = "RedundantPar",
errorMessage = { "Use of \\par is redundant here" },
pattern = Pattern.compile("((\\s*\\n\\s*\\n\\s*(\\\\par))|(\\n\\s*(\\\\par)\\s*\\n)|((\\\\par)\\s*\\n\\s*\\n))"),
replacement = { _, _ -> "" },
replacementRange = this::parRange,
quickFixName = { "Remove \\par" },
highlightRange = { parRange(it).toTextRange() }
) {
companion object {
fun parRange(it: Matcher) = when {
it.group(3) != null -> it.groupRange(3)
it.group(5) != null -> it.groupRange(5)
else -> it.groupRange(7)
}
}
override fun checkContext(matcher: Matcher, element: PsiElement): Boolean {
val elt = element.containingFile.findElementAt(matcher.end()) as? LeafPsiElement
return super.checkContext(matcher, element) && elt?.elementType != LatexTypes.COMMAND_TOKEN ?: true
}
} | mit | 44bb4b05b7e8152147cd29461a710d6f | 36.473684 | 117 | 0.670415 | 3.89863 | false | false | false | false |
RoverPlatform/rover-android | experiences/src/main/kotlin/io/rover/sdk/experiences/ui/blocks/poll/VotingService.kt | 1 | 2760 | package io.rover.sdk.experiences.ui.blocks.poll
import android.net.Uri
import io.rover.sdk.core.data.NetworkResult
import io.rover.sdk.core.data.http.AndroidHttpsUrlConnectionNetworkClient
import io.rover.sdk.core.data.http.HttpClientResponse
import io.rover.sdk.core.data.http.HttpRequest
import io.rover.sdk.core.data.http.HttpVerb
import io.rover.sdk.core.streams.map
import io.rover.sdk.experiences.data.http.HttpResultMapper
import io.rover.sdk.experiences.logging.log
import org.json.JSONObject
import org.reactivestreams.Publisher
import java.net.URL
internal class VotingService(
private val endpoint: String,
private val httpClient: AndroidHttpsUrlConnectionNetworkClient,
private val httpResultMapper: HttpResultMapper = HttpResultMapper(),
private val urlBuilder: URLBuilder = URLBuilder()
) {
fun fetchResults(pollId: String, optionIds: List<String>): Publisher<NetworkResult<OptionResults>> {
val url = urlBuilder.build(endpoint, listOf(pollId), optionIds.map { "options" to it })
val urlRequest = HttpRequest(url, hashMapOf(), HttpVerb.GET)
return httpClient.request(urlRequest, null).map { httpClientResponse ->
httpResultMapper.mapResultWithBody(httpClientResponse) {
OptionResults.decodeJson(JSONObject(it))
}
}
}
fun castVote(pollId: String, optionId: String, jsonObject: JSONObject = JSONObject()): Publisher<VoteOutcome> {
val url = urlBuilder.build(endpoint, listOf(pollId, "vote"))
val urlRequest = HttpRequest(url, hashMapOf("Content-Type" to "application/json"), HttpVerb.POST)
val body = jsonObject.apply {
put("option", optionId)
}.toString()
return httpClient.request(urlRequest, body, false).map {
when (it) {
is HttpClientResponse.Success -> {
log.v("vote in poll $pollId with option $optionId succeeded")
VoteOutcome.VoteSuccess
}
is HttpClientResponse.ApplicationError, is HttpClientResponse.ConnectionFailure -> {
log.w("voting failed $it")
VoteOutcome.VoteFailure
}
}
}
}
}
internal sealed class VoteOutcome {
object VoteSuccess: VoteOutcome()
object VoteFailure: VoteOutcome()
}
internal class URLBuilder {
fun build(url: String, pathParams: List<String>? = null, queryParams: List<Pair<String, String>>? = null): URL {
val uri = Uri.parse(url).buildUpon().apply {
pathParams?.forEach { appendPath(it) }
queryParams?.forEach { appendQueryParameter(it.first, it.second) }
}.toString()
return URL(uri)
}
}
| apache-2.0 | 7ba3bcb5654777f05fc6e715fbe71b62 | 38.428571 | 116 | 0.670652 | 4.387917 | false | false | false | false |
GuiyeC/Aerlink-for-Android | wear/src/main/java/com/codegy/aerlink/ui/AerlinkActivity.kt | 1 | 3329 | package com.codegy.aerlink.ui
import android.util.Log
import android.view.View
import com.codegy.aerlink.R
import com.codegy.aerlink.connection.ConnectionState
import kotlinx.android.synthetic.main.merge_connection_info.*
import kotlinx.android.synthetic.main.merge_error.*
import kotlinx.android.synthetic.main.merge_loading.*
abstract class AerlinkActivity : ServiceActivity() {
override fun updateInterfaceForState(state: ConnectionState) {
Log.d(LOG_TAG, "updateInterfaceForState :: state: $state")
val connectionInfoView = connectionInfoView ?: return
val connectionInfoTextView = connectionInfoTextView ?: return
runOnUiThread {
if (state == ConnectionState.Ready) {
connectionInfoView.visibility = View.GONE
return@runOnUiThread
}
connectionInfoView.visibility = View.VISIBLE
when (state) {
ConnectionState.Ready -> {}
ConnectionState.Connecting -> {
connectionInfoTextView.setTextColor(getColor(R.color.connection_state_connecting))
connectionInfoTextView.text = getString(R.string.connection_state_connecting)
connectionInfoHelpTextView?.text = getString(R.string.connection_state_disconnected_help)
}
ConnectionState.Bonding -> {
connectionInfoTextView.setTextColor(getColor(R.color.connection_state_bonding))
connectionInfoTextView.text = getString(R.string.connection_state_bonding)
connectionInfoHelpTextView?.text = getString(R.string.connection_state_disconnected_help)
}
ConnectionState.Disconnected -> {
connectionInfoTextView.setTextColor(getColor(R.color.connection_state_disconnected))
connectionInfoTextView.text = getString(R.string.connection_state_disconnected)
connectionInfoHelpTextView?.text = getString(R.string.connection_state_disconnected_help)
}
ConnectionState.Stopped -> {
connectionInfoTextView.setTextColor(getColor(R.color.connection_state_stopped))
connectionInfoTextView.text = getString(R.string.connection_state_stopped)
connectionInfoHelpTextView?.text = getString(R.string.connection_state_stopped_help)
}
}
}
}
fun showLoading(visible: Boolean) {
Log.d(LOG_TAG, "showLoading :: Visible: $visible")
val loadingView = loadingView ?: return
if (visible && loadingView.visibility == View.VISIBLE
|| !visible && loadingView.visibility == View.GONE) {
return
}
runOnUiThread {
loadingView.visibility = if (visible) View.VISIBLE else View.GONE
}
}
fun showError(visible: Boolean) {
Log.d(LOG_TAG, "showError :: Visible: $visible")
runOnUiThread {
errorView?.visibility = if (visible) View.VISIBLE else View.GONE
}
}
fun restartConnectionAction(view: View) {
stopService()
startService()
}
companion object {
private val LOG_TAG: String = AerlinkActivity::class.java.simpleName
}
} | mit | 6f083c31c86c67165feb88288f5289b5 | 42.246753 | 109 | 0.637429 | 5.043939 | false | false | false | false |
NextFaze/dev-fun | devfun-annotations/src/main/java/com/nextfaze/devfun/function/DeveloperArguments.kt | 1 | 7031 | package com.nextfaze.devfun.function
import com.nextfaze.devfun.DeveloperAnnotation
import com.nextfaze.devfun.category.DeveloperCategory
import com.nextfaze.devfun.category.DeveloperCategoryProperties
import kotlin.annotation.AnnotationRetention.SOURCE
import kotlin.annotation.AnnotationTarget.FUNCTION
import kotlin.reflect.KClass
/**
* A function transformer that tells DevFun how to generate functions for annotation-defined arguments.
*
* @see DeveloperArguments
*/
interface ArgumentsTransformer : FunctionTransformer
/**
* An alternative to [DeveloperFunction] that allows you to provide arguments for multiple invocations.
*
* _Note: This annotation is *[SOURCE]* retained - its contents will not be kept in your binary!_
*
* For an example usage, see demo [AuthenticateFragment.signInAs](https://github.com/NextFaze/dev-fun/tree/master/demo/src/main/java/com/nextfaze/devfun/demo/AuthenticateScreen.kt#L200)
*
*
* # Args Format
* Each element in the args will be converted to the appropriate type from the string provided based on the function's parameter types.
* i.e. "1.0f" -> Float
*
* ```kotlin
* @DeveloperArguments(
* args = [Args(["A string", "1.0f"])]
* )
* fun myFunction(str: String, float: Float) = Unit
* ```
* If the second parameter was a string then it would remain a string `"1.0f"` etc.
*
*
* # Supported Types
* At present only simple types and strings are supported simply because I haven't used anything more - you're welcome to create an issue
* for other types and it'll likely be supported.
*
* If a type is not supported (or an arg is out of bounds) then DevFun will attempt to inject it as per normal DevFun behaviour.
*
*
* # Arg-index [name] & [group]
* You can use `%d` to reference your args array.
*
* i.e.
* `name = "%2"` -> `name = args[n][2]`
*
* e.g.
* ```kotlin
* @DeveloperArguments(
* name = "The string arg is: '%0'"
* args = [
* Args(["Hello", "1.0f"]), // name = "The string arg is: 'Hello'"
* Args(["World", "-1.0f"]) // name = "The string arg is: 'World'"
* ]
* )
* fun myFunction(str: String, float: Float) = Unit
* ```
*
*
* # Example Usage
* _Taken from demo [AuthenticateFragment.signInAs](https://github.com/NextFaze/dev-fun/tree/master/demo/src/main/java/com/nextfaze/devfun/demo/AuthenticateScreen.kt#L200)_
*
* ```kotlin
* @DeveloperArguments(
* args = [
* Args(["[email protected]", "hello", "Normal"]),
* Args(["[email protected]", "world", "Normal"]),
* Args(["[email protected]", "ContainDateNeck76", "Normal"]),
* Args(["[email protected]", "EveningVermontNeck29", "Normal"]),
* Args(["[email protected]", "OftenJumpCost02", "Normal"]),
* Args(["[email protected]", "TakePlayThought95", "Restricted"]),
* Args(["[email protected]", "DeviceSeedsSeason16", "Restricted"]),
* Args(["[email protected]", "ChinaMisterGeneral11", "Banned"]),
* Args(["[email protected]", "my.password", "Underage"]),
* Args(["[email protected]", "password", "Underage"]),
* Args(["[email protected]", "D3;d<HF-", "Invalid Password"]),
* Args(["[email protected]", "r2Z@fMhA", "Invalid Password"]),
* Args(["[email protected]", "RV[(x43@", "Unknown User"])
* ],
* group = "Authenticate as %2"
* )
* private fun signInAs(email: String, password: String) {
* emailEditText.setText(email)
* passwordEditText.setText(password)
* attemptLogin()
* }
* ```
* - Will result in 13 functions in the Context group when on the authenticate screen.
* - The functions will be grouped by the 3rd element "Authenticate as %2"
*
* Context Menu:
* - Authenticate as Normal
* - [email protected]
* - [email protected]
* - ...
* - Authenticate as Restricted
* - [email protected]
* - ...
*
*
* ## Sensitive Information
* A reminder that `DeveloperArguments` is _SOURCE_ retained - it will not be present in your compiled files.
*
* An alternative to having this annotation at the use-site could be to have the declaration in your Debug sources an invoke it from there.
* ```kotlin
* object MyDebugUtils {
* @DeveloperArguments(...)
* fun signInAs(...) {
* }
* }
* ```
* An alternative would be to have `signInAs` be called from the `Debug` source tree or by some other means
*
*
* # Experimental Feature
* __This annotation is experimental.__
*
* Any and all input is welcome!
*
* @param name The function's name (equivalent to [DeveloperFunction.value]). Defaults to the first element in each args item `%0`. A `null` or blank value falls back [FunctionItem.name].
* @param args A list of [Args], with each item an alternative invocation. Behaviour is as [FunctionItem.args].
* @param group A grouping for the functions - defaults to the function's name. A `null` or blank value falls back to [FunctionItem.group].
* @param requiresApi This is equivalent to [DeveloperFunction.requiresApi].
* @param transformer This is equivalent to [DeveloperFunction.transformer] - _do not change this unless you know what you're doing!_
*
* @see ArgumentsTransformer
* @see DeveloperFunction
*/
@Retention(SOURCE)
@Target(FUNCTION)
@DeveloperAnnotation(developerFunction = true)
annotation class DeveloperArguments(
val name: String = "%0",
val args: Array<Args>,
val group: String = "%FUN_SN%",
val category: DeveloperCategory = DeveloperCategory(),
val requiresApi: Int = 0,
val transformer: KClass<out FunctionTransformer> = ArgumentsTransformer::class
)
/**
* Nested annotation for declaring the arguments of a function invocation.
*
* @param value The arguments of the invocation. At present only primitive types are supported (`.toType()` will be used on the entry).
*
* @see DeveloperArguments
*/
annotation class Args(
val value: Array<String>
)
/** Properties interface for @[Args].
*
* TODO: This interface should be generated by DevFun at compile time, but as the annotations are in a separate module to the compiler
* that itself depends on the annotations module, it is non-trivial to run the DevFun processor upon it (module dependencies become cyclic).
*/
interface ArgsProperties {
val value: Array<String>
}
/**
* Properties interface for @[DeveloperArguments].
*
* TODO: This interface should be generated by DevFun at compile time, but as the annotations are in a separate module to the compiler
* that itself depends on the annotations module, it is non-trivial to run the DevFun processor upon it (module dependencies become cyclic).
*/
interface DeveloperArgumentsProperties {
val name: String get() = "%0"
val args: Array<ArgsProperties>
val group: String get() = "%FUN_SN%"
val category: DeveloperCategoryProperties get() = object : DeveloperCategoryProperties {}
val requiresApi: Int get() = 0
val transformer: KClass<out FunctionTransformer> get() = ArgumentsTransformer::class
}
| apache-2.0 | 2a6e9d58bc5f7ad5c65ade51046d0dc7 | 38.5 | 187 | 0.689802 | 3.767953 | false | false | false | false |
yinpeng/kotlin-matrix | src/main/kotlin/com/ichipsea/kotlin/matrix/NumberMatrix.kt | 1 | 1428 | package com.ichipsea.kotlin.matrix
operator fun <M: Number, N: Number> Matrix<M>.plus(other: Matrix<N>): Matrix<Double> {
if (rows !== other.rows || cols !== other.cols)
throw IllegalArgumentException("Matrices not match")
return mapIndexed { x, y, value -> value.toDouble() + other[x, y].toDouble() }
}
operator fun <N: Number> Matrix<N>.unaryMinus(): Matrix<Double> {
return map { -it.toDouble() }
}
operator fun <M: Number, N: Number> Matrix<M>.minus(other: Matrix<N>): Matrix<Double> {
return this + (-other)
}
operator fun <M: Number, N: Number> Matrix<M>.times(other: Matrix<N>): Matrix<Double> {
if (rows !== other.rows || cols !== other.cols)
throw IllegalArgumentException("Matrices not match")
return mapIndexed { x, y, value -> value.toDouble() * other[x, y].toDouble() }
}
operator fun <M: Number> Matrix<M>.times(other: Number): Matrix<Double> {
return map { it.toDouble() * other.toDouble() }
}
operator fun <M: Number> Number.times(other: Matrix<M>): Matrix<Double> {
return other * this
}
infix fun <M: Number, N: Number> Matrix<M>.x(other: Matrix<N>): Matrix<Double> {
if (rows !== other.cols)
throw IllegalArgumentException("Matrices not match")
return createMatrix(cols, other.rows) { x, y ->
var value = .0
for (i in 0..rows-1)
value += this[x, i].toDouble() * other[i, y].toDouble()
value
}
}
| apache-2.0 | daaeef565081e252621e7fdd222fd168 | 32.209302 | 87 | 0.630952 | 3.42446 | false | false | false | false |
wiltonlazary/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/cgen/CBridgeGen.kt | 1 | 62687 | package org.jetbrains.kotlin.backend.konan.cgen
import org.jetbrains.kotlin.backend.common.ir.addFakeOverrides
import org.jetbrains.kotlin.backend.common.ir.createDispatchReceiverParameter
import org.jetbrains.kotlin.backend.common.ir.createParameterDeclarations
import org.jetbrains.kotlin.backend.common.ir.simpleFunctions
import org.jetbrains.kotlin.backend.common.lower.at
import org.jetbrains.kotlin.backend.common.lower.irNot
import org.jetbrains.kotlin.backend.konan.KonanFqNames
import org.jetbrains.kotlin.backend.konan.PrimitiveBinaryType
import org.jetbrains.kotlin.backend.konan.RuntimeNames
import org.jetbrains.kotlin.backend.konan.descriptors.konanLibrary
import org.jetbrains.kotlin.backend.konan.ir.*
import org.jetbrains.kotlin.backend.konan.isObjCMetaClass
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.UnsignedType
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrClassImpl
import org.jetbrains.kotlin.ir.declarations.impl.IrConstructorImpl
import org.jetbrains.kotlin.ir.declarations.impl.IrFunctionImpl
import org.jetbrains.kotlin.ir.declarations.impl.IrValueParameterImpl
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.IrConstImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrFunctionReferenceImpl
import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
import org.jetbrains.kotlin.ir.symbols.impl.IrClassSymbolImpl
import org.jetbrains.kotlin.ir.symbols.impl.IrConstructorSymbolImpl
import org.jetbrains.kotlin.ir.symbols.impl.IrSimpleFunctionSymbolImpl
import org.jetbrains.kotlin.ir.symbols.impl.IrValueParameterSymbolImpl
import org.jetbrains.kotlin.ir.types.*
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.konan.target.Family
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.backend.konan.getObjCMethodInfo
import org.jetbrains.kotlin.backend.konan.lower.FunctionReferenceLowering
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.ir.descriptors.*
import org.jetbrains.kotlin.konan.ForeignExceptionMode
internal interface KotlinStubs {
val irBuiltIns: IrBuiltIns
val symbols: KonanSymbols
val target: KonanTarget
fun addKotlin(declaration: IrDeclaration)
fun addC(lines: List<String>)
fun getUniqueCName(prefix: String): String
fun getUniqueKotlinFunctionReferenceClassName(prefix: String): String
fun reportError(location: IrElement, message: String): Nothing
fun throwCompilerError(element: IrElement?, message: String): Nothing
}
private class KotlinToCCallBuilder(
val irBuilder: IrBuilderWithScope,
val stubs: KotlinStubs,
val isObjCMethod: Boolean,
foreignExceptionMode: ForeignExceptionMode.Mode
) {
val cBridgeName = stubs.getUniqueCName("knbridge")
val symbols: KonanSymbols get() = stubs.symbols
val bridgeCallBuilder = KotlinCallBuilder(irBuilder, symbols)
val bridgeBuilder = KotlinCBridgeBuilder(irBuilder.startOffset, irBuilder.endOffset, cBridgeName, stubs, isKotlinToC = true, foreignExceptionMode)
val cBridgeBodyLines = mutableListOf<String>()
val cCallBuilder = CCallBuilder()
val cFunctionBuilder = CFunctionBuilder()
}
private fun KotlinToCCallBuilder.passThroughBridge(argument: IrExpression, kotlinType: IrType, cType: CType): CVariable {
bridgeCallBuilder.arguments += argument
return bridgeBuilder.addParameter(kotlinType, cType).second
}
private fun KotlinToCCallBuilder.addArgument(
argument: IrExpression,
type: IrType,
variadic: Boolean,
parameter: IrValueParameter?
) {
val argumentPassing = mapCalleeFunctionParameter(type, variadic, parameter, argument)
addArgument(argument, argumentPassing, variadic)
}
private fun KotlinToCCallBuilder.addArgument(
argument: IrExpression,
argumentPassing: KotlinToCArgumentPassing,
variadic: Boolean
) {
val cArgument = with(argumentPassing) { passValue(argument) } ?: return
cCallBuilder.arguments += cArgument.expression
if (!variadic) cFunctionBuilder.addParameter(cArgument.type)
}
private fun KotlinToCCallBuilder.buildKotlinBridgeCall(transformCall: (IrMemberAccessExpression<*>) -> IrExpression = { it }): IrExpression =
bridgeCallBuilder.build(
bridgeBuilder.buildKotlinBridge().also {
this.stubs.addKotlin(it)
},
transformCall
)
internal fun KotlinStubs.generateCCall(expression: IrCall, builder: IrBuilderWithScope, isInvoke: Boolean,
foreignExceptionMode: ForeignExceptionMode.Mode = ForeignExceptionMode.default): IrExpression {
require(expression.dispatchReceiver == null)
val callBuilder = KotlinToCCallBuilder(builder, this, isObjCMethod = false, foreignExceptionMode)
val callee = expression.symbol.owner
// TODO: consider computing all arguments before converting.
val targetPtrParameter: String?
val targetFunctionName: String
if (isInvoke) {
targetPtrParameter = callBuilder.passThroughBridge(
expression.extensionReceiver!!,
symbols.interopCPointer.typeWithStarProjections,
CTypes.voidPtr
).name
targetFunctionName = "targetPtr"
(0 until expression.valueArgumentsCount).forEach {
callBuilder.addArgument(
expression.getValueArgument(it)!!,
type = expression.getTypeArgument(it)!!,
variadic = false,
parameter = null
)
}
} else {
require(expression.extensionReceiver == null)
targetPtrParameter = null
targetFunctionName = this.getUniqueCName("target")
val arguments = (0 until expression.valueArgumentsCount).map {
expression.getValueArgument(it)
}
callBuilder.addArguments(arguments, callee)
}
val returnValuePassing = if (isInvoke) {
val returnType = expression.getTypeArgument(expression.typeArgumentsCount - 1)!!
mapReturnType(returnType, TypeLocation.FunctionCallResult(expression), signature = null)
} else {
mapReturnType(callee.returnType, TypeLocation.FunctionCallResult(expression), signature = callee)
}
val result = callBuilder.buildCall(targetFunctionName, returnValuePassing)
val targetFunctionVariable = CVariable(CTypes.pointer(callBuilder.cFunctionBuilder.getType()), targetFunctionName)
if (isInvoke) {
callBuilder.cBridgeBodyLines.add(0, "$targetFunctionVariable = ${targetPtrParameter!!};")
} else {
val cCallSymbolName = callee.getAnnotationArgumentValue<String>(cCall, "id")!!
this.addC(listOf("extern const $targetFunctionVariable __asm(\"$cCallSymbolName\");")) // Exported from cinterop stubs.
}
callBuilder.emitCBridge()
return result
}
private fun KotlinToCCallBuilder.addArguments(arguments: List<IrExpression?>, callee: IrFunction) {
arguments.forEachIndexed { index, argument ->
val parameter = callee.valueParameters[index]
if (parameter.isVararg) {
require(index == arguments.lastIndex)
addVariadicArguments(argument)
cFunctionBuilder.variadic = true
} else {
addArgument(argument!!, parameter.type, variadic = false, parameter = parameter)
}
}
}
private fun KotlinToCCallBuilder.addVariadicArguments(
argumentForVarargParameter: IrExpression?
) = handleArgumentForVarargParameter(argumentForVarargParameter) { variable, elements ->
if (variable == null) {
unwrapVariadicArguments(elements).forEach {
addArgument(it, it.type, variadic = true, parameter = null)
}
} else {
// See comment in [handleArgumentForVarargParameter].
// Array for this vararg parameter is already computed before the call,
// so query statically known typed arguments from this array.
with(irBuilder) {
val argumentTypes = unwrapVariadicArguments(elements).map { it.type }
argumentTypes.forEachIndexed { index, type ->
val untypedArgument = irCall(symbols.arrayGet[symbols.array]!!.owner).apply {
dispatchReceiver = irGet(variable)
putValueArgument(0, irInt(index))
}
val argument = irAs(untypedArgument, type) // Note: this cast always succeeds.
addArgument(argument, type, variadic = true, parameter = null)
}
}
}
}
private fun KotlinToCCallBuilder.unwrapVariadicArguments(
elements: List<IrVarargElement>
): List<IrExpression> = elements.flatMap {
when (it) {
is IrExpression -> listOf(it)
is IrSpreadElement -> {
val expression = it.expression
if (expression is IrCall && expression.symbol == symbols.arrayOf) {
handleArgumentForVarargParameter(expression.getValueArgument(0)) { _, elements ->
unwrapVariadicArguments(elements)
}
} else {
stubs.reportError(it, "When calling variadic " +
(if (isObjCMethod) "Objective-C methods " else "C functions ") +
"spread operator is supported only for *arrayOf(...)")
}
}
else -> stubs.throwCompilerError(it, "unexpected IrVarargElement")
}
}
private fun <R> KotlinToCCallBuilder.handleArgumentForVarargParameter(
argument: IrExpression?,
block: (variable: IrVariable?, elements: List<IrVarargElement>) -> R
): R = when (argument) {
null -> block(null, emptyList())
is IrVararg -> block(null, argument.elements)
is IrGetValue -> {
/* This is possible when using named arguments with reordering, i.e.
*
* foo(second = *arrayOf(...), first = ...)
*
* psi2ir generates as
*
* val secondTmp = *arrayOf(...)
* val firstTmp = ...
* foo(firstTmp, secondTmp)
*
*
**/
val variable = argument.symbol.owner
if (variable is IrVariable && variable.origin == IrDeclarationOrigin.IR_TEMPORARY_VARIABLE && !variable.isVar) {
val initializer = variable.initializer
if (initializer is IrVararg) {
block(variable, initializer.elements)
} else {
stubs.throwCompilerError(initializer, "unexpected initializer")
}
} else if (variable is IrValueParameter && FunctionReferenceLowering.isLoweredFunctionReference(variable)) {
val location = variable.parent // Parameter itself has incorrect location.
val kind = if (this.isObjCMethod) "Objective-C methods" else "C functions"
stubs.reportError(location, "callable references to variadic $kind are not supported")
} else {
stubs.throwCompilerError(variable, "unexpected value declaration")
}
}
else -> stubs.throwCompilerError(argument, "unexpected vararg")
}
private fun KotlinToCCallBuilder.emitCBridge() {
val cLines = mutableListOf<String>()
cLines += "${bridgeBuilder.buildCSignature(cBridgeName)} {"
cLines += cBridgeBodyLines
cLines += "}"
stubs.addC(cLines)
}
private fun KotlinToCCallBuilder.buildCall(
targetFunctionName: String,
returnValuePassing: ValueReturning
): IrExpression = with(returnValuePassing) {
returnValue(cCallBuilder.build(targetFunctionName))
}
internal sealed class ObjCCallReceiver {
class Regular(val rawPtr: IrExpression) : ObjCCallReceiver()
class Retained(val rawPtr: IrExpression) : ObjCCallReceiver()
}
internal fun KotlinStubs.generateObjCCall(
builder: IrBuilderWithScope,
method: IrSimpleFunction,
isStret: Boolean,
selector: String,
call: IrFunctionAccessExpression,
superQualifier: IrClassSymbol?,
receiver: ObjCCallReceiver,
arguments: List<IrExpression?>
) = builder.irBlock {
val resolved = method.resolveFakeOverride(allowAbstract = true)?: method
val exceptionMode = ForeignExceptionMode.byValue(
resolved.module.konanLibrary?.manifestProperties
?.getProperty(ForeignExceptionMode.manifestKey)
)
val callBuilder = KotlinToCCallBuilder(builder, this@generateObjCCall, isObjCMethod = true, exceptionMode)
val superClass = irTemporaryVar(
superQualifier?.let { getObjCClass(symbols, it) } ?: irNullNativePtr(symbols)
)
val messenger = irCall(if (isStret) {
symbols.interopGetMessengerStret
} else {
symbols.interopGetMessenger
}.owner).apply {
putValueArgument(0, irGet(superClass)) // TODO: check superClass statically.
}
val targetPtrParameter = callBuilder.passThroughBridge(
messenger,
symbols.interopCPointer.typeWithStarProjections,
CTypes.voidPtr
).name
val targetFunctionName = "targetPtr"
val preparedReceiver = if (method.consumesReceiver()) {
when (receiver) {
is ObjCCallReceiver.Regular -> irCall(symbols.interopObjCRetain.owner).apply {
putValueArgument(0, receiver.rawPtr)
}
is ObjCCallReceiver.Retained -> receiver.rawPtr
}
} else {
when (receiver) {
is ObjCCallReceiver.Regular -> receiver.rawPtr
is ObjCCallReceiver.Retained -> {
// Note: shall not happen: Retained is used only for alloc result currently,
// which is used only as receiver for init methods, which are always receiver-consuming.
// Can't even add a test for the code below.
val rawPtrVar = scope.createTemporaryVariable(receiver.rawPtr)
callBuilder.bridgeCallBuilder.prepare += rawPtrVar
callBuilder.bridgeCallBuilder.cleanup += {
irCall(symbols.interopObjCRelease).apply {
putValueArgument(0, irGet(rawPtrVar)) // Balance retained pointer.
}
}
irGet(rawPtrVar)
}
}
}
val receiverOrSuper = if (superQualifier != null) {
irCall(symbols.interopCreateObjCSuperStruct.owner).apply {
putValueArgument(0, preparedReceiver)
putValueArgument(1, irGet(superClass))
}
} else {
preparedReceiver
}
callBuilder.cCallBuilder.arguments += callBuilder.passThroughBridge(
receiverOrSuper, symbols.nativePtrType, CTypes.voidPtr).name
callBuilder.cFunctionBuilder.addParameter(CTypes.voidPtr)
callBuilder.cCallBuilder.arguments += "@selector($selector)"
callBuilder.cFunctionBuilder.addParameter(CTypes.voidPtr)
callBuilder.addArguments(arguments, method)
val returnValuePassing =
mapReturnType(method.returnType, TypeLocation.FunctionCallResult(call), signature = method)
val result = callBuilder.buildCall(targetFunctionName, returnValuePassing)
val targetFunctionVariable = CVariable(CTypes.pointer(callBuilder.cFunctionBuilder.getType()), targetFunctionName)
callBuilder.cBridgeBodyLines.add(0, "$targetFunctionVariable = $targetPtrParameter;")
callBuilder.emitCBridge()
+result
}
internal fun IrBuilderWithScope.getObjCClass(symbols: KonanSymbols, symbol: IrClassSymbol): IrExpression {
val classDescriptor = symbol.descriptor
assert(!classDescriptor.isObjCMetaClass())
return irCall(symbols.interopGetObjCClass, symbols.nativePtrType, listOf(symbol.typeWithStarProjections))
}
private fun IrBuilderWithScope.irNullNativePtr(symbols: KonanSymbols) = irCall(symbols.getNativeNullPtr.owner)
private class CCallbackBuilder(
val stubs: KotlinStubs,
val location: IrElement,
val isObjCMethod: Boolean
) {
val irBuiltIns: IrBuiltIns get() = stubs.irBuiltIns
val symbols: KonanSymbols get() = stubs.symbols
private val cBridgeName = stubs.getUniqueCName("knbridge")
fun buildCBridgeCall(): String = cBridgeCallBuilder.build(cBridgeName)
fun buildCBridge(): String = bridgeBuilder.buildCSignature(cBridgeName)
val bridgeBuilder = KotlinCBridgeBuilder(location.startOffset, location.endOffset, cBridgeName, stubs, isKotlinToC = false)
val kotlinCallBuilder = KotlinCallBuilder(bridgeBuilder.kotlinIrBuilder, symbols)
val kotlinBridgeStatements = mutableListOf<IrStatement>()
val cBridgeCallBuilder = CCallBuilder()
val cBodyLines = mutableListOf<String>()
val cFunctionBuilder = CFunctionBuilder()
}
private fun CCallbackBuilder.passThroughBridge(
cBridgeArgument: String,
cBridgeParameterType: CType,
kotlinBridgeParameterType: IrType
): IrValueParameter {
cBridgeCallBuilder.arguments += cBridgeArgument
return bridgeBuilder.addParameter(kotlinBridgeParameterType, cBridgeParameterType).first
}
private fun CCallbackBuilder.addParameter(it: IrValueParameter, functionParameter: IrValueParameter) {
val typeLocation = if (isObjCMethod) {
TypeLocation.ObjCMethodParameter(it.index, functionParameter)
} else {
TypeLocation.FunctionPointerParameter(cFunctionBuilder.numberOfParameters, location)
}
if (functionParameter.isVararg) {
stubs.reportError(typeLocation.element, if (isObjCMethod) {
"overriding variadic Objective-C methods is not supported"
} else {
"variadic function pointers are not supported"
})
}
val valuePassing = stubs.mapFunctionParameterType(
it.type,
retained = it.isConsumed(),
variadic = false,
location = typeLocation
)
val kotlinArgument = with(valuePassing) { receiveValue() }
kotlinCallBuilder.arguments += kotlinArgument
}
private fun CCallbackBuilder.build(function: IrSimpleFunction, signature: IrSimpleFunction): String {
val typeLocation = if (isObjCMethod) {
TypeLocation.ObjCMethodReturnValue(function)
} else {
TypeLocation.FunctionPointerReturnValue(location)
}
val valueReturning = stubs.mapReturnType(signature.returnType, typeLocation, signature)
buildValueReturn(function, valueReturning)
return buildCFunction()
}
private fun CCallbackBuilder.buildValueReturn(function: IrSimpleFunction, valueReturning: ValueReturning) {
val kotlinCall = kotlinCallBuilder.build(function)
with(valueReturning) {
returnValue(kotlinCall)
}
val kotlinBridge = bridgeBuilder.buildKotlinBridge()
kotlinBridge.body = bridgeBuilder.kotlinIrBuilder.irBlockBody {
kotlinBridgeStatements.forEach { +it }
}
stubs.addKotlin(kotlinBridge)
stubs.addC(listOf("${buildCBridge()};"))
}
private fun CCallbackBuilder.buildCFunction(): String {
val result = stubs.getUniqueCName("kncfun")
val cLines = mutableListOf<String>()
cLines += "${cFunctionBuilder.buildSignature(result)} {"
cLines += cBodyLines
cLines += "}"
stubs.addC(cLines)
return result
}
private fun KotlinStubs.generateCFunction(
function: IrSimpleFunction,
signature: IrSimpleFunction,
isObjCMethod: Boolean,
location: IrElement
): String {
val callbackBuilder = CCallbackBuilder(this, location, isObjCMethod)
if (isObjCMethod) {
val receiver = signature.dispatchReceiverParameter!!
assert(isObjCReferenceType(receiver.type))
val valuePassing = ObjCReferenceValuePassing(symbols, receiver.type, retained = signature.consumesReceiver())
val kotlinArgument = with(valuePassing) { callbackBuilder.receiveValue() }
callbackBuilder.kotlinCallBuilder.arguments += kotlinArgument
// Selector is ignored:
with(TrivialValuePassing(symbols.nativePtrType, CTypes.voidPtr)) { callbackBuilder.receiveValue() }
} else {
require(signature.dispatchReceiverParameter == null)
}
signature.extensionReceiverParameter?.let { callbackBuilder.addParameter(it, function.extensionReceiverParameter!!) }
signature.valueParameters.forEach {
callbackBuilder.addParameter(it, function.valueParameters[it.index])
}
return callbackBuilder.build(function, signature)
}
internal fun KotlinStubs.generateCFunctionPointer(
function: IrSimpleFunction,
signature: IrSimpleFunction,
expression: IrExpression
): IrExpression {
val fakeFunction = generateCFunctionAndFakeKotlinExternalFunction(
function,
signature,
isObjCMethod = false,
location = expression
)
addKotlin(fakeFunction)
return IrFunctionReferenceImpl(
expression.startOffset,
expression.endOffset,
expression.type,
fakeFunction.symbol,
typeArgumentsCount = 0,
reflectionTarget = null
)
}
internal fun KotlinStubs.generateCFunctionAndFakeKotlinExternalFunction(
function: IrSimpleFunction,
signature: IrSimpleFunction,
isObjCMethod: Boolean,
location: IrElement
): IrSimpleFunction {
val cFunction = generateCFunction(function, signature, isObjCMethod, location)
return createFakeKotlinExternalFunction(signature, cFunction, isObjCMethod)
}
private fun KotlinStubs.createFakeKotlinExternalFunction(
signature: IrSimpleFunction,
cFunctionName: String,
isObjCMethod: Boolean
): IrSimpleFunction {
val bridgeDescriptor = WrappedSimpleFunctionDescriptor()
val bridge = IrFunctionImpl(
UNDEFINED_OFFSET,
UNDEFINED_OFFSET,
IrDeclarationOrigin.DEFINED,
IrSimpleFunctionSymbolImpl(bridgeDescriptor),
Name.identifier(cFunctionName),
DescriptorVisibilities.PRIVATE,
Modality.FINAL,
signature.returnType,
isInline = false,
isExternal = true,
isTailrec = false,
isSuspend = false,
isExpect = false,
isFakeOverride = false,
isOperator = false,
isInfix = false
)
bridgeDescriptor.bind(bridge)
bridge.annotations += buildSimpleAnnotation(irBuiltIns, UNDEFINED_OFFSET, UNDEFINED_OFFSET,
symbols.symbolName.owner, cFunctionName)
if (isObjCMethod) {
val methodInfo = signature.getObjCMethodInfo()!!
bridge.annotations += buildSimpleAnnotation(irBuiltIns, UNDEFINED_OFFSET, UNDEFINED_OFFSET,
symbols.objCMethodImp.owner, methodInfo.selector, methodInfo.encoding)
}
return bridge
}
private val cCall = RuntimeNames.cCall
private fun IrType.isUnsigned(unsignedType: UnsignedType) = this is IrSimpleType && !this.hasQuestionMark &&
(this.classifier.owner as? IrClass)?.classId == unsignedType.classId
private fun IrType.isUByte() = this.isUnsigned(UnsignedType.UBYTE)
private fun IrType.isUShort() = this.isUnsigned(UnsignedType.USHORT)
private fun IrType.isUInt() = this.isUnsigned(UnsignedType.UINT)
private fun IrType.isULong() = this.isUnsigned(UnsignedType.ULONG)
internal fun IrType.isCEnumType(): Boolean {
val simpleType = this as? IrSimpleType ?: return false
if (simpleType.hasQuestionMark) return false
val enumClass = simpleType.classifier.owner as? IrClass ?: return false
if (!enumClass.isEnumClass) return false
return enumClass.superTypes
.any { (it.classifierOrNull?.owner as? IrClass)?.fqNameForIrSerialization == FqName("kotlinx.cinterop.CEnum") }
}
// Make sure external stubs always get proper annotaions.
private fun IrDeclaration.hasCCallAnnotation(name: String): Boolean =
this.annotations.hasAnnotation(cCall.child(Name.identifier(name)))
// LazyIr doesn't pass annotations from descriptor to IrValueParameter.
|| this.descriptor.annotations.hasAnnotation(cCall.child(Name.identifier(name)))
private fun IrValueParameter.isWCStringParameter() = hasCCallAnnotation("WCString")
private fun IrValueParameter.isCStringParameter() = hasCCallAnnotation("CString")
private fun IrValueParameter.isConsumed() = hasCCallAnnotation("Consumed")
private fun IrSimpleFunction.consumesReceiver() = hasCCallAnnotation("ConsumesReceiver")
private fun IrSimpleFunction.returnsRetained() = hasCCallAnnotation("ReturnsRetained")
private fun getStructSpelling(kotlinClass: IrClass): String? =
kotlinClass.getAnnotationArgumentValue(FqName("kotlinx.cinterop.internal.CStruct"), "spelling")
private fun getCStructType(kotlinClass: IrClass): CType? =
getStructSpelling(kotlinClass)?.let { CTypes.simple(it) }
private fun KotlinStubs.getNamedCStructType(kotlinClass: IrClass): CType? {
val cStructType = getCStructType(kotlinClass) ?: return null
val name = getUniqueCName("struct")
addC(listOf("typedef ${cStructType.render(name)};"))
return CTypes.simple(name)
}
// TODO: rework Boolean support.
// TODO: What should be used on watchOS?
private fun cBoolType(target: KonanTarget): CType? = when (target.family) {
Family.IOS, Family.TVOS, Family.WATCHOS -> CTypes.C99Bool
else -> CTypes.signedChar
}
private fun KotlinToCCallBuilder.mapCalleeFunctionParameter(
type: IrType,
variadic: Boolean,
parameter: IrValueParameter?,
argument: IrExpression
): KotlinToCArgumentPassing {
val classifier = type.classifierOrNull
return when {
classifier == symbols.interopCValues || // Note: this should not be accepted, but is required for compatibility
classifier == symbols.interopCValuesRef -> CValuesRefArgumentPassing
classifier == symbols.string && (variadic || parameter?.isCStringParameter() == true) -> {
if (variadic && isObjCMethod) {
stubs.reportError(argument, "Passing String as variadic Objective-C argument is ambiguous; " +
"cast it to NSString or pass with '.cstr' as C string")
// TODO: consider reporting a warning for C functions.
}
CStringArgumentPassing()
}
classifier == symbols.string && parameter?.isWCStringParameter() == true ->
WCStringArgumentPassing()
else -> stubs.mapFunctionParameterType(
type,
retained = parameter?.isConsumed() ?: false,
variadic = variadic,
location = TypeLocation.FunctionArgument(argument)
)
}
}
private fun KotlinStubs.mapFunctionParameterType(
type: IrType,
retained: Boolean,
variadic: Boolean,
location: TypeLocation
): ArgumentPassing = when {
type.isUnit() && !variadic -> IgnoredUnitArgumentPassing
else -> mapType(type, retained = retained, variadic = variadic, location = location)
}
private sealed class TypeLocation(val element: IrElement) {
class FunctionArgument(val argument: IrExpression) : TypeLocation(argument)
class FunctionCallResult(val call: IrFunctionAccessExpression) : TypeLocation(call)
class FunctionPointerParameter(val index: Int, element: IrElement) : TypeLocation(element)
class FunctionPointerReturnValue(element: IrElement) : TypeLocation(element)
class ObjCMethodParameter(val index: Int, element: IrElement) : TypeLocation(element)
class ObjCMethodReturnValue(element: IrElement) : TypeLocation(element)
class BlockParameter(val index: Int, val blockLocation: TypeLocation) : TypeLocation(blockLocation.element)
class BlockReturnValue(val blockLocation: TypeLocation) : TypeLocation(blockLocation.element)
}
private fun KotlinStubs.mapReturnType(
type: IrType,
location: TypeLocation,
signature: IrSimpleFunction?
): ValueReturning = when {
type.isUnit() -> VoidReturning
else -> mapType(type, retained = signature?.returnsRetained() ?: false, variadic = false, location = location)
}
private fun KotlinStubs.mapBlockType(
type: IrType,
retained: Boolean,
location: TypeLocation
): ObjCBlockPointerValuePassing {
type as IrSimpleType
require(type.classifier == symbols.functionN(type.arguments.size - 1))
val returnTypeArgument = type.arguments.last()
val valueReturning = when (returnTypeArgument) {
is IrTypeProjection -> if (returnTypeArgument.variance == Variance.INVARIANT) {
mapReturnType(returnTypeArgument.type, TypeLocation.BlockReturnValue(location), null)
} else {
reportUnsupportedType("${returnTypeArgument.variance.label}-variance of return type", type, location)
}
is IrStarProjection -> reportUnsupportedType("* as return type", type, location)
else -> error(returnTypeArgument)
}
val parameterValuePassings = type.arguments.dropLast(1).mapIndexed { index, argument ->
when (argument) {
is IrTypeProjection -> if (argument.variance == Variance.INVARIANT) {
mapType(
argument.type,
retained = false,
variadic = false,
location = TypeLocation.BlockParameter(index, location)
)
} else {
reportUnsupportedType("${argument.variance.label}-variance of ${index + 1} parameter type", type, location)
}
is IrStarProjection -> reportUnsupportedType("* as ${index + 1} parameter type", type, location)
else -> error(argument)
}
}
return ObjCBlockPointerValuePassing(
this,
location.element,
type,
valueReturning,
parameterValuePassings,
retained
)
}
private fun KotlinStubs.mapType(type: IrType, retained: Boolean, variadic: Boolean, location: TypeLocation): ValuePassing =
mapType(type, retained, variadic, location, { reportUnsupportedType(it, type, location) })
private fun IrType.isTypeOfNullLiteral(): Boolean = this is IrSimpleType && hasQuestionMark
&& classifier.isClassWithFqName(StandardNames.FqNames.nothing)
internal fun IrType.isVector(): Boolean {
if (this is IrSimpleType && !this.hasQuestionMark) {
return classifier.isClassWithFqName(KonanFqNames.Vector128.toUnsafe())
}
return false
}
private fun KotlinStubs.mapType(
type: IrType,
retained: Boolean,
variadic: Boolean,
typeLocation: TypeLocation,
reportUnsupportedType: (String) -> Nothing
): ValuePassing = when {
type.isBoolean() -> BooleanValuePassing(
cBoolType(target) ?: reportUnsupportedType("unavailable on target platform"),
irBuiltIns
)
type.isByte() -> TrivialValuePassing(irBuiltIns.byteType, CTypes.signedChar)
type.isShort() -> TrivialValuePassing(irBuiltIns.shortType, CTypes.short)
type.isInt() -> TrivialValuePassing(irBuiltIns.intType, CTypes.int)
type.isLong() -> TrivialValuePassing(irBuiltIns.longType, CTypes.longLong)
type.isFloat() -> TrivialValuePassing(irBuiltIns.floatType, CTypes.float)
type.isDouble() -> TrivialValuePassing(irBuiltIns.doubleType, CTypes.double)
type.classifierOrNull == symbols.interopCPointer -> TrivialValuePassing(type, CTypes.voidPtr)
type.isTypeOfNullLiteral() && variadic -> TrivialValuePassing(symbols.interopCPointer.typeWithStarProjections.makeNullable(), CTypes.voidPtr)
type.isUByte() -> UnsignedValuePassing(type, CTypes.signedChar, CTypes.unsignedChar)
type.isUShort() -> UnsignedValuePassing(type, CTypes.short, CTypes.unsignedShort)
type.isUInt() -> UnsignedValuePassing(type, CTypes.int, CTypes.unsignedInt)
type.isULong() -> UnsignedValuePassing(type, CTypes.longLong, CTypes.unsignedLongLong)
type.isVector() -> TrivialValuePassing(type, CTypes.vector128)
type.isCEnumType() -> {
val enumClass = type.getClass()!!
val value = enumClass.declarations
.filterIsInstance<IrProperty>()
.single { it.name.asString() == "value" }
CEnumValuePassing(
enumClass,
value,
mapType(value.getter!!.returnType, retained, variadic, typeLocation) as SimpleValuePassing
)
}
type.classifierOrNull == symbols.interopCValue -> if (type.isNullable()) {
reportUnsupportedType("must not be nullable")
} else {
val kotlinClass = (type as IrSimpleType).arguments.singleOrNull()?.typeOrNull?.getClass()
?: reportUnsupportedType("must be parameterized with concrete class")
StructValuePassing(kotlinClass, getNamedCStructType(kotlinClass)
?: reportUnsupportedType("not a structure or too complex"))
}
type.classOrNull?.isSubtypeOfClass(symbols.nativePointed) == true -> {
TrivialValuePassing(type, CTypes.voidPtr)
}
type.isFunction() -> if (variadic){
reportUnsupportedType("not supported as variadic argument")
} else {
mapBlockType(type, retained = retained, location = typeLocation)
}
isObjCReferenceType(type) -> ObjCReferenceValuePassing(symbols, type, retained = retained)
else -> reportUnsupportedType("doesn't correspond to any C type")
}
private fun KotlinStubs.isObjCReferenceType(type: IrType): Boolean {
if (!target.family.isAppleFamily) return false
// Handle the same types as produced by [objCPointerMirror] in Interop/StubGenerator/.../Mappings.kt.
if (type.isObjCObjectType()) return true
val descriptor = type.classifierOrNull?.descriptor ?: return false
val builtIns = irBuiltIns.builtIns
return when (descriptor) {
builtIns.any,
builtIns.string,
builtIns.list, builtIns.mutableList,
builtIns.set,
builtIns.map -> true
else -> false
}
}
private class CExpression(val expression: String, val type: CType)
private interface KotlinToCArgumentPassing {
fun KotlinToCCallBuilder.passValue(expression: IrExpression): CExpression?
}
private interface ValueReturning {
val cType: CType
fun KotlinToCCallBuilder.returnValue(expression: String): IrExpression
fun CCallbackBuilder.returnValue(expression: IrExpression)
}
private interface ArgumentPassing : KotlinToCArgumentPassing {
fun CCallbackBuilder.receiveValue(): IrExpression
}
private interface ValuePassing : ArgumentPassing, ValueReturning
private abstract class SimpleValuePassing : ValuePassing {
abstract val kotlinBridgeType: IrType
abstract val cBridgeType: CType
override abstract val cType: CType
open val callbackParameterCType get() = cType
abstract fun IrBuilderWithScope.kotlinToBridged(expression: IrExpression): IrExpression
open fun IrBuilderWithScope.kotlinCallbackResultToBridged(expression: IrExpression): IrExpression =
kotlinToBridged(expression)
abstract fun IrBuilderWithScope.bridgedToKotlin(expression: IrExpression, symbols: KonanSymbols): IrExpression
abstract fun bridgedToC(expression: String): String
abstract fun cToBridged(expression: String): String
override fun KotlinToCCallBuilder.passValue(expression: IrExpression): CExpression {
val bridgeArgument = irBuilder.kotlinToBridged(expression)
val cBridgeValue = passThroughBridge(bridgeArgument, kotlinBridgeType, cBridgeType).name
return CExpression(bridgedToC(cBridgeValue), cType)
}
override fun KotlinToCCallBuilder.returnValue(expression: String): IrExpression {
cFunctionBuilder.setReturnType(cType)
bridgeBuilder.setReturnType(kotlinBridgeType, cBridgeType)
cBridgeBodyLines.add("return ${cToBridged(expression)};")
val kotlinBridgeCall = buildKotlinBridgeCall()
return irBuilder.bridgedToKotlin(kotlinBridgeCall, symbols)
}
override fun CCallbackBuilder.receiveValue(): IrExpression {
val cParameter = cFunctionBuilder.addParameter(callbackParameterCType)
val cBridgeArgument = cToBridged(cParameter.name)
val kotlinParameter = passThroughBridge(cBridgeArgument, cBridgeType, kotlinBridgeType)
return with(bridgeBuilder.kotlinIrBuilder) {
bridgedToKotlin(irGet(kotlinParameter), symbols)
}
}
override fun CCallbackBuilder.returnValue(expression: IrExpression) {
cFunctionBuilder.setReturnType(cType)
bridgeBuilder.setReturnType(kotlinBridgeType, cBridgeType)
kotlinBridgeStatements += with(bridgeBuilder.kotlinIrBuilder) {
irReturn(kotlinCallbackResultToBridged(expression))
}
val cBridgeCall = buildCBridgeCall()
cBodyLines += "return ${bridgedToC(cBridgeCall)};"
}
}
private class TrivialValuePassing(val kotlinType: IrType, override val cType: CType) : SimpleValuePassing() {
override val kotlinBridgeType: IrType
get() = kotlinType
override val cBridgeType: CType
get() = cType
override fun IrBuilderWithScope.kotlinToBridged(expression: IrExpression): IrExpression = expression
override fun IrBuilderWithScope.bridgedToKotlin(expression: IrExpression, symbols: KonanSymbols): IrExpression = expression
override fun bridgedToC(expression: String): String = expression
override fun cToBridged(expression: String): String = expression
}
private class UnsignedValuePassing(val kotlinType: IrType, val cSignedType: CType, override val cType: CType) : SimpleValuePassing() {
override val kotlinBridgeType: IrType
get() = kotlinType
override val cBridgeType: CType
get() = cSignedType
override fun IrBuilderWithScope.kotlinToBridged(expression: IrExpression): IrExpression = expression
override fun IrBuilderWithScope.bridgedToKotlin(expression: IrExpression, symbols: KonanSymbols): IrExpression = expression
override fun bridgedToC(expression: String): String = cType.cast(expression)
override fun cToBridged(expression: String): String = cBridgeType.cast(expression)
}
private class BooleanValuePassing(override val cType: CType, private val irBuiltIns: IrBuiltIns) : SimpleValuePassing() {
override val cBridgeType: CType get() = CTypes.signedChar
override val kotlinBridgeType: IrType get() = irBuiltIns.byteType
override fun IrBuilderWithScope.kotlinToBridged(expression: IrExpression): IrExpression = irIfThenElse(
irBuiltIns.byteType,
condition = expression,
thenPart = IrConstImpl.byte(startOffset, endOffset, irBuiltIns.byteType, 1),
elsePart = IrConstImpl.byte(startOffset, endOffset, irBuiltIns.byteType, 0)
)
override fun IrBuilderWithScope.bridgedToKotlin(
expression: IrExpression,
symbols: KonanSymbols
): IrExpression = irNot(irCall(symbols.areEqualByValue[PrimitiveBinaryType.BYTE]!!.owner).apply {
putValueArgument(0, expression)
putValueArgument(1, IrConstImpl.byte(startOffset, endOffset, irBuiltIns.byteType, 0))
})
override fun bridgedToC(expression: String): String = cType.cast(expression)
override fun cToBridged(expression: String): String = cBridgeType.cast(expression)
}
private class StructValuePassing(private val kotlinClass: IrClass, override val cType: CType) : ValuePassing {
override fun KotlinToCCallBuilder.passValue(expression: IrExpression): CExpression {
val cBridgeValue = passThroughBridge(
cValuesRefToPointer(expression),
symbols.interopCPointer.typeWithStarProjections,
CTypes.pointer(cType)
).name
return CExpression("*$cBridgeValue", cType)
}
override fun KotlinToCCallBuilder.returnValue(expression: String): IrExpression = with(irBuilder) {
cFunctionBuilder.setReturnType(cType)
bridgeBuilder.setReturnType(context.irBuiltIns.unitType, CTypes.void)
val kotlinPointed = scope.createTemporaryVariable(irCall(symbols.interopAllocType.owner).apply {
extensionReceiver = bridgeCallBuilder.getMemScope()
putValueArgument(0, getTypeObject())
})
bridgeCallBuilder.prepare += kotlinPointed
val cPointer = passThroughBridge(irGet(kotlinPointed), kotlinPointedType, CTypes.pointer(cType))
cBridgeBodyLines += "*${cPointer.name} = $expression;"
buildKotlinBridgeCall {
irBlock {
at(it)
+it
+readCValue(irGet(kotlinPointed), symbols)
}
}
}
override fun CCallbackBuilder.receiveValue(): IrExpression = with(bridgeBuilder.kotlinIrBuilder) {
val cParameter = cFunctionBuilder.addParameter(cType)
val kotlinPointed = passThroughBridge("&${cParameter.name}", CTypes.voidPtr, kotlinPointedType)
readCValue(irGet(kotlinPointed), symbols)
}
private fun IrBuilderWithScope.readCValue(kotlinPointed: IrExpression, symbols: KonanSymbols): IrExpression =
irCall(symbols.interopCValueRead.owner).apply {
extensionReceiver = kotlinPointed
putValueArgument(0, getTypeObject())
}
override fun CCallbackBuilder.returnValue(expression: IrExpression) = with(bridgeBuilder.kotlinIrBuilder) {
bridgeBuilder.setReturnType(irBuiltIns.unitType, CTypes.void)
cFunctionBuilder.setReturnType(cType)
val result = "callbackResult"
val cReturnValue = CVariable(cType, result)
cBodyLines += "$cReturnValue;"
val kotlinPtr = passThroughBridge("&$result", CTypes.voidPtr, symbols.nativePtrType)
kotlinBridgeStatements += irCall(symbols.interopCValueWrite.owner).apply {
extensionReceiver = expression
putValueArgument(0, irGet(kotlinPtr))
}
val cBridgeCall = buildCBridgeCall()
cBodyLines += "$cBridgeCall;"
cBodyLines += "return $result;"
}
private val kotlinPointedType: IrType get() = kotlinClass.defaultType
private fun IrBuilderWithScope.getTypeObject() =
irGetObject(
kotlinClass.declarations.filterIsInstance<IrClass>()
.single { it.isCompanion }.symbol
)
}
private class CEnumValuePassing(
val enumClass: IrClass,
val value: IrProperty,
val baseValuePassing: SimpleValuePassing
) : SimpleValuePassing() {
override val kotlinBridgeType: IrType
get() = baseValuePassing.kotlinBridgeType
override val cBridgeType: CType
get() = baseValuePassing.cBridgeType
override val cType: CType
get() = baseValuePassing.cType
override fun IrBuilderWithScope.kotlinToBridged(expression: IrExpression): IrExpression {
val value = irCall(value.getter!!).apply {
dispatchReceiver = expression
}
return with(baseValuePassing) { kotlinToBridged(value) }
}
override fun IrBuilderWithScope.bridgedToKotlin(expression: IrExpression, symbols: KonanSymbols): IrExpression {
val companionClass = enumClass.declarations.filterIsInstance<IrClass>().single { it.isCompanion }
val byValue = companionClass.simpleFunctions().single { it.name.asString() == "byValue" }
return irCall(byValue).apply {
dispatchReceiver = irGetObject(companionClass.symbol)
putValueArgument(0, expression)
}
}
override fun bridgedToC(expression: String): String = with(baseValuePassing) { bridgedToC(expression) }
override fun cToBridged(expression: String): String = with(baseValuePassing) { cToBridged(expression) }
}
private class ObjCReferenceValuePassing(
private val symbols: KonanSymbols,
private val type: IrType,
private val retained: Boolean
) : SimpleValuePassing() {
override val kotlinBridgeType: IrType
get() = symbols.nativePtrType
override val cBridgeType: CType
get() = CTypes.voidPtr
override val cType: CType
get() = CTypes.voidPtr
override fun IrBuilderWithScope.kotlinToBridged(expression: IrExpression): IrExpression {
val ptr = irCall(symbols.interopObjCObjectRawValueGetter.owner).apply {
extensionReceiver = expression
}
return if (retained) {
irCall(symbols.interopObjCRetain).apply {
putValueArgument(0, ptr)
}
} else {
ptr
}
}
override fun IrBuilderWithScope.kotlinCallbackResultToBridged(expression: IrExpression): IrExpression {
if (retained) return kotlinToBridged(expression) // Optimization.
// Kotlin code may loose the ownership on this pointer after returning from the bridge,
// so retain the pointer and autorelease it:
return irCall(symbols.interopObjcRetainAutoreleaseReturnValue.owner).apply {
putValueArgument(0, kotlinToBridged(expression))
}
// TODO: optimize by using specialized Kotlin-to-ObjC converter.
}
override fun IrBuilderWithScope.bridgedToKotlin(expression: IrExpression, symbols: KonanSymbols): IrExpression =
convertPossiblyRetainedObjCPointer(symbols, retained, expression) {
irCall(symbols.interopInterpretObjCPointerOrNull, listOf(type)).apply {
putValueArgument(0, it)
}
}
override fun bridgedToC(expression: String): String = expression
override fun cToBridged(expression: String): String = expression
}
private fun IrBuilderWithScope.convertPossiblyRetainedObjCPointer(
symbols: KonanSymbols,
retained: Boolean,
pointer: IrExpression,
convert: (IrExpression) -> IrExpression
): IrExpression = if (retained) {
irBlock(startOffset, endOffset) {
val ptrVar = irTemporary(pointer)
val resultVar = irTemporary(convert(irGet(ptrVar)))
+irCall(symbols.interopObjCRelease.owner).apply {
putValueArgument(0, irGet(ptrVar))
}
+irGet(resultVar)
}
} else {
convert(pointer)
}
private class ObjCBlockPointerValuePassing(
val stubs: KotlinStubs,
private val location: IrElement,
private val functionType: IrSimpleType,
private val valueReturning: ValueReturning,
private val parameterValuePassings: List<ValuePassing>,
private val retained: Boolean
) : SimpleValuePassing() {
val symbols get() = stubs.symbols
override val kotlinBridgeType: IrType
get() = symbols.nativePtrType
override val cBridgeType: CType
get() = CTypes.id
override val cType: CType
get() = CTypes.id
/**
* Callback can receive stack-allocated block. Using block type for parameter and passing it as `id` to the bridge
* makes Objective-C compiler generate proper copying to heap.
*/
override val callbackParameterCType: CType
get() = CTypes.blockPointer(
CTypes.function(
valueReturning.cType,
parameterValuePassings.map { it.cType },
variadic = false
))
override fun IrBuilderWithScope.kotlinToBridged(expression: IrExpression): IrExpression =
irCall(symbols.interopCreateKotlinObjectHolder.owner).apply {
putValueArgument(0, expression)
}
override fun IrBuilderWithScope.bridgedToKotlin(expression: IrExpression, symbols: KonanSymbols): IrExpression =
irLetS(expression) { blockPointerVarSymbol ->
val blockPointerVar = blockPointerVarSymbol.owner
irIfThenElse(
functionType.makeNullable(),
condition = irCall(symbols.areEqualByValue.getValue(PrimitiveBinaryType.POINTER).owner).apply {
putValueArgument(0, irGet(blockPointerVar))
putValueArgument(1, irNullNativePtr(symbols))
},
thenPart = irNull(),
elsePart = convertPossiblyRetainedObjCPointer(symbols, retained, irGet(blockPointerVar)) {
createKotlinFunctionObject(it)
}
)
}
private object OBJC_BLOCK_FUNCTION_IMPL : IrDeclarationOriginImpl("OBJC_BLOCK_FUNCTION_IMPL")
private fun IrBuilderWithScope.createKotlinFunctionObject(blockPointer: IrExpression): IrExpression {
val constructor = generateKotlinFunctionClass()
return irCall(constructor).apply {
putValueArgument(0, blockPointer)
}
}
private fun IrBuilderWithScope.generateKotlinFunctionClass(): IrConstructor {
val symbols = stubs.symbols
val classDescriptor = WrappedClassDescriptor()
val irClass = IrClassImpl(
startOffset, endOffset,
OBJC_BLOCK_FUNCTION_IMPL, IrClassSymbolImpl(classDescriptor),
Name.identifier(stubs.getUniqueKotlinFunctionReferenceClassName("BlockFunctionImpl")),
ClassKind.CLASS, DescriptorVisibilities.PRIVATE, Modality.FINAL,
isCompanion = false, isInner = false, isData = false, isExternal = false,
isInline = false, isExpect = false, isFun = false
)
classDescriptor.bind(irClass)
irClass.createParameterDeclarations()
irClass.superTypes += stubs.irBuiltIns.anyType
irClass.superTypes += functionType.makeNotNull()
val blockHolderField = createField(
startOffset, endOffset,
OBJC_BLOCK_FUNCTION_IMPL,
stubs.irBuiltIns.anyType,
Name.identifier("blockHolder"),
isMutable = false, owner = irClass
)
val constructorDescriptor = WrappedClassConstructorDescriptor()
val constructor = IrConstructorImpl(
startOffset, endOffset,
OBJC_BLOCK_FUNCTION_IMPL,
IrConstructorSymbolImpl(constructorDescriptor),
Name.special("<init>"),
DescriptorVisibilities.PUBLIC,
irClass.defaultType,
isInline = false, isExternal = false, isPrimary = true, isExpect = false
)
constructorDescriptor.bind(constructor)
irClass.addChild(constructor)
val constructorParameterDescriptor = WrappedValueParameterDescriptor()
val constructorParameter = IrValueParameterImpl(
startOffset, endOffset,
OBJC_BLOCK_FUNCTION_IMPL,
IrValueParameterSymbolImpl(constructorParameterDescriptor),
Name.identifier("blockPointer"),
0,
symbols.nativePtrType,
varargElementType = null, isCrossinline = false, isNoinline = false
)
constructorParameterDescriptor.bind(constructorParameter)
constructor.valueParameters += constructorParameter
constructorParameter.parent = constructor
constructor.body = irBuilder(stubs.irBuiltIns, constructor.symbol).irBlockBody(startOffset, endOffset) {
+irDelegatingConstructorCall(symbols.any.owner.constructors.single())
+irSetField(irGet(irClass.thisReceiver!!), blockHolderField,
irCall(symbols.interopCreateObjCObjectHolder.owner).apply {
putValueArgument(0, irGet(constructorParameter))
})
}
val parameterCount = parameterValuePassings.size
assert(functionType.arguments.size == parameterCount + 1)
val overriddenInvokeMethod = (functionType.classifier.owner as IrClass).simpleFunctions()
.single { it.name == OperatorNameConventions.INVOKE }
val invokeMethodDescriptor = WrappedSimpleFunctionDescriptor()
val invokeMethod = IrFunctionImpl(
startOffset, endOffset,
OBJC_BLOCK_FUNCTION_IMPL,
IrSimpleFunctionSymbolImpl(invokeMethodDescriptor),
overriddenInvokeMethod.name,
DescriptorVisibilities.PUBLIC, Modality.FINAL,
returnType = functionType.arguments.last().typeOrNull!!,
isInline = false, isExternal = false, isTailrec = false, isSuspend = false, isExpect = false,
isFakeOverride = false, isOperator = false, isInfix = false
)
invokeMethodDescriptor.bind(invokeMethod)
invokeMethod.overriddenSymbols += overriddenInvokeMethod.symbol
irClass.addChild(invokeMethod)
invokeMethod.createDispatchReceiverParameter()
invokeMethod.valueParameters += (0 until parameterCount).map { index ->
val parameterDescriptor = WrappedValueParameterDescriptor()
val parameter = IrValueParameterImpl(
startOffset, endOffset,
OBJC_BLOCK_FUNCTION_IMPL,
IrValueParameterSymbolImpl(parameterDescriptor),
Name.identifier("p$index"),
index,
functionType.arguments[index].typeOrNull!!,
varargElementType = null, isCrossinline = false, isNoinline = false
)
parameterDescriptor.bind(parameter)
parameter.parent = invokeMethod
parameter
}
invokeMethod.body = irBuilder(stubs.irBuiltIns, invokeMethod.symbol).irBlockBody(startOffset, endOffset) {
val blockPointer = irCall(symbols.interopObjCObjectRawValueGetter.owner).apply {
extensionReceiver = irGetField(irGet(invokeMethod.dispatchReceiverParameter!!), blockHolderField)
}
val arguments = (0 until parameterCount).map { index ->
irGet(invokeMethod.valueParameters[index])
}
+irReturn(callBlock(blockPointer, arguments))
}
irClass.addFakeOverrides(stubs.irBuiltIns)
stubs.addKotlin(irClass)
return constructor
}
private fun IrBuilderWithScope.callBlock(blockPtr: IrExpression, arguments: List<IrExpression>): IrExpression {
val callBuilder = KotlinToCCallBuilder(this, stubs, isObjCMethod = false, ForeignExceptionMode.default)
val rawBlockPointerParameter = callBuilder.passThroughBridge(blockPtr, blockPtr.type, CTypes.id)
val blockVariableName = "block"
arguments.forEachIndexed { index, argument ->
callBuilder.addArgument(argument, parameterValuePassings[index], variadic = false)
}
val result = callBuilder.buildCall(blockVariableName, valueReturning)
val blockVariableType = CTypes.blockPointer(callBuilder.cFunctionBuilder.getType())
val blockVariable = CVariable(blockVariableType, blockVariableName)
callBuilder.cBridgeBodyLines.add(0, "$blockVariable = ${rawBlockPointerParameter.name};")
callBuilder.emitCBridge()
return result
}
override fun bridgedToC(expression: String): String {
val callbackBuilder = CCallbackBuilder(stubs, location, isObjCMethod = false)
val kotlinFunctionHolder = "kotlinFunctionHolder"
callbackBuilder.cBridgeCallBuilder.arguments += kotlinFunctionHolder
val (kotlinFunctionHolderParameter, _) =
callbackBuilder.bridgeBuilder.addParameter(symbols.nativePtrType, CTypes.id)
callbackBuilder.kotlinCallBuilder.arguments += with(callbackBuilder.bridgeBuilder.kotlinIrBuilder) {
// TODO: consider casting to [functionType].
irCall(symbols.interopUnwrapKotlinObjectHolderImpl.owner).apply {
putValueArgument(0, irGet(kotlinFunctionHolderParameter) )
}
}
parameterValuePassings.forEach {
callbackBuilder.kotlinCallBuilder.arguments += with(it) {
callbackBuilder.receiveValue()
}
}
assert(functionType.isFunction())
val invokeFunction = (functionType.classifier.owner as IrClass)
.simpleFunctions().single { it.name == OperatorNameConventions.INVOKE }
callbackBuilder.buildValueReturn(invokeFunction, valueReturning)
val block = buildString {
append('^')
append(callbackBuilder.cFunctionBuilder.buildSignature(""))
append(" { ")
callbackBuilder.cBodyLines.forEach {
append(it)
append(' ')
}
append(" }")
}
val blockAsId = if (retained) {
"(__bridge id)(__bridge_retained void*)$block" // Retain and convert to id.
} else {
"(id)$block"
}
return "({ id $kotlinFunctionHolder = $expression; $kotlinFunctionHolder ? $blockAsId : (id)0; })"
}
override fun cToBridged(expression: String) = expression
}
private class WCStringArgumentPassing : KotlinToCArgumentPassing {
override fun KotlinToCCallBuilder.passValue(expression: IrExpression): CExpression {
val wcstr = irBuilder.irSafeTransform(expression) {
irCall(symbols.interopWcstr.owner).apply {
extensionReceiver = it
}
}
return with(CValuesRefArgumentPassing) { passValue(wcstr) }
}
}
private class CStringArgumentPassing : KotlinToCArgumentPassing {
override fun KotlinToCCallBuilder.passValue(expression: IrExpression): CExpression {
val cstr = irBuilder.irSafeTransform(expression) {
irCall(symbols.interopCstr.owner).apply {
extensionReceiver = it
}
}
return with(CValuesRefArgumentPassing) { passValue(cstr) }
}
}
private object CValuesRefArgumentPassing : KotlinToCArgumentPassing {
override fun KotlinToCCallBuilder.passValue(expression: IrExpression): CExpression {
val bridgeArgument = cValuesRefToPointer(expression)
val cBridgeValue = passThroughBridge(
bridgeArgument,
symbols.interopCPointer.typeWithStarProjections.makeNullable(),
CTypes.voidPtr
)
return CExpression(cBridgeValue.name, cBridgeValue.type)
}
}
private fun KotlinToCCallBuilder.cValuesRefToPointer(
value: IrExpression
): IrExpression = if (value.type.classifierOrNull == symbols.interopCPointer) {
value // Optimization
} else {
val getPointerFunction = symbols.interopCValuesRef.owner
.simpleFunctions()
.single { it.name.asString() == "getPointer" }
irBuilder.irSafeTransform(value) {
irCall(getPointerFunction).apply {
dispatchReceiver = it
putValueArgument(0, bridgeCallBuilder.getMemScope())
}
}
}
private fun IrBuilderWithScope.irSafeTransform(
value: IrExpression,
block: IrBuilderWithScope.(IrExpression) -> IrExpression
): IrExpression = if (!value.type.isNullable()) {
block(value) // Optimization
} else {
irLetS(value) { valueVarSymbol ->
val valueVar = valueVarSymbol.owner
val transformed = block(irGet(valueVar))
irIfThenElse(
type = transformed.type.makeNullable(),
condition = irEqeqeq(irGet(valueVar), irNull()),
thenPart = irNull(),
elsePart = transformed
)
}
}
private object VoidReturning : ValueReturning {
override val cType: CType
get() = CTypes.void
override fun KotlinToCCallBuilder.returnValue(expression: String): IrExpression {
bridgeBuilder.setReturnType(irBuilder.context.irBuiltIns.unitType, CTypes.void)
cFunctionBuilder.setReturnType(CTypes.void)
cBridgeBodyLines += "$expression;"
return buildKotlinBridgeCall()
}
override fun CCallbackBuilder.returnValue(expression: IrExpression) {
bridgeBuilder.setReturnType(irBuiltIns.unitType, CTypes.void)
cFunctionBuilder.setReturnType(CTypes.void)
kotlinBridgeStatements += bridgeBuilder.kotlinIrBuilder.irReturn(expression)
cBodyLines += "${buildCBridgeCall()};"
}
}
private object IgnoredUnitArgumentPassing : ArgumentPassing {
override fun KotlinToCCallBuilder.passValue(expression: IrExpression): CExpression? {
// Note: it is not correct to just drop the expression (due to possible side effects),
// so (in lack of other options) evaluate the expression and pass ignored value to the bridge:
val bridgeArgument = irBuilder.irBlock {
+expression
+irInt(0)
}
passThroughBridge(bridgeArgument, irBuilder.context.irBuiltIns.intType, CTypes.int).name
return null
}
override fun CCallbackBuilder.receiveValue(): IrExpression {
return bridgeBuilder.kotlinIrBuilder.irGetObject(irBuiltIns.unitClass)
}
}
internal fun CType.cast(expression: String): String = "((${this.render("")})$expression)"
private fun KotlinStubs.reportUnsupportedType(reason: String, type: IrType, location: TypeLocation): Nothing {
// TODO: report errors in frontend instead.
fun TypeLocation.render(): String = when (this) {
is TypeLocation.FunctionArgument -> ""
is TypeLocation.FunctionCallResult -> " of return value"
is TypeLocation.FunctionPointerParameter -> " of callback parameter ${index + 1}"
is TypeLocation.FunctionPointerReturnValue -> " of callback return value"
is TypeLocation.ObjCMethodParameter -> " of overridden Objective-C method parameter"
is TypeLocation.ObjCMethodReturnValue -> " of overridden Objective-C method return value"
is TypeLocation.BlockParameter -> " of ${index + 1} parameter in Objective-C block type${blockLocation.render()}"
is TypeLocation.BlockReturnValue -> " of return value of Objective-C block type${blockLocation.render()}"
}
val typeLocation: String = location.render()
reportError(location.element, "type ${type.render()} $typeLocation is not supported here" +
if (reason.isNotEmpty()) ": $reason" else "")
}
| apache-2.0 | 5ad4c0ce70a4bd65a6fb441b133af248 | 39.758778 | 150 | 0.689984 | 4.874193 | false | false | false | false |
nickbutcher/plaid | designernews/src/test/java/io/plaidapp/designernews/data/comments/CommentsRepositoryTest.kt | 1 | 4607 | /*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 io.plaidapp.designernews.data.comments
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import io.plaidapp.core.data.Result
import io.plaidapp.designernews.repliesResponses
import io.plaidapp.designernews.replyResponse1
import java.io.IOException
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Tests for [CommentsRepository] mocking all dependencies
*/
class CommentsRepositoryTest {
private val body = "Plaid 2.0 is awesome"
private val dataSource: CommentsRemoteDataSource = mock()
private val repository = CommentsRepository(dataSource)
@Test
fun getComments_withSuccess() = runBlocking {
// Given a list of comment responses that are return for a specific list of ids
val ids = listOf(1L)
val result = Result.Success(repliesResponses)
whenever(dataSource.getComments(ids)).thenReturn(result)
// When requesting the comments
val data = repository.getComments(ids)
// The correct response is returned
assertEquals(result, data)
}
@Test
fun getComments_withError() = runBlocking {
// Given a list of comment responses that are return for a specific list of ids
val ids = listOf(1L)
val result = Result.Error(IOException("error"))
whenever(dataSource.getComments(ids)).thenReturn(result)
// When requesting the comments
val data = repository.getComments(ids)
// The correct response is returned
assertEquals(result, data)
}
@Test
fun postStoryComment_withSuccess() = runBlocking {
// Given that a result is return when posting a story comment
val result = Result.Success(replyResponse1)
whenever(
dataSource.comment(
commentBody = body,
parentCommentId = null,
storyId = 11L,
userId = 111L
)
).thenReturn(result)
// When posting a story comment
val data = repository.postStoryComment(body, 11L, 111L)
// The correct response is returned
assertEquals(result, data)
}
@Test
fun postStoryComment_withError() = runBlocking {
// Given that an error result is return when posting a story comment
val result = Result.Error(IOException("error"))
whenever(
dataSource.comment(
commentBody = body,
parentCommentId = null,
storyId = 11L,
userId = 111L
)
).thenReturn(result)
// When posting a story comment
val data = repository.postStoryComment(body, 11L, 111L)
// The correct response is returned
assertEquals(result, data)
}
@Test
fun postReply_withSuccess() = runBlocking {
// Given that a result is return when posting a story comment
val result = Result.Success(replyResponse1)
whenever(
dataSource.comment(
commentBody = body,
parentCommentId = 11L,
storyId = null,
userId = 111L
)
).thenReturn(result)
// When posting reply
val data = repository.postReply(body, 11L, 111L)
// The correct response is returned
assertEquals(result, data)
}
@Test
fun postReply_withError() = runBlocking {
// Given that an error result is return when posting a reply to a comment
val result = Result.Error(IOException("error"))
whenever(
dataSource.comment(
commentBody = body,
parentCommentId = 11L,
storyId = null,
userId = 111L
)
).thenReturn(result)
// When posting reply
val data = repository.postReply(body, 11L, 111L)
// The correct response is returned
assertEquals(result, data)
}
}
| apache-2.0 | 8e27987fef4470e6486738a47e7cdd7d | 30.772414 | 87 | 0.634686 | 4.834208 | false | true | false | false |
ibaton/3House | mobile/src/main/java/treehou/se/habit/ui/colorpicker/LightPresenter.kt | 1 | 1885 | package treehou.se.habit.ui.colorpicker
import android.content.Context
import android.os.Bundle
import android.util.Log
import java.util.Locale
import javax.inject.Inject
import javax.inject.Named
import io.realm.Realm
import se.treehou.ng.ohcommunicator.connector.models.OHItem
import se.treehou.ng.ohcommunicator.connector.models.OHServer
import treehou.se.habit.connector.Constants
import treehou.se.habit.core.db.model.ServerDB
import treehou.se.habit.dagger.RxPresenter
import treehou.se.habit.ui.sitemaps.page.PageContract
import treehou.se.habit.util.ConnectionFactory
class LightPresenter @Inject
constructor(private val context: Context, private val realm: Realm, @param:Named("arguments") private val args: Bundle, private val connectionFactory: ConnectionFactory) : RxPresenter(), LightContract.Presenter {
private var serverDb: ServerDB? = null
private var server: OHServer? = null
override fun load(launchData: Bundle?, savedData: Bundle?) {
super.load(launchData, savedData)
val serverId = args.getLong(PageContract.ARG_SERVER)
serverDb = ServerDB.load(realm, serverId)
server = serverDb!!.toGeneric()
}
override fun setHSV(item: OHItem, hue: Int, saturation: Int, value: Int) {
val server = server
if(server != null) {
val serverHandler = connectionFactory.createServerHandler(server, context)
Log.d(TAG, "Color changed to " + String.format("%d,%d,%d", hue, saturation, value))
if (value > 5) {
serverHandler.sendCommand(item.name, String.format(Locale.getDefault(), Constants.COMMAND_COLOR, hue, saturation, value))
} else {
serverHandler.sendCommand(item.name, Constants.COMMAND_OFF)
}
}
}
companion object {
private val TAG = LightPresenter::class.java.simpleName
}
}
| epl-1.0 | 2a62ef76bd5699a46825810fe8482521 | 35.25 | 212 | 0.711936 | 4.142857 | false | false | false | false |
Orchextra/orchextra-android-sdk | core/src/main/java/com/gigigo/orchextra/core/domain/actions/ActionHandlerService.kt | 1 | 1892 | /*
* Created by Orchextra
*
* Copyright (C) 2017 Gigigo Mobile Services SL
*
* 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.gigigo.orchextra.core.domain.actions
import android.app.IntentService
import android.content.Context
import android.content.Intent
import android.util.Log
import com.gigigo.orchextra.core.domain.entities.Action
class ActionHandlerService : IntentService(TAG) {
override fun onHandleIntent(intent: Intent?) {
val actionDispatcher: ActionDispatcher = ActionDispatcher.create(this)
val action = intent?.getParcelableExtra<Action>(ACTION_EXTRA)
if (action == null) {
Log.d(TAG, "Action empty")
return
}
Log.d(TAG, "Execute action: $action")
actionDispatcher.executeAction(action)
}
companion object {
private const val TAG = "ActionHandlerService"
const val ACTION_EXTRA = "action_extra"
}
}
class ActionHandlerServiceExecutor(val context: Context) {
fun execute(action: Action) {
val intent = Intent(context, ActionHandlerService::class.java)
intent.putExtra(ActionHandlerService.ACTION_EXTRA, action)
context.startService(intent)
}
companion object Factory {
fun create(context: Context): ActionHandlerServiceExecutor = ActionHandlerServiceExecutor(
context
)
}
} | apache-2.0 | 99076438742747df6b5d455aa612e97c | 29.532258 | 98 | 0.707188 | 4.4 | false | false | false | false |
niranjan94/show-java | app/src/main/kotlin/com/njlabs/showjava/decompilers/BaseDecompiler.kt | 1 | 10687 | /*
* Show Java - A java/apk decompiler for android
* Copyright (c) 2018 Niranjan Rajendran
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.njlabs.showjava.decompilers
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.work.*
import com.njlabs.showjava.BuildConfig
import com.njlabs.showjava.Constants
import com.njlabs.showjava.R
import com.njlabs.showjava.data.PackageInfo
import com.njlabs.showjava.utils.ProcessNotifier
import com.njlabs.showjava.utils.UserPreferences
import com.njlabs.showjava.utils.ktx.appStorage
import com.njlabs.showjava.utils.ktx.cleanMemory
import com.njlabs.showjava.utils.streams.ProgressStream
import com.njlabs.showjava.workers.DecompilerWorker
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import org.apache.commons.io.FileUtils
import timber.log.Timber
import java.io.File
import java.io.PrintStream
import java.util.concurrent.TimeUnit
/**
* The base decompiler. This reads the input [Data] into easy to use properties of the class.
* All other components of the decompiler will extend this one.
*/
abstract class BaseDecompiler(val context: Context, val data: Data) {
var printStream: PrintStream? = null
private var id = data.getString("id")
private var processNotifier: ProcessNotifier? = null
private var runAttemptCount: Int = 0
protected var outOfMemory = false
protected val decompiler = data.getString("decompiler")
protected val type = PackageInfo.Type.values()[data.getInt("type", 0)]
private val maxAttempts = data.getInt("maxAttempts", UserPreferences.DEFAULTS.MAX_ATTEMPTS)
private val memoryThreshold = data.getInt("memoryThreshold", 80)
protected val packageName = data.getString("name").toString()
protected val packageLabel = data.getString("label").toString()
protected val keepIntermediateFiles = data.getBoolean("keepIntermediateFiles", UserPreferences.DEFAULTS.KEEP_INTERMEDIATE_FILES)
protected val workingDirectory: File = appStorage.resolve("sources/$packageName/")
protected val cacheDirectory: File = appStorage.resolve("sources/.cache/")
protected val inputPackageFile: File = File(data.getString("inputPackageFile"))
protected val outputDexFiles: File = workingDirectory.resolve("dex-files")
protected val outputJarFiles: File = workingDirectory.resolve("jar-files")
protected val outputSrcDirectory: File = workingDirectory.resolve("src")
protected val outputJavaSrcDirectory: File = outputSrcDirectory.resolve("java")
private val disposables = CompositeDisposable()
private var onLowMemory: ((Boolean) -> Unit)? = null
private var memoryThresholdCrossCount = 0
protected open val maxMemoryAdjustmentFactor = 1.25
init {
@Suppress("LeakingThis")
printStream = PrintStream(ProgressStream(this))
System.setErr(printStream)
System.setOut(printStream)
}
/**
* Prepare the required directories.
* All child classes must call this method on override.
*/
open fun doWork(): ListenableWorker.Result {
cleanMemory()
monitorMemory()
outputJavaSrcDirectory.mkdirs()
if (BuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
data.keyValueMap.forEach { t, u ->
Timber.d("[WORKER] [INPUT] $t: $u")
}
}
return ListenableWorker.Result.success()
}
fun withAttempt(attempt: Int = 0): ListenableWorker.Result {
this.runAttemptCount = attempt
return this.doWork()
}
fun withNotifier(notifier: ProcessNotifier): BaseDecompiler {
this.processNotifier = notifier
return this
}
fun withLowMemoryCallback(onLowMemory: ((Boolean) -> Unit)): BaseDecompiler {
this.onLowMemory = onLowMemory
return this
}
private fun monitorMemory() {
disposables.add(
Observable.interval(1000, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe {
val maxAdjusted = Runtime.getRuntime().maxMemory() / maxMemoryAdjustmentFactor
val used = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()).toDouble().let { m ->
if (m > maxAdjusted) maxAdjusted else m
}
val usedPercentage = (used / maxAdjusted) * 100
Timber.d("[mem] ----")
Timber.d("[mem] Used: ${FileUtils.byteCountToDisplaySize(used.toLong())}")
Timber.d("[mem] Max: ${FileUtils.byteCountToDisplaySize(maxAdjusted.toLong())} at factor $maxMemoryAdjustmentFactor")
Timber.d("[mem] Used %: $usedPercentage")
broadcastStatus("memory", "%.2f".format(usedPercentage), "memory")
if (usedPercentage > memoryThreshold) {
if (memoryThresholdCrossCount > 2) {
onLowMemory?.invoke(true)
} else {
memoryThresholdCrossCount++
}
} else {
memoryThresholdCrossCount = 0
}
}
)
}
/**
* Update the notification and broadcast status
*/
protected fun sendStatus(title: String, message: String, forceSet: Boolean = false) {
processNotifier?.updateTitleText(title, message, forceSet)
this.broadcastStatus(title, message)
}
fun sendStatus(message: String, forceSet: Boolean = false) {
processNotifier?.updateText(message, forceSet)
this.broadcastStatus(null, message)
}
/**
* Set the current decompilation step
*/
fun setStep(title: String) {
sendStatus(title, context.getString(R.string.initializing), true)
}
/**
* Clear the notification and exit marking the work job as failed
*/
protected fun exit(exception: Exception?): ListenableWorker.Result {
Timber.e(exception)
onStopped()
disposables.clear()
return if (runAttemptCount >= (maxAttempts - 1))
ListenableWorker.Result.failure()
else
ListenableWorker.Result.retry()
}
/**
* Return a success only if the conditions is true. Else exit with an exception.
*/
protected fun successIf(condition: Boolean): ListenableWorker.Result {
disposables.clear()
return if (condition)
ListenableWorker.Result.success()
else
exit(Exception("Success condition failed"))
}
/**
* Broadcast the status to the receiver
*/
private fun broadcastStatus(title: String?, message: String, type: String = "progress") {
context.sendBroadcast(
Intent(Constants.WORKER.ACTION.BROADCAST + packageName)
.putExtra(Constants.WORKER.STATUS_TITLE, title)
.putExtra(Constants.WORKER.STATUS_MESSAGE, message)
.putExtra(Constants.WORKER.STATUS_TYPE, type)
)
}
/**
* Build a persistent notification
*/
protected fun buildNotification(title: String) {
if (processNotifier == null) {
processNotifier = ProcessNotifier(context, id)
}
processNotifier!!.buildFor(
title,
packageName,
packageLabel,
inputPackageFile,
context.resources.getStringArray(R.array.decompilersValues).indexOf(decompiler)
)
}
/**
* Clear notifications and show a success notification.
*/
fun onCompleted() {
processNotifier?.success()
broadcastStatus(
context.getString(R.string.appHasBeenDecompiled, packageLabel),
""
)
}
/**
* Cancel notification on worker stop
*/
open fun onStopped() {
Timber.d("[cancel-request] cancelled")
disposables.clear()
processNotifier?.cancel()
}
companion object {
/**
* Check if the specified decompiler is available on the device based on the android version
*/
fun isAvailable(decompiler: String): Boolean {
return when (decompiler) {
"cfr" -> true
"jadx" -> Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
"fernflower" -> Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
else -> false
}
}
/**
* For the WorkManager compatible Data object from the given map
*/
fun formData(dataMap: Map<String, Any>): Data {
val id = dataMap["name"] as String
return Data.Builder()
.putAll(dataMap)
.putString("id", id)
.build()
}
/**
* Start the jobs using the given map
*/
fun start(dataMap: Map<String, Any>): String {
val data = formData(dataMap)
val id = data.getString("id")!!
fun buildWorkRequest(type: String): OneTimeWorkRequest {
return OneTimeWorkRequestBuilder<DecompilerWorker>()
.addTag("decompile")
.addTag(type)
.addTag(id)
.setBackoffCriteria(BackoffPolicy.LINEAR, 0, TimeUnit.SECONDS)
.setInputData(data)
.build()
}
WorkManager.getInstance()
.beginUniqueWork(
id,
ExistingWorkPolicy.REPLACE,
buildWorkRequest("jar-extraction")
)
.then(buildWorkRequest("java-extraction"))
.then(buildWorkRequest("resources-extraction"))
.enqueue()
return id
}
}
class OutOfMemoryError: Exception()
} | gpl-3.0 | 73706f50c67916b97eafa3afeb6a2db1 | 34.390728 | 137 | 0.623655 | 4.940823 | false | false | false | false |
matejdro/WearMusicCenter | wear/src/main/java/com/matejdro/wearmusiccenter/watch/view/RecyclerClickDetector.kt | 1 | 2687 | package com.matejdro.wearmusiccenter.watch.view
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.widget.FrameLayout
import kotlin.math.abs
import kotlin.math.roundToLong
/**
* RecyclerView does not support click detection for whole view. This wrapper view provides that.
*/
class RecyclerClickDetector @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private var pressX = 0f
private var pressY = 0f
private var prePressed = false
private val maxAllowedPressMovement = ViewConfiguration.get(context).scaledTouchSlop
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
if (!isClickable) {
return false
}
when (ev.actionMasked) {
MotionEvent.ACTION_DOWN -> {
pressX = ev.x
pressY = ev.y
postDelayed(pressRunnable, ViewConfiguration.getTapTimeout().toLong())
prePressed = true
}
MotionEvent.ACTION_MOVE -> {
if (prePressed) {
drawableHotspotChanged(ev.x, ev.y)
val newY = ev.y.roundToLong()
val oldYRound = pressY.roundToLong()
val fingerMovedY = abs(newY - oldYRound)
if (fingerMovedY > maxAllowedPressMovement) {
// We are scrolling.
cancelPress()
}
}
}
MotionEvent.ACTION_UP -> {
removeCallbacks(pressRunnable)
if (prePressed) {
performClick()
isPressed = true
isPressed = false
prePressed = false
return true
}
prePressed = false
}
MotionEvent.ACTION_CANCEL -> {
cancelPress()
}
}
return isPressed
}
private fun cancelPress() {
prePressed = false
isPressed = false
removeCallbacks(pressRunnable)
}
private val pressRunnable = Runnable {
drawableHotspotChanged(pressX, pressY)
isPressed = true
}
override fun setClickable(clickable: Boolean) {
super.setClickable(clickable)
if (!clickable) {
cancelPress()
}
}
// Child buttons in RecyclerView should not get pressed when we do
override fun dispatchSetPressed(pressed: Boolean) = Unit
} | gpl-3.0 | 9574b1e22632ffdde2b6ae62f9cf023b | 29.202247 | 97 | 0.568292 | 5.341948 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/views/ImagePreviewDialog.kt | 1 | 6208 | package org.wikipedia.views
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import androidx.core.os.bundleOf
import com.google.android.material.bottomsheet.BottomSheetBehavior
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.commons.ImageTagsProvider
import org.wikipedia.databinding.DialogImagePreviewBinding
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.mwapi.MwQueryPage
import org.wikipedia.descriptions.DescriptionEditActivity.Action
import org.wikipedia.page.ExtendedBottomSheetDialogFragment
import org.wikipedia.suggestededits.PageSummaryForEdit
import org.wikipedia.util.DimenUtil
import org.wikipedia.util.L10nUtil.setConditionalLayoutDirection
import org.wikipedia.util.StringUtil
import org.wikipedia.util.log.L
class ImagePreviewDialog : ExtendedBottomSheetDialogFragment(), DialogInterface.OnDismissListener {
private var _binding: DialogImagePreviewBinding? = null
private val binding get() = _binding!!
private lateinit var pageSummaryForEdit: PageSummaryForEdit
private var action: Action? = null
private val disposables = CompositeDisposable()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = DialogImagePreviewBinding.inflate(inflater, container, false)
pageSummaryForEdit = requireArguments().getParcelable(ARG_SUMMARY)!!
action = requireArguments().getSerializable(ARG_ACTION) as Action?
setConditionalLayoutDirection(binding.root, pageSummaryForEdit.lang)
return binding.root
}
override fun onStart() {
super.onStart()
BottomSheetBehavior.from(requireView().parent as View).peekHeight = DimenUtil.roundedDpToPx(DimenUtil.getDimension(R.dimen.imagePreviewSheetPeekHeight))
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.progressBar.visibility = VISIBLE
binding.toolbarView.setOnClickListener { dismiss() }
binding.titleText.text = StringUtil.removeHTMLTags(StringUtil.removeNamespace(pageSummaryForEdit.displayTitle!!))
loadImageInfo()
}
override fun onDestroyView() {
binding.toolbarView.setOnClickListener(null)
_binding = null
disposables.clear()
super.onDestroyView()
}
private fun showError(caught: Throwable?) {
binding.dialogDetailContainer.layoutTransition = null
binding.dialogDetailContainer.minimumHeight = 0
binding.progressBar.visibility = GONE
binding.filePageView.visibility = GONE
binding.errorView.visibility = VISIBLE
binding.errorView.setError(caught, pageSummaryForEdit.pageTitle)
}
private fun loadImageInfo() {
lateinit var imageTags: Map<String, List<String>>
lateinit var page: MwQueryPage
var isFromCommons = false
var thumbnailWidth = 0
var thumbnailHeight = 0
disposables.add(ServiceFactory.get(Constants.commonsWikiSite).getImageInfo(pageSummaryForEdit.title, pageSummaryForEdit.lang)
.subscribeOn(Schedulers.io())
.flatMap {
if (it.query?.firstPage()?.imageInfo() == null) {
// If file page originally comes from *.wikipedia.org (i.e. movie posters), it will not have imageInfo and pageId.
ServiceFactory.get(pageSummaryForEdit.pageTitle.wikiSite).getImageInfo(pageSummaryForEdit.title, pageSummaryForEdit.lang)
} else {
// Fetch API from commons.wikimedia.org and check whether if it is not a "shared" image.
isFromCommons = it.query?.firstPage()?.isImageShared != true
Observable.just(it)
}
}
.flatMap { response ->
page = response.query?.firstPage()!!
page.imageInfo()?.let {
pageSummaryForEdit.timestamp = it.timestamp
pageSummaryForEdit.user = it.user
pageSummaryForEdit.metadata = it.metadata
thumbnailWidth = it.thumbWidth
thumbnailHeight = it.thumbHeight
}
ImageTagsProvider.getImageTagsObservable(page.pageId, pageSummaryForEdit.lang)
}
.observeOn(AndroidSchedulers.mainThread())
.doAfterTerminate {
binding.filePageView.visibility = VISIBLE
binding.progressBar.visibility = GONE
binding.filePageView.setup(
pageSummaryForEdit,
imageTags,
page,
binding.dialogDetailContainer.width,
thumbnailWidth, thumbnailHeight,
imageFromCommons = isFromCommons,
showFilename = false,
showEditButton = false,
action = action
)
}
.subscribe({ imageTags = it }, { caught ->
L.e(caught)
showError(caught)
}))
}
companion object {
private const val ARG_SUMMARY = "summary"
private const val ARG_ACTION = "action"
fun newInstance(pageSummaryForEdit: PageSummaryForEdit, action: Action? = null): ImagePreviewDialog {
val dialog = ImagePreviewDialog()
dialog.arguments = bundleOf(ARG_SUMMARY to pageSummaryForEdit,
ARG_ACTION to action)
return dialog
}
}
}
| apache-2.0 | d2c73a648920bfa5b04255cff239cfb7 | 43.661871 | 160 | 0.653351 | 5.552773 | false | false | false | false |
stripe/stripe-android | payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/CardBillingSpec.kt | 1 | 1747 | package com.stripe.android.ui.core.elements
import androidx.annotation.RestrictTo
import com.stripe.android.ui.core.R
import com.stripe.android.ui.core.address.AddressRepository
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
@Serializable
data class CardBillingSpec(
@SerialName("api_path")
override val apiPath: IdentifierSpec = IdentifierSpec.Generic("card_billing"),
@SerialName("allowed_country_codes")
val allowedCountryCodes: Set<String> = supportedBillingCountries
) : FormItemSpec() {
fun transform(
initialValues: Map<IdentifierSpec, String?>,
addressRepository: AddressRepository,
shippingValues: Map<IdentifierSpec, String?>?
): SectionElement {
val sameAsShippingElement =
shippingValues?.get(IdentifierSpec.SameAsShipping)
?.toBooleanStrictOrNull()
?.let {
SameAsShippingElement(
identifier = IdentifierSpec.SameAsShipping,
controller = SameAsShippingController(it)
)
}
val addressElement = CardBillingAddressElement(
IdentifierSpec.Generic("credit_billing"),
addressRepository = addressRepository,
countryCodes = allowedCountryCodes,
rawValuesMap = initialValues,
sameAsShippingElement = sameAsShippingElement,
shippingValuesMap = shippingValues
)
return createSectionElement(
listOfNotNull(
addressElement,
sameAsShippingElement
),
R.string.billing_details
)
}
}
| mit | e322ea306206d10ae4f0872cfb031daf | 35.395833 | 82 | 0.651402 | 5.459375 | false | false | false | false |
deva666/anko | anko/library/robolectricTests/src/main/java/AndroidLayoutParamsTestActivity.kt | 4 | 1963 | package com.example.android_test
import android.app.Activity
import android.os.Bundle
import android.view.Gravity
import android.widget.RelativeLayout
import org.jetbrains.anko.*
open class AndroidLayoutParamsTestActivity : Activity() {
public override fun onCreate(savedInstanceState: Bundle?): Unit {
super.onCreate(savedInstanceState)
UI {
linearLayout {
editText().lparams(-2, -2) {
bottomMargin = 1
leftMargin = 2
rightMargin = 3
topMargin = 4
height = 9
gravity = Gravity.RIGHT
weight = 1.3591409142295225f
}
}
relativeLayout {
editText().lparams(-2, -2) {
bottomMargin = 1
leftMargin = 2
rightMargin = 3
topMargin = 4
height = 9
addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE)
addRule(RelativeLayout.CENTER_IN_PARENT)
}
}
absoluteLayout {
editText().lparams(-2, -2, 12, 23) {
height = 9
x = 100
y = 200
}
}
frameLayout {
editText().lparams(-2, -2) {
bottomMargin = 1
leftMargin = 2
rightMargin = 3
topMargin = 4
height = 9
gravity = Gravity.RIGHT
}
}
gridLayout {
editText().lparams {
bottomMargin = 1
leftMargin = 2
rightMargin = 3
topMargin = 4
height = 9
}
}
}
}
} | apache-2.0 | 80ef2aa4c7b6d6428c63b0bdb3874eda | 30.174603 | 82 | 0.413653 | 6.271565 | false | false | false | false |
arcuri82/testing_security_development_enterprise_systems | advanced/graphql/news-graphql/src/main/kotlin/org/tsdes/advanced/graphql/newsgraphql/type/NewsType.kt | 1 | 346 | package org.tsdes.advanced.graphql.newsgraphql.type
import java.time.ZonedDateTime
open class NewsType(
authorId: String? = null,
text: String? = null,
country: String? = null,
creationTime: ZonedDateTime? = null,
var newsId: String? = null
) : InputUpdateNewsType(authorId, text, country, creationTime) | lgpl-3.0 | e0276c93b21292f4d7660593c0c31dfb | 27.916667 | 62 | 0.682081 | 4.168675 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/cli/options/OptionParser.kt | 1 | 6305 | /*
Copyright 2017-2020 Charles Korn.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batect.cli.options
import batect.cli.options.defaultvalues.DefaultValueProvider
import batect.cli.options.defaultvalues.StandardFlagOptionDefaultValueProvider
import batect.cli.options.defaultvalues.StaticDefaultValueProvider
class OptionParser {
private val options = mutableSetOf<OptionDefinition>()
private val optionNames = mutableMapOf<String, OptionDefinition>()
fun parseOptions(args: Iterable<String>): OptionsParsingResult {
var argIndex = 0
while (argIndex < args.count()) {
when (val optionParsingResult = parseOption(args, argIndex)) {
is OptionParsingResult.ReadOption -> argIndex += optionParsingResult.argumentsConsumed
is OptionParsingResult.InvalidOption -> return OptionsParsingResult.InvalidOptions(optionParsingResult.message)
is OptionParsingResult.NoOption -> return checkDefaults(argIndex)
}
}
return checkDefaults(argIndex)
}
private fun parseOption(args: Iterable<String>, currentIndex: Int): OptionParsingResult {
val arg = args.elementAt(currentIndex)
val argName = arg.substringBefore("=")
val option = optionNames[argName]
if (option == null) {
if (argName.startsWith("-")) {
return OptionParsingResult.InvalidOption("Invalid option '$argName'. Run './batect --help' for a list of valid options.")
} else {
return OptionParsingResult.NoOption
}
}
return option.parse(args.drop(currentIndex))
}
private fun checkDefaults(argumentsConsumed: Int): OptionsParsingResult {
options.forEach {
when (val result = it.checkDefaultValue()) {
is DefaultApplicationResult.Failed -> return OptionsParsingResult.InvalidOptions("The default value for the ${it.longOption} option is invalid: ${result.message}")
}
}
return OptionsParsingResult.ReadOptions(argumentsConsumed)
}
fun addOption(option: OptionDefinition) {
if (optionNames.containsKey(option.longOption)) {
throw IllegalArgumentException("An option with the name '${option.longName}' has already been added.")
}
if (option.shortOption != null && optionNames.containsKey(option.shortOption)) {
throw IllegalArgumentException("An option with the name '${option.shortName}' has already been added.")
}
options.add(option)
optionNames[option.longOption] = option
if (option.shortOption != null) {
optionNames[option.shortOption] = option
}
}
fun getOptions(): Set<OptionDefinition> = options
}
interface OptionParserContainer {
val optionParser: OptionParser
fun valueOption(group: OptionGroup, longName: String, description: String, shortName: Char? = null) =
valueOption(group, longName, description, ValueConverters::string, shortName)
fun <V> valueOption(group: OptionGroup, longName: String, description: String, valueConverter: (String) -> ValueConversionResult<V>, shortName: Char? = null) =
valueOption(group, longName, description, StaticDefaultValueProvider<V?>(null), valueConverter, shortName)
fun valueOption(group: OptionGroup, longName: String, description: String, defaultValue: String, shortName: Char? = null) =
valueOption(group, longName, description, defaultValue, ValueConverters::string, shortName)
fun <StorageType, ValueType : StorageType> valueOption(group: OptionGroup, longName: String, description: String, defaultValue: StorageType, valueConverter: (String) -> ValueConversionResult<ValueType>, shortName: Char? = null) =
valueOption(group, longName, description, StaticDefaultValueProvider(defaultValue), valueConverter, shortName)
fun valueOption(group: OptionGroup, longName: String, description: String, defaultValueProvider: DefaultValueProvider<String>, shortName: Char? = null) =
valueOption(group, longName, description, defaultValueProvider, ValueConverters::string, shortName)
fun <StorageType, ValueType : StorageType> valueOption(group: OptionGroup, longName: String, description: String, defaultValueProvider: DefaultValueProvider<StorageType>, valueConverter: (String) -> ValueConversionResult<ValueType>, shortName: Char? = null) =
ValueOption(group, longName, description, defaultValueProvider, valueConverter, shortName)
fun flagOption(group: OptionGroup, longName: String, description: String, shortName: Char? = null) =
flagOption(group, longName, description, StandardFlagOptionDefaultValueProvider, shortName)
fun flagOption(group: OptionGroup, longName: String, description: String, defaultValueProvider: DefaultValueProvider<Boolean>, shortName: Char? = null) =
FlagOption(group, longName, description, defaultValueProvider, shortName)
fun mapOption(group: OptionGroup, longName: String, description: String, shortName: Char? = null) = MapOption(group, longName, description, shortName)
fun mapOption(group: OptionGroup, longName: String, description: String, valueFormatForHelp: String, shortName: Char? = null) = MapOption(group, longName, description, shortName, valueFormatForHelp)
}
sealed class OptionsParsingResult {
data class ReadOptions(val argumentsConsumed: Int) : OptionsParsingResult()
data class InvalidOptions(val message: String) : OptionsParsingResult()
}
sealed class OptionParsingResult {
data class ReadOption(val argumentsConsumed: Int) : OptionParsingResult()
data class InvalidOption(val message: String) : OptionParsingResult()
object NoOption : OptionParsingResult()
}
| apache-2.0 | df0f86becdb4c15c7c6e81a3f92d1ad4 | 48.645669 | 263 | 0.726249 | 4.880031 | false | false | false | false |
stoyicker/dinger | data/src/main/kotlin/data/tinder/recommendation/RecommendationProcessedFileDaoDelegate.kt | 1 | 2062 | package data.tinder.recommendation
import data.database.CollectibleDaoDelegate
import domain.recommendation.DomainRecommendationProcessedFile
internal class RecommendationProcessedFileDaoDelegate(
private val processedFileDao: RecommendationProcessedFileDao,
private val photoProcessedFileDao: RecommendationPhoto_ProcessedFileDao,
private val albumProcessedFileDao: RecommendationSpotifyAlbum_ProcessedFileDao)
: CollectibleDaoDelegate<String, DomainRecommendationProcessedFile>() {
override fun selectByPrimaryKey(primaryKey: String) =
processedFileDao.selectProcessedFileByUrl(primaryKey).firstOrNull()?.let {
return DomainRecommendationProcessedFile(
widthPx = it.widthPx,
url = it.url,
heightPx = it.heightPx)
} ?: DomainRecommendationProcessedFile.NONE
override fun insertResolved(source: DomainRecommendationProcessedFile) =
processedFileDao.insertProcessedFile(RecommendationUserPhotoProcessedFileEntity(
widthPx = source.widthPx,
url = source.url,
heightPx = source.heightPx))
fun insertResolvedForPhotoId(
photoId: String, processedFiles: Iterable<DomainRecommendationProcessedFile>) =
processedFiles.forEach {
insertResolved(it)
photoProcessedFileDao.insertPhoto_ProcessedFile(
RecommendationUserPhotoEntity_RecommendationUserPhotoProcessedFileEntity(
recommendationUserPhotoEntityId = photoId,
recommendationUserPhotoProcessedFileEntityUrl = it.url))
}
fun insertResolvedForAlbumId(
albumId: String, processedFiles: Iterable<DomainRecommendationProcessedFile>) =
processedFiles.forEach {
insertResolved(it)
albumProcessedFileDao.insertSpotifyAlbum_ProcessedFile(
RecommendationUserSpotifyThemeTrackAlbumEntity_RecommendationUserPhotoProcessedFileEntity(
recommendationUserSpotifyThemeTrackAlbumEntityId = albumId,
recommendationUserPhotoProcessedFileEntityUrl = it.url))
}
}
| mit | ff00287dba4fc9d14db712a9dd2e4dc8 | 45.863636 | 102 | 0.762367 | 5.426316 | false | false | false | false |
androidx/androidx | health/health-services-client/src/main/java/androidx/health/services/client/data/MilestoneMarkerSummary.kt | 3 | 4023 | /*
* Copyright (C) 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.health.services.client.data
import androidx.health.services.client.proto.DataProto
import androidx.health.services.client.proto.DataProto.AchievedExerciseGoal
import androidx.health.services.client.proto.DataProto.MilestoneMarkerSummary.SummaryMetricsEntry
import java.time.Duration
import java.time.Instant
/**
* The summary of metrics and state from the previously achieved milestone marker [ExerciseGoal].
*/
@Suppress("ParcelCreator")
public class MilestoneMarkerSummary(
/** Returns the time at which this milestone marker started being tracked. */
public val startTime: Instant,
/** Returns the time at which this milestone marker was reached. */
public val endTime: Instant,
/**
* Returns the total elapsed time for which the exercise was active during this milestone, i.e.
* started but not paused.
*/
public val activeDuration: Duration,
/** The [ExerciseGoal] that triggered this milestone summary. */
public val achievedGoal: ExerciseGoal<out Number>,
/**
* Returns the [DataPointContainer] for aggregated metrics tracked between [startTime] and
* [endTime] i.e. during the duration of this milestone. This summary will only contain
* [DataPoint]s for [AggregateDataType]s.
*/
public val summaryMetrics: DataPointContainer,
) {
internal constructor(
proto: DataProto.MilestoneMarkerSummary
) : this(
Instant.ofEpochMilli(proto.startTimeEpochMs),
Instant.ofEpochMilli(proto.endTimeEpochMs),
Duration.ofMillis(proto.activeDurationMs),
ExerciseGoal.fromProto(proto.achievedGoal.exerciseGoal),
DataPointContainer(proto.summaryMetricsList.map {
DataPoint.fromProto(it.aggregateDataPoint)
})
)
internal val proto: DataProto.MilestoneMarkerSummary =
DataProto.MilestoneMarkerSummary.newBuilder()
.setStartTimeEpochMs(startTime.toEpochMilli())
.setEndTimeEpochMs(endTime.toEpochMilli())
.setActiveDurationMs(activeDuration.toMillis())
.setAchievedGoal(AchievedExerciseGoal.newBuilder().setExerciseGoal(achievedGoal.proto))
.addAllSummaryMetrics(
summaryMetrics.cumulativeDataPoints
.map {
SummaryMetricsEntry.newBuilder()
.setDataType(it.dataType.proto)
.setAggregateDataPoint(it.proto)
.build()
}
// Sorting to ensure equals() works correctly.
.sortedBy { it.dataType.name }
)
.addAllSummaryMetrics(
summaryMetrics.statisticalDataPoints
.map {
SummaryMetricsEntry.newBuilder()
.setDataType(it.dataType.proto)
.setAggregateDataPoint(it.proto)
.build()
}
// Sorting to ensure equals() works correctly.
.sortedBy { it.dataType.name }
)
.build()
override fun toString(): String =
"MilestoneMarkerSummary(" +
"startTime=$startTime, " +
"endTime=$endTime, " +
"achievedGoal=$achievedGoal, " +
"summaryMetrics=$summaryMetrics)"
}
| apache-2.0 | ca203aa8f120760ab58d43eed3452aac | 38.831683 | 99 | 0.644047 | 5.035044 | false | false | false | false |
androidx/androidx | compose/material3/material3/samples/src/main/java/androidx/compose/material3/samples/AppBarSamples.kt | 3 | 15788 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material3.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.BottomAppBar
import androidx.compose.material3.BottomAppBarDefaults
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.FloatingActionButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LargeTopAppBar
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MediumTopAppBar
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
/**
* A sample for a simple use of small [TopAppBar].
*
* The top app bar here does not react to any scroll events in the content under it.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun SimpleTopAppBar() {
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
"Simple TopAppBar",
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
navigationIcon = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(
imageVector = Icons.Filled.Menu,
contentDescription = "Localized description"
)
}
},
actions = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(
imageVector = Icons.Filled.Favorite,
contentDescription = "Localized description"
)
}
}
)
},
content = { innerPadding ->
LazyColumn(
contentPadding = innerPadding,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
val list = (0..75).map { it.toString() }
items(count = list.size) {
Text(
text = list[it],
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
)
}
}
}
)
}
/**
* A sample for a simple use of [CenterAlignedTopAppBar].
*
* The top app bar here does not react to any scroll events in the content under it.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun SimpleCenterAlignedTopAppBar() {
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = {
Text(
"Centered TopAppBar",
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
navigationIcon = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(
imageVector = Icons.Filled.Menu,
contentDescription = "Localized description"
)
}
},
actions = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(
imageVector = Icons.Filled.Favorite,
contentDescription = "Localized description"
)
}
}
)
},
content = { innerPadding ->
LazyColumn(
contentPadding = innerPadding,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
val list = (0..75).map { it.toString() }
items(count = list.size) {
Text(
text = list[it],
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
)
}
}
}
)
}
/**
* A sample for a pinned small [TopAppBar].
*
* The top app bar here is pinned to its location and changes its container color when the content
* under it is scrolled.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun PinnedTopAppBar() {
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
TopAppBar(
title = {
Text(
"TopAppBar",
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
navigationIcon = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(
imageVector = Icons.Filled.Menu,
contentDescription = "Localized description"
)
}
},
actions = {
// RowScope here, so these icons will be placed horizontally
IconButton(onClick = { /* doSomething() */ }) {
Icon(
imageVector = Icons.Filled.Favorite,
contentDescription = "Localized description"
)
}
IconButton(onClick = { /* doSomething() */ }) {
Icon(
imageVector = Icons.Filled.Favorite,
contentDescription = "Localized description"
)
}
},
scrollBehavior = scrollBehavior
)
},
content = { innerPadding ->
LazyColumn(
contentPadding = innerPadding,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
val list = (0..75).map { it.toString() }
items(count = list.size) {
Text(
text = list[it],
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
)
}
}
}
)
}
/**
* A sample for a small [TopAppBar] that collapses when the content is scrolled up, and
* appears when the content scrolled down.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun EnterAlwaysTopAppBar() {
val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior()
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
TopAppBar(
title = {
Text(
"TopAppBar",
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
navigationIcon = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(
imageVector = Icons.Filled.Menu,
contentDescription = "Localized description"
)
}
},
actions = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(
imageVector = Icons.Filled.Favorite,
contentDescription = "Localized description"
)
}
},
scrollBehavior = scrollBehavior
)
},
content = { innerPadding ->
LazyColumn(
contentPadding = innerPadding,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
val list = (0..75).map { it.toString() }
items(count = list.size) {
Text(
text = list[it],
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
)
}
}
}
)
}
/**
* A sample for a [MediumTopAppBar] that collapses when the content is scrolled up, and
* appears when the content is completely scrolled back down.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun ExitUntilCollapsedMediumTopAppBar() {
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
MediumTopAppBar(
title = {
Text(
"Medium TopAppBar",
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
navigationIcon = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(
imageVector = Icons.Filled.Menu,
contentDescription = "Localized description"
)
}
},
actions = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(
imageVector = Icons.Filled.Favorite,
contentDescription = "Localized description"
)
}
},
scrollBehavior = scrollBehavior
)
},
content = { innerPadding ->
LazyColumn(
contentPadding = innerPadding,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
val list = (0..75).map { it.toString() }
items(count = list.size) {
Text(
text = list[it],
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
)
}
}
}
)
}
/**
* A sample for a [LargeTopAppBar] that collapses when the content is scrolled up, and
* appears when the content is completely scrolled back down.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Sampled
@Composable
fun ExitUntilCollapsedLargeTopAppBar() {
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
LargeTopAppBar(
title = {
Text(
"Large TopAppBar",
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
navigationIcon = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(
imageVector = Icons.Filled.Menu,
contentDescription = "Localized description"
)
}
},
actions = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(
imageVector = Icons.Filled.Favorite,
contentDescription = "Localized description"
)
}
},
scrollBehavior = scrollBehavior
)
},
content = { innerPadding ->
LazyColumn(
contentPadding = innerPadding,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
val list = (0..75).map { it.toString() }
items(count = list.size) {
Text(
text = list[it],
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
)
}
}
}
)
}
@Preview
@Sampled
@Composable
fun SimpleBottomAppBar() {
BottomAppBar {
IconButton(onClick = { /* doSomething() */ }) {
Icon(Icons.Filled.Menu, contentDescription = "Localized description")
}
}
}
@Preview
@Sampled
@Composable
fun BottomAppBarWithFAB() {
BottomAppBar(
actions = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(Icons.Filled.Check, contentDescription = "Localized description")
}
IconButton(onClick = { /* doSomething() */ }) {
Icon(
Icons.Filled.Edit,
contentDescription = "Localized description",
)
}
},
floatingActionButton = {
FloatingActionButton(
onClick = { /* do something */ },
containerColor = BottomAppBarDefaults.bottomAppBarFabColor,
elevation = FloatingActionButtonDefaults.bottomAppBarFabElevation()
) {
Icon(Icons.Filled.Add, "Localized description")
}
}
)
}
| apache-2.0 | fbd5f59aa6ce945892dcad21ae41c030 | 33.77533 | 98 | 0.484482 | 6.025954 | false | false | false | false |
willjgriff/android-ethereum-wallet | app/src/main/kotlin/com/github/willjgriff/ethereumwallet/ui/screens/transactions/TransactionsController.kt | 1 | 3359 | package com.github.willjgriff.ethereumwallet.ui.screens.transactions
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.github.willjgriff.ethereumwallet.R
import com.github.willjgriff.ethereumwallet.ethereum.transactions.model.DomainTransaction
import com.github.willjgriff.ethereumwallet.mvp.BaseMvpControllerKotlin
import com.github.willjgriff.ethereumwallet.ui.navigation.NavigationToolbarListener
import com.github.willjgriff.ethereumwallet.ui.screens.transactions.adapters.TransactionsAdapter
import com.github.willjgriff.ethereumwallet.ui.screens.transactions.di.injectPresenter
import com.github.willjgriff.ethereumwallet.ui.screens.transactions.mvp.TransactionsPresenter
import com.github.willjgriff.ethereumwallet.ui.screens.transactions.mvp.TransactionsView
import com.github.willjgriff.ethereumwallet.ui.utils.inflate
import com.github.willjgriff.ethereumwallet.ui.utils.listdecorator.EvenPaddingDecorator
import com.jakewharton.rxbinding2.view.RxView
import kotlinx.android.synthetic.main.controller_transactions.view.*
import javax.inject.Inject
/**
* Created by williamgriffiths on 11/04/2017.
*/
class TransactionsController : BaseMvpControllerKotlin<TransactionsView, TransactionsPresenter>(),
TransactionsView {
override val mvpView: TransactionsView
get() = this
@Inject lateinit override var presenter: TransactionsPresenter
private val TRANSACTIONS_LIST_ITEM_TOP_BOTTOM_PADDING_DP = 16
private val TRANSACTIONS_LIST_ITEM_LEFT_RIGHT_PADDING_DP = 8
private val transactionsAdapter: TransactionsAdapter = TransactionsAdapter()
init {
injectPresenter()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View {
val view = container.inflate(R.layout.controller_transactions)
setNavigationToolbarListener()
bindViews(view)
setupTransactionsList(view)
return view
}
private fun bindViews(view: View) {
val clearTxsButton = view.controller_transactions_clear_transactions
val selectSearchRange = view.controller_transactions_search_in_range
presenter.setObservables(RxView.clicks(clearTxsButton), RxView.clicks(selectSearchRange))
}
private fun setNavigationToolbarListener() {
val navigationToolbarListener = targetController
if (navigationToolbarListener is NavigationToolbarListener) {
navigationToolbarListener.setToolbarTitle(applicationContext?.getString(R.string.controller_transactions_title) ?: "")
}
}
private fun setupTransactionsList(view: View) {
view.controller_transactions_recycler_view.apply {
layoutManager = LinearLayoutManager(applicationContext)
adapter = transactionsAdapter
addItemDecoration(EvenPaddingDecorator(TRANSACTIONS_LIST_ITEM_TOP_BOTTOM_PADDING_DP, TRANSACTIONS_LIST_ITEM_LEFT_RIGHT_PADDING_DP))
}
}
override fun addTransaction(transaction: DomainTransaction) {
transactionsAdapter.addTransaction(transaction)
}
override fun clearTransactions() {
transactionsAdapter.transactions = mutableListOf()
}
override fun displayRangeDialog() {
SelectBlockRangeAlertDialog(activity!!).show()
}
}
| apache-2.0 | 046d83423b52531c5615212ad721b989 | 41.518987 | 143 | 0.777612 | 4.946981 | false | false | false | false |
codebutler/odyssey | retrograde-app-shared/src/main/java/com/codebutler/retrograde/lib/storage/StorageProviderRegistry.kt | 1 | 1592 | /*
* GameLibraryProviderRegistry.kt
*
* Copyright (C) 2017 Retrograde Project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.codebutler.retrograde.lib.storage
import android.content.Context
import android.content.SharedPreferences
import com.codebutler.retrograde.lib.library.db.entity.Game
class StorageProviderRegistry(context: Context, val providers: Set<StorageProvider>) {
companion object {
const val PREF_NAME = "storage_providers"
}
private val providersByScheme = mapOf(*providers.map { provider ->
provider.uriSchemes.map { scheme ->
scheme to provider
}
}.flatten().toTypedArray())
private val prefs: SharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
val enabledProviders: Iterable<StorageProvider>
get() = providers.filter { prefs.getBoolean(it.id, it.enabledByDefault) }
fun getProvider(game: Game) = providersByScheme[game.fileUri.scheme]!!
}
| gpl-3.0 | 76c332a5c795f58ba5013349e6db4c18 | 35.181818 | 104 | 0.736181 | 4.349727 | false | false | false | false |
inorichi/tachiyomi-extensions | src/pt/mangayabu/src/eu/kanade/tachiyomi/extension/pt/mangayabu/MangaYabu.kt | 1 | 7507 | package eu.kanade.tachiyomi.extension.pt.mangayabu
import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.POST
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.FormBody
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Request
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import rx.Observable
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.concurrent.TimeUnit
class MangaYabu : ParsedHttpSource() {
// Hardcode the id because the language wasn't specific.
override val id: Long = 7152688036023311164
override val name = "MangaYabu!"
override val baseUrl = "https://mangayabu.top"
override val lang = "pt-BR"
override val supportsLatest = true
override val client: OkHttpClient = network.client.newBuilder()
.connectTimeout(2, TimeUnit.MINUTES)
.readTimeout(2, TimeUnit.MINUTES)
.writeTimeout(2, TimeUnit.MINUTES)
.addInterceptor(RateLimitInterceptor(1, 1, TimeUnit.SECONDS))
.build()
override fun headersBuilder(): Headers.Builder = Headers.Builder()
.add("User-Agent", USER_AGENT)
.add("Origin", baseUrl)
.add("Referer", baseUrl)
override fun popularMangaRequest(page: Int): Request = GET(baseUrl, headers)
override fun popularMangaSelector(): String = "#main div.row:contains(Populares) div.carousel div.card > a"
override fun popularMangaFromElement(element: Element): SManga = SManga.create().apply {
val tooltip = element.select("div.card-image.mango-hover").first()!!
title = Jsoup.parse(tooltip.attr("data-tooltip")).select("span b").first()!!.text()
thumbnail_url = element.select("img").first()!!.attr("src")
setUrlWithoutDomain(element.attr("href"))
}
override fun popularMangaNextPageSelector(): String? = null
override fun fetchLatestUpdates(page: Int): Observable<MangasPage> {
return super.fetchLatestUpdates(page)
.map { MangasPage(it.mangas.distinctBy { m -> m.url }, it.hasNextPage) }
}
override fun latestUpdatesRequest(page: Int): Request = GET(baseUrl, headers)
override fun latestUpdatesSelector() = "#main div.row:contains(Lançamentos) div.card"
override fun latestUpdatesFromElement(element: Element): SManga = SManga.create().apply {
title = element.select("div.card-content h4").first()!!.text().withoutFlags()
thumbnail_url = element.select("div.card-image img").first()!!.attr("src")
url = mapChapterToMangaUrl(element.select("div.card-image > a").first()!!.attr("href"))
}
override fun latestUpdatesNextPageSelector(): String? = null
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val form = FormBody.Builder()
.add("action", "data_fetch")
.add("search_keyword", query)
.build()
val newHeaders = headers.newBuilder()
.add("X-Requested-With", "XMLHttpRequest")
.add("Content-Length", form.contentLength().toString())
.add("Content-Type", form.contentType().toString())
.build()
return POST("$baseUrl/wp-admin/admin-ajax.php", newHeaders, form)
}
override fun searchMangaSelector() = "ul.popup-list div.row > div.col.s4 a.search-links"
override fun searchMangaFromElement(element: Element): SManga = SManga.create().apply {
val thumbnail = element.select("img").first()!!
title = thumbnail.attr("alt").withoutFlags()
thumbnail_url = thumbnail.attr("src")
setUrlWithoutDomain(element.attr("href"))
}
override fun searchMangaNextPageSelector(): String? = null
override fun mangaDetailsParse(document: Document): SManga {
val infoElement = document.select("div.manga-column")
return SManga.create().apply {
title = document.select("div.manga-info > h1").first()!!.text()
status = infoElement.select("div.manga-column:contains(Status:)").first()!!
.textWithoutLabel()
.toStatus()
genre = infoElement.select("div.manga-column:contains(Gêneros:)").first()!!
.textWithoutLabel()
description = document.select("div.manga-info").first()!!.text()
.substringAfter(title)
.trim()
thumbnail_url = document.select("div.manga-index div.mango-hover img")!!
.attr("src")
}
}
override fun chapterListSelector() = "div.manga-info:contains(Capítulos) div.manga-chapters div.single-chapter"
override fun chapterFromElement(element: Element): SChapter = SChapter.create().apply {
name = element.select("a").first()!!.text().substringAfter("–").trim()
date_upload = element.select("small")!!.text().toDate()
setUrlWithoutDomain(element.select("a").first()!!.attr("href"))
}
override fun pageListParse(document: Document): List<Page> {
return document.select("div.image-navigator img.slideit")
.mapIndexed { i, element ->
Page(i, document.location(), element.attr("abs:src"))
}
}
override fun imageUrlParse(document: Document) = ""
override fun imageRequest(page: Page): Request {
val newHeaders = headersBuilder()
.set("Referer", page.url)
.build()
return GET(page.imageUrl!!, newHeaders)
}
/**
* Some mangas doesn't use the same slug from the chapter url, and
* since the site doesn't have a proper popular list yet, we have
* to deal with some exceptions and map them to the correct
* slug manually.
*
* It's a bad solution, but it's a working one for now.
*/
private fun mapChapterToMangaUrl(chapterUrl: String): String {
val chapterSlug = chapterUrl
.substringBefore("-capitulo")
.substringAfter("ler/")
return "/manga/" + (SLUG_EXCEPTIONS[chapterSlug] ?: chapterSlug)
}
private fun String.toDate(): Long {
return try {
DATE_FORMATTER.parse(this)?.time ?: 0L
} catch (e: ParseException) {
0L
}
}
private fun String.toStatus() = when (this) {
"Em lançamento" -> SManga.ONGOING
"Completo" -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
private fun String.withoutFlags(): String = replace(FLAG_REGEX, "").trim()
private fun Element.textWithoutLabel(): String = text()!!.substringAfter(":").trim()
companion object {
private const val USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36"
private val FLAG_REGEX = "\\((Pt[-/]br|Scan)\\)".toRegex(RegexOption.IGNORE_CASE)
private val DATE_FORMATTER by lazy { SimpleDateFormat("dd/MM/yy", Locale.ENGLISH) }
private val SLUG_EXCEPTIONS = mapOf(
"the-promised-neverland-yakusoku-no-neverland" to "yakusoku-no-neverland-the-promised-neverland"
)
}
}
| apache-2.0 | 8a5afd16703049e107831f781b756c86 | 37.076142 | 115 | 0.656312 | 4.288736 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/dashboard/user/UserFragment.kt | 1 | 17318 | package com.intfocus.template.dashboard.user
import android.app.Activity.RESULT_CANCELED
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Typeface
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.support.v4.content.FileProvider
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.RelativeLayout
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.BitmapImageViewTarget
import com.google.gson.Gson
import com.intfocus.template.ConfigConstants
import com.intfocus.template.R
import com.intfocus.template.constant.Params.USER_BEAN
import com.intfocus.template.constant.Params.USER_NUM
import com.intfocus.template.constant.ToastColor
import com.intfocus.template.dashboard.feedback.FeedbackActivity
import com.intfocus.template.dashboard.mine.activity.AlterPasswordActivity
import com.intfocus.template.dashboard.mine.activity.FavoriteArticleActivity
import com.intfocus.template.dashboard.mine.activity.SettingActivity
import com.intfocus.template.dashboard.mine.activity.ShowPushMessageActivity
import com.intfocus.template.general.net.ApiException
import com.intfocus.template.general.net.CodeHandledSubscriber
import com.intfocus.template.general.net.RetrofitUtil
import com.intfocus.template.login.LoginActivity
import com.intfocus.template.model.response.login.RegisterResult
import com.intfocus.template.model.response.mine_page.UserInfoResult
import com.intfocus.template.subject.one.UserContract
import com.intfocus.template.subject.one.UserImpl
import com.intfocus.template.subject.one.UserPresenter
import com.intfocus.template.ui.BaseFragment
import com.intfocus.template.util.ActionLogUtil
import com.intfocus.template.util.DisplayUtil
import com.intfocus.template.util.ImageUtil.*
import com.intfocus.template.util.PageLinkManage
import com.intfocus.template.util.ToastUtils
import kotlinx.android.synthetic.main.activity_dashboard.*
import kotlinx.android.synthetic.main.fragment_user.*
import kotlinx.android.synthetic.main.item_mine_user_top.*
import kotlinx.android.synthetic.main.items_single_value.*
import kotlinx.android.synthetic.main.yh_custom_user.*
import java.io.File
/**
* Created by liuruilin on 2017/6/7.
*/
class UserFragment : BaseFragment(), UserContract.View {
override lateinit var presenter: UserContract.Presenter
lateinit var mUserInfoSP: SharedPreferences
lateinit var mUserSP: SharedPreferences
var rootView: View? = null
var gson = Gson()
var userNum: String? = null
/* 请求识别码 */
private val CODE_GALLERY_REQUEST = 0xa0
private val CODE_CAMERA_REQUEST = 0xa1
private val CODE_RESULT_REQUEST = 0xa2
private var rl_logout_confirm: RelativeLayout? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
UserPresenter(UserImpl.getInstance(), this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
mUserSP = ctx.getSharedPreferences(USER_BEAN, Context.MODE_PRIVATE)
if (rootView == null) {
rootView = inflater.inflate(R.layout.fragment_user, container, false)
presenter.loadData(ctx)
}
return rootView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val mTypeFace = Typeface.createFromAsset(ctx.assets, "ALTGOT2N.TTF")
tv_login_number.typeface = mTypeFace
tv_report_number.typeface = mTypeFace
tv_beyond_number.typeface = mTypeFace
initView()
initShow()
}
override fun onResume() {
super.onResume()
if (ConfigConstants.USER_CUSTOM) {
refreshData()
}
}
fun initView() {
userNum = activity!!.getSharedPreferences(USER_BEAN, Context.MODE_PRIVATE).getString(USER_NUM, "")
requestUserData()
iv_user_icon.setOnClickListener {
if (ConfigConstants.HEAD_ICON_UPLOAD_SUPPORT) {
showIconSelectPopWindow()
}
}
rl_password_alter.setOnClickListener { startPassWordAlterActivity() }
rl_issue.setOnClickListener { startIssueActivity() }
rl_setting.setOnClickListener { startSettingActivity() }
rl_favorite.setOnClickListener { startFavoriteActivity() }
rl_message.setOnClickListener { startMessageActivity() }
rl_logout.setOnClickListener { showLogoutPopupWindow() }
rl_user_location.setOnClickListener {
if (ConfigConstants.USER_GROUP_CONTENT) {
startUserLocationPage()
}
}
}
private fun requestUserData() {
RetrofitUtil.getHttpService(ctx).getUserInfo(userNum)
.compose(RetrofitUtil.CommonOptions<UserInfoResult>())
.subscribe(object : CodeHandledSubscriber<UserInfoResult>() {
override fun onError(apiException: ApiException?) {
ToastUtils.show(ctx, apiException!!.displayMessage)
}
override fun onBusinessNext(mUserInfo: UserInfoResult?) {
tv_user_name.text = mUserInfo!!.data!!.user_name
tv_user_role.text = mUserInfo.data!!.role_name
tv_mine_user_num_value.text = mUserInfo.data!!.user_num
tv_mine_user_group_value.text = mUserInfo.data!!.group_name
Glide.with(ctx)
.load(mUserInfo.data!!.gravatar)
.asBitmap()
.placeholder(R.drawable.face_default)
.error(R.drawable.face_default)
.override(DisplayUtil.dip2px(ctx, 60f), DisplayUtil.dip2px(ctx, 60f))
.into(object : BitmapImageViewTarget(iv_user_icon) {
override fun setResource(resource: Bitmap?) {
val circularBitmapDrawable = RoundedBitmapDrawableFactory.create(ctx.resources, resource)
circularBitmapDrawable.isCircular = true
iv_user_icon.setImageDrawable(circularBitmapDrawable)
}
})
}
override fun onCompleted() {
}
})
}
private fun initShow() {
setViewVisible(ll_single_value, ConfigConstants.USER_CUSTOM)
// setViewVisible(ll_yh_custom_user, ConfigConstants.USER_CUSTOM)
setViewVisible(rl_favorite, ConfigConstants.USER_CUSTOM)
// setViewVisible(rl_message, ConfigConstants.USER_CUSTOM)
setViewVisible(rl_password_alter, ConfigConstants.USER_CUSTOM)
setViewVisible(iv_mine_user_group_arrow, ConfigConstants.USER_GROUP_CONTENT)
}
private fun setViewVisible(view: View, show: Boolean) {
if (show) {
view.visibility = View.VISIBLE
} else {
view.visibility = View.GONE
}
}
private fun refreshData() {
RetrofitUtil.getHttpService(ctx).getUserInfo(userNum)
.compose(RetrofitUtil.CommonOptions<UserInfoResult>())
.subscribe(object : CodeHandledSubscriber<UserInfoResult>() {
override fun onError(apiException: ApiException?) {
ToastUtils.show(ctx, apiException!!.displayMessage)
}
override fun onBusinessNext(mUserInfo: UserInfoResult?) {
tv_login_number.text = mUserInfo!!.data!!.login_duration
tv_report_number.text = mUserInfo.data!!.browse_report_count
tv_beyond_number.text = mUserInfo.data!!.surpass_percentage.toString()
}
override fun onCompleted() {
}
})
}
override fun dataLoaded(data: UserInfoResult) {
val user = data.data
tv_user_name.text = user!!.user_name
tv_login_number.text = user.login_duration
tv_report_number.text = user.browse_report_count
tv_mine_user_num_value.text = user.user_num
tv_beyond_number.text = user.surpass_percentage.toString()
tv_user_role.text = user.role_name
tv_mine_user_group_value.text = user.group_name
Glide.with(ctx)
.load(user.gravatar)
.asBitmap()
.placeholder(R.drawable.face_default)
.error(R.drawable.face_default)
.override(DisplayUtil.dip2px(ctx, 60f), DisplayUtil.dip2px(ctx, 60f))
.into(object : BitmapImageViewTarget(iv_user_icon) {
override fun setResource(resource: Bitmap?) {
val circularBitmapDrawable = RoundedBitmapDrawableFactory.create(ctx.resources, resource)
circularBitmapDrawable.isCircular = true
iv_user_icon.setImageDrawable(circularBitmapDrawable)
}
})
}
private fun startPassWordAlterActivity() {
val intent = Intent(ctx, AlterPasswordActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
startActivity(intent)
ActionLogUtil.actionLog("点击/个人信息/修改密码")
}
private fun startFavoriteActivity() {
val intent = Intent(activity, FavoriteArticleActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
startActivity(intent)
}
private fun startMessageActivity() {
val intent = Intent(activity, ShowPushMessageActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
startActivity(intent)
}
private fun startIssueActivity() {
val intent = Intent(activity, FeedbackActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
startActivity(intent)
}
private fun startSettingActivity() {
val intent = Intent(activity, SettingActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
startActivity(intent)
}
private fun startUserLocationPage() {
RetrofitUtil.getHttpService(ctx).getRegister("sypc_000103")
.compose(RetrofitUtil.CommonOptions())
.subscribe(object : CodeHandledSubscriber<RegisterResult>() {
override fun onError(apiException: ApiException) {
ToastUtils.show(ctx, "功能开发中")
}
override fun onBusinessNext(data: RegisterResult) {
if (data.data!!.contains("http")) {
PageLinkManage.pageLink(ctx!!, "归属部门", data.data!!)
} else {
ToastUtils.show(ctx, data.data!!)
}
}
override fun onCompleted() {}
})
}
/**
* 退出登录选择窗
*/
private fun showLogoutPopupWindow() {
val contentView = LayoutInflater.from(ctx).inflate(R.layout.popup_logout, null)
//设置弹出框的宽度和高度
val popupWindow = PopupWindow(contentView,
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
popupWindow.isFocusable = true// 取得焦点
//注意 要是点击外部空白处弹框消息 那么必须给弹框设置一个背景色 不然是不起作用的
popupWindow.setBackgroundDrawable(BitmapDrawable())
//点击外部消失
popupWindow.isOutsideTouchable = true
//设置可以点击
popupWindow.isTouchable = true
popupWindow.animationStyle = R.style.anim_popup_bottombar
popupWindow.showAtLocation(this.view, Gravity.BOTTOM, 0, contentView.height)
rl_logout_confirm = contentView.findViewById(R.id.rl_logout_confirm)
rl_logout_confirm!!.setOnClickListener {
// 取消
popupWindow.dismiss()
// 确认退出
presenter.logout(ctx)
}
contentView.findViewById<RelativeLayout>(R.id.rl_cancel).setOnClickListener {
// 取消
popupWindow.dismiss()
}
contentView.findViewById<RelativeLayout>(R.id.rl_popup_logout_background).setOnClickListener {
// 点击背景半透明区域
popupWindow.dismiss()
}
}
/**
* 退出登录成功
*/
override fun logoutSuccess() {
val intent = Intent(activity, LoginActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK and Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(intent)
RetrofitUtil.destroyInstance()
activity!!.finish()
}
/**
* 吐司错误信息
*/
override fun showErrorMsg(errorMsg: String) {
ToastUtils.show(ctx, errorMsg)
}
/**
* 吐司成功信息
*/
override fun showSuccessMsg(msg: String) {
ToastUtils.show(ctx, msg, ToastColor.SUCCESS)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
// 用户没有选择图片,返回
if (resultCode == RESULT_CANCELED) {
ToastUtils.show(ctx, "取消")
return
}
when (requestCode) {
CODE_GALLERY_REQUEST -> {
val cropIntent = launchSystemImageCrop(ctx, data!!.data)
startActivityForResult(cropIntent, CODE_RESULT_REQUEST)
}
CODE_CAMERA_REQUEST -> {
val cropIntent: Intent
val tempFile = File(Environment.getExternalStorageDirectory(), "icon.jpg")
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val photoURI = FileProvider.getUriForFile(ctx,
"com.intfocus.template.fileprovider",
tempFile)
cropIntent = launchSystemImageCrop(ctx, photoURI)
} else {
cropIntent = launchSystemImageCrop(ctx, Uri.fromFile(tempFile))
}
startActivityForResult(cropIntent, CODE_RESULT_REQUEST)
}
else -> {
}
}
if (data != null) {
setImageToHeadView()
}
super.onActivityResult(requestCode, resultCode, data)
}
/**
* 显示头像选择菜单
*/
private fun showIconSelectPopWindow() {
val contentView = LayoutInflater.from(ctx).inflate(R.layout.popup_mine_icon_select, null)
//设置弹出框的宽度和高度
val popupWindow = PopupWindow(contentView,
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT)
popupWindow.isFocusable = true// 取得焦点
//注意 要是点击外部空白处弹框消息 那么必须给弹框设置一个背景色 不然是不起作用的
// todo bug 验证最新bitmap 创建
popupWindow.setBackgroundDrawable(BitmapDrawable())
//点击外部消失
popupWindow.isOutsideTouchable = true
//设置可以点击
popupWindow.isTouchable = true
popupWindow.showAtLocation(activity!!.toolBar, Gravity.BOTTOM, 0, 0)
contentView.findViewById<RelativeLayout>(R.id.rl_camera).setOnClickListener {
// 打开相机
startActivityForResult(launchCamera(ctx), CODE_CAMERA_REQUEST)
popupWindow.dismiss()
}
contentView.findViewById<RelativeLayout>(R.id.rl_gallery).setOnClickListener {
// 打开相册
startActivityForResult(getGallery(), CODE_GALLERY_REQUEST)
popupWindow.dismiss()
}
contentView.findViewById<RelativeLayout>(R.id.rl_cancel).setOnClickListener {
// 取消
popupWindow.dismiss()
}
contentView.findViewById<RelativeLayout>(R.id.rl_popup_icon_background).setOnClickListener {
// 点击背景半透明区域
popupWindow.dismiss()
}
ActionLogUtil.actionLog("点击/个人信息/设置头像")
}
/**
* 提取保存裁剪之后的图片数据,并设置头像部分的View
*/
private fun setImageToHeadView() {
val imgPath = Environment.getExternalStorageDirectory().toString() + "/icon.jpg"
val bitmap = BitmapFactory.decodeFile(imgPath)
if (bitmap != null) {
iv_user_icon.setImageBitmap(makeRoundCorner(bitmap))
presenter.uploadUserIcon(ctx, bitmap, imgPath)
}
}
}
| gpl-3.0 | 93f51a91a5036629dd0690ddbfb1a583 | 38.654846 | 129 | 0.629784 | 4.637545 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/query/s9api/binding/XdmEmptySequence.kt | 1 | 1043 | /*
* Copyright (C) 2019 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding
object XdmEmptySequence {
private var instance: XdmValue? = null
fun getInstance(classLoader: ClassLoader): XdmValue {
if (instance == null) {
val `class` = classLoader.loadClass("net.sf.saxon.s9api.XdmEmptySequence")
instance = XdmValue(`class`.getMethod("getInstance").invoke(null), `class`)
}
return instance!!
}
}
| apache-2.0 | 4c038ea296add339c2ec6d8932d4a0bc | 36.25 | 87 | 0.704698 | 4.090196 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/presentation/course_revenue/reducer/CourseBenefitsMonthlyReducer.kt | 1 | 3208 | package org.stepik.android.presentation.course_revenue.reducer
import org.stepik.android.domain.course_revenue.model.CourseBenefitByMonthListItem
import org.stepik.android.presentation.course_revenue.CourseBenefitsMonthlyFeature.State
import org.stepik.android.presentation.course_revenue.CourseBenefitsMonthlyFeature.Message
import org.stepik.android.presentation.course_revenue.CourseBenefitsMonthlyFeature.Action
import ru.nobird.android.core.model.concatWithPagedList
import ru.nobird.android.presentation.redux.reducer.StateReducer
import javax.inject.Inject
class CourseBenefitsMonthlyReducer
@Inject
constructor() : StateReducer<State, Message, Action> {
override fun reduce(state: State, message: Message): Pair<State, Set<Action>> =
when (message) {
is Message.FetchCourseBenefitsByMonthsSuccess -> {
when (state) {
is State.Loading -> {
val courseBenefitsMonthlyState =
if (message.courseBenefitByMonthListDataItems.isEmpty()) {
State.Empty
} else {
State.Content(message.courseBenefitByMonthListDataItems, message.courseBenefitByMonthListDataItems)
}
courseBenefitsMonthlyState to emptySet()
}
is State.Content -> {
val resultingList = state.courseBenefitByMonthListDataItems.concatWithPagedList(message.courseBenefitByMonthListDataItems)
state.copy(courseBenefitByMonthListDataItems = resultingList, courseBenefitByMonthListItems = resultingList) to emptySet()
}
else ->
null
}
}
is Message.FetchCourseBenefitsByMonthsFailure -> {
when (state) {
is State.Loading ->
State.Error to emptySet()
is State.Content ->
state to emptySet()
else ->
null
}
}
is Message.FetchCourseBenefitsByMonthNext -> {
if (state is State.Content) {
if (state.courseBenefitByMonthListDataItems.hasNext && state.courseBenefitByMonthListItems.last() !is CourseBenefitByMonthListItem.Placeholder) {
state.copy(courseBenefitByMonthListItems = state.courseBenefitByMonthListItems + CourseBenefitByMonthListItem.Placeholder) to
setOf(Action.FetchCourseBenefitsByMonths(message.courseId, state.courseBenefitByMonthListDataItems.page + 1))
} else {
null
}
} else {
null
}
}
is Message.TryAgain -> {
if (state is State.Error) {
State.Loading to setOf(Action.FetchCourseBenefitsByMonths(message.courseId))
} else {
null
}
}
} ?: state to emptySet()
} | apache-2.0 | 93090d2395e3532ea3498619689a6fb6 | 46.895522 | 165 | 0.573254 | 5.832727 | false | false | false | false |
robfletcher/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/CompleteTaskHandlerTest.kt | 1 | 13081 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spectator.api.NoopRegistry
import com.netflix.spinnaker.orca.DefaultStageResolver
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.CANCELED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.FAILED_CONTINUE
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.NOT_STARTED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.REDIRECT
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SKIPPED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.STOPPED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.api.pipeline.models.TaskExecution
import com.netflix.spinnaker.orca.api.test.pipeline
import com.netflix.spinnaker.orca.api.test.stage
import com.netflix.spinnaker.orca.events.TaskComplete
import com.netflix.spinnaker.orca.pipeline.DefaultStageDefinitionBuilderFactory
import com.netflix.spinnaker.orca.pipeline.model.TaskExecutionImpl
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor
import com.netflix.spinnaker.orca.q.CompleteStage
import com.netflix.spinnaker.orca.q.CompleteTask
import com.netflix.spinnaker.orca.q.RunTask
import com.netflix.spinnaker.orca.q.SkipStage
import com.netflix.spinnaker.orca.q.StageDefinitionBuildersProvider
import com.netflix.spinnaker.orca.q.StartTask
import com.netflix.spinnaker.orca.q.buildTasks
import com.netflix.spinnaker.orca.q.get
import com.netflix.spinnaker.orca.q.multiTaskStage
import com.netflix.spinnaker.orca.q.rollingPushStage
import com.netflix.spinnaker.orca.q.singleTaskStage
import com.netflix.spinnaker.q.Queue
import com.netflix.spinnaker.spek.and
import com.netflix.spinnaker.time.fixedClock
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.check
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.verifyZeroInteractions
import com.nhaarman.mockito_kotlin.whenever
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP
import org.jetbrains.spek.subject.SubjectSpek
import org.springframework.context.ApplicationEventPublisher
object CompleteTaskHandlerTest : SubjectSpek<CompleteTaskHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val publisher: ApplicationEventPublisher = mock()
val clock = fixedClock()
val stageResolver = DefaultStageResolver(StageDefinitionBuildersProvider(emptyList()))
subject(GROUP) {
CompleteTaskHandler(queue, repository, DefaultStageDefinitionBuilderFactory(stageResolver), ContextParameterProcessor(), publisher, clock, NoopRegistry())
}
fun resetMocks() = reset(queue, repository, publisher)
setOf(SUCCEEDED, SKIPPED).forEach { successfulStatus ->
describe("when a task completes with $successfulStatus status") {
given("the stage contains further tasks") {
val pipeline = pipeline {
stage {
type = multiTaskStage.type
multiTaskStage.buildTasks(this)
}
}
val message = CompleteTask(
pipeline.type,
pipeline.id,
pipeline.application,
pipeline.stages.first().id,
"1",
successfulStatus,
successfulStatus
)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the task state in the stage") {
verify(repository).storeStage(
check {
it.tasks.first().apply {
assertThat(status).isEqualTo(successfulStatus)
assertThat(endTime).isEqualTo(clock.millis())
}
}
)
}
it("runs the next task") {
verify(queue)
.push(
StartTask(
message.executionType,
message.executionId,
message.application,
message.stageId,
"2"
)
)
}
it("publishes an event") {
verify(publisher).publishEvent(
check<TaskComplete> {
assertThat(it.executionType).isEqualTo(pipeline.type)
assertThat(it.executionId).isEqualTo(pipeline.id)
assertThat(it.stageId).isEqualTo(message.stageId)
assertThat(it.taskId).isEqualTo(message.taskId)
assertThat(it.status).isEqualTo(successfulStatus)
}
)
}
}
given("the stage is complete") {
val pipeline = pipeline {
stage {
type = singleTaskStage.type
singleTaskStage.buildTasks(this)
}
}
val message = CompleteTask(
pipeline.type,
pipeline.id,
pipeline.application,
pipeline.stages.first().id,
"1",
SUCCEEDED,
SUCCEEDED
)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the task state in the stage") {
verify(repository).storeStage(
check {
it.tasks.last().apply {
assertThat(status).isEqualTo(SUCCEEDED)
assertThat(endTime).isEqualTo(clock.millis())
}
}
)
}
it("emits an event to signal the stage is complete") {
verify(queue)
.push(
CompleteStage(
message.executionType,
message.executionId,
message.application,
message.stageId
)
)
}
}
given("the task is the end of a rolling push loop") {
val pipeline = pipeline {
stage {
refId = "1"
type = rollingPushStage.type
rollingPushStage.buildTasks(this)
}
}
and("when the task returns REDIRECT") {
val message = CompleteTask(
pipeline.type,
pipeline.id,
pipeline.application,
pipeline.stageByRef("1").id,
"4",
REDIRECT,
REDIRECT
)
beforeGroup {
pipeline.stageByRef("1").apply {
tasks[0].status = SUCCEEDED
tasks[1].status = SUCCEEDED
tasks[2].status = SUCCEEDED
}
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("repeats the loop") {
verify(queue).push(
check<StartTask> {
assertThat(it.taskId).isEqualTo("2")
}
)
}
it("resets the status of the loop tasks") {
verify(repository).storeStage(
check {
assertThat(it.tasks[1..3].map(TaskExecution::getStatus)).allMatch { it == NOT_STARTED }
}
)
}
it("does not publish an event") {
verifyZeroInteractions(publisher)
}
}
}
}
}
setOf(TERMINAL, CANCELED, STOPPED).forEach { status ->
describe("when a task completes with $status status") {
val pipeline = pipeline {
stage {
type = multiTaskStage.type
multiTaskStage.buildTasks(this)
}
}
val message = CompleteTask(
pipeline.type,
pipeline.id,
pipeline.application,
pipeline.stages.first().id,
"1",
status,
status
)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the task state in the stage") {
verify(repository).storeStage(
check {
it.tasks.first().apply {
assertThat(status).isEqualTo(status)
assertThat(endTime).isEqualTo(clock.millis())
}
}
)
}
it("fails the stage") {
verify(queue).push(
CompleteStage(
message.executionType,
message.executionId,
message.application,
message.stageId
)
)
}
it("does not run the next task") {
verify(queue, never()).push(any<RunTask>())
}
it("publishes an event") {
verify(publisher).publishEvent(
check<TaskComplete> {
assertThat(it.executionType).isEqualTo(pipeline.type)
assertThat(it.executionId).isEqualTo(pipeline.id)
assertThat(it.stageId).isEqualTo(message.stageId)
assertThat(it.taskId).isEqualTo(message.taskId)
assertThat(it.status).isEqualTo(status)
}
)
}
}
}
describe("when a task should complete parent stage") {
val task = fun(isStageEnd: Boolean): TaskExecution {
val task = TaskExecutionImpl()
task.isStageEnd = isStageEnd
return task
}
it("is last task in stage") {
subject.shouldCompleteStage(task(true), SUCCEEDED, SUCCEEDED) == true
subject.shouldCompleteStage(task(false), SUCCEEDED, SUCCEEDED) == false
}
it("did not originally complete with FAILED_CONTINUE") {
subject.shouldCompleteStage(task(false), TERMINAL, TERMINAL) == true
subject.shouldCompleteStage(task(false), FAILED_CONTINUE, TERMINAL) == true
subject.shouldCompleteStage(task(false), FAILED_CONTINUE, FAILED_CONTINUE) == false
}
}
describe("manual skip behavior") {
given("a stage with a manual skip flag") {
val pipeline = pipeline {
stage {
refId = "1"
type = singleTaskStage.type
singleTaskStage.buildTasks(this)
context["manualSkip"] = true
}
}
val message = CompleteTask(
pipeline.type,
pipeline.id,
pipeline.application,
pipeline.stageByRef("1").id,
"1",
SKIPPED,
SKIPPED
)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("skips the stage") {
verify(queue).push(SkipStage(pipeline.stageByRef("1")))
}
}
given("a stage whose parent has a manual skip flag") {
val pipeline = pipeline {
stage {
refId = "1"
type = singleTaskStage.type
singleTaskStage.buildTasks(this)
context["manualSkip"] = true
stage {
refId = "1<1"
type = singleTaskStage.type
singleTaskStage.buildTasks(this)
}
}
}
val message = CompleteTask(
pipeline.type,
pipeline.id,
pipeline.application,
pipeline.stageByRef("1<1").id,
"1",
SKIPPED,
SKIPPED
)
beforeGroup {
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("skips the parent stage") {
verify(queue).push(SkipStage(pipeline.stageByRef("1")))
}
}
}
})
| apache-2.0 | 49e0fd32d9ad0ab8a9d1a9973092fc0c | 29.99763 | 158 | 0.622353 | 4.791575 | false | false | false | false |
MarkNKamau/JustJava-Android | app/src/main/java/com/marknkamau/justjava/ui/addressBook/AddressBookViewModel.kt | 1 | 1771 | package com.marknkamau.justjava.ui.addressBook
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.marknjunge.core.data.model.Address
import com.marknjunge.core.data.model.Resource
import com.marknjunge.core.data.model.User
import com.marknjunge.core.data.repository.UsersRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class AddressBookViewModel @Inject constructor(private val usersRepository: UsersRepository) : ViewModel() {
private val _loading = MutableLiveData<Boolean>()
val loading: LiveData<Boolean> = _loading
private val _user = MutableLiveData<Resource<User>>()
val user: LiveData<Resource<User>> = _user
fun getAddresses() {
viewModelScope.launch {
_loading.value = true
usersRepository.getCurrentUser().collect { _user.value = it }
_loading.value = false
}
}
fun addAddress(address: Address): LiveData<Resource<Address>> {
val liveData = MutableLiveData<Resource<Address>>()
viewModelScope.launch {
_loading.value = true
liveData.value = usersRepository.addAddress(address)
_loading.value = false
}
return liveData
}
fun deleteAddress(address: Address): LiveData<Resource<Unit>> {
val livedata = MutableLiveData<Resource<Unit>>()
viewModelScope.launch {
_loading.value = true
livedata.value = usersRepository.deleteAddress(address)
_loading.value = false
}
return livedata
}
}
| apache-2.0 | 6d4b32838c7129bb7391f801ae65088e | 31.2 | 108 | 0.702993 | 4.672823 | false | false | false | false |
GDGLima/CodeLab-Kotlin-Infosoft-2017 | Infosoft2017/app/src/main/java/com/emedinaa/infosoft2017/ui/adapterskt/EventAdapterK.kt | 1 | 1811 | package com.emedinaa.infosoft2017.ui.adapterskt
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.emedinaa.infosoft2017.R
import com.emedinaa.infosoft2017.helpers.formatDate
import com.emedinaa.infosoft2017.model.EntityK
import kotlinx.android.synthetic.main.row_event.view.*
/**
* Created by emedinaa on 3/09/17.
*/
class EventAdapterK(val events:List<EntityK.EventK>, val context: Context): RecyclerView.Adapter<EventAdapterK.ViewHolder>() {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val textViewHour: TextView = view.textViewHour
val textViewTitle: TextView = view.textViewTitle
val textSpeaker: TextView = view.textSpeaker
val textViewDate: TextView = view.textViewDate
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
return ViewHolder(layoutInflater.inflate(R.layout.row_event, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val title: String = events[position].titulo!!
val sb = StringBuilder()
sb.append(events[position].horario_inicio).append("-").append(events[position].horario_fin)
val hour: String? = sb.toString()
val speaker:String=events[position].expositor_nombre
val date:String =events[position].fecha
holder.textViewHour.text = hour
holder.textViewTitle.text = title
holder.textSpeaker.text = speaker
holder.textViewDate.text = formatDate(date)
}
override fun getItemCount(): Int {
return events.size
}
} | apache-2.0 | 715bb7333631e9ea77f30a5c0ad1e9c5 | 35.24 | 126 | 0.729431 | 4.221445 | false | false | false | false |
square/wire | wire-library/wire-gson-support/src/main/java/com/squareup/wire/MessageTypeAdapter.kt | 1 | 2812 | /*
* Copyright 2013 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import com.squareup.wire.internal.FieldOrOneOfBinding
import com.squareup.wire.internal.RuntimeMessageAdapter
import java.io.IOException
internal class MessageTypeAdapter<M : Message<M, B>, B : Message.Builder<M, B>>(
private val messageAdapter: RuntimeMessageAdapter<M, B>,
private val jsonAdapters: List<TypeAdapter<Any?>>
) : TypeAdapter<M>() {
private val nameToField = mutableMapOf<String, JsonField<M, B>>()
.also { map ->
for (index in jsonAdapters.indices) {
val fieldBinding = messageAdapter.fieldBindingsArray[index]
val jsonField = JsonField(jsonAdapters[index], fieldBinding)
map[messageAdapter.jsonNames[index]] = jsonField
val alternateName = messageAdapter.jsonAlternateNames[index]
if (alternateName != null) {
map[alternateName] = jsonField
}
}
}
@Throws(IOException::class)
override fun write(out: JsonWriter, message: M?) {
out.beginObject()
messageAdapter.writeAllFields(
message = message,
jsonAdapters = jsonAdapters,
redactedFieldsAdapter = null
) { name, value, jsonAdapter ->
out.name(name)
jsonAdapter.write(out, value)
}
out.endObject()
}
@Throws(IOException::class)
override fun read(input: JsonReader): M {
val builder = messageAdapter.newBuilder()
input.beginObject()
while (input.hasNext()) {
val name = input.nextName()
val jsonField = nameToField[name]
if (jsonField == null) {
input.skipValue()
continue
}
val value = jsonField.adapter.read(input)
// "If a value is missing in the JSON-encoded data or if its value is null, it will be
// interpreted as the appropriate default value when parsed into a protocol buffer."
if (value == null) continue
jsonField.fieldBinding.set(builder, value)
}
input.endObject()
return builder.build()
}
data class JsonField<M : Message<M, B>, B : Message.Builder<M, B>>(
val adapter: TypeAdapter<Any?>,
val fieldBinding: FieldOrOneOfBinding<M, B>
)
}
| apache-2.0 | df6bbc4d778d7cd2a56d7191e6c1d7e8 | 32.47619 | 92 | 0.694879 | 4.123167 | false | false | false | false |
realm/realm-java | realm/realm-annotations-processor/src/main/java/io/realm/processor/nameconverter/PascalCaseConverter.kt | 1 | 1232 | /*
* Copyright 2018 Realm 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 io.realm.processor.nameconverter
/**
* Converter that converts input to "PascalCase".
*/
class PascalCaseConverter : NameConverter {
private val tokenizer = WordTokenizer()
override fun convert(name: String): String {
val words = tokenizer.split(name)
val output = StringBuilder()
for (i in words.indices) {
val word = words[i].toLowerCase()
val codepoint = word.codePointAt(0)
output.appendCodePoint(Character.toUpperCase(codepoint))
output.append(word.substring(Character.charCount(codepoint)))
}
return output.toString()
}
}
| apache-2.0 | 025114f43b47d18aeb21ab55b195fc49 | 32.297297 | 75 | 0.693182 | 4.384342 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/host/ArcHostContextParticle.kt | 1 | 10851 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.host
import arcs.core.common.toArcId
import arcs.core.data.Annotation
import arcs.core.data.Capabilities
import arcs.core.data.Capability.Ttl
import arcs.core.data.CollectionType
import arcs.core.data.EntityType
import arcs.core.data.Plan
import arcs.core.data.Schema
import arcs.core.data.SchemaSerializer
import arcs.core.data.SingletonType
import arcs.core.data.expression.deserializeExpression
import arcs.core.data.expression.serialize
import arcs.core.data.toSchema
import arcs.core.entity.Reference
import arcs.core.host.api.Particle
import arcs.core.host.generated.AbstractArcHostContextParticle
import arcs.core.host.generated.ArcHostContextPlan
import arcs.core.storage.CapabilitiesResolver
import arcs.core.storage.StorageKeyManager
import arcs.core.type.Tag
import arcs.core.type.Type
import arcs.core.util.plus
import arcs.core.util.traverse
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.Job
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.withContext
typealias ArcHostContextParticle_HandleConnections = AbstractArcHostContextParticle.HandleConnection
typealias ArcHostContextParticle_Particles = AbstractArcHostContextParticle.ParticleSchema
typealias ArcHostContextParticle_PlanHandle = AbstractArcHostContextParticle.PlanHandle
/**
* An implicit [Particle] that lives within the [ArcHost] and used as a utility class to
* serialize/deserialize [ArcHostContext] information from [Plan.Handle]s. It does not live in an
* Arc or participate in normal [Particle] lifecycle.
*/
class ArcHostContextParticle(
private val hostId: String,
private val handleManager: HandleManager,
private val storageKeyManager: StorageKeyManager,
private val serializer: SchemaSerializer<String>
) : AbstractArcHostContextParticle() {
/**
* Given an [ArcHostContext], convert these types to Arc Schema types, and write them to the
* appropriate handles. See `ArcHostContext.arcs` for schema definitions.
*/
suspend fun writeArcHostContext(
context: arcs.core.host.ArcHostContext
) = onHandlesReady {
try {
handles.planHandles.clear()
val connections = context.particles.flatMap {
it.planParticle.handles.map { (handleName, handle) ->
val planHandle = ArcHostContextParticle_PlanHandle(
storageKey = handle.handle.storageKey.toString(),
type = handle.handle.type.tag.name,
schema = serializer.serialize(handle.handle.type.toSchema())
)
// Write Plan.Handle
handles.planHandles.store(planHandle).join()
ArcHostContextParticle_HandleConnections(
connectionName = handleName,
planHandle = handles.planHandles.createReference(planHandle),
storageKey = handle.storageKey.toString(),
mode = handle.mode.name, type = handle.type.tag.name,
ttl = handle.ttl.minutes.toDouble(),
expression = handle.expression?.serialize() ?: "",
schema = serializer.serialize(handle.type.toSchema())
)
}
}
// Write Plan.HandleConnection
handles.handleConnections.clear()
connections.map { handles.handleConnections.store(it) }.joinAll()
val particles = context.particles.map {
ArcHostContextParticle_Particles(
particleName = it.planParticle.particleName,
location = it.planParticle.location,
particleState = it.particleState.toString(),
consecutiveFailures = it.consecutiveFailureCount.toDouble(),
handles = connections.map { connection ->
handles.handleConnections.createReference(connection)
}.toSet()
)
}
// Write Plan.Particle + ParticleContext
handles.particles.clear()
particles.map { handles.particles.store(it) }.joinAll()
val arcHostContext = AbstractArcHostContextParticle.ArcHostContext(
arcId = context.arcId, hostId = hostId, arcState = context.arcState.toString(),
particles = particles.map { handles.particles.createReference(it) }.toSet()
)
handles.arcHostContext.clear()
handles.arcHostContext.store(arcHostContext).join()
} catch (e: Exception) {
// TODO: retry?
throw IllegalStateException("Unable to serialize ${context.arcId} for $hostId", e)
}
}
/**
* Reads [ArcHostContext] from serialized representation as Arcs Schema types. See
* `ArcHostContext.arcs' for Schema definitions. NOTE: This is more complex than it needs
* to be because references are not supported yet in schema2kotlin, and so this information
* is stored in de-normalized format.
*/
suspend fun readArcHostContext(
arcHostContext: arcs.core.host.ArcHostContext
): arcs.core.host.ArcHostContext? = onHandlesReady {
val arcId = arcHostContext.arcId
try {
// TODO(cromwellian): replace with .query(arcId, hostId) when queryHandles are efficient
val arcStateEntity = handles.arcHostContext.fetch()
?: return@onHandlesReady null
val particles = arcStateEntity.particles.map {
requireNotNull(it.dereference()) {
"Invalid particle reference when deserialising arc $arcId for host $hostId"
}
}.map { particleEntity ->
val handlesMap = createHandlesMap(
arcId,
particleEntity.particleName,
particleEntity.handles
)
ParticleContext(
Plan.Particle(particleEntity.particleName, particleEntity.location, handlesMap),
ParticleState.fromString(particleEntity.particleState),
particleEntity.consecutiveFailures.toInt()
)
}
return@onHandlesReady ArcHostContext(
arcId,
particles.toMutableList(),
initialArcState = ArcState.fromString(arcStateEntity.arcState)
)
} catch (e: Exception) {
throw IllegalStateException("Unable to deserialize $arcId for $hostId", e)
}
}
private suspend inline fun <T> onHandlesReady(
coroutineContext: CoroutineContext = handles.dispatcher,
crossinline block: suspend () -> T
): T {
val onReadyJobs = mapOf(
"particles" to Job(),
"arcHostContext" to Job(),
"handleConnections" to Job(),
"planHandles" to Job()
)
handles.particles.onReady { onReadyJobs["particles"]?.complete() }
handles.arcHostContext.onReady { onReadyJobs["arcHostContext"]?.complete() }
handles.handleConnections.onReady { onReadyJobs["handleConnections"]?.complete() }
handles.planHandles.onReady { onReadyJobs["planHandles"]?.complete() }
onReadyJobs.values.joinAll()
return withContext(coroutineContext) { block() }
}
suspend fun close() { handleManager.close() }
private suspend fun createHandlesMap(
arcId: String,
particleName: String,
handles: Set<Reference<ArcHostContextParticle_HandleConnections>>
) = handles.map { handle ->
requireNotNull(handle.dereference()) {
"HandleConnection couldn't be dereferenced for arcId $arcId, particle $particleName"
}
}.map { handle ->
val planHandle = requireNotNull(requireNotNull(handle.planHandle).dereference()) {
"PlanHandle couldn't be dereferenced for arcId $arcId, particle $handle.connectionName"
}
handle.connectionName to Plan.HandleConnection(
Plan.Handle(
storageKeyManager.parse(planHandle.storageKey),
fromTag(arcId, serializer.deserialize(planHandle.schema), planHandle.type),
emptyList()
),
HandleMode.valueOf(handle.mode),
fromTag(arcId, serializer.deserialize(handle.schema), handle.type),
if (handle.ttl != Ttl.TTL_INFINITE.toDouble()) {
listOf(Annotation.createTtl("$handle.ttl minutes"))
} else {
emptyList()
},
handle.expression.ifEmpty { null }?.let { it.deserializeExpression() }
)
}.toSet().associateBy({ it.first }, { it.second })
/**
* Using instantiated particle to obtain [Schema] objects through their
* associated [EntitySpec], reconstruct an associated [Type] object.
*/
fun fromTag(arcId: String, schema: Schema, tag: String): Type {
return when (Tag.valueOf(tag)) {
Tag.Singleton -> SingletonType(EntityType(schema))
Tag.Collection -> CollectionType(EntityType(schema))
Tag.Entity -> EntityType(schema)
else -> throw IllegalArgumentException(
"Illegal Tag $tag when deserializing ArcHostContext with ArcId '$arcId'"
)
}
}
/**
* When recipe2plan is finished, the 'Plan' to serialize/deserialize ArcHost information
* will be code-genned, and this method will mostly go away, in combination with
* the move away from denormalized schemas to schema definitions using references.
*/
fun createArcHostContextPersistencePlan(
capability: Capabilities,
arcId: String
): Plan.Partition {
val resolver = CapabilitiesResolver(
CapabilitiesResolver.Options(arcId.toArcId())
)
/*
* Because query() isn't efficient yet, we don't store all serializations under a
* single key in the recipe, but per-arcId.
* TODO: once efficient queries exist, remove and use recipe2plan key
*/
val arcHostContextKey = resolver.createStorageKey(
capability, EntityType(AbstractArcHostContextParticle.ArcHostContext.SCHEMA),
"${hostId}_arcState"
)
val particlesKey = resolver.createStorageKey(
capability, EntityType(ArcHostContextParticle_Particles.SCHEMA),
"${hostId}_arcState_particles"
)
val handleConnectionsKey = resolver.createStorageKey(
capability, EntityType(ArcHostContextParticle_HandleConnections.SCHEMA),
"${hostId}_arcState_handleConnections"
)
val planHandlesKey = resolver.createStorageKey(
capability, EntityType(ArcHostContextParticle_PlanHandle.SCHEMA),
"${hostId}_arcState_planHandles"
)
// replace keys with per-arc created ones.
val allStorageKeyLens = Plan.Particle.handlesLens.traverse() +
Plan.HandleConnection.handleLens + Plan.Handle.storageKeyLens
val particle = allStorageKeyLens.mod(ArcHostContextPlan.particles.first()) { storageKey ->
val keyString = storageKey.toKeyString()
when {
"arcHostContext" in keyString -> arcHostContextKey
"particles" in keyString -> particlesKey
"handleConnections" in keyString -> handleConnectionsKey
"planHandles" in keyString -> planHandlesKey
else -> storageKey
}
}
return Plan.Partition(arcId, hostId, listOf(particle))
}
}
| bsd-3-clause | 7957145f2fed718cd437f1b7180664f5 | 38.032374 | 100 | 0.709612 | 4.661082 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/core/host/NoOpArcHost.kt | 1 | 1247 | package arcs.core.host
import arcs.core.common.ArcId
import arcs.core.data.Plan
/** Fake [ArcHost] used in Tests */
class NoOpArcHost(override val hostId: String) : ArcHost {
/** Property used to test [pause] and [unpause] methods. */
var isPaused = false
override suspend fun registeredParticles(): List<ParticleIdentifier> = emptyList()
override suspend fun startArc(partition: Plan.Partition) = Unit
override suspend fun stopArc(partition: Plan.Partition) = Unit
override suspend fun lookupArcHostStatus(partition: Plan.Partition): ArcState =
ArcState.Indeterminate
override suspend fun isHostForParticle(particle: Plan.Particle): Boolean = false
override suspend fun pause() {
require(!isPaused) {
"Can only pause an ArcHost that is currently unpaused."
}
isPaused = true
}
override suspend fun unpause() {
require(isPaused) {
"Can only unpause an ArcHost that is currently paused."
}
isPaused = false
}
override suspend fun waitForArcIdle(arcId: String) = Unit
override suspend fun addOnArcStateChange(
arcId: ArcId,
block: ArcStateChangeCallback
): ArcStateChangeRegistration =
throw NotImplementedError("Method not implemented for NoOpArcHost.")
}
| bsd-3-clause | 1be865cd997d86fad78015522fa6a79d | 27.340909 | 84 | 0.731355 | 4.485612 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/core/storage/LocalStorageEndpointTest.kt | 1 | 2573 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.storage
import arcs.core.crdt.CrdtData
import arcs.core.crdt.CrdtEntity
import arcs.core.crdt.CrdtOperation
import arcs.core.crdt.CrdtSingleton
import arcs.core.crdt.VersionMap
import arcs.core.data.util.toReferencable
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(JUnit4::class)
class LocalStorageEndpointTest {
@Test
fun endpoint_idle_delegatesToStore() = runTest {
val mock = mock<ActiveStore<*, CrdtOperation, *>>()
val endpoint = LocalStorageEndpoint(mock, 0)
endpoint.idle()
verify(mock, times(1)).idle()
}
@Test
fun endpoint_proxyMessage_delegatesToStoreAndCopiesId() = runTest {
val mock = mock<ActiveStore<CrdtData, CrdtOperation, Any?>>()
val endpoint = LocalStorageEndpoint(mock, 10)
endpoint.onProxyMessage(DUMMY_PROXY_MESSAGE)
verify(mock, times(1)).onProxyMessage(DUMMY_PROXY_MESSAGE.copy(id = 10))
}
@Test
fun endpoint_close_removesStoreCallback() = runTest {
val mock = mock<ActiveStore<*, CrdtOperation, *>>()
val endpoint = LocalStorageEndpoint(mock, 12)
endpoint.close()
verify(mock, times(1)).off(12)
}
private fun runTest(block: suspend CoroutineScope.() -> Unit): Unit = runBlockingTest {
block()
}
companion object {
val DUMMY_PROXY_MESSAGE = ProxyMessage.ModelUpdate<CrdtData, CrdtOperation, Any?>(
model = CrdtEntity.Data(
singletons = mapOf(
"a" to CrdtSingleton<CrdtEntity.Reference>(
VersionMap("alice" to 1),
CrdtEntity.ReferenceImpl("AAA".toReferencable().id)
),
"b" to CrdtSingleton<CrdtEntity.Reference>(
VersionMap("bob" to 1),
CrdtEntity.ReferenceImpl("BBB".toReferencable().id)
)
),
collections = mapOf(),
versionMap = VersionMap("Bar" to 2),
creationTimestamp = 971,
expirationTimestamp = -1
),
id = 1
)
}
}
| bsd-3-clause | e276f2cb99aab04a37202e01e8f9f398 | 28.238636 | 96 | 0.702293 | 4.259934 | false | true | false | false |
raflop/kotlin-android-presentation | samples/openid/app/src/main/java/com/example/rlopatka/openidsample/UsersApi.kt | 1 | 2094 | package com.example.rlopatka.openidsample
import com.google.gson.annotations.SerializedName
import io.reactivex.Observable
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
/**
* Created by rlopatka on 30.10.2017.
*/
interface UsersApi {
@GET("userinfo")
fun getCurrentUser(): Observable<User>
}
interface ApiFactory {
fun <TApi> create(apiClass: Class<TApi>): TApi
}
object TokenReference {
var token: String = ""
}
class ApiHeadersInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val builder = request.newBuilder()
builder.addHeader("Authorization", "Bearer ${TokenReference.token}")
return chain.proceed(builder.build())
}
}
class RetrofitApiFactory: ApiFactory {
private var retrofit: Retrofit
init {
val httpClient = OkHttpClient.Builder()
.addInterceptor(ApiHeadersInterceptor())
.build()
this.retrofit = Retrofit.Builder()
.client(httpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://kotlin-android-presentation.eu.auth0.com/")
.build()
}
override fun <TApi> create(apiClass: Class<TApi>): TApi {
return retrofit.create(apiClass)
}
}
class UserApiClient(apiFactory: ApiFactory) {
private val api: UsersApi by lazy { apiFactory.create(UsersApi::class.java) }
fun getCurrentUser(): Observable<User> {
return api.getCurrentUser()
}
}
class User {
@SerializedName("sub")
var userId: String = ""
@SerializedName("nickname")
var userName: String = ""
@SerializedName("email")
var email: String = ""
@SerializedName("updated_at")
var updatedAt: String = ""
} | gpl-3.0 | 0a94529425e6698025695a5a1e437394 | 24.240964 | 81 | 0.678128 | 4.389937 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/base/scripting/projectStructure/ScriptDependenciesInfo.kt | 4 | 5399 | // 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.base.scripting.projectStructure
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.*
import org.jetbrains.kotlin.idea.base.scripting.KotlinBaseScriptingBundle
import org.jetbrains.kotlin.idea.base.scripting.ScriptingTargetPlatformDetector
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager
import org.jetbrains.kotlin.idea.core.script.dependencies.KotlinScriptSearchScope
import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.TargetPlatformVersion
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.resolve.PlatformDependentAnalyzerServices
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatformAnalyzerServices
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
sealed class ScriptDependenciesInfo(override val project: Project) : IdeaModuleInfo, BinaryModuleInfo {
abstract val sdk: Sdk?
override val name = Name.special("<Script dependencies>")
override val displayedName: String
get() = KotlinBaseScriptingBundle.message("script.dependencies")
override fun dependencies(): List<IdeaModuleInfo> = listOfNotNull(this, sdk?.let { SdkInfo(project, it) })
// NOTE: intentionally not taking corresponding script info into account
// otherwise there is no way to implement getModuleInfo
override fun hashCode() = project.hashCode()
override fun equals(other: Any?): Boolean = other is ScriptDependenciesInfo && this.project == other.project
override val moduleOrigin: ModuleOrigin
get() = ModuleOrigin.LIBRARY
override val sourcesModuleInfo: SourceForBinaryModuleInfo?
get() = ScriptDependenciesSourceInfo.ForProject(project)
override val platform: TargetPlatform
get() = JvmPlatforms.unspecifiedJvmPlatform // TODO(dsavvinov): choose proper TargetVersion
override val analyzerServices: PlatformDependentAnalyzerServices
get() = JvmPlatformAnalyzerServices
override val moduleContentScope: GlobalSearchScope
get() = KotlinScriptSearchScope(project, contentScope)
class ForFile(
project: Project,
val scriptFile: VirtualFile,
val scriptDefinition: ScriptDefinition
) : ScriptDependenciesInfo(project), LanguageSettingsOwner {
override val sdk: Sdk?
get() = ScriptConfigurationManager.getInstance(project).getScriptSdk(scriptFile)
override val languageVersionSettings: LanguageVersionSettings
get() = ScriptingTargetPlatformDetector.getLanguageVersionSettings(project, scriptFile, scriptDefinition)
override val targetPlatformVersion: TargetPlatformVersion
get() = ScriptingTargetPlatformDetector.getTargetPlatformVersion(project, scriptFile, scriptDefinition)
override val contentScope: GlobalSearchScope
get() {
// TODO: this is not very efficient because KotlinSourceFilterScope already checks if the files are in scripts classpath
return KotlinSourceFilterScope.libraryClasses(
ScriptConfigurationManager.getInstance(project).getScriptDependenciesClassFilesScope(scriptFile), project
)
}
}
// we do not know which scripts these dependencies are
class ForProject(project: Project) : ScriptDependenciesInfo(project) {
override val sdk: Sdk?
get() {
return ScriptConfigurationManager.getInstance(project).getFirstScriptsSdk()
}
override val contentScope: GlobalSearchScope
get() {
return KotlinSourceFilterScope.libraryClasses(
ScriptConfigurationManager.getInstance(project).getAllScriptsDependenciesClassFilesScope(), project
)
}
companion object {
fun createIfRequired(project: Project, moduleInfos: List<IdeaModuleInfo>): IdeaModuleInfo? =
if (moduleInfos.any { gradleApiPresentInModule(it) }) ForProject(project) else null
private fun gradleApiPresentInModule(moduleInfo: IdeaModuleInfo) =
moduleInfo is JvmLibraryInfo &&
moduleInfo.library.safeAs<LibraryEx>()?.isDisposed != true &&
moduleInfo.getLibraryRoots().any {
// TODO: it's ugly ugly hack as Script (Gradle) SDK has to be provided in case of providing script dependencies.
// So far the indication of usages of script dependencies by module is `gradleApi`
// Note: to be deleted with https://youtrack.jetbrains.com/issue/KTIJ-19276
it.contains("gradle-api")
}
}
}
} | apache-2.0 | 0a79bde7fbe5e99f5361cb06884f8722 | 49 | 140 | 0.727727 | 5.665268 | false | true | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/model/data/remote/api/theme/ThemeParser.kt | 1 | 7324 | package forpdateam.ru.forpda.model.data.remote.api.theme
import android.util.Log
import android.util.Pair
import forpdateam.ru.forpda.entity.remote.others.pagination.Pagination
import forpdateam.ru.forpda.entity.remote.theme.*
import forpdateam.ru.forpda.model.data.remote.ParserPatterns
import forpdateam.ru.forpda.model.data.remote.parser.BaseParser
import forpdateam.ru.forpda.model.data.storage.IPatternProvider
import java.util.regex.Matcher
class ThemeParser(
private val patternProvider: IPatternProvider
) : BaseParser() {
private val scope = ParserPatterns.Topic
fun parsePage(response: String, argUrl: String, hatOpen: Boolean = false, pollOpen: Boolean = false): ThemePage = ThemePage().also { page ->
page.isHatOpen = hatOpen
page.isPollOpen = pollOpen
page.url = argUrl
patternProvider
.getPattern(scope.scope, scope.scroll_anchor)
.matcher(argUrl)
.findAll {
page.addAnchor(it.group(1))
}
patternProvider
.getPattern(scope.scope, scope.topic_id)
.matcher(response)
.findOnce {
page.forumId = it.group(1).toInt()
page.id = it.group(2).toInt()
}
page.pagination = Pagination.parseForum(response)
patternProvider
.getPattern(scope.scope, scope.title)
.matcher(response)
.findOnce {
page.title = it.group(1).fromHtml()
page.desc = it.group(2).fromHtml()
}
patternProvider
.getPattern(scope.scope, scope.already_in_fav)
.matcher(response)
.findOnce {
page.isInFavorite = true
patternProvider
.getPattern(scope.scope, scope.fav_id)
.matcher(response)
.findOnce {
page.favId = it.group(1).toInt()
}
}
var attachMatcher: Matcher? = null
val posts = patternProvider
.getPattern(scope.scope, scope.posts)
.matcher(response)
.map { matcher ->
ThemePost().apply {
topicId = page.id
forumId = page.forumId
id = matcher.group(1).toInt()
date = matcher.group(5)
number = matcher.group(6).toInt()
isOnline = matcher.group(7).contains("green")
matcher.group(8).also {
avatar = if (!it.isEmpty()) "https://s.4pda.to/forum/uploads/$it" else it
}
nick = matcher.group(9).fromHtml()
userId = matcher.group(10).toInt()
isCurator = matcher.group(11) != null
groupColor = matcher.group(12)
group = matcher.group(13)
canMinusRep = !matcher.group(14).isEmpty()
reputation = matcher.group(15)
canPlusRep = !matcher.group(16).isEmpty()
canReport = !matcher.group(17).isEmpty()
canEdit = !matcher.group(18).isEmpty()
canDelete = !matcher.group(19).isEmpty()
page.canQuote = !matcher.group(20).isEmpty()
canQuote = page.canQuote
body = matcher.group(21)
attachMatcher = attachMatcher?.reset(body) ?: patternProvider
.getPattern(scope.scope, scope.attached_images)
.matcher(body)
attachMatcher
?.findAll {
attachImages.add(Pair("https://${it.group(1)}", it.group(2)))
}
}
/*if (isCurator() && getUserId() == ClientHelper.getUserId())
page.setCurator(true);*/
}
page.posts.addAll(posts)
patternProvider
.getPattern(scope.scope, scope.poll_main)
.matcher(response)
.findOnce { matcher ->
val isResult = matcher.group().contains("<img")
val poll = Poll()
poll.isResult = isResult
poll.title = matcher.group(1).fromHtml()
val questions = patternProvider
.getPattern(scope.scope, scope.poll_questions)
.matcher(matcher.group(2))
.map {
PollQuestion().apply {
title = it.group(1).fromHtml()
val items = patternProvider
.getPattern(scope.scope, scope.poll_question_item)
.matcher(it.group(2))
.map {
PollQuestionItem().apply {
if (!isResult) {
type = it.group(1)
name = it.group(2).fromHtml()
value = it.group(3).toInt()
title = it.group(4).fromHtml()
} else {
title = it.group(5).fromHtml()
votes = it.group(6).toInt()
percent = java.lang.Float.parseFloat(it.group(7).replace(",", "."))
}
}
}
this.questionItems.addAll(items)
}
}
poll.questions.addAll(questions)
patternProvider
.getPattern(scope.scope, scope.poll_buttons)
.matcher(matcher.group(4))
.findAll {
val value = it.group(1)
when {
value.contains("Голосовать") -> poll.voteButton = true
value.contains("результаты") -> poll.showResultsButton = true
value.contains("пункты опроса") -> poll.showPollButton = true
}
}
poll.votesCount = matcher.group(3).toInt()
page.poll = poll
}
return page
}
}
| gpl-3.0 | 76e3d539193fd0412bcd977d66dc30ec | 44.575 | 144 | 0.414427 | 5.626543 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/widgets/BadgedImageView.kt | 1 | 7042 | package org.wordpress.android.widgets
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Bitmap.Config.ARGB_8888
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Paint.ANTI_ALIAS_FLAG
import android.graphics.Paint.Style
import android.graphics.PorterDuff.Mode.CLEAR
import android.graphics.PorterDuffXfermode
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import androidx.annotation.DrawableRes
import androidx.appcompat.widget.AppCompatImageView
import org.wordpress.android.R
import org.wordpress.android.util.DisplayUtils
/**
* A ImageView that can draw a badge at the corner of its view.
* The main difference between this implementation and others commonly found online, is that this one uses
* Porter/Duff Compositing to create a transparent space between the badge background and the view.
*/
class BadgedImageView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {
companion object {
const val DEFAULT_BADGE_BACKGROUND_SIZE = 16f
const val DEFAULT_BADGE_BACKGROUND_BORDER_WIDTH = 0f
const val DEFAULT_BADGE_ICON_SIZE = 16f
const val DEFAULT_BADGE_HORIZONTAL_OFFSET = 0f
const val DEFAULT_BADGE_VERTICAL_OFFSET = 0f
}
var badgeBackground: Drawable? = null
set(value) {
field = value
invalidate()
}
var badgeBackgroundSize: Float = 0f
set(value) {
field = value
invalidate()
}
var badgeBackgroundBorderWidth: Float = 0f
set(value) {
field = value
invalidate()
}
var badgeIcon: Drawable? = null
set(value) {
field = value
invalidate()
}
var badgeIconSize: Float = 0f
set(value) {
field = value
invalidate()
}
var badgeHorizontalOffset: Float = 0f
set(value) {
field = value
invalidate()
}
var badgeVerticalOffset: Float = 0f
set(value) {
field = value
invalidate()
}
init {
val styledAttributes = context.obtainStyledAttributes(attrs, R.styleable.BadgedImageView)
badgeBackground = styledAttributes.getDrawable(
R.styleable.BadgedImageView_badgeBackground
)
badgeBackgroundSize = styledAttributes.getDimension(
R.styleable.BadgedImageView_badgeBackgroundSize,
DisplayUtils.dpToPx(context, DEFAULT_BADGE_BACKGROUND_SIZE.toInt()).toFloat()
)
badgeBackgroundBorderWidth = styledAttributes.getDimension(
R.styleable.BadgedImageView_badgeBackgroundBorderWidth,
DisplayUtils.dpToPx(context, DEFAULT_BADGE_BACKGROUND_BORDER_WIDTH.toInt()).toFloat()
)
badgeIcon = styledAttributes.getDrawable(
R.styleable.BadgedImageView_badgeIcon
)
badgeIconSize = styledAttributes.getDimension(
R.styleable.BadgedImageView_badgeIconSize,
DisplayUtils.dpToPx(context, DEFAULT_BADGE_ICON_SIZE.toInt()).toFloat()
)
badgeHorizontalOffset = styledAttributes.getDimension(
R.styleable.BadgedImageView_badgeHorizontalOffset,
DisplayUtils.dpToPx(context, DEFAULT_BADGE_HORIZONTAL_OFFSET.toInt()).toFloat()
)
badgeVerticalOffset = styledAttributes.getDimension(
R.styleable.BadgedImageView_badgeVerticalOffset,
DisplayUtils.dpToPx(context, DEFAULT_BADGE_VERTICAL_OFFSET.toInt()).toFloat()
)
styledAttributes.recycle()
}
private val paint = Paint(ANTI_ALIAS_FLAG)
private val eraserPaint = Paint(ANTI_ALIAS_FLAG).apply {
color = Color.TRANSPARENT
style = Style.FILL_AND_STROKE
strokeWidth = badgeBackgroundBorderWidth
xfermode = PorterDuffXfermode(CLEAR)
}
private var tempCanvasBitmap: Bitmap? = null
private var tempCanvas: Canvas? = null
private var invalidated = true
fun setBadgeBackground(@DrawableRes badgeBackgroundResId: Int) {
badgeBackground = context.getDrawable(badgeBackgroundResId)
}
fun setBadgeIcon(@DrawableRes badgeIconResId: Int) {
badgeIcon = context.getDrawable(badgeIconResId)
}
override fun invalidate() {
invalidated = true
super.invalidate()
}
override fun onSizeChanged(width: Int, height: Int, oldWidht: Int, oldHeight: Int) {
super.onSizeChanged(width, height, oldWidht, oldHeight)
val sizeChanged = width != oldWidht || height != oldHeight
val isValid = width > 0 && height > 0
if (isValid && (tempCanvas == null || sizeChanged)) {
tempCanvasBitmap = Bitmap.createBitmap(
width + badgeBackgroundSize.toInt() / 2,
height + badgeBackgroundSize.toInt() / 2,
ARGB_8888
)
tempCanvas = tempCanvasBitmap?.let { Canvas(it) }
invalidated = true
}
}
override fun onDraw(canvas: Canvas) {
if (invalidated) {
tempCanvas?.let {
clearCanvas(it)
super.onDraw(it)
drawBadge(it)
}
invalidated = false
}
if (!invalidated) {
tempCanvasBitmap?.let { canvas.drawBitmap(it, 0f, 0f, paint) }
}
}
private fun clearCanvas(canvas: Canvas) {
canvas.drawColor(Color.TRANSPARENT, CLEAR)
}
private fun drawBadge(canvas: Canvas) {
val x = pivotX + width / 2f - badgeBackgroundSize / 2f + badgeHorizontalOffset
val y = pivotY + height / 2f - badgeBackgroundSize / 2f + badgeVerticalOffset
drawBadgeSpace(canvas, x, y)
drawBadgeBackground(canvas, x, y)
drawBadgeIcon(canvas, x, y)
}
private fun drawBadgeSpace(canvas: Canvas, x: Float, y: Float) {
canvas.drawCircle(x, y, badgeBackgroundSize / 2f + badgeBackgroundBorderWidth, eraserPaint)
}
private fun drawBadgeBackground(canvas: Canvas, x: Float, y: Float) {
if (badgeBackground != null) {
badgeBackground?.setBounds(0, 0, badgeBackgroundSize.toInt(), badgeBackgroundSize.toInt())
canvas.save()
canvas.translate(x - badgeBackgroundSize / 2f, y - badgeBackgroundSize / 2f)
badgeBackground?.draw(canvas)
canvas.restore()
}
}
private fun drawBadgeIcon(canvas: Canvas, x: Float, y: Float) {
if (badgeIcon != null) {
badgeIcon?.setBounds(0, 0, badgeIconSize.toInt(), badgeIconSize.toInt())
canvas.save()
canvas.translate(x - badgeIconSize / 2f, y - badgeIconSize / 2f)
badgeIcon?.draw(canvas)
canvas.restore()
}
}
}
| gpl-2.0 | 2c0e508776d9b4007343d91b7b66a043 | 33.35122 | 106 | 0.636609 | 4.688415 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.