content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
@file:JvmName("GroupFollowInteractionUtils")
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.common.UpdatableInteraction
import com.vimeo.networking2.enums.FollowType
import com.vimeo.networking2.enums.asEnum
import java.util.Date
/**
* Follow a group interaction.
*
* @param rawType Whether the authenticated user is a moderator or subscriber. See [GroupFollowInteraction.type].
* @param title The user's title, or the null value if not applicable.
*/
@JsonClass(generateAdapter = true)
data class GroupFollowInteraction(
@Json(name = "added")
override val added: Boolean? = null,
@Json(name = "added_time")
override val addedTime: Date? = null,
@Json(name = "options")
override val options: List<String>? = null,
@Json(name = "uri")
override val uri: String? = null,
@Json(name = "type")
val rawType: String? = null,
@Json(name = "title")
val title: String? = null
) : UpdatableInteraction
/**
* @see GroupFollowInteraction.rawType
* @see FollowType
*/
val GroupFollowInteraction.type: FollowType
get() = rawType.asEnum(FollowType.UNKNOWN)
| models/src/main/java/com/vimeo/networking2/GroupFollowInteraction.kt | 1653019954 |
/*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tealcube.minecraft.bukkit.mythicdrops.api.choices
import com.tealcube.minecraft.bukkit.mythicdrops.api.weight.Weighted
import com.tealcube.minecraft.bukkit.mythicdrops.safeRandom
import io.pixeloutlaw.minecraft.spigot.mythicdrops.isZero
/**
* Simple utility for making weighted choices.
*/
class WeightedChoice<T : Weighted> : Choice<T>() {
companion object {
/**
* Constructs a [WeightedChoice] for the given [option].
*
* @param option Option(s) for choice.
* @return constructed choice
*/
@JvmStatic
fun <T : Weighted> between(vararg option: T): WeightedChoice<T> =
between(option.asIterable())
/**
* Constructs a [WeightedChoice] for the given [options].
*
* @param option Option(s) for choice.
* @return constructed choice
*/
@JvmStatic
fun <T : Weighted> between(options: Iterable<T>): WeightedChoice<T> =
WeightedChoice<T>().also { it.addOptions(options) }
}
override fun choose(): T? {
return choose { true }
}
/**
* Chooses one of the available options and returns it based on weight.
*
* @param block Extra block to execute to determine if option is selectable
* @return chosen option or null if one cannot be chosen
*/
fun choose(block: (T) -> Boolean): T? {
val selectableOptions = options.filter(block).filter {
!it.weight.isZero()
}
val totalWeight: Double = selectableOptions.fold(0.0) { sum, element -> sum + element.weight }
val chosenWeight = (0.0..totalWeight).safeRandom()
val shuffledOptions = selectableOptions.shuffled()
var currentWeight = 0.0
for (option in shuffledOptions) {
currentWeight += option.weight
if (currentWeight >= chosenWeight) {
return option
}
}
return null
}
}
| src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/api/choices/WeightedChoice.kt | 1202898998 |
package abi44_0_0.host.exp.exponent.modules.api.components.gesturehandler.react
import androidx.core.util.Pools
import abi44_0_0.com.facebook.react.bridge.Arguments
import abi44_0_0.com.facebook.react.bridge.WritableMap
import abi44_0_0.com.facebook.react.uimanager.events.Event
import abi44_0_0.com.facebook.react.uimanager.events.RCTEventEmitter
import abi44_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandler
class RNGestureHandlerStateChangeEvent private constructor() : Event<RNGestureHandlerStateChangeEvent>() {
private var extraData: WritableMap? = null
private fun <T : GestureHandler<T>> init(
handler: T,
newState: Int,
oldState: Int,
dataExtractor: RNGestureHandlerEventDataExtractor<T>?,
) {
super.init(handler.view!!.id)
extraData = createEventData(handler, dataExtractor, newState, oldState)
}
override fun onDispose() {
extraData = null
EVENTS_POOL.release(this)
}
override fun getEventName() = EVENT_NAME
// TODO: coalescing
override fun canCoalesce() = false
// TODO: coalescing
override fun getCoalescingKey(): Short = 0
override fun dispatch(rctEventEmitter: RCTEventEmitter) {
rctEventEmitter.receiveEvent(viewTag, EVENT_NAME, extraData)
}
companion object {
const val EVENT_NAME = "onGestureHandlerStateChange"
private const val TOUCH_EVENTS_POOL_SIZE = 7 // magic
private val EVENTS_POOL = Pools.SynchronizedPool<RNGestureHandlerStateChangeEvent>(TOUCH_EVENTS_POOL_SIZE)
fun <T : GestureHandler<T>> obtain(
handler: T,
newState: Int,
oldState: Int,
dataExtractor: RNGestureHandlerEventDataExtractor<T>?,
): RNGestureHandlerStateChangeEvent =
(EVENTS_POOL.acquire() ?: RNGestureHandlerStateChangeEvent()).apply {
init(handler, newState, oldState, dataExtractor)
}
fun <T : GestureHandler<T>> createEventData(
handler: T,
dataExtractor: RNGestureHandlerEventDataExtractor<T>?,
newState: Int,
oldState: Int,
): WritableMap = Arguments.createMap().apply {
dataExtractor?.extractEventData(handler, this)
putInt("handlerTag", handler.tag)
putInt("state", newState)
putInt("oldState", oldState)
}
}
}
| android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/api/components/gesturehandler/react/RNGestureHandlerStateChangeEvent.kt | 2469459203 |
// Copyright 2015-present 650 Industries. All rights reserved.
package versioned.host.exp.exponent
import android.content.Context
import android.view.ContextThemeWrapper
import host.exp.expoview.R
import com.facebook.react.ReactRootView
class ReactUnthemedRootView(context: Context?) : ReactRootView(
ContextThemeWrapper(
context,
R.style.Theme_Exponent_None
)
)
| android/expoview/src/main/java/versioned/host/exp/exponent/ReactUnthemedRootView.kt | 3302817266 |
package com.vimeo.networking2.enums
/**
* An enumeration of the supported types representing the published status
* of the upload/post on a third party social network platform.
*/
enum class PublishStatusType(override val value: String?) : StringValue {
/**
* Status when an error has occurred.
*/
ERROR("error"),
/**
* Status when a job has successfully completed.
*/
FINISHED("finished"),
/**
* Status when a job is currently in progress.
*/
IN_PROGRESS("in_progress"),
/**
* Unknown status type.
*/
UNKNOWN(null);
}
| models/src/main/java/com/vimeo/networking2/enums/PublishStatusType.kt | 3290407671 |
fun foo(vararg strings: String){ }
fun bar(arr: Array<String>){
foo(<caret>)
}
// ELEMENT: arr
| plugins/kotlin/completion/tests/testData/handlers/smart/Vararg4.kt | 816695870 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.ui.preview.jcef
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.Base64
import com.intellij.util.io.HttpRequests
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.MarkdownNotifier
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import org.jsoup.select.Elements
import java.io.File
import java.io.IOException
data class HtmlResourceSavingSettings(val isSaved: Boolean, val resourceDir: String)
class HtmlExporter(htmlSource: String,
private val savingSettings: HtmlResourceSavingSettings,
private val project: Project,
private val targetFile: File) {
private val document = Jsoup.parse(htmlSource)
fun export() {
with(document.head()) {
getElementsByTag("script").remove()
getElementsByTag("meta").remove()
appendInlineStylesContent(select("link[rel=\"stylesheet\"]"))
}
val images = document.body().getElementsByTag("img")
if (savingSettings.isSaved) {
saveImages(images)
}
else {
inlineImagesContent(images)
}
targetFile.writeText(document.html())
}
private fun appendInlineStylesContent(styles: Elements) {
val inlinedStyles = styles.mapNotNull {
val content = getStyleContent(it) ?: return@mapNotNull null
Element("style").text(content)
}
styles.remove()
inlinedStyles.forEach {
if (it.hasText()) {
document.head().appendChild(it)
}
}
}
private fun getStyleContent(linkElement: Element): String? {
val url = linkElement.attr("href") ?: return null
return try {
HttpRequests.request(url).readString()
}
catch (exception: IOException) {
val name = File(url).name
MarkdownNotifier.showWarningNotification(project, MarkdownBundle.message("markdown.export.style.not.found.msg", name))
null
}
}
private fun inlineImagesContent(images: Elements) {
images.forEach {
val imgSrc = getImgUriWithProtocol(it.attr("src"))
val content = getResource(imgSrc)
if (content != null && imgSrc.isNotEmpty()) {
it.attr("src", encodeImage(imgSrc, content))
}
}
}
private fun encodeImage(url: String, bytes: ByteArray): String {
val extension = FileUtil.getExtension(url, "png")
val contentType = if (extension == "svg") "svg+xml" else extension
return "data:image/$contentType;base64, ${Base64.encode(bytes)}"
}
private fun saveImages(images: Elements) {
images.forEach {
val imgSrc = it.attr("src")
val imgUri = getImgUriWithProtocol(imgSrc)
val content = getResource(imgUri)
if (content != null && imgSrc.isNotEmpty()) {
val savedImgFile = getSavedImageFile(savingSettings.resourceDir, imgSrc)
FileUtil.createIfDoesntExist(savedImgFile)
savedImgFile.writeBytes(content)
val relativeImgPath = getRelativeImagePath(savingSettings.resourceDir)
it.attr("src", FileUtil.join(relativeImgPath, File(imgSrc).name))
}
}
}
private fun getImgUriWithProtocol(imgSrc: String): String {
return if (imgSrc.startsWith("file:")) imgSrc
else File(imgSrc).toURI().toString()
}
private fun getResource(url: String): ByteArray? =
try {
HttpRequests.request(url).readBytes(null)
}
catch (exception: IOException) {
val name = File(url).name
MarkdownNotifier.showWarningNotification(project, MarkdownBundle.message("markdown.export.images.not.found.msg", name))
null
}
private fun getSavedImageFile(resDir: String, imgUrl: String) = File(FileUtil.join(resDir, File(imgUrl).name))
private fun getRelativeImagePath(resDir: String) = FileUtil.getRelativePath(targetFile.parentFile, File(resDir))
}
| plugins/markdown/core/src/org/intellij/plugins/markdown/ui/preview/jcef/HtmlExporter.kt | 1385044642 |
fun test() {
with(Main()) {
42.memberExtension()
}
} | plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/members/extension/Foo.kt | 3827599760 |
package one.two
object KotlinObject {
object Nested {
@JvmField
val fieldPrope<caret>rty = 42
}
}
| plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/fromObject/nestedObject/fieldProperty/KotlinObject.kt | 430499044 |
fun t() {
while (true) {
brea<caret>
}
} | plugins/kotlin/completion/tests/testData/handlers/keywords/Break.kt | 1691424102 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.action
import com.intellij.icons.AllIcons
import com.intellij.ide.actions.RefreshAction
import com.intellij.openapi.actionSystem.AnActionEvent
import org.jetbrains.plugins.github.i18n.GithubBundle
class GHPRUpdateTimelineAction
: RefreshAction({ GithubBundle.message("pull.request.timeline.refresh.action") },
{ GithubBundle.message("pull.request.timeline.refresh.action.description") },
AllIcons.Actions.Refresh) {
override fun update(e: AnActionEvent) {
val dataProvider = e.getData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER)
e.presentation.isEnabled = dataProvider?.timelineLoader != null
}
override fun actionPerformed(e: AnActionEvent) {
val dataProvider = e.getRequiredData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER)
dataProvider.detailsData.reloadDetails()
if (dataProvider.timelineLoader?.loadMore(true) != null)
dataProvider.reviewData.resetReviewThreads()
}
} | plugins/github/src/org/jetbrains/plugins/github/pullrequest/action/GHPRUpdateTimelineAction.kt | 957418058 |
// WITH_STDLIB
// IS_APPLICABLE: false
// ERROR: 'infix' modifier is inapplicable on this function: must be a member or an extension function
package demo
infix fun foo(str: String) = kotlin.io.println(str)
fun main() {
<caret>demo.foo("")
}
| plugins/kotlin/idea/tests/testData/intentions/toInfixCall/singlePackageFunctionCall.kt | 899886865 |
package info.nightscout.androidaps.plugins.general.automation.actions
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.events.EventRefreshOverview
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.elements.InputDuration
import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement
import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.JsonHelper
import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.json.JSONObject
import javax.inject.Inject
class ActionLoopSuspend(injector: HasAndroidInjector) : Action(injector) {
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var loopPlugin: LoopPlugin
@Inject lateinit var rxBus: RxBusWrapper
var minutes = InputDuration(injector, 0, InputDuration.TimeUnit.MINUTES)
override fun friendlyName(): Int = R.string.suspendloop
override fun shortDescription(): String = resourceHelper.gs(R.string.suspendloopforXmin, minutes.getMinutes())
@DrawableRes override fun icon(): Int = R.drawable.ic_pause_circle_outline_24dp
override fun doAction(callback: Callback) {
if (!loopPlugin.isSuspended) {
loopPlugin.suspendLoop(minutes.getMinutes())
rxBus.send(EventRefreshOverview("ActionLoopSuspend"))
callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run()
} else {
callback.result(PumpEnactResult(injector).success(true).comment(R.string.alreadysuspended))?.run()
}
}
override fun toJSON(): String {
val data = JSONObject().put("minutes", minutes.getMinutes())
return JSONObject()
.put("type", this.javaClass.name)
.put("data", data)
.toString()
}
override fun fromJSON(data: String): Action {
val o = JSONObject(data)
minutes.setMinutes(JsonHelper.safeGetInt(o, "minutes"))
return this
}
override fun hasDialog(): Boolean = true
override fun generateDialog(root: LinearLayout) {
LayoutBuilder()
.add(LabelWithElement(injector, resourceHelper.gs(R.string.careportal_newnstreatment_duration_min_label), "", minutes))
.build(root)
}
} | app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.kt | 2503450238 |
package com.example.multiapp
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
| test_projects/android/multi-modules/multiapp/src/test/java/com/example/multiapp/ExampleUnitTest.kt | 926049911 |
package com.quixom.apps.deviceinfo.fragments
import android.Manifest
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Camera
import android.graphics.ImageFormat
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.hardware.camera2.params.StreamConfigurationMap
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Range
import android.util.Rational
import android.util.Size
import android.view.*
import android.widget.*
import com.quixom.apps.deviceinfo.R
import com.quixom.apps.deviceinfo.adapters.CameraAdapter
import com.quixom.apps.deviceinfo.models.FeaturesHW
import com.quixom.apps.deviceinfo.utilities.KeyUtil
import java.lang.StringBuilder
import java.util.*
class CameraFragment : BaseFragment(), View.OnClickListener {
@RequiresApi(Build.VERSION_CODES.M)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun onClick(view: View?) {
when (view) {
tvRearCamera -> {
checkCameraPermission("1")
tabSelector(tvRearCamera!!, tvFrontCamera!!)
}
tvFrontCamera -> {
checkCameraPermission("0")
tabSelector(tvFrontCamera!!, tvRearCamera!!)
}
}
}
var ivMenu: ImageView? = null
var ivBack: ImageView? = null
var tvTitle: TextView? = null
var tvCameraFeature: TextView? = null
var tvRearCamera: TextView? = null
var tvFrontCamera: TextView? = null
var textAreaScroller: ScrollView? = null
var llParentCamera: LinearLayout? = null
private var rvCameraFeatures: RecyclerView? = null
var camera: Camera? = null
private var cameraManager: CameraManager? = null
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// val view = inflater.inflate(R.layout.fragment_camera, container, false)
val contextThemeWrapper = ContextThemeWrapper(activity, R.style.CameraTheme)
val localInflater = inflater.cloneInContext(contextThemeWrapper)
val view = localInflater.inflate(R.layout.fragment_camera, container, false)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val window = activity!!.window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.statusBarColor = resources.getColor(R.color.dark_green_blue)
window.navigationBarColor = resources.getColor(R.color.dark_green_blue)
}
ivMenu = view.findViewById(R.id.iv_menu)
ivBack = view.findViewById(R.id.iv_back)
tvTitle = view.findViewById(R.id.tv_title)
tvCameraFeature = view.findViewById(R.id.tv_camera_feature)
tvRearCamera = view.findViewById(R.id.tv_rear_camera)
tvFrontCamera = view.findViewById(R.id.tv_front_camera)
textAreaScroller = view.findViewById(R.id.textAreaScroller)
llParentCamera = view.findViewById(R.id.ll_parent_camera)
rvCameraFeatures = view.findViewById(R.id.rv_Camera_Features)
cameraManager = mActivity.getSystemService(Context.CAMERA_SERVICE) as CameraManager?
camera = Camera()
return view
}
@RequiresApi(Build.VERSION_CODES.M)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
initToolbar()
tvRearCamera?.setOnClickListener(this)
tvFrontCamera?.setOnClickListener(this)
if (cameraManager?.cameraIdList?.size!! >= 2) {
llParentCamera?.visibility = View.VISIBLE
} else {
llParentCamera?.visibility = View.GONE
}
rvCameraFeatures?.layoutManager = LinearLayoutManager(mActivity)
rvCameraFeatures?.hasFixedSize()
checkCameraPermission("1")
}
override fun onHiddenChanged(hidden: Boolean) {
super.onHiddenChanged(hidden)
if (!hidden && isAdded) {
initToolbar()
}
}
private fun initToolbar() {
ivMenu?.visibility = View.VISIBLE
ivBack?.visibility = View.GONE
tvTitle?.text = mResources.getString(R.string.camera)
ivMenu?.setOnClickListener {
mActivity.openDrawer()
}
}
@RequiresApi(Build.VERSION_CODES.M)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
/**
* this method will show permission pop up messages to user.
*/
private fun checkCameraPermission(ids: String) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val hasWriteCameraPermission = mActivity.checkSelfPermission(Manifest.permission.CAMERA)
if (hasWriteCameraPermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.CAMERA), KeyUtil.KEY_CAMERA_CODE)
} else {
fetchCameraCharacteristics(cameraManager!!, ids)
}
} else {
fetchCameraCharacteristics(cameraManager!!, ids)
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
KeyUtil.KEY_CAMERA_CODE -> if (permissions.isNotEmpty()) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
fetchCameraCharacteristics(cameraManager!!, "1")
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity, Manifest.permission.GET_ACCOUNTS)) {
//Show permission explanation dialog...
Toast.makeText(mActivity, "Need to grant account Permission", Toast.LENGTH_LONG).show()
}
}
}
else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
private fun tabSelector(textview1: TextView, textview2: TextView) {
/*** Set text color */
textview1.setTextColor(ContextCompat.getColor(mActivity, R.color.font_white))
textview2.setTextColor(ContextCompat.getColor(mActivity, R.color.orange))
/*** Background color */
textview1.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.orange))
textview2.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.font_white))
/*** Set background drawable */
textview1.setBackgroundResource(R.drawable.rectangle_fill)
textview2.setBackgroundResource(R.drawable.rectangle_unfill)
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private fun fetchCameraCharacteristics(cameraManager: CameraManager, ids: String) {
val lists = ArrayList<FeaturesHW>()
val sb = StringBuilder()
val characteristics = cameraManager.getCameraCharacteristics(ids)
for (key in characteristics.keys) {
sb.append(key.name).append("=").append(getCharacteristicsValue(key, characteristics)).append("\n\n")
val keyNm = key.name.split(".")
if (getCharacteristicsValue(key, characteristics) != "") {
if (key.name.split(".").size == 4) {
lists.add(FeaturesHW(keyNm[3], getCharacteristicsValue(key, characteristics)))
} else {
lists.add(FeaturesHW(keyNm[2], getCharacteristicsValue(key, characteristics)))
}
}
}
val adapter = CameraAdapter(lists, mActivity)
//now adding the adapter to RecyclerView
rvCameraFeatures?.adapter = adapter
}
@SuppressLint("NewApi")
@Suppress("UNCHECKED_CAST")
private fun <T> getCharacteristicsValue(key: CameraCharacteristics.Key<T>, characteristics: CameraCharacteristics): String {
val values = mutableListOf<String>()
if (CameraCharacteristics.COLOR_CORRECTION_AVAILABLE_ABERRATION_MODES == key) {
val modes = characteristics.get(key) as IntArray
modes.forEach {
when (it) {
CameraCharacteristics.COLOR_CORRECTION_ABERRATION_MODE_OFF -> values.add("Off")
CameraCharacteristics.COLOR_CORRECTION_ABERRATION_MODE_FAST -> values.add("Fast")
CameraCharacteristics.COLOR_CORRECTION_ABERRATION_MODE_HIGH_QUALITY -> values.add("High Quality")
}
}
} else if (CameraCharacteristics.CONTROL_AE_AVAILABLE_ANTIBANDING_MODES == key) {
val modes = characteristics.get(key) as IntArray
modes.forEach {
when (it) {
CameraCharacteristics.CONTROL_AE_ANTIBANDING_MODE_OFF -> values.add("Off")
CameraCharacteristics.CONTROL_AE_ANTIBANDING_MODE_AUTO -> values.add("Auto")
CameraCharacteristics.CONTROL_AE_ANTIBANDING_MODE_50HZ -> values.add("50Hz")
CameraCharacteristics.CONTROL_AE_ANTIBANDING_MODE_60HZ -> values.add("60Hz")
}
}
} else if (CameraCharacteristics.CONTROL_AE_AVAILABLE_MODES == key) {
val modes = characteristics.get(key) as IntArray
modes.forEach {
when (it) {
CameraCharacteristics.CONTROL_AE_MODE_OFF -> values.add("Off")
CameraCharacteristics.CONTROL_AE_MODE_ON -> values.add("On")
CameraCharacteristics.CONTROL_AE_MODE_ON_ALWAYS_FLASH -> values.add("Always Flash")
CameraCharacteristics.CONTROL_AE_MODE_ON_AUTO_FLASH -> values.add("Auto Flash")
CameraCharacteristics.CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE -> values.add("Auto Flash Redeye")
}
}
} else if (CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES == key) {
val ranges = characteristics.get(key) as Array<Range<Int>>
ranges.forEach {
values.add(getRangeValue(it))
}
} else if (CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE == key) {
val range = characteristics.get(key) as Range<Int>
values.add(getRangeValue(range))
} else if (CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP == key) {
val step = characteristics.get(key) as Rational
values.add(step.toString())
}/* else if (CameraCharacteristics.CONTROL_AE_LOCK_AVAILABLE == key) { // TODO requires >23
val available = characteristics.get(key)
values.add(available.toString())
} */ else if (CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES == key) {
val modes = characteristics.get(key) as IntArray
modes.forEach {
when (it) {
CameraCharacteristics.CONTROL_AF_MODE_OFF -> values.add("Off")
CameraCharacteristics.CONTROL_AF_MODE_AUTO -> values.add("Auto")
CameraCharacteristics.CONTROL_AF_MODE_EDOF -> values.add("EDOF")
CameraCharacteristics.CONTROL_AF_MODE_MACRO -> values.add("Macro")
CameraCharacteristics.CONTROL_AF_MODE_CONTINUOUS_PICTURE -> values.add("Continous Picture")
CameraCharacteristics.CONTROL_AF_MODE_CONTINUOUS_VIDEO -> values.add("Continous Video")
}
}
} else if (CameraCharacteristics.CONTROL_AVAILABLE_EFFECTS == key) {
val effects = characteristics.get(key) as IntArray
effects.forEach {
values.add(when (it) {
CameraCharacteristics.CONTROL_EFFECT_MODE_OFF -> "Off"
CameraCharacteristics.CONTROL_EFFECT_MODE_AQUA -> "Aqua"
CameraCharacteristics.CONTROL_EFFECT_MODE_BLACKBOARD -> "Blackboard"
CameraCharacteristics.CONTROL_EFFECT_MODE_MONO -> "Mono"
CameraCharacteristics.CONTROL_EFFECT_MODE_NEGATIVE -> "Negative"
CameraCharacteristics.CONTROL_EFFECT_MODE_POSTERIZE -> "Posterize"
CameraCharacteristics.CONTROL_EFFECT_MODE_SEPIA -> "Sepia"
CameraCharacteristics.CONTROL_EFFECT_MODE_SOLARIZE -> "Solarize"
CameraCharacteristics.CONTROL_EFFECT_MODE_WHITEBOARD -> "Whiteboard"
else -> {
"Unkownn ${it}"
}
})
}
} /*else if (CameraCharacteristics.CONTROL_AVAILABLE_MODES == key) {
val modes = characteristics.get(key) as IntArray
modes.forEach {
values.add(when (it) {
CameraCharacteristics.CONTROL_MODE_OFF -> "Off"
CameraCharacteristics.CONTROL_MODE_OFF_KEEP_STATE -> "Off Keep State"
CameraCharacteristics.CONTROL_MODE_AUTO -> "Auto"
CameraCharacteristics.CONTROL_MODE_USE_SCENE_MODE -> "Use Scene Mode"
else -> {
"Unkownn ${it}"
}
})
}
}*/ else if (CameraCharacteristics.CONTROL_AVAILABLE_SCENE_MODES == key) {
val modes = characteristics.get(key) as IntArray
modes.forEach {
values.add(when (it) {
CameraCharacteristics.CONTROL_SCENE_MODE_DISABLED -> "Disabled"
CameraCharacteristics.CONTROL_SCENE_MODE_ACTION -> "Action"
CameraCharacteristics.CONTROL_SCENE_MODE_BARCODE -> "Barcode"
CameraCharacteristics.CONTROL_SCENE_MODE_BEACH -> "Beach"
CameraCharacteristics.CONTROL_SCENE_MODE_CANDLELIGHT -> "Candlelight"
CameraCharacteristics.CONTROL_SCENE_MODE_FACE_PRIORITY -> "Face Priority"
CameraCharacteristics.CONTROL_SCENE_MODE_FIREWORKS -> "Fireworks"
CameraCharacteristics.CONTROL_SCENE_MODE_HDR -> "HDR"
CameraCharacteristics.CONTROL_SCENE_MODE_LANDSCAPE -> "Landscape"
CameraCharacteristics.CONTROL_SCENE_MODE_NIGHT -> "Night"
CameraCharacteristics.CONTROL_SCENE_MODE_NIGHT_PORTRAIT -> "Night Portrait"
CameraCharacteristics.CONTROL_SCENE_MODE_PARTY -> "Party"
CameraCharacteristics.CONTROL_SCENE_MODE_PORTRAIT -> "Portrait"
CameraCharacteristics.CONTROL_SCENE_MODE_SNOW -> "Snow"
CameraCharacteristics.CONTROL_SCENE_MODE_SPORTS -> "Sports"
CameraCharacteristics.CONTROL_SCENE_MODE_STEADYPHOTO -> "Steady Photo"
CameraCharacteristics.CONTROL_SCENE_MODE_SUNSET -> "Sunset"
CameraCharacteristics.CONTROL_SCENE_MODE_THEATRE -> "Theatre"
CameraCharacteristics.CONTROL_SCENE_MODE_HIGH_SPEED_VIDEO -> "High Speed Video"
else -> {
"Unkownn ${it}"
}
})
}
} else if (CameraCharacteristics.CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES == key) {
val modes = characteristics.get(key) as IntArray
modes.forEach {
values.add(when (it) {
CameraCharacteristics.CONTROL_VIDEO_STABILIZATION_MODE_ON -> "On"
CameraCharacteristics.CONTROL_VIDEO_STABILIZATION_MODE_OFF -> "Off"
else -> {
"Unkownn ${it}"
}
})
}
} else if (CameraCharacteristics.CONTROL_AWB_AVAILABLE_MODES == key) {
} /*else if (CameraCharacteristics.CONTROL_AWB_LOCK_AVAILABLE == key) {
} */ else if (CameraCharacteristics.CONTROL_MAX_REGIONS_AE == key) {
} else if (CameraCharacteristics.CONTROL_MAX_REGIONS_AF == key) {
} else if (CameraCharacteristics.CONTROL_MAX_REGIONS_AWB == key) {
} /*else if (CameraCharacteristics.CONTROL_POST_RAW_SENSITIVITY_BOOST_RANGE == key) {
} else if (CameraCharacteristics.DEPTH_DEPTH_IS_EXCLUSIVE == key) {
}*/ else if (CameraCharacteristics.EDGE_AVAILABLE_EDGE_MODES == key) {
} else if (CameraCharacteristics.FLASH_INFO_AVAILABLE == key) {
} else if (CameraCharacteristics.HOT_PIXEL_AVAILABLE_HOT_PIXEL_MODES == key) {
} else if (CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL == key) {
} else if (CameraCharacteristics.JPEG_AVAILABLE_THUMBNAIL_SIZES == key) {
} else if (CameraCharacteristics.LENS_FACING == key) {
val facing = characteristics.get(key)
values.add(
when (facing) {
CameraCharacteristics.LENS_FACING_BACK -> "Back"
CameraCharacteristics.LENS_FACING_FRONT -> "Front"
CameraCharacteristics.LENS_FACING_EXTERNAL -> "External"
else -> "Unkown"
}
)
} else if (CameraCharacteristics.LENS_INFO_AVAILABLE_APERTURES == key) {
} else if (CameraCharacteristics.LENS_INFO_AVAILABLE_FILTER_DENSITIES == key) {
} else if (CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS == key) {
} else if (CameraCharacteristics.LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION == key) {
} else if (CameraCharacteristics.LENS_INFO_FOCUS_DISTANCE_CALIBRATION == key) {
} else if (CameraCharacteristics.LENS_INFO_HYPERFOCAL_DISTANCE == key) {
} else if (CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE == key) {
}/* else if (CameraCharacteristics.LENS_INTRINSIC_CALIBRATION == key) {
} else if (CameraCharacteristics.LENS_POSE_ROTATION == key) {
} /**/else if (CameraCharacteristics.LENS_POSE_TRANSLATION == key) {
} /**/else if (CameraCharacteristics.LENS_RADIAL_DISTORTION == key) {
}*//* else if (CameraCharacteristics.NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES == key) {
} *//*else if (CameraCharacteristics.REPROCESS_MAX_CAPTURE_STALL == key) {
} */ else if (CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES == key) {
} else if (CameraCharacteristics.REQUEST_MAX_NUM_INPUT_STREAMS == key) {
} else if (CameraCharacteristics.REQUEST_MAX_NUM_OUTPUT_PROC == key) {
} else if (CameraCharacteristics.REQUEST_MAX_NUM_OUTPUT_PROC_STALLING == key) {
} else if (CameraCharacteristics.REQUEST_MAX_NUM_OUTPUT_RAW == key) {
} else if (CameraCharacteristics.REQUEST_PARTIAL_RESULT_COUNT == key) {
} else if (CameraCharacteristics.REQUEST_PIPELINE_MAX_DEPTH == key) {
} else if (CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM == key) {
} else if (CameraCharacteristics.SCALER_CROPPING_TYPE == key) {
} else if (CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP == key) {
val map = characteristics.get(key) as StreamConfigurationMap
val outputFormats = map.outputFormats
outputFormats.forEach {
values.add(printOutputFormat(it, map))
}
} else if (CameraCharacteristics.SENSOR_AVAILABLE_TEST_PATTERN_MODES == key) {
} else if (CameraCharacteristics.SENSOR_BLACK_LEVEL_PATTERN == key) {
} else if (CameraCharacteristics.SENSOR_CALIBRATION_TRANSFORM1 == key) {
} else if (CameraCharacteristics.SENSOR_CALIBRATION_TRANSFORM2 == key) {
} else if (CameraCharacteristics.SENSOR_COLOR_TRANSFORM1 == key) {
} else if (CameraCharacteristics.SENSOR_COLOR_TRANSFORM2 == key) {
} else if (CameraCharacteristics.SENSOR_FORWARD_MATRIX1 == key) {
} else if (CameraCharacteristics.SENSOR_FORWARD_MATRIX2 == key) {
} else if (CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE == key) {
} else if (CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT == key) {
} else if (CameraCharacteristics.SENSOR_INFO_EXPOSURE_TIME_RANGE == key) {
} /*else if (CameraCharacteristics.SENSOR_INFO_LENS_SHADING_APPLIED == key) {
} */ else if (CameraCharacteristics.SENSOR_INFO_MAX_FRAME_DURATION == key) {
} else if (CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE == key) {
} else if (CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE == key) {
} /*else if (CameraCharacteristics.SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE == key) {
}*/ else if (CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE == key) {
} else if (CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE == key) {
} else if (CameraCharacteristics.SENSOR_INFO_WHITE_LEVEL == key) {
} else if (CameraCharacteristics.SENSOR_MAX_ANALOG_SENSITIVITY == key) {
} /*else if (CameraCharacteristics.SENSOR_OPTICAL_BLACK_REGIONS == key) {
}*/ else if (CameraCharacteristics.SENSOR_ORIENTATION == key) {
val orientation = characteristics.get(key) as Int
values.add(orientation.toString())
} else if (CameraCharacteristics.SENSOR_REFERENCE_ILLUMINANT1 == key) {
} else if (CameraCharacteristics.SENSOR_REFERENCE_ILLUMINANT2 == key) {
}/* else if (CameraCharacteristics.SHADING_AVAILABLE_MODES == key) {
}*/ else if (CameraCharacteristics.STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES == key) {
} else if (CameraCharacteristics.STATISTICS_INFO_AVAILABLE_HOT_PIXEL_MAP_MODES == key) {
}/* else if (CameraCharacteristics.STATISTICS_INFO_AVAILABLE_LENS_SHADING_MAP_MODES == key) {
}*/ else if (CameraCharacteristics.SYNC_MAX_LATENCY == key) {
} else if (CameraCharacteristics.TONEMAP_AVAILABLE_TONE_MAP_MODES == key) {
} else if (CameraCharacteristics.TONEMAP_MAX_CURVE_POINTS == key) {
}
values.sort()
return if (values.isEmpty()) "" else join(", ", values)
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private fun printOutputFormat(outputFormat: Int, map: StreamConfigurationMap): String {
val formatName = getImageFormat(outputFormat)
val outputSizes = map.getOutputSizes(outputFormat);
val outputSizeValues = mutableListOf<String>()
outputSizes.forEach {
val mp = getMegaPixel(it)
outputSizeValues.add("${it.width}x${it.height} (${mp}MP)")
}
val sizesString = join(", ", outputSizeValues)
return "\n$formatName -> [$sizesString]"
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private fun getMegaPixel(size: Size): String {
val mp = (size.width * size.height) / 1000000f
return String.format("%.1f", mp)
}
private fun getImageFormat(format: Int): String {
return when (format) {
ImageFormat.DEPTH16 -> "DEPTH16"
ImageFormat.DEPTH_POINT_CLOUD -> "DEPTH_POINT_CLOUD"
ImageFormat.FLEX_RGBA_8888 -> "FLEX_RGBA_8888"
ImageFormat.FLEX_RGB_888 -> "FLEX_RGB_888"
ImageFormat.JPEG -> "JPEG"
ImageFormat.NV16 -> "NV16"
ImageFormat.NV21 -> "NV21"
ImageFormat.PRIVATE -> "PRIVATE"
ImageFormat.RAW10 -> "RAW10"
ImageFormat.RAW12 -> "RAW12"
ImageFormat.RAW_PRIVATE -> "RAW_PRIVATE"
ImageFormat.RAW_SENSOR -> "RAW_SENSOR"
ImageFormat.RGB_565 -> "RGB_565"
ImageFormat.YUV_420_888 -> "YUV_420_888"
ImageFormat.YUV_422_888 -> "YUV_422_888"
ImageFormat.YUV_444_888 -> "YUV_444_888"
ImageFormat.YUY2 -> "YUY2"
ImageFormat.YV12 -> "YV12"
else -> "Unkown"
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private fun <T : Comparable<T>> getRangeValue(range: Range<T>): String {
return "[${range.lower},${range.upper}]"
}
fun <T> join(delimiter: String, elements: Collection<T>?): String {
if (null == elements || elements.isEmpty()) {
return ""
}
val sb = StringBuilder()
val iter = elements.iterator()
while (iter.hasNext()) {
val element = iter.next()
sb.append(element.toString())
if (iter.hasNext()) {
sb.append(delimiter)
}
}
return sb.toString()
}
}
| app/src/main/java/com/quixom/apps/deviceinfo/fragments/CameraFragment.kt | 28241640 |
package info.nightscout.androidaps.dialogs
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.common.base.Joiner
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.OKDialog
import info.nightscout.androidaps.utils.SafeParse
import kotlinx.android.synthetic.main.dialog_tempbasal.*
import kotlinx.android.synthetic.main.okcancel.*
import java.text.DecimalFormat
import java.util.*
import kotlin.math.abs
class TempBasalDialog : DialogFragmentWithDate() {
private var isPercentPump = true
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
savedInstanceState.putDouble("actions_tempbasal_duration", actions_tempbasal_duration.value)
savedInstanceState.putDouble("actions_tempbasal_basalpercentinput", actions_tempbasal_basalpercentinput.value)
savedInstanceState.putDouble("actions_tempbasal_basalabsoluteinput", actions_tempbasal_basalabsoluteinput.value)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
onCreateViewGeneral()
return inflater.inflate(R.layout.dialog_tempbasal, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val pumpDescription = ConfigBuilderPlugin.getPlugin().activePump?.pumpDescription ?: return
val profile = ProfileFunctions.getInstance().profile ?: return
val maxTempPercent = pumpDescription.maxTempPercent.toDouble()
val tempPercentStep = pumpDescription.tempPercentStep.toDouble()
actions_tempbasal_basalpercentinput.setParams(savedInstanceState?.getDouble("actions_tempbasal_basalpercentinput")
?: 100.0, 0.0, maxTempPercent, tempPercentStep, DecimalFormat("0"), true, ok)
actions_tempbasal_basalabsoluteinput.setParams(savedInstanceState?.getDouble("actions_tempbasal_basalabsoluteinput")
?: profile.basal, 0.0, pumpDescription.maxTempAbsolute, pumpDescription.tempAbsoluteStep, DecimalFormat("0.00"), true, ok)
val tempDurationStep = pumpDescription.tempDurationStep.toDouble()
val tempMaxDuration = pumpDescription.tempMaxDuration.toDouble()
actions_tempbasal_duration.setParams(savedInstanceState?.getDouble("actions_tempbasal_duration")
?: tempDurationStep, tempDurationStep, tempMaxDuration, tempDurationStep, DecimalFormat("0"), false, ok)
isPercentPump = pumpDescription.tempBasalStyle and PumpDescription.PERCENT == PumpDescription.PERCENT
if (isPercentPump) {
actions_tempbasal_percent_layout.visibility = View.VISIBLE
actions_tempbasal_absolute_layout.visibility = View.GONE
} else {
actions_tempbasal_percent_layout.visibility = View.GONE
actions_tempbasal_absolute_layout.visibility = View.VISIBLE
}
}
override fun submit(): Boolean {
var percent = 0
var absolute = 0.0
val durationInMinutes = SafeParse.stringToInt(actions_tempbasal_duration.text)
val profile = ProfileFunctions.getInstance().profile ?: return false
val actions: LinkedList<String> = LinkedList()
if (isPercentPump) {
val basalPercentInput = SafeParse.stringToInt(actions_tempbasal_basalpercentinput.text)
percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(Constraint(basalPercentInput), profile).value()
actions.add(MainApp.gs(R.string.pump_tempbasal_label)+ ": $percent%")
actions.add(MainApp.gs(R.string.duration) + ": " + MainApp.gs(R.string.format_mins, durationInMinutes))
if (percent != basalPercentInput) actions.add(MainApp.gs(R.string.constraintapllied))
} else {
val basalAbsoluteInput = SafeParse.stringToDouble(actions_tempbasal_basalabsoluteinput.text)
absolute = MainApp.getConstraintChecker().applyBasalConstraints(Constraint(basalAbsoluteInput), profile).value()
actions.add(MainApp.gs(R.string.pump_tempbasal_label)+ ": " + MainApp.gs(R.string.pump_basebasalrate, absolute))
actions.add(MainApp.gs(R.string.duration) + ": " + MainApp.gs(R.string.format_mins, durationInMinutes))
if (abs(absolute - basalAbsoluteInput) > 0.01)
actions.add("<font color='" + MainApp.gc(R.color.warning) + "'>" + MainApp.gs(R.string.constraintapllied) + "</font>")
}
activity?.let { activity ->
OKDialog.showConfirmation(activity, MainApp.gs(R.string.pump_tempbasal_label), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable {
val callback: Callback = object : Callback() {
override fun run() {
if (!result.success) {
val i = Intent(MainApp.instance(), ErrorHelperActivity::class.java)
i.putExtra("soundid", R.raw.boluserror)
i.putExtra("status", result.comment)
i.putExtra("title", MainApp.gs(R.string.tempbasaldeliveryerror))
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
MainApp.instance().startActivity(i)
}
}
}
if (isPercentPump) {
log.debug("USER ENTRY: TEMP BASAL $percent% duration: $durationInMinutes")
ConfigBuilderPlugin.getPlugin().commandQueue.tempBasalPercent(percent, durationInMinutes, true, profile, callback)
} else {
log.debug("USER ENTRY: TEMP BASAL $absolute duration: $durationInMinutes")
ConfigBuilderPlugin.getPlugin().commandQueue.tempBasalAbsolute(absolute, durationInMinutes, true, profile, callback)
}
})
}
return true
}
} | app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt | 492961601 |
package com.habitrpg.android.habitica.models
class SetupCustomization {
var key: String = ""
var drawableId: Int? = null
var colorId: Int? = null
var text: String = ""
var path: String = ""
var category: String = ""
var subcategory: String = ""
companion object {
fun createSize(key: String, drawableId: Int, text: String): SetupCustomization {
val customization = SetupCustomization()
customization.key = key
customization.drawableId = drawableId
customization.text = text
customization.path = "size"
customization.category = "body"
customization.subcategory = "size"
return customization
}
fun createShirt(key: String, drawableId: Int): SetupCustomization {
val customization = SetupCustomization()
customization.key = key
customization.drawableId = drawableId
customization.path = "shirt"
customization.category = "body"
customization.subcategory = "shirt"
return customization
}
fun createSkin(key: String, colorId: Int?): SetupCustomization {
val customization = SetupCustomization()
customization.key = key
customization.colorId = colorId
customization.path = "skin"
customization.category = "skin"
return customization
}
fun createHairColor(key: String, colorId: Int?): SetupCustomization {
val customization = SetupCustomization()
customization.key = key
customization.colorId = colorId
customization.path = "hair.color"
customization.category = "hair"
customization.subcategory = "color"
return customization
}
fun createHairBangs(key: String, drawableId: Int?): SetupCustomization {
val customization = SetupCustomization()
customization.key = key
customization.drawableId = drawableId
customization.path = "hair.bangs"
customization.category = "hair"
customization.subcategory = "bangs"
return customization
}
fun createHairPonytail(key: String, drawableId: Int?): SetupCustomization {
val customization = SetupCustomization()
customization.key = key
customization.drawableId = drawableId
customization.path = "hair.base"
customization.category = "hair"
customization.subcategory = "base"
return customization
}
fun createGlasses(key: String, drawableId: Int?): SetupCustomization {
val customization = SetupCustomization()
customization.key = key
customization.drawableId = drawableId
customization.path = "glasses"
customization.category = "extras"
customization.subcategory = "glasses"
return customization
}
fun createFlower(key: String, drawableId: Int?): SetupCustomization {
val customization = SetupCustomization()
customization.key = key
customization.drawableId = drawableId
customization.path = "hair.flower"
customization.category = "extras"
customization.subcategory = "flower"
return customization
}
fun createWheelchair(key: String, drawableId: Int?): SetupCustomization {
val customization = SetupCustomization()
customization.key = key
customization.drawableId = drawableId
customization.path = "chair"
customization.category = "extras"
customization.subcategory = "wheelchair"
return customization
}
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/models/SetupCustomization.kt | 3851999881 |
package com.cout970.reactive.dsl
import com.cout970.reactive.core.RBuilder
import com.cout970.reactive.core.Renderer
import com.cout970.reactive.nodes.ComponentBuilder
import com.cout970.reactive.nodes.comp
import org.liquidengine.legui.component.Component
import org.liquidengine.legui.event.Event
import org.liquidengine.legui.listener.EventListener
import org.liquidengine.legui.listener.ListenerMap
/**
* This function converts all the children of this component to RNodes so they are not ignored/removed by
* the reconciliation algorithm
*/
fun <T : Component> ComponentBuilder<T>.childrenAsNodes() {
this.component.childComponents.forEach {
comp(it) {
if (!it.isEmpty) {
childrenAsNodes()
}
}
}
}
/**
* This stores a function in a component, this function will be called after the component is mounted in
* the component tree.
*
* The order of execution of this function is the following:
* - The parent function gets called if exist
* - Then for every child, it's function is called if exists, this follows the childComponents order in the parent
*/
fun RBuilder.postMount(func: Component.() -> Unit) {
val oldDeferred = this.deferred
this.deferred = {
val oldFunc = it.metadata[Renderer.METADATA_POST_MOUNT]
// Preserve the old postMount
val finalFunc = if (oldFunc != null) {
val comb: Component.() -> Unit = {
(oldFunc as? (Component.() -> Unit))?.invoke(this)
func()
}
comb
} else {
func
}
it.metadata[Renderer.METADATA_POST_MOUNT] = finalFunc
oldDeferred?.invoke(it)
}
}
/**
* Given a key, finds a child of this component with it or returns null
*/
fun Component.child(key: String): Component? {
return childComponents.find { it.metadata[Renderer.METADATA_KEY] == key }
}
fun <E : Event<*>> ListenerMap.replaceListener(eventClass: Class<E>, listener: EventListener<E>) {
getListeners<E>(eventClass).firstOrNull()?.let { removeListener(eventClass, it) }
getListeners<E>(eventClass).add(listener)
} | src/main/kotlin/com/cout970/reactive/dsl/Util.kt | 3782230929 |
package org.jetbrains.plugins.notebooks.visualization
import com.intellij.openapi.editor.event.DocumentEvent
/**
* Passed to NotebookCellLines.IntervalListener when document is changed.
*
* Intervals that were just shifted are included neither [oldIntervals], nor in [newIntervals].
*
* Intervals in the lists are valid only until the document changes. Check their validity
* when postponing handling of intervals.
*
* If document is changed, but intervals aren’t changed, both [oldIntervals] and [newIntervals] are empty,
* and the [modificationStamp] stamp doesn’t change.
*
* [oldAffectedIntervals] and [oldAffectedIntervals] are same as event.oldFragment and event.newFragment
* [oldAffectedIntervals] are intervals containing oldFragment and same with [newAffectedIntervals]
*
* If existing line is edited, [oldAffectedIntervals] and/or [newAffectedIntervals] contain interval with the line,
* but [oldIntervals] and [newIntervals] are empty.
*
* Both [oldAffectedIntervals] and [newAffectedIntervals] are necessary to distinguish last cell line removing and whole cell removing.
* "#%%\n 1 \n\n#%%\n 2" -> "#%%\n 1 \n": [oldAffectedIntervals] contains second cell, [newAffectedIntervals] are empty
* ^^^^^^^^^
* "#%%\n 1 \n text" -> "#%%\n 1 \n": [oldAffectedIntervals] contain cell, [newAffectedIntervals] are empty
* ^^^^^
* "#%%\n 1 text \n#%%\n 2" -> "#%% 1 \n#%%\n new": [oldAffectedIntervals] contain all cells,
* ^^^^^^^^^^^^^^ ^^^^^^^^^^^
* [newAffectedIntervals] contain only second cell, because range of inserted text related to second cell only
*
* It is guaranteed that:
* * Ordinals from every list defines an arithmetical progression where
* every next element has ordinal of the previous element incremented by one.
* * If oldIntervals and newIntervals lists are not empty, the first elements of both lists has the same ordinal.
* * Both lists don't contain any interval that has been only shifted, shrank or enlarged.
*
* See `NotebookCellLinesTest` for examples of calls for various changes.
*/
data class NotebookCellLinesEvent(
val documentEvent: DocumentEvent,
val oldIntervals: List<NotebookCellLines.Interval>,
val oldAffectedIntervals: List<NotebookCellLines.Interval>,
val newIntervals: List<NotebookCellLines.Interval>,
val newAffectedIntervals: List<NotebookCellLines.Interval>,
val modificationStamp: Long,
) {
fun isIntervalsChanged(): Boolean =
!(oldIntervals.isEmpty() && newIntervals.isEmpty())
} | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/NotebookCellLinesEvent.kt | 2024300872 |
package org.purescript.psi.expression
import com.intellij.lang.ASTNode
import org.purescript.psi.PSPsiElement
import org.purescript.psi.name.PSQualifiedSymbol
/**
* A Operator in an expression, e.g.
* ```
* P.(+)
* ```
* in
* ```
* import Prelude as P
* f = P.(+) 1 3
* ```
*/
class PSExpressionSymbol(node: ASTNode) : PSPsiElement(node) {
/**
* @return the [PSQualifiedSymbol] identifying this constructor
*/
internal val qualifiedSymbol: PSQualifiedSymbol
get() = findNotNullChildByClass(PSQualifiedSymbol::class.java)
override fun getName(): String = qualifiedSymbol.name
override fun getReference() =
ExpressionSymbolReference(this, qualifiedSymbol.symbol.operator)
} | src/main/kotlin/org/purescript/psi/expression/PSExpressionSymbol.kt | 1867762872 |
fun returnFun() {}
fun usage(a: Int?): Int {
a ?: re<caret>
return 10
}
// ORDER: return
// ORDER: returnFun
| plugins/kotlin/completion/tests/testData/weighers/basic/contextualReturn/withReturnType/InElvis.kt | 1365627351 |
// SET_FALSE: METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE
// SET_TRUE: METHOD_PARAMETERS_RPAREN_ON_NEXT_LINE
fun foo(p: Int, c: Char, b: <caret>Boolean) {
} | plugins/kotlin/idea/tests/testData/intentions/chop/parameterList/leftParOnSameLine.kt | 890639683 |
package io.mironov.sento.sample.extensions
fun <T> Any?.notNull(): T {
return null as T
}
fun Any?.asTrue(): Boolean {
return true
}
fun Any?.asFalse(): Boolean {
return false
}
| sento-sample/src/main/java/io/mironov/sento/sample/extensions/AnyExtensions.kt | 4157404746 |
package com.intellij.configurationStore
import com.intellij.openapi.Disposable
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.JDOMUtil
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.codeStyle.CodeStyleSettingsProvider
import com.intellij.psi.codeStyle.CustomCodeStyleSettings
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.ProjectRule
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.loadElement
import org.assertj.core.api.Assertions.assertThat
import org.jdom.Element
import org.junit.ClassRule
import org.junit.Test
class CodeStyleTest {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule()
}
@Test fun `do not remove unknown`() {
val settings = CodeStyleSettings()
val loaded = """
<code_scheme name="testSchemeName">
<UnknownDoNotRemoveMe>
<option name="ALIGN_OBJECT_PROPERTIES" value="2" />
</UnknownDoNotRemoveMe>
<codeStyleSettings language="CoffeeScript">
<option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" />
</codeStyleSettings>
<codeStyleSettings language="Gherkin">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="SQL">
<option name="KEEP_LINE_BREAKS" value="false" />
<option name="KEEP_BLANK_LINES_IN_CODE" value="10" />
</codeStyleSettings>
</code_scheme>""".trimIndent()
settings.readExternal(loadElement(loaded))
val serialized = Element("code_scheme").setAttribute("name", "testSchemeName")
settings.writeExternal(serialized)
assertThat(JDOMUtil.writeElement(serialized)).isEqualTo(loaded)
}
@Test fun `do not duplicate known extra sections`() {
val newProvider: CodeStyleSettingsProvider = object : CodeStyleSettingsProvider() {
override fun createCustomSettings(settings: CodeStyleSettings?): CustomCodeStyleSettings {
return object : CustomCodeStyleSettings("NewComponent", settings) {
override fun getKnownTagNames(): List<String> {
return ContainerUtil.concat(super.getKnownTagNames(), listOf("NewComponent-extra"))
}
override fun readExternal(parentElement: Element?) {
super.readExternal(parentElement)
}
override fun writeExternal(parentElement: Element?, parentSettings: CustomCodeStyleSettings) {
super.writeExternal(parentElement, parentSettings)
writeMain(parentElement)
writeExtra(parentElement)
}
private fun writeMain(parentElement: Element?) {
var extra = parentElement!!.getChild(tagName)
if (extra == null) {
extra = Element(tagName)
parentElement.addContent(extra)
}
val option = Element("option")
option.setAttribute("name", "MAIN")
option.setAttribute("value", "3")
extra.addContent(option)
}
private fun writeExtra(parentElement: Element?) {
val extra = Element("NewComponent-extra")
val option = Element("option")
option.setAttribute("name", "EXTRA")
option.setAttribute("value", "3")
extra.addContent(option)
parentElement!!.addContent(extra)
}
}
}
override fun createSettingsPage(settings: CodeStyleSettings?, originalSettings: CodeStyleSettings?): Configurable {
throw UnsupportedOperationException("not implemented")
}
}
val disposable = Disposable() {}
PlatformTestUtil.registerExtension(com.intellij.psi.codeStyle.CodeStyleSettingsProvider.EXTENSION_POINT_NAME,
newProvider, disposable)
try {
val settings = CodeStyleSettings()
val text : (param: String) -> String = { param ->
"""
<code_scheme name="testSchemeName">
<NewComponent>
<option name="MAIN" value="${param}" />
</NewComponent>
<NewComponent-extra>
<option name="EXTRA" value="${param}" />
</NewComponent-extra>
<codeStyleSettings language="CoffeeScript">
<option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" />
</codeStyleSettings>
<codeStyleSettings language="Gherkin">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="SQL">
<option name="KEEP_LINE_BREAKS" value="false" />
<option name="KEEP_BLANK_LINES_IN_CODE" value="10" />
</codeStyleSettings>
</code_scheme>""".trimIndent()
}
settings.readExternal(loadElement(text("2")))
val serialized = Element("code_scheme").setAttribute("name", "testSchemeName")
settings.writeExternal(serialized)
assertThat(JDOMUtil.writeElement(serialized)).isEqualTo(text("3"))
}
finally {
Disposer.dispose(disposable)
}
}
} | platform/configuration-store-impl/testSrc/CodeStyleTest.kt | 2161681091 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger.frame
import com.intellij.icons.AllIcons
import com.intellij.ui.ColoredTextContainer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XStackFrame
import org.jetbrains.concurrency.Promise
import org.jetbrains.debugger.*
// isInLibraryContent call could be costly, so we compute it only once (our customizePresentation called on each repaint)
class CallFrameView @JvmOverloads constructor(val callFrame: CallFrame,
override val viewSupport: DebuggerViewSupport,
val script: Script? = null,
sourceInfo: SourceInfo? = null,
isInLibraryContent: Boolean? = null,
override val vm: Vm? = null) : XStackFrame(), VariableContext {
private val sourceInfo = sourceInfo ?: viewSupport.getSourceInfo(script, callFrame)
private val isInLibraryContent: Boolean = isInLibraryContent ?: (this.sourceInfo != null && viewSupport.isInLibraryContent(this.sourceInfo, script))
private var evaluator: XDebuggerEvaluator? = null
override fun getEqualityObject() = callFrame.equalityObject
override fun computeChildren(node: XCompositeNode) {
node.setAlreadySorted(true)
createAndAddScopeList(node, callFrame.variableScopes, this, callFrame)
}
override val evaluateContext: EvaluateContext
get() = callFrame.evaluateContext
override fun watchableAsEvaluationExpression() = true
override val memberFilter: Promise<MemberFilter>
get() = viewSupport.getMemberFilter(this)
fun getMemberFilter(scope: Scope) = createVariableContext(scope, this, callFrame).memberFilter
override fun getEvaluator(): XDebuggerEvaluator? {
if (evaluator == null) {
evaluator = viewSupport.createFrameEvaluator(this)
}
return evaluator
}
override fun getSourcePosition() = sourceInfo
override fun customizePresentation(component: ColoredTextContainer) {
if (sourceInfo == null) {
val scriptName = if (script == null) "unknown" else script.url.trimParameters().toDecodedForm()
val line = callFrame.line
component.append(if (line == -1) scriptName else "$scriptName:$line", SimpleTextAttributes.ERROR_ATTRIBUTES)
return
}
val fileName = sourceInfo.file.name
val line = sourceInfo.line + 1
val textAttributes =
if (isInLibraryContent || callFrame.isFromAsyncStack) SimpleTextAttributes.GRAYED_ATTRIBUTES
else SimpleTextAttributes.REGULAR_ATTRIBUTES
val functionName = sourceInfo.functionName
if (functionName == null || (functionName.isEmpty() && callFrame.hasOnlyGlobalScope)) {
if (fileName.startsWith("index.")) {
sourceInfo.file.parent?.let {
component.append("${it.name}/", textAttributes)
}
}
component.append("$fileName:$line", textAttributes)
}
else {
if (functionName.isEmpty()) {
component.append("anonymous", if (isInLibraryContent) SimpleTextAttributes.GRAYED_ITALIC_ATTRIBUTES else SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES)
}
else {
component.append(functionName, textAttributes)
}
component.append("(), $fileName:$line", textAttributes)
}
component.setIcon(AllIcons.Debugger.StackFrame)
}
} | platform/script-debugger/debugger-ui/src/CallFrameView.kt | 2533977903 |
package pl.srw.billcalculator.form
import android.arch.core.executor.testing.InstantTaskExecutorRule
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.Observer
import com.nhaarman.mockito_kotlin.*
import io.reactivex.Single
import junitparams.JUnitParamsRunner
import junitparams.Parameters
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestRule
import org.junit.runner.RunWith
import pl.srw.billcalculator.RxJavaBaseTest
import pl.srw.billcalculator.data.bill.ReadingsRepo
import pl.srw.billcalculator.data.settings.prices.EnergyTariff
import pl.srw.billcalculator.data.settings.prices.PricesRepo
import pl.srw.billcalculator.type.Provider
@RunWith(JUnitParamsRunner::class)
class FormPreviousReadingsVMTest : RxJavaBaseTest() {
@get:Rule val rule: TestRule = InstantTaskExecutorRule()
val readings = intArrayOf(1, 2, 3)
val readingsRepo: ReadingsRepo = mock {
on { getPreviousReadingsFor(any()) } doReturn Single.just(readings)
}
val tariffLiveData = MutableLiveData<EnergyTariff>()
val pricesRepo: PricesRepo = mock {
on { tariffPge } doReturn tariffLiveData
on { tariffTauron } doReturn tariffLiveData
}
val testObserver: Observer<IntArray> = mock()
lateinit var sut: FormPreviousReadingsVM
@Test
@Parameters("PGNIG", "PGE", "TAURON")
fun `fetches single previous readings for PGNIG or G11 tariff`(provider: Provider) {
setTariff(EnergyTariff.G11)
init(provider)
sut.singlePrevReadings.observeForever(testObserver)
verify(testObserver).onChanged(readings)
}
@Test
@Parameters("PGNIG", "PGE", "TAURON")
fun `does not fetch double previous readings for PGNIG or G11 tariff`(provider: Provider) {
setTariff(EnergyTariff.G11)
init(provider)
sut.dayPrevReadings.observeForever(testObserver)
sut.nightPrevReadings.observeForever(testObserver)
verify(testObserver, never()).onChanged(readings)
}
@Test
@Parameters("PGE", "TAURON")
fun `fetches double previous readings for G12 tariff`(provider: Provider) {
setTariff(EnergyTariff.G12)
init(provider)
sut.dayPrevReadings.observeForever(testObserver)
sut.nightPrevReadings.observeForever(testObserver)
verify(testObserver, times(2)).onChanged(readings)
}
@Test
@Parameters("PGE", "TAURON")
fun `does not fetch single previous readings for G12 tariff`(provider: Provider) {
setTariff(EnergyTariff.G12)
init(provider)
sut.singlePrevReadings.observeForever(testObserver)
verify(testObserver, never()).onChanged(readings)
}
@Test
@Parameters("PGE", "TAURON")
fun `fetch previous readings when tariff changes`(provider: Provider) {
setTariff(EnergyTariff.G11)
init(provider)
sut.dayPrevReadings.observeForever(testObserver)
sut.nightPrevReadings.observeForever(testObserver)
clearInvocations(testObserver, readingsRepo)
setTariff(EnergyTariff.G12)
verify(readingsRepo, times(2)).getPreviousReadingsFor(any())
verify(testObserver, times(2)).onChanged(readings)
}
@Test
@Parameters("PGE", "TAURON")
fun `does not re-fetch previous readings but notifies cached value, when view re-attached`(provider: Provider) {
setTariff(EnergyTariff.G11)
init(provider)
sut.singlePrevReadings.observeForever(testObserver)
clearInvocations(readingsRepo)
val afterReAttachObserver: Observer<IntArray> = mock()
sut.singlePrevReadings.observeForever(afterReAttachObserver)
verify(readingsRepo, never()).getPreviousReadingsFor(any())
verify(afterReAttachObserver).onChanged(readings)
}
private fun setTariff(tariff: EnergyTariff) {
tariffLiveData.value = tariff
waitToFinish() // tariff change after observing trigger prev reading fetch
}
private fun init(provider: Provider) {
sut = FormPreviousReadingsVM(provider, readingsRepo, pricesRepo)
waitToFinish() // constructor is triggering prev readings fetch
}
}
| app/src/test/java/pl/srw/billcalculator/form/FormPreviousReadingsVMTest.kt | 3828911689 |
// 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.nj2k.conversions
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.tree.*
import java.math.BigInteger
class LiteralConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (element !is JKLiteralExpression) return recurse(element)
val convertedElement = try {
element.apply { convertLiteral() }
} catch (_: NumberFormatException) {
createTodoCall(cannotConvertLiteralMessage(element))
}
return recurse(convertedElement)
}
private fun createTodoCall(@NonNls message: String): JKCallExpressionImpl {
val todoMethodSymbol = symbolProvider.provideMethodSymbol("kotlin.TODO")
val todoMessageArgument = JKArgumentImpl(JKLiteralExpression("\"$message\"", JKLiteralExpression.LiteralType.STRING))
return JKCallExpressionImpl(todoMethodSymbol, JKArgumentList(todoMessageArgument))
}
private fun cannotConvertLiteralMessage(element: JKLiteralExpression): String {
val literalType = element.type.toString().toLowerCase()
val literalValue = element.literal
return "Could not convert $literalType literal '$literalValue' to Kotlin"
}
private fun JKLiteralExpression.convertLiteral() {
literal = when (type) {
JKLiteralExpression.LiteralType.DOUBLE -> toDoubleLiteral()
JKLiteralExpression.LiteralType.FLOAT -> toFloatLiteral()
JKLiteralExpression.LiteralType.LONG -> toLongLiteral()
JKLiteralExpression.LiteralType.INT -> toIntLiteral()
JKLiteralExpression.LiteralType.CHAR -> convertCharLiteral()
JKLiteralExpression.LiteralType.STRING -> toStringLiteral()
else -> return
}
}
private fun JKLiteralExpression.toDoubleLiteral() =
literal.cleanFloatAndDoubleLiterals().let { text ->
if (!text.contains(".") && !text.contains("e", true))
"$text."
else text
}.let { text ->
if (text.endsWith(".")) "${text}0" else text
}
private fun JKLiteralExpression.toFloatLiteral() =
literal.cleanFloatAndDoubleLiterals().let { text ->
if (!text.endsWith("f")) "${text}f"
else text
}
private fun JKLiteralExpression.toStringLiteral() =
literal.replace("""((?:\\)*)\\([0-3]?[0-7]{1,2})""".toRegex()) { matchResult ->
val leadingBackslashes = matchResult.groupValues[1]
if (leadingBackslashes.length % 2 == 0)
String.format("%s\\u%04x", leadingBackslashes, Integer.parseInt(matchResult.groupValues[2], 8))
else matchResult.value
}.replace("""(?<!\\)\$([A-Za-z]+|\{)""".toRegex(), "\\\\$0")
private fun JKLiteralExpression.convertCharLiteral() =
literal.replace("""\\([0-3]?[0-7]{1,2})""".toRegex()) {
String.format("\\u%04x", Integer.parseInt(it.groupValues[1], 8))
}
private fun JKLiteralExpression.toIntLiteral() =
literal
.cleanIntAndLongLiterals()
.convertHexLiteral(isLongLiteral = false)
.convertBinaryLiteral(isLongLiteral = false)
.convertOctalLiteral(isLongLiteral = false)
private fun JKLiteralExpression.toLongLiteral() =
literal
.cleanIntAndLongLiterals()
.convertHexLiteral(isLongLiteral = true)
.convertBinaryLiteral(isLongLiteral = true)
.convertOctalLiteral(isLongLiteral = true) + "L"
private fun String.convertHexLiteral(isLongLiteral: Boolean): String {
if (!startsWith("0x", ignoreCase = true)) return this
val value = BigInteger(drop(2), 16)
return when {
isLongLiteral && value.bitLength() > 63 ->
"-0x${value.toLong().toString(16).substring(1)}"
!isLongLiteral && value.bitLength() > 31 ->
"-0x${value.toInt().toString(16).substring(1)}"
else -> this
}
}
private fun String.convertBinaryLiteral(isLongLiteral: Boolean): String {
if (!startsWith("0b", ignoreCase = true)) return this
val value = BigInteger(drop(2), 2)
return if (isLongLiteral) value.toLong().toString(10) else value.toInt().toString()
}
private fun String.convertOctalLiteral(isLongLiteral: Boolean): String {
if (!startsWith("0") || length == 1 || get(1).toLowerCase() == 'x') return this
val value = BigInteger(drop(1), 8)
return if (isLongLiteral) value.toLong().toString(10) else value.toInt().toString(10)
}
private fun String.cleanFloatAndDoubleLiterals() =
replace("L", "", ignoreCase = true)
.replace("d", "", ignoreCase = true)
.replace(".e", "e", ignoreCase = true)
.replace(".f", "", ignoreCase = true)
.replace("f", "", ignoreCase = true)
.replace("_", "")
private fun String.cleanIntAndLongLiterals() =
replace("l", "", ignoreCase = true)
.replace("_", "")
}
| plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/LiteralConversion.kt | 1638200812 |
// "Add '@JvmName' annotation" "true"
// WITH_RUNTIME
interface Foo<T>
fun Foo<Int>.foo() = this
fun <caret>Foo<String>.foo() = this | plugins/kotlin/idea/tests/testData/quickfix/addJvmNameAnnotation/extension.kt | 2410891068 |
/*
* Copyright 2010-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 kotlin
import kotlin.native.internal.ExportForCompiler
import kotlin.native.internal.ExportTypeInfo
import kotlin.native.internal.PointsTo
/**
* Represents an array. Array instances can be created using the constructor, [arrayOf], [arrayOfNulls] and [emptyArray]
* standard library functions.
* See [Kotlin language documentation](https://kotlinlang.org/docs/reference/basic-types.html#arrays)
* for more information on arrays.
*/
@ExportTypeInfo("theArrayTypeInfo")
public final class Array<T> {
/**
* Creates a new array with the specified [size], where each element is calculated by calling the specified
* [init] function.
*
* The function [init] is called for each array element sequentially starting from the first one.
* It should return the value for an array element given its index.
*/
@Suppress("TYPE_PARAMETER_AS_REIFIED")
public constructor(size: Int, init: (Int) -> T): this(size) {
var index = 0
while (index < size) {
this[index] = init(index)
index++
}
}
@PublishedApi
@ExportForCompiler
internal constructor(@Suppress("UNUSED_PARAMETER") size: Int) {}
/**
* Returns the number of elements in the array.
*/
public val size: Int
get() = getArrayLength()
/**
* Returns the array element at the specified [index]. This method can be called using the
* index operator.
* ```
* value = arr[index]
* ```
*
* If the [index] is out of bounds of this array, throws an [IndexOutOfBoundsException].
*/
@SymbolName("Kotlin_Array_get")
@PointsTo(0x000, 0x000, 0x002) // ret -> this.intestines
external public operator fun get(index: Int): T
/**
* Sets the array element at the specified [index] to the specified [value]. This method can
* be called using the index operator.
* ```
* arr[index] = value
* ```
*
* If the [index] is out of bounds of this array, throws an [IndexOutOfBoundsException].
*/
@SymbolName("Kotlin_Array_set")
@PointsTo(0x300, 0x000, 0x000) // this.intestines -> value
external public operator fun set(index: Int, value: T): Unit
/**
* Creates an [Iterator] for iterating over the elements of the array.
*/
public operator fun iterator(): kotlin.collections.Iterator<T> {
return IteratorImpl(this)
}
@SymbolName("Kotlin_Array_getArrayLength")
external private fun getArrayLength(): Int
}
private class IteratorImpl<T>(val collection: Array<T>) : Iterator<T> {
var index : Int = 0
public override fun next(): T {
if (!hasNext()) throw NoSuchElementException("$index")
return collection[index++]
}
public override operator fun hasNext(): Boolean {
return index < collection.size
}
}
| runtime/src/main/kotlin/kotlin/Array.kt | 1267302464 |
// 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.checkers
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.test.Directives
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import org.junit.Assert
import java.util.regex.Pattern
const val LANGUAGE_DIRECTIVE = "LANGUAGE"
const val API_VERSION_DIRECTIVE = "API_VERSION"
const val USE_EXPERIMENTAL_DIRECTIVE = "USE_EXPERIMENTAL"
const val IGNORE_DATA_FLOW_IN_ASSERT_DIRECTIVE = "IGNORE_DATA_FLOW_IN_ASSERT"
const val JVM_DEFAULT_MODE = "JVM_DEFAULT_MODE"
const val SKIP_METADATA_VERSION_CHECK = "SKIP_METADATA_VERSION_CHECK"
const val ALLOW_RESULT_RETURN_TYPE = "ALLOW_RESULT_RETURN_TYPE"
const val INHERIT_MULTIFILE_PARTS = "INHERIT_MULTIFILE_PARTS"
const val SANITIZE_PARENTHESES = "SANITIZE_PARENTHESES"
const val CONSTRAINT_SYSTEM_FOR_OVERLOAD_RESOLUTION = "CONSTRAINT_SYSTEM_FOR_OVERLOAD_RESOLUTION"
const val ENABLE_JVM_PREVIEW = "ENABLE_JVM_PREVIEW"
data class CompilerTestLanguageVersionSettings(
private val initialLanguageFeatures: Map<LanguageFeature, LanguageFeature.State>,
override val apiVersion: ApiVersion,
override val languageVersion: LanguageVersion,
val analysisFlags: Map<AnalysisFlag<*>, Any?> = emptyMap()
) : LanguageVersionSettings {
val extraLanguageFeatures = specificFeaturesForTests() + initialLanguageFeatures
private val delegate = LanguageVersionSettingsImpl(languageVersion, apiVersion, emptyMap(), extraLanguageFeatures)
override fun getFeatureSupport(feature: LanguageFeature): LanguageFeature.State =
extraLanguageFeatures[feature] ?: delegate.getFeatureSupport(feature)
override fun isPreRelease(): Boolean = false
@Suppress("UNCHECKED_CAST")
override fun <T> getFlag(flag: AnalysisFlag<T>): T = analysisFlags[flag] as T? ?: flag.defaultValue
}
private fun specificFeaturesForTests(): Map<LanguageFeature, LanguageFeature.State> {
return if (System.getProperty("kotlin.ni") == "true")
mapOf(LanguageFeature.NewInference to LanguageFeature.State.ENABLED)
else
emptyMap()
}
fun parseLanguageVersionSettingsOrDefault(directiveMap: Directives): CompilerTestLanguageVersionSettings =
parseLanguageVersionSettings(directiveMap) ?: defaultLanguageVersionSettings()
fun parseLanguageVersionSettings(directives: Directives): CompilerTestLanguageVersionSettings? {
val apiVersionString = directives[API_VERSION_DIRECTIVE]
val languageFeaturesString = directives[LANGUAGE_DIRECTIVE]
val analysisFlags = listOfNotNull(
analysisFlag(AnalysisFlags.optIn, directives[USE_EXPERIMENTAL_DIRECTIVE]?.split(' ')),
analysisFlag(JvmAnalysisFlags.jvmDefaultMode, directives[JVM_DEFAULT_MODE]?.let { JvmDefaultMode.fromStringOrNull(it) }),
analysisFlag(AnalysisFlags.ignoreDataFlowInAssert, if (IGNORE_DATA_FLOW_IN_ASSERT_DIRECTIVE in directives) true else null),
analysisFlag(AnalysisFlags.skipMetadataVersionCheck, if (SKIP_METADATA_VERSION_CHECK in directives) true else null),
analysisFlag(AnalysisFlags.allowResultReturnType, if (ALLOW_RESULT_RETURN_TYPE in directives) true else null),
analysisFlag(JvmAnalysisFlags.inheritMultifileParts, if (INHERIT_MULTIFILE_PARTS in directives) true else null),
analysisFlag(JvmAnalysisFlags.sanitizeParentheses, if (SANITIZE_PARENTHESES in directives) true else null),
analysisFlag(JvmAnalysisFlags.enableJvmPreview, if (ENABLE_JVM_PREVIEW in directives) true else null),
analysisFlag(AnalysisFlags.constraintSystemForOverloadResolution, directives[CONSTRAINT_SYSTEM_FOR_OVERLOAD_RESOLUTION]?.let {
ConstraintSystemForOverloadResolutionMode.valueOf(it)
}),
analysisFlag(AnalysisFlags.explicitApiVersion, if (apiVersionString != null) true else null)
)
if (apiVersionString == null && languageFeaturesString == null && analysisFlags.isEmpty()) {
return null
}
val apiVersion = when (apiVersionString) {
null -> KotlinPluginLayout.instance.standaloneCompilerVersion.apiVersion
"LATEST" -> ApiVersion.LATEST
else -> ApiVersion.parse(apiVersionString) ?: error("Unknown API version: $apiVersionString")
}
val languageVersion = maxOf(
KotlinPluginLayout.instance.standaloneCompilerVersion.languageVersion,
LanguageVersion.fromVersionString(apiVersion.versionString)!!
)
val languageFeatures = languageFeaturesString?.let(::collectLanguageFeatureMap).orEmpty()
return CompilerTestLanguageVersionSettings(languageFeatures, apiVersion, languageVersion, mapOf(*analysisFlags.toTypedArray()))
}
fun defaultLanguageVersionSettings(): CompilerTestLanguageVersionSettings {
val bundledKotlinVersion = KotlinPluginLayout.instance.standaloneCompilerVersion
return CompilerTestLanguageVersionSettings(
initialLanguageFeatures = emptyMap(),
bundledKotlinVersion.apiVersion,
bundledKotlinVersion.languageVersion
)
}
fun languageVersionSettingsFromText(fileTexts: List<String>): LanguageVersionSettings {
val allDirectives = Directives()
for (fileText in fileTexts) {
KotlinTestUtils.parseDirectives(fileText, allDirectives)
}
return parseLanguageVersionSettingsOrDefault(allDirectives)
}
@Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE", "HIDDEN")
private fun <T : Any> analysisFlag(flag: AnalysisFlag<T>, value: @kotlin.internal.NoInfer T?): Pair<AnalysisFlag<T>, T>? =
value?.let(flag::to)
private val languagePattern = Pattern.compile("(\\+|-|warn:)(\\w+)\\s*")
private fun collectLanguageFeatureMap(directives: String): Map<LanguageFeature, LanguageFeature.State> {
val matcher = languagePattern.matcher(directives)
if (!matcher.find()) {
Assert.fail(
"Wrong syntax in the '// !$LANGUAGE_DIRECTIVE: ...' directive:\n" +
"found: '$directives'\n" +
"Must be '((+|-|warn:)LanguageFeatureName)+'\n" +
"where '+' means 'enable', '-' means 'disable', 'warn:' means 'enable with warning'\n" +
"and language feature names are names of enum entries in LanguageFeature enum class"
)
}
val values = HashMap<LanguageFeature, LanguageFeature.State>()
do {
val mode = when (matcher.group(1)) {
"+" -> LanguageFeature.State.ENABLED
"-" -> LanguageFeature.State.DISABLED
"warn:" -> LanguageFeature.State.ENABLED_WITH_WARNING
else -> error("Unknown mode for language feature: ${matcher.group(1)}")
}
val name = matcher.group(2)
val feature = LanguageFeature.fromString(name) ?: throw AssertionError(
"Language feature not found, please check spelling: $name\n" +
"Known features:\n ${LanguageFeature.values().joinToString("\n ")}"
)
if (values.put(feature, mode) != null) {
Assert.fail("Duplicate entry for the language feature: $name")
}
}
while (matcher.find())
return values
}
| plugins/kotlin/tests-common/test/org/jetbrains/kotlin/idea/checkers/CompilerTestLanguageVersionSettings.kt | 124159130 |
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.di
import android.content.Context
import androidx.datastore.preferences.SharedPreferencesMigration
import androidx.datastore.preferences.preferencesDataStore
import com.google.samples.apps.iosched.shared.data.prefs.DataStorePreferenceStorage
import com.google.samples.apps.iosched.shared.data.prefs.PreferenceStorage
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@InstallIn(SingletonComponent::class)
@Module
object PreferencesStorageModule {
val Context.dataStore by preferencesDataStore(
name = DataStorePreferenceStorage.PREFS_NAME,
produceMigrations = { context ->
listOf(
SharedPreferencesMigration(
context,
DataStorePreferenceStorage.PREFS_NAME
)
)
}
)
@Singleton
@Provides
fun providePreferenceStorage(@ApplicationContext context: Context): PreferenceStorage =
DataStorePreferenceStorage(context.dataStore)
}
| mobile/src/main/java/com/google/samples/apps/iosched/di/PreferencesStorageModule.kt | 1531823332 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material.icons.generator
import androidx.compose.material.icons.generator.vector.FillType
import androidx.compose.material.icons.generator.vector.PathParser
import androidx.compose.material.icons.generator.vector.Vector
import androidx.compose.material.icons.generator.vector.VectorNode
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParser.END_DOCUMENT
import org.xmlpull.v1.XmlPullParser.END_TAG
import org.xmlpull.v1.XmlPullParser.START_TAG
import org.xmlpull.v1.XmlPullParserException
import org.xmlpull.v1.XmlPullParserFactory
/**
* Parser that converts [icon]s into [Vector]s
*/
class IconParser(private val icon: Icon) {
/**
* @return a [Vector] representing the provided [icon].
*/
fun parse(): Vector {
val parser = XmlPullParserFactory.newInstance().newPullParser().apply {
setInput(icon.fileContent.byteInputStream(), null)
seekToStartTag()
}
check(parser.name == "vector") { "The start tag must be <vector>!" }
parser.next()
val nodes = mutableListOf<VectorNode>()
var currentGroup: VectorNode.Group? = null
while (!parser.isAtEnd()) {
when (parser.eventType) {
START_TAG -> {
when (parser.name) {
PATH -> {
val pathData = parser.getAttributeValue(
null,
PATH_DATA
)
val fillAlpha = parser.getValueAsFloat(FILL_ALPHA)
val strokeAlpha = parser.getValueAsFloat(STROKE_ALPHA)
val fillType = when (parser.getAttributeValue(null, FILL_TYPE)) {
// evenOdd and nonZero are the only supported values here, where
// nonZero is the default if no values are defined.
EVEN_ODD -> FillType.EvenOdd
else -> FillType.NonZero
}
val path = VectorNode.Path(
strokeAlpha = strokeAlpha ?: 1f,
fillAlpha = fillAlpha ?: 1f,
fillType = fillType,
nodes = PathParser.parsePathString(pathData)
)
if (currentGroup != null) {
currentGroup.paths.add(path)
} else {
nodes.add(path)
}
}
// Material icons are simple and don't have nested groups, so this can be simple
GROUP -> {
val group = VectorNode.Group()
currentGroup = group
nodes.add(group)
}
CLIP_PATH -> { /* TODO: b/147418351 - parse clipping paths */
}
}
}
}
parser.next()
}
return Vector(nodes)
}
}
/**
* @return the float value for the attribute [name], or null if it couldn't be found
*/
private fun XmlPullParser.getValueAsFloat(name: String) =
getAttributeValue(null, name)?.toFloatOrNull()
private fun XmlPullParser.seekToStartTag(): XmlPullParser {
var type = next()
while (type != START_TAG && type != END_DOCUMENT) {
// Empty loop
type = next()
}
if (type != START_TAG) {
throw XmlPullParserException("No start tag found")
}
return this
}
private fun XmlPullParser.isAtEnd() =
eventType == END_DOCUMENT || (depth < 1 && eventType == END_TAG)
// XML tag names
private const val CLIP_PATH = "clip-path"
private const val GROUP = "group"
private const val PATH = "path"
// XML attribute names
private const val PATH_DATA = "android:pathData"
private const val FILL_ALPHA = "android:fillAlpha"
private const val STROKE_ALPHA = "android:strokeAlpha"
private const val FILL_TYPE = "android:fillType"
// XML attribute values
private const val EVEN_ODD = "evenOdd"
| compose/material/material/icons/generator/src/main/kotlin/androidx/compose/material/icons/generator/IconParser.kt | 1644907373 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.integration.demos.test
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.SemanticsNodeInteractionCollection
import androidx.compose.ui.test.hasClickAction
import androidx.compose.ui.test.hasScrollToNodeAction
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.isDialog
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollToNode
import androidx.test.espresso.Espresso
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.FlakyTest
import androidx.test.filters.LargeTest
import androidx.wear.compose.integration.demos.Demo
import androidx.wear.compose.integration.demos.DemoActivity
import androidx.wear.compose.integration.demos.DemoCategory
import androidx.wear.compose.integration.demos.WearComposeDemos
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
private val ignoredDemos = listOf<String>(
// Not ignoring any of them \o/
)
@LargeTest
@RunWith(AndroidJUnit4::class)
@OptIn(ExperimentalTestApi::class)
class DemoTest {
// We need to provide the recompose factory first to use new clock.
@get:Rule
val rule = createAndroidComposeRule<DemoActivity>()
@FlakyTest(bugId = 259724403)
@Test
fun navigateThroughAllDemos() {
// Compose integration-tests are split into batches due to size,
// but that's overkill until we have a decent population of tests.
navigateThroughAllDemos(AllButIgnoredDemos)
}
private fun navigateThroughAllDemos(root: DemoCategory, fastForwardClock: Boolean = false) {
// Keep track of each demo we visit.
val visitedDemos = mutableListOf<Demo>()
// Visit all demos.
root.visitDemos(
visitedDemos = visitedDemos,
path = listOf(root),
fastForwardClock = fastForwardClock
)
// Ensure that we visited all the demos we expected to, in the order we expected to.
assertThat(visitedDemos).isEqualTo(root.allDemos())
}
/**
* DFS traversal of each demo in a [DemoCategory] using [Demo.visit]
*
* @param path The path of categories that leads to this demo
*/
private fun DemoCategory.visitDemos(
visitedDemos: MutableList<Demo>,
path: List<DemoCategory>,
fastForwardClock: Boolean
) {
demos.forEach { demo ->
visitedDemos.add(demo)
demo.visit(visitedDemos, path, fastForwardClock)
}
}
/**
* Visits a [Demo], and then navigates back up to the [DemoCategory] it was inside.
*
* If this [Demo] is a [DemoCategory], this will visit sub-[Demo]s first before continuing
* in the current category.
*
* @param path The path of categories that leads to this demo
*/
private fun Demo.visit(
visitedDemos: MutableList<Demo>,
path: List<DemoCategory>,
fastForwardClock: Boolean
) {
if (fastForwardClock) {
// Skip through the enter animation of the list screen
fastForwardClock()
}
rule.onNode(hasScrollToNodeAction())
.performScrollToNode(hasText(title) and hasClickAction())
rule.onNode(hasText(title) and hasClickAction()).performClick()
if (this is DemoCategory) {
visitDemos(visitedDemos, path + this, fastForwardClock)
}
if (fastForwardClock) {
// Skip through the enter animation of the visited demo
fastForwardClock()
}
rule.waitForIdle()
while (rule.onAllNodes(isDialog()).isNotEmpty()) {
Espresso.pressBack()
rule.waitForIdle()
}
clearFocusFromDemo()
rule.waitForIdle()
Espresso.pressBack()
rule.waitForIdle()
if (fastForwardClock) {
// Pump press back
fastForwardClock(2000)
}
}
private fun fastForwardClock(millis: Long = 5000) {
rule.waitForIdle()
rule.mainClock.advanceTimeBy(millis)
}
private fun SemanticsNodeInteractionCollection.isNotEmpty(): Boolean {
return fetchSemanticsNodes(atLeastOneRootRequired = false).isNotEmpty()
}
private fun clearFocusFromDemo() {
with(rule.activity) {
if (hostView.hasFocus()) {
if (hostView.isFocused) {
// One of the Compose components has focus.
focusManager.clearFocus(force = true)
} else {
// A child view has focus. (View interop scenario).
// We could also use hostViewGroup.focusedChild?.clearFocus(), but the
// interop views might end up being focused if one of them is marked as
// focusedByDefault. So we clear focus by requesting focus on the owner.
rule.runOnUiThread { hostView.requestFocus() }
}
}
}
}
}
private val AllButIgnoredDemos =
WearComposeDemos.filter { path, demo ->
demo.navigationTitle(path) !in ignoredDemos
}
private fun Demo.navigationTitle(path: List<DemoCategory>): String {
return path.plus(this).navigationTitle
}
private val List<Demo>.navigationTitle: String
get() = if (size == 1) first().title else drop(1).joinToString(" > ")
/**
* Trims the tree of [Demo]s represented by this [DemoCategory] by cutting all leave demos for
* which the [predicate] returns `false` and recursively removing all empty categories as a result.
*/
private fun DemoCategory.filter(
path: List<DemoCategory> = emptyList(),
predicate: (path: List<DemoCategory>, demo: Demo) -> Boolean
): DemoCategory {
val newPath = path + this
return DemoCategory(
title,
demos.mapNotNull {
when (it) {
is DemoCategory -> {
it.filter(newPath, predicate).let { if (it.demos.isEmpty()) null else it }
}
else -> {
if (predicate(newPath, it)) it else null
}
}
}
)
}
/**
* Flattened recursive DFS [List] of every demo in [this].
*/
fun DemoCategory.allDemos(): List<Demo> {
val allDemos = mutableListOf<Demo>()
fun DemoCategory.addAllDemos() {
demos.forEach { demo ->
allDemos += demo
if (demo is DemoCategory) {
demo.addAllDemos()
}
}
}
addAllDemos()
return allDemos
}
| wear/compose/integration-tests/demos/src/androidTest/java/androidx/wear/compose/integration/demos/test/DemoTest.kt | 1799918084 |
package com.kamer.orny.data.domain.model
import java.util.*
data class NewExpense(
var comment: String = "",
var date: Date = Date(),
var isOffBudget: Boolean = false,
var amount: Double = 0.0,
var author: Author
) | app/src/main/kotlin/com/kamer/orny/data/domain/model/NewExpense.kt | 556388950 |
package com.developerphil.adbidea.compatibility
import com.google.common.truth.Truth.assertThat
import org.joor.ReflectException
import org.junit.Assert.fail
import org.junit.Test
class BackwardCompatibleGetterTest {
@Test
fun onlyCallCurrentImplementationWhenItIsValid() {
var value = false
object : BackwardCompatibleGetter<Boolean>() {
override fun getCurrentImplementation(): Boolean {
value = true
return true
}
override fun getPreviousImplementation(): Boolean {
fail("should not be called")
return true
}
}.get()
assertThat(value).isTrue()
}
@Test
fun callPreviousImplementationWhenCurrentThrowsErrors() {
expectPreviousImplementationIsCalledFor(ClassNotFoundException())
expectPreviousImplementationIsCalledFor(NoSuchMethodException())
expectPreviousImplementationIsCalledFor(NoSuchFieldException())
expectPreviousImplementationIsCalledFor(LinkageError())
expectPreviousImplementationIsCalledFor(ReflectException())
}
@Test(expected = RuntimeException::class)
fun throwExceptionsWhenTheyAreNotRelatedToBackwardCompatibility() {
object : BackwardCompatibleGetter<Boolean>() {
override fun getCurrentImplementation(): Boolean {
throw RuntimeException("exception!")
}
override fun getPreviousImplementation(): Boolean {
fail("should not be called")
return false
}
}.get()
}
private fun expectPreviousImplementationIsCalledFor(throwable: Throwable) {
var value = false
object : BackwardCompatibleGetter<Boolean>() {
override fun getCurrentImplementation(): Boolean {
throw throwable
}
override fun getPreviousImplementation(): Boolean {
value = true
return true
}
}.get()
assertThat(value).isTrue()
}
} | src/test/kotlin/com/developerphil/adbidea/compatibility/BackwardCompatibleGetterTest.kt | 2933775484 |
/*
* 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.viewpager2.widget
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.viewpager2.widget.ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
import androidx.viewpager2.widget.ViewPager2.ORIENTATION_HORIZONTAL
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit.MILLISECONDS
private const val STATE_RESUMED = "RESUMED"
private const val STATE_STARTED = "STARTED"
private const val STATE_INITIALIZING = "INITIALIZING"
private const val STATE_CREATED = "CREATED"
private const val STATE_ACTIVITY_CREATED = "ACTIVITY_CREATED"
private val FRAGMENT_LIFECYCLE_STATES = listOf(
STATE_INITIALIZING,
STATE_CREATED,
STATE_ACTIVITY_CREATED,
STATE_STARTED,
STATE_RESUMED
)
// TODO: add tests for data-set changes
/** Verifies that primary item Fragment is RESUMED while the rest is STARTED */
@RunWith(AndroidJUnit4::class)
@LargeTest
class FragmentLifecycleTest : BaseTest() {
private val orientation = ORIENTATION_HORIZONTAL
private val totalPages = 10
private val adapterProvider = fragmentAdapterProviderValueId
private val timeoutMs = 3000L
@Test
fun test_swipeBetweenPages() {
setUpTest(orientation).apply {
val expectedValues = stringSequence(totalPages).toMutableList()
val adapter = adapterProvider.provider(expectedValues.toList()) // defensive copy
setAdapterSync(adapter)
var ix = 0
performAssertions(expectedValues, ix)
val swipeCount = expectedValues.count() - 1
repeat(swipeCount) {
val latch = viewPager.addWaitForIdleLatch()
swipeForward()
latch.await(timeoutMs, MILLISECONDS)
performAssertions(expectedValues, ++ix)
}
repeat(swipeCount) {
val latch = viewPager.addWaitForIdleLatch()
swipeBackward()
latch.await(timeoutMs, MILLISECONDS)
performAssertions(expectedValues, --ix)
}
}
}
@Test
fun test_setCurrentItem_offscreenPageLimit_default() {
test_setCurrentItem_offscreenPageLimit(OFFSCREEN_PAGE_LIMIT_DEFAULT)
}
@Test
fun test_setCurrentItem_offscreenPageLimit_3() {
test_setCurrentItem_offscreenPageLimit(3)
}
private fun test_setCurrentItem_offscreenPageLimit(offscreenPageLimit: Int) {
setUpTest(orientation).apply {
runOnUiThreadSync {
viewPager.offscreenPageLimit = offscreenPageLimit
}
val expectedValues = stringSequence(totalPages).toMutableList()
val adapter = adapterProvider.provider(expectedValues.toList()) // defensive copy
setAdapterSync(adapter)
performAssertions(expectedValues, 0)
// Pair(targetPageIx, isSmoothScroll)
val steps = listOf(
9 to true,
0 to false,
1 to true,
8 to false,
7 to false,
9 to true,
5 to true,
0 to true
)
steps.forEach { (target, isSmoothScroll) ->
viewPager.setCurrentItemSync(target, isSmoothScroll, timeoutMs, MILLISECONDS)
performAssertions(expectedValues, target)
}
}
}
@Test
fun test_dataSetChange() {
setUpTest(orientation).apply {
val items = stringSequence(totalPages).toMutableList()
setAdapterSync(adapterProvider.provider(items))
val adapter = viewPager.adapter!!
performAssertions(items, 0)
val steps = listOf(
DataChangeTestStep(
description = "Remove current; current=lastIx; notifyItemRemoved",
startPageIx = 9,
expectedPageIx = 8,
expectedPageText = "8",
dataChangeAction = {
val ix = 9
items.removeAt(ix)
adapter.notifyItemRemoved(ix)
}
),
DataChangeTestStep(
description = "Remove current; current=lastIx; dataSetChanged",
startPageIx = 8,
expectedPageIx = 0,
expectedPageText = "0",
dataChangeAction = {
items.removeAt(8)
adapter.notifyDataSetChanged()
}
),
DataChangeTestStep(
description = "Remove after current",
startPageIx = 3,
expectedPageIx = 3,
expectedPageText = "3",
dataChangeAction = {
val ix = items.lastIndex
items.removeAt(ix)
adapter.notifyItemRemoved(ix)
}
),
DataChangeTestStep(
description = "Move current",
startPageIx = 5,
expectedPageIx = 4,
expectedPageText = "5",
dataChangeAction = {
assertThat(items[5], equalTo("5")) // quick check
items.removeAt(5)
items.add(4, "5")
assertThat(items[4], equalTo("5")) // quick check
adapter.notifyItemMoved(5, 4)
}
),
DataChangeTestStep(
description = "Add before current",
startPageIx = 3,
expectedPageIx = 4,
expectedPageText = "3",
dataChangeAction = {
val ix = 0
items.add(ix, "999")
adapter.notifyItemInserted(ix)
}
)
)
steps.forEach {
viewPager.setCurrentItemSync(it.startPageIx, false, timeoutMs, MILLISECONDS)
performAssertions(items, it.startPageIx)
// wait for layout to finish after data-set change
val latchLayout = viewPager.addWaitForLayoutChangeLatch()
runOnUiThreadSync(it.dataChangeAction)
latchLayout.await(timeoutMs, MILLISECONDS)
// wait for animations to finish after data-set change
val latchAnim = CountDownLatch(1)
(viewPager.getChildAt(0) as RecyclerView).itemAnimator!!.isRunning {
latchAnim.countDown()
}
latchAnim.await(timeoutMs, MILLISECONDS)
performAssertions(items, it.expectedPageIx)
}
}
}
private data class DataChangeTestStep(
val description: String,
val startPageIx: Int,
val expectedPageIx: Int,
val expectedPageText: String,
val dataChangeAction: (() -> Unit)
)
/**
* Verifies the following:
* - Primary item Fragment is Resumed
* - Primary item Fragment's menu is visible
* - Other Fragments are Started
* - Other Fragments's menu is not visible
* - Correct page content is displayed
* - ViewPager2 currentItem is correct
* - A11y page actions are correct
* - Adapter self-checks if present are passing
*/
private fun Context.performAssertions(
expectedValues: MutableList<String>,
ix: Int,
text: String = expectedValues[ix]
) {
val fragmentInfo: List<FragmentInfo> =
activity.supportFragmentManager.fragments.map {
FragmentInfo(
it.tag!!,
it.stateString,
it.isResumed,
it.isMenuVisible
)
}
val resumed = fragmentInfo.filter { it.state == STATE_RESUMED }.toList()
assertThat(resumed.count(), equalTo(1))
val expectedId = expectedValues[ix].toInt()
val expectedTag = "f$expectedId"
assertThat(resumed.first().tag, equalTo(expectedTag))
assertThat(resumed.first().isResumed, equalTo(true))
assertThat(resumed.first().isMenuVisible, equalTo(true))
fragmentInfo.filter { it.state != STATE_RESUMED }.forEach { fi ->
assertThat(fi.state, equalTo(STATE_STARTED))
assertThat(fi.isResumed, equalTo(false))
assertThat(fi.isMenuVisible, equalTo(false))
}
assertBasicState(
ix,
text,
performSelfCheck = viewPager.offscreenPageLimit == OFFSCREEN_PAGE_LIMIT_DEFAULT
)
}
}
private data class FragmentInfo(
val tag: String,
val state: String,
val isResumed: Boolean,
val isMenuVisible: Boolean
)
private fun fragmentStateToString(state: Int): String =
FRAGMENT_LIFECYCLE_STATES.first { getFragmentFieldValue<Int>(it, null) == state }
private val (Fragment).stateInt: Int get() = getFragmentFieldValue("mState", this)
private val (Fragment).stateString: String get() = fragmentStateToString(this.stateInt)
private fun <T> getFragmentFieldValue(methodName: String, target: Fragment?): T {
val field = Fragment::class.java.declaredFields.first { it.name.contains(methodName) }
field.isAccessible = true
val result = field.get(target)
@Suppress("UNCHECKED_CAST")
return result as T
}
| viewpager2/viewpager2/src/androidTest/java/androidx/viewpager2/widget/FragmentLifecycleTest.kt | 1030203491 |
// 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.training.ift.lesson.basic
import training.dsl.LessonSample
import training.dsl.parseLessonSample
import training.learn.lesson.general.NewSelectLesson
class KotlinSelectLesson : NewSelectLesson() {
override val selectArgument = "\"$selectString\""
override val selectCall = """someMethod("$firstString", $selectArgument, "$thirdString")"""
override val numberOfSelectsForWholeCall = 2
override val sample: LessonSample = parseLessonSample("""
abstract class Scratch {
abstract fun someMethod(string1: String, string2: String, string3: String)
fun exampleMethod(condition: Boolean) {
<select id=1>if (condition) {
System.err.println("$beginString")
$selectCall
System.err.println("$endString")
}</select>
}
}
""".trimIndent())
override val selectIf = sample.getPosition(1).selection!!.let { sample.text.substring(it.first, it.second) }
} | plugins/kotlin/features-trainer/src/org/jetbrains/kotlin/training/ift/lesson/basic/KotlinSelectLesson.kt | 897512353 |
/*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.search.ideaExtensions
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.search.searches.ClassInheritorsSearch
import com.intellij.psi.search.searches.OverridingMethodsSearch
import com.intellij.util.Processor
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport
import com.intellij.openapi.application.runReadAction
fun findOverridingMethodsInKotlin(
parentClass: PsiClass,
baseElement: PsiNamedElement,
parameters: OverridingMethodsSearch.SearchParameters,
consumer: Processor<in PsiMethod>,
): Boolean = ClassInheritorsSearch.search(parentClass, parameters.scope, true).forEach(Processor { inheritor: PsiClass ->
val found = runReadAction { findOverridingMethod(inheritor, baseElement) }
found == null || (consumer.process(found) && parameters.isCheckDeep)
})
private fun findOverridingMethod(inheritor: PsiClass, baseElement: PsiNamedElement): PsiMethod? {
// Leave Java classes search to JavaOverridingMethodsSearcher
if (inheritor !is KtLightClass) return null
val name = baseElement.name
val methodsByName = inheritor.findMethodsByName(name, false)
for (lightMethodCandidate in methodsByName) {
val kotlinOrigin = (lightMethodCandidate as? KtLightMethod)?.kotlinOrigin ?: continue
if (KotlinSearchUsagesSupport.getInstance(inheritor.project).isCallableOverride(kotlinOrigin, baseElement)) {
return lightMethodCandidate
}
}
return null
} | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/search/ideaExtensions/internalSearchUtils.kt | 2820648444 |
// 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.quickfix.fixes
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInsight.daemon.impl.ShowAutoImportPass
import com.intellij.codeInsight.hint.HintManager
import com.intellij.codeInsight.hint.QuestionAction
import com.intellij.codeInspection.HintAction
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.psi.*
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.psi.util.parentsOfType
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic
import org.jetbrains.kotlin.analysis.api.fir.utils.addImportToFile
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtNamedClassOrObjectSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtSymbol
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithVisibility
import org.jetbrains.kotlin.idea.base.analysis.api.utils.KtSymbolFromIndexProvider
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.diagnosticFixFactory
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.QuickFixActionBase
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.KtPsiUtil.isSelectorInQualified
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.unwrapNullability
internal class ImportQuickFix(
element: KtElement,
private val importCandidates: List<FqName>
) : QuickFixActionBase<KtElement>(element), HintAction {
init {
require(importCandidates.isNotEmpty())
}
override fun getText(): String = KotlinBundle.message("fix.import")
override fun getFamilyName(): String = KotlinBundle.message("fix.import")
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
if (file !is KtFile) return
createAddImportAction(project, editor, file).execute()
}
private fun createAddImportAction(project: Project, editor: Editor, file: KtFile): QuestionAction {
return ImportQuestionAction(project, editor, file, importCandidates)
}
override fun showHint(editor: Editor): Boolean {
val element = element ?: return false
if (
ApplicationManager.getApplication().isHeadlessEnvironment
|| HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true)
) {
return false
}
val file = element.containingKtFile
val project = file.project
val elementRange = element.textRange
val autoImportHintText = KotlinBundle.message("fix.import.question", importCandidates.first().asString())
HintManager.getInstance().showQuestionHint(
editor,
autoImportHintText,
elementRange.startOffset,
elementRange.endOffset,
createAddImportAction(project, editor, file)
)
return true
}
override fun fixSilently(editor: Editor): Boolean {
val element = element ?: return false
val file = element.containingKtFile
if (!DaemonCodeAnalyzerSettings.getInstance().isImportHintEnabled) return false
if (!ShowAutoImportPass.isAddUnambiguousImportsOnTheFlyEnabled(file)) return false
val project = file.project
val addImportAction = createAddImportAction(project, editor, file)
if (importCandidates.size == 1) {
addImportAction.execute()
return true
} else {
return false
}
}
private val modificationCountOnCreate: Long = PsiModificationTracker.getInstance(element.project).modificationCount
/**
* This is a safe-guard against showing hint after the quickfix have been applied.
*
* Inspired by the org.jetbrains.kotlin.idea.quickfix.ImportFixBase.isOutdated
*/
private fun isOutdated(project: Project): Boolean {
return modificationCountOnCreate != PsiModificationTracker.getInstance(project).modificationCount
}
override fun isAvailableImpl(project: Project, editor: Editor?, file: PsiFile): Boolean {
return super.isAvailableImpl(project, editor, file) && !isOutdated(project)
}
private class ImportQuestionAction(
private val project: Project,
private val editor: Editor,
private val file: KtFile,
private val importCandidates: List<FqName>
) : QuestionAction {
init {
require(importCandidates.isNotEmpty())
}
override fun execute(): Boolean {
when (importCandidates.size) {
1 -> {
addImport(importCandidates.single())
return true
}
0 -> {
return false
}
else -> {
if (ApplicationManager.getApplication().isUnitTestMode) return false
createImportSelectorPopup().showInBestPositionFor(editor)
return true
}
}
}
private fun createImportSelectorPopup(): JBPopup {
return JBPopupFactory.getInstance()
.createPopupChooserBuilder(importCandidates)
.setTitle(KotlinBundle.message("action.add.import.chooser.title"))
.setItemChosenCallback { selectedValue: FqName -> addImport(selectedValue) }
.createPopup()
}
private fun addImport(nameToImport: FqName) {
project.executeWriteCommand(QuickFixBundle.message("add.import")) {
addImportToFile(project, file, nameToImport)
}
}
}
internal companion object {
val FACTORY = diagnosticFixFactory(KtFirDiagnostic.UnresolvedReference::class) { diagnostic ->
val element = diagnostic.psi
val project = element.project
val indexProvider = KtSymbolFromIndexProvider(project)
val quickFix = when (element) {
is KtTypeReference -> createImportTypeFix(indexProvider, element)
is KtNameReferenceExpression -> createImportNameFix(indexProvider, element)
else -> null
}
listOfNotNull(quickFix)
}
private fun KtAnalysisSession.createImportNameFix(
indexProvider: KtSymbolFromIndexProvider,
element: KtNameReferenceExpression
): ImportQuickFix? {
if (isSelectorInQualified(element)) return null
val firFile = element.containingKtFile.getFileSymbol()
val unresolvedName = element.getReferencedNameAsName()
val isVisible: (KtSymbol) -> Boolean =
{ it !is KtSymbolWithVisibility || isVisible(it, firFile, null, element) }
val callableCandidates = collectCallableCandidates(indexProvider, unresolvedName, isVisible)
val typeCandidates = collectTypesCandidates(indexProvider, unresolvedName, isVisible)
val importCandidates = (callableCandidates + typeCandidates).distinct()
if (importCandidates.isEmpty()) return null
return ImportQuickFix(element, importCandidates)
}
private fun KtAnalysisSession.createImportTypeFix(
indexProvider: KtSymbolFromIndexProvider,
element: KtTypeReference
): ImportQuickFix? {
val firFile = element.containingKtFile.getFileSymbol()
val unresolvedName = element.typeName ?: return null
val isVisible: (KtNamedClassOrObjectSymbol) -> Boolean =
{ isVisible(it, firFile, null, element) }
val acceptableClasses = collectTypesCandidates(indexProvider, unresolvedName, isVisible).distinct()
if (acceptableClasses.isEmpty()) return null
return ImportQuickFix(element, acceptableClasses)
}
private fun KtAnalysisSession.collectCallableCandidates(
indexProvider: KtSymbolFromIndexProvider,
unresolvedName: Name,
isVisible: (KtCallableSymbol) -> Boolean
): List<FqName> {
val callablesCandidates =
indexProvider.getKotlinCallableSymbolsByName(unresolvedName) { it.canBeImported() } +
indexProvider.getJavaCallableSymbolsByName(unresolvedName) { it.canBeImported() }
return callablesCandidates
.filter(isVisible)
.mapNotNull { it.callableIdIfNonLocal?.asSingleFqName() }
.toList()
}
private fun KtAnalysisSession.collectTypesCandidates(
indexProvider: KtSymbolFromIndexProvider,
unresolvedName: Name,
isVisible: (KtNamedClassOrObjectSymbol) -> Boolean
): List<FqName> {
val classesCandidates =
indexProvider.getKotlinClassesByName(unresolvedName) { it.canBeImported() } +
indexProvider.getJavaClassesByName(unresolvedName) { it.canBeImported() }
return classesCandidates
.filter(isVisible)
.mapNotNull { it.classIdIfNonLocal?.asSingleFqName() }
.toList()
}
}
}
private fun PsiMember.canBeImported(): Boolean {
return when (this) {
is PsiClass -> qualifiedName != null && (containingClass == null || hasModifier(JvmModifier.STATIC))
is PsiField, is PsiMethod -> hasModifier(JvmModifier.STATIC) && containingClass?.qualifiedName != null
else -> false
}
}
private fun KtDeclaration.canBeImported(): Boolean {
return when (this) {
is KtProperty -> isTopLevel || containingClassOrObject is KtObjectDeclaration
is KtNamedFunction -> isTopLevel || containingClassOrObject is KtObjectDeclaration
is KtClassOrObject ->
getClassId() != null && parentsOfType<KtClassOrObject>(withSelf = true).none { it.hasModifier(KtTokens.INNER_KEYWORD) }
else -> false
}
}
private val KtTypeReference.typeName: Name?
get() {
val userType = typeElement?.unwrapNullability() as? KtUserType
return userType?.referencedName?.let(Name::identifier)
} | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/quickfix/fixes/ImportQuickFix.kt | 2191475055 |
package foo
fun main(args: Array<String>) = println("a") | plugins/kotlin/jps/jps-plugin/tests/testData/incremental/withJava/other/mainRedeclaration/a.kt | 3276188151 |
interface OurFace
open class OurClass
fun context() {
val v = object : OurClass(), OurFace {}
v<caret>
}
//INFO: <div class='definition'><pre>val <b>v</b>: <anonymous object : <a href="psi_element://OurClass">OurClass</a>, <a href="psi_element://OurFace">OurFace</a>></pre></div>
| plugins/kotlin/idea/tests/testData/editor/quickDoc/AnonymousObjectLocalVariable.kt | 3856235167 |
// WITH_RUNTIME
// INTENTION_TEXT: "Replace with 'contains()'"
// IS_APPLICABLE_2: false
fun foo(list: List<String>) {
var v = true
<caret>for (s in list) {
if (s == "a") {
v = false
break
}
}
} | plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/contains/2.kt | 4177210770 |
package io.github.feelfreelinux.wykopmobilny.ui.widgets.link.related
import android.content.Context
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import androidx.core.app.ShareCompat
import androidx.core.content.ContextCompat
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Related
import io.github.feelfreelinux.wykopmobilny.ui.dialogs.showExceptionDialog
import io.github.feelfreelinux.wykopmobilny.ui.modules.profile.ProfileActivity
import io.github.feelfreelinux.wykopmobilny.utils.api.getGroupColor
import io.github.feelfreelinux.wykopmobilny.utils.getActivityContext
import io.github.feelfreelinux.wykopmobilny.utils.isVisible
import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi
import kotlinx.android.synthetic.main.link_related_layout.view.*
class RelatedWidget(context: Context, attrs: AttributeSet) :
androidx.cardview.widget.CardView(context, attrs), RelatedWidgetView {
init {
View.inflate(context, R.layout.link_related_layout, this)
isClickable = true
isFocusable = true
val typedValue = TypedValue()
getActivityContext()!!.theme?.resolveAttribute(R.attr.itemBackgroundColorStatelist, typedValue, true)
setBackgroundResource(typedValue.resourceId)
}
val url: String
get() = relatedItem.url
private lateinit var presenter: RelatedWidgetPresenter
private lateinit var relatedItem: Related
fun setRelatedData(related: Related, userManagerApi: UserManagerApi, relatedWidgetPresenter: RelatedWidgetPresenter) {
relatedItem = related
presenter = relatedWidgetPresenter
title.text = related.title
urlTextView.text = related.url
presenter.subscribe(this)
presenter.relatedId = relatedItem.id
setOnClickListener {
presenter.handleLink(related.url)
}
shareTextView.setOnClickListener {
shareUrl()
}
setVoteCount(related.voteCount)
authorHeaderView.isVisible = related.author != null
userNameTextView.isVisible = related.author != null
related.author?.apply {
userNameTextView.text = nick
userNameTextView.setOnClickListener { openProfile() }
authorHeaderView.setOnClickListener { openProfile() }
authorHeaderView.setAuthor(this)
userNameTextView.setTextColor(context.getGroupColor(group))
}
setupButtons()
plusButton.setup(userManagerApi)
minusButton.setup(userManagerApi)
}
private fun openProfile() {
val context = getActivityContext()!!
context.startActivity(ProfileActivity.createIntent(context, relatedItem.author!!.nick))
}
private fun setupButtons() {
when (relatedItem.userVote) {
1 -> {
plusButton.isButtonSelected = true
plusButton.isEnabled = false
minusButton.isButtonSelected = false
minusButton.isEnabled = true
minusButton.voteListener = {
presenter.voteDown()
}
}
0 -> {
plusButton.isButtonSelected = false
plusButton.isEnabled = true
plusButton.voteListener = {
presenter.voteUp()
}
minusButton.isButtonSelected = false
minusButton.isEnabled = true
minusButton.voteListener = {
presenter.voteDown()
}
}
-1 -> {
minusButton.isButtonSelected = true
minusButton.isEnabled = false
plusButton.isButtonSelected = false
plusButton.isEnabled = true
plusButton.voteListener = {
presenter.voteUp()
}
}
}
}
override fun markUnvoted() {
relatedItem.userVote = -1
setupButtons()
}
override fun markVoted() {
relatedItem.userVote = 1
setupButtons()
}
override fun setVoteCount(voteCount: Int) {
relatedItem.voteCount = voteCount
voteCountTextView.text = if (relatedItem.voteCount > 0) "+${relatedItem.voteCount}" else "${relatedItem.voteCount}"
if (relatedItem.voteCount > 0) {
voteCountTextView.setTextColor(ContextCompat.getColor(context, R.color.plusPressedColor))
} else if (relatedItem.voteCount < 0) {
voteCountTextView.setTextColor(ContextCompat.getColor(context, R.color.minusPressedColor))
}
}
override fun showErrorDialog(e: Throwable) = context.showExceptionDialog(e)
private fun shareUrl() {
ShareCompat.IntentBuilder
.from(getActivityContext()!!)
.setType("text/plain")
.setChooserTitle(R.string.share)
.setText(url)
.startChooser()
}
} | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/widgets/link/related/RelatedWidget.kt | 547915511 |
// WITH_RUNTIME
// PROBLEM: none
fun foo(a: Float) {
1f<caret>..a - 1
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceRangeToWithUntil/closedRange.kt | 66567105 |
/*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package org.ethereum.validator
import org.ethereum.core.BlockHeader
/**
* Checks if [BlockHeader.number] == [BlockHeader.number] + 1 of parent's block
*/
class ParentNumberRule : DependentBlockHeaderRule() {
override fun validate(header: BlockHeader, parent: BlockHeader): Boolean {
errors.clear()
if (header.number != parent.number + 1) {
errors.add(String.format("#%d: block number is not parentBlock number + 1", header.number))
return false
}
return true
}
}
| free-ethereum-core/src/main/java/org/ethereum/validator/ParentNumberRule.kt | 3041301072 |
package smartStepIntoDefferedSamLambda
import kotlin.concurrent.thread
fun interface DoStuffer {
fun doStuff()
}
typealias FunT = DoStuffer
fun MutableList<FunT>.foo(f: FunT): MutableList<FunT> {
add(f)
return this
}
fun MutableList<FunT>.bar(f: FunT): MutableList<FunT> {
add(f)
return this
}
fun putLambdaInACollection(list: MutableList<FunT>, f: FunT) {
list.add(f)
}
fun MutableList<FunT>.invokeAndClear() {
forEach { it.doStuff() }
clear()
}
fun main() {
// STEP_OVER: 1
//Breakpoint!
val list = mutableListOf<FunT>()
// SMART_STEP_INTO_BY_INDEX: 2
// RESUME: 1
list.foo { println(1) }
.bar { println(2) }
.foo { println(3) }
list.invokeAndClear()
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 4
// RESUME: 1
list.foo { println(1) }
.bar { println(2) }
.foo { println(3) }
list.invokeAndClear()
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 6
// RESUME: 1
list.foo { println(1) }
.bar { println(2) }
.foo { println(3) }
list.invokeAndClear()
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 2
// RESUME: 1
putLambdaInACollection(list) { println(4) }
list.invokeAndClear()
// STEP_OVER: 1
//Breakpoint!
stopHere()
// SMART_STEP_INTO_BY_INDEX: 2
// RESUME: 1
putLambdaInACollection(list) { println(4) }
val thread = thread(true) { list.invokeAndClear() }
thread.join()
}
fun stopHere() {
}
| plugins/kotlin/jvm-debugger/test/testData/stepping/custom/smartStepIntoDeferredSamLambdas.kt | 2952709666 |
fun test(list: List<String>?) {
list<caret>
} | plugins/kotlin/code-insight/postfix-templates/testData/expansion/for/nullable.kt | 3037955930 |
/*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.dfu.analytics
import android.annotation.SuppressLint
import no.nordicsemi.android.common.analytics.NordicAnalytics
import javax.inject.Inject
import javax.inject.Singleton
@SuppressLint("MissingPermission")
@Singleton
class DfuAnalytics @Inject constructor(
private val analytics: NordicAnalytics,
) {
fun logEvent(event: DfuEvent) {
when (event) {
AppOpenEvent,
HandleDeepLinkEvent,
InstallationStartedEvent,
ResetSettingsEvent,
DFUAbortedEvent,
DFUSuccessEvent -> analytics.logEvent(event.eventName)
is FileSelectedEvent -> analytics.logEvent(event.eventName, event.createBundle())
is DFUErrorEvent -> analytics.logEvent(event.eventName, event.createBundle())
is DFUSettingsChangeEvent -> analytics.logEvent(event.eventName, event.createBundle())
}
}
} | lib_analytics/src/main/java/no/nordicsemi/android/dfu/analytics/DfuAnalytics.kt | 1128984568 |
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import java.util.*
import java.util.UUID
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SecondSampleEntityImpl(val dataSource: SecondSampleEntityData) : SecondSampleEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val intProperty: Int get() = dataSource.intProperty
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: SecondSampleEntityData?) : ModifiableWorkspaceEntityBase<SecondSampleEntity, SecondSampleEntityData>(
result), SecondSampleEntity.Builder {
constructor() : this(SecondSampleEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SecondSampleEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as SecondSampleEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.intProperty != dataSource.intProperty) this.intProperty = dataSource.intProperty
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var intProperty: Int
get() = getEntityData().intProperty
set(value) {
checkModificationAllowed()
getEntityData(true).intProperty = value
changedProperty.add("intProperty")
}
override fun getEntityClass(): Class<SecondSampleEntity> = SecondSampleEntity::class.java
}
}
class SecondSampleEntityData : WorkspaceEntityData<SecondSampleEntity>() {
var intProperty: Int = 0
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<SecondSampleEntity> {
val modifiable = SecondSampleEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): SecondSampleEntity {
return getCached(snapshot) {
val entity = SecondSampleEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SecondSampleEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return SecondSampleEntity(intProperty, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as SecondSampleEntityData
if (this.entitySource != other.entitySource) return false
if (this.intProperty != other.intProperty) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as SecondSampleEntityData
if (this.intProperty != other.intProperty) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + intProperty.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + intProperty.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SecondSampleEntityImpl.kt | 3701817817 |
/**
* @sample samples.SampleGroup.mySample
* @sample samples.megasamples.MegaSamplesGroup.megaSample
* @sample samples.notindir.NotInDirSamples.sssample
* @sample smaplez.a.b.c.Samplez.sssample
*/
fun some<caret>() {
}
//INFO: <div class='definition'><pre><span style="color:#000080;font-weight:bold;">public</span> <span style="color:#000080;font-weight:bold;">fun</span> <span style="color:#000000;">some</span>()<span style="">: </span><span style="color:#000000;">Unit</span></pre></div><table class='sections'><tr><td valign='top' class='section'><p>Samples:</td><td valign='top'><p><a href="psi_element://samples.SampleGroup.mySample"><code style='font-size:96%;'><span style="color:#000000;">samples</span><span style="">.</span><span style="color:#000000;">SampleGroup</span><span style="">.</span><span style="color:#0000ff;">mySample</span></code></a><pre><code><span style=""><br><span style="">println(</span><span style="color:#008000;font-weight:bold;">"Hello, world"</span><span style="">)<br></span></span></code></pre><p><a href="psi_element://samples.megasamples.MegaSamplesGroup.megaSample"><code style='font-size:96%;'><span style="color:#000000;">samples</span><span style="">.</span><span style="color:#000000;">megasamples</span><span style="">.</span><span style="color:#000000;">MegaSamplesGroup</span><span style="">.</span><span style="color:#0000ff;">megaSample</span></code></a><pre><code><span style=""><br><span style="">println(</span><span style="color:#008000;font-weight:bold;">"...---..."</span><span style="">)<br></span></span></code></pre><p><a href="psi_element://samples.notindir.NotInDirSamples.sssample"><code style='font-size:96%;'><span style="color:#000000;">samples</span><span style="">.</span><span style="color:#000000;">notindir</span><span style="">.</span><span style="color:#000000;">NotInDirSamples</span><span style="">.</span><span style="color:#0000ff;">sssample</span></code></a><pre><code><span style=""><br><span style="">println(</span><span style="color:#008000;font-weight:bold;">"location is samplesTest/"</span><span style="">)<br></span></span></code></pre><p><a href="psi_element://smaplez.a.b.c.Samplez.sssample"><code style='font-size:96%;'><span style="color:#000000;">smaplez</span><span style="">.</span><span style="color:#000000;">a</span><span style="">.</span><span style="color:#000000;">b</span><span style="">.</span><span style="color:#000000;">c</span><span style="">.</span><span style="color:#000000;">Samplez</span><span style="">.</span><span style="color:#4585be;">sssample</span></code></a><pre><code><span style=""><span style="color:#808080;font-style:italic;">// Unresolved</span></span></code></pre></td></table><div class='bottom'><icon src="/org/jetbrains/kotlin/idea/icons/kotlin_file.svg"/> usage.kt<br/></div>
| plugins/kotlin/idea/tests/testData/kdoc/multiModuleResolve/fqName/code/usage.kt | 767591884 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.jsonpath
import com.intellij.json.psi.JsonFile
import com.intellij.jsonpath.ui.IncorrectDocument
import com.intellij.jsonpath.ui.IncorrectExpression
import com.intellij.jsonpath.ui.JsonPathEvaluator
import com.intellij.jsonpath.ui.ResultString
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixture4TestCase
import com.jayway.jsonpath.Configuration
import com.jayway.jsonpath.JsonPath
import com.jayway.jsonpath.Option
import com.jayway.jsonpath.spi.json.JacksonJsonProvider
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.util.*
@RunWith(JUnit4::class)
class JsonPathEvaluateTest : LightPlatformCodeInsightFixture4TestCase() {
companion object {
init {
Configuration.setDefaults(object : Configuration.Defaults {
private val jsonProvider = JacksonJsonProvider()
private val mappingProvider = JacksonMappingProvider()
override fun jsonProvider() = jsonProvider
override fun mappingProvider() = mappingProvider
override fun options() = EnumSet.noneOf(Option::class.java)
})
}
}
@Test
fun evaluateWithBindingFromClasspath() {
val documentContext = JsonPath.parse("{ \"some\": 12 }")
val data = documentContext.read<Any>("$.some")
assertEquals(12, data)
}
@Test
fun evaluateWithOptionsAndDocument() {
val document = myFixture.configureByText("data.json", sampleDocument)
val evaluator = JsonPathEvaluator(document as JsonFile, "$..book[?(@.price > 0.1)]", setOf(Option.AS_PATH_LIST))
val result = evaluator.evaluate() as ResultString
assertEquals("[\"\$['store']['book'][0]\", \"\$['store']['book'][1]\"]", result.value)
}
@Test
fun primitiveResult() {
val document = myFixture.configureByText("data.json", sampleDocument)
val evaluator = JsonPathEvaluator(document as JsonFile, "$.store.book[0].price", setOf())
val result = evaluator.evaluate() as ResultString
assertEquals("0.15", result.value)
}
@Test
fun collectionResult() {
val document = myFixture.configureByText("data.json", sampleDocument)
val evaluator = JsonPathEvaluator(document as JsonFile, "$.store.book.*.price", setOf())
val result = evaluator.evaluate() as ResultString
assertEquals("[0.15, 7.99]", result.value)
}
@Test
fun nullResult() {
val document = myFixture.configureByText("data.json", sampleDocument)
val evaluator = JsonPathEvaluator(document as JsonFile, "$.country", setOf())
val result = evaluator.evaluate() as ResultString
assertEquals("null", result.value)
}
@Test
fun stringResult() {
val document = myFixture.configureByText("data.json", sampleDocument)
val evaluator = JsonPathEvaluator(document as JsonFile, "$.store.book[0].category", setOf())
val result = evaluator.evaluate() as ResultString
assertEquals("\"reference\"", result.value)
}
@Test
fun treeResult() {
val document = myFixture.configureByText("data.json", sampleDocument)
val evaluator = JsonPathEvaluator(document as JsonFile, "$.store.book[1]", setOf())
val result = evaluator.evaluate() as ResultString
assertEquals("{\"category\":\"fiction\",\"author\":\"Peter Pan\",\"title\":\"No Future\",\"price\":7.99}", result.value)
}
@Test
fun incorrectExpression() {
val document = myFixture.configureByText("data.json", sampleDocument)
val evaluator = JsonPathEvaluator(document as JsonFile, "$$", setOf())
val result = evaluator.evaluate() as IncorrectExpression
assertEquals("Illegal character at position 1 expected '.' or '['", result.message)
}
@Test
fun incorrectDocument() {
val document = myFixture.configureByText("my.json", "{ invalid }")
val evaluator = JsonPathEvaluator(document as JsonFile, "$", setOf())
val result = evaluator.evaluate() as IncorrectDocument
assertThat(result.message).contains("Unexpected character ('i' (code 105)): was expecting double-quote to start field name")
}
private val sampleDocument: String
get() = /* language=JSON */ """
{
"store": {
"book": [
{
"category": "reference",
"author": "Sam Smith",
"title": "First way",
"price": 0.15
},
{
"category": "fiction",
"author": "Peter Pan",
"title": "No Future",
"price": 7.99
}
],
"bicycle": {
"color": "white",
"price": 2.95
}
},
"country": null,
"expensive": 10
}
""".trimIndent()
} | json/tests/test/com/intellij/jsonpath/JsonPathEvaluateTest.kt | 3237108190 |
// "class org.jetbrains.kotlin.idea.quickfix.ChangeVariableTypeFix" "false"
// ERROR: Type of 'x' doesn't match the type of the overridden var-property 'public abstract var x: Int defined in A'
interface A {
var x: Int
}
interface B {
var x: Any
}
interface C : A, B {
override var x: String<caret>
}
| plugins/kotlin/idea/tests/testData/quickfix/override/typeMismatchOnOverride/cantChangeOverriddenPropertyTypeToMatchOverridingProperty.kt | 3663276854 |
package b
import java.util.function.IntPredicate
interface Factory {
operator fun invoke(i: Int): IntPredicate
companion object {
inline operator fun invoke(crossinline f: (Int) -> IntPredicate) = object : Factory {
override fun invoke(i: Int) = f(i)
}
}
} | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/misc/shortenCompanionObject2/before/b/boo.kt | 2634456423 |
annotation class TestAnnotation
@TestAnnotation
val prop1: Int = 0
@get:TestAnnotation
val prop2: Int
get() = 0
@set:TestAnnotation
var prop3: Int = 0
get() = 0
set(value) { field = value } | plugins/kotlin/uast/uast-kotlin/tests/testData/PropertyWithAnnotation.kt | 2381865494 |
class A(val b: Boolean, val c: Int, val d: Int)
fun d() {
println(<warning descr="SSR">A(true, 0, 1)</warning>)
println(<warning descr="SSR">A(b = true, c = 0, d = 1)</warning>)
println(<warning descr="SSR">A(c = 0, b = true, d = 1)</warning>)
println(<warning descr="SSR">A(true, d = 1, c = 0)</warning>)
} | plugins/kotlin/idea/tests/testData/structuralsearch/callExpression/constrNamedArgsCall.kt | 3062884971 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.credentialStore.keePass
import com.intellij.credentialStore.*
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.util.io.delete
import com.intellij.util.io.readBytes
import com.intellij.util.io.safeOutputStream
import org.yaml.snakeyaml.composer.Composer
import org.yaml.snakeyaml.nodes.*
import org.yaml.snakeyaml.parser.ParserImpl
import org.yaml.snakeyaml.reader.StreamReader
import org.yaml.snakeyaml.resolver.Resolver
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.util.*
internal const val MASTER_KEY_FILE_NAME = "c.pwd"
private const val OLD_MASTER_PASSWORD_FILE_NAME = "pdb.pwd"
class MasterKey(value: ByteArray,
// is password auto-generated, used to force set master password if database file location changed
val isAutoGenerated: Boolean,
val encryptionSpec: EncryptionSpec) {
var value: ByteArray? = value
/**
* Clear byte array to avoid sensitive data in memory
*/
fun clear() {
value?.fill(0)
value = null
}
}
class MasterKeyFileStorage(val passwordFile: Path) {
fun load(): ByteArray? {
var data: ByteArray
var isOld = false
try {
data = passwordFile.readBytes()
}
catch (e: NoSuchFileException) {
try {
data = passwordFile.parent.resolve(OLD_MASTER_PASSWORD_FILE_NAME).readBytes()
}
catch (e: NoSuchFileException) {
return null
}
isOld = true
}
try {
val decrypted: ByteArray
if (isOld) {
decrypted = createBuiltInOrCrypt32EncryptionSupport(SystemInfo.isWindows).decrypt(data)
data.fill(0)
}
else {
decrypted = decryptMasterKey(data) ?: return null
}
data.fill(0)
return decrypted
}
catch (e: Exception) {
LOG.warn("Cannot decrypt master key, file content:\n${if (isOld) Base64.getEncoder().encodeToString(data) else data.toString(Charsets.UTF_8)}", e)
return null
}
}
private fun decryptMasterKey(data: ByteArray): ByteArray? {
var encryptionType: EncryptionType? = null
var value: ByteArray? = null
for (node in createMasterKeyReader(data)) {
val keyNode = node.keyNode
val valueNode = node.valueNode
if (keyNode is ScalarNode && valueNode is ScalarNode) {
val propertyValue = valueNode.value ?: continue
when (keyNode.value) {
"encryption" -> encryptionType = EncryptionType.valueOf(propertyValue.toUpperCase())
"value" -> value = Base64.getDecoder().decode(propertyValue)
}
}
}
if (encryptionType == null) {
LOG.error("encryption type not specified in $passwordFile, default one will be used (file content:\n${data.toString(Charsets.UTF_8)})")
encryptionType = getDefaultEncryptionType()
}
if (value == null) {
LOG.error("password not specified in $passwordFile, automatically generated will be used (file content:\n${data.toString(Charsets.UTF_8)})")
return null
}
// PGP key id is not stored in master key file because PGP encoded data already contains recipient id and no need to explicitly specify it,
// so, this EncryptionSupport MUST be used only for decryption since pgpKeyId is set to null.
return createEncryptionSupport(EncryptionSpec(encryptionType, pgpKeyId = null)).decrypt(value)
}
// passed key will be cleared
fun save(key: MasterKey?) {
if (key == null) {
passwordFile.delete()
return
}
val encodedValue = Base64.getEncoder().encode(createEncryptionSupport(key.encryptionSpec).encrypt(key.value!!))
key.clear()
val out = BufferExposingByteArrayOutputStream()
val encryptionType = key.encryptionSpec.type
out.writer().use {
it.append("encryption: ").append(encryptionType.name).append('\n')
it.append("isAutoGenerated: ").append(key.isAutoGenerated.toString()).append('\n')
it.append("value: !!binary ")
}
passwordFile.safeOutputStream().use {
it.write(out.internalBuffer, 0, out.size())
it.write(encodedValue)
encodedValue.fill(0)
}
}
private fun readMasterKeyIsAutoGeneratedMetadata(data: ByteArray): Boolean {
var isAutoGenerated = true
for (node in createMasterKeyReader(data)) {
val keyNode = node.keyNode
val valueNode = node.valueNode
if (keyNode is ScalarNode && valueNode is ScalarNode) {
val propertyValue = valueNode.value ?: continue
when (keyNode.value) {
"isAutoGenerated" -> isAutoGenerated = propertyValue.toBoolean() || propertyValue == "yes"
}
}
}
return isAutoGenerated
}
fun isAutoGenerated(): Boolean {
try {
return readMasterKeyIsAutoGeneratedMetadata(passwordFile.readBytes())
}
catch (e: NoSuchFileException) {
// true because on save will be generated
return true
}
}
}
private fun createMasterKeyReader(data: ByteArray): List<NodeTuple> {
val composer = Composer(ParserImpl(StreamReader(data.inputStream().reader())), object : Resolver() {
override fun resolve(kind: NodeId, value: String?, implicit: Boolean): Tag {
return when (kind) {
NodeId.scalar -> Tag.STR
else -> super.resolve(kind, value, implicit)
}
}
})
return (composer.singleNode as? MappingNode)?.value ?: emptyList()
}
| platform/credential-store/src/keePass/masterKey.kt | 66638402 |
// WITH_STDLIB
fun List<Int>.test(): List<Int> {
return <caret>filter { it > 1 }.map { it * 2 }
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/implicitReceiver.kt | 1597912206 |
package test
import dependency.*
fun foo(f: Foo<Int>) {
for (elem i<caret>n f) {
}
}
// MULTIRESOLVE
// REF: (for dependency.Foo<T> in dependency).iterator()
// REF: (for dependency.FooIterator<T> in dependency).hasNext()
// REF: (for dependency.FooIterator<T> in dependency).next()
| plugins/kotlin/idea/tests/testData/resolve/referenceWithLib/iteratorWithTypeParameter.kt | 1965871587 |
// AFTER-WARNING: Parameter 'f' is never used
class A {
fun b() = B()
}
class B {
operator fun invoke(f: () -> Unit) {}
}
fun test(a: A) {
a.b().<caret>invoke {
}
} | plugins/kotlin/idea/tests/testData/intentions/conventionNameCalls/replaceInvoke/dotQualifiedReceiver3.kt | 4117089245 |
package foo
import foo.onlyInImport
import foo.onlyInImportNoWarn
fun onlyInImport() {
}
@Suppress("unused")
fun onlyInImportNoWarn() {}
| plugins/kotlin/idea/tests/testData/inspections/unusedSymbol/function/topLevelOnlyInImport.kt | 1052539626 |
package a.b
fun foo(s: String) {}
fun foo(i: Int) {}
internal val Foo.foo: Int get() = 123
class Foo {} | plugins/kotlin/idea/tests/testData/shortenRefs/PropertyFunctionConflict.dependency.kt | 1637310886 |
// "Remove braces" "false"
// TOOL: org.jetbrains.kotlin.idea.inspections.FunctionWithLambdaExpressionBodyInspection
// ACTION: Convert to block body
// ACTION: Convert to multi-line lambda
// ACTION: Convert to run { ... }
// ACTION: Enable a trailing comma by default in the formatter
// ACTION: Specify explicit lambda signature
// ACTION: Specify explicit lambda signature
// ACTION: Specify return type explicitly
// ACTION: Convert to anonymous function
fun test(a: Int, b: Int) = <caret>{} | plugins/kotlin/idea/tests/testData/quickfix/functionWithLambdaExpressionBody/removeBraces/functionHasNoStatement.kt | 2239400422 |
// LANGUAGE_VERSION: 1.2
annotation class Some(val strings: Array<String>)
@Some(strings = <caret>emptyArray())
class My
| plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceArrayOfWithLiteral/empty.kt | 632839037 |
package com.ifabijanovic.holonet.forum.data
import com.ifabijanovic.holonet.forum.model.ForumThread
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
/**
* Created by Ivan Fabijanovic on 31/03/2017.
*/
class ForumPostRepositoryTests: ForumRepositoryTestsBase() {
private var repo: ForumPostRepository? = null
private val testThread = ForumThread(5, "Test", "Today", "Test user", 5, 7)
@Before
override fun setUp() {
super.setUp()
this.repo = DefaultForumPostRepository(ForumParser(), this.service!!, this.settings)
}
@Test
fun emptyHtml() {
this.stubHtmlResource("forum-empty")
val items = this.repo!!.posts(this.language, this.testThread, 1).blockingFirst()
assertNotNull(items)
assertEquals(0, items.size)
}
@Test
fun singleItem_Valid() {
this.stubHtmlResource("Post/forum-post-single-valid")
val items = this.repo!!.posts(this.language, this.testThread, 1).blockingFirst()
assertNotNull(items)
assertEquals(1, items.size)
if (items.size != 1) { return }
assertEquals(5, items[0].id)
assertEquals("http://www.holonet.test/avatar.png", items[0].avatarUrl)
assertEquals("User name 5", items[0].username)
assertEquals("1.1.2014, 08:22 AM", items[0].date)
assertEquals(1, items[0].postNumber)
assertTrue(items[0].isBiowarePost)
assertTrue(items[0].text.count() > 0)
assertTrue(items[0].signature!!.count() > 0)
}
@Test
fun singleItem_NotDev() {
this.stubHtmlResource("Post/forum-post-single-valid-not-dev")
val items = this.repo!!.posts(this.language, this.testThread, 1).blockingFirst()
assertNotNull(items)
assertEquals(1, items.size)
if (items.size != 1) { return }
assertEquals(5, items[0].id)
assertFalse(items[0].isBiowarePost)
}
@Test
fun singleItem_InvalidId() {
this.stubHtmlResource("Post/forum-post-single-invalid-id")
val items = this.repo!!.posts(this.language, this.testThread, 1).blockingFirst()
assertNotNull(items)
assertEquals(0, items.size)
}
@Test
fun singleItem_InvalidUsername() {
this.stubHtmlResource("Post/forum-post-single-invalid-username")
val items = this.repo!!.posts(this.language, this.testThread, 1).blockingFirst()
assertNotNull(items)
assertEquals(0, items.size)
}
@Test
fun singleItem_InvalidDate() {
this.stubHtmlResource("Post/forum-post-single-invalid-date")
val items = this.repo!!.posts(this.language, this.testThread, 1).blockingFirst()
assertNotNull(items)
assertEquals(0, items.size)
}
@Test
fun singleItem_MissingOptionals() {
this.stubHtmlResource("Post/forum-post-single-missing-optionals")
val items = this.repo!!.posts(this.language, this.testThread, 1).blockingFirst()
assertNotNull(items)
assertEquals(1, items.size)
if (items.size != 1) { return }
assertEquals(5, items[0].id)
assertNull(items[0].avatarUrl)
assertNull(items[0].postNumber)
}
@Test
fun multipleItems_Valid() {
this.stubHtmlResource("Post/forum-post-multiple-valid")
val items = this.repo!!.posts(this.language, this.testThread, 1).blockingFirst()
assertNotNull(items)
assertEquals(3, items.size)
if (items.size != 3) { return }
assertEquals(5, items[0].id)
assertEquals("http://www.holonet.test/avatar.png", items[0].avatarUrl)
assertEquals("User name 5", items[0].username)
assertEquals("1.1.2014, 08:22 AM", items[0].date)
assertEquals(1, items[0].postNumber)
assertTrue(items[0].isBiowarePost)
assertTrue(items[0].text.count() > 0)
assertTrue(items[0].signature!!.count() > 0)
assertEquals(6, items[1].id)
assertEquals("http://www.holonet.test/avatar.png", items[1].avatarUrl)
assertEquals("User name 6", items[1].username)
assertEquals("2.2.2014, 09:22 AM", items[1].date)
assertEquals(2, items[1].postNumber)
assertFalse(items[1].isBiowarePost)
assertTrue(items[1].text.count() > 0)
assertTrue(items[1].signature!!.count() > 0)
assertEquals(7, items[2].id)
assertEquals("http://www.holonet.test/avatar.png", items[2].avatarUrl)
assertEquals("User name 7", items[2].username)
assertEquals("3.3.2014, 10:22 AM", items[2].date)
assertEquals(3, items[2].postNumber)
assertTrue(items[2].isBiowarePost)
assertTrue(items[2].text.count() > 0)
assertTrue(items[2].signature!!.count() > 0)
}
@Test
fun multipleItems_InvalidId() {
this.stubHtmlResource("Post/forum-post-multiple-invalid-id")
val items = this.repo!!.posts(this.language, this.testThread, 1).blockingFirst()
assertNotNull(items)
assertEquals(2, items.size)
if (items.size != 2) { return }
assertEquals(5, items[0].id)
assertEquals(7, items[1].id)
}
} | android/app/src/test/java/com/ifabijanovic/holonet/forum/data/ForumPostRepositoryTests.kt | 2617962080 |
/*
* Copyright 2011-2021 GatlingCorp (https://gatling.io)
*
* 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.
*/
import io.gatling.javaapi.core.CoreDsl.*
import io.gatling.javaapi.core.Simulation
import io.gatling.javaapi.http.HttpDsl.*
import org.apache.commons.codec.digest.DigestUtils
import java.util.*
import javax.net.ssl.KeyManagerFactory
class HttpProtocolSampleKotlin: Simulation() {
init {
//#bootstrapping
val httpProtocol = http.baseUrl("https://gatling.io")
val scn = scenario("Scenario") // etc...
setUp(scn.injectOpen(atOnceUsers(1)).protocols(httpProtocol))
//#bootstrapping
}
init {
//#baseUrl
val httpProtocol = http.baseUrl("https://gatling.io")
val scn = scenario("Scenario")
// will make a request to "https://gatling.io/docs"
.exec(
http("Relative").get("/docs/")
)
// will make a request to "https://github.com/gatling/gatling"
.exec(
http("Absolute").get("https://github.com/gatling/gatling")
)
setUp(scn.injectOpen(atOnceUsers(1)).protocols(httpProtocol))
//#baseUrl
}
init {
//#baseUrls
http.baseUrls(
"https://gatling.io",
"https://github.com"
)
//#baseUrls
//#warmUp
// change the warm up URL to https://www.google.com
http.warmUp("https://www.google.com")
// disable warm up
http.disableWarmUp()
//#warmUp
//#maxConnectionsPerHost
http.maxConnectionsPerHost(10)
//#maxConnectionsPerHost
//#shareConnections
http.shareConnections()
//#shareConnections
//#enableHttp2
http.enableHttp2()
//#enableHttp2
//#http2PriorKnowledge
http
.enableHttp2()
.http2PriorKnowledge(
mapOf(
"www.google.com" to true,
"gatling.io" to false
)
)
//#http2PriorKnowledge
//#dns-async
// use hosts' configured DNS servers on Linux and MacOS
// use Google's DNS servers on Windows
http.asyncNameResolution()
// force DNS servers
http.asyncNameResolution("8.8.8.8")
// instead of having a global DNS resolver
// have each virtual user to have its own (hence own cache, own UDP requests)
// only effective with asyncNameResolution
http
.asyncNameResolution()
.perUserNameResolution()
//#dns-async
//#hostNameAliases
http
.hostNameAliases(mapOf("gatling.io" to listOf("192.168.0.1", "192.168.0.2")))
//#hostNameAliases
//#virtualHost
// with a static value
http.virtualHost("virtualHost")
// with a Gatling EL string
http.virtualHost("#{virtualHost}")
// with a function
http.virtualHost { session -> session.getString("virtualHost") }
//#virtualHost
//#localAddress
http.localAddress("localAddress")
http.localAddresses("localAddress1", "localAddress2")
// automatically discover all bindable local addresses
http.useAllLocalAddresses()
// automatically discover all bindable local addresses
// matching one of the Java Regex patterns
http.useAllLocalAddressesMatching("pattern1", "pattern2")
//#localAddress
//#perUserKeyManagerFactory
http.perUserKeyManagerFactory { userId -> null as KeyManagerFactory? }
//#perUserKeyManagerFactory
//#disableAutoReferer
http.disableAutoReferer()
//#disableAutoReferer
//#disableCaching
http.disableCaching()
//#disableCaching
//#disableUrlEncoding
http.disableUrlEncoding()
//#disableUrlEncoding
//#silentUri
// make all requests whose url matches the provided Java Regex pattern silent
http.silentUri("https://myCDN/.*")
// make all resource requests silent
http.silentResources()
//#silentUri
//#headers
http
// with a static header value
.header("foo", "bar")
// with a Gatling EL string header value
.header("foo", "#{headerValue}")
// with a function value
.header("foo") { session -> session.getString("headerValue") }
.headers(mapOf("foo" to "bar"))
//#headers
//#headers-built-ins
// all those also accept a Gatling EL string or a function parameter
http
.acceptHeader("value")
.acceptCharsetHeader("value")
.acceptEncodingHeader("value")
.acceptLanguageHeader("value")
.authorizationHeader("value")
.connectionHeader("value")
.contentTypeHeader("value")
.doNotTrackHeader("value")
.originHeader("value")
.userAgentHeader("value")
.upgradeInsecureRequestsHeader("value")
//#headers-built-ins
//#sign
http.sign { request ->
// import org.apache.commons.codec.digest.DigestUtils
val md5 = DigestUtils.md5Hex(request.body.bytes)
request.headers.add("X-MD5", md5)
}
// or with access to the Session
http.sign { request, session -> }
//#sign
//#sign-oauth1
// with static values
http.signWithOAuth1(
"consumerKey",
"clientSharedSecret",
"token",
"tokenSecret"
)
// with functions
http.signWithOAuth1(
{ session -> session.getString("consumerKey") },
{ session -> session.getString("clientSharedSecret") },
{ session -> session.getString("token") }
) { session -> session.getString("tokenSecret") }
//#sign-oauth1
//#authorization
// with static values
http.basicAuth("username", "password")
// with Gatling El strings
http.basicAuth("#{username}", "#{password}")
// with functions
http.basicAuth({ session -> session.getString("username") }) { session -> session.getString("password") }
// with static values
http.digestAuth("username", "password")
// with Gatling El strings
http.digestAuth("#{username}", "#{password}")
// with functions
http.digestAuth({ session -> session.getString("username") }) { session -> session.getString("password") }
//#authorization
//#disableFollowRedirect
http.disableFollowRedirect()
//#disableFollowRedirect
//#redirectNamingStrategy
http.redirectNamingStrategy {
uri, originalRequestName, redirectCount -> "redirectedRequestName"
}
//#redirectNamingStrategy
//#transformResponse
http.transformResponse { response, session -> response }
//#transformResponse
//#inferHtmlResources
// fetch only resources matching one of the patterns in the allow list
http.inferHtmlResources(AllowList("pattern1", "pattern2"))
// fetch all resources except those matching one of the patterns in the deny list
http.inferHtmlResources(DenyList("pattern1", "pattern2"))
// fetch only resources matching one of the patterns in the allow list
// but not matching one of the patterns in the deny list
http.inferHtmlResources(AllowList("pattern1", "pattern2"), DenyList("pattern3", "pattern4"))
//#inferHtmlResources
//#nameInferredHtmlResources
// (default): name requests after the resource's url tail (after last `/`)
http.nameInferredHtmlResourcesAfterUrlTail()
// name requests after the resource's path
http.nameInferredHtmlResourcesAfterPath()
// name requests after the resource's absolute url
http.nameInferredHtmlResourcesAfterAbsoluteUrl()
// name requests after the resource's relative url
http.nameInferredHtmlResourcesAfterRelativeUrl()
// name requests after the resource's last path element
http.nameInferredHtmlResourcesAfterLastPathElement()
// name requests with a custom strategy
http.nameInferredHtmlResources { uri -> "name" }
//#nameInferredHtmlResources
//#proxy
http.proxy(
Proxy("myHttpProxyHost", 8080)
.httpsPort(8143)
.credentials("myUsername", "myPassword")
)
http.proxy(
Proxy("mySocks4ProxyHost", 8080)
.socks4()
)
http.proxy(
Proxy("mySocks5ProxyHost", 8080)
.httpsPort(8143)
.socks5()
)
//#proxy
//#noProxyFor
http
.proxy(Proxy("myProxyHost", 8080))
.noProxyFor("www.github.com", "gatling.io")
//#noProxyFor
}
}
| src/docs/content/reference/current/http/protocol/code/HttpProtocolSampleKotlin.kt | 2952700045 |
package com.lee.socrates.mvvmdemo.bluetooth
import android.Manifest
import android.app.Activity
import android.databinding.ObservableField
import android.view.View
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.Context
import android.bluetooth.BluetoothDevice
import android.util.Log
import java.util.*
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGatt
import android.content.Intent
import android.bluetooth.BluetoothGattDescriptor
import android.bluetooth.BluetoothGattService
import android.bluetooth.BluetoothGattCallback
import android.content.pm.PackageManager
import android.os.Build
import android.support.v4.app.ActivityCompat
import android.text.TextUtils
import kotlin.experimental.and
import android.support.v4.app.ActivityCompat.startActivityForResult
import android.support.v4.content.ContextCompat
/**
* Created by lee on 2018/3/20.
*/
public class BluetoothViewModel {
private val TAG = this.javaClass.simpleName
private val bleAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
val info = ObservableField<String>()
private lateinit var mContext: Context
private var bleGatt: BluetoothGatt? = null
private var bleScanCallback: BluetoothAdapter.LeScanCallback? = null
private lateinit var mNavigator: BlueToothNavigator
fun init(context: Context, navigator: BlueToothNavigator) {
mContext = context
mNavigator = navigator
}
fun handleActivityResult(requestCode: Int, resultCode: Int) {
if (requestCode == BlueToothActivity.REQUEST_ENABLE_BT) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
mNavigator.requestLocationPermission()
return
}
}
startScan()
}
}
fun handleRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (requestCode == BlueToothActivity.MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startScan()
}
}
}
fun startSearch(view: View) {
Log.e(TAG, "startSearch ...")
// 检测蓝牙
if (!check()) {
if (bleAdapter != null && !bleAdapter.isEnabled) {
mNavigator.requestOpenBlueTooth()
}
return
}
startScan()
}
private fun startScan() {
bleScanCallback = BleScanCallback() // 回调接口
bleAdapter != null && bleAdapter.startLeScan(bleScanCallback)
// var pairedDevices: Set<BluetoothDevice>? = bleAdapter?.bondedDevices
// if(pairedDevices!=null && pairedDevices.isNotEmpty()){
// for (device in pairedDevices) {
// Log.e(TAG, "found device name : " + device.name + " address : " + device.address)
// }
// }
}
private fun check(): Boolean {
return null != bleAdapter && bleAdapter.isEnabled && !bleAdapter.isDiscovering
}
// 实现扫描回调接口
private inner class BleScanCallback : BluetoothAdapter.LeScanCallback {
// 扫描到新设备时,会回调该接口。可以将新设备显示在ui中,看具体需求
override fun onLeScan(device: BluetoothDevice, rssi: Int, scanRecord: ByteArray) {
if (device.name!=null && device.name.isNotEmpty()) {
Log.e(TAG, "found device name : " + device.name + " address : " + device.address)
} else{
Log.e(TAG, "found device name : " + device.name + " address : " + device.address)
bleAdapter?.stopLeScan(bleScanCallback)
}
}
}
// 连接蓝牙设备,device为之前扫描得到的
fun connect(device: BluetoothDevice) {
if (!check()) return // 检测蓝牙
bleAdapter?.stopLeScan(bleScanCallback)
if (bleGatt != null && bleGatt!!.connect()) { // 已经连接了其他设备
// 如果是先前连接的设备,则不做处理
if (TextUtils.equals(device.address, bleGatt?.device?.address)) {
return
} else {
// 否则断开连接
bleGatt?.close()
}
}
// 连接设备,第二个参数为是否自动连接,第三个为回调函数
bleGatt = device.connectGatt(mContext, false, BleGattCallback())
}
// 实现连接回调接口[关键]
private inner class BleGattCallback : BluetoothGattCallback() {
// 连接状态改变(连接成功或失败)时回调该接口
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
if (newState == BluetoothGatt.STATE_CONNECTED) { // 连接成功
connectSuccess()
gatt.discoverServices() // 则去搜索设备的服务(Service)和服务对应Characteristic
} else { // 连接失败
connectFail()
}
}
// 发现设备的服务(Service)回调,需要在这里处理订阅事件。
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
if (status == BluetoothGatt.GATT_SUCCESS) { // 成功订阅
var services = gatt.services // 获得设备所有的服务
var characteristics = ArrayList<BluetoothGattCharacteristic>()
var descriptors = ArrayList<BluetoothGattDescriptor>()
// 依次遍历每个服务获得相应的Characteristic集合
// 之后遍历Characteristic获得相应的Descriptor集合
for (service in services) {
Log.e(TAG, "-- service uuid : " + service.uuid.toString() + " --")
for (characteristic in service.characteristics) {
Log.e(TAG, "characteristic uuid : " + characteristic.uuid)
characteristics.add(characteristic)
// String READ_UUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e";
// 判断当前的Characteristic是否想要订阅的,这个要依据各自蓝牙模块的协议而定
if (characteristic.uuid.toString() == "sdfadasfadfdfafdafdfadfa") {
// 依据协议订阅相关信息,否则接收不到数据
bleGatt?.setCharacteristicNotification(characteristic, true)
// 大坑,适配某些手机!!!比如小米...
bleGatt?.readCharacteristic(characteristic)
for (descriptor in characteristic.descriptors) {
descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
bleGatt?.writeDescriptor(descriptor)
}
}
for (descriptor in characteristic.descriptors) {
Log.e(TAG, "descriptor uuid : " + characteristic.uuid)
descriptors.add(descriptor)
}
}
}
discoverServiceSuccess()
} else {
discoverServiceFail()
}
}
// 发送消息结果回调
override fun onCharacteristicWrite(gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic,
status: Int) {
val intent: Intent
if (BluetoothGatt.GATT_SUCCESS == status) { // 发送成功
sendMessageSuccess()
} else { // 发送失败
sendMessageFail()
}
}
// 当订阅的Characteristic接收到消息时回调
override fun onCharacteristicChanged(gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic) {
// 数据为 characteristic.getValue())
Log.e(TAG, "onCharacteristicChanged: " + Arrays.toString(characteristic.value))
}
}
private fun connectSuccess() {
}
private fun connectFail() {
}
private fun discoverServiceSuccess() {
}
private fun discoverServiceFail() {
}
private fun sendMessageSuccess() {
}
private fun sendMessageFail() {
}
// byte转十六进制字符串
fun bytes2HexString(bytes: ByteArray): String {
var ret = ""
for (item in bytes) {
var hex = Integer.toHexString((item and 0xFF.toByte()).toInt())
if (hex.length == 1) {
hex = '0' + hex
}
ret += hex.toUpperCase(Locale.CHINA)
}
return ret
}
// 将16进制的字符串转换为字节数组
fun getHexBytes(message: String): ByteArray {
val len = message.length / 2
val chars = message.toCharArray()
val hexStr = arrayOfNulls<String>(len)
val bytes = ByteArray(len)
var i = 0
var j = 0
while (j < len) {
hexStr[j] = "" + chars[i] + chars[i + 1]
bytes[j] = Integer.parseInt(hexStr[j], 16).toByte()
i += 2
j++
}
return bytes
}
} | mvvmdemo/src/main/java/com/lee/socrates/mvvmdemo/bluetooth/BluetoothViewModel.kt | 2948453513 |
package org.cakesolutions.hello.api
import akka.Done
import akka.NotUsed
import com.lightbend.lagom.javadsl.api.Descriptor
import com.lightbend.lagom.javadsl.api.Service
import com.lightbend.lagom.javadsl.api.Service.named
import com.lightbend.lagom.javadsl.api.Service.pathCall
import com.lightbend.lagom.javadsl.api.ServiceCall
import kotlin.reflect.jvm.javaMethod
/**
* The Hello service interface.
*
* This describes everything that Lagom needs to know about how to serve and
* consume the Hello.
*/
interface KHelloService : Service {
/**
* Example: `curl http://localhost:9000/api/hello/Alice`
*/
fun hello(id: String): ServiceCall<NotUsed, String>
/**
* Example:
* ```
* curl -H "Content-Type: application/json" -X POST -d '{"message": "Hi"}' http://localhost:9000/api/hello/Alice
* ```
*/
fun useGreeting(id: String): ServiceCall<KGreetingMessage, Done>
@JvmDefault
override fun descriptor(): Descriptor {
return named("hello").withCalls(
pathCall<NotUsed, String>("/api/hello/:id", KHelloService::hello.javaMethod),
pathCall<KGreetingMessage, Done>("/api/hello/:id", KHelloService::useGreeting.javaMethod)
).withAutoAcl(true)
}
} | hello-api/src/main/kotlin/org/cakesolutions/hello/api/KHelloService.kt | 18739103 |
package com.github.jameshnsears.brexitsoundboard.sound
import com.github.jameshnsears.brexitsoundboard.R
import org.junit.Test
class MapButtonToSoundTheresaTest : AbstractMapButtonToSound() {
@Test
fun ensureButtonsPlayCorrectSounds() {
keyValueMap[R.id.buttonTheresaBrexitMeansBrexit] = R.raw.theresa_sound_brexit_means_brexit
keyValueMap[R.id.buttonTheresaNoDealBetterThanABadDeal] = R.raw.theresa_sound_no_deal_better_than_a_bad_deal
keyValueMap[R.id.buttonTheresaNoNeedForAnElection] = R.raw.theresa_sound_no_need_for_an_election
keyValueMap[R.id.buttonTheresaRedWhiteAndBlueBrexit] = R.raw.theresa_sound_red_white_and_blue_brexit
keyValueMap[R.id.buttonTheresaStrongAndStableLeadership] = R.raw.theresa_sound_strong_and_stable_leadership
keyValueMap[R.id.buttonTheresAPlan] = R.raw.theresa_sound_a_plan_for_britain
keyValueMap[R.id.buttonTheresaCertaintyAndClarity] = R.raw.theresa_sound_certainty_and_clarity
keyValueMap[R.id.buttonTheresaWeShouldStayInTheEu] = R.raw.theresa_sound_we_should_stay_inside_eu
keyValueMap[R.id.buttonTheresaNIisPartOfTheUK] = R.raw.theresa_sound_ni_is_part_of_the_uk
keyValueMap[R.id.buttonTheresaIWillNeverAgreeTo] = R.raw.theresa_sound_something_i_will_never_agree_to
keyValueMap[R.id.buttonTheresaCitizenOfNowhere] = R.raw.theresa_sound_citizen_of_nowhere
assertKeyValueMatch()
}
}
| app/src/test/java/com/github/jameshnsears/brexitsoundboard/sound/MapButtonToSoundTheresaTest.kt | 2268783462 |
/*
* BSD 3-Clause License
*
* Copyright 2018 Sage Bionetworks. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder(s) nor the names of any contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission. No license is granted to the trademarks of
* the copyright holders even if such marks are included in this software.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.sagebionetworks.bridge.android.access
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import dagger.android.support.DaggerFragment
import org.sagebionetworks.bridge.android.R
import org.slf4j.LoggerFactory
import javax.inject.Inject
/**
* A fragment for functionality that is gated by Bridge access rules.
*/
abstract class BridgeAccessFragment : BridgeAccessStrategy, DaggerFragment() {
private val logger = LoggerFactory.getLogger(BridgeAccessFragment::class.java)
@Inject
lateinit var bridgeAccessViewModelFactory: BridgeAccessViewModel.Factory
private lateinit var bridgeAccessViewModel: BridgeAccessViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
return inflater.inflate(R.layout.osb_access_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
bridgeAccessViewModel = ViewModelProviders.of(requireActivity(), bridgeAccessViewModelFactory)
.get(BridgeAccessViewModel::class.java)
bridgeAccessViewModel.bridgeAccessStatus.observe(this,
Observer<Resource<BridgeAccessState>> { state ->
state?.let {
BridgeAccessStrategy.handle(it, this)
}
})
}
override fun onResume() {
super.onResume()
logger.debug("onResume")
bridgeAccessViewModel.checkAccess()
}
override fun onPause() {
super.onPause()
logger.debug("onPause")
}
override fun onRequireAppUpgrade() {
val container = view?.findViewById<FrameLayout>(R.id.container)
layoutInflater.inflate(R.layout.osb_app_upgrade_required, container, true)
}
override fun onLoading(state: BridgeAccessState) {
logger.debug("Loading bridge access state: {}", state)
}
override fun onErrored(state: BridgeAccessState, message: String?) {
logger.warn("Error loading bridge access state: {}, message: {}", state, message)
}
}
| android-sdk/src/main/java/org/sagebionetworks/bridge/android/access/BridgeAccessFragment.kt | 1415169380 |
package com.ivanovsky.passnotes.domain.entity.filter
import com.ivanovsky.passnotes.data.entity.Property
import com.ivanovsky.passnotes.data.entity.PropertyType
class FilterTitleStrategy : PropertyFilterStrategy {
override fun apply(properties: Sequence<Property>): Sequence<Property> {
return properties.filter { property -> property.type == PropertyType.TITLE }
}
} | app/src/main/kotlin/com/ivanovsky/passnotes/domain/entity/filter/FilterTitleStrategy.kt | 704505251 |
package <%= appPackage %>.domain.check
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
/**
* Created by nelo on 21/3/17.
*/
class PreconditionsTest {
@Rule
@JvmField
public var exception = ExpectedException.none()
@Test
fun checkNotNull(){
var message : String = ""
Preconditions.checkNotNull(message)
}
@Test
fun checkNull(){
exception.expect(NullPointerException::class.java)
Preconditions.checkNotNull(null)
}
} | generators/app/templates/clean-architecture/domain/src/test/kotlin/com/nelosan/clean/domain/check/PreconditionsTest.kt | 1096335462 |
package fi.lasicaine.navigationdrawer
import android.os.Bundle
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import androidx.core.view.GravityCompat
import androidx.appcompat.app.ActionBarDrawerToggle
import android.view.MenuItem
import androidx.drawerlayout.widget.DrawerLayout
import com.google.android.material.navigation.NavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import android.view.Menu
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
val fab: FloatingActionButton = findViewById(R.id.fab)
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
val navView: NavigationView = findViewById(R.id.nav_view)
val toggle = ActionBarDrawerToggle(
this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close
)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
navView.setNavigationItemSelectedListener(this)
}
override fun onBackPressed() {
val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
when (item.itemId) {
R.id.nav_home -> {
// Handle the camera action
}
R.id.nav_gallery -> {
}
R.id.nav_slideshow -> {
}
R.id.nav_tools -> {
}
R.id.nav_share -> {
}
R.id.nav_send -> {
}
}
val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
drawerLayout.closeDrawer(GravityCompat.START)
return true
}
}
| NavigationDrawer/app/src/main/java/fi/lasicaine/navigationdrawer/MainActivity.kt | 2275246174 |
package ch.softappeal.yass.remote
import ch.softappeal.yass.*
import java.lang.reflect.*
@MustBeDocumented
@Retention
@Target(AnnotationTarget.FUNCTION)
annotation class OneWay
val Method.isOneWay: Boolean get() = isAnnotationPresent(OneWay::class.java)
data class MethodMapping(val method: Method, val id: Int, val oneWay: Boolean = method.isOneWay) {
init {
if (oneWay) {
check(method.returnType === Void.TYPE) { "OneWay method '$method' must return void" }
check(method.exceptionTypes.isEmpty()) { "OneWay method '$method' must not throw exceptions" }
}
}
}
interface MethodMapper {
@Throws(Exception::class)
fun map(id: Int): MethodMapping
@Throws(Exception::class)
fun map(method: Method): MethodMapping
}
typealias MethodMapperFactory = (contract: Class<*>) -> MethodMapper
fun MethodMapperFactory.mappings(contract: Class<*>): Sequence<MethodMapping> {
val methodMapper = this(contract)
return contract.methods.asSequence()
.map(methodMapper::map)
.sortedBy(MethodMapping::id)
}
val SimpleMethodMapperFactory: MethodMapperFactory = { contract ->
val mappings = mutableListOf<MethodMapping>()
val name2mapping = mutableMapOf<String, MethodMapping>()
for (method in contract.methods.sortedBy(Method::getName)) {
val mapping = MethodMapping(method, mappings.size)
val oldMapping = name2mapping.put(method.name, mapping)
check(oldMapping == null) {
"methods '$method' and '${oldMapping!!.method}' in contract '$contract' are overloaded"
}
mappings.add(mapping)
}
object : MethodMapper {
override fun map(id: Int) = if (id in 0 until mappings.size)
mappings[id]
else
error("unexpected method id $id for contract '$contract'")
override fun map(method: Method) =
checkNotNull(name2mapping[method.name]) { "unexpected method '$method' for contract '$contract'" }
}
}
val TaggedMethodMapperFactory: MethodMapperFactory = { contract ->
val id2mapping = mutableMapOf<Int, MethodMapping>()
for (method in contract.methods) {
val id = tag(method)
val oldMapping = id2mapping.put(id, MethodMapping(method, id))
check(oldMapping == null) {
"tag $id used for methods '$method' and '${oldMapping!!.method}' in contract '$contract'"
}
}
object : MethodMapper {
override fun map(id: Int) =
checkNotNull(id2mapping[id]) { "unexpected method id $id for contract '$contract'" }
override fun map(method: Method) =
checkNotNull(id2mapping[tag(method)]) { "unexpected method '$method' for contract '$contract'" }
}
}
| kotlin/yass/main/ch/softappeal/yass/remote/MethodMapper.kt | 153703558 |
/**
* BreadWallet
*
* Created by Ahsan Butt <[email protected]> on 1/15/20.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.platform.jsbridge
import android.content.Context
import android.security.keystore.UserNotAuthenticatedException
import android.webkit.JavascriptInterface
import com.breadwallet.BuildConfig
import com.breadwallet.R
import com.breadwallet.app.Buy
import com.breadwallet.app.ConversionTracker
import com.breadwallet.app.Trade
import com.breadwallet.breadbox.BreadBox
import com.breadwallet.breadbox.TransferSpeed
import com.breadwallet.breadbox.addressFor
import com.breadwallet.breadbox.baseUnit
import com.breadwallet.breadbox.containsCurrency
import com.breadwallet.breadbox.currencyId
import com.breadwallet.breadbox.defaultUnit
import com.breadwallet.breadbox.estimateFee
import com.breadwallet.breadbox.estimateMaximum
import com.breadwallet.breadbox.feeForSpeed
import com.breadwallet.breadbox.findCurrency
import com.breadwallet.breadbox.hashString
import com.breadwallet.breadbox.isBitcoin
import com.breadwallet.breadbox.isNative
import com.breadwallet.breadbox.toBigDecimal
import com.breadwallet.breadbox.toSanitizedString
import com.breadwallet.crypto.Address
import com.breadwallet.crypto.AddressScheme
import com.breadwallet.crypto.Amount
import com.breadwallet.crypto.Transfer
import com.breadwallet.crypto.TransferAttribute
import com.breadwallet.crypto.TransferFeeBasis
import com.breadwallet.crypto.TransferState
import com.breadwallet.crypto.Wallet
import com.breadwallet.crypto.errors.FeeEstimationError
import com.breadwallet.logger.logDebug
import com.breadwallet.logger.logError
import com.breadwallet.model.TokenItem
import com.breadwallet.repository.RatesRepository
import com.breadwallet.tools.manager.BRSharedPrefs
import com.breadwallet.tools.security.BrdUserManager
import com.breadwallet.tools.util.EventUtils
import com.breadwallet.tools.util.TokenUtil
import com.breadwallet.ui.send.TransferField
import com.platform.ConfirmTransactionMessage
import com.platform.PlatformTransactionBus
import com.platform.TransactionResultMessage
import com.breadwallet.platform.entities.TxMetaDataValue
import com.breadwallet.platform.interfaces.AccountMetaDataProvider
import com.platform.util.getStringOrNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.transform
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.math.BigDecimal
import java.util.Currency
import java.util.Locale
class WalletJs(
private val promise: NativePromiseFactory,
private val context: Context,
private val metaDataProvider: AccountMetaDataProvider,
private val breadBox: BreadBox,
private val ratesRepository: RatesRepository,
private val userManager: BrdUserManager,
private val conversionTracker: ConversionTracker
) : JsApi {
companion object {
private const val KEY_BTC_DENOMINATION_DIGITS = "btc_denomination_digits"
private const val KEY_LOCAL_CURRENCY_CODE = "local_currency_code"
private const val KEY_LOCAL_CURRENCY_PRECISION = "local_currency_precision"
private const val KEY_LOCAL_CURRENCY_SYMBOL = "local_currency_symbol"
private const val KEY_APP_PLATFORM = "app_platform"
private const val KEY_APP_VERSION = "app_version"
private const val KEY_CURRENCY = "currency"
private const val KEY_ADDRESS = "address"
private const val KEY_CURRENCIES = "currencies"
private const val KEY_ID = "id"
private const val KEY_TICKER = "ticker"
private const val KEY_NAME = "name"
private const val KEY_COLORS = "colors"
private const val KEY_BALANCE = "balance"
private const val KEY_FIAT_BALANCE = "fiatBalance"
private const val KEY_EXCHANGE = "exchange"
private const val KEY_NUMERATOR = "numerator"
private const val KEY_DENOMINATOR = "denominator"
private const val KEY_HASH = "hash"
private const val KEY_TRANSMITTED = "transmitted"
private const val APP_PLATFORM = "android"
private const val ERR_EMPTY_CURRENCIES = "currencies_empty"
private const val ERR_ESTIMATE_FEE = "estimate_fee"
private const val ERR_INSUFFICIENT_BALANCE = "insufficient_balance"
private const val ERR_SEND_TXN = "send_txn"
private const val ERR_CURRENCY_NOT_SUPPORTED = "currency_not_supported"
private const val DOLLAR_IN_CENTS = 100
private const val BASE_10 = 10
private const val FORMAT_DELIMITER = "?format="
private const val FORMAT_LEGACY = "legacy"
private const val FORMAT_SEGWIT = "segwit"
}
@JavascriptInterface
fun info() = promise.create {
val system = checkNotNull(breadBox.getSystemUnsafe())
val btcWallet = system.wallets.first { it.currency.isBitcoin() }
val preferredCode = BRSharedPrefs.getPreferredFiatIso()
val fiatCurrency = Currency.getInstance(preferredCode)
JSONObject().apply {
put(KEY_BTC_DENOMINATION_DIGITS, btcWallet.defaultUnit.decimals)
put(KEY_LOCAL_CURRENCY_CODE, fiatCurrency.currencyCode.toUpperCase())
put(KEY_LOCAL_CURRENCY_PRECISION, fiatCurrency.defaultFractionDigits)
put(KEY_LOCAL_CURRENCY_SYMBOL, fiatCurrency.symbol)
put(KEY_APP_PLATFORM, APP_PLATFORM)
put(KEY_APP_VERSION, "${BuildConfig.VERSION_NAME}.${BuildConfig.BUILD_VERSION}")
}
}
@JvmOverloads
@JavascriptInterface
fun event(
name: String,
attributes: String? = null
) = promise.create {
if (attributes != null) {
val json = JSONObject(attributes)
val attr = mutableMapOf<String, String>()
json.keys().forEach {
attr[it] = json.getString(it)
}
EventUtils.pushEvent(name, attr)
} else {
EventUtils.pushEvent(name)
}
null
}
@JavascriptInterface
fun addresses(
currencyCodeQ: String
) = promise.create {
var (currencyCode, format) = parseCurrencyCodeQuery(currencyCodeQ)
val system = checkNotNull(breadBox.getSystemUnsafe())
val wallet = system.wallets.first { it.currency.code.equals(currencyCode, true) }
val address = getAddress(wallet, format)
JSONObject().apply {
put(KEY_CURRENCY, currencyCode)
put(KEY_ADDRESS, address)
}
}
@Suppress("LongMethod", "ComplexMethod")
@JavascriptInterface
@JvmOverloads
fun currencies(listAll: Boolean = false) = promise.create {
val system = checkNotNull(breadBox.getSystemUnsafe())
val wallets = if (listAll) {
TokenUtil.getTokenItems()
.filter(TokenItem::isSupported)
.map(TokenItem::currencyId)
} else {
checkNotNull(metaDataProvider.getEnabledWalletsUnsafe())
}
val currenciesJSON = JSONArray()
wallets.forEach { currencyId ->
val wallet = system.wallets.firstOrNull { it.currencyId.equals(currencyId, true) }
val tokenItem = TokenUtil.tokenForCurrencyId(currencyId)
val currencyCode =
wallet?.currency?.code?.toUpperCase() ?: tokenItem?.symbol
if (currencyCode.isNullOrBlank()) return@forEach
val json = JSONObject().apply {
try {
put(KEY_ID, currencyCode)
put(KEY_TICKER, currencyCode)
put(KEY_NAME, tokenItem?.name ?: wallet?.name)
val colors = JSONArray().apply {
put(TokenUtil.getTokenStartColor(currencyCode))
put(TokenUtil.getTokenEndColor(currencyCode))
}
put(KEY_COLORS, colors)
// Add balance info if wallet is available
if (wallet != null) {
val balance = JSONObject().apply {
val numerator = wallet.balance.toStringWithBase(BASE_10, "")
val denominator =
Amount.create(
"1",
false,
wallet.defaultUnit
).orNull()?.toStringWithBase(BASE_10, "") ?: Amount.create(
0,
wallet.baseUnit
)
put(KEY_CURRENCY, currencyCode)
put(KEY_NUMERATOR, numerator)
put(KEY_DENOMINATOR, denominator)
}
val fiatCurrency = BRSharedPrefs.getPreferredFiatIso()
val fiatBalance = JSONObject().apply {
val fiatAmount = ratesRepository.getFiatForCrypto(
wallet.balance.toBigDecimal(),
currencyCode,
fiatCurrency
)?.multiply(BigDecimal(DOLLAR_IN_CENTS)) ?: BigDecimal.ZERO
put(KEY_CURRENCY, fiatCurrency)
put(KEY_NUMERATOR, fiatAmount.toPlainString())
put(KEY_DENOMINATOR, DOLLAR_IN_CENTS.toString())
}
val exchange = JSONObject().apply {
val fiatPerUnit = ratesRepository.getFiatForCrypto(
BigDecimal.ONE,
currencyCode,
fiatCurrency
)?.multiply(BigDecimal(DOLLAR_IN_CENTS)) ?: BigDecimal.ZERO
put(KEY_CURRENCY, fiatCurrency)
put(KEY_NUMERATOR, fiatPerUnit.toPlainString())
put(KEY_DENOMINATOR, DOLLAR_IN_CENTS.toString())
}
put(KEY_BALANCE, balance)
put(KEY_FIAT_BALANCE, fiatBalance)
put(KEY_EXCHANGE, exchange)
}
} catch (ex: JSONException) {
logError("Failed to load currency data: $currencyCode")
}
}
currenciesJSON.put(json)
}
if (currenciesJSON.length() == 0) throw IllegalStateException(ERR_EMPTY_CURRENCIES)
JSONObject().put(KEY_CURRENCIES, currenciesJSON)
}
@JavascriptInterface
fun transferAttrsFor(currency: String, addressString: String) = promise.createForArray {
val wallet = breadBox.wallet(currency).first()
val address = wallet.addressFor(addressString)
val attrs = address?.run(wallet::getTransferAttributesFor) ?: wallet.transferAttributes
val jsonAttrs = attrs.map { attr ->
JSONObject().apply {
put("key", attr.key)
put("required", attr.isRequired)
put("value", attr.value.orNull())
}
}
JSONArray(jsonAttrs)
}
@JvmOverloads
@JavascriptInterface
fun transaction(
toAddress: String,
description: String,
amountStr: String,
currency: String,
transferAttrsString: String = "[]"
) = promise.create {
val system = checkNotNull(breadBox.getSystemUnsafe())
val wallet = system.wallets.first { it.currency.code.equals(currency, true) }
val amountJSON = JSONObject(amountStr)
val numerator = amountJSON.getString(KEY_NUMERATOR).toDouble()
val denominator = amountJSON.getString(KEY_DENOMINATOR).toDouble()
val amount = Amount.create((numerator / denominator), wallet.unit)
val address = checkNotNull(wallet.addressFor(toAddress)) {
"Invalid address ($toAddress)"
}
val transferAttrs = wallet.getTransferAttributesFor(address)
val transferAttrsInput = JSONArray(transferAttrsString).run {
List(length(), ::getJSONObject)
}
transferAttrs.forEach { attribute ->
val key = attribute.key.toLowerCase(Locale.ROOT)
val attrJson = transferAttrsInput.firstOrNull { attr ->
attr.getStringOrNull("key").equals(key, true)
}
attribute.setValue(attrJson?.getStringOrNull("value"))
val error = wallet.validateTransferAttribute(attribute).orNull()
require(error == null) {
"Invalid attribute key=${attribute.key} value=${attribute.value.orNull()} error=${error?.name}"
}
}
val feeBasis =
checkNotNull(estimateFee(wallet, address, amount)) { ERR_ESTIMATE_FEE }
val fee = feeBasis.fee.toBigDecimal()
val totalCost = if (feeBasis.currency.code == wallet.currency.code) {
amount.toBigDecimal() + fee
} else {
amount.toBigDecimal()
}
val balance = wallet.balance.toBigDecimal()
check(!amount.isZero && totalCost <= balance) { ERR_INSUFFICIENT_BALANCE }
val transaction =
checkNotNull(
sendTransaction(
wallet,
address,
amount,
totalCost,
feeBasis,
transferAttrs
)
) { ERR_SEND_TXN }
metaDataProvider.putTxMetaData(
transaction,
TxMetaDataValue(comment = description)
)
conversionTracker.track(Trade(currency, transaction.hashString()))
JSONObject().apply {
put(KEY_HASH, transaction.hashString())
put(KEY_TRANSMITTED, true)
}
}
@JavascriptInterface
fun enableCurrency(currencyCode: String) = promise.create {
val system = checkNotNull(breadBox.system().first())
val currencyId = TokenUtil.tokenForCode(currencyCode)?.currencyId.orEmpty()
check(currencyId.isNotEmpty()) { ERR_CURRENCY_NOT_SUPPORTED }
val network = system.networks.find { it.containsCurrency(currencyId) }
when (network?.findCurrency(currencyId)?.isNative()) {
null -> logError("No network or currency found for $currencyId.")
false -> {
val trackedWallets = breadBox.wallets().first()
if (!trackedWallets.containsCurrency(network.currency.uids)) {
logDebug("Adding native wallet ${network.currency.uids} for $currencyId.")
metaDataProvider.enableWallet(network.currency.uids)
}
}
}
metaDataProvider.enableWallet(currencyId)
// Suspend until the wallet exists, i.e. an address is available.
val wallet = breadBox.wallet(currencyCode).first()
JSONObject().apply {
put(KEY_CURRENCY, currencyCode)
put(KEY_ADDRESS, getAddress(wallet, FORMAT_LEGACY))
if (wallet.currency.isBitcoin()) {
put("${KEY_ADDRESS}_${FORMAT_SEGWIT}", getAddress(wallet, FORMAT_SEGWIT))
}
}
}
@JavascriptInterface
fun maxlimit(
toAddress: String,
currency: String
) = promise.create {
val system = checkNotNull(breadBox.getSystemUnsafe())
val wallet = system.wallets.first { it.currency.code.equals(currency, true) }
val address = checkNotNull(wallet.addressFor(toAddress))
val limitMaxAmount =
wallet.estimateMaximum(address, wallet.feeForSpeed(TransferSpeed.Priority(currency)))
checkNotNull(limitMaxAmount)
val numerator = limitMaxAmount.convert(wallet.baseUnit).orNull()
?.toStringWithBase(BASE_10, "") ?: "0"
val denominator = Amount.create("1", false, wallet.baseUnit).orNull()
?.toStringWithBase(BASE_10, "")
?: Amount.create(0, wallet.baseUnit).toStringWithBase(BASE_10, "")
JSONObject().apply {
put(KEY_NUMERATOR, numerator)
put(KEY_DENOMINATOR, denominator)
}
}
@JavascriptInterface
fun trackBuy(
currencyCode: String,
amount: String
) = promise.createForUnit {
conversionTracker.track(Buy(currencyCode, amount.toDouble(), System.currentTimeMillis()))
}
private suspend fun estimateFee(
wallet: Wallet,
address: Address?,
amount: Amount
): TransferFeeBasis? {
if (address == null || wallet.containsAddress(address)) {
return null
}
try {
return wallet.estimateFee(
address,
amount,
wallet.feeForSpeed(TransferSpeed.Priority(wallet.currency.code))
)
} catch (e: FeeEstimationError) {
logError("Failed get fee estimate", e)
} catch (e: IllegalStateException) {
logError("Failed get fee estimate", e)
}
return null
}
@Suppress("LongMethod")
private suspend fun sendTransaction(
wallet: Wallet,
address: Address,
amount: Amount,
totalCost: BigDecimal,
feeBasis: TransferFeeBasis,
transferAttributes: Set<TransferAttribute>
): Transfer? {
val fiatCode = BRSharedPrefs.getPreferredFiatIso()
val fiatAmount = ratesRepository.getFiatForCrypto(
amount.toBigDecimal(),
wallet.currency.code,
fiatCode
) ?: BigDecimal.ZERO
val fiatTotalCost = ratesRepository.getFiatForCrypto(
totalCost,
wallet.currency.code,
fiatCode
) ?: BigDecimal.ZERO
val fiatNetworkFee = ratesRepository.getFiatForCrypto(
feeBasis.fee.toBigDecimal(),
wallet.currency.code,
fiatCode
) ?: BigDecimal.ZERO
val transferFields = transferAttributes.map { attribute ->
TransferField(
attribute.key,
attribute.isRequired,
false,
attribute.value.orNull()
)
}
val result = PlatformTransactionBus.results().onStart {
PlatformTransactionBus.sendMessage(
ConfirmTransactionMessage(
wallet.currency.code,
fiatCode,
feeBasis.currency.code,
address.toSanitizedString(),
TransferSpeed.Priority(wallet.currency.code),
amount.toBigDecimal(),
fiatAmount,
fiatTotalCost,
fiatNetworkFee,
transferFields
)
)
}.first()
return when (result) {
is TransactionResultMessage.TransactionCancelled -> throw IllegalStateException(
context.getString(R.string.Platform_transaction_cancelled)
)
is TransactionResultMessage.TransactionConfirmed -> {
val phrase = try {
checkNotNull(userManager.getPhrase())
} catch (ex: UserNotAuthenticatedException) {
logError("Failed to get phrase.", ex)
return null
}
val newTransfer =
wallet.createTransfer(address, amount, feeBasis, transferAttributes).orNull()
if (newTransfer == null) {
logError("Failed to create transfer.")
return null
}
wallet.walletManager.submit(newTransfer, phrase)
breadBox.walletTransfer(wallet.currency.code, newTransfer.hashString())
.transform { transfer ->
when (checkNotNull(transfer.state.type)) {
TransferState.Type.INCLUDED,
TransferState.Type.PENDING,
TransferState.Type.SUBMITTED -> emit(transfer)
TransferState.Type.DELETED,
TransferState.Type.FAILED -> {
logError("Failed to submit transfer ${transfer.state.failedError.orNull()}")
emit(null)
}
// Ignore pre-submit states
TransferState.Type.CREATED,
TransferState.Type.SIGNED -> Unit
}
}.first()
}
}
}
private fun parseCurrencyCodeQuery(currencyCodeQuery: String) = when {
currencyCodeQuery.contains(FORMAT_DELIMITER) -> {
val parts = currencyCodeQuery.split(FORMAT_DELIMITER)
parts[0] to parts[1]
}
else -> {
currencyCodeQuery to ""
}
}
private fun getAddress(wallet: Wallet, format: String) = when {
wallet.currency.isBitcoin() -> {
wallet.getTargetForScheme(
when {
format.equals(FORMAT_SEGWIT, true) -> AddressScheme.BTC_SEGWIT
else -> AddressScheme.BTC_LEGACY
}
).toString()
}
else -> wallet.target.toSanitizedString()
}
}
| app/src/main/java/com/platform/jsbridge/WalletJs.kt | 2719636516 |
/*
* Copyright 2020 Ren Binden
*
* 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.rpkit.professions.bukkit.listener
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.core.bukkit.util.addLore
import com.rpkit.itemquality.bukkit.itemquality.RPKItemQuality
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import com.rpkit.professions.bukkit.RPKProfessionsBukkit
import com.rpkit.professions.bukkit.profession.RPKCraftingAction
import com.rpkit.professions.bukkit.profession.RPKProfessionProvider
import org.bukkit.GameMode
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.block.BlockBreakEvent
import org.bukkit.inventory.ItemStack
import kotlin.math.roundToInt
import kotlin.random.Random
class BlockBreakListener(private val plugin: RPKProfessionsBukkit): Listener {
@EventHandler
fun onBlockBreak(event: BlockBreakEvent) {
val bukkitPlayer = event.player
if (bukkitPlayer.gameMode == GameMode.CREATIVE || bukkitPlayer.gameMode == GameMode.SPECTATOR) return
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val professionProvider = plugin.core.serviceManager.getServiceProvider(RPKProfessionProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer)
if (minecraftProfile == null) {
event.isDropItems = false
return
}
val character = characterProvider.getActiveCharacter(minecraftProfile)
if (character == null) {
event.isDropItems = false
return
}
val professions = professionProvider.getProfessions(character)
val professionLevels = professions
.associateWith { profession -> professionProvider.getProfessionLevel(character, profession) }
val itemsToDrop = mutableListOf<ItemStack>()
for (item in event.block.getDrops(event.player.inventory.itemInMainHand)) {
val material = item.type
val amount = professionLevels.entries
.map { (profession, level) -> profession.getAmountFor(RPKCraftingAction.MINE, material, level) }
.max() ?: plugin.config.getDouble("default.mining.$material.amount", 1.0)
val potentialQualities = professionLevels.entries
.mapNotNull { (profession, level) -> profession.getQualityFor(RPKCraftingAction.MINE, material, level) }
val quality = potentialQualities.maxBy(RPKItemQuality::durabilityModifier)
if (quality != null) {
item.addLore(quality.lore)
}
if (amount > 1) {
item.amount = amount.roundToInt()
itemsToDrop.add(item)
} else if (amount < 1) {
val random = Random.nextDouble()
if (random <= amount) {
item.amount = 1
itemsToDrop.add(item)
}
} else {
itemsToDrop.add(item)
}
professions.forEach { profession ->
val receivedExperience = plugin.config.getInt("professions.${profession.name}.experience.items.mining.$material", 0) * item.amount
if (receivedExperience > 0) {
professionProvider.setProfessionExperience(character, profession, professionProvider.getProfessionExperience(character, profession) + receivedExperience)
val level = professionProvider.getProfessionLevel(character, profession)
val experience = professionProvider.getProfessionExperience(character, profession)
event.player.sendMessage(plugin.messages["mine-experience", mapOf(
"profession" to profession.name,
"level" to level.toString(),
"received-experience" to receivedExperience.toString(),
"experience" to (experience - profession.getExperienceNeededForLevel(level)).toString(),
"next-level-experience" to (profession.getExperienceNeededForLevel(level + 1) - profession.getExperienceNeededForLevel(level)).toString(),
"total-experience" to experience.toString(),
"total-next-level-experience" to profession.getExperienceNeededForLevel(level + 1).toString(),
"material" to material.toString().toLowerCase().replace('_', ' ')
)])
}
}
}
event.isDropItems = false
for (item in itemsToDrop) {
event.block.world.dropItemNaturally(event.block.location, item)
}
}
} | bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/listener/BlockBreakListener.kt | 3021058241 |
/*
* Copyright 2020 Ren Binden
*
* 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.rpkit.players.bukkit.database.table
import com.rpkit.chat.bukkit.discord.RPKDiscordProvider
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.players.bukkit.RPKPlayersBukkit
import com.rpkit.players.bukkit.database.jooq.rpkit.Tables.RPKIT_DISCORD_PROFILE
import com.rpkit.players.bukkit.profile.*
import net.dv8tion.jda.api.entities.User
import org.ehcache.config.builders.CacheConfigurationBuilder
import org.ehcache.config.builders.ResourcePoolsBuilder
import org.jooq.impl.DSL.constraint
import org.jooq.impl.SQLDataType.BIGINT
import org.jooq.impl.SQLDataType.INTEGER
class RPKDiscordProfileTable(
database: Database,
private val plugin: RPKPlayersBukkit
): Table<RPKDiscordProfile>(database, RPKDiscordProfile::class) {
private val cache = if (plugin.config.getBoolean("caching.rpkit_discord_profile.id.enabled")) {
database.cacheManager.createCache("rpk-players-bukkit.rpkit_discord_profile.id",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKDiscordProfile::class.java,
ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_discord_profile.id.size"))))
} else {
null
}
override fun create() {
database.create
.createTableIfNotExists(RPKIT_DISCORD_PROFILE)
.column(RPKIT_DISCORD_PROFILE.ID, INTEGER.identity(true))
.column(RPKIT_DISCORD_PROFILE.PROFILE_ID, INTEGER)
.column(RPKIT_DISCORD_PROFILE.DISCORD_ID, BIGINT)
.constraints(
constraint("pk_rpkit_discord_profile").primaryKey(RPKIT_DISCORD_PROFILE.ID)
)
.execute()
}
override fun applyMigrations() {
if (database.getTableVersion(this) == null) {
database.setTableVersion(this, "1.8.0")
}
}
override fun insert(entity: RPKDiscordProfile): Int {
val profile = entity.profile
database.create
.insertInto(
RPKIT_DISCORD_PROFILE,
RPKIT_DISCORD_PROFILE.PROFILE_ID,
RPKIT_DISCORD_PROFILE.DISCORD_ID
)
.values(
if (profile is RPKProfile) {
profile.id
} else {
null
},
entity.discordId
)
.execute()
val id = database.create.lastID().toInt()
entity.id = id
cache?.put(id, entity)
return id
}
override fun update(entity: RPKDiscordProfile) {
val profile = entity.profile
database.create
.update(RPKIT_DISCORD_PROFILE)
.set(
RPKIT_DISCORD_PROFILE.PROFILE_ID,
if (profile is RPKProfile) {
profile.id
} else {
null
}
)
.set(RPKIT_DISCORD_PROFILE.DISCORD_ID, entity.discordId)
.where(RPKIT_DISCORD_PROFILE.ID.eq(entity.id))
.execute()
cache?.put(entity.id, entity)
}
override fun get(id: Int): RPKDiscordProfile? {
if (cache?.containsKey(id) == true) {
return cache[id]
}
val result = database.create
.select(
RPKIT_DISCORD_PROFILE.PROFILE_ID,
RPKIT_DISCORD_PROFILE.DISCORD_ID
)
.from(RPKIT_DISCORD_PROFILE)
.where(RPKIT_DISCORD_PROFILE.ID.eq(id))
.fetchOne() ?: return null
val profileId = result[RPKIT_DISCORD_PROFILE.PROFILE_ID]
val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class)
val discordProvider = plugin.core.serviceManager.getServiceProvider(RPKDiscordProvider::class)
val profile = if (profileId != null) {
profileProvider.getProfile(profileId)
} else {
null
} ?: RPKThinProfileImpl(discordProvider.getUser(result[RPKIT_DISCORD_PROFILE.DISCORD_ID])?.name ?: "Unknown Discord user")
val discordProfile = RPKDiscordProfileImpl(
id,
profile,
result[RPKIT_DISCORD_PROFILE.DISCORD_ID]
)
cache?.put(id, discordProfile)
return discordProfile
}
fun get(user: User): RPKDiscordProfile? {
val result = database.create
.select(RPKIT_DISCORD_PROFILE.ID)
.from(RPKIT_DISCORD_PROFILE)
.where(RPKIT_DISCORD_PROFILE.DISCORD_ID.eq(user.idLong))
.fetchOne() ?: return null
return get(result[RPKIT_DISCORD_PROFILE.ID])
}
fun get(profile: RPKProfile): List<RPKDiscordProfile> {
val results = database.create
.select(RPKIT_DISCORD_PROFILE.PROFILE_ID)
.from(RPKIT_DISCORD_PROFILE)
.where(RPKIT_DISCORD_PROFILE.PROFILE_ID.eq(profile.id))
.fetch()
return results.mapNotNull { result ->
get(result[RPKIT_DISCORD_PROFILE.ID])
}
}
override fun delete(entity: RPKDiscordProfile) {
database.create
.deleteFrom(RPKIT_DISCORD_PROFILE)
.where(RPKIT_DISCORD_PROFILE.ID.eq(entity.id))
.execute()
cache?.remove(entity.id)
}
} | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/database/table/RPKDiscordProfileTable.kt | 2948763413 |
package cmrdt
/**
* Created by jackqack on 03/06/17.
*/
abstract class CmRDT<V, O : Operation, T : CmRDT<V, O, T>>(
/**
* After any changes in local CmRDT replica each operation
* must be transmitted to all replicas. This listener
* is called after local changes with an operation which should be send.
* Operation must be commutative.
*/
protected var onDownstream: ((O) -> Unit) // do nothing approach for function type
) {
fun setDownstream(onDownstream: (O) -> Unit) {
this.onDownstream = onDownstream
}
/**
* Upgrade CmRDT replica by given operation received from
* another replica.
* Operation must be commutative.
*/
abstract fun upgrade(op: O)
/**
* Returns the immutable value of this CmRDT.
*/
abstract fun value(): V
/**
* Create a copy of this CmRDT.
*/
abstract fun copy(): T
}
| src/main/kotlin/crdt/cmrdt/CmRDT.kt | 731878289 |
package com.orgzly.android.usecase
import com.orgzly.android.data.DataRepository
import com.orgzly.android.db.entity.SavedSearch
class SavedSearchUpdate(val savedSearch: SavedSearch) : UseCase() {
override fun run(dataRepository: DataRepository): UseCaseResult {
dataRepository.updateSavedSearch(savedSearch)
return UseCaseResult(
modifiesListWidget = true
)
}
} | app/src/main/java/com/orgzly/android/usecase/SavedSearchUpdate.kt | 3723736373 |
package com.orgzly.android.espresso
import android.widget.TextView
import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import com.orgzly.R
import com.orgzly.android.OrgzlyTest
import com.orgzly.android.espresso.util.EspressoUtils.*
import com.orgzly.android.ui.main.MainActivity
import org.hamcrest.CoreMatchers.allOf
import org.hamcrest.CoreMatchers.instanceOf
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
class InternalLinksTest : OrgzlyTest() {
@Before
@Throws(Exception::class)
override fun setUp() {
super.setUp()
testUtils.setupBook(
"book-a",
"""
:PROPERTIES:
:ID: 019ae998-1439-4a28-988a-291ee8428245
:END:
* Note [a-1]
[[id:bdce923b-C3CD-41ED-B58E-8BDF8BABA54F]]
* Note [a-2]
[[#Different case custom id]]
* Note [a-3]
[[#Link to note in a different book]]
* Note [a-4]
file:book-b.org
* Note [a-5]
file:./book-b.org
* Note [a-6]
[[id:note-with-this-id-does-not-exist]]
* Note [a-7]
[[id:dd791937-3fb6-4018-8d5d-b278e0e52c80][Link to book-b by id]]
""".trimIndent()
)
testUtils.setupBook(
"book-b",
"""
:PROPERTIES:
dd791937-3fb6-4018-8d5d-b278e0e52c80
:END:
* Note [b-1]
:PROPERTIES:
:CUSTOM_ID: DIFFERENT case CUSTOM id
:END:
* Note [b-2]
:PROPERTIES:
:ID: BDCE923B-C3CD-41ED-B58E-8BDF8BABA54F
:END:
* Note [b-3]
:PROPERTIES:
:CUSTOM_ID: Link to note in a different book
:END:
""".trimIndent()
)
ActivityScenario.launch(MainActivity::class.java)
onBook(0).perform(click())
}
@Test
fun testDifferentCaseUuidInternalLink() {
onNoteInBook(1, R.id.item_head_content_view)
.perform(clickClickableSpan("id:bdce923b-C3CD-41ED-B58E-8BDF8BABA54F"))
onView(withId(R.id.title_view)).check(matches(withText("Note [b-2]")))
}
@Test
fun testDifferentCaseCustomIdInternalLink() {
onNoteInBook(2, R.id.item_head_content_view)
.perform(clickClickableSpan("#Different case custom id"))
onView(withId(R.id.title_view)).check(matches(withText("Note [b-1]")))
}
@Test
fun testCustomIdLink() {
onNoteInBook(3, R.id.item_head_content_view)
.perform(clickClickableSpan("#Link to note in a different book"))
onView(withId(R.id.title_view)).check(matches(withText("Note [b-3]")))
}
@Test
fun testBookLink() {
onNoteInBook(4, R.id.item_head_content_view)
.perform(clickClickableSpan("file:book-b.org"))
onView(withId(R.id.fragment_book_view_flipper)).check(matches(isDisplayed()))
onNoteInBook(1, R.id.item_head_title_view).check(matches(withText("Note [b-1]")))
}
@Test
fun testBookRelativeLink() {
onNoteInBook(5, R.id.item_head_content_view)
.perform(clickClickableSpan("file:./book-b.org"))
onView(withId(R.id.fragment_book_view_flipper)).check(matches(isDisplayed()))
onNoteInBook(1, R.id.item_head_title_view).check(matches(withText("Note [b-1]")))
}
@Test
fun testNonExistentId() {
onNoteInBook(6, R.id.item_head_content_view)
.perform(clickClickableSpan("id:note-with-this-id-does-not-exist"))
onSnackbar()
.check(matches(withText("Note with “ID” property set to “note-with-this-id-does-not-exist” not found")))
}
@Test
@Ignore("Parsing PROPERTIES drawer from book preface is not supported yet")
fun testLinkToBookById() {
onNoteInBook(7, R.id.item_head_content_view)
.perform(clickClickableSpan("Link to book-b by id"))
// onSnackbar()
// .check(matches(withText("Note with “ID” property set to “dd791937-3fb6-4018-8d5d-b278e0e52c80” not found")))
// In book
onView(withId(R.id.fragment_book_view_flipper)).check(matches(isDisplayed()))
// In book-b
onView(allOf(instanceOf(TextView::class.java), withParent(withId(R.id.top_toolbar))))
.check(matches(withText("book-b")))
}
}
| app/src/androidTest/java/com/orgzly/android/espresso/InternalLinksTest.kt | 3439634853 |
package com.simplemobiletools.gallery.pro.dialogs
import android.view.View
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.dialogs.RadioGroupDialog
import com.simplemobiletools.commons.extensions.hideKeyboard
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.commons.extensions.value
import com.simplemobiletools.commons.models.RadioItem
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.helpers.SLIDESHOW_ANIMATION_FADE
import com.simplemobiletools.gallery.pro.helpers.SLIDESHOW_ANIMATION_NONE
import com.simplemobiletools.gallery.pro.helpers.SLIDESHOW_ANIMATION_SLIDE
import com.simplemobiletools.gallery.pro.helpers.SLIDESHOW_DEFAULT_INTERVAL
import kotlinx.android.synthetic.main.dialog_slideshow.view.*
class SlideshowDialog(val activity: BaseSimpleActivity, val callback: () -> Unit) {
val view: View
init {
view = activity.layoutInflater.inflate(R.layout.dialog_slideshow, null).apply {
interval_value.setOnClickListener {
val text = interval_value.text
if (text.isNotEmpty()) {
text.replace(0, 1, text.subSequence(0, 1), 0, 1)
interval_value.selectAll()
}
}
interval_value.setOnFocusChangeListener { v, hasFocus ->
if (!hasFocus)
activity.hideKeyboard(v)
}
animation_holder.setOnClickListener {
val items = arrayListOf(
RadioItem(SLIDESHOW_ANIMATION_NONE, activity.getString(R.string.no_animation)),
RadioItem(SLIDESHOW_ANIMATION_SLIDE, activity.getString(R.string.slide)),
RadioItem(SLIDESHOW_ANIMATION_FADE, activity.getString(R.string.fade)))
RadioGroupDialog(activity, items, activity.config.slideshowAnimation) {
activity.config.slideshowAnimation = it as Int
animation_value.text = getAnimationText()
}
}
include_videos_holder.setOnClickListener {
interval_value.clearFocus()
include_videos.toggle()
}
include_gifs_holder.setOnClickListener {
interval_value.clearFocus()
include_gifs.toggle()
}
random_order_holder.setOnClickListener {
interval_value.clearFocus()
random_order.toggle()
}
move_backwards_holder.setOnClickListener {
interval_value.clearFocus()
move_backwards.toggle()
}
loop_slideshow_holder.setOnClickListener {
interval_value.clearFocus()
loop_slideshow.toggle()
}
}
setupValues()
AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.create().apply {
activity.setupDialogStuff(view, this) {
hideKeyboard()
getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
storeValues()
callback()
dismiss()
}
}
}
}
private fun setupValues() {
val config = activity.config
view.apply {
interval_value.setText(config.slideshowInterval.toString())
animation_value.text = getAnimationText()
include_videos.isChecked = config.slideshowIncludeVideos
include_gifs.isChecked = config.slideshowIncludeGIFs
random_order.isChecked = config.slideshowRandomOrder
move_backwards.isChecked = config.slideshowMoveBackwards
loop_slideshow.isChecked = config.loopSlideshow
}
}
private fun storeValues() {
var interval = view.interval_value.text.toString()
if (interval.trim('0').isEmpty())
interval = SLIDESHOW_DEFAULT_INTERVAL.toString()
activity.config.apply {
slideshowAnimation = getAnimationValue(view.animation_value.value)
slideshowInterval = interval.toInt()
slideshowIncludeVideos = view.include_videos.isChecked
slideshowIncludeGIFs = view.include_gifs.isChecked
slideshowRandomOrder = view.random_order.isChecked
slideshowMoveBackwards = view.move_backwards.isChecked
loopSlideshow = view.loop_slideshow.isChecked
}
}
private fun getAnimationText(): String {
return when (activity.config.slideshowAnimation) {
SLIDESHOW_ANIMATION_SLIDE -> activity.getString(R.string.slide)
SLIDESHOW_ANIMATION_FADE -> activity.getString(R.string.fade)
else -> activity.getString(R.string.no_animation)
}
}
private fun getAnimationValue(text: String): Int {
return when (text) {
activity.getString(R.string.slide) -> SLIDESHOW_ANIMATION_SLIDE
activity.getString(R.string.fade) -> SLIDESHOW_ANIMATION_FADE
else -> SLIDESHOW_ANIMATION_NONE
}
}
}
| app/src/main/kotlin/com/simplemobiletools/gallery/pro/dialogs/SlideshowDialog.kt | 3649590292 |
package net.ketc.numeri.domain.model
import net.ketc.numeri.domain.model.cache.Cacheable
import net.ketc.numeri.domain.service.TwitterClient
interface Tweet : Cacheable<Long> {
val user: TwitterUser
val createdAt: String
val text: String
val quotedTweet: Tweet?
val retweetedTweet: Tweet?
val source: String
val favoriteCount: Int
val retweetCount: Int
val hashtags: List<String>
val urlEntities: List<UrlEntity>
val mediaEntities: List<MediaEntity>
val userMentionEntities: List<UserMentionEntity>
val inReplyToStatusId: Long
}
infix fun TwitterClient.isMyTweet(tweet: Tweet) = tweet.user.id == id
infix fun Tweet.isMention(client: TwitterClient) = userMentionEntities.any { it.id == client.id } && retweetedTweet == null
| app/src/main/kotlin/net/ketc/numeri/domain/model/Tweet.kt | 3638020431 |
package com.hisham.jsonparsingdemo.source
import com.google.gson.Gson
import com.hisham.jsonparsingdemo.model.Movie
import com.hisham.jsonparsingdemo.model.MovieObject
import java.io.BufferedInputStream
import java.lang.Exception
import java.net.URL
import org.json.JSONObject
class ManualParsing : MoviesApi {
override suspend fun getMovies(): MovieObject {
try {
val url = URL("https://jsonparsingdemo-cec5b.firebaseapp.com/json/moviesDemoItem.json")
val connection = url.openConnection()
connection.connect()
val inputStream = BufferedInputStream(url.openStream())
val bufferedReader = inputStream.bufferedReader()
val stringBuffer = StringBuffer()
for (line in bufferedReader.readLines()) {
stringBuffer.append(line)
}
bufferedReader.close()
// JSON parsing
val json = stringBuffer.toString()
return Gson().fromJson(json, MovieObject::class.java)
// val topLevelObject = JSONObject(json)
// val moviesArray = topLevelObject.getJSONArray("movies")
// val movieObject = moviesArray.getJSONObject(0)
// val movieName = movieObject.getString("movie")
// val movieYear = movieObject.getInt("year")
// return MovieObject(listOf(Movie(movieName.plus(" From manual parsing"), movieYear)))
} catch (e: Exception) {
return MovieObject(emptyList())
}
}
override suspend fun getMovie(): Movie {
try {
val url = URL("https://jsonparsingdemo-cec5b.firebaseapp.com/json/movie.json")
val connection = url.openConnection()
connection.connect()
val inputStream = BufferedInputStream(url.openStream())
val bufferedReader = inputStream.bufferedReader()
val stringBuffer = StringBuffer()
for (line in bufferedReader.readLines()) {
stringBuffer.append(line)
}
bufferedReader.close()
// JSON parsing
val json = stringBuffer.toString()
return Gson().fromJson(json, Movie::class.java)
// val topLevelObject = JSONObject(json)
// val moviesArray = topLevelObject.getJSONArray("movies")
// val movieObject = moviesArray.getJSONObject(0)
// val movieName = movieObject.getString("movie")
// val movieYear = movieObject.getInt("year")
// return MovieObject(listOf(Movie(movieName.plus(" From manual parsing"), movieYear)))
} catch (e: Exception) {
return Movie("", -1, "")
}
}
} | app/src/main/java/com/hisham/jsonparsingdemo/source/ManualParsing.kt | 1940976295 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.tests.community
import com.intellij.testGuiFramework.framework.GuiTestSuite
import com.intellij.testGuiFramework.framework.RunWithIde
import com.intellij.testGuiFramework.launcher.ide.IdeType
import org.junit.runner.RunWith
import org.junit.runners.Suite
@RunWith(GuiTestSuite::class)
@RunWithIde(IdeType.IDEA_COMMUNITY)
@Suite.SuiteClasses(CommandLineProjectTest::class)
class CommunityTestSuite | platform/testGuiFramework/testSrc/com/intellij/testGuiFramework/tests/community/CommunityTestSuite.kt | 3014993136 |
package com.myls.odes.request
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
/**
* Created by myls on 12/2/17.
*/
object QueryUser
{
class Request
: ArgumentsHolder, IRequest
{
constructor(username: String): super() {
with(bundle) {
putString("stuid", username)
}
}
override val url: String
get() = "https://api.mysspku.com/index.php/V1/MobileCourse/getDetail"
override val query: Bundle
get() = bundle
override val method: String
get() = "GET"
override val response: Class<*>
get() = Response::class.java
private constructor(parcel: Parcel): super(parcel)
companion object CREATOR : Parcelable.Creator<Request> {
override fun createFromParcel(parcel: Parcel) = Request(parcel)
override fun newArray(size: Int) = arrayOfNulls<Request>(size)
}
}
data class Response(val errcode: Int, val data: Data) {
data class Data
(
val errmsg: String = "",
var studentid: String = "",
var name: String = "",
var gender: String = "",
var grade: String = "",
var vcode: String = "",
var room: String = "",
var building: String = "",
var location: String = ""
)
}
}
| 2017.AndroidApplicationDevelopment/ODES/app/src/main/java/com/myls/odes/request/QueryUser.kt | 2531610594 |
package org.bvic23.intellij.plugin.storybook.models
import com.fasterxml.jackson.module.kotlin.readValue
import org.bvic23.intellij.plugin.storybook.JacksonMapper
import org.bvic23.intellij.plugin.storybook.firstLetters
import org.bvic23.intellij.plugin.storybook.normalized
import org.bvic23.intellij.plugin.storybook.similar
data class Story(val kind: String, val story: String) {
private val normalizedSearchString = (kind + " " + story).normalized
private val firstLetters = (kind + " " + story).firstLetters
fun toJSON() = JacksonMapper.mapper.writeValueAsString(this)
fun toMessage() = StorySelectionMessage("setCurrentStory", listOf(this)).toJSON()
fun similarTo(target: String) = normalizedSearchString.similar(target, 10) || firstLetters.similar(target, 3)
companion object {
fun fromJSON(string: String?) = if (string != null) JacksonMapper.mapper.readValue<Story>(string) else null
}
} | src/org/bvic23/intellij/plugin/storybook/models/Story.kt | 473284222 |
/*
* Copyright 2016 Dionysis Lorentzos
*
* 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.lorentzos.slicknode.internal
import com.google.android.gms.common.api.Result
import com.lorentzos.slicknode.WearOperationException
import rx.SingleSubscriber
/**
* A lambda which emits a single item and then completes.
*/
internal class SingleResultLambda<in T : Result>(private val subscriber: SingleSubscriber<in T>) : (T) -> Unit {
override fun invoke(child: T) {
if (!child.status.isSuccess) {
subscriber.onError(WearOperationException(child))
}
subscriber.onSuccess(child)
}
} | slicknode-kotlin/src/main/kotlin/com/lorentzos/slicknode/internal/SingleResultLambda.kt | 4086868419 |
/*
* Copyright 2013 Maurício Linhares
*
* Maurício Linhares licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.github.mauricio.async.db.exceptions
/**
*
* Raised when the user gives more or less parameters than the query takes. Each parameter is a ?
* (question mark) in the query string. The count of ? should be the same as the count of items in the provided
* sequence of parameters.
*
* @param expected the expected count of parameters
* @param given the collection given
*/
class InsufficientParametersException( expected : Int, given : List<Any?> )
: DatabaseException(
"The query contains %s parameters but you gave it %s (%s)".format(expected, given.size, given.joinToString(",")
)
)
| db-async-common/src/main/kotlin/com/github/mauricio/async/db/exceptions/InsufficientParametersException.kt | 3344493005 |
package com.github.davinkevin.podcastserver.config
import com.fasterxml.jackson.databind.ObjectMapper
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.ImportAutoConfiguration
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
import org.springframework.context.annotation.Import
import org.springframework.test.context.junit.jupiter.SpringExtension
import java.time.ZoneId
import java.time.ZonedDateTime
/**
* Created by kevin on 15/06/2016 for Podcast Server
*/
@ExtendWith(SpringExtension::class)
@Import(JacksonConfig::class)
@ImportAutoConfiguration(JacksonAutoConfiguration::class)
class JacksonConfigTest (@Autowired val mapper: ObjectMapper) {
@Test
fun `should serialize date as iso 8601`() {
/* Given */
val date = ZonedDateTime.of(2016, 6, 15, 2, 43, 15, 826, ZoneId.of("Europe/Paris"))
/* When */
val jsonDate = mapper.writeValueAsString(date)
/* Then */
assertThat(jsonDate).isEqualTo(""""2016-06-15T02:43:15.000000826+02:00"""")
}
}
| backend/src/test/kotlin/com/github/davinkevin/podcastserver/config/JacksonConfigTest.kt | 2878486518 |
package com.battlelancer.seriesguide.extensions
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.api.Action
import com.battlelancer.seriesguide.api.Episode
import com.battlelancer.seriesguide.api.Movie
import com.battlelancer.seriesguide.api.SeriesGuideExtension
import com.battlelancer.seriesguide.util.ServiceUtils
/**
* Searches the Google Play TV and movies section for an episode or movie.
*/
class GooglePlayExtension : SeriesGuideExtension("GooglePlayExtension") {
override fun onRequest(episodeIdentifier: Int, episode: Episode) {
// we need at least a show or an episode title
if (episode.showTitle.isNullOrEmpty() || episode.title.isNullOrEmpty()) {
return
}
publishGooglePlayAction(
episodeIdentifier,
String.format("%s %s", episode.showTitle, episode.title)
)
}
override fun onRequest(movieIdentifier: Int, movie: Movie) {
// we need at least a movie title
if (movie.title.isNullOrEmpty()) {
return
}
publishGooglePlayAction(movieIdentifier, movie.title)
}
private fun publishGooglePlayAction(identifier: Int, searchTerm: String) {
publishAction(
Action.Builder(getString(R.string.extension_google_play), identifier)
.viewIntent(
ServiceUtils.buildGooglePlayIntent(searchTerm, applicationContext)
)
.build()
)
}
} | app/src/main/java/com/battlelancer/seriesguide/extensions/GooglePlayExtension.kt | 2805410728 |
package org.jetbrains.exposed.sql
import java.lang.UnsupportedOperationException
interface SizedIterable<out T>: Iterable<T> {
fun limit(n: Int, offset: Int = 0): SizedIterable<T>
fun count(): Int
fun empty(): Boolean
fun forUpdate(): SizedIterable<T> = this
fun notForUpdate(): SizedIterable<T> = this
}
fun <T> emptySized() : SizedIterable<T> = EmptySizedIterable()
class EmptySizedIterable<out T> : SizedIterable<T>, Iterator<T> {
override fun count(): Int = 0
override fun limit(n: Int, offset: Int): SizedIterable<T> = this
override fun empty(): Boolean = true
operator override fun iterator(): Iterator<T> = this
operator override fun next(): T {
throw UnsupportedOperationException()
}
override fun hasNext(): Boolean = false
}
class SizedCollection<out T>(val delegate: Collection<T>): SizedIterable<T> {
override fun limit(n: Int, offset: Int): SizedIterable<T> = SizedCollection(delegate.drop(offset).take(n))
operator override fun iterator() = delegate.iterator()
override fun count() = delegate.size
override fun empty() = delegate.isEmpty()
}
class LazySizedCollection<out T>(val delegate: SizedIterable<T>): SizedIterable<T> {
private var _wrapper: List<T>? = null
private var _size: Int? = null
private var _empty: Boolean? = null
val wrapper: List<T> get() {
if (_wrapper == null) {
_wrapper = delegate.toList()
}
return _wrapper!!
}
override fun limit(n: Int, offset: Int): SizedIterable<T> = delegate.limit(n, offset)
operator override fun iterator() = wrapper.iterator()
override fun count() = _wrapper?.size ?: _count()
override fun empty() = _wrapper?.isEmpty() ?: _empty()
override fun forUpdate(): SizedIterable<T> = delegate.forUpdate()
override fun notForUpdate(): SizedIterable<T> = delegate.notForUpdate()
private fun _count(): Int {
if (_size == null) {
_size = delegate.count()
_empty = (_size == 0)
}
return _size!!
}
private fun _empty(): Boolean {
if (_empty == null) {
_empty = delegate.empty()
if (_empty == true) _size = 0
}
return _empty!!
}
}
infix fun <T, R> SizedIterable<T>.mapLazy(f:(T)->R):SizedIterable<R> {
val source = this
return object : SizedIterable<R> {
override fun limit(n: Int, offset: Int): SizedIterable<R> = source.limit(n, offset).mapLazy(f)
override fun forUpdate(): SizedIterable<R> = source.forUpdate().mapLazy(f)
override fun notForUpdate(): SizedIterable<R> = source.notForUpdate().mapLazy(f)
override fun count(): Int = source.count()
override fun empty(): Boolean = source.empty()
operator override fun iterator(): Iterator<R> {
val sourceIterator = source.iterator()
return object: Iterator<R> {
operator override fun next(): R = f(sourceIterator.next())
override fun hasNext(): Boolean = sourceIterator.hasNext()
}
}
}
}
| extra/exposed/src/main/kotlin/org/jetbrains/exposed/sql/IterableEx.kt | 2621154840 |
package com.example.subtitlecollapsingtoolbarlayout
import android.content.SharedPreferences
import android.content.SharedPreferences.OnSharedPreferenceChangeListener
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.annotation.ColorInt
import androidx.annotation.Px
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.view.GravityCompat
import com.google.android.material.appbar.SubtitleCollapsingToolbarLayout
import com.hendraanggrian.auto.prefs.BindPreference
import com.hendraanggrian.auto.prefs.PreferencesSaver
import com.hendraanggrian.auto.prefs.Prefs
import com.hendraanggrian.auto.prefs.android.AndroidPreferences
import com.hendraanggrian.auto.prefs.android.preferences
import com.jakewharton.processphoenix.ProcessPhoenix
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(), OnSharedPreferenceChangeListener {
@JvmField @BindPreference("theme") var theme2 = AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
@JvmField @BindPreference var showSubtitle = false
@JvmField @BindPreference var statusBarScrim = Color.TRANSPARENT
@JvmField @BindPreference var contentScrim = Color.TRANSPARENT
@JvmField @BindPreference var marginLeft = 0
@JvmField @BindPreference var marginTop = 0
@JvmField @BindPreference var marginRight = 0
@JvmField @BindPreference var marginBottom = 0
@JvmField @BindPreference var collapsedTitleColor = Color.TRANSPARENT
@JvmField @BindPreference var collapsedSubtitleColor = Color.TRANSPARENT
@JvmField @BindPreference @ColorInt var expandedTitleColor = Color.TRANSPARENT
@JvmField @BindPreference @ColorInt var expandedSubtitleColor = Color.TRANSPARENT
private lateinit var prefs: AndroidPreferences
private lateinit var saver: PreferencesSaver
@Px private var marginScale = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
supportFragmentManager
.beginTransaction()
.replace(R.id.container, MainFragment())
.commitNow()
prefs = preferences
marginScale = resources.getDimensionPixelSize(R.dimen.margin_scale)
onSharedPreferenceChanged(prefs, "")
}
override fun onResume() {
super.onResume()
prefs.registerOnSharedPreferenceChangeListener(this)
}
override fun onPause() {
super.onPause()
prefs.unregisterOnSharedPreferenceChangeListener(this)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.activity_main, menu)
menu.findItem(
when (theme2) {
AppCompatDelegate.MODE_NIGHT_NO -> R.id.lightThemeItem
AppCompatDelegate.MODE_NIGHT_YES -> R.id.darkThemeItem
else -> R.id.defaultThemeItem
}
).isChecked = true
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.defaultThemeItem, R.id.lightThemeItem, R.id.darkThemeItem -> {
theme2 = when (item.itemId) {
R.id.lightThemeItem -> AppCompatDelegate.MODE_NIGHT_NO
R.id.darkThemeItem -> AppCompatDelegate.MODE_NIGHT_YES
else -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
}
saver.save()
AppCompatDelegate.setDefaultNightMode(theme2)
}
R.id.resetItem -> {
prefs.edit { clear() }
ProcessPhoenix.triggerRebirth(this)
}
}
return super.onOptionsItemSelected(item)
}
override fun onSharedPreferenceChanged(p: SharedPreferences, key: String) {
saver = Prefs.bind(prefs, this)
toolbarLayout.subtitle = if (showSubtitle) SubtitleCollapsingToolbarLayout::class.java.simpleName else null
toolbarLayout.statusBarScrim = if (statusBarScrim.isConfigured()) ColorDrawable(statusBarScrim) else null
toolbarLayout.contentScrim = if (contentScrim.isConfigured()) ColorDrawable(contentScrim) else null
toolbarLayout.collapsedTitleGravity =
prefs.getGravity("collapsedGravity", GravityCompat.START or Gravity.CENTER_VERTICAL)
toolbarLayout.expandedTitleGravity =
prefs.getGravity("expandedGravity", GravityCompat.START or Gravity.BOTTOM)
if (marginLeft != 0) toolbarLayout.expandedTitleMarginStart = marginLeft * marginScale
if (marginTop != 0) toolbarLayout.expandedTitleMarginTop = marginTop * marginScale
if (marginRight != 0) toolbarLayout.expandedTitleMarginEnd = marginRight * marginScale
if (marginBottom != 0) toolbarLayout.expandedTitleMarginBottom = marginBottom * marginScale
collapsedTitleColor.ifConfigured { toolbarLayout.setCollapsedTitleTextColor(it) }
collapsedSubtitleColor.ifConfigured { toolbarLayout.setCollapsedSubtitleTextColor(it) }
expandedTitleColor.ifConfigured { toolbarLayout.setExpandedTitleTextColor(it) }
expandedSubtitleColor.ifConfigured { toolbarLayout.setExpandedSubtitleTextColor(it) }
}
fun expand(view: View) = appbar.setExpanded(true)
private companion object {
fun SharedPreferences.getGravity(key: String, def: Int): Int {
val iterator = getStringSet(key, emptySet())!!.iterator()
var gravity: Int? = null
while (iterator.hasNext()) {
val next = iterator.next().toInt()
gravity = when (gravity) {
null -> next
else -> gravity or next
}
}
return gravity ?: def
}
fun @receiver:ColorInt Int.isConfigured(): Boolean = this != Color.TRANSPARENT
fun @receiver:ColorInt Int.ifConfigured(action: (Int) -> Unit) {
if (isConfigured()) action(this)
}
}
} | sample/src/com/example/subtitlecollapsingtoolbarlayout/MainActivity.kt | 1511162723 |
/*
* Copyright 2013-2015 Eugene Petrenko
*
* 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.jonnyzzz.teamcity.plugins.node.common
class GulpBean {
val gulpConfigurationParameter: String = "gulp"
val runTypeName: String = "jonnyzzz.gulp"
val file: String = "jonnyzzz.gulp.file"
val targets: String = "jonnyzzz.gulp.tasks"
val commandLineParameterKey : String = "jonnyzzz.commandLine"
val gulpMode : String = "jonnyzzz.gulp.mode"
val gulpModeDefault : GulpExecutionMode = GulpExecutionMode.NPM
val gulpModes : List<GulpExecutionMode>
get() = arrayListOf(*GulpExecutionMode.values())
fun parseMode(text : String?) : GulpExecutionMode?
= gulpModes.firstOrNull { text == it.value } ?: gulpModeDefault
fun parseCommands(text: String?): Collection<String> {
if (text == null)
return listOf()
else
return text
.lines()
.map { it.trim() }
.filterNot { it.isEmpty() }
}
}
enum class GulpExecutionMode(val title : String,
val value : String) {
NPM("NPM package from project", "npm"),
GLOBAL("System-wide gulp", "global"),
}
| common/src/main/java/com/jonnyzzz/teamcity/plugins/node/common/GulpBean.kt | 3219930265 |
@file:Suppress(
names = "NOTHING_TO_INLINE"
)
package com.jakewharton.rxbinding2.widget
import android.view.MenuItem
import android.widget.Toolbar
import com.jakewharton.rxbinding2.internal.VoidToUnit
import io.reactivex.Observable
import io.reactivex.functions.Consumer
import kotlin.Int
import kotlin.Suppress
import kotlin.Unit
/**
* Create an observable which emits the clicked item in `view`'s menu.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
inline fun Toolbar.itemClicks(): Observable<MenuItem> = RxToolbar.itemClicks(this)
/**
* Create an observable which emits on `view` navigation click events. The emitted value is
* unspecified and should only be used as notification.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [Toolbar.setNavigationOnClickListener]
* to observe clicks. Only one observable can be used for a view at a time.
*/
inline fun Toolbar.navigationClicks(): Observable<Unit> = RxToolbar.navigationClicks(this).map(VoidToUnit)
/**
* An action which sets the title property of `view` with character sequences.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
inline fun Toolbar.title(): Consumer<in CharSequence?> = RxToolbar.title(this)
/**
* An action which sets the title property of `view` string resource IDs.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
inline fun Toolbar.titleRes(): Consumer<in Int> = RxToolbar.titleRes(this)
/**
* An action which sets the subtitle property of `view` with character sequences.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
inline fun Toolbar.subtitle(): Consumer<in CharSequence?> = RxToolbar.subtitle(this)
/**
* An action which sets the subtitle property of `view` string resource IDs.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
inline fun Toolbar.subtitleRes(): Consumer<in Int> = RxToolbar.subtitleRes(this)
| rxbinding-kotlin/src/main/kotlin/com/jakewharton/rxbinding2/widget/RxToolbar.kt | 2482999045 |
/*
* Copyright 2021 Ren Binden
* 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.rpkit.characters.bukkit.command.race
import com.rpkit.characters.bukkit.RPKCharactersBukkit
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
/**
* Race command.
* Parent for all race management commands.
*/
class RaceCommand(private val plugin: RPKCharactersBukkit) : CommandExecutor {
private val raceListCommand = RaceListCommand(plugin)
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean {
if (args.isNotEmpty()) {
val newArgs = args.drop(1).toTypedArray()
if (args[0].equals("list", ignoreCase = true)) {
return raceListCommand.onCommand(sender, command, label, newArgs)
} else {
sender.sendMessage(plugin.messages["race-usage"])
}
} else {
sender.sendMessage(plugin.messages["race-usage"])
}
return true
}
}
| bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/command/race/RaceCommand.kt | 1512512766 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package backcompat.ui.layout
import java.awt.Container
import javax.swing.ButtonGroup
import javax.swing.JLabel
// see com.intellij.uiDesigner.core.AbstractLayout.DEFAULT_HGAP and DEFAULT_VGAP
// https://docs.google.com/document/d/1DKnLkO-7_onA7_NCw669aeMH5ltNvw-QMiQHnXu8k_Y/edit
internal const val HORIZONTAL_GAP = 10
internal const val VERTICAL_GAP = 5
fun createLayoutBuilder() = LayoutBuilder(MigLayoutBuilder())
// cannot use the same approach as in case of Row because cannot access to `build` method in inlined `panel` method,
// in any case Kotlin compiler does the same thing —
// "When a protected member is accessed from an inline function, a public accessor method is created to provide an access to that protected member from the outside of the class where the function will be inlined to."
// (https://youtrack.jetbrains.com/issue/KT-12215)
interface LayoutBuilderImpl {
fun newRow(label: JLabel? = null, buttonGroup: ButtonGroup? = null, separated: Boolean = false, indented: Boolean = false): Row
fun build(container: Container, layoutConstraints: Array<out LCFlags>)
fun noteRow(text: String)
}
| src/main/kotlin/backcompat/ui/layout/layoutImpl.kt | 1791498333 |
/*
* Copyright 2019 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.clouddriver.event.exceptions
import com.netflix.spinnaker.kork.exceptions.SystemException
class DuplicateEventAggregateException(e: Exception) : SystemException(e), EventingException
| clouddriver-event/src/main/kotlin/com/netflix/spinnaker/clouddriver/event/exceptions/DuplicateEventAggregateException.kt | 2008537623 |
/*
* Copyright (C) 2019 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("KotlinPoetMetadata")
@file:Suppress("unused")
package com.squareup.kotlinpoet.metadata
import javax.lang.model.element.TypeElement
import kotlin.annotation.AnnotationTarget.CLASS
import kotlin.annotation.AnnotationTarget.FUNCTION
import kotlin.annotation.AnnotationTarget.PROPERTY
import kotlin.reflect.KClass
import kotlinx.metadata.KmClass
import kotlinx.metadata.jvm.KotlinClassHeader
import kotlinx.metadata.jvm.KotlinClassMetadata
/**
* Indicates that a given API is part of the experimental KotlinPoet metadata support. This exists
* because kotlinx-metadata is not a stable API, and will remain in place until it is.
*/
@RequiresOptIn
@Retention(AnnotationRetention.BINARY)
@Target(CLASS, FUNCTION, PROPERTY)
public annotation class KotlinPoetMetadataPreview
/** @return a new [KmClass] representation of the Kotlin metadata for [this] class. */
@KotlinPoetMetadataPreview
public fun KClass<*>.toKmClass(): KmClass = java.toKmClass()
/** @return a new [KmClass] representation of the Kotlin metadata for [this] class. */
@KotlinPoetMetadataPreview
public fun Class<*>.toKmClass(): KmClass = readMetadata(::getAnnotation).toKmClass()
/** @return a new [KmClass] representation of the Kotlin metadata for [this] type. */
@KotlinPoetMetadataPreview
public fun TypeElement.toKmClass(): KmClass = readMetadata(::getAnnotation).toKmClass()
@KotlinPoetMetadataPreview
public fun Metadata.toKmClass(): KmClass {
return toKotlinClassMetadata<KotlinClassMetadata.Class>()
.toKmClass()
}
@KotlinPoetMetadataPreview
public inline fun <reified T : KotlinClassMetadata> Metadata.toKotlinClassMetadata(): T {
val expectedType = T::class
val metadata = readKotlinClassMetadata()
return when (expectedType) {
KotlinClassMetadata.Class::class -> {
check(metadata is KotlinClassMetadata.Class)
metadata as T
}
KotlinClassMetadata.FileFacade::class -> {
check(metadata is KotlinClassMetadata.FileFacade)
metadata as T
}
KotlinClassMetadata.SyntheticClass::class ->
throw UnsupportedOperationException("SyntheticClass isn't supported yet!")
KotlinClassMetadata.MultiFileClassFacade::class ->
throw UnsupportedOperationException("MultiFileClassFacade isn't supported yet!")
KotlinClassMetadata.MultiFileClassPart::class ->
throw UnsupportedOperationException("MultiFileClassPart isn't supported yet!")
KotlinClassMetadata.Unknown::class ->
throw RuntimeException("Recorded unknown metadata type! $metadata")
else -> TODO("Unrecognized KotlinClassMetadata type: $expectedType")
}
}
/**
* Returns the [KotlinClassMetadata] this represents. In general you should only use this function
* when you don't know what the underlying [KotlinClassMetadata] subtype is, otherwise you should
* use one of the more direct functions like [toKmClass].
*/
@KotlinPoetMetadataPreview
public fun Metadata.readKotlinClassMetadata(): KotlinClassMetadata {
val metadata = KotlinClassMetadata.read(asClassHeader())
checkNotNull(metadata) {
"Could not parse metadata! Try bumping kotlinpoet and/or kotlinx-metadata version."
}
return metadata
}
private inline fun readMetadata(lookup: ((Class<Metadata>) -> Metadata?)): Metadata {
return checkNotNull(lookup.invoke(Metadata::class.java)) {
"No Metadata annotation found! Must be Kotlin code built with the standard library on the classpath."
}
}
private fun Metadata.asClassHeader(): KotlinClassHeader {
return KotlinClassHeader(
kind = kind,
metadataVersion = metadataVersion,
data1 = data1,
data2 = data2,
extraString = extraString,
packageName = packageName,
extraInt = extraInt,
)
}
| interop/kotlinx-metadata/src/main/kotlin/com/squareup/kotlinpoet/metadata/KotlinPoetMetadata.kt | 2913600805 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.options.ExternalizableScheme
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.TemporaryDirectory
import com.intellij.testFramework.runInEdtAndWait
import com.intellij.util.io.createDirectories
import com.intellij.util.io.directoryStreamIfExists
import com.intellij.util.io.readText
import com.intellij.util.io.write
import com.intellij.util.loadElement
import com.intellij.util.toByteArray
import com.intellij.util.xmlb.annotations.Tag
import gnu.trove.THashMap
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.io.File
import java.nio.file.Path
import java.util.function.Function
internal val FILE_SPEC = "REMOTE"
/**
* Functionality without stream provider covered, ICS has own test suite
*/
internal class SchemeManagerTest {
companion object {
@JvmField
@ClassRule val projectRule = ProjectRule()
}
private val tempDirManager = TemporaryDirectory()
@Rule fun getTemporaryFolder() = tempDirManager
private var localBaseDir: Path? = null
private var remoteBaseDir: Path? = null
private fun getTestDataPath() = PlatformTestUtil.getCommunityPath().replace(File.separatorChar, '/') + "/platform/platform-tests/testData/options"
@Test fun loadSchemes() {
doLoadSaveTest("options1", "1->first;2->second")
}
@Test fun loadSimpleSchemes() {
doLoadSaveTest("options", "1->1")
}
@Test fun deleteScheme() {
val manager = createAndLoad("options1")
manager.removeScheme("first")
manager.save()
checkSchemes("2->second")
}
@Test fun renameScheme() {
val manager = createAndLoad("options1")
val scheme = manager.findSchemeByName("first")
assertThat(scheme).isNotNull()
scheme!!.name = "renamed"
manager.save()
checkSchemes("2->second;renamed->renamed")
}
@Test fun testRenameScheme2() {
val manager = createAndLoad("options1")
val first = manager.findSchemeByName("first")
assertThat(first).isNotNull()
assert(first != null)
first!!.name = "2"
val second = manager.findSchemeByName("second")
assertThat(second).isNotNull()
assert(second != null)
second!!.name = "1"
manager.save()
checkSchemes("1->1;2->2")
}
@Test fun testDeleteRenamedScheme() {
val manager = createAndLoad("options1")
val firstScheme = manager.findSchemeByName("first")
assertThat(firstScheme).isNotNull()
assert(firstScheme != null)
firstScheme!!.name = "first_renamed"
manager.save()
checkSchemes(remoteBaseDir!!.resolve("REMOTE"), "first_renamed->first_renamed;2->second", true)
checkSchemes(localBaseDir!!, "", false)
firstScheme.name = "first_renamed2"
manager.removeScheme(firstScheme)
manager.save()
checkSchemes(remoteBaseDir!!.resolve("REMOTE"), "2->second", true)
checkSchemes(localBaseDir!!, "", false)
}
@Test fun testDeleteAndCreateSchemeWithTheSameName() {
val manager = createAndLoad("options1")
val firstScheme = manager.findSchemeByName("first")
assertThat(firstScheme).isNotNull()
manager.removeScheme(firstScheme!!)
manager.addScheme(TestScheme("first"))
manager.save()
checkSchemes("2->second;first->first")
}
@Test fun testGenerateUniqueSchemeName() {
val manager = createAndLoad("options1")
val scheme = TestScheme("first")
manager.addNewScheme(scheme, false)
assertThat("first2").isEqualTo(scheme.name)
}
fun TestScheme.save(file: Path) {
file.write(serialize().toByteArray())
}
@Test fun `different extensions`() {
val dir = tempDirManager.newPath()
val scheme = TestScheme("local", "true")
scheme.save(dir.resolve("1.icls"))
TestScheme("local", "false").save(dir.resolve("1.xml"))
class ATestSchemesProcessor : TestSchemesProcessor(), SchemeExtensionProvider {
override val schemeExtension = ".icls"
}
val schemesManager = SchemeManagerImpl(FILE_SPEC, ATestSchemesProcessor(), null, dir)
schemesManager.loadSchemes()
assertThat(schemesManager.allSchemes).containsOnly(scheme)
assertThat(dir.resolve("1.icls")).isRegularFile()
assertThat(dir.resolve("1.xml")).isRegularFile()
scheme.data = "newTrue"
schemesManager.save()
assertThat(dir.resolve("1.icls")).isRegularFile()
assertThat(dir.resolve("1.xml")).doesNotExist()
}
@Test fun setSchemes() {
val dir = tempDirManager.newPath()
val schemeManager = createSchemeManager(dir)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).isEmpty()
val scheme = TestScheme("s1")
schemeManager.setSchemes(listOf(scheme))
val schemes = schemeManager.allSchemes
assertThat(schemes).containsOnly(scheme)
assertThat(dir.resolve("s1.xml")).doesNotExist()
scheme.data = "newTrue"
schemeManager.save()
assertThat(dir.resolve("s1.xml")).isRegularFile()
schemeManager.setSchemes(emptyList())
schemeManager.save()
assertThat(dir).doesNotExist()
}
@Test fun `reload schemes`() {
val dir = tempDirManager.newPath()
val schemeManager = createSchemeManager(dir)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).isEmpty()
val scheme = TestScheme("s1", "oldData")
schemeManager.setSchemes(listOf(scheme))
assertThat(schemeManager.allSchemes).containsOnly(scheme)
schemeManager.save()
dir.resolve("s1.xml").write("""<scheme name="s1" data="newData" />""")
schemeManager.reload()
assertThat(schemeManager.allSchemes).containsOnly(TestScheme("s1", "newData"))
}
@Test fun `save only if scheme differs from bundled`() {
val dir = tempDirManager.newPath()
var schemeManager = createSchemeManager(dir)
val bundledPath = "/com/intellij/configurationStore/bundledSchemes/default"
schemeManager.loadBundledScheme(bundledPath, this)
val customScheme = TestScheme("default")
assertThat(schemeManager.allSchemes).containsOnly(customScheme)
schemeManager.save()
assertThat(dir).doesNotExist()
schemeManager.save()
schemeManager.setSchemes(listOf(customScheme))
assertThat(dir).doesNotExist()
assertThat(schemeManager.allSchemes).containsOnly(customScheme)
customScheme.data = "foo"
schemeManager.save()
assertThat(dir.resolve("default.xml")).isRegularFile()
schemeManager = createSchemeManager(dir)
schemeManager.loadBundledScheme(bundledPath, this)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).containsOnly(customScheme)
}
@Test fun `don't remove dir if no schemes but at least one non-hidden file exists`() {
val dir = tempDirManager.newPath()
val schemeManager = createSchemeManager(dir)
val scheme = TestScheme("s1")
schemeManager.setSchemes(listOf(scheme))
schemeManager.save()
val schemeFile = dir.resolve("s1.xml")
assertThat(schemeFile).isRegularFile()
schemeManager.setSchemes(emptyList())
dir.resolve("empty").write(byteArrayOf())
schemeManager.save()
assertThat(schemeFile).doesNotExist()
assertThat(dir).isDirectory()
}
@Test fun `remove empty directory only if some file was deleted`() {
val dir = tempDirManager.newPath()
val schemeManager = createSchemeManager(dir)
schemeManager.loadSchemes()
dir.createDirectories()
schemeManager.save()
assertThat(dir).isDirectory()
schemeManager.addScheme(TestScheme("test"))
schemeManager.save()
assertThat(dir).isDirectory()
schemeManager.setSchemes(emptyList())
schemeManager.save()
assertThat(dir).doesNotExist()
}
@Test fun rename() {
val dir = tempDirManager.newPath()
val schemeManager = createSchemeManager(dir)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).isEmpty()
val scheme = TestScheme("s1")
schemeManager.setSchemes(listOf(scheme))
val schemes = schemeManager.allSchemes
assertThat(schemes).containsOnly(scheme)
assertThat(dir.resolve("s1.xml")).doesNotExist()
scheme.data = "newTrue"
schemeManager.save()
assertThat(dir.resolve("s1.xml")).isRegularFile()
scheme.name = "s2"
schemeManager.save()
assertThat(dir.resolve("s1.xml")).doesNotExist()
assertThat(dir.resolve("s2.xml")).isRegularFile()
}
@Test fun `rename A to B and B to A`() {
val dir = tempDirManager.newPath()
val schemeManager = createSchemeManager(dir)
val a = TestScheme("a", "a")
val b = TestScheme("b", "b")
schemeManager.setSchemes(listOf(a, b))
schemeManager.save()
assertThat(dir.resolve("a.xml")).isRegularFile()
assertThat(dir.resolve("b.xml")).isRegularFile()
a.name = "b"
b.name = "a"
schemeManager.save()
assertThat(dir.resolve("a.xml").readText()).isEqualTo("""<scheme name="a" data="b" />""")
assertThat(dir.resolve("b.xml").readText()).isEqualTo("""<scheme name="b" data="a" />""")
}
@Test fun `VFS - rename A to B and B to A`() {
val dir = tempDirManager.newPath()
val schemeManager = SchemeManagerImpl(FILE_SPEC, TestSchemesProcessor(), null, dir, messageBus = ApplicationManager.getApplication().messageBus)
val a = TestScheme("a", "a")
val b = TestScheme("b", "b")
schemeManager.setSchemes(listOf(a, b))
runInEdtAndWait { schemeManager.save() }
assertThat(dir.resolve("a.xml")).isRegularFile()
assertThat(dir.resolve("b.xml")).isRegularFile()
a.name = "b"
b.name = "a"
runInEdtAndWait { schemeManager.save() }
assertThat(dir.resolve("a.xml").readText()).isEqualTo("""<scheme name="a" data="b" />""")
assertThat(dir.resolve("b.xml").readText()).isEqualTo("""<scheme name="b" data="a" />""")
}
@Test fun `path must not contains ROOT_CONFIG macro`() {
assertThatThrownBy({ SchemeManagerFactory.getInstance().create("\$ROOT_CONFIG$/foo", TestSchemesProcessor()) }).hasMessage("Path must not contains ROOT_CONFIG macro, corrected: foo")
}
@Test fun `path must be system-independent`() {
assertThatThrownBy({ SchemeManagerFactory.getInstance().create("foo\\bar", TestSchemesProcessor())}).hasMessage("Path must be system-independent, use forward slash instead of backslash")
}
private fun createSchemeManager(dir: Path) = SchemeManagerImpl(FILE_SPEC, TestSchemesProcessor(), null, dir)
private fun createAndLoad(testData: String): SchemeManagerImpl<TestScheme, TestScheme> {
createTempFiles(testData)
return createAndLoad()
}
private fun doLoadSaveTest(testData: String, expected: String, localExpected: String = "") {
val schemesManager = createAndLoad(testData)
schemesManager.save()
checkSchemes(remoteBaseDir!!.resolve("REMOTE"), expected, true)
checkSchemes(localBaseDir!!, localExpected, false)
}
private fun checkSchemes(expected: String) {
checkSchemes(remoteBaseDir!!.resolve("REMOTE"), expected, true)
checkSchemes(localBaseDir!!, "", false)
}
private fun createAndLoad(): SchemeManagerImpl<TestScheme, TestScheme> {
val schemesManager = SchemeManagerImpl(FILE_SPEC, TestSchemesProcessor(), MockStreamProvider(remoteBaseDir!!), localBaseDir!!)
schemesManager.loadSchemes()
return schemesManager
}
private fun createTempFiles(testData: String) {
val temp = tempDirManager.newPath()
localBaseDir = temp.resolve("__local")
remoteBaseDir = temp
FileUtil.copyDir(File("${getTestDataPath()}/$testData"), temp.resolve("REMOTE").toFile())
}
}
private fun checkSchemes(baseDir: Path, expected: String, ignoreDeleted: Boolean) {
val filesToScheme = StringUtil.split(expected, ";")
val fileToSchemeMap = THashMap<String, String>()
for (fileToScheme in filesToScheme) {
val index = fileToScheme.indexOf("->")
fileToSchemeMap.put(fileToScheme.substring(0, index), fileToScheme.substring(index + 2))
}
baseDir.directoryStreamIfExists {
for (file in it) {
val fileName = FileUtil.getNameWithoutExtension(file.fileName.toString())
if ("--deleted" == fileName && ignoreDeleted) {
assertThat(fileToSchemeMap).containsKey(fileName)
}
}
}
for (file in fileToSchemeMap.keys) {
assertThat(baseDir.resolve("$file.xml")).isRegularFile()
}
baseDir.directoryStreamIfExists {
for (file in it) {
val scheme = loadElement(file).deserialize(TestScheme::class.java)
assertThat(fileToSchemeMap.get(FileUtil.getNameWithoutExtension(file.fileName.toString()))).isEqualTo(scheme.name)
}
}
}
@Tag("scheme")
data class TestScheme(@field:com.intellij.util.xmlb.annotations.Attribute @field:kotlin.jvm.JvmField var name: String = "", @field:com.intellij.util.xmlb.annotations.Attribute var data: String? = null) : ExternalizableScheme, SerializableScheme {
override fun getName() = name
override fun setName(value: String) {
name = value
}
override fun writeScheme() = serialize()
}
open class TestSchemesProcessor : LazySchemeProcessor<TestScheme, TestScheme>() {
override fun createScheme(dataHolder: SchemeDataHolder<TestScheme>,
name: String,
attributeProvider: Function<String, String?>,
isBundled: Boolean): TestScheme {
val scheme = dataHolder.read().deserialize(TestScheme::class.java)
dataHolder.updateDigest(scheme)
return scheme
}
} | platform/configuration-store-impl/testSrc/SchemeManagerTest.kt | 1030672904 |
package net.perfectdreams.loritta.cinnamon.pudding.services
import kotlinx.datetime.Clock
import kotlinx.datetime.toJavaInstant
import kotlinx.datetime.toKotlinInstant
import mu.KotlinLogging
import net.perfectdreams.loritta.common.utils.LorittaBovespaBrokerUtils
import net.perfectdreams.loritta.cinnamon.pudding.Pudding
import net.perfectdreams.loritta.cinnamon.pudding.data.BrokerTickerInformation
import net.perfectdreams.loritta.cinnamon.pudding.data.UserId
import net.perfectdreams.loritta.cinnamon.pudding.tables.BoughtStocks
import net.perfectdreams.loritta.cinnamon.pudding.tables.Profiles
import net.perfectdreams.loritta.cinnamon.pudding.tables.SonhosTransactionsLog
import net.perfectdreams.loritta.cinnamon.pudding.tables.TickerPrices
import net.perfectdreams.loritta.cinnamon.pudding.tables.transactions.BrokerSonhosTransactionsLog
import net.perfectdreams.loritta.cinnamon.pudding.utils.exposed.selectFirstOrNull
import org.jetbrains.exposed.sql.SqlExpressionBuilder
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.avg
import org.jetbrains.exposed.sql.batchInsert
import org.jetbrains.exposed.sql.count
import org.jetbrains.exposed.sql.deleteWhere
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.insertAndGetId
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.sum
import org.jetbrains.exposed.sql.update
import java.math.BigDecimal
class BovespaBrokerService(private val pudding: Pudding) : Service(pudding) {
companion object {
private val logger = KotlinLogging.logger {}
}
/**
* Gets all ticker informations in the database
*
* @return a list of all tickers
*/
suspend fun getAllTickers() = pudding.transaction {
TickerPrices.select { TickerPrices.enabled eq true }
.map {
BrokerTickerInformation(
it[TickerPrices.ticker].value,
it[TickerPrices.status],
it[TickerPrices.value],
it[TickerPrices.dailyPriceVariation],
it[TickerPrices.lastUpdatedAt].toKotlinInstant()
)
}
}
/**
* Gets ticker [tickerId] information in the database
*
* @return a list of all tickers
*/
suspend fun getTicker(tickerId: String) = getTickerOrNull(tickerId) ?: error("Ticker $tickerId is not present in the database!")
/**
* Gets ticker [tickerId] information in the database
*
* @return a list of all tickers
*/
suspend fun getTickerOrNull(tickerId: String) = pudding.transaction {
TickerPrices.selectFirstOrNull { TickerPrices.ticker eq tickerId }
?.let {
BrokerTickerInformation(
it[TickerPrices.ticker].value,
it[TickerPrices.status],
it[TickerPrices.value],
it[TickerPrices.dailyPriceVariation],
it[TickerPrices.lastUpdatedAt].toKotlinInstant()
)
}
}
/**
* Gets all ticker informations in the database
*
* @return a list of all tickers
*/
suspend fun getUserBoughtStocks(userId: Long) = pudding.transaction {
val stockCount = BoughtStocks.ticker.count()
val sumPrice = BoughtStocks.price.sum()
val averagePrice = BoughtStocks.price.avg()
BoughtStocks
.slice(BoughtStocks.ticker, stockCount, sumPrice, averagePrice)
.select {
BoughtStocks.user eq userId
}.groupBy(BoughtStocks.ticker)
.map {
BrokerUserStockShares(
it[BoughtStocks.ticker].value,
it[stockCount],
it[sumPrice]!!,
it[averagePrice]!!
)
}
}
/**
* Buys [quantity] shares in the [tickerId] ticker in [userId]'s account
*
* @param userId the user ID that is buying the assets
* @param tickerId the ticker's ID
* @param quantity how many assets are going to be bought
* @throws StaleTickerDataException if the data is stale and shouldn't be relied on
* @throws TooManySharesException if the amount of stocks bought plus the user's current stock count will be more than [LorittaBovespaBrokerUtils.MAX_STOCK_SHARES_PER_USER]
* @throws NotEnoughSonhosException if the user doesn't have enough sonhos to purchase the assets
* @throws OutOfSessionException if the ticker isn't active
*/
suspend fun buyStockShares(userId: Long, tickerId: String, quantity: Long): BoughtSharesResponse {
if (0 >= quantity)
throw TransactionActionWithLessThanOneShareException()
return pudding.transaction {
val tickerInformation = getTicker(tickerId)
val valueOfStock = LorittaBovespaBrokerUtils.convertToBuyingPrice(tickerInformation.value)
checkIfTickerIsInactive(tickerInformation)
checkIfTickerDataIsStale(tickerInformation)
val userProfile = pudding.users.getUserProfile(UserId(userId)) ?: error("User does not have a profile!")
val currentStockCount = BoughtStocks.select {
BoughtStocks.user eq userProfile.id.value.toLong()
}.count()
if (quantity + currentStockCount > LorittaBovespaBrokerUtils.MAX_STOCK_SHARES_PER_USER)
throw TooManySharesException(currentStockCount)
val money = userProfile.money
val howMuchValue = valueOfStock * quantity
if (howMuchValue > money)
throw NotEnoughSonhosException(money, howMuchValue)
logger.info { "User $userId is trying to buy $quantity $tickerId for $howMuchValue" }
val now = Clock.System.now()
// By using shouldReturnGeneratedValues, the database won't need to synchronize on each insert
// this increases insert performance A LOT and, because we don't need the IDs, it is very useful to make
// stocks purchases be VERY fast
BoughtStocks.batchInsert(0 until quantity, shouldReturnGeneratedValues = false) {
this[BoughtStocks.user] = userId
this[BoughtStocks.ticker] = tickerId
this[BoughtStocks.price] = valueOfStock
this[BoughtStocks.boughtAt] = now.toEpochMilliseconds()
}
Profiles.update({ Profiles.id eq userId }) {
with(SqlExpressionBuilder) {
it.update(Profiles.money, Profiles.money - howMuchValue)
}
}
val timestampLogId = SonhosTransactionsLog.insertAndGetId {
it[SonhosTransactionsLog.user] = userId
it[SonhosTransactionsLog.timestamp] = now.toJavaInstant()
}
BrokerSonhosTransactionsLog.insert {
it[BrokerSonhosTransactionsLog.timestampLog] = timestampLogId
it[BrokerSonhosTransactionsLog.action] = LorittaBovespaBrokerUtils.BrokerSonhosTransactionsEntryAction.BOUGHT_SHARES
it[BrokerSonhosTransactionsLog.ticker] = tickerId
it[BrokerSonhosTransactionsLog.sonhos] = howMuchValue
it[BrokerSonhosTransactionsLog.stockPrice] = tickerInformation.value
it[BrokerSonhosTransactionsLog.stockQuantity] = quantity
}
logger.info { "User $userId bought $quantity $tickerId for $howMuchValue" }
return@transaction BoughtSharesResponse(
tickerId,
quantity,
howMuchValue
)
}
}
/**
* Sells [quantity] shares in the [tickerId] ticker from [userId]'s account
*
* @param userId the user ID that is selling the assets
* @param tickerId the ticker's ID
* @param quantity how many assets are going to be sold
* @throws StaleTickerDataException if the data is stale and shouldn't be relied on
* @throws NotEnoughSharesException if the [userId] doesn't have enough stocks to be sold
* @throws OutOfSessionException if the ticker isn't active
*/
suspend fun sellStockShares(userId: Long, tickerId: String, quantity: Long): SoldSharesResponse {
if (0 >= quantity)
throw TransactionActionWithLessThanOneShareException()
return pudding.transaction {
val tickerInformation = getTicker(tickerId)
checkIfTickerIsInactive(tickerInformation)
checkIfTickerDataIsStale(tickerInformation)
val selfStocks = BoughtStocks.select {
BoughtStocks.user eq userId and (BoughtStocks.ticker eq tickerId)
}.toList()
// Proper exceptions
if (quantity > selfStocks.size)
throw NotEnoughSharesException(selfStocks.size)
val stocksThatWillBeSold = selfStocks.take(quantity.toInt())
val sellingPrice = LorittaBovespaBrokerUtils.convertToSellingPrice(tickerInformation.value)
val howMuchWillBePaidToTheUser = sellingPrice * quantity
logger.info { "User $userId is trying to sell $quantity $tickerId for $howMuchWillBePaidToTheUser" }
val userProfit = howMuchWillBePaidToTheUser - stocksThatWillBeSold.sumOf { it[BoughtStocks.price] }
val now = Clock.System.now()
// The reason we batch the stocks in multiple queries is due to this issue:
// https://github.com/LorittaBot/Loritta/issues/2343
// https://stackoverflow.com/questions/49274390/postgresql-and-hibernate-java-io-ioexception-tried-to-send-an-out-of-range-inte
stocksThatWillBeSold.chunked(32767).forEachIndexed { index, chunkedStocks ->
BoughtStocks.deleteWhere {
BoughtStocks.id inList chunkedStocks.map { it[BoughtStocks.id] }
}
}
Profiles.update({ Profiles.id eq userId }) {
with(SqlExpressionBuilder) {
it.update(Profiles.money, Profiles.money + howMuchWillBePaidToTheUser)
}
}
val timestampLogId = SonhosTransactionsLog.insertAndGetId {
it[SonhosTransactionsLog.user] = userId
it[SonhosTransactionsLog.timestamp] = now.toJavaInstant()
}
BrokerSonhosTransactionsLog.insert {
it[BrokerSonhosTransactionsLog.timestampLog] = timestampLogId
it[BrokerSonhosTransactionsLog.action] = LorittaBovespaBrokerUtils.BrokerSonhosTransactionsEntryAction.SOLD_SHARES
it[BrokerSonhosTransactionsLog.ticker] = tickerId
it[BrokerSonhosTransactionsLog.sonhos] = howMuchWillBePaidToTheUser
it[BrokerSonhosTransactionsLog.stockPrice] = tickerInformation.value
it[BrokerSonhosTransactionsLog.stockQuantity] = quantity
}
logger.info { "User $userId sold $quantity $tickerId for $howMuchWillBePaidToTheUser" }
return@transaction SoldSharesResponse(
tickerId,
quantity,
howMuchWillBePaidToTheUser,
userProfit
)
}
}
private fun checkIfTickerIsInactive(tickerInformation: BrokerTickerInformation) {
if (!LorittaBovespaBrokerUtils.checkIfTickerIsActive(tickerInformation.status))
throw OutOfSessionException(tickerInformation.status)
}
private fun checkIfTickerDataIsStale(tickerInformation: BrokerTickerInformation) {
if (LorittaBovespaBrokerUtils.checkIfTickerDataIsStale(tickerInformation.lastUpdatedAt))
throw StaleTickerDataException()
}
data class BrokerUserStockShares(
val ticker: String,
val count: Long,
val sum: Long,
val average: BigDecimal
)
data class BoughtSharesResponse(
val tickerId: String,
val quantity: Long,
val value: Long
)
data class SoldSharesResponse(
val tickerId: String,
val quantity: Long,
val earnings: Long,
val profit: Long
)
class NotEnoughSonhosException(val userSonhos: Long, val howMuch: Long) : RuntimeException()
class OutOfSessionException(val currentSession: String) : RuntimeException()
class TooManySharesException(val currentSharesCount: Long) : RuntimeException()
class NotEnoughSharesException(val currentBoughtSharesCount: Int) : RuntimeException()
class StaleTickerDataException : RuntimeException()
class TransactionActionWithLessThanOneShareException : RuntimeException()
} | pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/services/BovespaBrokerService.kt | 3011944892 |
package net.perfectdreams.loritta.common.utils.text
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class VaporwaveTest {
@Test
fun `test special characters`() {
assertThat(
VaporwaveUtils.vaporwave("A Loritta é muito fofa! Ela é tão fofinha que dá até vontade de abraçar ela!")
).isEqualTo("A Loritta é muito fofa! Ela é tão fofinha que dá até vontade de abraçar ela!")
}
} | common/src/jvmTest/kotlin/net/perfectdreams/loritta/common/utils/text/VaporwaveTest.kt | 2407410531 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.