content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Copyright 2016 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.forecast.ui.common
const val EXTRA_CITY_ID = "io.michaelrocks.forecast.intent.extra.CITY_ID"
const val EXTRA_CITY_NAME = "io.michaelrocks.forecast.intent.extra.CITY_NAME"
const val EXTRA_COUNTRY = "io.michaelrocks.forecast.intent.extra.COUNTRY"
| app/src/main/kotlin/io/michaelrocks/forecast/ui/common/Keys.kt | 63877686 |
package moe.tlaster.openween.core.model
import com.fasterxml.jackson.annotation.JsonProperty
/**
* Created by Tlaster on 2016/8/26.
*/
class LimitStatusModel {
@field:JsonProperty("ip_limit")
var ipLimit: Long = 0
@field:JsonProperty("limit_time_unit")
var limitTimeUnit: String? = null
@field:JsonProperty("remaining_ip_hits")
var remainingIpHits: Long = 0
@field:JsonProperty("remaining_user_hits")
var remainingUserHits: Int = 0
@field:JsonProperty("reset_time")
var resetTimeValue: String? = null
@field:JsonProperty("reset_time_in_seconds")
var resetTimeInSeconds: Long = 0
@field:JsonProperty("user_limit")
var userLimit: Int = 0
@field:JsonProperty("error")
var error: String? = null
@field:JsonProperty("error_code")
var errorCode: String? = null
}
| app/src/main/java/moe/tlaster/openween/core/model/LimitStatusModel.kt | 1388147751 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.vanilla.packet.codec.login
import org.lanternpowered.server.network.buffer.ByteBuffer
import org.lanternpowered.server.network.packet.PacketDecoder
import org.lanternpowered.server.network.packet.CodecContext
import org.lanternpowered.server.network.vanilla.packet.type.login.LoginStartPacket
object LoginStartDecoder : PacketDecoder<LoginStartPacket> {
override fun decode(ctx: CodecContext, buf: ByteBuffer): LoginStartPacket = LoginStartPacket(buf.readString())
}
| src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/login/LoginStartDecoder.kt | 401170678 |
package br.com.insanitech.spritekit
import br.com.insanitech.spritekit.graphics.SKColor
import br.com.insanitech.spritekit.graphics.SKPoint
import br.com.insanitech.spritekit.graphics.SKSize
open class SKScene : SKEffectNode {
var anchorPoint: SKPoint = SKPoint()
set(value) { field.point.assignByValue(value.point) }
var size: SKSize = SKSize()
set(value) {
val oldSize = SKSize(field)
field.size.assignByValue(value.size)
this.didChangeSize(oldSize)
}
var scaleMode: SKSceneScaleMode = SKSceneScaleMode.AspectFill
var backgroundColor: SKColor = SKColor(0.15f, 0.15f, 0.15f, 1.0f)
set(value) { field.color.assignByValue(value.color) }
var view: SKView? = null
internal set
init {
this.isUserInteractionEnabled = true
}
constructor(size: SKSize) {
this.size = size
this.sceneDidLoad()
}
open fun didChangeSize(oldSize: SKSize) {
}
open fun sceneDidLoad() {
}
open fun willMove(fromView: SKView) {
}
open fun didMove(toView: SKView) {
}
open fun update(currentTime: Long) {
}
open fun didEvaluateActions() {
}
open fun didFinishUpdate() {
}
override fun addChild(node: SKNode) {
super.addChild(node, false)
this.movedToScene(this)
}
override fun insertChild(node: SKNode, index: Int) {
super.insertChild(node, index, false)
this.movedToScene(this)
}
override fun convertPointForCandidateParentIfNeeded(p: SKPoint, parent: SKNode): SKPoint {
return if (parent == this) p else parent.convertFrom(p, this)
}
}
| SpriteKitLib/src/main/java/br/com/insanitech/spritekit/SKScene.kt | 3692607965 |
package com.mercadopago.android.px.addons.model.internal
import java.io.Serializable
data class Experiment(val id: Int, val name: String, val variant: Variant) : Serializable | px-addons/src/main/java/com/mercadopago/android/px/addons/model/internal/Experiment.kt | 2187185239 |
package ch.difty.scipamato.core
import ch.difty.scipamato.common.navigator.ItemNavigator
import ch.difty.scipamato.common.navigator.LongNavigator
import ch.difty.scipamato.core.sync.launcher.SyncJobResult
import com.giffing.wicket.spring.boot.starter.configuration.extensions.external.spring.security.SecureWebSession
import org.apache.wicket.Session
import org.apache.wicket.request.Request
/**
* Scipamato specific Session
*
* Holds an instance of [ItemNavigator] to manage the paper ids of the
* latest search result. Both keeps track of the id of the currently
* viewed/edited paper ('focus') and/or move the focus to the previous/next
* paper in the list of managed ids.
*
* Holds an instance of the [SyncJobResult] capturing the state of the
* Spring batch job that synchronizes Core data to the public database.
*/
class ScipamatoSession(request: Request) : SecureWebSession(request) {
val paperIdManager: ItemNavigator<Long> = LongNavigator()
val syncJobResult: SyncJobResult = SyncJobResult()
companion object {
private const val serialVersionUID = 1L
@JvmStatic
fun get(): ScipamatoSession = Session.get() as ScipamatoSession
}
}
| core/core-web/src/main/java/ch/difty/scipamato/core/ScipamatoSession.kt | 2811171504 |
package nl.tudelft.ewi.ds.bankchain.bank.bunq
import nl.tudelft.ewi.ds.bankchain.bank.Account
import nl.tudelft.ewi.ds.bankchain.bank.Party
import java8.util.stream.StreamSupport.*
import nl.tudelft.ewi.ds.bankchain.bank.bunq.api.AccountService.*
/**
* Bunq implementation of account
*/
class BunqAccount : Account {
override val party: Party
override val iban: String
override val id: Int
constructor(account: ListResponse.BunqBankAccount, party: Party) {
//retreive IBAN from list of aliases
val ac = stream<ListResponse.Alias>(account.aliases)
.filter { c -> c.type == "IBAN" }
.findFirst()
id = account.id
this.party = party
iban = ac.get().value
}
constructor(iban: String, id: Int, party: Party) {
this.iban = iban
this.party = party
this.id = id
}
}
| BankChain/app/src/main/java/nl/tudelft/ewi/ds/bankchain/bank/bunq/BunqAccount.kt | 600229282 |
package net.torvald.terrarum.virtualcomputer.terranvmadapter
import net.torvald.terranvm.runtime.TerranVM
import net.torvald.terranvm.runtime.to8HexString
import net.torvald.terranvm.runtime.toHexString
import net.torvald.terranvm.runtime.toUint
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.Font
import javax.swing.JFrame
import javax.swing.JTextArea
import javax.swing.WindowConstants
/**
* Created by minjaesong on 2017-11-21.
*/
class Memvwr(val vm: TerranVM) : JFrame("TerranVM Memory Viewer - Core Memory") {
val memArea = JTextArea()
var columns = 16
fun composeMemText() {
val sb = StringBuilder()
/*
stack: 60h..1FFh
r1: 00000000h; 0; 0.0f
cp: -1
000000 : 00 00 00 00 00 00 00 48 00 00 00 50 00 00 00 58 | .......H...P...X
*/
if (vm.stackSize != null) {
sb.append("stack: ${vm.ivtSize.toHexString()}..${(vm.ivtSize + vm.stackSize!! - 1).toHexString()} (size: ${vm.stackSize} bytes)\n")
}
else {
sb.append("stack: not defined\n")
}
// registers
for (r in 1..8) {
val rI = vm.readregInt(r)
val rF = vm.readregFloat(r)
sb.append("r$r: " +
"${rI.to8HexString()}; " +
"$rI; ${rF}f\n"
)
}
sb.append("cp: " +
"${vm.cp.to8HexString()}; " +
"${vm.cp}\n"
)
sb.append("uptime: ${vm.uptime} ms\n")
sb.append("ips: ${vm.instPerSec}\n")
sb.append("ADRESS : 0 1 2 3| 4 5 6 7| 8 9 A B| C D E F\n")
// coremem
for (i in 0..vm.memory.lastIndex) {
if (i % columns == 0) {
sb.append(i.toString(16).toUpperCase().padStart(6, '0')) // mem addr
sb.append(" : ") // separator
}
sb.append(vm.memory[i].toUint().toString(16).toUpperCase().padStart(2, '0'))
if (i % 16 in intArrayOf(3, 7, 11)) {
sb.append('|') // mem value
}
else {
sb.append(' ') // mem value
}
// ASCII viewer
if (i % columns == 15) {
sb.append("| ")
for (x in -15..0) {
val mem = vm.memory[i + x].toUint()
if (mem < 32) {
sb.append('.')
}
else {
sb.append(mem.toChar())
}
if (x + 15 in intArrayOf(3, 7, 11))
sb.append('|')
}
sb.append('\n')
}
}
// peripherals
sb.append("peripherals:\n")
for (i in 0 until vm.peripherals.size) {
sb.append("peri[$i]: ${vm.peripherals[i]?.javaClass?.simpleName ?: "null"}\n")
}
memArea.text = sb.toString()
}
fun update() {
composeMemText()
}
init {
memArea.font = Font("Monospaced", Font.PLAIN, 12)
memArea.highlighter = null
this.layout = BorderLayout()
this.isVisible = true
this.add(javax.swing.JScrollPane(memArea), BorderLayout.CENTER)
this.defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
this.size = Dimension(600, 960)
}
} | src/net/torvald/terrarum/virtualcomputer/terranvmadapter/Memvwr.kt | 2207735962 |
package com.cypress.Locale.en
/** Returns string with score info on English. */
public fun score() : String {
val text =
"Level score\n" +
"Player deaths\n" +
"Enemies killed\n" +
"Shots fired\n" +
"Shots hit\n" +
"Accuracy"
return text
}
| core/src/com/cypress/Locale/en/score.kt | 362610996 |
package br.ufpe.cin.android.systemservices.phonesms
import android.Manifest
import android.app.ListActivity
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.telephony.TelephonyManager
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.core.content.ContextCompat
import java.util.ArrayList
class PhoneManagerActivity : ListActivity() {
internal var data = ArrayList<String>()
internal var adapter: ArrayAdapter<String>? = null
internal var telephonyManager: TelephonyManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, data)
listAdapter = adapter
}
override fun onStart() {
super.onStart()
val readPhoneState = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
val accessCoarseLocation = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
if (readPhoneState && accessCoarseLocation) {
adapter?.add("Device ID: " + telephonyManager?.deviceId)
adapter?.add("Call State: " + telephonyManager?.callState)
adapter?.add("Device SW Version: " + telephonyManager?.deviceSoftwareVersion)
adapter?.add("Network Operator: " + telephonyManager?.networkOperator)
adapter?.add("Network Operator Name: " + telephonyManager?.networkOperatorName)
adapter?.add("Network Country ISO: " + telephonyManager?.networkCountryIso)
adapter?.add("Network Type: " + telephonyManager?.networkType)
adapter?.add("Cell Location: " + telephonyManager?.cellLocation)
adapter?.add("SIM Operator: " + telephonyManager?.simOperator)
adapter?.add("SIM Serial Number: " + telephonyManager?.simSerialNumber)
adapter?.add("SIM State: " + telephonyManager?.simState)
adapter?.add("Voice Mail Number: " + telephonyManager?.voiceMailNumber)
adapter?.add("Phone Type: " + telephonyManager?.phoneType)
//adapter.add...
} else {
Toast.makeText(this, "Conceda permissões em settings", Toast.LENGTH_SHORT).show()
finish()
}
}
override fun onStop() {
super.onStop()
adapter?.clear()
}
} | 2019-10-02/SystemServices/app/src/main/java/br/ufpe/cin/android/systemservices/phonesms/PhoneManagerActivity.kt | 2689858992 |
package com.task.ui.base
import android.os.Bundle
import android.view.MenuItem
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.Unbinder
import com.task.R
import com.task.ui.base.listeners.ActionBarView
import com.task.ui.base.listeners.BaseView
/**
* Created by AhmedEltaher on 5/12/2016
*/
abstract class BaseActivity : AppCompatActivity(), BaseView, ActionBarView {
protected lateinit var presenter: Presenter<*>
@JvmField
@BindView(R.id.toolbar)
internal var toolbar: Toolbar? = null
@JvmField
@BindView(R.id.ic_toolbar_setting)
internal var icSettings: ImageView? = null
@JvmField
@BindView(R.id.ic_toolbar_refresh)
var icHome: ImageView? = null
private var unbinder: Unbinder? = null
abstract val layoutId: Int
protected abstract fun initializeDagger()
protected abstract fun initializePresenter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(layoutId)
unbinder = ButterKnife.bind(this)
initializeDagger()
initializePresenter()
initializeToolbar()
presenter.initialize(intent.extras)
}
override fun onStart() {
super.onStart()
presenter.start()
}
override fun onStop() {
super.onStop()
presenter.finalizeView()
}
private fun initializeToolbar() {
if (toolbar != null) {
setSupportActionBar(toolbar)
supportActionBar?.title = ""
}
}
override fun setUpIconVisibility(visible: Boolean) {
val actionBar = supportActionBar
actionBar?.setDisplayHomeAsUpEnabled(visible)
}
override fun setTitle(titleKey: String) {
val actionBar = supportActionBar
if (actionBar != null) {
val title = findViewById<TextView>(R.id.txt_toolbar_title)
title?.text = titleKey
}
}
override fun setSettingsIconVisibility(visibility: Boolean) {
val actionBar = supportActionBar
if (actionBar != null) {
val icon = findViewById<ImageView>(R.id.ic_toolbar_setting)
icon?.visibility = if (visibility) VISIBLE else GONE
}
}
override fun setRefreshVisibility(visibility: Boolean) {
val actionBar = supportActionBar
if (actionBar != null) {
val icon = findViewById<ImageView>(R.id.ic_toolbar_refresh)
icon?.visibility = if (visibility) VISIBLE else GONE
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> finish()
}
return super.onOptionsItemSelected(item)
}
override fun onDestroy() {
super.onDestroy()
unbinder?.unbind()
}
}
| app/src/main/java/com/task/ui/base/BaseActivity.kt | 1623559767 |
package io.casey.musikcube.remote.ui.shared.extension
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import java.io.Serializable
@Suppress("deprecation")
inline fun <reified T: Parcelable> Intent.getParcelableExtraCompat(name: String): T? =
if (Build.VERSION.SDK_INT >= 33) {
this.getParcelableExtra(name, T::class.java)
}
else {
this.getParcelableExtra(name)
}
@Suppress("deprecation")
inline fun <reified T: Parcelable> Bundle.getParcelableCompat(name: String): T? =
if (Build.VERSION.SDK_INT >= 33) {
this.getParcelable(name, T::class.java)
}
else {
this.getParcelable(name)
}
@Suppress("deprecation")
inline fun <reified T: Serializable> Bundle.getSerializableCompat(name: String): T? =
if (Build.VERSION.SDK_INT >= 33) {
this.getSerializable(name, T::class.java)
}
else {
this.getSerializable(name) as T?
}
@Suppress("deprecation")
fun PackageManager.getPackageInfoCompat(name: String): PackageInfo =
if (Build.VERSION.SDK_INT >= 33) {
this.getPackageInfo(name, PackageManager.PackageInfoFlags.of(0))
}
else {
this.getPackageInfo(name, 0)
}
fun ComponentActivity.launcher(callback: ActivityResultCallback<ActivityResult>): ActivityResultLauncher<Intent> =
this.registerForActivityResult(ActivityResultContracts.StartActivityForResult(), callback)
fun Fragment.launcher(callback: ActivityResultCallback<ActivityResult>): ActivityResultLauncher<Intent> =
this.registerForActivityResult(ActivityResultContracts.StartActivityForResult(), callback)
| src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/shared/extension/Compat.kt | 2506609137 |
package cc.aoeiuv020.panovel.find.qidiantu.list
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import cc.aoeiuv020.panovel.IView
import cc.aoeiuv020.panovel.R
import cc.aoeiuv020.panovel.data.entity.Novel
import cc.aoeiuv020.panovel.detail.NovelDetailActivity
import cc.aoeiuv020.panovel.find.qidiantu.QidiantuActivity
import cc.aoeiuv020.panovel.settings.OtherSettings
import cc.aoeiuv020.panovel.util.safelyShow
import cc.aoeiuv020.regex.pick
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.activity_qidiantu_list.*
import kotlinx.android.synthetic.main.activity_single_search.srlRefresh
import org.jetbrains.anko.*
/**
* 起点图首订统计小说列表页,
*/
class QidiantuListActivity : AppCompatActivity(), IView, AnkoLogger {
companion object {
fun start(ctx: Context) {
ctx.startActivity<QidiantuListActivity>()
}
fun start(ctx: Context, postUrl: String) {
ctx.startActivity<QidiantuListActivity>(
"postUrl" to postUrl
)
}
}
private lateinit var presenter: QidiantuListPresenter
private lateinit var adapter: QidiantuListAdapter
private lateinit var headAdapter: QidiantuPostAdapter
private lateinit var postUrl: String
private var itemJumpQidian: MenuItem? = null
private val snack: Snackbar by lazy {
Snackbar.make(rvContent, "", Snackbar.LENGTH_SHORT)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_qidiantu_list)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
setTitle(R.string.qidiantu)
postUrl = intent.getStringExtra("postUrl") ?: "https://www.qidiantu.com/shouding/"
srlRefresh.isRefreshing = true
srlRefresh.setOnRefreshListener {
presenter.refresh()
}
initRecycler()
presenter = QidiantuListPresenter()
presenter.attach(this)
presenter.start(this, postUrl)
}
override fun onDestroy() {
presenter.stop()
super.onDestroy()
}
private fun initRecycler() {
rvHead.adapter = QidiantuPostAdapter().also {
headAdapter = it
it.setOnItemClickListener(object : QidiantuPostAdapter.OnItemClickListener {
override fun onItemClick(item: Post) {
start(ctx, item.url)
finish()
}
})
}
rvContent.adapter = QidiantuListAdapter().also {
adapter = it
it.setOnItemClickListener(object : QidiantuListAdapter.OnItemClickListener {
override fun onItemClick(item: Item) {
try {
openBook(item)
} catch (ignore: Exception) {
innerBrowse(item.url)
}
}
})
}
}
fun innerBrowse(url: String) {
QidiantuActivity.start(this, url)
}
private fun openBook(item: Item) {
// http://www.qidiantu.com/info/1030268248.html
val bookId = item.url.pick("http.*/info/(\\d*)").first()
// https://book.qidian.com/info/1027440366
// https://m.qidian.com/info/1027440366
if (OtherSettings.jumpQidian) {
try {
// I/ActivityTaskManager: START u0 {act=android.intent.action.VIEW cat=[android.intent.category.BROWSABLE] dat=QDReader://app/showBook?query={"bookId":1027440366} flg=0x14400000 cmp=com.qidian.QDReader/.ui.activity.MainGroupActivity (has extras)} from uid 10241
// intent://app/showBook?query=%7B%22bookId%22%3A1027440366%7D#Intent;scheme=QDReader;S.browser_fallback_url=http%3A%2F%2Fdownload.qidian.com%2Fapknew%2Fsource%2FQDReaderAndroid.apk;end
val intent = Intent.parseUri(
"intent://app/showBook?query=%7B%22bookId%22%3A$bookId%7D#Intent;scheme=QDReader;S.browser_fallback_url=http%3A%2F%2Fdownload.qidian.com%2Fapknew%2Fsource%2FQDReaderAndroid.apk;end",
Intent.URI_INTENT_SCHEME
)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
return
} catch (e: ActivityNotFoundException) {
toast(R.string.qidian_not_found)
OtherSettings.jumpQidian = false
updateItem()
}
}
presenter.open(item, bookId)
}
fun openNovelDetail(novel: Novel) {
NovelDetailActivity.start(ctx, novel)
}
fun showResult(data: List<Item>, head: List<Post>, title: String) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed) {
return
}
srlRefresh.isRefreshing = false
adapter.setData(data)
headAdapter.setData(head)
if (title.isNotBlank()) {
setTitle(title)
}
if (data.isEmpty()) {
snack.setText(R.string.qidiantu_empty_new)
snack.show()
} else {
snack.dismiss()
}
}
fun showProgress(retry: Int, maxRetry: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed) {
return
}
srlRefresh.isRefreshing = false
snack.setText(getString(R.string.qidianshuju_post_progress_place_holder, retry, maxRetry))
snack.show()
}
fun showError(message: String, e: Throwable) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed) {
return
}
srlRefresh.isRefreshing = false
snack.dismiss()
alert(
title = ctx.getString(R.string.error),
message = message + e.message
) {
okButton { }
}.safelyShow()
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_qidianshuju_list, menu)
itemJumpQidian = menu.findItem(R.id.qidian)
updateItem()
return true
}
override fun onRestart() {
super.onRestart()
updateItem()
}
private fun updateItem() {
itemJumpQidian?.setIcon(
if (OtherSettings.jumpQidian) {
R.drawable.ic_jump_qidian
} else {
R.drawable.ic_jump_qidian_blocked
}
)
}
private fun toggleQidian() {
OtherSettings.jumpQidian = !OtherSettings.jumpQidian
updateItem()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.browse -> presenter.browse()
R.id.qidian -> toggleQidian()
else -> return super.onOptionsItemSelected(item)
}
return true
}
}
| app/src/main/java/cc/aoeiuv020/panovel/find/qidiantu/list/QidiantuListActivity.kt | 2545543189 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package pluginbase.messages
import java.util.HashMap
/**
* All supported color values for chat.
*/
enum class ChatColor constructor(
/**
* Gets the char value associated with this color.
*
* @return A char value of this color code.
*/
val char: Char,
private val intCode: Int,
/**
* Checks if this code is a format code as opposed to a color code.
*/
val isFormat: Boolean = false) {
/**
* Represents black.
*/
BLACK('0', 0x00),
/**
* Represents dark blue.
*/
DARK_BLUE('1', 0x1),
/**
* Represents dark green.
*/
DARK_GREEN('2', 0x2),
/**
* Represents dark blue (aqua).
*/
DARK_AQUA('3', 0x3),
/**
* Represents dark red.
*/
DARK_RED('4', 0x4),
/**
* Represents dark purple.
*/
DARK_PURPLE('5', 0x5),
/**
* Represents gold.
*/
GOLD('6', 0x6),
/**
* Represents gray.
*/
GRAY('7', 0x7),
/**
* Represents dark gray.
*/
DARK_GRAY('8', 0x8),
/**
* Represents blue.
*/
BLUE('9', 0x9),
/**
* Represents green.
*/
GREEN('a', 0xA),
/**
* Represents aqua.
*/
AQUA('b', 0xB),
/**
* Represents red.
*/
RED('c', 0xC),
/**
* Represents light purple.
*/
LIGHT_PURPLE('d', 0xD),
/**
* Represents yellow.
*/
YELLOW('e', 0xE),
/**
* Represents white.
*/
WHITE('f', 0xF),
/**
* Represents magical characters that change around randomly.
*/
MAGIC('k', 0x10, true),
/**
* Makes the text bold.
*/
BOLD('l', 0x11, true),
/**
* Makes a line appear through the text.
*/
STRIKETHROUGH('m', 0x12, true),
/**
* Makes the text appear underlined.
*/
UNDERLINE('n', 0x13, true),
/**
* Makes the text italic.
*/
ITALIC('o', 0x14, true),
/**
* Resets all previous chat colors or formats.
*/
RESET('r', 0x15);
private val stringForm by lazy { "$COLOR_CHAR$char" }
override fun toString(): String {
return stringForm
}
/**
* Checks if this code is a color code as opposed to a format code.
*/
val isColor: Boolean
get() = !isFormat && this != RESET
companion object {
/**
* The special character which prefixes all chat colour codes.
*
* Use this if you need to dynamically convert colour codes from your custom format.
*/
const val COLOR_CHAR = '\u00A7'
private val STRIP_COLOR_PATTERN = "(?i)$COLOR_CHAR[0-9A-FK-OR]".toPattern()
private val BY_ID = HashMap<Int, ChatColor>()
private val BY_CHAR = HashMap<Char, ChatColor>()
/**
* Gets the color represented by the specified color code.
*
* @param code Code to check.
* @return Associated [ChatColor] with the given code, or null if it doesn't exist.
*/
@JvmStatic
fun getByChar(code: Char): ChatColor? {
return BY_CHAR[code]
}
/**
* Gets the color represented by the specified color code.
*
* @param code Code to check.
* @return Associated [ChatColor] with the given code, or null if it doesn't exist.
*/
@JvmStatic
fun getByChar(code: String): ChatColor? {
return BY_CHAR[code[0]]
}
/**
* Strips the given message of all color codes.
*
* @param input String to strip of color.
* @return A copy of the input string, without any coloring.
*/
@JvmStatic
fun stripColor(input: String?): String? {
if (input == null) {
return null
}
return STRIP_COLOR_PATTERN.matcher(input).replaceAll("")
}
/**
* Translates a string using an alternate color code character into a string that uses the internal
* ChatColor.COLOR_CODE color code character.
*
* The alternate color code character will only be replaced if it is immediately followed by 0-9, A-F, or a-f.
*
* @param altColorChar The alternate color code character to replace. Ex: &.
* @param textToTranslate Text containing the alternate color code character.
* @return Text containing the ChatColor.COLOR_CODE color code character.
*/
@JvmStatic
fun translateAlternateColorCodes(altColorChar: Char, textToTranslate: String): String {
val b = textToTranslate.toCharArray()
for (i in 0..(b.size - 2)) {
if (b[i] == altColorChar && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[i + 1]) > -1) {
b[i] = COLOR_CHAR
b[i + 1] = Character.toLowerCase(b[i + 1])
}
}
return String(b)
}
/**
* Gets the ChatColors used at the end of the given input string.
*
* @param input Input string to retrieve the colors from.
* @return Any remaining ChatColors to pass onto the next line.
*/
@JvmStatic
fun getLastColors(input: String): String {
var result = ""
val length = input.length
// Search backwards from the end as it is faster
for (index in length - 1 downTo 0) {
val section = input[index]
if (section == COLOR_CHAR && index < length - 1) {
val c = input[index + 1]
val color = getByChar(c)
if (color != null) {
result = color.toString() + result
// Once we find a color or reset we can stop searching
if (color.isColor || color == RESET) {
break
}
}
}
}
return result
}
init {
for (color in values()) {
BY_ID.put(color.intCode, color)
BY_CHAR.put(color.char, color)
}
}
}
}
| pluginbase-core/messages/src/main/kotlin/pluginbase/messages/ChatColor.kt | 350723835 |
package org.panoptes.server.core
import io.netty.handler.codec.http.HttpResponseStatus
import io.netty.handler.codec.mqtt.MqttConnectReturnCode
import io.vertx.core.AbstractVerticle
import io.vertx.core.DeploymentOptions
import io.vertx.core.http.HttpMethod
import io.vertx.core.json.JsonObject
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import io.vertx.kotlin.mqtt.MqttServerOptions
import io.vertx.mqtt.MqttServer
class MainVerticle : AbstractVerticle() {
@Throws(Exception::class)
override fun start() {
startMongoVerticle()
}
private fun startMongoVerticle() {
val options = DeploymentOptions().setConfig(config())
vertx.deployVerticle(MongoVerticle::class.java, options, { verticleDeployment ->
if (verticleDeployment.succeeded()) {
val httpPort = config().getInteger("http.port", 8080)!!
val mqttPort = config().getInteger("mqtt.port", 1883)!!
startHttpServer(httpPort)
startMqttBroker(mqttPort)
} else {
println("could not start mongo verticle because : ${verticleDeployment.cause()}")
}
})
}
private fun startMqttBroker(mqttPort: Int) {
val mqttServerOptions = MqttServerOptions(clientAuthRequired = true, port = mqttPort, autoClientId = true)
val mqttServer = MqttServer.create(vertx, mqttServerOptions)
mqttServer.endpointHandler { endpoint ->
// shows main connect info
println("MQTT client [" + endpoint.clientIdentifier() + "] request to connect, clean session = " + endpoint.isCleanSession)
if (endpoint.auth() != null) {
println("try to authenticate [username = " + endpoint.auth().userName() + ", password = " + endpoint.auth().password() + "]")
vertx.eventBus().send<Boolean>(Constants.TOPIC_AUTH_USER, JsonObject().put("login", endpoint.auth().userName()).put("password", endpoint.auth().password()), { response ->
if (!response.succeeded() || !response.result().body()) {
endpoint.reject(MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED)
} else {
println("authenticate [username = " + endpoint.auth().userName() + ", password = " + endpoint.auth().password() + "] => OK")
if (endpoint.will() != null) {
println("[will topic = " + endpoint.will().willTopic() + " msg = " + endpoint.will().willMessage() +
" QoS = " + endpoint.will().willQos() + " isRetain = " + endpoint.will().isWillRetain + "]")
}
println("[keep alive timeout = " + endpoint.keepAliveTimeSeconds() + "]")
// accept connection from the remote client
endpoint.accept(false)
}
})
} else {
endpoint.reject(MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED)
}
endpoint.publishHandler({ message ->
println("msg published on topic ${message.topicName()} : ${String(message.payload().getBytes())}")
})
}.listen { ar ->
if (ar.succeeded()) {
println("MQTT server is listening on port " + ar.result().actualPort())
} else {
println("Error on starting the server")
ar.cause().printStackTrace()
}
}
}
private fun startHttpServer(httpPort: Int) {
val router = Router.router(vertx)
router.route("/auth").handler { routingContext ->
if (routingContext.request().method() == HttpMethod.GET) {
val login = routingContext.request().getParam("login")
val password = routingContext.request().getParam("password")
checkLogin(login, password, routingContext)
} else {
routingContext.fail(HttpResponseStatus.BAD_REQUEST.code())
}
}
router.route("/user").handler { routingContext ->
if (routingContext.request().method() == HttpMethod.POST) {
val login = routingContext.request().getParam("login")
val password = routingContext.request().getParam("password")
createUser(login, password, routingContext)
} else {
routingContext.fail(HttpResponseStatus.BAD_REQUEST.code())
}
}
vertx.createHttpServer().requestHandler(router::accept).listen(httpPort)
println("HTTP server started on port ${httpPort}")
}
private fun createUser(login: String?, password: String?, routingContext: RoutingContext) {
if (login != null && password != null) {
vertx.eventBus().send<String>(Constants.TOPIC_CREATE_USER, JsonObject().put("login",login).put("password", password),{ response ->
if (response.succeeded()) {
routingContext.response().statusCode = HttpResponseStatus.CREATED.code()
routingContext.response().end(response.result().body())
} else {
routingContext.fail(response.cause())
}
} )
} else {
routingContext.fail(HttpResponseStatus.FORBIDDEN.code())
}
}
private fun checkLogin(login: String?, password: String?, routingContext: RoutingContext) {
if (login != null && password != null) {
vertx.eventBus().send<Boolean>(Constants.TOPIC_AUTH_USER, JsonObject().put("login",login).put("password", password),{ response ->
if (response.succeeded() && response.result().body()) {
routingContext.response().statusCode = HttpResponseStatus.OK.code()
} else {
routingContext.fail( HttpResponseStatus.FORBIDDEN.code())
}
} )
} else {
routingContext.response().statusCode = HttpResponseStatus.FORBIDDEN.code()
}
routingContext.response().end()
}
}
| src/main/kotlin/org/panoptes/server/core/MainVerticle.kt | 947129852 |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.spectralogic.ds3autogen.go.utils
import com.spectralogic.ds3autogen.utils.ConverterUtil.hasContent
import com.spectralogic.ds3autogen.utils.ConverterUtil.isEmpty
import com.spectralogic.ds3autogen.utils.NormalizingContractNamesUtil
/**
* Contains utils for converting contract types into their corresponding Go types
*/
/**
* Retrieves the Go type associated with the specific contract type/compoundType.
*/
fun toGoResponseType(contractType: String?, compoundContractType: String?, nullable: Boolean): String {
if (isEmpty(contractType)) {
throw IllegalArgumentException("The contract type cannot be null or an empty string")
}
if (!contractType.equals("array", ignoreCase = true) || isEmpty(compoundContractType)) {
return toGoResponseType(contractType!!, nullable)
}
return "[]" + toGoType(compoundContractType!!)
}
/**
* Retrieves the Go type associated with the specific contract type for a request.
* If the type is nullable and a primitive, then the Go type is a pointer.
*/
fun toGoRequestType(contractType: String, nullable: Boolean): String {
val goType: String = toGoType(contractType)
if (nullable && hasContent(goType) && isGoPrimitiveType(goType)) {
return "*" + goType
}
return goType
}
/**
* Determines if a Go type is a primitive type.
*/
fun isGoPrimitiveType(goType: String): Boolean {
return when (goType) {
"bool", "int", "string", "float64", "int64" -> true
else -> false
}
}
/**
* Retrieves the Go type associated with the specific contract type. If the
* type is nullable, then the Go type is a pointer to the specified type.
*/
fun toGoResponseType(contractType: String, nullable: Boolean): String {
val goType: String = toGoType(contractType)
if (nullable && hasContent(goType)) {
return "*" + goType
}
return goType
}
/**
* Retrieves the Go type associated with the specified contract type. Nullability
* is not taken into account
*/
fun toGoType(contractType: String): String {
val type: String = NormalizingContractNamesUtil.removePath(contractType)
return when (type.toLowerCase()) {
"boolean" -> "bool"
"integer", "int" -> "int"
"string", "uuid", "date" -> "string"
"double" -> "float64"
"long" -> "int64"
"void" -> ""
else -> type
}
}
| ds3-autogen-go/src/main/kotlin/com/spectralogic/ds3autogen/go/utils/GoTypeUtil.kt | 4188642718 |
package net.nemerosa.ontrack.kdsl.spec.extension.av
import net.nemerosa.ontrack.kdsl.spec.Ontrack
/**
* Management of auto versioning in Ontrack.
*/
val Ontrack.autoVersioning: AutoVersioningMgt get() = AutoVersioningMgt(connector)
| ontrack-kdsl/src/main/java/net/nemerosa/ontrack/kdsl/spec/extension/av/AutoVersioningOntrackExtensions.kt | 1109180723 |
package net.nemerosa.ontrack.service.elasticsearch
import net.nemerosa.ontrack.model.structure.SearchService
import net.nemerosa.ontrack.model.support.StartupService
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
class ElasticSearchStartupService(
private val searchService: SearchService
) : StartupService {
override fun getName(): String = "Creation of ElasticSearch indexes"
override fun startupOrder(): Int = StartupService.JOB_REGISTRATION - 1 // Just before the jobs
override fun start() {
searchService.indexInit()
}
}
| ontrack-service/src/main/java/net/nemerosa/ontrack/service/elasticsearch/ElasticSearchStartupService.kt | 2302929378 |
fun for_1_simple(): Int {
var sum = 0
for (i in 10..20) {
sum += i
}
return sum
} | translator/src/test/kotlin/tests/for_1/for_1.kt | 690203353 |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.materialstudies.reply.data
import androidx.annotation.DrawableRes
data class EmailAttachment(
@DrawableRes val resId: Int,
val contentDesc: String
) | Reply/app/src/main/java/com/materialstudies/reply/data/EmailAttachment.kt | 3527711234 |
package com.hewking.pointerpanel
import android.content.Context
import android.content.res.Resources
import android.graphics.*
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import androidx.core.graphics.toColorInt
import androidx.core.math.MathUtils
import com.hewking.custom.R
import kotlin.math.min
/**
* 指针面板视图
*
* 注意:只有[paddingTop]属性有效
*
* 角度按照安卓坐标系的方向从0-360
*
* @author hewking
* @date 2019/12/27
*/
class PointerPanelView(context: Context, attributeSet: AttributeSet? = null) :
View(context, attributeSet) {
val degreesGestureDetector: DegreesGestureDetector
/**轨道背景颜色*/
var trackBgColor: Int = "#E8E8E8".toColorInt()
/**轨道进度*/
var trackProgressStartColor: Int = "#FFC24B".toColorInt()
var trackProgressEndColor: Int = "#FF8E24".toColorInt()
/**轨道大小*/
var trackSize: Int = 10.toDpi()
/**
* 轨道的半径
* 用来推算原点坐标
*
* 只有将轨道绘制成圆,用户体验才好. 椭圆的体验不好.
* */
var trackRadius: Float = -1f
/**轨道绘制开始的角度*/
var trackStartAngle: Int = 200
var trackEndAngle: Int = 340
/**当前的进度*/
var trackProgress: Float = 0f
set(value) {
field = value
postInvalidate()
}
/**浮子*/
var thumbDrawable: Drawable? = null
/**浮子绘制在多少半径上, -1表示在轨道上*/
var thumbRadius: Float = -1f
/**浮子是否跟随进度,旋转*/
var thumbEnableRotate: Boolean = true
/**浮子额外旋转的角度*/
var thumbRotateOffsetDegrees: Int = 90
/**文本指示绘制回调*/
var onPointerTextConfig: (degrees: Int, progress: Float, config: PointerTextConfig) -> Unit =
{ degrees, progress, config ->
if (progress == 0.1f || progress == 0.9f || progress == 0.5f || progress == 0.3f || progress == 0.7f) {
config.text = "$degrees°C"
}
}
/**文本绘制时, 跨度多少*/
var angleTextConfigStep = 1
/**进度改变回调*/
var onProgressChange: (progress: Float, fromUser: Boolean) -> Unit = { _, _ ->
}
val _pointerTextConfig = PointerTextConfig()
val paint: Paint by lazy {
Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeCap = Paint.Cap.ROUND
}
}
init {
val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.PointerPanelView)
trackRadius =
typedArray.getDimensionPixelOffset(R.styleable.PointerPanelView_p_track_radius, -1)
.toFloat()
trackSize =
typedArray.getDimensionPixelOffset(R.styleable.PointerPanelView_p_track_size, trackSize)
trackStartAngle =
typedArray.getInt(R.styleable.PointerPanelView_p_track_start_angle, trackStartAngle)
trackEndAngle =
typedArray.getInt(R.styleable.PointerPanelView_p_track_end_angle, trackEndAngle)
thumbDrawable = typedArray.getDrawable(R.styleable.PointerPanelView_p_thumb_drawable)
angleTextConfigStep = typedArray.getInt(
R.styleable.PointerPanelView_p_track_angle_text_step,
angleTextConfigStep
)
setProgress(
typedArray.getFloat(
R.styleable.PointerPanelView_p_track_progress,
trackProgress
), false
)
thumbRadius = typedArray.getDimensionPixelOffset(
R.styleable.PointerPanelView_p_thumb_radius,
thumbRadius.toInt()
).toFloat()
typedArray.recycle()
degreesGestureDetector = DegreesGestureDetector()
degreesGestureDetector.onHandleEvent = { touchDegrees, rotateDegrees, touchDistance ->
//i("handle:$touchDegrees $rotateDegrees")
if (rotateDegrees <= 3) {
val range = (trackStartAngle - 10)..(trackEndAngle + 10)
touchDegrees in range ||
(touchDegrees + 360) in range
} else {
true
}
}
degreesGestureDetector.onDegreesChange =
{ touchDegrees, touchDegreesQuadrant, rotateDegrees, touchDistance ->
val range = trackStartAngle..trackEndAngle
//i("$touchDegrees $touchDegreesQuadrant")
var degress = if (touchDegreesQuadrant < 0) touchDegrees else touchDegreesQuadrant
if (degreesGestureDetector._downQuadrant == 4 &&
degreesGestureDetector._downQuadrant == degreesGestureDetector._lastQuadrant
) {
//在第4象限按下, 并且未改变过象限
degress = touchDegrees + 360
}
if (degress in range) {
setProgress(
(degress - trackStartAngle.toFloat()) / (trackEndAngle.toFloat() - trackStartAngle.toFloat()),
true
)
}
//i("进度:$touchDegrees $touchDegreesQuadrant $trackProgress")
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (trackRadius < 0) {
trackRadius = min(measuredWidth, measuredHeight) / 2f
}
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
paint.style = Paint.Style.STROKE
paint.strokeWidth = trackSize.toFloat()
paint.color = trackBgColor
tempRectF.set(trackRectF)
tempRectF.inset(paint.strokeWidth / 2, paint.strokeWidth / 2)
//绘制背景
paint.shader = null
canvas.drawArc(
tempRectF,
trackStartAngle.toFloat(),
trackEndAngle.toFloat() - trackStartAngle.toFloat(),
false, paint
)
//绘制进度
paint.shader = LinearGradient(
tempRectF.left,
0f,
tempRectF.left + tempRectF.width() * trackProgress,
0f,
trackProgressStartColor,
trackProgressEndColor,
Shader.TileMode.CLAMP
)
canvas.drawArc(
tempRectF,
trackStartAngle.toFloat(),
(trackEndAngle - trackStartAngle) * trackProgress,
false,
paint
)
paint.shader = null
paint.style = Paint.Style.FILL
//绘制文本
for (angle in trackStartAngle..trackEndAngle step angleTextConfigStep) {
_pointerTextConfig.reset()
onPointerTextConfig(
angle,
(angle - trackStartAngle).toFloat() / (trackEndAngle - trackStartAngle),
_pointerTextConfig
)
_pointerTextConfig.apply {
if (text?.isNotEmpty() == true) {
paint.color = textColor
paint.textSize = textSize
val textWidth = paint.measureText(text)
val pointF = dotDegrees(
trackRadius - trackSize / 2 - textWidth, angle,
trackRectF.centerX().toInt(),
trackRectF.centerY().toInt()
)
canvas.drawText(
text!!,
pointF.x - textWidth / 2 + textOffsetX,
pointF.y + textOffsetY,
paint
)
}
}
}
val angle = trackStartAngle + (trackEndAngle - trackStartAngle) * trackProgress
//绘制浮子
thumbDrawable?.apply {
val radius = if (thumbRadius >= 0) thumbRadius else trackRadius - trackSize / 2
val pointF = dotDegrees(
radius, angle.toInt(),
trackRectF.centerX().toInt(),
trackRectF.centerY().toInt()
)
val left = (pointF.x - minimumWidth / 2).toInt()
val top = (pointF.y - minimumHeight / 2).toInt()
setBounds(
left,
top,
left + minimumWidth,
top + minimumHeight
)
if (thumbEnableRotate) {
canvas.save()
canvas.rotate(angle + thumbRotateOffsetDegrees, pointF.x, pointF.y)
draw(canvas)
canvas.restore()
} else {
draw(canvas)
}
}
//i("${(trackEndAngle - trackStartAngle) * trackProgress}")
}
val drawRectF = RectF()
get() {
field.set(
paddingLeft.toFloat(),
paddingTop.toFloat(),
(measuredWidth - paddingRight).toFloat(),
(measuredHeight - paddingBottom).toFloat()
)
return field
}
val trackRectF = RectF()
get() {
field.set(
drawRectF.centerX() - trackRadius,
drawRectF.top,
drawRectF.centerX() + trackRadius,
drawRectF.top + trackRadius * 2
)
return field
}
val tempRectF = RectF()
override fun onTouchEvent(event: MotionEvent): Boolean {
super.onTouchEvent(event)
if (!isEnabled) {
return false
}
degreesGestureDetector.onTouchEvent(event, trackRectF.centerX(), trackRectF.centerY())
return true
}
fun setProgress(progress: Float, fromUser: Boolean = false) {
//i("进度:$progress")
trackProgress = MathUtils.clamp(progress, 0f, 1f)
onProgressChange(trackProgress, fromUser)
}
fun i(msg: String) {
Log.i("PointerPanelView", msg)
}
}
data class PointerTextConfig(
var text: String? = null,
var textColor: Int = 0,
var textSize: Float = 0f,
var textOffsetX: Int = 0,
var textOffsetY: Int = 0
)
fun PointerTextConfig.reset() {
text = null
textColor = "#333333".toColorInt()
textSize = 10.toDp()
textOffsetX = 0
textOffsetY = 0
}
internal val dp: Float = Resources.getSystem()?.displayMetrics?.density ?: 0f
internal val dpi: Int = Resources.getSystem()?.displayMetrics?.density?.toInt() ?: 0
internal fun Int.toDp(): Float {
return this * dp
}
internal fun Int.toDpi(): Int {
return this * dpi
} | app/src/main/java/com/hewking/custom/pointerpanel/PointerPanelView.kt | 1813180762 |
linearLayout {
orientation = LinearLayout.VERTICAL
textView("Hello World").layoutParams(width = matchParent, height = wrapContent)
} | preview/xml-converter/testData/simple/layout.kt | 957399619 |
package io.gitlab.arturbosch.tinbo.api
import java.util.ArrayList
fun Number.toTimeString(): String {
return toString().apply {
if (length == 1) {
return "0$this"
}
}
}
fun String.spaceIfEmpty(): String =
when (this) {
"" -> " "
else -> this
}
fun String.orThrow(message: () -> String = { "Empty value not allowed!" }): String =
if (this.isEmpty())
throw IllegalArgumentException(message())
else this
inline fun String.toLongOrDefault(long: () -> Long): Long {
return try {
this.toLong()
} catch (e: NumberFormatException) {
long.invoke()
}
}
inline fun String.toIntOrDefault(int: () -> Int): Int {
return try {
this.toInt()
} catch (e: NumberFormatException) {
int.invoke()
}
}
fun <E> List<E>.plusElementAtBeginning(element: E): List<E> {
val result = ArrayList<E>(size + 1)
result.add(element)
result.addAll(this)
return result
}
fun List<String>.withIndexedColumn(): List<String> = this.withIndex().map { "${it.index + 1};${it.value}" }
fun <E> List<E>.applyToString(): List<String> = this.map { it.toString() }
fun <E> List<E>.replaceAt(index: Int, element: E): List<E> {
val list = this.toMutableList()
list[index] = element
return list.toList()
}
fun String.orValue(value: String): String = if (this.isEmpty()) value else this
fun String?.orDefault(value: String): String = if (this.isNullOrEmpty()) value else this!!
fun String.replaceSeparator(): String {
return this.replace(";", ".,")
}
fun String.orDefaultMonth(): Int = this.toIntOrDefault { java.time.LocalDate.now().month.value }
fun String?.toLongOrNull(): Long? = if (this.isNullOrEmpty()) null else this?.toLong()
fun String?.nullIfEmpty(): String? = if (this.isNullOrEmpty()) null else this
fun <E> List<E>.ifNotEmpty(function: List<E>.() -> Unit) {
if (this.isNotEmpty()) {
function.invoke(this)
}
}
| tinbo-plugin-api/src/main/kotlin/io/gitlab/arturbosch/tinbo/api/Junk.kt | 372754724 |
package imgui.internal.sections
import glm_.f
import glm_.glm
import glm_.i
import glm_.min
import glm_.vec2.Vec2
import glm_.vec4.Vec4
import imgui.clamp
import imgui.classes.DrawList
import imgui.font.Font
import kotlin.math.acos
import kotlin.math.cos
import kotlin.math.sin
//-----------------------------------------------------------------------------
// [SECTION] ImDrawList support
//-----------------------------------------------------------------------------
// ImDrawList: Helper function to calculate a circle's segment count given its radius and a "maximum error" value.
// FIXME: the minimum number of auto-segment may be undesirably high for very small radiuses (e.g. 1.0f)
const val DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN = 12
const val DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX = 512
fun DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(_RAD: Float, _MAXERROR: Float) = clamp(((glm.πf * 2f) / acos((_RAD - _MAXERROR) / _RAD)).i, DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN, DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX)
/** ImDrawList: You may set this to higher values (e.g. 2 or 3) to increase tessellation of fast rounded corners path. */
var DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER = 1
/** Data shared between all ImDrawList instances
* You may want to create your own instance of this if you want to use ImDrawList completely without ImGui. In that case, watch out for future changes to this structure.
* Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself) */
class DrawListSharedData {
/** UV of white pixel in the atlas */
var texUvWhitePixel = Vec2()
/** Current/default font (optional, for simplified AddText overload) */
var font: Font? = null
/** Current/default font size (optional, for simplified AddText overload) */
var fontSize = 0f
var curveTessellationTol = 0f
/** Number of circle segments to use per pixel of radius for AddCircle() etc */
var circleSegmentMaxError = 0f
/** Value for pushClipRectFullscreen() */
var clipRectFullscreen = Vec4()
/** Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) */
var initialFlags = DrawListFlag.None.i
// [Internal] Lookup tables
// Lookup tables
val arcFastVtx = Array(12 * DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER) {
// FIXME: Bake rounded corners fill/borders in atlas
val a = it * 2 * glm.PIf / 12
Vec2(cos(a), sin(a))
}
/** Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead) */
val circleSegmentCounts = IntArray(64)
/** UV of anti-aliased lines in the atlas */
lateinit var texUvLines: Array<Vec4>
fun setCircleSegmentMaxError_(maxError: Float) {
if (circleSegmentMaxError == maxError)
return
circleSegmentMaxError = maxError
for (i in circleSegmentCounts.indices) {
val radius = i.f
val segmentCount = DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, circleSegmentMaxError)
circleSegmentCounts[i] = segmentCount min 255
}
}
}
/** Helper to build a ImDrawData instance */
class DrawDataBuilder {
/** Global layers for: regular, tooltip */
val layers = Array(2) { ArrayList<DrawList>() }
fun clear() = layers.forEach { it.clear() }
fun flattenIntoSingleLayer() {
val size = layers.map { it.size }.count()
layers[0].ensureCapacity(size)
for (layerN in 1 until layers.size) {
val layer = layers[layerN]
if (layer.isEmpty()) continue
layers[0].addAll(layer)
layer.clear()
}
}
} | core/src/main/kotlin/imgui/internal/sections/drawList support.kt | 156001178 |
package app.cash.sqldelight.dialects.sqlite_3_24.grammar.mixins
import app.cash.sqldelight.dialects.sqlite_3_24.grammar.psi.SqliteInsertStmt
import com.alecstrong.sql.psi.core.SqlAnnotationHolder
import com.alecstrong.sql.psi.core.psi.SqlTypes
import com.alecstrong.sql.psi.core.psi.impl.SqlInsertStmtImpl
import com.intellij.lang.ASTNode
internal abstract class InsertStmtMixin(
node: ASTNode,
) : SqlInsertStmtImpl(node),
SqliteInsertStmt {
override fun annotate(annotationHolder: SqlAnnotationHolder) {
super.annotate(annotationHolder)
val insertDefaultValues = insertStmtValues?.node?.findChildByType(
SqlTypes.DEFAULT,
) != null
upsertClause?.let { upsert ->
val upsertDoUpdate = upsert.upsertDoUpdate
if (insertDefaultValues && upsertDoUpdate != null) {
annotationHolder.createErrorAnnotation(upsert, "The upsert clause is not supported after DEFAULT VALUES")
}
val insertOr = node.findChildByType(
SqlTypes.INSERT,
)?.treeNext
val replace = node.findChildByType(
SqlTypes.REPLACE,
)
val conflictResolution = when {
replace != null -> SqlTypes.REPLACE
insertOr != null && insertOr.elementType == SqlTypes.OR -> {
val type = insertOr.treeNext.elementType
check(
type == SqlTypes.ROLLBACK || type == SqlTypes.ABORT ||
type == SqlTypes.FAIL || type == SqlTypes.IGNORE,
)
type
}
else -> null
}
if (conflictResolution != null && upsertDoUpdate != null) {
annotationHolder.createErrorAnnotation(
upsertDoUpdate,
"Cannot use DO UPDATE while " +
"also specifying a conflict resolution algorithm ($conflictResolution)",
)
}
}
}
}
| dialects/sqlite-3-24/src/main/kotlin/app/cash/sqldelight/dialects/sqlite_3_24/grammar/mixins/InsertStmtMixin.kt | 1427231835 |
/*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.sqldelight.paging3
import androidx.paging.PagingState
import app.cash.sqldelight.Query
import app.cash.sqldelight.Transacter
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext
internal class OffsetQueryPagingSource<RowType : Any>(
private val queryProvider: (limit: Int, offset: Int) -> Query<RowType>,
private val countQuery: Query<Int>,
private val transacter: Transacter,
private val context: CoroutineContext,
) : QueryPagingSource<Int, RowType>() {
override val jumpingSupported get() = true
override suspend fun load(
params: LoadParams<Int>,
): LoadResult<Int, RowType> = withContext(context) {
val key = params.key ?: 0
val limit = when (params) {
is LoadParams.Prepend -> minOf(key, params.loadSize)
else -> params.loadSize
}
val loadResult = transacter.transactionWithResult {
val count = countQuery.executeAsOne()
val offset = when (params) {
is LoadParams.Prepend -> maxOf(0, key - params.loadSize)
is LoadParams.Append -> key
is LoadParams.Refresh -> if (key >= count) maxOf(0, count - params.loadSize) else key
}
val data = queryProvider(limit, offset)
.also { currentQuery = it }
.executeAsList()
val nextPosToLoad = offset + data.size
LoadResult.Page(
data = data,
prevKey = offset.takeIf { it > 0 && data.isNotEmpty() },
nextKey = nextPosToLoad.takeIf { data.isNotEmpty() && data.size >= limit && it < count },
itemsBefore = offset,
itemsAfter = maxOf(0, count - nextPosToLoad),
)
}
if (invalid) LoadResult.Invalid() else loadResult
}
override fun getRefreshKey(state: PagingState<Int, RowType>) =
state.anchorPosition?.let { maxOf(0, it - (state.config.initialLoadSize / 2)) }
}
| extensions/android-paging3/src/main/java/app/cash/sqldelight/paging3/OffsetQueryPagingSource.kt | 2855656741 |
package app.cash.sqldelight.tests
import app.cash.sqldelight.withCommonConfiguration
import com.google.common.truth.Truth
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.TaskOutcome
import org.junit.Test
import java.io.File
class TaskDependenciesTest {
@Test
fun `task dependencies are properly propagated`() {
val output = GradleRunner.create()
.withCommonConfiguration(File("src/test/task-dependencies"))
.withArguments("clean", "checkSources", "--stacktrace")
.build()
Truth.assertThat(output.task(":checkSources")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
Truth.assertThat(output.task(":generateMainDatabaseInterface")!!.outcome).isEqualTo(TaskOutcome.SUCCESS)
}
}
| sqldelight-gradle-plugin/src/test/kotlin/app/cash/sqldelight/tests/TaskDependenciesTest.kt | 457797879 |
//
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
@file:Suppress("unused")
package o.katydid.events.eventhandling
import o.katydid.events.types.*
//---------------------------------------------------------------------------------------------------------------------
/**
* Message-generating event handler: argument is any event, output is a list of messages.
* To cancel an event throw EventCancellationException.
*/
typealias KatydidEventToMessage<Msg> = (event: KatydidEvent) -> Iterable<Msg>
//---------------------------------------------------------------------------------------------------------------------
/**
* Message-generating event handler: argument is any focus event, output is a list of messages.
* To cancel an event throw EventCancellationException.
*/
typealias KatydidFocusEventToMessage<Msg> = (event: KatydidFocusEvent) -> Iterable<Msg>
//---------------------------------------------------------------------------------------------------------------------
/**
* Message-generating event handler: argument is any input event, output is a list of messages.
* To cancel an event throw EventCancellationException.
*/
typealias KatydidInputEventToMessage<Msg> = (event: KatydidInputEvent) -> Iterable<Msg>
//---------------------------------------------------------------------------------------------------------------------
/**
* Message-generating event handler: argument is any mouse event, output is a list of messages.
* To cancel an event throw EventCancellationException.
*/
typealias KatydidMouseEventToMessage<Msg> = (event: KatydidMouseEvent) -> Iterable<Msg>
//---------------------------------------------------------------------------------------------------------------------
/**
* Message-generating event handler: argument is any wheel event, output is a list of messages.
* To cancel an event throw EventCancellationException.
*/
typealias KatydidWheelEventToMessage<Msg> = (event: KatydidWheelEvent) -> Iterable<Msg>
//---------------------------------------------------------------------------------------------------------------------
| Katydid-Events-JS/src/main/kotlin/o/katydid/events/eventhandling/Handlers.kt | 724372779 |
/*
* Copyright 2021 Peter Kenji Yamanaka
*
* 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.pyamsoft.pasterino.test
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import androidx.annotation.CheckResult
import androidx.compose.runtime.Composable
import coil.ImageLoader
import coil.annotation.ExperimentalCoilApi
import coil.bitmap.BitmapPool
import coil.decode.DataSource
import coil.memory.MemoryCache
import coil.request.DefaultRequestOptions
import coil.request.Disposable
import coil.request.ImageRequest
import coil.request.ImageResult
import coil.request.SuccessResult
/** Only use for tests/previews */
private class TestImageLoader(context: Context) : ImageLoader {
private val context = context.applicationContext
private val loadingDrawable by lazy(LazyThreadSafetyMode.NONE) { ColorDrawable(Color.BLACK) }
private val successDrawable by lazy(LazyThreadSafetyMode.NONE) { ColorDrawable(Color.GREEN) }
private val disposable =
object : Disposable {
override val isDisposed: Boolean = true
@ExperimentalCoilApi override suspend fun await() {}
override fun dispose() {}
}
override val bitmapPool: BitmapPool = BitmapPool(0)
override val defaults: DefaultRequestOptions = DefaultRequestOptions()
override val memoryCache: MemoryCache =
object : MemoryCache {
override val maxSize: Int = 1
override val size: Int = 0
override fun clear() {}
override fun get(key: MemoryCache.Key): Bitmap? {
return null
}
override fun remove(key: MemoryCache.Key): Boolean {
return false
}
override fun set(key: MemoryCache.Key, bitmap: Bitmap) {}
}
override fun enqueue(request: ImageRequest): Disposable {
request.apply {
target?.onStart(placeholder = loadingDrawable)
target?.onSuccess(result = successDrawable)
}
return disposable
}
override suspend fun execute(request: ImageRequest): ImageResult {
return SuccessResult(
drawable = successDrawable,
request = request,
metadata =
ImageResult.Metadata(
memoryCacheKey = MemoryCache.Key(""),
isSampled = false,
dataSource = DataSource.MEMORY_CACHE,
isPlaceholderMemoryCacheKeyPresent = false,
))
}
override fun newBuilder(): ImageLoader.Builder {
return ImageLoader.Builder(context)
}
override fun shutdown() {}
}
/** Only use for tests/previews */
@Composable
@CheckResult
fun createNewTestImageLoader(context: Context): ImageLoader {
return TestImageLoader(context)
}
| app/src/main/java/com/pyamsoft/pasterino/test/TestImageLoader.kt | 1348229170 |
package mswift42.com.github.weatherapp
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private val items = listOf(
"Mon 6/23 - Sunny - 31/17",
"Tue 6/24 - Foggy - 21/8",
"Wed 6/25 - Cloudy - 22/17",
"Thurs 6/26 - Rainy - 18/11",
"Fri 6/27 - Foggy - 21/10",
"Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18",
"Sun 6/29 - Sunny - 20/7"
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val forecastlist = findViewById(R.id.forecast_list) as RecyclerView
forecastlist.layoutManager = LinearLayoutManager(this)
forecastlist.adapter = ForecastListAdapter(items)
}
}
| WeatherApp/app/src/main/java/mswift42/com/github/weatherapp/MainActivity.kt | 1385547034 |
package me.smr.weatherforecast.fragments
import android.app.SearchManager
import android.content.Context
import android.os.Bundle
import android.view.*
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import dagger.hilt.android.AndroidEntryPoint
import me.smr.weatherforecast.R
import me.smr.weatherforecast.adapters.SearchClickListener
import me.smr.weatherforecast.adapters.SearchResultAdapter
import me.smr.weatherforecast.adapters.WeatherAdapter
import me.smr.weatherforecast.databinding.HomeFragmentBinding
import me.smr.weatherforecast.models.CitySearchResult
import me.smr.weatherforecast.viewmodels.HomeViewModel
@AndroidEntryPoint
class HomeFragment : Fragment() {
private lateinit var binding: HomeFragmentBinding
private lateinit var searchMenu:MenuItem
private val viewModel: HomeViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = HomeFragmentBinding.inflate(inflater, container, false)
binding.lifecycleOwner = this
binding.viewmodel = viewModel
val searchAdapter = SearchResultAdapter(object : SearchClickListener {
override fun onSearchItemClicked(item: CitySearchResult) {
viewModel.onSearchResultClicked(item)
searchMenu.collapseActionView()
}
})
binding.lvSearch.adapter = searchAdapter
val weatherAdapter = WeatherAdapter()
binding.lvCities.adapter = weatherAdapter
viewModel.searchResult.observe(viewLifecycleOwner) {
searchAdapter.submitList(it)
}
viewModel.weatherData.observe(viewLifecycleOwner) {
weatherAdapter.submitList(it)
}
requireActivity().setTitle(R.string.app_name)
setHasOptionsMenu(true)
return binding.root
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.home, menu)
// Associate searchable configuration with the SearchView
val searchManager =
requireActivity().getSystemService(Context.SEARCH_SERVICE) as SearchManager
searchMenu = menu.findItem(R.id.search)
val searchView = searchMenu.actionView as SearchView
searchView.setSearchableInfo(searchManager.getSearchableInfo(requireActivity().componentName))
val listener = object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(p0: MenuItem?): Boolean {
viewModel.showSearch()
return true
}
override fun onMenuItemActionCollapse(p0: MenuItem?): Boolean {
viewModel.hideSearch()
return true
}
}
searchMenu.setOnActionExpandListener(listener)
}
companion object {
const val TAG = "HomeFragment"
}
} | app/src/main/java/me/smr/weatherforecast/fragments/HomeFragment.kt | 3578941824 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.test.injectionscope.touch
import android.os.SystemClock.sleep
import androidx.compose.testutils.expectError
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEventType.Companion.Move
import androidx.compose.ui.input.pointer.PointerType.Companion.Touch
import androidx.compose.ui.test.InputDispatcher.Companion.eventPeriodMillis
import androidx.compose.ui.test.TouchInjectionScope
import androidx.compose.ui.test.injectionscope.touch.Common.performTouchInput
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.util.ClickableTestBox
import androidx.compose.ui.test.util.MultiPointerInputRecorder
import androidx.compose.ui.test.util.assertTimestampsAreIncreasing
import androidx.compose.ui.test.util.verify
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
/**
* Tests if [TouchInjectionScope.moveBy] and [TouchInjectionScope.updatePointerBy] work
*/
@MediumTest
class MoveByTest {
companion object {
private val downPosition1 = Offset(10f, 10f)
private val downPosition2 = Offset(20f, 20f)
private val delta1 = Offset(11f, 11f)
private val delta2 = Offset(21f, 21f)
}
@get:Rule
val rule = createComposeRule()
private val recorder = MultiPointerInputRecorder()
@Before
fun setUp() {
// Given some content
rule.setContent {
ClickableTestBox(recorder)
}
}
@Test
fun onePointer() {
// When we inject a down event followed by a move event
rule.performTouchInput { down(downPosition1) }
sleep(20) // (with some time in between)
rule.performTouchInput { moveBy(delta1) }
rule.runOnIdle {
recorder.run {
// Then we have recorded 1 down event and 1 move event
assertTimestampsAreIncreasing()
assertThat(events).hasSize(2)
var t = events[0].getPointer(0).timestamp
val pointerId = events[0].getPointer(0).id
t += eventPeriodMillis
assertThat(events[1].pointerCount).isEqualTo(1)
events[1].getPointer(0)
.verify(t, pointerId, true, downPosition1 + delta1, Touch, Move)
}
}
}
@Test
fun twoPointers() {
// When we inject two down events followed by two move events
rule.performTouchInput { down(1, downPosition1) }
rule.performTouchInput { down(2, downPosition2) }
rule.performTouchInput { moveBy(1, delta1) }
rule.performTouchInput { moveBy(2, delta2) }
rule.runOnIdle {
recorder.run {
// Then we have recorded two down events and two move events
assertTimestampsAreIncreasing()
assertThat(events).hasSize(4)
var t = events[0].getPointer(0).timestamp
val pointerId1 = events[0].getPointer(0).id
val pointerId2 = events[1].getPointer(1).id
t += eventPeriodMillis
assertThat(events[2].pointerCount).isEqualTo(2)
events[2].getPointer(0)
.verify(t, pointerId1, true, downPosition1 + delta1, Touch, Move)
events[2].getPointer(1)
.verify(t, pointerId2, true, downPosition2, Touch, Move)
t += eventPeriodMillis
assertThat(events[3].pointerCount).isEqualTo(2)
events[3].getPointer(0)
.verify(t, pointerId1, true, downPosition1 + delta1, Touch, Move)
events[3].getPointer(1)
.verify(t, pointerId2, true, downPosition2 + delta2, Touch, Move)
}
}
}
@Test
fun twoPointers_oneMoveEvent() {
// When we inject two down events followed by one move events
rule.performTouchInput { down(1, downPosition1) }
rule.performTouchInput { down(2, downPosition2) }
sleep(20) // (with some time in between)
rule.performTouchInput { updatePointerBy(1, delta1) }
rule.performTouchInput { updatePointerBy(2, delta2) }
rule.performTouchInput { move() }
rule.runOnIdle {
recorder.run {
// Then we have recorded two down events and one move events
assertTimestampsAreIncreasing()
assertThat(events).hasSize(3)
var t = events[0].getPointer(0).timestamp
val pointerId1 = events[0].getPointer(0).id
val pointerId2 = events[1].getPointer(1).id
t += eventPeriodMillis
assertThat(events[2].pointerCount).isEqualTo(2)
events[2].getPointer(0)
.verify(t, pointerId1, true, downPosition1 + delta1, Touch, Move)
events[2].getPointer(1)
.verify(t, pointerId2, true, downPosition2 + delta2, Touch, Move)
}
}
}
@Test
fun moveBy_withoutDown() {
expectError<IllegalStateException> {
rule.performTouchInput { moveBy(delta1) }
}
}
@Test
fun moveBy_wrongPointerId() {
rule.performTouchInput { down(1, downPosition1) }
expectError<IllegalArgumentException> {
rule.performTouchInput { moveBy(2, delta1) }
}
}
@Test
fun moveBy_afterUp() {
rule.performTouchInput { down(downPosition1) }
rule.performTouchInput { up() }
expectError<IllegalStateException> {
rule.performTouchInput { moveBy(delta1) }
}
}
@Test
fun moveBy_afterCancel() {
rule.performTouchInput { down(downPosition1) }
rule.performTouchInput { cancel() }
expectError<IllegalStateException> {
rule.performTouchInput { moveBy(delta1) }
}
}
@Test
fun updatePointerBy_withoutDown() {
expectError<IllegalStateException> {
rule.performTouchInput { updatePointerBy(1, delta1) }
}
}
@Test
fun updatePointerBy_wrongPointerId() {
rule.performTouchInput { down(1, downPosition1) }
expectError<IllegalArgumentException> {
rule.performTouchInput { updatePointerBy(2, delta1) }
}
}
@Test
fun updatePointerBy_afterUp() {
rule.performTouchInput { down(1, downPosition1) }
rule.performTouchInput { up(1) }
expectError<IllegalStateException> {
rule.performTouchInput { updatePointerBy(1, delta1) }
}
}
@Test
fun updatePointerBy_afterCancel() {
rule.performTouchInput { down(1, downPosition1) }
rule.performTouchInput { cancel() }
expectError<IllegalStateException> {
rule.performTouchInput { updatePointerBy(1, delta1) }
}
}
}
| compose/ui/ui-test/src/androidAndroidTest/kotlin/androidx/compose/ui/test/injectionscope/touch/MoveByTest.kt | 2295543216 |
package tech.salroid.filmy.ui.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import tech.salroid.filmy.data.local.model.CastMovie
import tech.salroid.filmy.databinding.CharCustomRowBinding
class CharacterDetailsActivityAdapter(
private val moviesList: List<CastMovie>,
private val fixedSize: Boolean,
private val clickListener: ((CastMovie, Int) -> Unit)? = null
) : RecyclerView.Adapter<CharacterDetailsActivityAdapter.CharacterDetailsViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CharacterDetailsViewHolder {
val binding =
CharCustomRowBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return CharacterDetailsViewHolder(binding)
}
override fun onBindViewHolder(holder: CharacterDetailsViewHolder, position: Int) {
holder.bindData(moviesList[position])
}
override fun getItemCount(): Int =
if (fixedSize) if (moviesList.size >= 5) 5 else moviesList.size else moviesList.size
inner class CharacterDetailsViewHolder(private val binding: CharCustomRowBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bindData(movie: CastMovie) {
val movieName = movie.originalTitle
val moviePoster = movie.posterPath
val rolePlayed = movie.character
binding.movieName.text = movieName
binding.movieRolePlayed.text = rolePlayed
Glide.with(binding.root.context)
.load("http://image.tmdb.org/t/p/w342${moviePoster}")
.fitCenter()
.into(binding.moviePoster)
}
init {
binding.root.setOnClickListener {
clickListener?.invoke(moviesList[adapterPosition], adapterPosition)
}
}
}
} | app/src/main/java/tech/salroid/filmy/ui/adapters/CharacterDetailsActivityAdapter.kt | 1560694729 |
package <%= appPackage %>.base.ui
import android.arch.lifecycle.LifecycleActivity
import android.arch.lifecycle.ViewModelProviders
import android.support.v4.app.Fragment
import android.view.KeyEvent
import butterknife.ButterKnife
import butterknife.Unbinder
import <%= appPackage %>.base.util.plusAssign
import <%= appPackage %>.viewmodel.ViewModelFactory
import com.grayherring.kotlintest.util.KeyUpListener
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import io.reactivex.disposables.CompositeDisposable
import javax.inject.Inject
abstract class BaseActivity<V : BaseState, T : BaseViewModel<V>> : LifecycleActivity(), HasSupportFragmentInjector {
override fun supportFragmentInjector() = dispatchingAndroidInjector
//todo hmmm will always need fragments need to think about it and look more at dagger android
@Inject
protected lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
@Inject
protected lateinit var viewModelFactory: ViewModelFactory
@Inject lateinit internal var keyUpListener: KeyUpListener
protected lateinit var viewModel: T
protected val disposable = CompositeDisposable()
lateinit private var unbinder : Unbinder
//not sure if this would be better then the function but the issue is u can override it as var
// abstract val viewLayout: Int
override fun onCreate(savedInstanceState: android.os.Bundle?) {
super.onCreate(savedInstanceState)
setContentView(viewLayout())
unbinder = ButterKnife.bind(this)
initViewModel()
}
//todo this code maybe the same in the fragment and activity maybe abstract it?
/**
* setup for view model and stream
*/
fun initViewModel() {
viewModel = ViewModelProviders.of(this, viewModelFactory).get(viewModelClass())
viewModel.init()
initView(viewModel.lastState)
disposable += viewModel.observeState { bindView(it) }
setUpEventStream()
}
/**
* if initializing view if you have to
*/
open fun initView(state: V) {}
/**
* class needed to get the viewModel
*/
abstract internal fun viewModelClass(): Class<T>
/**
* layout id for view
*/
abstract internal fun viewLayout(): Int
/**
* hook for handling view updates
*/
abstract internal fun bindView(state: V)
/**
* put code that creates events for into the even stream here remember to add to [disposable]
*/
abstract fun setUpEventStream()
override fun onDestroy() {
unbinder.unbind()
disposable.clear()
super.onDestroy()
}
//maybe move this to an other sort of base base class extending this
/**
* used to start debug draw
*/
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
keyUpListener.onKeyUp(this, keyCode, event)
return super.onKeyUp(keyCode, event)
}
}
| generator-ssb/generators/templates/template-normal/app/src/main/kotlin/com/grayherring/temp/base/ui/BaseActivity.kt | 248547275 |
/*
* 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.
*/
@file:Suppress("DEPRECATION_ERROR")
package androidx.compose.ui.benchmark
import androidx.compose.foundation.Indication
import androidx.compose.foundation.IndicationInstance
import androidx.compose.foundation.MutatePriority
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.DragScope
import androidx.compose.foundation.gestures.DraggableState
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.ScrollableState
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.indication
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.testutils.benchmark.ComposeBenchmarkRule
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.focusTarget
import androidx.compose.ui.focus.onFocusEvent
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.ContentDrawScope
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import androidx.test.filters.LargeTest
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@LargeTest
@RunWith(Parameterized::class)
class ModifiersBenchmark(
val name: String,
val count: Int,
val modifierFn: (Boolean) -> Modifier
) {
companion object {
/**
* INSTRUCTIONS FOR ADDING A MODIFIER TO THIS LIST
* ===============================================
*
* To add a modifier, add a `*modifier(...)` line which includes:
* (1) the name of the modifier
* (2) a lambda which accepts a boolean value and returns the modifier. You should use
* the passed in boolean value to toggle between two different sets of parameters
* to the modifier chain. If the modifier takes no parameters, just ignore the
* boolean.
*
* Many modifiers require parameters that are objects that need to be allocated. If this is
* an object which the developer is expected to remember or hold on to somewhere in their
* composition, you should allocate one below on this companion object and then just
* reference it in the modifier lambda so that allocating these isn't included in the
* "recomposition" time.
*/
@JvmStatic
@Parameterized.Parameters(name = "{0}_{1}x")
fun data(): Collection<Array<Any>> = listOf(
*modifier("Modifier") { Modifier },
*modifier("emptyElement", true) { Modifier.emptyElement() },
*modifier("clickable", true) { Modifier.clickable { capture(it) } },
*modifier("semantics", true) { Modifier.semantics { capture(it) } },
*modifier("pointerInput") { Modifier.pointerInput(it) { capture(it) } },
*modifier("focusable") { Modifier.focusable() },
*modifier("drawWithCache") {
Modifier.drawWithCache {
val rectSize = if (it) size / 2f else size
onDrawBehind {
drawRect(Color.Black, size = rectSize)
}
}
},
*modifier("testTag") { Modifier.testTag("$it") },
*modifier("selectableGroup") { Modifier.selectableGroup() },
*modifier("indication") {
Modifier.indication(interactionSource, if (it) indication else null)
},
*modifier("draggable") {
Modifier.draggable(
draggableState,
if (it) Orientation.Vertical else Orientation.Horizontal
)
},
*modifier("hoverable") {
Modifier.hoverable(interactionSource)
},
*modifier("scrollable") {
Modifier.scrollable(
scrollableState,
if (it) Orientation.Vertical else Orientation.Horizontal
)
},
*modifier("toggleable") { Modifier.toggleable(it) { capture(it) } },
*modifier("onFocusEvent") { Modifier.onFocusEvent { capture(it) } },
*modifier("selectable") { Modifier.selectable(it) { capture(it) } },
*modifier("focusTarget", true) { Modifier.focusTarget() },
*modifier("focusRequester") { Modifier.focusRequester(focusRequester) },
*modifier("border") {
Modifier.border(
if (it) 4.dp else 2.dp,
if (it) Color.Black else Color.Blue,
CircleShape
)
},
)
private val focusRequester = FocusRequester()
private val interactionSource = MutableInteractionSource()
private val indication = object : Indication {
@Composable
override fun rememberUpdatedInstance(
interactionSource: InteractionSource
): IndicationInstance {
return object : IndicationInstance {
override fun ContentDrawScope.drawIndication() {
drawContent()
}
}
}
}
private val draggableState = object : DraggableState {
override suspend fun drag(
dragPriority: MutatePriority,
block: suspend DragScope.() -> Unit
) {}
override fun dispatchRawDelta(delta: Float) {}
}
private val scrollableState = ScrollableState { it }
fun modifier(
name: String,
allCounts: Boolean = false,
modifierFn: (Boolean) -> Modifier
): Array<Array<Any>> {
return if (allCounts) {
arrayOf(
arrayOf(name, 1, modifierFn),
arrayOf(name, 10, modifierFn),
arrayOf(name, 100, modifierFn)
)
} else {
arrayOf(arrayOf(name, 10, modifierFn))
}
}
}
@get:Rule
val rule = ComposeBenchmarkRule()
/**
* DEFINITIONS
* ===========
*
* "base" - means that we are only including cost of composition and cost of setting the
* modifier on the layoutnode itself, but excluding Layout/Draw.
*
* "full" - means that we includ all costs from "base", but also including Layout/Draw.
*
* "hoisted" - means that the modifier chain's creation is not included in the benchmark.
* The hoisted measurement is representative of a developer "hoisting" the
* allocation of the benchmark up into a higher scope than the composable it is
* used in so that recomposition doesn't create a new one. The non-hoisted
* variants are more representative of developers making modifier chains inline
* in the composable body (most common).
*
* "reuse" - means that we change up the parameters of the modifier factory, so we are
* effectively measuring how well we are able to "reuse" the state from the
* "same" modifier, but with different parameters
*/
// base cost, including calling the modifier factory
@Test
fun base() = rule.measureModifier(
count = count,
reuse = false,
hoistCreation = false,
includeComposition = true,
includeLayout = false,
includeDraw = false,
modifierFn = modifierFn,
)
// base cost. without calling the modifier factory
@Test
fun baseHoisted() = rule.measureModifier(
count = count,
reuse = false,
hoistCreation = true,
includeComposition = true,
includeLayout = false,
includeDraw = false,
modifierFn = modifierFn,
)
// base cost. with different parameters (potential for reuse). includes calling the modifier factory.
@Test
fun baseReuse() = rule.measureModifier(
count = count,
reuse = true,
hoistCreation = true,
includeComposition = true,
includeLayout = false,
includeDraw = false,
modifierFn = modifierFn,
)
// base cost. with different parameters (potential for reuse). without calling the modifier factory
@Test
fun baseReuseHoisted() = rule.measureModifier(
count = count,
reuse = true,
hoistCreation = true,
includeComposition = true,
includeLayout = false,
includeDraw = false,
modifierFn = modifierFn,
)
// base cost + layout/draw, including calling the modifier factory
@Test
fun full() = rule.measureModifier(
count = count,
reuse = false,
hoistCreation = false,
includeComposition = true,
includeLayout = true,
includeDraw = true,
modifierFn = modifierFn,
)
// base cost + layout/draw. without calling the modifier factory
@Test
fun fullHoisted() = rule.measureModifier(
count = count,
reuse = false,
hoistCreation = true,
includeComposition = true,
includeLayout = true,
includeDraw = true,
modifierFn = modifierFn,
)
// base cost + layout/draw. with different parameters (potential for reuse). includes calling the modifier factory.
@Test
fun fullReuse() = rule.measureModifier(
count = count,
reuse = true,
hoistCreation = false,
includeComposition = true,
includeLayout = true,
includeDraw = true,
modifierFn = modifierFn,
)
// base cost + layout/draw. with different parameters (potential for reuse). without calling the modifier factory
@Test
fun fullReuseHoisted() = rule.measureModifier(
count = count,
reuse = true,
hoistCreation = true,
includeComposition = true,
includeLayout = true,
includeDraw = true,
modifierFn = modifierFn,
)
}
fun Modifier.emptyElement(): Modifier = this then object : Modifier.Element {}
@Suppress("UNUSED_PARAMETER")
fun capture(value: Any?) {} | compose/ui/ui/benchmark/src/androidTest/java/androidx/compose/ui/benchmark/ModifiersBenchmark.kt | 730551649 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ml
import org.junit.Test
class RsModelMetadataConsistencyTest {
@Test
fun `test model metadata consistency`() = RsMLRankingProvider().assertModelMetadataConsistent()
}
| ml-completion/src/test/kotlin/org/rust/ml/RsModelMetadataConsistencyTest.kt | 2099010199 |
package com.twitter.meil_mitu.twitter4hk.aclog.api.tweets
import com.twitter.meil_mitu.twitter4hk.AbsAPI
import com.twitter.meil_mitu.twitter4hk.AbsOauth
import com.twitter.meil_mitu.twitter4hk.aclog.converter.api.ITweetsConverter
class TweetsAPI<TAclogStatus>(
oauth: AbsOauth,
protected val json: ITweetsConverter<TAclogStatus>) : AbsAPI(oauth) {
fun show(id: Long) = Show(oauth, json, id)
fun lookup(ids: LongArray) = Lookup(oauth, json, ids)
fun userBest() = UserBest(oauth, json)
fun userTimeline() = UserTimeline(oauth, json)
fun userFavorites() = UserFavorites(oauth, json)
fun userFavoritedBy() = UserFavoritedBy(oauth, json)
}
| library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/aclog/api/tweets/TweetsAPI.kt | 941711543 |
/*
* This file is generated by jOOQ.
*/
package io.heapy.crm.komodo.store.postgres.tables
import io.heapy.crm.komodo.store.postgres.Public
import io.heapy.crm.komodo.store.postgres.tables.records.PersonRecord
import org.jooq.Field
import org.jooq.ForeignKey
import org.jooq.Name
import org.jooq.Record
import org.jooq.Row2
import org.jooq.Schema
import org.jooq.Table
import org.jooq.TableField
import org.jooq.TableOptions
import org.jooq.impl.DSL
import org.jooq.impl.Internal
import org.jooq.impl.SQLDataType
import org.jooq.impl.TableImpl
/**
* This class is generated by jOOQ.
*/
@Suppress("UNCHECKED_CAST")
open class Person(
alias: Name,
child: Table<out Record>?,
path: ForeignKey<out Record, PersonRecord>?,
aliased: Table<PersonRecord>?,
parameters: Array<Field<*>?>?
): TableImpl<PersonRecord>(
alias,
Public.PUBLIC,
child,
path,
aliased,
parameters,
DSL.comment(""),
TableOptions.table()
) {
companion object {
/**
* The reference instance of <code>public.person</code>
*/
val PERSON = Person()
}
/**
* The class holding records for this type
*/
override fun getRecordType(): Class<PersonRecord> = PersonRecord::class.java
/**
* The column <code>public.person.id</code>.
*/
val ID: TableField<PersonRecord, Int?> = createField(DSL.name("id"), SQLDataType.INTEGER.nullable(false), this, "")
/**
* The column <code>public.person.name</code>.
*/
val NAME: TableField<PersonRecord, String?> = createField(DSL.name("name"), SQLDataType.VARCHAR(100).nullable(false), this, "")
private constructor(alias: Name, aliased: Table<PersonRecord>?): this(alias, null, null, aliased, null)
private constructor(alias: Name, aliased: Table<PersonRecord>?, parameters: Array<Field<*>?>?): this(alias, null, null, aliased, parameters)
/**
* Create an aliased <code>public.person</code> table reference
*/
constructor(alias: String): this(DSL.name(alias))
/**
* Create an aliased <code>public.person</code> table reference
*/
constructor(alias: Name): this(alias, null)
/**
* Create a <code>public.person</code> table reference
*/
constructor(): this(DSL.name("person"), null)
constructor(child: Table<out Record>, key: ForeignKey<out Record, PersonRecord>): this(Internal.createPathAlias(child, key), child, key, PERSON, null)
override fun getSchema(): Schema = Public.PUBLIC
override fun `as`(alias: String): Person = Person(DSL.name(alias), this)
override fun `as`(alias: Name): Person = Person(alias, this)
/**
* Rename this table
*/
override fun rename(name: String): Person = Person(DSL.name(name), null)
/**
* Rename this table
*/
override fun rename(name: Name): Person = Person(name, null)
// -------------------------------------------------------------------------
// Row2 type methods
// -------------------------------------------------------------------------
override fun fieldsRow(): Row2<Int?, String?> = super.fieldsRow() as Row2<Int?, String?>
}
| backend-store-postgres/src/main/kotlin/io/heapy/crm/komodo/store/postgres/tables/Person.kt | 4099651594 |
package com.twitter.meil_mitu.twitter4hk.converter.api
interface IMutesConverter<TCursorIDs, TCursorUsers, TUser> : IMutesUsersConverter<TCursorIDs, TCursorUsers, TUser> {
} | library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/converter/api/IMutesConverter.kt | 3718521554 |
package org.jetbrains.dokka.Formats
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiParameter
import org.jetbrains.dokka.*
import org.jetbrains.dokka.ExternalDocumentationLinkResolver.Companion.DOKKA_PARAM_PREFIX
import org.jetbrains.kotlin.asJava.toLightElements
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.impl.EnumEntrySyntheticClassDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaPropertyDescriptor
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.descriptorUtil.isCompanionObject
import org.jetbrains.kotlin.types.KotlinType
class JavaLayoutHtmlPackageListService: PackageListService {
private fun StringBuilder.appendParam(name: String, value: String) {
append(DOKKA_PARAM_PREFIX)
append(name)
append(":")
appendln(value)
}
override fun formatPackageList(module: DocumentationModule): String {
val packages = module.members(NodeKind.Package).map { it.name }
return buildString {
appendParam("format", "java-layout-html")
appendParam("mode", "kotlin")
for (p in packages) {
appendln(p)
}
}
}
}
class JavaLayoutHtmlInboundLinkResolutionService(private val paramMap: Map<String, List<String>>,
private val resolutionFacade: DokkaResolutionFacade) : InboundExternalLinkResolutionService {
constructor(asJava: Boolean, resolutionFacade: DokkaResolutionFacade) :
this(mapOf("mode" to listOf(if (asJava) "java" else "kotlin")), resolutionFacade)
private val isJavaMode = paramMap["mode"]!!.single() == "java"
private fun getContainerPath(symbol: DeclarationDescriptor): String? {
return when (symbol) {
is PackageFragmentDescriptor -> symbol.fqName.asString().replace('.', '/') + "/"
is ClassifierDescriptor -> getContainerPath(symbol.findPackage()) + symbol.nameWithOuter() + ".html"
else -> null
}
}
private fun DeclarationDescriptor.findPackage(): PackageFragmentDescriptor =
generateSequence(this) { it.containingDeclaration }.filterIsInstance<PackageFragmentDescriptor>().first()
private fun ClassifierDescriptor.nameWithOuter(): String =
generateSequence(this) { it.containingDeclaration as? ClassifierDescriptor }
.toList().asReversed().joinToString(".") { it.name.asString() }
private fun getJavaPagePath(symbol: DeclarationDescriptor): String? {
val sourcePsi = symbol.sourcePsi() ?: return null
val source = (if (sourcePsi is KtDeclaration) {
sourcePsi.toLightElements().firstOrNull()
} else {
sourcePsi
}) as? PsiMember ?: return null
val desc = source.getJavaMemberDescriptor(resolutionFacade) ?: return null
return getPagePath(desc)
}
private fun getPagePath(symbol: DeclarationDescriptor): String? {
return when (symbol) {
is PackageFragmentDescriptor -> getContainerPath(symbol) + "package-summary.html"
is EnumEntrySyntheticClassDescriptor -> getContainerPath(symbol.containingDeclaration) + "#" + symbol.signatureForAnchorUrlEncoded()
is ClassifierDescriptor -> getContainerPath(symbol) + "#"
is FunctionDescriptor, is PropertyDescriptor -> getContainerPath(symbol.containingDeclaration!!) + "#" + symbol.signatureForAnchorUrlEncoded()
else -> null
}
}
private fun DeclarationDescriptor.signatureForAnchor(): String? {
fun ReceiverParameterDescriptor.extractReceiverName(): String {
var receiverClass: DeclarationDescriptor = type.constructor.declarationDescriptor!!
if (receiverClass.isCompanionObject()) {
receiverClass = receiverClass.containingDeclaration!!
} else if (receiverClass is TypeParameterDescriptor) {
val upperBoundClass = receiverClass.upperBounds.singleOrNull()?.constructor?.declarationDescriptor
if (upperBoundClass != null) {
receiverClass = upperBoundClass
}
}
return receiverClass.name.asString()
}
fun KotlinType.qualifiedNameForSignature(): String {
val desc = constructor.declarationDescriptor
return desc?.fqNameUnsafe?.asString() ?: "<ERROR TYPE NAME>"
}
fun StringBuilder.appendReceiverAndCompanion(desc: CallableDescriptor) {
if (desc.containingDeclaration.isCompanionObject()) {
append("Companion.")
}
desc.extensionReceiverParameter?.let {
append("(")
append(it.extractReceiverName())
append(").")
}
}
return when (this) {
is EnumEntrySyntheticClassDescriptor -> buildString {
append("ENUM_VALUE:")
append(name.asString())
}
is JavaMethodDescriptor -> buildString {
append(name.asString())
valueParameters.joinTo(this, prefix = "(", postfix = ")") {
val param = it.sourcePsi() as PsiParameter
param.type.canonicalText
}
}
is JavaPropertyDescriptor -> buildString {
append(name.asString())
}
is FunctionDescriptor -> buildString {
appendReceiverAndCompanion(this@signatureForAnchor)
append(name.asString())
valueParameters.joinTo(this, prefix = "(", postfix = ")") {
it.type.qualifiedNameForSignature()
}
}
is PropertyDescriptor -> buildString {
appendReceiverAndCompanion(this@signatureForAnchor)
append(name.asString())
append(":")
append(returnType?.qualifiedNameForSignature())
}
else -> null
}
}
private fun DeclarationDescriptor.signatureForAnchorUrlEncoded(): String? = signatureForAnchor()?.anchorEncoded()
override fun getPath(symbol: DeclarationDescriptor) = if (isJavaMode) getJavaPagePath(symbol) else getPagePath(symbol)
}
| core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt | 2224519585 |
package com.habitrpg.android.habitica.ui.fragments.skills
import android.app.Activity
import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.databinding.FragmentSkillsBinding
import com.habitrpg.android.habitica.extensions.subscribeWithErrorHandler
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.Skill
import com.habitrpg.android.habitica.models.responses.SkillResponse
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.ui.activities.SkillMemberActivity
import com.habitrpg.android.habitica.ui.activities.SkillTasksActivity
import com.habitrpg.android.habitica.ui.adapter.SkillsRecyclerViewAdapter
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import com.habitrpg.android.habitica.ui.helpers.SafeDefaultItemAnimator
import com.habitrpg.android.habitica.ui.viewmodels.MainUserViewModel
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar
import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar.Companion.showSnackbar
import io.reactivex.rxjava3.core.Flowable
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import javax.inject.Inject
class SkillsFragment : BaseMainFragment<FragmentSkillsBinding>() {
internal var adapter: SkillsRecyclerViewAdapter? = null
private var selectedSkill: Skill? = null
override var binding: FragmentSkillsBinding? = null
@Inject
lateinit var userViewModel: MainUserViewModel
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentSkillsBinding {
return FragmentSkillsBinding.inflate(inflater, container, false)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
adapter = SkillsRecyclerViewAdapter()
adapter?.useSkillEvents?.subscribeWithErrorHandler { onSkillSelected(it) }?.let { compositeSubscription.add(it) }
this.tutorialStepIdentifier = "skills"
this.tutorialText = getString(R.string.tutorial_skills)
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
userViewModel.user.observe(viewLifecycleOwner) { user ->
user?.let { checkUserLoadSkills(it) }
}
binding?.recyclerView?.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(activity)
binding?.recyclerView?.adapter = adapter
binding?.recyclerView?.itemAnimator = SafeDefaultItemAnimator()
}
private fun checkUserLoadSkills(user: User) {
if (adapter == null) {
return
}
adapter?.mana = user.stats?.mp ?: 0.0
adapter?.level = user.stats?.lvl ?: 0
adapter?.specialItems = user.items?.special
Flowable.combineLatest(
userRepository.getSkills(user),
userRepository.getSpecialItems(user),
{ skills, items ->
val allEntries = mutableListOf<Skill>()
for (skill in skills) {
allEntries.add(skill)
}
for (item in items) {
allEntries.add(item)
}
return@combineLatest allEntries
}
).subscribe({ skills -> adapter?.setSkillList(skills) }, RxErrorHandler.handleEmptyError())
}
private fun onSkillSelected(skill: Skill) {
when {
"special" == skill.habitClass -> {
selectedSkill = skill
val intent = Intent(activity, SkillMemberActivity::class.java)
memberSelectionResult.launch(intent)
}
skill.target == "task" -> {
selectedSkill = skill
val intent = Intent(activity, SkillTasksActivity::class.java)
taskSelectionResult.launch(intent)
}
else -> useSkill(skill)
}
}
private fun displaySkillResult(usedSkill: Skill?, response: SkillResponse) {
if (!isAdded) return
adapter?.mana = response.user?.stats?.mp ?: 0.0
val activity = activity ?: return
if ("special" == usedSkill?.habitClass) {
showSnackbar(activity.snackbarContainer, context?.getString(R.string.used_skill_without_mana, usedSkill.text), HabiticaSnackbar.SnackbarDisplayType.BLUE)
} else {
context?.let {
showSnackbar(
activity.snackbarContainer, null,
context?.getString(R.string.used_skill_without_mana, usedSkill?.text),
BitmapDrawable(resources, HabiticaIconsHelper.imageOfMagic()),
ContextCompat.getColor(it, R.color.blue_10), "-" + usedSkill?.mana,
HabiticaSnackbar.SnackbarDisplayType.BLUE
)
}
}
if (response.damage > 0) {
lifecycleScope.launch {
delay(2000L)
if (!isAdded) return@launch
showSnackbar(
activity.snackbarContainer, null,
context?.getString(R.string.caused_damage),
BitmapDrawable(resources, HabiticaIconsHelper.imageOfDamage()),
ContextCompat.getColor(activity, R.color.green_10), "+%.01f".format(response.damage),
HabiticaSnackbar.SnackbarDisplayType.SUCCESS
)
}
}
compositeSubscription.add(userRepository.retrieveUser(false).subscribe({ }, RxErrorHandler.handleEmptyError()))
}
private val taskSelectionResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == Activity.RESULT_OK) {
useSkill(selectedSkill, it.data?.getStringExtra("taskID"))
}
}
private val memberSelectionResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == Activity.RESULT_OK) {
useSkill(selectedSkill, it.data?.getStringExtra("member_id"))
}
}
private fun useSkill(skill: Skill?, taskId: String? = null) {
if (skill == null) {
return
}
val observable: Flowable<SkillResponse> = if (taskId != null) {
userRepository.useSkill(skill.key, skill.target, taskId)
} else {
userRepository.useSkill(skill.key, skill.target)
}
compositeSubscription.add(
observable.subscribe(
{ skillResponse -> this.displaySkillResult(skill, skillResponse) },
RxErrorHandler.handleEmptyError()
)
)
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/skills/SkillsFragment.kt | 2036697536 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.glance.appwidget.action
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.widget.RemoteViews
import androidx.annotation.DoNotInline
import androidx.annotation.RequiresApi
import androidx.glance.appwidget.TranslationContext
internal enum class ActionTrampolineType {
ACTIVITY, BROADCAST, SERVICE, FOREGROUND_SERVICE, CALLBACK
}
private const val ActionTrampolineScheme = "glance-action"
/**
* Wraps the "action intent" into an activity trampoline intent, where it will be invoked based on
* the type, with modifying its content.
*
* @see launchTrampolineAction
*/
internal fun Intent.applyTrampolineIntent(
translationContext: TranslationContext,
viewId: Int,
type: ActionTrampolineType
): Intent {
val target = if (type == ActionTrampolineType.ACTIVITY) {
ActionTrampolineActivity::class.java
} else {
InvisibleActionTrampolineActivity::class.java
}
return Intent(translationContext.context, target).also { intent ->
intent.data = createUniqueUri(translationContext, viewId, type)
intent.putExtra(ActionTypeKey, type.name)
intent.putExtra(ActionIntentKey, this)
}
}
internal fun createUniqueUri(
translationContext: TranslationContext,
viewId: Int,
type: ActionTrampolineType,
extraData: String = "",
): Uri = Uri.Builder().apply {
scheme(ActionTrampolineScheme)
path(type.name)
appendQueryParameter("appWidgetId", translationContext.appWidgetId.toString())
appendQueryParameter("viewId", viewId.toString())
appendQueryParameter("viewSize", translationContext.layoutSize.toString())
appendQueryParameter("extraData", extraData)
if (translationContext.isLazyCollectionDescendant) {
appendQueryParameter(
"lazyCollection",
translationContext.layoutCollectionViewId.toString()
)
appendQueryParameter(
"lazeViewItem",
translationContext.layoutCollectionItemId.toString()
)
}
}.build()
/**
* Unwraps and launches the action intent based on its type.
*
* @see applyTrampolineIntent
*/
@Suppress("DEPRECATION")
internal fun Activity.launchTrampolineAction(intent: Intent) {
val actionIntent = requireNotNull(intent.getParcelableExtra<Intent>(ActionIntentKey)) {
"List adapter activity trampoline invoked without specifying target intent."
}
if (intent.hasExtra(RemoteViews.EXTRA_CHECKED)) {
actionIntent.putExtra(
RemoteViews.EXTRA_CHECKED,
intent.getBooleanExtra(RemoteViews.EXTRA_CHECKED, false)
)
}
val type = requireNotNull(intent.getStringExtra(ActionTypeKey)) {
"List adapter activity trampoline invoked without trampoline type"
}
when (ActionTrampolineType.valueOf(type)) {
ActionTrampolineType.ACTIVITY -> startActivity(actionIntent)
ActionTrampolineType.BROADCAST, ActionTrampolineType.CALLBACK -> sendBroadcast(actionIntent)
ActionTrampolineType.SERVICE -> startService(actionIntent)
ActionTrampolineType.FOREGROUND_SERVICE -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ListAdapterTrampolineApi26Impl.startForegroundService(
context = this,
intent = actionIntent
)
} else {
startService(actionIntent)
}
}
}
finish()
}
private const val ActionTypeKey = "ACTION_TYPE"
private const val ActionIntentKey = "ACTION_INTENT"
@RequiresApi(Build.VERSION_CODES.O)
private object ListAdapterTrampolineApi26Impl {
@DoNotInline
fun startForegroundService(context: Context, intent: Intent) {
context.startForegroundService(intent)
}
}
| glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/action/ActionTrampoline.kt | 3910912732 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.util.lmdb.templates
import org.lwjgl.generator.*
import org.lwjgl.util.lmdb.*
val lmdb = "LMDB".nativeClass(LMDB_PACKAGE, prefix = "MDB", prefixMethod = "mdb_", library = "lwjgl_lmdb") {
nativeDirective(
"""#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4710 4711))
#endif""", beforeIncludes = true)
nativeDirective(
"""DISABLE_WARNINGS()
#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4172 4701 4706))
#endif
#define MDB_DEVEL 2
#include "lmdb.h"
ENABLE_WARNINGS()""")
documentation =
"""
Contains bindings to <a href="http://symas.com/mdb/">LMDB</a>, the Symas Lightning Memory-Mapped Database.
<h3>Getting Started</h3>
LMDB is compact, fast, powerful, and robust and implements a simplified variant of the BerkeleyDB (BDB) API.
Everything starts with an environment, created by #env_create(). Once created, this environment must also be opened with #env_open(). #env_open() gets
passed a name which is interpreted as a directory path. Note that this directory must exist already, it is not created for you. Within that directory,
a lock file and a storage file will be generated. If you don't want to use a directory, you can pass the #NOSUBDIR option, in which case the path you
provided is used directly as the data file, and another file with a "-lock" suffix added will be used for the lock file.
Once the environment is open, a transaction can be created within it using #txn_begin(). Transactions may be read-write or read-only, and read-write
transactions may be nested. A transaction must only be used by one thread at a time. Transactions are always required, even for read-only access. The
transaction provides a consistent view of the data.
Once a transaction has been created, a database can be opened within it using #dbi_open(). If only one database will ever be used in the environment, a
$NULL can be passed as the database name. For named databases, the #CREATE flag must be used to create the database if it doesn't already exist. Also,
#env_set_maxdbs() must be called after #env_create() and before #env_open() to set the maximum number of named databases you want to support.
Note: a single transaction can open multiple databases. Generally databases should only be opened once, by the first transaction in the process. After
the first transaction completes, the database handles can freely be used by all subsequent transactions.
Within a transaction, #get() and #put() can store single key/value pairs if that is all you need to do (but see {@code Cursors} below if you want to do
more).
A key/value pair is expressed as two ##MDBVal structures. This struct has two fields, {@code mv_size} and {@code mv_data}. The data is a {@code void}
pointer to an array of {@code mv_size} bytes.
Because LMDB is very efficient (and usually zero-copy), the data returned in an ##MDBVal structure may be memory-mapped straight from disk. In other
words <b>look but do not touch</b> (or {@code free()} for that matter). Once a transaction is closed, the values can no longer be used, so make a copy
if you need to keep them after that.
<h3>Cursors</h3>
To do more powerful things, we must use a cursor.
Within the transaction, a cursor can be created with #cursor_open(). With this cursor we can store/retrieve/delete (multiple) values using
#cursor_get(), #cursor_put(), and #cursor_del().
#cursor_get() positions itself depending on the cursor operation requested, and for some operations, on the supplied key. For example, to list all
key/value pairs in a database, use operation #FIRST for the first call to #cursor_get(), and #NEXT on subsequent calls, until the end is hit.
To retrieve all keys starting from a specified key value, use #SET.
When using #cursor_put(), either the function will position the cursor for you based on the {@code key}, or you can use operation #CURRENT to use the
current position of the cursor. Note that {@code key} must then match the current position's key.
<h4>Summarizing the Opening</h4>
So we have a cursor in a transaction which opened a database in an environment which is opened from a filesystem after it was separately created.
Or, we create an environment, open it from a filesystem, create a transaction within it, open a database within that transaction, and create a cursor
within all of the above.
<h3>Threads and Processes</h3>
LMDB uses POSIX locks on files, and these locks have issues if one process opens a file multiple times. Because of this, do not #env_open() a file
multiple times from a single process. Instead, share the LMDB environment that has opened the file across all threads. Otherwise, if a single process
opens the same environment multiple times, closing it once will remove all the locks held on it, and the other instances will be vulnerable to
corruption from other processes.
Also note that a transaction is tied to one thread by default using Thread Local Storage. If you want to pass read-only transactions across threads,
you can use the #NOTLS option on the environment.
<h3><Transactions, Rollbacks, etc.</h3>
To actually get anything done, a transaction must be committed using #txn_commit(). Alternatively, all of a transaction's operations can be discarded
using #txn_abort(). In a read-only transaction, any cursors will <b>not</b> automatically be freed. In a read-write transaction, all cursors will be
freed and must not be used again.
For read-only transactions, obviously there is nothing to commit to storage. The transaction still must eventually be aborted to close any database
handle(s) opened in it, or committed to keep the database handles around for reuse in new transactions.
In addition, as long as a transaction is open, a consistent view of the database is kept alive, which requires storage. A read-only transaction that no
longer requires this consistent view should be terminated (committed or aborted) when the view is no longer needed (but see below for an optimization).
There can be multiple simultaneously active read-only transactions but only one that can write. Once a single read-write transaction is opened, all
further attempts to begin one will block until the first one is committed or aborted. This has no effect on read-only transactions, however, and they
may continue to be opened at any time.
<h3>Duplicate Keys</h3>
#get() and #put() respectively have no and only some support for multiple key/value pairs with identical keys. If there are multiple values for a key,
#get() will only return the first value.
When multiple values for one key are required, pass the #DUPSORT flag to #dbi_open(). In an #DUPSORT database, by default #put() will not replace the
value for a key if the key existed already. Instead it will add the new value to the key. In addition, #del() will pay attention to the value field
too, allowing for specific values of a key to be deleted.
Finally, additional cursor operations become available for traversing through and retrieving duplicate values.
<h3>Some Optimization</h3>
If you frequently begin and abort read-only transactions, as an optimization, it is possible to only reset and renew a transaction.
#txn_reset() releases any old copies of data kept around for a read-only transaction. To reuse this reset transaction, call #txn_renew() on it. Any
cursors in this transaction must also be renewed using #cursor_renew().
Note that #txn_reset() is similar to #txn_abort() and will close any databases you opened within the transaction.
To permanently free a transaction, reset or not, use #txn_abort().
<h3>Cleaning Up</h3>
For read-only transactions, any cursors created within it must be closed using #cursor_close().
It is very rarely necessary to close a database handle, and in general they should just be left open.
"""
IntConstant(
"mmap at a fixed address (experimental).",
"FIXEDMAP"..0x01
)
IntConstant(
"No environment directory.",
"NOSUBDIR"..0x4000
)
IntConstant(
"Don't fsync after commit.",
"NOSYNC"..0x10000
)
IntConstant(
"Read only.",
"RDONLY"..0x20000
)
IntConstant(
"Don't fsync metapage after commit.",
"NOMETASYNC"..0x40000
)
IntConstant(
"Use writable mmap.",
"WRITEMAP"..0x80000
)
IntConstant(
"Use asynchronous msync when #WRITEMAP is used.",
"MAPASYNC"..0x100000
)
IntConstant(
"Tie reader locktable slots to {@code MDB_txn} objects instead of to threads.",
"NOTLS"..0x200000
)
IntConstant(
"Don't do any locking, caller must manage their own locks.",
"NOLOCK"..0x400000
)
IntConstant(
"Don't do readahead (no effect on Windows).",
"NORDAHEAD"..0x800000
)
IntConstant(
"Don't initialize malloc'd memory before writing to datafile.",
"NOMEMINIT"..0x1000000
)
IntConstant(
"Use reverse string keys.",
"REVERSEKEY"..0x02
)
IntConstant(
"Use sorted duplicates.",
"DUPSORT"..0x04
)
IntConstant(
"Numeric keys in native byte order: either {@code unsigned int} or {@code size_t}. The keys must all be of the same size.",
"INTEGERKEY"..0x08
)
IntConstant(
"With #DUPSORT, sorted dup items have fixed size.",
"DUPFIXED"..0x10
)
IntConstant(
"With #DUPSORT, dups are #INTEGERKEY -style integers.",
"INTEGERDUP"..0x20
)
IntConstant(
"With #DUPSORT, use reverse string dups.",
"REVERSEDUP"..0x40
)
IntConstant(
"Create DB if not already existing.",
"CREATE"..0x40000
)
IntConstant(
"Don't write if the key already exists.",
"NOOVERWRITE"..0x10
)
IntConstant(
"Remove all duplicate data items.",
"NODUPDATA"..0x20
)
IntConstant(
"Overwrite the current key/data pair.",
"CURRENT"..0x40
)
IntConstant(
"Just reserve space for data, don't copy it. Return a pointer to the reserved space.",
"RESERVE"..0x10000
)
IntConstant(
"Data is being appended, don't split full pages.",
"APPEND"..0x20000
)
IntConstant(
"Duplicate data is being appended, don't split full pages.",
"APPENDDUP"..0x40000
)
IntConstant(
"Store multiple data items in one call. Only for #DUPFIXED.",
"MULTIPLE"..0x80000
)
IntConstant(
"Omit free space from copy, and renumber all pages sequentially.",
"CP_COMPACT"..0x01
)
EnumConstant(
"MDB_cursor_op",
"FIRST".enum("Position at first key/data item."),
"FIRST_DUP".enum("Position at first data item of current key. Only for #DUPSORT."),
"GET_BOTH".enum("Position at key/data pair. Only for #DUPSORT."),
"GET_BOTH_RANGE".enum("position at key, nearest data. Only for #DUPSORT."),
"GET_CURRENT".enum("Return key/data at current cursor position."),
"GET_MULTIPLE".enum("Return key and up to a page of duplicate data items from current cursor position. Move cursor to prepare for #NEXT_MULTIPLE. Only for #DUPFIXED."),
"LAST".enum("Position at last key/data item."),
"LAST_DUP".enum("Position at last data item of current key. Only for #DUPSORT."),
"NEXT".enum("Position at next data item."),
"NEXT_DUP".enum("Position at next data item of current key. Only for #DUPSORT."),
"NEXT_MULTIPLE".enum(
"Return key and up to a page of duplicate data items from next cursor position. Move cursor to prepare for #NEXT_MULTIPLE. Only for #DUPFIXED."
),
"NEXT_NODUP".enum("Position at first data item of next key."),
"PREV".enum("Position at previous data item."),
"PREV_DUP".enum("Position at previous data item of current key. Only for #DUPSORT."),
"PREV_NODUP".enum("Position at last data item of previous key."),
"SET".enum("Position at specified key."),
"SET_KEY".enum("Position at specified key, return key + data."),
"SET_RANGE".enum("Position at first key greater than or equal to specified key."),
"PREV_MULTIPLE".enum("Position at previous page and return key and up to a page of duplicate data items. Only for #DUPFIXED.")
)
IntConstant(
"Successful result.",
"SUCCESS".."0"
)
IntConstant(
"Key/data pair already exists.",
"KEYEXIST".."-30799"
)
IntConstant(
"Key/data pair not found (EOF).",
"NOTFOUND".."-30798"
)
IntConstant(
"Requested page not found - this usually indicates corruption.",
"PAGE_NOTFOUND".."-30797"
)
IntConstant(
"Located page was wrong type.",
"CORRUPTED".."-30796"
)
IntConstant(
"Update of meta page failed or environment had fatal error.",
"PANIC".."-30795"
)
IntConstant(
"Environment version mismatch.",
"VERSION_MISMATCH".."-30794"
)
IntConstant(
"File is not a valid LMDB file.",
"INVALID".."-30793"
)
IntConstant(
"Environment mapsize reached.",
"MAP_FULL".."-30792"
)
IntConstant(
"Environment maxdbs reached.",
"DBS_FULL".."-30791"
)
IntConstant(
"Environment maxreaders reached.",
"READERS_FULL".."-30790"
)
IntConstant(
"Too many TLS keys in use - Windows only.",
"TLS_FULL".."-30789"
)
IntConstant(
"Txn has too many dirty pages.",
"TXN_FULL".."-30788"
)
IntConstant(
"Cursor stack too deep - internal error.",
"CURSOR_FULL".."-30787"
)
IntConstant(
"Page has not enough space - internal error.",
"PAGE_FULL".."-30786"
)
IntConstant(
"Database contents grew beyond environment mapsize.",
"MAP_RESIZED".."-30785"
)
IntConstant(
"""
The operation expects an #DUPSORT / #DUPFIXED database. Opening a named DB when the unnamed DB has #DUPSORT / #INTEGERKEY. Accessing a data record as a
database, or vice versa. The database was dropped and recreated with different flags.
""",
"INCOMPATIBLE".."-30784"
)
IntConstant(
"Invalid reuse of reader locktable slot.",
"BAD_RSLOT".."-30783"
)
IntConstant(
"Transaction must abort, has a child, or is invalid.",
"BAD_TXN".."-30782"
)
IntConstant(
"Unsupported size of key/DB name/data, or wrong #DUPFIXED size.",
"BAD_VALSIZE".."-30781"
)
IntConstant(
"The specified DBI was changed unexpectedly.",
"BAD_DBI".."-30780"
)
IntConstant(
"Unexpected problem - txn should abort.",
"PROBLEM".."-30779"
)
IntConstant(
"The last defined error code.",
"LAST_ERRCODE".."MDB_PROBLEM"
)
charASCII_p(
"version",
"Returns the LMDB library version information.",
Check(1)..nullable..int_p.OUT("major", "if non-$NULL, the library major version number is copied here"),
Check(1)..nullable..int_p.OUT("minor", "if non-$NULL, the library minor version number is copied here"),
Check(1)..nullable..int_p.OUT("patch", "if non-$NULL, the library patch version number is copied here"),
returnDoc = "the library version as a string"
)
charASCII_p(
"strerror",
"""
Returns a string describing a given error code.
This function is a superset of the ANSI C X3.159-1989 (ANSI C) strerror(3) function. If the error code is greater than or equal to 0, then the string
returned by the system function strerror(3) is returned. If the error code is less than 0, an error string corresponding to the LMDB library error is
returned.
""",
int.IN("err", "the error code"),
returnDoc = "the description of the error"
)
int(
"env_create",
"""
Creates an LMDB environment handle.
This function allocates memory for a {@code MDB_env} structure. To release the allocated memory and discard the handle, call #env_close(). Before the
handle may be used, it must be opened using #env_open(). Various other options may also need to be set before opening the handle, e.g.
#env_set_mapsize(), #env_set_maxreaders(), #env_set_maxdbs(), depending on usage requirements.
""",
Check(1)..MDB_env_pp.OUT("env", "the address where the new handle will be stored"),
returnDoc = "a non-zero error value on failure and 0 on success"
)
val env_open = int(
"env_open",
"""
Opens an environment handle.
If this function fails, #env_close() must be called to discard the {@code MDB_env} handle.
""",
MDB_env_p.IN("env", "an environment handle returned by #env_create()"),
const..charUTF8_p.IN("path", "the directory in which the database files reside. This directory must already exist and be writable."),
unsigned_int.IN(
"flags",
"""
Special options for this environment. This parameter must be set to 0 or by bitwise OR'ing together one or more of the values described here. Flags
set by #env_set_flags() are also used.
${ul(
"""#FIXEDMAP
Use a fixed address for the mmap region. This flag must be specified when creating the environment, and is stored persistently in the
environment. If successful, the memory map will always reside at the same virtual address and pointers used to reference data items in the
database will be constant across multiple invocations. This option may not always work, depending on how the operating system has allocated
memory to shared libraries and other uses.
The feature is highly experimental.
""",
"""#NOSUBDIR
By default, LMDB creates its environment in a directory whose pathname is given in {@code path}, and creates its data and lock files under that
directory. With this option, {@code path} is used as-is for the database main data file. The database lock file is the {@code path} with
"-lock" appended.
""",
"""#RDONLY
Open the environment in read-only mode. No write operations will be allowed. LMDB will still modify the lock file - except on read-only
filesystems, where LMDB does not use locks.
""",
"""#WRITEMAP
Use a writeable memory map unless #RDONLY is set. This uses fewer mallocs but loses protection from application bugs like wild pointer writes
and other bad updates into the database. This may be slightly faster for DBs that fit entirely in RAM, but is slower for DBs larger than RAM.
Incompatible with nested transactions.
Do not mix processes with and without #WRITEMAP on the same environment. This can defeat durability (#env_sync() etc).
""",
"""#NOMETASYNC
Flush system buffers to disk only once per transaction, omit the metadata flush. Defer that until the system flushes files to disk, or next
non-#RDONLY commit or #env_sync(). This optimization maintains database integrity, but a system crash may undo the last committed transaction.
I.e. it preserves the ACI (atomicity, consistency, isolation) but not D (durability) database property.
This flag may be changed at any time using #env_set_flags().
""",
"""#NOSYNC
Don't flush system buffers to disk when committing a transaction. This optimization means a system crash can corrupt the database or lose the
last transactions if buffers are not yet flushed to disk. The risk is governed by how often the system flushes dirty buffers to disk and how
often #env_sync() is called. However, if the filesystem preserves write order and the #WRITEMAP flag is not used, transactions exhibit ACI
(atomicity, consistency, isolation) properties and only lose D (durability). I.e. database integrity is maintained, but a system crash may undo
the final transactions. Note that (#NOSYNC | #WRITEMAP) leaves the system with no hint for when to write transactions to disk, unless
#env_sync() is called. (#MAPASYNC | #WRITEMAP) may be preferable.
This flag may be changed at any time using #env_set_flags().
""",
"""#MAPASYNC
When using #WRITEMAP, use asynchronous flushes to disk. As with #NOSYNC, a system crash can then corrupt the database or lose the last
transactions. Calling #env_sync() ensures on-disk database integrity until next commit.
This flag may be changed at any time using #env_set_flags().
""",
"""#NOTLS
Don't use Thread-Local Storage. Tie reader locktable slots to {@code MDB_txn} objects instead of to threads. I.e. #txn_reset() keeps the slot
reseved for the {@code MDB_txn} object. A thread may use parallel read-only transactions. A read-only transaction may span threads if the user
synchronizes its use. Applications that multiplex many user threads over individual OS threads need this option. Such an application must also
serialize the write transactions in an OS thread, since LMDB's write locking is unaware of the user threads.
""",
"""#NOLOCK
Don't do any locking. If concurrent access is anticipated, the caller must manage all concurrency itself. For proper operation the caller must
enforce single-writer semantics, and must ensure that no readers are using old transactions while a writer is active. The simplest approach is
to use an exclusive lock so that no readers may be active at all when a writer begins.
""",
"""#NORDAHEAD
Turn off readahead. Most operating systems perform readahead on read requests by default. This option turns it off if the OS supports it.
Turning it off may help random read performance when the DB is larger than RAM and system RAM is full.
The option is not implemented on Windows.
""",
"""#NOMEMINIT
Don't initialize malloc'd memory before writing to unused spaces in the data file. By default, memory for pages written to the data file is
obtained using malloc. While these pages may be reused in subsequent transactions, freshly malloc'd pages will be initialized to zeroes before
use. This avoids persisting leftover data from other code (that used the heap and subsequently freed the memory) into the data file. Note that
many other system libraries may allocate and free memory from the heap for arbitrary uses. E.g., stdio may use the heap for file I/O buffers.
This initialization step has a modest performance cost so some applications may want to disable it using this flag. This option can be a
problem for applications which handle sensitive data like passwords, and it makes memory checkers like Valgrind noisy. This flag is not needed
with #WRITEMAP, which writes directly to the mmap instead of using malloc for pages. The initialization is also skipped if #RESERVE is used;
the caller is expected to overwrite all of the memory that was reserved in that case.
This flag may be changed at any time using #env_set_flags().
"""
)}
"""
),
mdb_mode_t.IN(
"mode",
"""
The UNIX permissions to set on created files and semaphores.
This parameter is ignored on Windows.
"""
),
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"#VERSION_MISMATCH - the version of the LMDB library doesn't match the version that created the database environment.",
"#INVALID - the environment file headers are corrupted.",
"{@code ENOENT} - the directory specified by the path parameter doesn't exist.",
"{@code EACCES} - the user didn't have permission to access the environment files.",
"{@code EAGAIN} - the environment was locked by another process."
)}
"""
)
int(
"env_copy",
"""
Copies an LMDB environment to the specified path.
This function may be used to make a backup of an existing environment. No lockfile is created, since it gets recreated at need.
This call can trigger significant file size growth if run in parallel with write transactions, because it employs a read-only transaction.
""",
MDB_env_p.IN("env", "an environment handle returned by #env_create(). It must have already been opened successfully."),
const..charUTF8_p.IN(
"path",
"the directory in which the copy will reside. This directory must already exist and be writable but must otherwise be empty."
),
returnDoc = "a non-zero error value on failure and 0 on success"
)
/*int(
"env_copyfd",
"",
MDB_env_p.IN("env", ""),
mdb_filehandle_t.IN("fd", "")
)*/
int(
"env_copy2",
"""
Copies an LMDB environment to the specified path, with options.
This function may be used to make a backup of an existing environment. No lockfile is created, since it gets recreated at need.
This call can trigger significant file size growth if run in parallel with write transactions, because it employs a read-only transaction.
""",
MDB_env_p.IN("env", "an environment handle returned by #env_create(). It must have already been opened successfully."),
const..charUTF8_p.IN(
"path",
"the directory in which the copy will reside. This directory must already exist and be writable but must otherwise be empty."
),
unsigned_int.IN(
"flags",
"""
special options for this operation. This parameter must be set to 0 or by bitwise OR'ing together one or more of the values described here.
${ul(
"""
#CP_COMPACT - Perform compaction while copying: omit free pages and sequentially renumber all pages in output. This option consumes more CPU
and runs more slowly than the default.
"""
)}
"""
)
)
/*int(
"env_copyfd2",
"",
MDB_env_p.IN("env", ""),
mdb_filehandle_t.IN("fd", ""),
unsigned_int.IN("flags", "")
)*/
int(
"env_stat",
"Returns statistics about the LMDB environment.",
env_open["env"],
MDB_stat_p.OUT("stat", "the address of an ##MDBStat structure where the statistics will be copied"),
returnDoc = "a non-zero error value on failure and 0 on success"
)
int(
"env_info",
"Returns information about the LMDB environment.",
env_open["env"],
MDB_envinfo_p.OUT("stat", "the address of an ##MDBEnvInfo structure where the information will be copied"),
returnDoc = "a non-zero error value on failure and 0 on success"
)
int(
"env_sync",
"""
Flushes the data buffers to disk.
Data is always written to disk when #txn_commit() is called, but the operating system may keep it buffered. LMDB always flushes the OS buffers upon
commit as well, unless the environment was opened with #NOSYNC or in part #NOMETASYNC. This call is not valid if the environment was opened with
#RDONLY.
""",
env_open["env"],
intb.IN(
"force",
"""
if non-zero, force a synchronous flush. Otherwise if the environment has the #NOSYNC flag set the flushes will be omitted, and with #MAPASYNC they
will be asynchronous.
"""
),
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"{@code EACCES} - the environment is read-only.",
"{@code EINVAL} - an invalid parameter was specified.",
"{@code EIO} - an error occurred during synchronization."
)}
"""
)
void(
"env_close",
"""
Closes the environment and releases the memory map.
Only a single thread may call this function. All transactions, databases, and cursors must already be closed before calling this function. Attempts to
use any such handles after calling this function will cause a SIGSEGV. The environment handle will be freed and must not be used again after this call.
""",
env_open["env"]
)
int(
"env_set_flags",
"""
Sets environment flags.
This may be used to set some flags in addition to those from #env_open(), or to unset these flags. If several threads change the flags at the same
time, the result is undefined.
""",
env_open["env"],
unsigned_int.IN("flags", "the flags to change, bitwise OR'ed together"),
intb.IN("onoff", "a non-zero value sets the flags, zero clears them."),
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"{@code EINVAL} - an invalid parameter was specified."
)}
"""
)
int(
"env_get_flags",
"Gets environment flags.",
env_open["env"],
unsigned_int_p.OUT("flags", "the address of an integer to store the flags"),
returnDoc = "a non-zero error value on failure and 0 on success"
)
int(
"env_get_path",
"Returns the path that was used in #env_open().",
env_open["env"],
const..charUTF8_pp.IN(
"path",
"address of a string pointer to contain the path. This is the actual string in the environment, not a copy. It should not be altered in any way."
),
returnDoc = "a non-zero error value on failure and 0 on success"
)
/*int(
"env_get_fd",
"",
MDB_env_p.IN("env", ""),
mdb_filehandle_t_p.OUT("fd", "")
)*/
int(
"env_set_mapsize",
"""
Sets the size of the memory map to use for this environment.
The size should be a multiple of the OS page size. The default is 10485760 bytes. The size of the memory map is also the maximum size of the database.
The value should be chosen as large as possible, to accommodate future growth of the database.
This function should be called after #env_create() and before #env_open(). It may be called at later times if no transactions are active in this
process. Note that the library does not check for this condition, the caller must ensure it explicitly.
The new size takes effect immediately for the current process but will not be persisted to any others until a write transaction has been committed by
the current process. Also, only mapsize increases are persisted into the environment.
If the mapsize is increased by another process, and data has grown beyond the range of the current mapsize, #txn_begin() will return #MAP_RESIZED. This
function may be called with a size of zero to adopt the new size.
Any attempt to set a size smaller than the space already consumed by the environment will be silently changed to the current size of the used space.
""",
env_open["env"],
mdb_size_t.IN("size", "the size in bytes"),
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"{@code EINVAL} - an invalid parameter was specified, or the environment has an active write transaction."
)}
"""
)
int(
"env_set_maxreaders",
"""
Sets the maximum number of threads/reader slots for the environment.
This defines the number of slots in the lock table that is used to track readers in the environment. The default is 126.
Starting a read-only transaction normally ties a lock table slot to the current thread until the environment closes or the thread exits. If #NOTLS is
in use, #txn_begin() instead ties the slot to the {@code MDB_txn} object until it or the {@code MDB_env} object is destroyed.
This function may only be called after #env_create() and before #env_open().
""",
env_open["env"],
unsigned_int.IN("readers", "the maximum number of reader lock table slots"),
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"{@code EINVAL} - an invalid parameter was specified, or the environment is already open."
)}
"""
)
int(
"env_get_maxreaders",
"Gets the maximum number of threads/reader slots for the environment.",
env_open["env"],
unsigned_int_p.OUT("readers", "address of an integer to store the number of readers"),
returnDoc = "a non-zero error value on failure and 0 on success"
)
int(
"env_set_maxdbs",
"""
Sets the maximum number of named databases for the environment.
This function is only needed if multiple databases will be used in the environment. Simpler applications that use the environment as a single unnamed
database can ignore this option.
This function may only be called after #env_create() and before #env_open().
Currently a moderate number of slots are cheap but a huge number gets expensive: 7-120 words per transaction, and every #dbi_open() does a linear
search of the opened slots.
""",
env_open["env"],
MDB_dbi.IN("dbs", "the maximum number of databases"),
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"{@code EINVAL} - an invalid parameter was specified, or the environment is already open."
)}
"""
)
int(
"env_get_maxkeysize",
"""
Gets the maximum size of keys and #DUPSORT data we can write.
Depends on the compile-time constant {@code MAXKEYSIZE}. Default 511.
""",
env_open["env"]
)
int(
"env_set_userctx",
"Set application information associated with the {@code MDB_env}.",
env_open["env"],
voidptr.IN("ctx", "an arbitrary pointer for whatever the application needs")
)
voidptr(
"env_get_userctx",
"Gets the application information associated with the {@code MDB_env}.",
env_open["env"]
)
/*int(
"env_set_assert",
"",
MDB_env_p.IN("env", ""),
MDB_assert_func_p.OUT("func", "")
)*/
int(
"txn_begin",
"""
Creates a transaction for use with the environment.
The transaction handle may be discarded using #txn_abort() or #txn_commit().
A transaction and its cursors must only be used by a single thread, and a thread may only have a single transaction at a time. If #NOTLS is in use,
this does not apply to read-only transactions.
Cursors may not span transactions.
""",
env_open["env"],
nullable..MDB_txn_p.IN(
"parent",
"""
if this parameter is non-$NULL, the new transaction will be a nested transaction, with the transaction indicated by {@code parent} as its parent.
Transactions may be nested to any level. A parent transaction and its cursors may not issue any other operations than #txn_commit() and
#txn_abort() while it has active child transactions.
"""
),
unsigned_int.IN(
"flags",
"""
special options for this transaction. This parameter must be set to 0 or by bitwise OR'ing together one or more of the values described here.
${ul(
"#RDONLY - This transaction will not perform any write operations.",
"#NOSYNC - Don't flush system buffers to disk when committing this transaction.",
"#NOMETASYNC - Flush system buffers but omit metadata flush when committing this transaction."
)}
"""
),
MDB_txn_pp.OUT("txn", "address where the new {@code MDB_txn} handle will be stored"),
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"#PANIC - a fatal error occurred earlier and the environment must be shut down.",
"""
#MAP_RESIZED - another process wrote data beyond this {@code MDB_env}'s mapsize and this environment's map must be resized as well. See
#env_set_mapsize().
""",
"#READERS_FULL - a read-only transaction was requested and the reader lock table is full. See #env_set_maxreaders().",
"{@code ENOMEM} - out of memory."
)}
"""
)
val txn_env = MDB_env_p(
"txn_env",
"Returns the transaction's {@code MDB_env}.",
MDB_txn_p.IN("txn", "a transaction handle returned by #txn_begin().")
)
mdb_size_t(
"txn_id",
"""
Returns the transaction's ID.
This returns the identifier associated with this transaction. For a read-only transaction, this corresponds to the snapshot being read; concurrent
readers will frequently have the same transaction ID.
""",
txn_env["txn"],
returnDoc = "a transaction ID, valid if input is an active transaction"
)
int(
"txn_commit",
"""
Commits all the operations of a transaction into the database.
The transaction handle is freed. It and its cursors must not be used again after this call, except with #cursor_renew().
Earlier documentation incorrectly said all cursors would be freed. Only write-transactions free cursors.
""",
txn_env["txn"],
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"{@code EINVAL} - an invalid parameter was specified.",
"{@code ENOSPC} - no more disk space.",
"{@code EIO} - a low-level I/O error occurred while writing.",
"{@code ENOMEM} - out of memory."
)}
"""
)
void(
"txn_abort",
"""
Abandons all the operations of the transaction instead of saving them.
The transaction handle is freed. It and its cursors must not be used again after this call, except with #cursor_renew().
Earlier documentation incorrectly said all cursors would be freed. Only write-transactions free cursors.
"""",
txn_env["txn"]
)
void(
"txn_reset",
"""
Resets a read-only transaction.
Aborts the transaction like #txn_abort(), but keeps the transaction handle. #txn_renew() may reuse the handle. This saves allocation overhead if the
process will start a new read-only transaction soon, and also locking overhead if #NOTLS is in use. The reader table lock is released, but the table
slot stays tied to its thread or {@code MDB_txn}. Use #txn_abort() to discard a reset handle, and to free its lock table slot if #NOTLS is in use.
Cursors opened within the transaction must not be used again after this call, except with #cursor_renew().
Reader locks generally don't interfere with writers, but they keep old versions of database pages allocated. Thus they prevent the old pages from being
reused when writers commit new data, and so under heavy load the database size may grow much more rapidly than otherwise.
""",
txn_env["txn"]
)
int(
"txn_renew",
"""
Renews a read-only transaction.
This acquires a new reader lock for a transaction handle that had been released by #txn_reset(). It must be called before a reset transaction may be
used again.
""",
txn_env["txn"]
)
int(
"dbi_open",
"""
Opens a database in the environment.
A database handle denotes the name and parameters of a database, independently of whether such a database exists. The database handle may be discarded
by calling #dbi_close(). The old database handle is returned if the database was already open. The handle may only be closed once.
The database handle will be private to the current transaction until the transaction is successfully committed. If the transaction is aborted the
handle will be closed automatically. After a successful commit the handle will reside in the shared environment, and may be used by other transactions.
This function must not be called from multiple concurrent transactions in the same process. A transaction that uses this function must finish (either
commit or abort) before any other transaction in the process may use this function.
To use named databases (with {@code name} != $NULL), #env_set_maxdbs() must be called before opening the environment. Database names are keys in the
unnamed database, and may be read but not written.
""",
txn_env["txn"],
nullable..const..charUTF8_p.IN(
"name",
"the name of the database to open. If only a single database is needed in the environment, this value may be $NULL."
),
unsigned_int.IN(
"flags",
"""
special options for this database. This parameter must be set to 0 or by bitwise OR'ing together one or more of the values described here.
${ul(
"""#REVERSEKEY
Keys are strings to be compared in reverse order, from the end of the strings to the beginning. By default, Keys are treated as strings and
compared from beginning to end.
""",
"""#DUPSORT
Duplicate keys may be used in the database. (Or, from another perspective, keys may have multiple data items, stored in sorted order.) By
default keys must be unique and may have only a single data item.
""",
"""#INTEGERKEY
Keys are binary integers in native byte order, either {@code unsigned int} or {@code mdb_size_t}, and will be sorted as such. The keys must all be
of the same size.
""",
"""#DUPFIXED
This flag may only be used in combination with #DUPSORT. This option tells the library that the data items for this database are all the same
size, which allows further optimizations in storage and retrieval. When all data items are the same size, the #GET_MULTIPLE and #NEXT_MULTIPLE
cursor operations may be used to retrieve multiple items at once.
""",
"""#INTEGERDUP
This option specifies that duplicate data items are binary integers, similar to #INTEGERKEY keys.
""",
"""#REVERSEDUP
This option specifies that duplicate data items should be compared as strings in reverse order.
""",
"""#CREATE
Create the named database if it doesn't exist. This option is not allowed in a read-only transaction or a read-only environment.
"""
)}
"""
),
MDB_dbi_p.OUT("dbi", "address where the new {@code MDB_dbi} handle will be stored"),
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"#NOTFOUND - the specified database doesn't exist in the environment and #CREATE was not specified.",
"#DBS_FULL - too many databases have been opened. See #env_set_maxdbs()."
)}
"""
)
val stat = int(
"stat",
"Retrieves statistics for a database.",
txn_env["txn"],
MDB_dbi.IN("dbi", "a database handle returned by #dbi_open()"),
MDB_stat_p.OUT("stat", "the address of an ##MDBStat structure where the statistics will be copied")
)
int(
"dbi_flags",
"Retrieve the DB flags for a database handle.",
txn_env["txn"],
stat["dbi"],
unsigned_int_p.OUT("flags", "address where the flags will be returned")
)
void(
"dbi_close",
"""
Closes a database handle. Normally unnecessary. Use with care:
This call is not mutex protected. Handles should only be closed by a single thread, and only if no other threads are going to reference the database
handle or one of its cursors any further. Do not close a handle if an existing transaction has modified its database. Doing so can cause misbehavior
from database corruption to errors like #BAD_VALSIZE (since the DB name is gone).
Closing a database handle is not necessary, but lets #dbi_open() reuse the handle value. Usually it's better to set a bigger #env_set_maxdbs(), unless
that value would be large.
""",
env_open["env"],
stat["dbi"]
)
int(
"drop",
"""
Empties or deletes+closes a database.
See #dbi_close() for restrictions about closing the DB handle.
""",
txn_env["txn"],
stat["dbi"],
intb.IN("del", "0 to empty the DB, 1 to delete it from the environment and close the DB handle")
)
int(
"set_compare",
"""
Sets a custom key comparison function for a database.
The comparison function is called whenever it is necessary to compare a key specified by the application with a key currently stored in the database.
If no comparison function is specified, and no special key flags were specified with #dbi_open(), the keys are compared lexically, with shorter keys
collating before longer keys.
This function must be called before any data access functions are used, otherwise data corruption may occur. The same comparison function must be used
by every program accessing the database, every time the database is used.
""",
txn_env["txn"],
stat["dbi"],
MDB_cmp_func.IN("cmp", "an ##MDBCmpFunc function")
)
int(
"set_dupsort",
"""
Sets a custom data comparison function for a #DUPSORT database.
This comparison function is called whenever it is necessary to compare a data item specified by the application with a data item currently stored in
the database.
This function only takes effect if the database was opened with the #DUPSORT flag.
If no comparison function is specified, and no special key flags were specified with #dbi_open(), the data items are compared lexically, with shorter
items collating before longer items.
This function must be called before any data access functions are used, otherwise data corruption may occur. The same comparison function must be used
by every program accessing the database, every time the database is used.
""",
txn_env["txn"],
stat["dbi"],
MDB_cmp_func.IN("cmp", "an ##MDBCmpFunc function")
)
int(
"set_relfunc",
"""
Sets a relocation function for a #FIXEDMAP database.
The relocation function is called whenever it is necessary to move the data of an item to a different position in the database (e.g. through tree
balancing operations, shifts as a result of adds or deletes, etc.). It is intended to allow address/position-dependent data items to be stored in a
database in an environment opened with the #FIXEDMAP option.
Currently the relocation feature is unimplemented and setting this function has no effect.
""",
txn_env["txn"],
stat["dbi"],
MDB_rel_func.IN("rel", "an ##MDBRelFunc function")
)
int(
"set_relctx",
"""
Sets a context pointer for a #FIXEDMAP database's relocation function.
See #set_relfunc() and ##MDBRelFunc for more details.
""",
txn_env["txn"],
stat["dbi"],
voidptr.IN(
"ctx",
"""
an arbitrary pointer for whatever the application needs. It will be passed to the callback function set by ##MDBRelFunc as its {@code relctx}
parameter whenever the callback is invoked.
"""
)
)
int(
"get",
"""
Gets items from a database.
This function retrieves key/data pairs from the database. The address and length of the data associated with the specified {@code key} are returned in
the structure to which {@code data} refers.
If the database supports duplicate keys (#DUPSORT) then the first data item for the key will be returned. Retrieval of other items requires the use of
#cursor_get().
The memory pointed to by the returned values is owned by the database. The caller need not dispose of the memory, and may not modify it in any way. For
values returned in a read-only transaction any modification attempts will cause a SIGSEGV.
Values returned from the database are valid only until a subsequent update operation, or the end of the transaction.
""",
txn_env["txn"],
stat["dbi"],
MDB_val_p.IN("key", "the key to search for in the database"),
MDB_val_p.OUT("data", "the data corresponding to the key")
)
int(
"put",
"""
Stores items into a database.
This function stores key/data pairs in the database. The default behavior is to enter the new key/data pair, replacing any previously existing key if
duplicates are disallowed, or adding a duplicate data item if duplicates are allowed (#DUPSORT).
""",
txn_env["txn"],
stat["dbi"],
MDB_val_p.IN("key", "the key to store in the database"),
MDB_val_p.IN("data", "the data to store"),
unsigned_int.IN(
"flags",
"""
special options for this operation. This parameter must be set to 0 or by bitwise OR'ing together one or more of the values described here.
${ul(
"""
#NODUPDATA - enter the new key/data pair only if it does not already appear in the database. This flag may only be specified if the database
was opened with #DUPSORT. The function will return #KEYEXIST if the key/data pair already appears in the database.
""",
"""
#NOOVERWRITE - enter the new key/data pair only if the key does not already appear in the database. The function will return #KEYEXIST if the
key already appears in the database, even if the database supports duplicates (#DUPSORT). The {@code data} parameter will be set to point to
the existing item.
""",
"""
#RESERVE - reserve space for data of the given size, but don't copy the given data. Instead, return a pointer to the reserved space, which the
caller can fill in later - before the next update operation or the transaction ends. This saves an extra memcpy if the data is being generated
later.
LMDB does nothing else with this memory, the caller is expected to modify all of the space requested. This flag must not be specified if the
database was opened with #DUPSORT.
""",
"""
#APPEND - append the given key/data pair to the end of the database. This option allows fast bulk loading when keys are already known to be in
the correct order. Loading unsorted keys with this flag will cause a #KEYEXIST error.
""",
"#APPENDDUP - as above, but for sorted dup data."
)}
"""
)
)
int(
"del",
"""
Deletes items from a database.
This function removes key/data pairs from the database. If the database does not support sorted duplicate data items (#DUPSORT) the data parameter is
ignored.
If the database supports sorted duplicates and the data parameter is $NULL, all of the duplicate data items for the key will be deleted. Otherwise, if
the data parameter is non-$NULL only the matching data item will be deleted.
This function will return #NOTFOUND if the specified key/data pair is not in the database.
""",
txn_env["txn"],
stat["dbi"],
MDB_val_p.IN("key", "the key to delete from the database"),
nullable..MDB_val_p.IN("data", "the data to delete")
)
int(
"cursor_open",
"""
Creates a cursor handle.
A cursor is associated with a specific transaction and database. A cursor cannot be used when its database handle is closed. Nor when its transaction
has ended, except with #cursor_renew().
It can be discarded with #cursor_close().
A cursor in a write-transaction can be closed before its transaction ends, and will otherwise be closed when its transaction ends.
A cursor in a read-only transaction must be closed explicitly, before or after its transaction ends. It can be reused with #cursor_renew() before
finally closing it.
Earlier documentation said that cursors in every transaction were closed when the transaction committed or aborted.
""",
txn_env["txn"],
stat["dbi"],
MDB_cursor_pp.OUT("cursor", "address where the new {@code MDB_cursor} handle will be stored")
)
val cursor_close = void(
"cursor_close",
"""
Closes a cursor handle.
The cursor handle will be freed and must not be used again after this call. Its transaction must still be live if it is a write-transaction.
""",
MDB_cursor_p.OUT("cursor", "a cursor handle returned by #cursor_open()")
)
int(
"cursor_renew",
"""
Renews a cursor handle.
A cursor is associated with a specific transaction and database. Cursors that are only used in read-only transactions may be re-used, to avoid
unnecessary malloc/free overhead. The cursor may be associated with a new read-only transaction, and referencing the same database handle as it was
created with. This may be done whether the previous transaction is live or dead.
""",
txn_env["txn"],
cursor_close["cursor"]
)
MDB_txn_p(
"cursor_txn",
"Returns the cursor's transaction handle.",
cursor_close["cursor"]
)
MDB_dbi(
"cursor_dbi",
"Return the cursor's database handle.",
cursor_close["cursor"]
)
int(
"cursor_get",
"""
Retrieves by cursor.
This function retrieves key/data pairs from the database. The address and length of the key are returned in the object to which {@code key} refers
(except for the case of the #SET option, in which the {@code key} object is unchanged), and the address and length of the data are returned in the
object to which {@code data} refers.
See #get() for restrictions on using the output values.
""",
cursor_close["cursor"],
MDB_val_p.IN("key", "the key for a retrieved item"),
MDB_val_p.OUT("data", "the data of a retrieved item"),
MDB_cursor_op.IN("op", "a cursor operation {@code MDB_cursor_op}")
)
int(
"cursor_put",
"""
Stores by cursor.
This function stores key/data pairs into the database. The cursor is positioned at the new item, or on failure usually near it.
Earlier documentation incorrectly said errors would leave the state of the cursor unchanged.
""",
cursor_close["cursor"],
MDB_val_p.IN("key", "the key operated on"),
MDB_val_p.IN("data", "the data operated on"),
unsigned_int.IN(
"flags",
"""
options for this operation. This parameter must be set to 0 or one of the values described here.
${ul(
"""
#CURRENT - replace the item at the current cursor position. The {@code key} parameter must still be provided, and must match it. If using
sorted duplicates (#DUPSORT) the data item must still sort into the same place. This is intended to be used when the new data is the same size
as the old. Otherwise it will simply perform a delete of the old record followed by an insert.
""",
"""
#NODUPDATA - enter the new key/data pair only if it does not already appear in the database. This flag may only be specified if the database
was opened with #DUPSORT. The function will return #KEYEXIST if the key/data pair already appears in the database.
""",
"""
#NOOVERWRITE - enter the new key/data pair only if the key does not already appear in the database. The function will return #KEYEXIST if
the key already appears in the database, even if the database supports duplicates (#DUPSORT).
""",
"""
#RESERVE - reserve space for data of the given size, but don't copy the given data. Instead, return a pointer to the reserved space, which
the caller can fill in later - before the next update operation or the transaction ends. This saves an extra memcpy if the data is being
generated later. This flag must not be specified if the database was opened with #DUPSORT.
""",
"""
#APPEND - append the given key/data pair to the end of the database. No key comparisons are performed. This option allows fast bulk loading
when keys are already known to be in the correct order. Loading unsorted keys with this flag will cause a #KEYEXIST error.
""",
"#APPENDDUP - as above, but for sorted dup data.",
"""
#MULTIPLE - store multiple contiguous data elements in a single request. This flag may only be specified if the database was opened with
#DUPFIXED. The {@code data} argument must be an array of two ##MDBVal. The {@code mv_size} of the first {@code MDBVal} must be the size of a
single data element. The {@code mv_data} of the first {@code MDBVal} must point to the beginning of the array of contiguous data elements. The
{@code mv_size} of the second {@code MDBVal} must be the count of the number of data elements to store. On return this field will be set to the
count of the number of elements actually written. The {@code mv_data} of the second {@code MDBVal} is unused.
"""
)}
"""
)
)
int(
"cursor_del",
"""
Deletes current key/data pair.
This function deletes the key/data pair to which the cursor refers.
""",
cursor_close["cursor"],
unsigned_int.IN(
"flags",
"""
options for this operation. This parameter must be set to 0 or one of the values described here.
${ul(
"#NODUPDATA - delete all of the data items for the current key. This flag may only be specified if the database was opened with #DUPSORT."
)}
"""
)
)
int(
"cursor_count",
"""
Returns count of duplicates for current key.
This call is only valid on databases that support sorted duplicate data items #DUPSORT.
""",
cursor_close["cursor"],
mdb_size_t_p.OUT("countp", "address where the count will be stored")
)
int(
"cmp",
"""
Compares two data items according to a particular database.
This returns a comparison as if the two data items were keys in the specified database.
""",
txn_env["txn"],
stat["dbi"],
const..MDB_val_p.IN("a", "the first item to compare"),
const..MDB_val_p.IN("b", "the second item to compare"),
returnDoc = "< 0 if a < b, 0 if a == b, > 0 if a > b"
)
int(
"dcmp",
"""
Compares two data items according to a particular database.
This returns a comparison as if the two items were data items of the specified database. The database must have the #DUPSORT flag.
""",
txn_env["txn"],
stat["dbi"],
const..MDB_val_p.IN("a", "the first item to compare"),
const..MDB_val_p.IN("b", "the second item to compare"),
returnDoc = "< 0 if a < b, 0 if a == b, > 0 if a > b"
)
int(
"reader_list",
"Dumps the entries in the reader lock table.",
env_open["env"],
MDB_msg_func.IN("func", "an ##MDBMsgFunc function"),
voidptr.IN("ctx", "anything the message function needs")
)
int(
"reader_check",
"Checks for stale entries in the reader lock table.",
env_open["env"],
int_p.OUT("dead", "number of stale slots that were cleared")
)
} | modules/templates/src/main/kotlin/org/lwjgl/util/lmdb/templates/lmdb.kt | 2110357377 |
package com.baeldung.springreactivekotlin
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.MediaType.APPLICATION_JSON
import org.springframework.http.MediaType.TEXT_HTML
import org.springframework.web.reactive.function.server.router
@Configuration
class HomeSensorsRouters(private val handler: HomeSensorsHandler) {
@Bean
fun roomsRouter() = router {
(accept(TEXT_HTML) and "/room").nest {
GET("/light", handler::getLightReading)
POST("/light", handler::setLight)
}
}
@Bean
fun deviceRouter() = router {
accept(TEXT_HTML).nest {
(GET("/device/") or GET("/devices/")).invoke(handler::getAllDevices)
GET("/device/{id}", handler::getDeviceReadings)
}
(accept(APPLICATION_JSON) and "/api").nest {
(GET("/device/") or GET("/devices/")).invoke(handler::getAllDeviceApi)
POST("/device/", handler::setDeviceReadingApi)
}
}
}
| projects/tutorials-master/tutorials-master/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsRouters.kt | 4107913887 |
fun hello(moParam : Int) : Int {
val more = 12
val test = object {
val sss = mo<caret>
}
return 12
}
// EXIST: more
// EXIST: moParam | kotlin-eclipse-ui-test/testData/completion/basic/common/InLocalObjectDeclaration.kt | 3211165103 |
class Vector constructor (val myCoo: DoubleArray) {
constructor(len: Int): this(DoubleArray(len))
constructor(vec: Vector): this(DoubleArray(vec.myCoo.size) { p: Int -> vec.myCoo[p]})
fun reflectWRT(y: Vector): Vector = add(y, mul(this, -2 * prod(this, y) / len2(this)))
override fun equals(o: Any?): Boolean {
if (o == null) return false
if (o is Vector) return len(add(this, minus(o))) < EPS
throw IllegalArgumentException()
}
override fun hashCode(): Int = myCoo.fold(0) { result: Int, p: Double -> result * 31 + Math.round(p / EPS).toInt()}
override fun toString(): String {
val result = StringBuilder("{")
for (i in myCoo.indices) {
result.append(fmt(myCoo[i]))
if (i < myCoo.size - 1) result.append(", ")
}
return result.toString() + "}"
}
fun getReflection(): Matrix {
val n = myCoo.size
val m = Array(n) { DoubleArray(n) }
var d = len2(this)
if (Math.abs(d) < EPS) throw IllegalArgumentException("Can not reflect w.r.t. zero vector.")
d = -2 / d
for (i in 0 until n) { //column iterator
val c = d * myCoo[i]
for (j in 0 until n) { //row iterator
m[j][i] = c * myCoo[j]
if (i == j) m[j][i] += 1.0
}
}
return Matrix(m)
}
companion object {
val EPS = 0.01
fun fmt(d: Double): String {
return if (Math.abs(d - d.toLong()) <= 0.00001)
String.format("%d", d.toLong())
else
String.format("%e", d)
}
fun add(a: Vector, b: Vector): Vector {
if (a.myCoo.size != b.myCoo.size) throw IllegalArgumentException()
val result = Vector(a.myCoo.size)
for (i in a.myCoo.indices) result.myCoo[i] = a.myCoo[i] + b.myCoo[i]
return result
}
fun mul(a: Vector, c: Double): Vector {
val result = Vector(a.myCoo.size)
for (i in a.myCoo.indices) result.myCoo[i] = c * a.myCoo[i]
return result
}
fun minus(a: Vector): Vector = mul(a, -1.0)
fun minus(a: Vector, b: Vector) = add(a, minus(b))
fun len2(a: Vector): Double = prod(a, a)
fun len(a: Vector): Double = Math.sqrt(len2(a))
fun prod(a: Vector, b: Vector): Double {
if (a.myCoo.size != b.myCoo.size) throw IllegalArgumentException()
return a.myCoo.zip(b.myCoo).fold(0.0, {result: Double, p: Pair<Double, Double> -> result + p.first * p.second })
}
fun angle(a: Vector, b: Vector): Double = prod(a, b) / (len(a) * len(b))
fun orthogonal(a: Vector, b: Vector): Boolean = Math.abs(angle(a, b)) < EPS
}
} | src/primitives/Vector.kt | 1409652081 |
package com.wealthfront.magellan.sample
import android.content.Context
import com.wealthfront.magellan.navigation.LoggingNavigableListener
import com.wealthfront.magellan.navigation.NavigationTraverser
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class AppModule(private val context: Context) {
@Provides
@Singleton
fun provideExpedition(): Expedition {
return Expedition()
}
@Provides
@Singleton
fun provideNavigationTraverser(expedition: Expedition): NavigationTraverser {
return NavigationTraverser(expedition)
}
@Provides
@Singleton
fun provideLoggingNavigableListener(navigationTraverser: NavigationTraverser): LoggingNavigableListener {
return LoggingNavigableListener(navigationTraverser)
}
@Provides
fun provideContext() = context
}
| magellan-sample/src/main/java/com/wealthfront/magellan/sample/AppModule.kt | 3424259599 |
package org.wordpress.aztec.demo
import org.wordpress.aztec.AztecTextFormat
import org.wordpress.aztec.ITextFormat
import org.wordpress.aztec.toolbar.IToolbarAction
import org.wordpress.aztec.toolbar.ToolbarActionType
enum class MediaToolbarAction constructor(
override val buttonId: Int,
override val buttonDrawableRes: Int,
override val actionType: ToolbarActionType,
override val textFormats: Set<ITextFormat> = setOf()
) : IToolbarAction {
GALLERY(R.id.media_bar_button_gallery, R.drawable.media_bar_button_image_multiple_selector, ToolbarActionType.OTHER, setOf(AztecTextFormat.FORMAT_NONE)),
CAMERA(R.id.media_bar_button_camera, R.drawable.media_bar_button_camera_selector, ToolbarActionType.OTHER, setOf(AztecTextFormat.FORMAT_NONE))
}
| app/src/main/kotlin/org/wordpress/aztec/demo/MediaToolbarAction.kt | 529623055 |
package bjzhou.coolapk.app.ui.base
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import bjzhou.coolapk.app.R
import java.util.*
open class BaseActivity : AppCompatActivity() {
private val REQUEST_PERMISSION = Random().nextInt(65535)
private var mPermissionListener: ((permission: String, succeed: Boolean) -> Unit)? = null
val currentFragment: Fragment
get() = supportFragmentManager.findFragmentById(R.id.container)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
fun setFragment(fragment: Fragment) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit()
}
fun addFragment(fragment: Fragment) {
supportFragmentManager.beginTransaction()
.add(R.id.container, fragment)
.commit()
}
fun checkPermissions(listener: (permission: String, succeed: Boolean) -> Unit, vararg permissions: String) {
this.mPermissionListener = listener
val needRequests = ArrayList<String>()
val needShowRationale = ArrayList<String>()
for (permission in permissions) {
val granted = ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
val shouldRational = ActivityCompat.shouldShowRequestPermissionRationale(this, permission)
if (!granted && !shouldRational) {
needRequests.add(permission)
} else if (!granted) {
needShowRationale.add(permission)
} else {
listener(permission, true)
}
}
if (needRequests.isNotEmpty()) {
ActivityCompat.requestPermissions(this, needRequests.toTypedArray(), REQUEST_PERMISSION)
}
if (needShowRationale.isNotEmpty()) {
Snackbar.make(window.decorView.rootView, getRequestPermissionRationaleMessage(), Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, {
ActivityCompat.requestPermissions(this, needShowRationale.toTypedArray(), REQUEST_PERMISSION)
})
.show()
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (requestCode == REQUEST_PERMISSION) {
for (i in permissions.indices) {
mPermissionListener?.invoke(permissions[i], grantResults[i] == PackageManager.PERMISSION_GRANTED)
}
}
}
protected fun getRequestPermissionRationaleMessage(): CharSequence {
return "Need permission granted to continue."
}
protected fun setActionBarTitle(resId: Int) {
supportActionBar?.setTitle(resId)
}
protected fun showHome(showHome: Boolean) {
supportActionBar?.setDisplayShowHomeEnabled(showHome)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}
}
| app/src/main/kotlin/bjzhou/coolapk/app/ui/base/BaseActivity.kt | 326201144 |
/*
* Copyright 2021 Automate The Planet Ltd.
* Author: Teodor Nikolov
* 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 appiumandroid
import io.appium.java_client.android.Activity
import io.appium.java_client.android.AndroidDriver
import io.appium.java_client.android.AndroidElement
import io.appium.java_client.remote.AndroidMobileCapabilityType
import io.appium.java_client.remote.MobileCapabilityType
import org.openqa.selenium.remote.DesiredCapabilities
import org.testng.annotations.*
import java.net.URL
import java.nio.file.Paths
class AppiumTests {
private lateinit var driver: AndroidDriver<AndroidElement>
////private lateinit var appiumLocalService: AppiumDriverLocalService
@BeforeClass
fun classInit() {
////appiumLocalService = AppiumServiceBuilder().usingAnyFreePort().build()
////appiumLocalService.start()
val testAppUrl = javaClass.classLoader.getResource("ApiDemos.apk")
val testAppFile = Paths.get((testAppUrl!!).toURI()).toFile()
val testAppPath = testAppFile.absolutePath
val desiredCaps = DesiredCapabilities()
desiredCaps.setCapability(MobileCapabilityType.DEVICE_NAME, "android25-test")
desiredCaps.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "com.example.android.apis")
desiredCaps.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android")
desiredCaps.setCapability(MobileCapabilityType.PLATFORM_VERSION, "7.1")
desiredCaps.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, ".view.Controls1")
desiredCaps.setCapability(MobileCapabilityType.APP, testAppPath)
////driver = AndroidDriver<AndroidElement>(appiumLocalService, desiredCaps)
driver = AndroidDriver<AndroidElement>(URL("http://127.0.0.1:4723/wd/hub"), desiredCaps)
driver.closeApp()
}
@BeforeMethod
fun testInit() {
driver.launchApp()
driver.startActivity(Activity("com.example.android.apis", ".view.Controls1"))
}
@AfterMethod
fun testCleanup() {
driver.closeApp()
}
@AfterClass
fun classCleanup() {
////appiumLocalService.stop()
}
@Test
fun locatingElementsTest() {
val button = driver.findElementById("com.example.android.apis:id/button")
button.click()
val checkBox = driver.findElementByClassName("android.widget.CheckBox")
checkBox.click()
val secondButton = driver.findElementByXPath("//*[@resource-id='com.example.android.apis:id/button']")
secondButton.click()
val thirdButton = driver.findElementByAndroidUIAutomator("new UiSelector().textContains(\"BUTTO\");")
thirdButton.click()
}
@Test
fun locatingElementsInsideAnotherElementTest() {
val mainElement = driver.findElementById("android:id/content")
val button = mainElement.findElementById("com.example.android.apis:id/button")
button.click()
val checkBox = mainElement.findElementByClassName("android.widget.CheckBox")
checkBox.click()
val secondButton = mainElement.findElementByXPath("//*[@resource-id='com.example.android.apis:id/button']")
secondButton.click()
val thirdButton = mainElement.findElementByAndroidUIAutomator("new UiSelector().textContains(\"BUTTO\");")
thirdButton.click()
}
} | kotlin/MobileAutomation-Series/src/test/kotlin/appiumandroid/AppiumTests.kt | 1128531987 |
package org.ccci.gto.android.common.util.lang
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class ClassTest {
@Test
fun verifyGetClassOrNull() {
assertNull(getClassOrNull("org.ccci.gto.android.common.util.lang.ClassTest\$Invalid"))
assertEquals(Test1::class.java, getClassOrNull("org.ccci.gto.android.common.util.lang.ClassTest\$Test1"))
}
@Test
fun verifyGetMethod() {
assertNull(Test1::class.java.getDeclaredMethodOrNull("invalid"))
assertEquals(
Test1::class.java.getDeclaredMethod("method1"),
Test1::class.java.getDeclaredMethodOrNull("method1")
)
assertNull(Test1::class.java.getDeclaredMethodOrNull("method1", String::class.java))
assertEquals(
Test1::class.java.getDeclaredMethod("method2", String::class.java),
Test1::class.java.getDeclaredMethodOrNull("method2", String::class.java)
)
assertNull(Test1::class.java.getDeclaredMethodOrNull("method2"))
assertNull(Test1::class.java.getDeclaredMethodOrNull("method2", Int::class.java))
}
class Test1 {
private fun method1() = Unit
private fun method2(param: String) = Unit
}
}
| gto-support-util/src/test/java/org/ccci/gto/android/common/util/lang/ClassTest.kt | 1709529408 |
/**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plsqlopen.metadata
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.fail
import org.junit.jupiter.api.Test
class FormsMetadataTest {
@Test
fun canReadSimpleMetadaFile() {
val metadata = FormsMetadata.loadFromFile("src/test/resources/metadata/metadata.json")
if (metadata == null) {
fail("Should load Oracle Forms metadata")
} else {
assertThat(metadata.alerts).containsExactly("foo", "bar")
assertThat(metadata.blocks).hasSize(2)
assertThat(metadata.blocks[0].name).isEqualTo("foo")
assertThat(metadata.blocks[0].items).containsExactly("item1", "item2")
assertThat(metadata.blocks[1].name).isEqualTo("bar")
assertThat(metadata.blocks[1].items).containsExactly("item1", "item2")
assertThat(metadata.lovs).containsExactly("foo", "bar")
}
}
@Test
fun returnsNullIfFileDoesNotExists() {
val metadata = FormsMetadata.loadFromFile("src/test/resources/metadata/metadata2.json")
assertThat(metadata).isNull()
}
}
| zpa-core/src/test/kotlin/org/sonar/plsqlopen/metadata/FormsMetadataTest.kt | 1813595327 |
package com.intfocus.template.subject.seven.indicatorgroup
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alibaba.fastjson.JSON
import com.intfocus.template.R
import com.intfocus.template.listener.NoDoubleClickListener
import com.intfocus.template.subject.one.entity.SingleValue
import com.intfocus.template.subject.seven.listener.EventRefreshIndicatorListItemData
import com.intfocus.template.util.LoadAssetsJsonUtil
import com.intfocus.template.util.LogUtil
import com.intfocus.template.util.OKHttpUtils
import com.intfocus.template.util.RxBusUtil
import kotlinx.android.synthetic.main.item_indicator_group.view.*
import okhttp3.Call
import java.io.IOException
import java.text.DecimalFormat
/**
* ****************************************************
* @author jameswong
* created on: 17/12/18 下午5:35
* e-mail: [email protected]
* name: 模板七 - 单值组件
* desc:
* ****************************************************
*/
class IndicatorGroupAdapter(val context: Context, private var mData: List<SingleValue>, private val eventCode: Int) : RecyclerView.Adapter<IndicatorGroupAdapter.IndicatorGroupViewHolder>() {
constructor(context: Context, mData: List<SingleValue>) : this(context, mData, -1)
val testApi = "https://api.douban.com/v2/book/search?q=%E7%BC%96%E7%A8%8B%E8%89%BA%E6%9C%AF"
val coCursor = context.resources.getIntArray(R.array.co_cursor)
var count = 0
companion object {
val CODE_EVENT_REFRESH_INDICATOR_LIST_ITEM_DATA = 1
}
override fun getItemCount(): Int = mData.size
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): IndicatorGroupViewHolder =
IndicatorGroupAdapter.IndicatorGroupViewHolder(LayoutInflater.from(context).inflate(R.layout.item_indicator_group, parent, false))
override fun onBindViewHolder(holder: IndicatorGroupViewHolder?, position: Int) {
holder!!.itemView.tv_item_indicator_group_main_data.tag = position
holder.itemView.tv_item_indicator_group_sub_data.tag = position
val data = mData[position]
if (data.isReal_time) {
// data.real_time_api?.let {
testApi.let {
OKHttpUtils.newInstance().getAsyncData(it, object : OKHttpUtils.OnReusltListener {
override fun onFailure(call: Call?, e: IOException?) {
}
override fun onSuccess(call: Call?, response: String?) {
val itemData = JSON.parseObject(LoadAssetsJsonUtil.getAssetsJsonData(data.real_time_api), SingleValue::class.java)
data.main_data = itemData.main_data
data.sub_data = itemData.sub_data
data.state = itemData.state
data.isReal_time = false
notifyItemChanged(position)
}
})
}
}
if (data.main_data == null || data.sub_data == null || data.state == null) {
return
}
val df = DecimalFormat("###,###.##")
val state = data.state.color % coCursor.size
val color = coCursor[state]
holder.itemView.tv_item_indicator_group_title.text = data.main_data.name
val mainValue = data.main_data.data.replace("%", "").toFloat()
holder.itemView.tv_item_indicator_group_main_data.text = df.format(mainValue.toDouble())
val subData = data.sub_data.data.replace("%", "").toFloat()
holder.itemView.tv_item_indicator_group_sub_data.text = df.format(subData.toDouble())
holder.itemView.tv_item_indicator_group_rate.setTextColor(color)
val diffRate = DecimalFormat(".##%").format(((mainValue - subData) / subData).toDouble())
holder.itemView.tv_item_indicator_group_rate.text = diffRate
holder.itemView.img_item_indicator_group_ratiocursor.setCursorState(data.state.color, false)
holder.itemView.img_item_indicator_group_ratiocursor.isDrawingCacheEnabled = true
holder.itemView.rl_item_indicator_group_container.setOnClickListener(object : NoDoubleClickListener() {
override fun onNoDoubleClick(v: View?) {
when (eventCode) {
CODE_EVENT_REFRESH_INDICATOR_LIST_ITEM_DATA -> {
RxBusUtil.getInstance().post(EventRefreshIndicatorListItemData(position))
}
}
LogUtil.d(this, "pos ::: " + position)
LogUtil.d(this, "itemView.id ::: " + holder.itemView.id)
LogUtil.d(this, "state ::: " + state)
LogUtil.d(this, "color ::: " + data.state.color)
LogUtil.d(this, "main_data ::: " + holder.itemView.tv_item_indicator_group_main_data.text)
LogUtil.d(this, "sub_data ::: " + holder.itemView.tv_item_indicator_group_sub_data.text)
LogUtil.d(this, "rate ::: " + holder.itemView.tv_item_indicator_group_rate.text)
LogUtil.d(this, "main_data.width ::: " + holder.itemView.tv_item_indicator_group_main_data.width)
val spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
holder.itemView.tv_item_indicator_group_main_data.measure(spec, spec)
LogUtil.d(this, "main_data.text.width ::: " + holder.itemView.tv_item_indicator_group_main_data.measuredWidth)
}
})
}
fun setData() {
}
class IndicatorGroupViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
} | app/src/main/java/com/intfocus/template/subject/seven/indicatorgroup/IndicatorGroupAdapter.kt | 3861969965 |
package com.serenegiant.widget
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2022 saki [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context
import android.graphics.PointF
import android.graphics.RectF
import android.graphics.SurfaceTexture
import android.media.FaceDetector
import android.os.Handler
import android.util.AttributeSet
import android.util.Log
import android.view.Surface
import android.view.View
import com.serenegiant.glpipeline.*
import com.serenegiant.gl.GLContext
import com.serenegiant.gl.GLEffect
import com.serenegiant.gl.GLManager
import com.serenegiant.math.Fraction
import com.serenegiant.view.ViewTransformDelegater
/**
* VideoSourceを使ってカメラ映像を受け取りSurfacePipelineで描画処理を行うZoomAspectScaledTextureView/ICameraView実装
*/
class SimpleVideoSourceCameraTextureView @JvmOverloads constructor(
context: Context?, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: ZoomAspectScaledTextureView(context, attrs, defStyleAttr), ICameraView, GLPipelineView {
private val mGLManager: GLManager
private val mGLContext: GLContext
private val mGLHandler: Handler
private val mCameraDelegator: CameraDelegator
private var mVideoSourcePipeline: VideoSourcePipeline? = null
var pipelineMode = GLPipelineView.PREVIEW_ONLY
var enableFaceDetect = false
init {
if (DEBUG) Log.v(TAG, "コンストラクタ:")
mGLManager = GLManager()
mGLContext = mGLManager.glContext
mGLHandler = mGLManager.glHandler
setEnableHandleTouchEvent(ViewTransformDelegater.TOUCH_DISABLED)
mCameraDelegator = CameraDelegator(this@SimpleVideoSourceCameraTextureView,
CameraDelegator.DEFAULT_PREVIEW_WIDTH, CameraDelegator.DEFAULT_PREVIEW_HEIGHT,
object : CameraDelegator.ICameraRenderer {
override fun hasSurface(): Boolean {
if (DEBUG) Log.v(TAG, "hasSurface:")
return mVideoSourcePipeline != null
}
override fun getInputSurface(): SurfaceTexture {
if (DEBUG) Log.v(TAG, "getInputSurfaceTexture:")
checkNotNull(mVideoSourcePipeline)
return mVideoSourcePipeline!!.inputSurfaceTexture
}
override fun onPreviewSizeChanged(width: Int, height: Int) {
if (DEBUG) Log.v(TAG, "onPreviewSizeChanged:(${width}x${height})")
mVideoSourcePipeline!!.resize(width, height)
setAspectRatio(width, height)
}
}
)
surfaceTextureListener = object : SurfaceTextureListener {
override fun onSurfaceTextureAvailable(
surface: SurfaceTexture, width: Int, height: Int) {
if (DEBUG) Log.v(TAG, "onSurfaceTextureAvailable:(${width}x${height})")
val source = mVideoSourcePipeline
if (source != null) {
addSurface(surface.hashCode(), surface, false)
source.resize(width, height)
mCameraDelegator.startPreview(
CameraDelegator.DEFAULT_PREVIEW_WIDTH, CameraDelegator.DEFAULT_PREVIEW_HEIGHT)
} else {
throw IllegalStateException("already released?")
}
}
override fun onSurfaceTextureSizeChanged(
surface: SurfaceTexture,
width: Int, height: Int) {
if (DEBUG) Log.v(TAG, "onSurfaceTextureSizeChanged:(${width}x${height})")
}
override fun onSurfaceTextureDestroyed(
surface: SurfaceTexture): Boolean {
if (DEBUG) Log.v(TAG, "onSurfaceTextureDestroyed:")
val source = mVideoSourcePipeline
if (source != null) {
val pipeline = GLSurfacePipeline.findById(source, surface.hashCode())
if (pipeline != null) {
pipeline.remove()
pipeline.release()
}
}
return true
}
override fun onSurfaceTextureUpdated(
surface: SurfaceTexture) {
// if (DEBUG) Log.v(TAG, "onSurfaceTextureUpdated:")
}
}
}
override fun onDetachedFromWindow() {
val source = mVideoSourcePipeline
mVideoSourcePipeline = null
source?.release()
mGLManager.release()
super.onDetachedFromWindow()
}
override fun getView() : View {
return this
}
override fun onResume() {
if (DEBUG) Log.v(TAG, "onResume:")
mVideoSourcePipeline = createVideoSource(
CameraDelegator.DEFAULT_PREVIEW_WIDTH, CameraDelegator.DEFAULT_PREVIEW_HEIGHT)
mCameraDelegator.onResume()
}
override fun onPause() {
if (DEBUG) Log.v(TAG, "onPause:")
mCameraDelegator.onPause()
mVideoSourcePipeline?.release()
mVideoSourcePipeline = null
}
override fun setVideoSize(width: Int, height: Int) {
if (DEBUG) Log.v(TAG, "setVideoSize:(${width}x${height})")
mCameraDelegator.setVideoSize(width, height)
}
override fun addListener(listener: CameraDelegator.OnFrameAvailableListener) {
if (DEBUG) Log.v(TAG, "addListener:")
mCameraDelegator.addListener(listener)
}
override fun removeListener(listener: CameraDelegator.OnFrameAvailableListener) {
if (DEBUG) Log.v(TAG, "removeListener:")
mCameraDelegator.removeListener(listener)
}
override fun setScaleMode(mode: Int) {
if (DEBUG) Log.v(TAG, "setScaleMode:")
super.setScaleMode(mode)
mCameraDelegator.scaleMode = mode
}
override fun getScaleMode(): Int {
if (DEBUG) Log.v(TAG, "getScaleMode:")
return mCameraDelegator.scaleMode
}
override fun getVideoWidth(): Int {
if (DEBUG) Log.v(TAG, "getVideoWidth:${mCameraDelegator.previewWidth}")
return mCameraDelegator.previewWidth
}
override fun getVideoHeight(): Int {
if (DEBUG) Log.v(TAG, "getVideoHeight:${mCameraDelegator.previewHeight}")
return mCameraDelegator.previewHeight
}
override fun addSurface(
id: Int, surface: Any,
isRecordable: Boolean,
maxFps: Fraction?) {
if (DEBUG) Log.v(TAG, "addSurface:id=${id},${surface}")
val source = mVideoSourcePipeline
if (source != null) {
when (val last = GLPipeline.findLast(source)) {
mVideoSourcePipeline -> {
source.pipeline = createPipeline(surface, maxFps)
if (SUPPORT_RECORDING) {
// 通常の録画(#addSurfaceでエンコーダーへの映像入力用surfaceを受け取る)場合は
// 毎フレームCameraDelegator#callOnFrameAvailableを呼び出さないといけないので
// OnFramePipelineを追加する
if (DEBUG) Log.v(TAG, "addSurface:create OnFramePipeline")
val p = GLPipeline.findLast(source)
p.pipeline = OnFramePipeline(object :
OnFramePipeline.OnFrameAvailableListener {
var cnt: Int = 0
override fun onFrameAvailable() {
if (DEBUG && ((++cnt) % 100 == 0)) {
Log.v(TAG, "onFrameAvailable:${cnt}")
}
mCameraDelegator.callOnFrameAvailable()
}
})
}
if (enableFaceDetect) {
if (DEBUG) Log.v(TAG, "addSurface:create FaceDetectPipeline")
val p = GLPipeline.findLast(source)
p.pipeline = FaceDetectPipeline(mGLManager, Fraction.FIVE, 1
) { /*bitmap,*/ num, faces, width, height ->
if (DEBUG) {
Log.v(TAG, "onDetected:n=${num}")
for (i in 0 until num) {
val face: FaceDetector.Face = faces[i]
val point = PointF()
face.getMidPoint(point)
Log.v(TAG, "onDetected:Confidence=" + face.confidence())
Log.v(TAG, "onDetected:MidPoint.X=" + point.x)
Log.v(TAG, "onDetected:MidPoint.Y=" + point.y)
Log.v(TAG, "onDetected:EyesDistance=" + face.eyesDistance())
}
}
// val context: Context = context
// val outputFile: DocumentFile = if (BuildCheck.isAPI29()) {
// // API29以降は対象範囲別ストレージ
// MediaStoreUtils.getContentDocument(
// context, "image/jpeg",
// Environment.DIRECTORY_DCIM + "/" + Const.APP_DIR,
// FileUtils.getDateTimeString() + ".jpg", null
// )
// } else {
// MediaFileUtils.getRecordingFile(
// context,
// Const.REQUEST_ACCESS_SD,
// Environment.DIRECTORY_DCIM,
// "image/jpeg",
// ".jpg"
// )
// }
// var bos: BufferedOutputStream? = null
// try {
// bos = BufferedOutputStream (context.contentResolver.openOutputStream(outputFile.uri))
// bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bos)
// MediaStoreUtils.updateContentUri(context, outputFile.uri)
// } catch (e: FileNotFoundException) {
// Log.w(TAG, e);
// } finally {
// if (bos != null) {
// try {
// bos.close();
// } catch (e: IOException) {
// Log.w(TAG, e);
// }
// }
// }
}
}
}
is GLSurfacePipeline -> {
if (last.hasSurface()) {
last.pipeline = SurfaceRendererPipeline(mGLManager, surface, maxFps)
} else {
last.setSurface(surface, null)
}
}
else -> {
last.pipeline = SurfaceRendererPipeline(mGLManager, surface, maxFps)
}
}
} else {
throw IllegalStateException("already released?")
}
}
override fun removeSurface(id: Int) {
if (DEBUG) Log.v(TAG, "removeSurface:id=${id}")
val found = GLSurfacePipeline.findById(mVideoSourcePipeline!!, id)
if (found != null) {
found.remove()
found.release()
}
}
override fun isRecordingSupported(): Boolean {
// XXX ここでtrueを返すなら録画中にCameraDelegatorのOnFrameAvailableListener#onFrameAvailableが呼び出されるようにしないといけない
return SUPPORT_RECORDING
}
/**
* GLPipelineViewの実装
* @param pipeline
*/
override fun addPipeline(pipeline: GLPipeline) {
val source = mVideoSourcePipeline
if (source != null) {
GLPipeline.append(source, pipeline)
if (DEBUG) Log.v(TAG, "addPipeline:" + GLPipeline.pipelineString(source))
} else {
throw IllegalStateException()
}
}
/**
* GLPipelineViewの実装
*/
override fun getGLManager(): GLManager {
return mGLManager
}
fun isEffectSupported(): Boolean {
return (pipelineMode == GLPipelineView.EFFECT_ONLY)
|| (pipelineMode == GLPipelineView.EFFECT_PLUS_SURFACE)
}
var effect: Int
get() {
val source = mVideoSourcePipeline
return if (source != null) {
val pipeline = GLPipeline.find(source, EffectPipeline::class.java)
if (DEBUG) Log.v(TAG, "getEffect:$pipeline")
pipeline?.currentEffect ?: 0
} else {
0
}
}
set(effect) {
if (DEBUG) Log.v(TAG, "setEffect:$effect")
if ((effect >= 0) && (effect < GLEffect.EFFECT_NUM)) {
post {
val source = mVideoSourcePipeline
if (source != null) {
val pipeline = GLPipeline.find(source, EffectPipeline::class.java)
pipeline?.setEffect(effect)
}
}
}
}
override fun getContentBounds(): RectF {
if (DEBUG) Log.v(TAG, "getContentBounds:")
return RectF(0.0f, 0.0f, getVideoWidth().toFloat(), getVideoHeight().toFloat())
}
/**
* VideoSourceインスタンスを生成
* @param width
* @param height
* @return
*/
private fun createVideoSource(
width: Int, height: Int): VideoSourcePipeline {
return VideoSourcePipeline(mGLManager,
width,
height,
object : GLPipelineSource.PipelineSourceCallback {
override fun onCreate(surface: Surface) {
if (DEBUG) Log.v(TAG, "PipelineSourceCallback#onCreate:$surface")
}
override fun onDestroy() {
if (DEBUG) Log.v(TAG, "PipelineSourceCallback#onDestroy:")
}
},
USE_SHARED_CONTEXT)
}
/**
* GLPipelineインスタンスを生成
* @param surface
*/
private fun createPipeline(surface: Any?, maxFps: Fraction?): GLPipeline {
if (DEBUG) Log.v(TAG, "createPipeline:surface=${surface}")
return when (pipelineMode) {
GLPipelineView.EFFECT_PLUS_SURFACE -> {
if (DEBUG) Log.v(TAG, "createPipeline:create EffectPipeline & SurfaceRendererPipeline")
val effect = EffectPipeline(mGLManager)
effect.pipeline = SurfaceRendererPipeline(mGLManager, surface, maxFps)
effect
}
GLPipelineView.EFFECT_ONLY -> {
if (DEBUG) Log.v(TAG, "createPipeline:create EffectPipeline")
EffectPipeline(mGLManager, surface, maxFps)
}
else -> {
if (DEBUG) Log.v(TAG, "createPipeline:create SurfaceRendererPipeline")
SurfaceRendererPipeline(mGLManager, surface, maxFps)
}
}
}
companion object {
private const val DEBUG = true // set false on production
private val TAG = SimpleVideoSourceCameraTextureView::class.java.simpleName
/**
* 共有GLコンテキストコンテキストを使ったマルチスレッド処理を行うかどうか
*/
private const val USE_SHARED_CONTEXT = false
private const val SUPPORT_RECORDING = true
}
}
| app/src/main/java/com/serenegiant/widget/SimpleVideoSourceCameraTextureView.kt | 1713765662 |
package de.westnordost.streetcomplete.quests.roof_shape
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.SimpleOverpassQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao
class AddRoofShape(o: OverpassMapDataDao) : SimpleOverpassQuestType<String>(o) {
override val tagFilters = """
ways, relations with roof:levels
and roof:levels!=0 and !roof:shape and !3dr:type and !3dr:roof
"""
override val commitMessage = "Add roof shapes"
override val icon = R.drawable.ic_quest_roof_shape
override fun getTitle(tags: Map<String, String>) = R.string.quest_roofShape_title
override fun createForm() = AddRoofShapeForm()
override fun applyAnswerTo(answer: String, changes: StringMapChangesBuilder) {
changes.add("roof:shape", answer)
}
}
| app/src/main/java/de/westnordost/streetcomplete/quests/roof_shape/AddRoofShape.kt | 3143965407 |
package com.gyro.tests
/* DO NOT EDIT | Generated by gyro */
enum class Type2(val jsonValue: String) {
TYPE2_ONE("json_type_one"),
TYPE2_TWO("json_type_two"),
TYPE2_THREE("json_type_three");
companion object {
@JvmStatic
fun get(jsonValue: String?): Type2? {
return Type2.values().firstOrNull { it.jsonValue == jsonValue }
}
}
}
| spec/fixtures/kotlin/enum_json/Type2.kt | 3722199715 |
package com.themovielist.moviecast
import com.themovielist.base.BasePresenter
import com.themovielist.model.MovieCastModel
import com.themovielist.model.MovieSizeModel
import com.themovielist.model.view.MovieCastViewModel
interface MovieCastContract {
interface View {
fun showLoadingIndicator()
fun hideLoadingIndicator()
fun showMovieCastList(movieCastList: List<MovieCastModel>, profileSizeList: List<MovieSizeModel>)
fun showErrorLoadingMovieCast(error: Throwable)
}
interface Presenter : BasePresenter<View> {
fun start(movieCastViewModel: MovieCastViewModel)
fun onStop()
fun setMovieId(movieId: Int?)
fun tryAgain()
}
} | app/src/main/java/com/themovielist/moviecast/MovieCastContract.kt | 580130326 |
package lijin.heinika.cn.mygankio.entiy
import com.google.gson.annotations.SerializedName
/**
* _id : 5732b15067765974f885c05a
* content : <h3><img alt="" src="http://ww2.sinaimg.cn/large/610dc034jw1f3rbikc83dj20dw0kuadt.jpg"></img></h3>
*
* <h3>Android</h3>
*
*
* * [Fragment完全解析三步曲](http://www.jianshu.com/p/d9143a92ad94) (AndWang)
* * [送给小白的设计说明书](http://blog.csdn.net/dd864140130/article/details/51313342) (Dong dong Liu)
* * [Material 风格的干货客户端](http://www.jcodecraeer.com/a/anzhuokaifa/2016/0508/4222.html) (None)
* * [可定制的Indicator,结合ViewPager使用](https://github.com/jiang111/ScalableTabIndicator) (NewTab)
* * [T-MVP:泛型深度解耦下的MVP大瘦身](https://github.com/north2014/T-MVP) (Bai xiaokang)
* * [Simple Android SharedPreferences wrapper](https://github.com/GrenderG/Prefs) (蒋朋)
* * [IntelliJ plugin for supporting PermissionsDispatcher](https://github.com/shiraji/permissions-dispatcher-plugin) (蒋朋)
*
*
* <h3>iOS</h3>
*
*
* * [&&&&别人的 App 不好用?自己改了便是。Moves 篇(上)](http://mp.weixin.qq.com/s?__biz=MzIwMTYzMzcwOQ==&mid=2650948304&idx=1&sn=f76e7b765a7fcabcb71d37052b46e489&scene=0#wechat_redirect) (tripleCC)
* * [网易云信iOS UI组件源码仓库](https://github.com/netease-im/NIM_iOS_UIKit) (__weak_Point)
* * [OpenShop 开源](https://github.com/openshopio/openshop.io-ios) (代码家)
* * [Swift 实现的 OCR 识别库](https://github.com/garnele007/SwiftOCR) (代码家)
* * [让你的微信不再被人撤回消息](http://yulingtianxia.com/blog/2016/05/06/Let-your-WeChat-for-Mac-never-revoke-messages/) (CallMeWhy)
* * [微信双开还是微信定时炸弹?](http://drops.wooyun.org/mobile/15406) (CallMeWhy)
*
*
* <h3>瞎推荐</h3>
*
*
* * [阻碍新手程序员提升的8件小事](http://blog.csdn.net/shenyisyn/article/details/50056319) (LHF)
* * [程序员、黑客与开发者之别](http://36kr.com/p/5046775.html) (LHF)
*
*
* <h3>拓展资源</h3>
*
*
* * [详细介绍了java jvm 垃圾回收相关的知识汇总](http://www.wxtlife.com/2016/04/25/java-jvm-gc/) (Aaron)
* * [使用GPG签名Git提交和标签](http://arondight.me/2016/04/17/%E4%BD%BF%E7%94%A8GPG%E7%AD%BE%E5%90%8DGit%E6%8F%90%E4%BA%A4%E5%92%8C%E6%A0%87%E7%AD%BE/) (蒋朋)
*
*
* <h3>休息视频</h3>
*
*
* * [秒拍牛人大合集,[笑cry]目测膝盖根本不够用啊。](http://weibo.com/p/2304443956b04478364a64185f196f0a89266d) (LHF)
*
*
*
* <iframe frameborder="0" height="498" src="http://v.qq.com/iframe/player.html?vid=w0198nyi5x5&tiny=0&auto=0" width="640">&&</iframe>
*
*
* 感谢所有默默付出的编辑们,愿大家有美好一天.
*
* publishedAt : 2016-05-11T12:11:00.0Z
* title : 秒拍牛人大集合,看到哪个你跪了
*/
data class DateBean(
@SerializedName("_id") val id: String,
val content: String,
val publishedAt: String,
val title: String
)
| app/src/main/java/lijin/heinika/cn/mygankio/entiy/DateBean.kt | 1471388815 |
fun box(): String {
infix fun Int.foo(a: Int): Int = a + 2
val s = object {
fun test(): Int {
return 1 foo 1
}
}
fun local(): Int {
return 1 foo 1
}
if (s.test() != 3) return "Fail"
if (local() != 3) return "Fail"
return "OK"
} | backend.native/tests/external/codegen/box/functions/localFunctions/kt4119_2.kt | 3162382615 |
package com.andrewvora.apps.historian.history
import android.util.SparseBooleanArray
import com.andrewvora.apps.historian.BaseUnitTest
import com.andrewvora.apps.historian.data.local.DatabaseService
import com.andrewvora.apps.historian.data.models.Snapshot
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.*
/**
* Created on 7/25/2017.
* @author Andrew Vorakrajangthiti
*/
class HistoryPresenterTest : BaseUnitTest() {
@Mock private lateinit var databaseService: DatabaseService
@Mock private lateinit var historyView: HistoryContract.View
private lateinit var historyPresenter: HistoryContract.Presenter
override fun setup() {
historyPresenter = HistoryPresenter(databaseService)
historyPresenter.setView(historyView)
}
@Test
fun start_viewMode() {
// given
`when`(databaseService.snapshots).thenReturn(emptyList())
historyPresenter.setActionMode(HistoryContract.ActionMode.VIEW)
// when
historyPresenter.start()
// then
verify(historyView, never()).startEditing()
verify(historyView).onHistoryLoaded(emptyList())
verify(databaseService).snapshots
}
@Test
fun start_editMode() {
// given
`when`(databaseService.snapshots).thenReturn(emptyList())
historyPresenter.setActionMode(HistoryContract.ActionMode.EDIT)
// when
historyPresenter.start()
// then
verify(historyView).startEditing()
verify(historyView).onHistoryLoaded(emptyList())
verify(databaseService).snapshots
}
@Test
fun stop() {
historyPresenter.stop()
}
@Test
fun loadSnapshots() {
// given
val snapshots = listOf(mock(Snapshot::class.java))
`when`(databaseService.snapshots).thenReturn(snapshots)
// when
historyPresenter.loadSnapshots()
// then
verify(historyView).onHistoryLoaded(snapshots)
}
@Test
fun loadSnapshots_viewUnset() {
// given
historyPresenter.setView(null)
// when
historyPresenter.loadSnapshots()
// then
verify(historyView, never()).onHistoryLoaded(anyList())
}
@Test
fun openSnapshot() {
// given
val snapshot = mock(Snapshot::class.java)
// when
historyPresenter.openSnapshot(snapshot)
// then
verify(historyView).openSnapshotView(any())
}
@Test
fun openSnapshot_viewUnset() {
// given
val snapshot = mock(Snapshot::class.java)
historyPresenter.setView(null)
// when
historyPresenter.openSnapshot(snapshot)
// then
verify(historyView, never()).openSnapshotView(any())
}
@Test
fun createNewSnapshot() {
// given
// when
historyPresenter.createNewSnapshot()
// then
verify(historyView).openSnapshotView()
}
@Test
fun createNewSnapshot_viewUnset() {
// given
historyPresenter.setView(null)
// when
historyPresenter.createNewSnapshot()
// then
verify(historyView, never()).openSnapshotView()
}
@Test
fun editSnapshot() {
// given
// when
historyPresenter.editSnapshot(mock(Snapshot::class.java), 0)
// then
verify(historyView).showSnapshotEditViewFor(any(), anyInt())
}
@Test
fun editSnapshot_viewUnset() {
// given
historyPresenter.setView(null)
// when
historyPresenter.editSnapshot(mock(Snapshot::class.java), 0)
// then
verify(historyView, never()).showSnapshotEditViewFor(any(), anyInt())
}
@Test
fun sortHistory() {
// given
val snapshot1 = mock(Snapshot::class.java)
`when`(snapshot1.name()).thenReturn("a")
val snapshot2 = mock(Snapshot::class.java)
`when`(snapshot2.name()).thenReturn("b")
val snapshot3 = mock(Snapshot::class.java)
`when`(snapshot3.name()).thenReturn("C")
val snapshots = listOf(snapshot3, snapshot2, snapshot1)
// when
historyPresenter.sortHistory(snapshots)
// then
val expected = listOf(snapshot1, snapshot2, snapshot3)
verify(historyView).onHistorySorted(expected)
}
@Test
fun sortHistory_viewUnset() {
// given
historyPresenter.setView(null)
// when
historyPresenter.sortHistory(emptyList())
// then
verify(historyView, never()).onHistorySorted(anyList())
}
@Test
fun deleteSnapshots() {
// given
val snapshot1 = mock(Snapshot::class.java)
`when`(snapshot1.name()).thenReturn("abra")
val snapshot2 = mock(Snapshot::class.java)
`when`(snapshot2.name()).thenReturn("Kadabra")
val snapshots = listOf(snapshot1, snapshot2)
`when`(databaseService.snapshots).thenReturn(snapshots)
historyPresenter.start()
val selected = mock(SparseBooleanArray::class.java)
`when`(selected[1]).thenReturn(true)
// when
historyPresenter.deleteSnapshots(selected)
// then
verify(selected)[0]
verify(selected)[1]
verify(databaseService).deleteSnapshot(listOf(snapshot2))
verify(historyView, times(2)).onHistoryLoaded(anyList())
verify(historyView).stopEditing()
}
@Test
fun deleteSnapshots_viewUnset() {
// given
`when`(databaseService.snapshots).thenReturn(emptyList())
historyPresenter.setView(null)
historyPresenter.start()
val selected = mock(SparseBooleanArray::class.java)
// when
historyPresenter.deleteSnapshots(selected)
// then
verify(historyView, never()).onHistoryLoaded(anyList())
verify(historyView, never()).stopEditing()
verify(databaseService).deleteSnapshot(any())
}
} | app/src/test/java/com/andrewvora/apps/historian/history/HistoryPresenterTest.kt | 2893441749 |
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
open class EmptyContinuation(override val context: CoroutineContext = EmptyCoroutineContext) : Continuation<Any?> {
companion object : EmptyContinuation()
override fun resume(value: Any?) {}
override fun resumeWithException(exception: Throwable) { throw exception }
}
suspend fun s1(): Int = suspendCoroutineOrReturn { x ->
println("s1")
x.resume(42)
COROUTINE_SUSPENDED
}
fun f1(): Int {
println("f1")
return 117
}
fun f2(): Int {
println("f2")
return 1
}
fun f3(x: Int, y: Int): Int {
println("f3")
return x + y
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
fun main(args: Array<String>) {
var result = 0
builder {
result = f3(if (f1() > 100) s1() else f2(), 42)
}
println(result)
} | backend.native/tests/codegen/coroutines/controlFlow_if1.kt | 2677985820 |
package org.dictat.wikistat.servlets
import org.dictat.wikistat.services.PageDao
abstract class PageDaoServlet<T> : SpringJsonServlet<T, PageDao>() {
override fun getBeanName(): String {
return "pageDao"
}
} | src/main/kotlin/org/dictat/wikistat/servlets/PageDaoServlet.kt | 484906882 |
package exh.metadata.sql.mappers
import android.content.ContentValues
import android.database.Cursor
import com.pushtorefresh.storio.sqlite.SQLiteTypeMapping
import com.pushtorefresh.storio.sqlite.operations.delete.DefaultDeleteResolver
import com.pushtorefresh.storio.sqlite.operations.get.DefaultGetResolver
import com.pushtorefresh.storio.sqlite.operations.put.DefaultPutResolver
import com.pushtorefresh.storio.sqlite.queries.DeleteQuery
import com.pushtorefresh.storio.sqlite.queries.InsertQuery
import com.pushtorefresh.storio.sqlite.queries.UpdateQuery
import exh.metadata.sql.models.SearchMetadata
import exh.metadata.sql.tables.SearchMetadataTable.COL_EXTRA
import exh.metadata.sql.tables.SearchMetadataTable.COL_EXTRA_VERSION
import exh.metadata.sql.tables.SearchMetadataTable.COL_INDEXED_EXTRA
import exh.metadata.sql.tables.SearchMetadataTable.COL_MANGA_ID
import exh.metadata.sql.tables.SearchMetadataTable.COL_UPLOADER
import exh.metadata.sql.tables.SearchMetadataTable.TABLE
class SearchMetadataTypeMapping : SQLiteTypeMapping<SearchMetadata>(
SearchMetadataPutResolver(),
SearchMetadataGetResolver(),
SearchMetadataDeleteResolver()
)
class SearchMetadataPutResolver : DefaultPutResolver<SearchMetadata>() {
override fun mapToInsertQuery(obj: SearchMetadata) = InsertQuery.builder()
.table(TABLE)
.build()
override fun mapToUpdateQuery(obj: SearchMetadata) = UpdateQuery.builder()
.table(TABLE)
.where("$COL_MANGA_ID = ?")
.whereArgs(obj.mangaId)
.build()
override fun mapToContentValues(obj: SearchMetadata) = ContentValues(5).apply {
put(COL_MANGA_ID, obj.mangaId)
put(COL_UPLOADER, obj.uploader)
put(COL_EXTRA, obj.extra)
put(COL_INDEXED_EXTRA, obj.indexedExtra)
put(COL_EXTRA_VERSION, obj.extraVersion)
}
}
class SearchMetadataGetResolver : DefaultGetResolver<SearchMetadata>() {
override fun mapFromCursor(cursor: Cursor): SearchMetadata = SearchMetadata(
mangaId = cursor.getLong(cursor.getColumnIndex(COL_MANGA_ID)),
uploader = cursor.getString(cursor.getColumnIndex(COL_UPLOADER)),
extra = cursor.getString(cursor.getColumnIndex(COL_EXTRA)),
indexedExtra = cursor.getString(cursor.getColumnIndex(COL_INDEXED_EXTRA)),
extraVersion = cursor.getInt(cursor.getColumnIndex(COL_EXTRA_VERSION))
)
}
class SearchMetadataDeleteResolver : DefaultDeleteResolver<SearchMetadata>() {
override fun mapToDeleteQuery(obj: SearchMetadata) = DeleteQuery.builder()
.table(TABLE)
.where("$COL_MANGA_ID = ?")
.whereArgs(obj.mangaId)
.build()
}
| app/src/main/java/exh/metadata/sql/mappers/SearchMetadataTypeMapping.kt | 2057458799 |
package eu.kanade.tachiyomi.ui.library
import android.os.Bundle
import com.jakewharton.rxrelay.BehaviorRelay
import eu.kanade.tachiyomi.data.cache.CoverCache
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Category
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.models.MangaCategory
import eu.kanade.tachiyomi.data.download.DownloadManager
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.source.LocalSource
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
import eu.kanade.tachiyomi.util.combineLatest
import eu.kanade.tachiyomi.util.isNullOrUnsubscribed
import exh.favorites.FavoritesSyncHelper
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.io.IOException
import java.io.InputStream
import java.util.ArrayList
import java.util.Collections
import java.util.Comparator
/**
* Class containing library information.
*/
private data class Library(val categories: List<Category>, val mangaMap: LibraryMap)
/**
* Typealias for the library manga, using the category as keys, and list of manga as values.
*/
private typealias LibraryMap = Map<Int, List<LibraryItem>>
/**
* Presenter of [LibraryController].
*/
class LibraryPresenter(
private val db: DatabaseHelper = Injekt.get(),
private val preferences: PreferencesHelper = Injekt.get(),
private val coverCache: CoverCache = Injekt.get(),
private val sourceManager: SourceManager = Injekt.get(),
private val downloadManager: DownloadManager = Injekt.get()
) : BasePresenter<LibraryController>() {
private val context = preferences.context
/**
* Categories of the library.
*/
var categories: List<Category> = emptyList()
private set
/**
* Relay used to apply the UI filters to the last emission of the library.
*/
private val filterTriggerRelay = BehaviorRelay.create(Unit)
/**
* Relay used to apply the UI update to the last emission of the library.
*/
private val downloadTriggerRelay = BehaviorRelay.create(Unit)
/**
* Relay used to apply the selected sorting method to the last emission of the library.
*/
private val sortTriggerRelay = BehaviorRelay.create(Unit)
/**
* Library subscription.
*/
private var librarySubscription: Subscription? = null
// --> EXH
val favoritesSync = FavoritesSyncHelper(context)
// <-- EXH
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
subscribeLibrary()
}
/**
* Subscribes to library if needed.
*/
fun subscribeLibrary() {
if (librarySubscription.isNullOrUnsubscribed()) {
librarySubscription = getLibraryObservable()
.combineLatest(downloadTriggerRelay.observeOn(Schedulers.io()),
{ lib, _ -> lib.apply { setDownloadCount(mangaMap) } })
.combineLatest(filterTriggerRelay.observeOn(Schedulers.io()),
{ lib, _ -> lib.copy(mangaMap = applyFilters(lib.mangaMap)) })
.combineLatest(sortTriggerRelay.observeOn(Schedulers.io()),
{ lib, _ -> lib.copy(mangaMap = applySort(lib.mangaMap)) })
.observeOn(AndroidSchedulers.mainThread())
.subscribeLatestCache({ view, (categories, mangaMap) ->
view.onNextLibraryUpdate(categories, mangaMap)
})
}
}
/**
* Applies library filters to the given map of manga.
*
* @param map the map to filter.
*/
private fun applyFilters(map: LibraryMap): LibraryMap {
val filterDownloaded = preferences.filterDownloaded().getOrDefault()
val filterUnread = preferences.filterUnread().getOrDefault()
val filterCompleted = preferences.filterCompleted().getOrDefault()
val filterFn: (LibraryItem) -> Boolean = f@ { item ->
// Filter when there isn't unread chapters.
if (filterUnread && item.manga.unread == 0) {
return@f false
}
if (filterCompleted && item.manga.status != SManga.COMPLETED) {
return@f false
}
// Filter when there are no downloads.
if (filterDownloaded) {
// Local manga are always downloaded
if (item.manga.source == LocalSource.ID) {
return@f true
}
// Don't bother with directory checking if download count has been set.
if (item.downloadCount != -1) {
return@f item.downloadCount > 0
}
return@f downloadManager.getDownloadCount(item.manga) > 0
}
true
}
return map.mapValues { entry -> entry.value.filter(filterFn) }
}
/**
* Sets downloaded chapter count to each manga.
*
* @param map the map of manga.
*/
private fun setDownloadCount(map: LibraryMap) {
if (!preferences.downloadBadge().getOrDefault()) {
// Unset download count if the preference is not enabled.
for ((_, itemList) in map) {
for (item in itemList) {
item.downloadCount = -1
}
}
return
}
for ((_, itemList) in map) {
for (item in itemList) {
item.downloadCount = downloadManager.getDownloadCount(item.manga)
}
}
}
/**
* Applies library sorting to the given map of manga.
*
* @param map the map to sort.
*/
private fun applySort(map: LibraryMap): LibraryMap {
val sortingMode = preferences.librarySortingMode().getOrDefault()
val lastReadManga by lazy {
var counter = 0
db.getLastReadManga().executeAsBlocking().associate { it.id!! to counter++ }
}
val totalChapterManga by lazy {
var counter = 0
db.getTotalChapterManga().executeAsBlocking().associate { it.id!! to counter++ }
}
val sortFn: (LibraryItem, LibraryItem) -> Int = { i1, i2 ->
when (sortingMode) {
LibrarySort.ALPHA -> i1.manga.title.compareTo(i2.manga.title, true)
LibrarySort.LAST_READ -> {
// Get index of manga, set equal to list if size unknown.
val manga1LastRead = lastReadManga[i1.manga.id!!] ?: lastReadManga.size
val manga2LastRead = lastReadManga[i2.manga.id!!] ?: lastReadManga.size
manga1LastRead.compareTo(manga2LastRead)
}
LibrarySort.LAST_UPDATED -> i2.manga.last_update.compareTo(i1.manga.last_update)
LibrarySort.UNREAD -> i1.manga.unread.compareTo(i2.manga.unread)
LibrarySort.TOTAL -> {
val manga1TotalChapter = totalChapterManga[i1.manga.id!!] ?: 0
val mange2TotalChapter = totalChapterManga[i2.manga.id!!] ?: 0
manga1TotalChapter.compareTo(mange2TotalChapter)
}
LibrarySort.SOURCE -> {
val source1Name = sourceManager.getOrStub(i1.manga.source).name
val source2Name = sourceManager.getOrStub(i2.manga.source).name
source1Name.compareTo(source2Name)
}
else -> throw Exception("Unknown sorting mode")
}
}
val comparator = if (preferences.librarySortingAscending().getOrDefault())
Comparator(sortFn)
else
Collections.reverseOrder(sortFn)
return map.mapValues { entry -> entry.value.sortedWith(comparator) }
}
/**
* Get the categories and all its manga from the database.
*
* @return an observable of the categories and its manga.
*/
private fun getLibraryObservable(): Observable<Library> {
return Observable.combineLatest(getCategoriesObservable(), getLibraryMangasObservable(),
{ dbCategories, libraryManga ->
val categories = if (libraryManga.containsKey(0))
arrayListOf(Category.createDefault()) + dbCategories
else
dbCategories
this.categories = categories
Library(categories, libraryManga)
})
}
/**
* Get the categories from the database.
*
* @return an observable of the categories.
*/
private fun getCategoriesObservable(): Observable<List<Category>> {
return db.getCategories().asRxObservable()
}
/**
* Get the manga grouped by categories.
*
* @return an observable containing a map with the category id as key and a list of manga as the
* value.
*/
private fun getLibraryMangasObservable(): Observable<LibraryMap> {
val libraryAsList = preferences.libraryAsList()
return db.getLibraryMangas().asRxObservable()
.map { list ->
list.map { LibraryItem(it, libraryAsList) }.groupBy { it.manga.category }
}
}
/**
* Requests the library to be filtered.
*/
fun requestFilterUpdate() {
filterTriggerRelay.call(Unit)
}
/**
* Requests the library to have download badges added.
*/
fun requestDownloadBadgesUpdate() {
downloadTriggerRelay.call(Unit)
}
/**
* Requests the library to be sorted.
*/
fun requestSortUpdate() {
sortTriggerRelay.call(Unit)
}
/**
* Called when a manga is opened.
*/
fun onOpenManga() {
// Avoid further db updates for the library when it's not needed
librarySubscription?.let { remove(it) }
}
/**
* Returns the common categories for the given list of manga.
*
* @param mangas the list of manga.
*/
fun getCommonCategories(mangas: List<Manga>): Collection<Category> {
if (mangas.isEmpty()) return emptyList()
return mangas.toSet()
.map { db.getCategoriesForManga(it).executeAsBlocking() }
.reduce { set1: Iterable<Category>, set2 -> set1.intersect(set2) }
}
/**
* Remove the selected manga from the library.
*
* @param mangas the list of manga to delete.
* @param deleteChapters whether to also delete downloaded chapters.
*/
fun removeMangaFromLibrary(mangas: List<Manga>, deleteChapters: Boolean) {
// Create a set of the list
val mangaToDelete = mangas.distinctBy { it.id }
mangaToDelete.forEach { it.favorite = false }
Observable.fromCallable { db.insertMangas(mangaToDelete).executeAsBlocking() }
.onErrorResumeNext { Observable.empty() }
.subscribeOn(Schedulers.io())
.subscribe()
Observable.fromCallable {
mangaToDelete.forEach { manga ->
coverCache.deleteFromCache(manga.thumbnail_url)
if (deleteChapters) {
val source = sourceManager.get(manga.source) as? HttpSource
if (source != null) {
downloadManager.deleteManga(manga, source)
}
}
}
}
.subscribeOn(Schedulers.io())
.subscribe()
}
/**
* Move the given list of manga to categories.
*
* @param categories the selected categories.
* @param mangas the list of manga to move.
*/
fun moveMangasToCategories(categories: List<Category>, mangas: List<Manga>) {
val mc = ArrayList<MangaCategory>()
for (manga in mangas) {
for (cat in categories) {
mc.add(MangaCategory.create(manga, cat))
}
}
db.setMangaCategories(mc, mangas)
}
/**
* Update cover with local file.
*
* @param inputStream the new cover.
* @param manga the manga edited.
* @return true if the cover is updated, false otherwise
*/
@Throws(IOException::class)
fun editCoverWithStream(inputStream: InputStream, manga: Manga): Boolean {
if (manga.source == LocalSource.ID) {
LocalSource.updateCover(context, manga, inputStream)
return true
}
if (manga.thumbnail_url != null && manga.favorite) {
coverCache.copyToCache(manga.thumbnail_url!!, inputStream)
return true
}
return false
}
}
| app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryPresenter.kt | 798377756 |
package eu.kanade.tachiyomi.data.track.myanimelist
import android.content.Context
import android.graphics.Color
import androidx.annotation.StringRes
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.track.TrackService
import eu.kanade.tachiyomi.data.track.model.TrackSearch
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import uy.kohesive.injekt.injectLazy
class MyAnimeList(private val context: Context, id: Long) : TrackService(id) {
companion object {
const val READING = 1
const val COMPLETED = 2
const val ON_HOLD = 3
const val DROPPED = 4
const val PLAN_TO_READ = 6
const val REREADING = 7
private const val SEARCH_ID_PREFIX = "id:"
private const val SEARCH_LIST_PREFIX = "my:"
}
private val json: Json by injectLazy()
private val interceptor by lazy { MyAnimeListInterceptor(this, getPassword()) }
private val api by lazy { MyAnimeListApi(client, interceptor) }
@StringRes
override fun nameRes() = R.string.tracker_myanimelist
override val supportsReadingDates: Boolean = true
override fun getLogo() = R.drawable.ic_tracker_mal
override fun getLogoColor() = Color.rgb(46, 81, 162)
override fun getStatusList(): List<Int> {
return listOf(READING, COMPLETED, ON_HOLD, DROPPED, PLAN_TO_READ, REREADING)
}
override fun getStatus(status: Int): String = with(context) {
when (status) {
READING -> getString(R.string.reading)
PLAN_TO_READ -> getString(R.string.plan_to_read)
COMPLETED -> getString(R.string.completed)
ON_HOLD -> getString(R.string.on_hold)
DROPPED -> getString(R.string.dropped)
REREADING -> getString(R.string.repeating)
else -> ""
}
}
override fun getReadingStatus(): Int = READING
override fun getRereadingStatus(): Int = REREADING
override fun getCompletionStatus(): Int = COMPLETED
override fun getScoreList(): List<String> {
return IntRange(0, 10).map(Int::toString)
}
override fun displayScore(track: Track): String {
return track.score.toInt().toString()
}
private suspend fun add(track: Track): Track {
return api.updateItem(track)
}
override suspend fun update(track: Track, didReadChapter: Boolean): Track {
if (track.status != COMPLETED) {
if (didReadChapter) {
if (track.last_chapter_read.toInt() == track.total_chapters && track.total_chapters > 0) {
track.status = COMPLETED
track.finished_reading_date = System.currentTimeMillis()
} else if (track.status != REREADING) {
track.status = READING
if (track.last_chapter_read == 1F) {
track.started_reading_date = System.currentTimeMillis()
}
}
}
}
return api.updateItem(track)
}
override suspend fun bind(track: Track, hasReadChapters: Boolean): Track {
val remoteTrack = api.findListItem(track)
return if (remoteTrack != null) {
track.copyPersonalFrom(remoteTrack)
track.media_id = remoteTrack.media_id
if (track.status != COMPLETED) {
val isRereading = track.status == REREADING
track.status = if (isRereading.not() && hasReadChapters) READING else track.status
}
update(track)
} else {
// Set default fields if it's not found in the list
track.status = if (hasReadChapters) READING else PLAN_TO_READ
track.score = 0F
add(track)
}
}
override suspend fun search(query: String): List<TrackSearch> {
if (query.startsWith(SEARCH_ID_PREFIX)) {
query.substringAfter(SEARCH_ID_PREFIX).toIntOrNull()?.let { id ->
return listOf(api.getMangaDetails(id))
}
}
if (query.startsWith(SEARCH_LIST_PREFIX)) {
query.substringAfter(SEARCH_LIST_PREFIX).let { title ->
return api.findListItems(title)
}
}
return api.search(query)
}
override suspend fun refresh(track: Track): Track {
return api.findListItem(track) ?: add(track)
}
override suspend fun login(username: String, password: String) = login(password)
suspend fun login(authCode: String) {
try {
val oauth = api.getAccessToken(authCode)
interceptor.setAuth(oauth)
val username = api.getCurrentUser()
saveCredentials(username, oauth.access_token)
} catch (e: Throwable) {
logout()
}
}
override fun logout() {
super.logout()
trackPreferences.trackToken(this).delete()
interceptor.setAuth(null)
}
fun saveOAuth(oAuth: OAuth?) {
trackPreferences.trackToken(this).set(json.encodeToString(oAuth))
}
fun loadOAuth(): OAuth? {
return try {
json.decodeFromString<OAuth>(trackPreferences.trackToken(this).get())
} catch (e: Exception) {
null
}
}
}
| app/src/main/java/eu/kanade/tachiyomi/data/track/myanimelist/MyAnimeList.kt | 336936459 |
/*
* Copyright 2017 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nomic.app.cli
import nomic.app.NomicApp
import nomic.app.config.TypesafeConfig
import nomic.core.BoxRef
import kotlin.system.exitProcess
/**
* @author [email protected]
*/
object RemoveCliCommand {
fun main(args: Array<String>) {
if (args.size < 1) {
printHelp()
exitProcess(1)
}
val app = NomicApp.createDefault()
val ref = BoxRef.parse(args[0])
app.uninstall(ref)
}
fun printHelp() {
println("nomic remove [box ref.]")
}
} | nomic-app/src/main/kotlin/nomic/app/cli/RemoveCliCommand.kt | 565042279 |
package me.toptas.rssreader.mocks
import android.app.Application
import dagger.Provides
import me.toptas.rssreader.di.NetworkModule
import me.toptas.rssreader.features.main.MainRepository
import me.toptas.rssreader.features.rss.*
import me.toptas.rssreader.network.RssService
import javax.inject.Singleton
class MockNetworkModule : NetworkModule() {
@Provides
@Singleton
override fun provideRssRepository(service: RssService): RssRepository = MockRssRepository()
@Provides
@Singleton
override fun provideMainRepository(app: Application): MainRepository = MockMainRepository()
} | app/src/androidTest/java/me/toptas/rssreader/mocks/MockNetworkModule.kt | 4183864463 |
package expo.modules.updates.selectionpolicy
import expo.modules.updates.db.entity.UpdateEntity
import org.json.JSONObject
class SelectionPolicy(
val launcherSelectionPolicy: LauncherSelectionPolicy,
val loaderSelectionPolicy: LoaderSelectionPolicy,
val reaperSelectionPolicy: ReaperSelectionPolicy
) {
fun selectUpdateToLaunch(updates: List<UpdateEntity>, filters: JSONObject?): UpdateEntity? {
return launcherSelectionPolicy.selectUpdateToLaunch(updates, filters)
}
fun selectUpdatesToDelete(
updates: List<UpdateEntity>,
launchedUpdate: UpdateEntity,
filters: JSONObject?
): List<UpdateEntity> {
return reaperSelectionPolicy.selectUpdatesToDelete(updates, launchedUpdate, filters)
}
fun shouldLoadNewUpdate(
newUpdate: UpdateEntity?,
launchedUpdate: UpdateEntity?,
filters: JSONObject?
): Boolean {
return loaderSelectionPolicy.shouldLoadNewUpdate(newUpdate, launchedUpdate, filters)
}
}
| packages/expo-updates/android/src/main/java/expo/modules/updates/selectionpolicy/SelectionPolicy.kt | 522446157 |
package info.nightscout.androidaps.utils
/**
* class contains useful String functions
*/
object StringUtils {
fun removeSurroundingQuotes(input: String): String {
var string = input
if (string.length >= 2 && string[0] == '"' && string[string.length - 1] == '"') {
string = string.substring(1, string.length - 1)
}
return string
}
} | core/src/main/java/info/nightscout/androidaps/utils/StringUtils.kt | 3630531329 |
package com.github.ahant.validator.annotation
/**
* Created by ahant on 8/29/2016.
*/
@Target(AnnotationTarget.FIELD)
@MustBeDocumented
annotation class CollectionType(
val minSize: Int = 1) | src/main/kotlin/com/github/ahant/validator/annotation/CollectionType.kt | 3354289477 |
package org.unbrokendome.gradle.plugins.xjc.work.common
import java.util.Locale
fun withDefaultLocale(locale: Locale?, action: () -> Unit) {
if (locale != null && locale != Locale.getDefault()) {
val oldLocale = Locale.getDefault()
Locale.setDefault(locale)
try {
action()
} finally {
Locale.setDefault(oldLocale)
}
} else {
action()
}
}
| src/xjcCommon/kotlin/org/unbrokendome/gradle/plugins/xjc/work/common/LocaleHelper.kt | 2104467183 |
package biz.eventually.atpl.data
import android.content.Context
import biz.eventually.atpl.data.dao.LastCallDao
import biz.eventually.atpl.data.db.Question
import biz.eventually.atpl.data.db.Source
import biz.eventually.atpl.data.db.Subject
import biz.eventually.atpl.data.service.SourceService
import biz.eventually.atpl.utils.Prefields.PREF_TOKEN
import biz.eventually.atpl.utils.prefsGetString
import biz.eventually.atpl.utils.prefsGetValue
import io.reactivex.Observable
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by Thibault de Lambilly on 21/03/17.
*
*/
@Singleton
class DataProvider @Inject constructor(private val sourceService: SourceService, val context: Context, val lastCallDao: LastCallDao) {
fun dataGetSources(lastCall: Long = 0L): Observable<List<Source>> {
return sourceService.loadSources(lastCall).map { api -> toAppSources(api.data) }
}
fun dataGetSubjects(sourceId: Long, lastCall: Long = 0L): Observable<List<Subject>> {
return sourceService.loadSubjects(sourceId, lastCall).map { api -> toAppSubjects(sourceId, api.data) }
}
fun dataGetTopicQuestions(topicId: Long, startFirst: Boolean, lastCall: Long = 0L): Observable<List<Question>> {
val questions = when (startFirst) {
true -> sourceService.loadQuestionsStarred(topicId, lastCall)
false -> sourceService.loadQuestions(topicId, lastCall)
}
return questions.map { response ->
response.data?.questions?.let { toAppQuestions(topicId, it) } ?: listOf()
}
}
}
| app/src/main/java/biz/eventually/atpl/data/DataProvider.kt | 1188383710 |
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.storage.api
import arcs.core.data.CreatableStorageKey
import arcs.core.storage.CapabilitiesResolver
import arcs.core.storage.DefaultDriverFactory
import arcs.core.storage.DriverProvider
import arcs.core.storage.StorageKeyManager
import arcs.core.storage.StorageKeyParser
import arcs.core.storage.database.DatabaseManager
import arcs.core.storage.driver.DatabaseDriverProvider
import arcs.core.storage.driver.RamDiskDriverProvider
import arcs.core.storage.driver.VolatileDriverProvider
import arcs.core.storage.keys.DatabaseStorageKey
import arcs.core.storage.keys.ForeignStorageKey
import arcs.core.storage.keys.JoinStorageKey
import arcs.core.storage.keys.RamDiskStorageKey
import arcs.core.storage.keys.VolatileStorageKey
import arcs.core.storage.referencemode.ReferenceModeStorageKey
/**
* Singleton to allow the caller to set up storage [DriverProvider]s and the [StorageKeyParser].
*/
object DriverAndKeyConfigurator {
/**
* Allows the caller to configure & register [DriverProvider]s as well as the
* [StorageKeyParser].
*/
// TODO: make the set of drivers/keyparsers configurable.
fun configure(databaseManager: DatabaseManager?) {
val driverProviders = mutableListOf(
RamDiskDriverProvider(),
VolatileDriverProvider()
)
// Only register the database driver provider if a database manager was provided.
databaseManager?.let {
driverProviders += DatabaseDriverProvider.configure(it)
}
DefaultDriverFactory.update(driverProviders)
// Also register the parsers.
configureKeyParsersAndFactories()
}
/**
* A convenience method to register behavior for the commonly used set of [StorageKey]s.
*
* Registers a number of likely-used [StorageKey]s with the global []StorageKeyParser] instance,
* and registers a number of like-used [StorageKeyFactory] instances with the global
* [CapabilitiesResolver] instance.
*/
fun configureKeyParsersAndFactories() {
// Start fresh.
StorageKeyManager.GLOBAL_INSTANCE.reset(
VolatileStorageKey,
RamDiskStorageKey,
DatabaseStorageKey.Persistent,
DatabaseStorageKey.Memory,
CreatableStorageKey,
ReferenceModeStorageKey,
JoinStorageKey,
ForeignStorageKey
)
CapabilitiesResolver.reset()
CapabilitiesResolver.registerStorageKeyFactory(VolatileStorageKey.VolatileStorageKeyFactory())
CapabilitiesResolver.registerStorageKeyFactory(RamDiskStorageKey.RamDiskStorageKeyFactory())
CapabilitiesResolver.registerStorageKeyFactory(DatabaseStorageKey.Persistent.Factory())
CapabilitiesResolver.registerStorageKeyFactory(DatabaseStorageKey.Memory.Factory())
}
}
| java/arcs/core/storage/api/DriverAndKeyConfigurator.kt | 1306077106 |
package com.nytclient.module.main
import com.nytclient.module.news.NewsFragment
import com.nytclient.module.news.NewsFragmentModule
import dagger.Module
import dagger.android.ContributesAndroidInjector
/**
* Created by Dogan Gulcan on 9/17/17.
*/
@Module
abstract class MainFragmentModule {
@ContributesAndroidInjector(modules = arrayOf(NewsFragmentModule::class))
abstract fun provideNewsFragment(): NewsFragment
} | app/src/main/java/com/nytclient/module/main/MainFragmentModule.kt | 1977235360 |
package bz.stew.bracken.ui.pages.browse.view.mixins
import bz.stew.bracken.ui.common.bill.BillAction
import bz.stew.bracken.ui.common.view.SubTemplate
import bz.stew.bracken.ui.extension.kotlinx.DlTitleFunc
import bz.stew.bracken.ui.extension.kotlinx.HtmlFunc
import bz.stew.bracken.ui.extension.kotlinx.horzizontalDescriptionList
import bz.stew.bracken.ui.util.date.DateFormatter
import kotlinx.html.FlowContent
import kotlinx.html.p
class ActionsList(private val actionsList: Set<BillAction>) : SubTemplate {
override fun renderIn(root: FlowContent) {
val descriptionListMap: MutableMap<DlTitleFunc, HtmlFunc> = mutableMapOf()
for (action in actionsList) {
descriptionListMap.put({
it.text(DateFormatter.prettyDate(action.actedAtDate()))
}, {
it.p {
+action.getText()
}
})
}
root.horzizontalDescriptionList(descriptionListMap)
}
} | ui/src/main/kotlin/bz/stew/bracken/ui/pages/browse/view/mixins/ActionsList.kt | 3008016336 |
package com.watchtower.networking
import android.content.Context
import bolts.CancellationToken
import bolts.Task
import bolts.TaskCompletionSource
import com.watchtower.storage.model.JokeApiModel
import retrofit.*
class ApiClient() {
//region Properties
private val service: APIEndpointInterface
//endregion
//region Init
init {
val retrofit = Retrofit.Builder()
.baseUrl("http://api.icndb.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
service = retrofit.create(APIEndpointInterface::class.java);
}
//endregion
//region Public API Methods
fun getRandomJoke(cancellationToken: CancellationToken) : Task<JokeApiModel> {
val tcs = TaskCompletionSource<JokeApiModel>()
val call = service.getRandomJoke()
// Cancel web call as soon as we request cancellation
cancellationToken.register {
call.cancel()
}
// Enqueue this call so it gets executed asyncronously on a bg thread
call.enqueue( object: Callback<JokeApiModel> {
override fun onFailure(t: Throwable?) {
tcs.setError(Exception(t?.message))
}
override fun onResponse(response: Response<JokeApiModel>?, retrofit: Retrofit?) {
if( response != null ) {
tcs.setResult(response.body())
} else {
tcs.setError(Exception("Null Response"))
}
}
})
return tcs.task
}
//endregion
}
| Watchtower/app/src/main/java/com/watchtower/networking/ApiClient.kt | 2628236934 |
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
@file:Suppress("UNCHECKED_CAST")
package arcs.core.data.expression
import arcs.core.data.expression.Expression.BinaryExpression
import arcs.core.data.expression.Expression.BinaryOp
import arcs.core.data.expression.Expression.Scope
import arcs.core.data.expression.Expression.UnaryExpression
import arcs.core.data.expression.Expression.UnaryOp
import arcs.core.util.BigInt
import arcs.core.util.Json
import arcs.core.util.JsonValue
import arcs.core.util.JsonValue.JsonArray
import arcs.core.util.JsonValue.JsonBoolean
import arcs.core.util.JsonValue.JsonNull
import arcs.core.util.JsonValue.JsonNumber
import arcs.core.util.JsonValue.JsonObject
import arcs.core.util.JsonValue.JsonString
import arcs.core.util.JsonVisitor
import arcs.core.util.toBigInt
/** Traverses a tree of [Expression] objects, serializing it into a JSON format. */
class ExpressionSerializer() : Expression.Visitor<JsonValue<*>, Unit> {
override fun <E, T> visit(expr: UnaryExpression<E, T>, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString(expr.op.token),
"expr" to expr.expr.accept(this, ctx)
)
)
override fun <L, R, T> visit(expr: BinaryExpression<L, R, T>, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString(expr.op.token),
"left" to expr.left.accept(this, ctx),
"right" to expr.right.accept(this, ctx)
)
)
override fun <T> visit(expr: Expression.FieldExpression<T>, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("."),
"qualifier" to (expr.qualifier?.accept(this, ctx) ?: JsonNull),
"field" to JsonString(expr.field),
"nullSafe" to JsonBoolean(expr.nullSafe)
)
)
override fun <T> visit(expr: Expression.QueryParameterExpression<T>, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("?"),
"identifier" to JsonString(expr.paramIdentifier)
)
)
override fun visit(expr: Expression.NumberLiteralExpression, ctx: Unit) = toNumber(expr.value)
override fun visit(expr: Expression.TextLiteralExpression, ctx: Unit) = JsonString(expr.value)
override fun visit(expr: Expression.BooleanLiteralExpression, ctx: Unit) =
JsonBoolean(expr.value)
override fun visit(expr: Expression.NullLiteralExpression, ctx: Unit) = JsonNull
override fun visit(expr: Expression.FromExpression, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("from"),
"source" to expr.source.accept(this, ctx),
"var" to JsonString(expr.iterationVar),
"qualifier" to (expr.qualifier?.accept(this, ctx) ?: JsonNull)
)
)
override fun visit(expr: Expression.WhereExpression, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("where"),
"expr" to expr.expr.accept(this, ctx),
"qualifier" to expr.qualifier.accept(this, ctx)
)
)
override fun visit(expr: Expression.LetExpression, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("let"),
"expr" to expr.variableExpr.accept(this, ctx),
"var" to JsonString(expr.variableName),
"qualifier" to (expr.qualifier.accept(this, ctx))
)
)
override fun <T> visit(expr: Expression.SelectExpression<T>, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("select"),
"expr" to expr.expr.accept(this, ctx),
"qualifier" to expr.qualifier.accept(this, ctx)
)
)
override fun visit(expr: Expression.NewExpression, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("new"),
"schemaName" to JsonArray(expr.schemaName.map { JsonString(it) }),
"fields" to JsonObject(
expr.fields.associateBy({ it.first }, { it.second.accept(this, ctx) })
)
)
)
override fun <T> visit(expr: Expression.FunctionExpression<T>, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("function"),
"functionName" to JsonString(expr.function.name),
"arguments" to JsonArray(
expr.arguments.map { it.accept(this, ctx) })
)
)
override fun <T> visit(expr: Expression.OrderByExpression<T>, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("orderBy"),
"selectors" to JsonArray(expr.selectors.map { sel ->
JsonArray(listOf(sel.expr.accept(this, ctx), JsonBoolean(sel.descending)))
}
),
"qualifier" to expr.qualifier.accept(this, ctx)
)
)
}
/** Traverses a parsed [JsonValue] representation and returns decoded [Expression] */
class ExpressionDeserializer : JsonVisitor<Expression<*>> {
override fun visit(value: JsonBoolean) = Expression.BooleanLiteralExpression(value.value)
override fun visit(value: JsonString) = Expression.TextLiteralExpression(value.value)
override fun visit(value: JsonNumber) = Expression.NumberLiteralExpression(value.value)
override fun visit(value: JsonNull) = Expression.NullLiteralExpression()
override fun visit(value: JsonArray) =
throw IllegalArgumentException("Arrays should not appear in JSON Serialized Expressions")
override fun visit(value: JsonObject): Expression<*> {
val type = value["op"].string()!!
return when {
type == "." -> Expression.FieldExpression<Any>(
if (value["qualifier"] == JsonNull) {
null
} else {
visit(value["qualifier"]) as Expression<Scope>
},
value["field"].string()!!,
value["nullSafe"].bool()!!
)
BinaryOp.fromToken(type) != null -> {
BinaryExpression(
BinaryOp.fromToken(type) as BinaryOp<Any, Any, Any>,
visit(value["left"]) as Expression<Any>,
visit(value["right"]) as Expression<Any>
)
}
UnaryOp.fromToken(type) != null -> {
UnaryExpression(
UnaryOp.fromToken(type)!! as UnaryOp<Any, Any>,
visit(value["expr"]) as Expression<Any>
)
}
type == "number" -> Expression.NumberLiteralExpression(fromNumber(value))
type == "?" -> Expression.QueryParameterExpression<Any>(value["identifier"].string()!!)
type == "from" ->
Expression.FromExpression(
if (value["qualifier"] == JsonNull) {
null
} else {
visit(value["qualifier"].obj()!!) as Expression<Sequence<Scope>>
},
visit(value["source"].obj()!!) as Expression<Sequence<Any>>,
value["var"].string()!!
)
type == "where" ->
Expression.WhereExpression(
visit(value["qualifier"].obj()!!) as Expression<Sequence<Scope>>,
visit(value["expr"]) as Expression<Boolean>
)
type == "let" ->
Expression.LetExpression(
visit(value["qualifier"].obj()!!) as Expression<Sequence<Scope>>,
visit(value["expr"]) as Expression<Any>,
value["var"].string()!!
)
type == "select" ->
Expression.SelectExpression(
visit(value["qualifier"].obj()!!) as Expression<Sequence<Scope>>,
visit(value["expr"]) as Expression<Sequence<Any>>
)
type == "new" ->
Expression.NewExpression(
value["schemaName"].array()!!.value.map { it.string()!! }.toSet(),
value["fields"].obj()!!.value.map { (name, expr) ->
name to visit(expr)
}.toList()
)
type == "function" ->
Expression.FunctionExpression<Any>(
GlobalFunction.of(value["functionName"].string()!!),
value["arguments"].array()!!.value.map { visit(it) }.toList()
)
type == "orderBy" ->
Expression.OrderByExpression<Any>(
visit(value["qualifier"].obj()!!) as Expression<Sequence<Scope>>,
value["selectors"].array()!!.value.map {
val array = it as JsonArray
Expression.OrderByExpression.Selector(
visit(array[0]) as Expression<Any>,
it[1].bool()!!
)
}.toList()
)
else -> throw IllegalArgumentException("Unknown type $type during deserialization")
}
}
}
/** Given an expression, return a string representation. */
fun <T> Expression<T>.serialize() = this.accept(ExpressionSerializer(), Unit).toString()
/** Given a serialized [Expression], deserialize it. */
fun String.deserializeExpression() = ExpressionDeserializer().visit(Json.parse(this))
private fun toNumberType(value: Number) = when (value) {
is Float -> "F"
is Int -> "I"
is Short -> "S"
is Double -> "D"
is BigInt -> "BI"
is Long -> "L"
is Byte -> "B"
else -> throw IllegalArgumentException("Unknown type of number $value, ${value::class}")
}
private fun toDouble(value: JsonObject) = value["value"].string()!!.toDouble()
private fun toInt(value: JsonObject) = value["value"].string()!!.toInt()
private fun fromNumber(value: JsonObject): Number = when (value["type"].string()!!) {
"F" -> toDouble(value).toFloat()
"D" -> toDouble(value)
"I" -> toInt(value)
"S" -> toInt(value).toShort()
"B" -> toInt(value).toByte()
"L" -> value["value"].string()!!.toLong()
"BI" -> value["value"].string()!!.toBigInt()
else -> throw IllegalArgumentException("Unknown numeric type ${value["type"]}")
}
private fun toNumber(value: Number) = JsonObject(
mutableMapOf(
"op" to JsonString("number"),
"type" to JsonString(toNumberType(value)),
"value" to JsonString(value.toString())
)
)
| java/arcs/core/data/expression/Serializer.kt | 452793233 |
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.yank
import com.maddyhome.idea.vim.action.motion.updown.MotionDownLess1FirstNonSpaceAction
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.getLineEndForOffset
import com.maddyhome.idea.vim.api.getLineStartForOffset
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.Argument
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.command.SelectionType
import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.listener.VimYankListener
import org.jetbrains.annotations.Contract
import kotlin.math.min
open class YankGroupBase : VimYankGroup {
private val yankListeners: MutableList<VimYankListener> = ArrayList()
protected fun yankRange(
editor: VimEditor,
caretToRange: Map<VimCaret, TextRange>,
range: TextRange,
type: SelectionType,
startOffsets: Map<VimCaret, Int>?,
): Boolean {
startOffsets?.forEach { (caret, offset) ->
caret.moveToOffset(offset)
}
notifyListeners(editor, range)
var result = true
for ((caret, myRange) in caretToRange) {
result = caret.registerStorage.storeText(caret, editor, myRange, type, false) && result
}
return result
}
@Contract("_, _ -> new")
protected fun getTextRange(ranges: List<Pair<Int, Int>>, type: SelectionType): TextRange? {
if (ranges.isEmpty()) return null
val size = ranges.size
val starts = IntArray(size)
val ends = IntArray(size)
if (type == SelectionType.LINE_WISE) {
starts[size - 1] = ranges[size - 1].first
ends[size - 1] = ranges[size - 1].second
for (i in 0 until size - 1) {
val range = ranges[i]
starts[i] = range.first
ends[i] = range.second - 1
}
} else {
for (i in 0 until size) {
val range = ranges[i]
starts[i] = range.first
ends[i] = range.second
}
}
return TextRange(starts, ends)
}
/**
* This yanks the text moved over by the motion command argument.
*
* @param editor The editor to yank from
* @param context The data context
* @param count The number of times to yank
* @param rawCount The actual count entered by the user
* @param argument The motion command argument
* @return true if able to yank the text, false if not
*/
override fun yankMotion(
editor: VimEditor,
context: ExecutionContext,
argument: Argument,
operatorArguments: OperatorArguments
): Boolean {
val motion = argument.motion
val type = if (motion.isLinewiseMotion()) SelectionType.LINE_WISE else SelectionType.CHARACTER_WISE
val nativeCaretCount = editor.nativeCarets().size
if (nativeCaretCount <= 0) return false
val carretToRange = HashMap<VimCaret, TextRange>(nativeCaretCount)
val ranges = ArrayList<Pair<Int, Int>>(nativeCaretCount)
// This logic is from original vim
val startOffsets = if (argument.motion.action is MotionDownLess1FirstNonSpaceAction) null else HashMap<VimCaret, Int>(nativeCaretCount)
for (caret in editor.nativeCarets()) {
val motionRange = injector.motion.getMotionRange(editor, caret, context, argument, operatorArguments)
?: continue
assert(motionRange.size() == 1)
ranges.add(motionRange.startOffset to motionRange.endOffset)
startOffsets?.put(caret, motionRange.normalize().startOffset)
carretToRange[caret] = TextRange(motionRange.startOffset, motionRange.endOffset)
}
val range = getTextRange(ranges, type) ?: return false
if (range.size() == 0) return false
return yankRange(
editor,
carretToRange,
range,
type,
startOffsets
)
}
/**
* This yanks count lines of text
*
* @param editor The editor to yank from
* @param count The number of lines to yank
* @return true if able to yank the lines, false if not
*/
override fun yankLine(editor: VimEditor, count: Int): Boolean {
val caretCount = editor.nativeCarets().size
val ranges = ArrayList<Pair<Int, Int>>(caretCount)
val caretToRange = HashMap<VimCaret, TextRange>(caretCount)
for (caret in editor.nativeCarets()) {
val start = injector.motion.moveCaretToCurrentLineStart(editor, caret)
val end = min(injector.motion.moveCaretToRelativeLineEnd(editor, caret, count - 1, true) + 1, editor.fileSize().toInt())
if (end == -1) continue
ranges.add(start to end)
caretToRange[caret] = TextRange(start, end)
}
val range = getTextRange(ranges, SelectionType.LINE_WISE) ?: return false
return yankRange(editor, caretToRange, range, SelectionType.LINE_WISE, null)
}
/**
* This yanks a range of text
*
* @param editor The editor to yank from
* @param range The range of text to yank
* @param type The type of yank
* @return true if able to yank the range, false if not
*/
override fun yankRange(editor: VimEditor, range: TextRange?, type: SelectionType, moveCursor: Boolean): Boolean {
range ?: return false
val caretToRange = HashMap<VimCaret, TextRange>()
val selectionType = if (type == SelectionType.CHARACTER_WISE && range.isMultiple) SelectionType.BLOCK_WISE else type
if (type == SelectionType.LINE_WISE) {
for (i in 0 until range.size()) {
if (editor.offsetToBufferPosition(range.startOffsets[i]).column != 0) {
range.startOffsets[i] = editor.getLineStartForOffset(range.startOffsets[i])
}
if (editor.offsetToBufferPosition(range.endOffsets[i]).column != 0) {
range.endOffsets[i] =
(editor.getLineEndForOffset(range.endOffsets[i]) + 1).coerceAtMost(editor.fileSize().toInt())
}
}
}
val rangeStartOffsets = range.startOffsets
val rangeEndOffsets = range.endOffsets
val startOffsets = HashMap<VimCaret, Int>(editor.nativeCarets().size)
if (type == SelectionType.BLOCK_WISE) {
startOffsets[editor.primaryCaret()] = range.normalize().startOffset
caretToRange[editor.primaryCaret()] = range
} else {
for ((i, caret) in editor.nativeCarets().withIndex()) {
val textRange = TextRange(rangeStartOffsets[i], rangeEndOffsets[i])
startOffsets[caret] = textRange.normalize().startOffset
caretToRange[caret] = textRange
}
}
return if (moveCursor) {
yankRange(editor, caretToRange, range, selectionType, startOffsets)
} else {
yankRange(editor, caretToRange, range, selectionType, null)
}
}
override fun addListener(listener: VimYankListener) = yankListeners.add(listener)
override fun removeListener(listener: VimYankListener) = yankListeners.remove(listener)
override fun notifyListeners(editor: VimEditor, textRange: TextRange) = yankListeners.forEach {
it.yankPerformed(editor, textRange)
}
}
| vim-engine/src/main/kotlin/com/maddyhome/idea/vim/yank/YankGroupBase.kt | 3471668928 |
/*
* Copyright 2019 Poly Forest, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui.formatters
import com.acornui.obj.removeNullValues
import com.acornui.i18n.Locale
import com.acornui.system.userInfo
import com.acornui.time.Date
import kotlin.js.Date as JsDate
/**
* This class formats dates into localized string representations.
*/
class DateTimeFormatter(
/**
* The date formatting style to use when called.
*/
dateStyle: DateTimeStyle? = null,
/**
* The time formatting style to use when called.
*/
timeStyle: DateTimeStyle? = null,
/**
* The number of fractional seconds to apply when calling format(). Valid values are 0-3.
*/
fractionalSecondsDigit: Int? = null,
calendar: Calendar? = null,
dayPeriod: DayPeriod? = null,
numberingSystem: NumberingSystem? = null,
/**
* The locale matching algorithm to use.
*/
localeMatcher: LocaleMatcher = LocaleMatcher.BEST_FIT,
/**
* The time zone for formatting.
* The only values this is guaranteed to work with are "UTC" or null.
* Other values that will likely work based on browser or jvm implementation are the full TZ code
* [https://en.wikipedia.org/wiki/List_of_tz_database_time_zones]
* For example, use "America/New_York" as opposed to "EST"
* If this is null, the user's timezone will be used.
*/
timeZone: String? = null,
/**
* Whether to use 12-hour time (as opposed to 24-hour time). Possible values are true and false; the default is
* locale dependent. This option overrides the hc language tag and/or the hourCycle option in case both are present.
*/
hour12: Boolean? = null,
/**
* The hour cycle to use. This option overrides the hc language tag, if both are present, and the hour12 option
* takes precedence in case both options have been specified.
*/
hourCycle: HourCycle? = null,
/**
* The format matching algorithm to use.
* See the following paragraphs for information about the use of this property.
*/
formatMatcher: FormatMatcher? = null,
weekday: WeekdayFormat? = null,
era: EraFormat? = null,
year: YearFormat? = null,
month: MonthFormat? = null,
day: TimePartFormat? = null,
hour: TimePartFormat? = null,
minute: TimePartFormat? = null,
second: TimePartFormat? = null,
timeZoneName: TimezoneNameFormat? = null,
/**
* The ordered locale chain to use for formatting. If this is left null, the user's current locale will be used.
*
* See [Locale Identification](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation)
*/
locales: List<Locale>? = null
) : StringFormatter<Date> {
private val formatter: dynamic
init {
@Suppress("LocalVariableName")
val JsDateTimeFormat = js("Intl.DateTimeFormat")
val options = js("({})")
options.dateStyle = dateStyle?.name.toJsValue()
options.timeStyle = timeStyle?.name.toJsValue()
options.fractionalSecondsDigit = fractionalSecondsDigit
options.calendar = calendar?.name.toJsValue()
options.dayPeriod = dayPeriod?.name.toJsValue()
options.numberingSystem = numberingSystem?.name.toJsValue()
options.localeMatcher = localeMatcher.name.toJsValue()
options.timeZone = timeZone
options.hour12 = hour12
options.hourCycle = hourCycle?.name.toJsValue()
options.formatMatcher = formatMatcher?.name.toJsValue()
options.weekday = weekday?.name.toJsValue()
options.era = era?.name.toJsValue()
options.year = year?.name.toJsValue()
options.month = month?.name.toJsValue()
options.day = day?.name.toJsValue()
options.hour = hour?.name.toJsValue()
options.minute = minute?.name.toJsValue()
options.second = second?.name.toJsValue()
options.timeZoneName = timeZoneName?.name.toJsValue()
removeNullValues(options)
val loc = (locales ?: userInfo.systemLocale).map { it.value }.toTypedArray()
formatter = JsDateTimeFormat(loc, options)
}
override fun format(value: Date): String =
formatter!!.format(value.jsDate).unsafeCast<String>()
}
enum class DateTimeStyle {
FULL,
LONG,
MEDIUM,
SHORT
}
enum class DayPeriod {
NARROW,
SHORT,
LONG
}
enum class NumberingSystem {
ARAB,
ARABEXT,
BALI,
BENG,
DEVA,
FULLWIDE,
GUJR,
GURU,
HANIDEC,
KHMR,
KNDA,
LAOO,
LATN,
LIMB,
MLYM,
MONG,
MYMR,
ORYA,
TAMLDEC,
TELU,
THAI,
TIBT
}
enum class LocaleMatcher {
LOOKUP,
BEST_FIT
}
enum class FormatMatcher {
BASIC,
BEST_FIT
}
enum class HourCycle {
H11,
H12,
H23,
H24
}
enum class DateTimeFormatStyle {
FULL,
LONG,
MEDIUM,
SHORT,
DEFAULT
}
enum class Calendar {
BUDDHIST,
CHINESE,
COPTIC,
ETHIOPIA,
ETHIOPIC,
GREGORY,
HEBREW,
INDIAN,
ISLAMIC,
ISO8601,
JAPANESE,
PERSIAN,
ROC
}
enum class WeekdayFormat {
/**
* E.g. Thursday
*/
LONG,
/**
* E.g. Thu
*/
SHORT,
/**
* E.g. T
*/
NARROW
}
enum class EraFormat {
/**
* E.g. Anno Domini
*/
LONG,
/**
* E.g. AD
*/
SHORT,
/**
* E.g. A
*/
NARROW
}
enum class YearFormat {
/**
* E.g. 2012
*/
NUMERIC,
/**
* E.g. 12
*/
TWO_DIGIT
}
enum class MonthFormat {
/**
* E.g. 2
*/
NUMERIC,
/**
* E.g. 02
*/
TWO_DIGIT,
/**
* E.g. March
*/
LONG,
/**
* E.g. Mar
*/
SHORT,
/**
* E.g. M
*/
NARROW
}
enum class TimePartFormat {
/**
* E.g. 1
*/
NUMERIC,
/**
* E.g. 01
*/
TWO_DIGIT
}
enum class TimezoneNameFormat {
/**
* E.g. British Summer Time
*/
LONG,
/**
* E.g. GMT+1
*/
SHORT
}
/**
* Converts a two digit year to a four digit year, relative to [currentYear].
* @param year If this is not a two digit year, it will be returned as is. Otherwise, it will be considered relative
* to [currentYear]. That is, the year returned will be in the century of the span of
* `currentYear - 49 to currentYear + 50`.
*/
fun calculateFullYear(year: Int, allowTwoDigitYears: Boolean = true, currentYear: Int = JsDate().getFullYear()): Int? {
return if (year < 100) {
// Two digit year
if (!allowTwoDigitYears) return null
val window = (currentYear + 50) % 100
if (year <= window) {
year + ((currentYear + 50) / 100) * 100
} else {
year + ((currentYear - 49) / 100) * 100
}
} else year
}
private val daysOfWeekCache = HashMap<Pair<Boolean, List<Locale>?>, List<String>>()
/**
* Returns a list of the localized days of the week.
* @param locales The locales to use for lookup. Use null for the user's locale.
*/
fun getDaysOfWeek(longFormat: Boolean, locales: List<Locale>? = null): List<String> {
val cacheKey = longFormat to locales
if (daysOfWeekCache.containsKey(cacheKey)) return daysOfWeekCache[cacheKey]!!
val list = ArrayList<String>(7)
val formatter = DateTimeFormatter(
weekday = if (longFormat) WeekdayFormat.LONG else WeekdayFormat.SHORT,
locales = locales
)
val d = Date(0)
val offset = d.dayOfMonth - d.dayOfWeek
for (i in 0..11) {
list.add(formatter.format(Date(year = 0, month = 1, day = i + offset)))
}
daysOfWeekCache[cacheKey] = list
return list
}
private val monthsOfYearCache = HashMap<Pair<Boolean, List<Locale>?>, List<String>>()
/**
* Returns a list of the localized months of the year.
*
* @param longFormat If true, the whole month names will be returned instead of the abbreviations.
* @param locales The locale chain to use for parsing. If this is null, then [com.acornui.system.UserInfo.currentLocale]
* will be used from [com.acornui.system.userInfo].
*/
fun getMonths(longFormat: Boolean, locales: List<Locale>? = null): List<String> {
val cacheKey = longFormat to locales
if (monthsOfYearCache.containsKey(cacheKey)) return monthsOfYearCache[cacheKey]!!
val list = ArrayList<String>(12)
val formatter = DateTimeFormatter(
month = if (longFormat) MonthFormat.LONG else MonthFormat.SHORT,
locales = locales
)
for (i in 1..12) {
list.add(formatter.format(Date(year = 0, month = i, day = 1)))
}
monthsOfYearCache[cacheKey] = list
return list
}
private fun String?.toJsValue(): String? {
if (this == null) return null
return if (this == "TWO_DIGIT") "2-digit" // Special case.
else toLowerCase().replace('_', ' ')
} | acornui-core/src/main/kotlin/com/acornui/formatters/DateTimeFormatter.kt | 2347026632 |
package com.fashare.mvvm_juejin.repo
import com.google.gson.Gson
/**
* Response 返回结果
*/
class Response<T> {
companion object Initializer {
private val GSON: Gson by lazy { Gson() }
}
var s = -1 // errorCode
var m = "" // errorMsg
var d: T? = null // data
override fun toString(): String {
return GSON.toJson(this)
}
}
| app/src/main/kotlin/com/fashare/mvvm_juejin/repo/Response.kt | 1755031902 |
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.helper
import com.intellij.DynamicBundle
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
@NonNls
private const val IDEAVIM_BUNDLE = "messages.IdeaVimBundle"
object MessageHelper : DynamicBundle(IDEAVIM_BUNDLE) {
const val BUNDLE = IDEAVIM_BUNDLE
@JvmStatic
fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) = getMessage(key, *params)
@JvmStatic
fun message(@PropertyKey(resourceBundle = BUNDLE) key: String) = getMessage(key)
}
| src/main/java/com/maddyhome/idea/vim/helper/MessageHelper.kt | 3562123874 |
package org.hexworks.zircon.api.builder.component
import org.hexworks.zircon.api.component.HBox
import org.hexworks.zircon.api.component.builder.base.BaseContainerBuilder
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.internal.component.impl.DefaultHBox
import org.hexworks.zircon.internal.component.renderer.DefaultHBoxRenderer
import org.hexworks.zircon.internal.dsl.ZirconDsl
import kotlin.math.max
import kotlin.jvm.JvmStatic
@Suppress("UNCHECKED_CAST")
@ZirconDsl
class HBoxBuilder private constructor() : BaseContainerBuilder<HBox, HBoxBuilder>(DefaultHBoxRenderer()) {
var spacing: Int = 0
set(value) {
require(value >= 0) {
"Can't use a negative spacing"
}
field = value
}
fun withSpacing(spacing: Int) = also {
this.spacing = spacing
}
override fun build(): HBox {
return DefaultHBox(
componentMetadata = createMetadata(),
renderingStrategy = createRenderingStrategy(),
initialTitle = title,
spacing = spacing,
).apply {
addComponents(*childrenToAdd.toTypedArray())
}.attachListeners()
}
override fun createCopy() = newBuilder()
.withProps(props.copy())
.withSpacing(spacing)
.withChildren(*childrenToAdd.toTypedArray())
@Suppress("DuplicatedCode")
override fun calculateContentSize(): Size {
if (childrenToAdd.isEmpty()) {
return Size.one()
}
var width = 0
var maxHeight = 0
childrenToAdd
.map { it.size }
.forEach {
width += it.width
maxHeight = max(maxHeight, it.height)
}
if (spacing > 0) {
width += childrenToAdd.size * spacing - 1
}
return Size.create(max(1, width), maxHeight)
}
companion object {
@JvmStatic
fun newBuilder() = HBoxBuilder()
}
}
| zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/component/HBoxBuilder.kt | 2236654427 |
package org.wordpress.android.ui.posts
import android.os.Bundle
import org.wordpress.android.ui.posts.PrepublishingHomeItemUiState.ActionType
interface PrepublishingActionClickedListener {
fun onActionClicked(actionType: ActionType, bundle: Bundle? = null)
fun onSubmitButtonClicked(publishPost: PublishPost)
}
| WordPress/src/main/java/org/wordpress/android/ui/posts/PrepublishingActionClickedListener.kt | 544579197 |
package org.wordpress.android.ui.posts
import android.annotation.SuppressLint
import android.os.Parcelable
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.parcelize.Parcelize
import org.wordpress.android.ui.posts.BasicDialogViewModel.DialogInteraction.Dismissed
import org.wordpress.android.ui.posts.BasicDialogViewModel.DialogInteraction.Negative
import org.wordpress.android.ui.posts.BasicDialogViewModel.DialogInteraction.Positive
import org.wordpress.android.viewmodel.Event
import javax.inject.Inject
class BasicDialogViewModel
@Inject constructor() : ViewModel() {
private val _onInteraction = MutableLiveData<Event<DialogInteraction>>()
val onInteraction = _onInteraction as LiveData<Event<DialogInteraction>>
fun showDialog(manager: FragmentManager, model: BasicDialogModel) {
val dialog = BasicDialog()
dialog.initialize(model)
dialog.show(manager, model.tag)
}
fun onPositiveClicked(tag: String) {
_onInteraction.postValue(Event(Positive(tag)))
}
fun onNegativeButtonClicked(tag: String) {
_onInteraction.postValue(Event(Negative(tag)))
}
fun onDismissByOutsideTouch(tag: String) {
_onInteraction.postValue(Event(Dismissed(tag)))
}
@Parcelize
@SuppressLint("ParcelCreator")
data class BasicDialogModel(
val tag: String,
val title: String? = null,
val message: String,
val positiveButtonLabel: String,
val negativeButtonLabel: String? = null,
val cancelButtonLabel: String? = null
) : Parcelable
sealed class DialogInteraction(open val tag: String) {
data class Positive(override val tag: String) : DialogInteraction(tag)
data class Negative(override val tag: String) : DialogInteraction(tag)
data class Dismissed(override val tag: String) : DialogInteraction(tag)
}
}
| WordPress/src/main/java/org/wordpress/android/ui/posts/BasicDialogViewModel.kt | 2369375606 |
package b
class C: a.B() {
fun test() {
super.t()
}
} | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/misc/superReferences/before/b/usage.kt | 792245953 |
// WITH_STDLIB
class C {
fun foo() = "c"
val bar = "C"
}
class D {
fun foo() = "d"
val bar = "D"
}
val d = D()
val x = d.apply {
C().<caret>let {
foo() + it.foo() + bar + it.bar
}
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/scopeFunctions/letToRun/qualifyThisWithLambda.kt | 3396835340 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.console
/**
* The [PyConsoleProcessFinishedException] is thrown when IDE is waiting for
* the reply from Python console and the Python console process is discovered
* to be finished.
*
* @see [synchronizedPythonConsoleClient]
*/
class PyConsoleProcessFinishedException(exitValue: Int)
: RuntimeException("Console already exited with value: $exitValue while waiting for an answer.") | python/src/com/jetbrains/python/console/PyConsoleProcessFinishedException.kt | 1001412007 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hints
import com.intellij.codeInsight.hints.presentation.SequencePresentation
import com.intellij.openapi.editor.Inlay
class InlineInlayRenderer(
constrainedPresentations: Collection<ConstrainedPresentation<*, HorizontalConstraints>>
) : LinearOrderInlayRenderer<HorizontalConstraints>(
constrainedPresentations = constrainedPresentations,
createPresentation = { constrained ->
when (constrained.size) {
1 -> constrained.first().root
else -> SequencePresentation(constrained.map { it.root })
}
}
) {
override fun isAcceptablePlacement(placement: Inlay.Placement): Boolean {
return placement == Inlay.Placement.INLINE
}
}
| platform/lang-impl/src/com/intellij/codeInsight/hints/InlineInlayRenderer.kt | 2301993408 |
/*
* DateTest.kt
*
* Copyright 2019 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.test
import au.id.micolous.metrodroid.time.getYMD
import au.id.micolous.metrodroid.time.yearToDays
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import java.util.*
/**
* Testing the Date functions
*/
class DateTest {
@Test
fun testYearToDays() {
// Before 1600 java calendar switches to Julian calendar.
// I don't think there were any contactless payment cards for horse
// carriages, so we don't care
for (year in 1600..10000) {
val d = yearToDays(year)
val g = GregorianCalendar(TimeZone.getTimeZone("UTC"))
g.timeInMillis = 0
g.set(Calendar.YEAR, year)
val expectedD = g.timeInMillis / (86400L * 1000L)
assertEquals(d, expectedD.toInt(),
"Wrong days for year $year: $d vs $expectedD")
}
}
@Test
fun testGetYMD() {
// years 1697 to 2517
for (days in (-100000)..200000) {
val ymd = getYMD(days)
val g = GregorianCalendar(TimeZone.getTimeZone("UTC"))
g.timeInMillis = days * 86400L * 1000L
val expectedY = g.get(Calendar.YEAR)
val expectedM = g.get(Calendar.MONTH)
val expectedD = g.get(Calendar.DAY_OF_MONTH)
assertEquals (ymd.year, expectedY,
"Wrong year for days $days: ${ymd.year} vs $expectedY")
assertEquals (ymd.month.zeroBasedIndex, expectedM,
"Wrong month for days $days: ${ymd.month} vs $expectedM")
assertEquals (ymd.day, expectedD,
"Wrong days for days $days: ${ymd.day} vs $expectedD")
}
}
@Test
fun testRoundTrip() {
// Cover over 4 years to check bisextile
for (days in 0..2000) {
val ymd = getYMD(days)
assertEquals (ymd.daysSinceEpoch, days,
"Wrong roundtrip $days vs ${ymd.daysSinceEpoch}")
}
}
}
| src/jvmCommonTest/kotlin/au/id/micolous/metrodroid/test/DateTest.kt | 3458060457 |
import authscreen.AuthScreen
fun main() {
val person = Person()
val programmer = Programmer("John", "Smith", "Kotlin")
programmer.preferredLanguage
programmer.firstName
printGreeting("Nate")
"message to log".log()
println(KEY_ID)
screenCount++
val result = AuthScreen.RESULT_AUTHENTICATED
val authScreen = AuthScreen() // wont compile
import authscreen.AuthScreen
val screen = AuthScreen.create()
} | kotlin/Mastering-Kotlin-master/Chapter07/src/Main.kt | 2913036318 |
/*
* RavKavLookup.kt
*
* Copyright 2018 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.ravkav
import au.id.micolous.metrodroid.multi.FormattedString
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.MetroTimeZone
import au.id.micolous.metrodroid.transit.Station
import au.id.micolous.metrodroid.transit.TransitCurrency
import au.id.micolous.metrodroid.transit.Trip
import au.id.micolous.metrodroid.transit.en1545.En1545LookupSTR
import au.id.micolous.metrodroid.util.StationTableReader
private const val RAVKAV_STR = "ravkav"
internal object RavKavLookup : En1545LookupSTR(RAVKAV_STR) {
override val timeZone: MetroTimeZone
get() = MetroTimeZone.JERUSALEM
override fun getRouteName(routeNumber: Int?, routeVariant: Int?, agency: Int?, transport: Int?): FormattedString? {
if (routeNumber == null || routeNumber == 0)
return null
if (agency != null && agency == EGGED)
return FormattedString((routeNumber % 1000).toString())
return FormattedString(routeNumber.toString())
}
override fun parseCurrency(price: Int)= TransitCurrency.ILS(price)
// Irrelevant as RavKAv has EventCode
override fun getMode(agency: Int?, route: Int?): Trip.Mode = Trip.Mode.OTHER
private const val EGGED = 0x3
override val subscriptionMap = mapOf(
641 to R.string.ravkav_generic_trips // generic trips
)
override fun getStation(station: Int, agency: Int?, transport: Int?): Station? {
if (station == 0)
return null
return StationTableReader.getStation(
RAVKAV_STR,
station,
station.toString())
}
}
| src/commonMain/kotlin/au/id/micolous/metrodroid/transit/ravkav/RavKavLookup.kt | 822664719 |
package io.github.bkmioa.nexusrss.download
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.os.Build
import android.widget.Toast
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import io.github.bkmioa.nexusrss.R
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
object RemoteDownloader {
fun download(context: Context, downloadNode: DownloadNode, torrentUrl: String, path: String? = null) {
download(context, DownloadTask(downloadNode, torrentUrl, path))
}
fun download(context: Context, downloadTask: DownloadTask) {
val app = context.applicationContext
Toast.makeText(context, R.string.downloading, Toast.LENGTH_SHORT).show()
val ignore = downloadTask.downloadNode.download(downloadTask.torrentUrl, downloadTask.path)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
Toast.makeText(app, it, Toast.LENGTH_SHORT).show()
}, {
it.printStackTrace()
showFailure(context, downloadTask, it.message)
Toast.makeText(app, it.message, Toast.LENGTH_SHORT).show()
})
}
private fun showFailure(context: Context, task: DownloadTask, message: String?) {
val code = task.torrentUrl.hashCode()
val downloadIntent = DownloadReceiver.createDownloadIntent(context, code, task)
var flag = PendingIntent.FLAG_UPDATE_CURRENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
flag = flag or PendingIntent.FLAG_IMMUTABLE
}
val retryIntent= PendingIntent.getBroadcast(context, code, downloadIntent, flag)
val retryAction = NotificationCompat.Action.Builder(R.drawable.ic_refresh, "retry", retryIntent)
.build()
val notification = NotificationCompat.Builder(context, createChannelIfNeeded(context))
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(0)
.setContentTitle("Download Failure")
.setContentText(message)
.setAutoCancel(true)
.addAction(retryAction)
.build()
NotificationManagerCompat.from(context)
.notify(code, notification)
}
private fun createChannelIfNeeded(context: Context): String {
val channelId = "download_state"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(channelId, "Download State", NotificationManager.IMPORTANCE_DEFAULT)
NotificationManagerCompat.from(context).createNotificationChannel(channel)
}
return channelId
}
} | app/src/main/java/io/github/bkmioa/nexusrss/download/RemoteDownloader.kt | 814299545 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.core.designsystem.component
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons
/**
* Now in Android view toggle button with included trailing icon as well as compact and expanded
* text label content slots.
*
* @param expanded Whether the view toggle is currently in expanded mode or compact mode.
* @param onExpandedChange Called when the user clicks the button and toggles the mode.
* @param modifier Modifier to be applied to the button.
* @param enabled Controls the enabled state of the button. When `false`, this button will not be
* clickable and will appear disabled to accessibility services.
* @param compactText The text label content to show in expanded mode.
* @param expandedText The text label content to show in compact mode.
*/
@Composable
fun NiaViewToggleButton(
expanded: Boolean,
onExpandedChange: (Boolean) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
compactText: @Composable () -> Unit,
expandedText: @Composable () -> Unit
) {
NiaTextButton(
onClick = { onExpandedChange(!expanded) },
modifier = modifier,
enabled = enabled,
text = if (expanded) expandedText else compactText,
trailingIcon = {
Icon(
imageVector = if (expanded) NiaIcons.ViewDay else NiaIcons.ShortText,
contentDescription = null
)
}
)
}
| core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/component/ViewToggle.kt | 4247690730 |
package com.startwithnah.android.helpyourself
import org.junit.Test
import org.junit.Assert.*
/**
* 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)
}
} | kotlin/developer-android/HelpYourself/app/src/test/java/com/startwithnah/android/helpyourself/ExampleUnitTest.kt | 3399292121 |
@file:Suppress("unused")
package instep.dao.sql
import instep.Instep
import java.sql.Connection
import java.sql.ResultSet
import java.time.temporal.Temporal
@Suppress("UNCHECKED_CAST")
val planExecutor: SQLPlanExecutor<SQLPlan<*>>
get() = Instep.make(SQLPlanExecutor::class.java) as SQLPlanExecutor<SQLPlan<*>>
/**
* @see [SQLPlanExecutor.execute]
*/
@Throws(SQLPlanExecutionException::class)
fun SQLPlan<*>.execute() {
planExecutor.execute(this)
}
/**
* @see [SQLPlanExecutor.execute]
*/
@Throws(SQLPlanExecutionException::class)
fun <T : Any> SQLPlan<*>.execute(cls: Class<T>): List<T> {
return planExecutor.execute(this, cls)
}
/**
* @see [SQLPlanExecutor.executeString]
*/
@Throws(SQLPlanExecutionException::class)
fun SQLPlan<*>.executeString(): String {
return planExecutor.executeString(this)
}
/**
* @see [SQLPlanExecutor.executeLong]
*/
@Throws(SQLPlanExecutionException::class)
fun SQLPlan<*>.executeLong(): Long {
return planExecutor.executeLong(this)
}
/**
* @see [SQLPlanExecutor.executeDouble]
*/
@Throws(SQLPlanExecutionException::class)
fun SQLPlan<*>.executeDouble(): Double {
return planExecutor.executeDouble(this)
}
/**
* @see [SQLPlanExecutor.executeTemporal]
*/
@Throws(SQLPlanExecutionException::class)
fun <R : Temporal> SQLPlan<*>.executeTemporal(cls: Class<R>): R? {
return planExecutor.executeTemporal(this, cls)
}
/**
* @see [SQLPlanExecutor.executeUpdate]
*/
@Throws(SQLPlanExecutionException::class)
fun SQLPlan<*>.executeUpdate(): Int {
return planExecutor.executeUpdate(this)
}
/**
* @see [SQLPlanExecutor.executeResultSet]
*/
@Throws(SQLPlanExecutionException::class)
fun SQLPlan<*>.executeResultSet(conn: Connection): ResultSet {
return planExecutor.executeResultSet(conn, this)
}
/**
* @see [SQLPlanExecutor.execute]
*/
@Throws(SQLPlanExecutionException::class)
fun TableSelectPlan.execute(): List<TableRow> {
return planExecutor.execute(this, TableRow::class.java)
}
/**
* @see [SQLPlanExecutor.execute]
*/
@Throws(SQLPlanExecutionException::class)
fun <T : Any> TableSelectPlan.execute(cls: Class<T>): List<T> {
return planExecutor.execute(this, cls)
}
| dao/src/main/kotlin/instep/dao/sql/SQLPlanExtensions.kt | 2339438846 |
package org.snakeskin.dsl
/**
* @author Cameron Earle
* @version 1/9/18
*/
typealias PistonState = org.snakeskin.logic.PistonState
typealias ShifterState = org.snakeskin.logic.ShifterState | SnakeSkin-FRC/src/main/kotlin/org/snakeskin/dsl/FRCAliases.kt | 3406730308 |
package io.ipoli.android.challenge.usecase
import io.ipoli.android.TestUtil
import io.ipoli.android.challenge.entity.Challenge
import io.ipoli.android.challenge.preset.PresetChallenge
import io.ipoli.android.challenge.usecase.CreateChallengeFromPresetUseCase.PhysicalCharacteristics.Gender
import io.ipoli.android.challenge.usecase.CreateChallengeFromPresetUseCase.PhysicalCharacteristics.Units
import io.ipoli.android.common.datetime.days
import io.ipoli.android.common.datetime.minutes
import io.ipoli.android.friends.feed.data.Post
import io.ipoli.android.quest.Color
import io.ipoli.android.quest.Icon
import io.ipoli.android.repeatingquest.usecase.SaveQuestsForRepeatingQuestUseCase
import io.ipoli.android.repeatingquest.usecase.SaveRepeatingQuestUseCase
import org.amshove.kluent.`should be equal to`
import org.amshove.kluent.`should be in range`
import org.amshove.kluent.`should equal`
import org.amshove.kluent.mock
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.threeten.bp.LocalDate
import java.util.*
class CreateChallengeFromPresetUseCaseSpek : Spek({
describe("CreateChallengeFromPresetUseCase") {
fun createPresetChallenge(
quests: List<PresetChallenge.Quest> = emptyList(),
habits: List<PresetChallenge.Habit> = emptyList()
) =
PresetChallenge(
id = UUID.randomUUID().toString(),
name = "c",
color = Color.BLUE,
icon = Icon.ACADEMIC,
shortDescription = "",
description = "",
category = PresetChallenge.Category.ADVENTURE,
imageUrl = "",
duration = 30.days,
busynessPerWeek = 120.minutes,
difficulty = Challenge.Difficulty.EASY,
requirements = emptyList(),
level = 1,
trackedValues = emptyList(),
expectedResults = emptyList(),
gemPrice = 0,
note = "",
config = PresetChallenge.Config(),
schedule = PresetChallenge.Schedule(
quests = quests,
habits = habits
),
status = Post.Status.APPROVED,
author = null,
participantCount = 0
)
fun createNutritionChallenge() =
createPresetChallenge().copy(
config = createPresetChallenge().config.copy(
nutritionMacros = PresetChallenge.NutritionMacros(
female = PresetChallenge.NutritionDetails(
caloriesPerKg = 1f,
proteinPerKg = 1f,
carbohydratesPerKg = 1f,
fatPerKg = 1f
),
male = PresetChallenge.NutritionDetails(
caloriesPerKg = 1f,
proteinPerKg = 1f,
carbohydratesPerKg = 1f,
fatPerKg = 1f
)
)
)
)
fun executeUseCase(params: CreateChallengeFromPresetUseCase.Params): Challenge {
val sc = SaveChallengeUseCase(
TestUtil.challengeRepoMock(),
SaveQuestsForChallengeUseCase(
questRepository = TestUtil.questRepoMock(),
repeatingQuestRepository = TestUtil.repeatingQuestRepoMock(),
saveRepeatingQuestUseCase = SaveRepeatingQuestUseCase(
questRepository = TestUtil.questRepoMock(),
repeatingQuestRepository = TestUtil.repeatingQuestRepoMock(),
saveQuestsForRepeatingQuestUseCase = SaveQuestsForRepeatingQuestUseCase(
TestUtil.questRepoMock(),
mock()
),
reminderScheduler = mock()
)
),
TestUtil.habitRepoMock(null)
)
return CreateChallengeFromPresetUseCase(sc, mock()).execute(params)
}
it("should create Challenge with Quests") {
val pc = createPresetChallenge(
quests = listOf(
PresetChallenge.Quest(
name = "q1",
color = Color.BLUE,
icon = Icon.ACADEMIC,
day = 1,
duration = 30.minutes,
subQuests = emptyList(),
note = ""
)
)
)
val c = executeUseCase(
CreateChallengeFromPresetUseCase.Params(
preset = pc,
schedule = pc.schedule
)
)
c.quests.size.`should be equal to`(1)
c.quests.first().scheduledDate.`should equal`(LocalDate.now())
}
it("should create Challenge with Habits") {
val pc = createPresetChallenge(
habits = listOf(
PresetChallenge.Habit(
name = "q1",
color = Color.BLUE,
icon = Icon.ACADEMIC,
isGood = true,
timesADay = 3,
isSelected = true
)
)
)
val c = executeUseCase(
CreateChallengeFromPresetUseCase.Params(
preset = pc,
schedule = pc.schedule
)
)
c.habits.size.`should be equal to`(1)
c.habits.first().timesADay.`should be equal to`(3)
}
it("should create Challenge that tracks weight") {
val pc = createNutritionChallenge()
val c = executeUseCase(
CreateChallengeFromPresetUseCase.Params(
preset = pc,
schedule = pc.schedule,
playerPhysicalCharacteristics = CreateChallengeFromPresetUseCase.PhysicalCharacteristics(
units = Units.METRIC,
gender = Gender.FEMALE,
weight = 60,
targetWeight = 50
)
)
)
val t =
c.trackedValues
.asSequence()
.filterIsInstance(Challenge.TrackedValue.Target::class.java)
.first()
t.startValue.`should be in range`(59.99, 60.01)
t.targetValue.`should be in range`(49.99, 50.01)
}
it("should create Challenge that tracks macros") {
val pc = createNutritionChallenge()
val c = executeUseCase(
CreateChallengeFromPresetUseCase.Params(
preset = pc,
schedule = pc.schedule,
playerPhysicalCharacteristics = CreateChallengeFromPresetUseCase.PhysicalCharacteristics(
units = Units.METRIC,
gender = Gender.FEMALE,
weight = 60,
targetWeight = 50
)
)
)
val atvs =
c.trackedValues
.filterIsInstance(Challenge.TrackedValue.Average::class.java)
atvs.size.`should be equal to`(4)
atvs.forEach {
it.targetValue.`should be in range`(59.99, 60.01)
}
}
}
})
| app/src/test/java/io/ipoli/android/challenge/usecase/CreateChallengeFromPresetUseCaseSpek.kt | 3783232185 |
package com.eden.orchid.api.site
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.tasks.TaskService.TaskType
import com.google.inject.name.Named
import javax.inject.Inject
class DevServerBaseUrlFactory
@Inject
constructor(
@Named("port") val port: Int
) : BaseUrlFactory("devServer", 100) {
override fun isEnabled(context: OrchidContext): Boolean = context.taskType == TaskType.SERVE
override fun getBaseUrl(context: OrchidContext): String = "http://localhost:${port}/"
}
| OrchidCore/src/main/kotlin/com/eden/orchid/api/site/DevServerBaseUrlFactory.kt | 4008888674 |
/*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.fasterxml.jackson.databind.ObjectMapper
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.api.pipeline.models.PipelineExecution
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import com.netflix.spinnaker.orca.api.pipeline.models.TaskExecution
import com.netflix.spinnaker.orca.exceptions.ExceptionHandler
import com.netflix.spinnaker.orca.ext.parent
import com.netflix.spinnaker.orca.jackson.OrcaObjectMapper
import com.netflix.spinnaker.orca.pipeline.model.StageExecutionImpl
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionNotFoundException
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository.ExecutionCriteria
import com.netflix.spinnaker.orca.q.CompleteExecution
import com.netflix.spinnaker.orca.q.ContinueParentStage
import com.netflix.spinnaker.orca.q.ExecutionLevel
import com.netflix.spinnaker.orca.q.InvalidExecutionId
import com.netflix.spinnaker.orca.q.InvalidStageId
import com.netflix.spinnaker.orca.q.InvalidTaskId
import com.netflix.spinnaker.orca.q.StageLevel
import com.netflix.spinnaker.orca.q.StartStage
import com.netflix.spinnaker.orca.q.TaskLevel
import com.netflix.spinnaker.q.Message
import com.netflix.spinnaker.q.MessageHandler
import java.time.Duration
import org.slf4j.Logger
import org.slf4j.LoggerFactory
internal interface OrcaMessageHandler<M : Message> : MessageHandler<M> {
companion object {
val log: Logger = LoggerFactory.getLogger(this::class.java)
val mapper: ObjectMapper = OrcaObjectMapper.getInstance()
val MIN_PAGE_SIZE = 2
}
val repository: ExecutionRepository
fun Collection<ExceptionHandler>.shouldRetry(ex: Exception, taskName: String?): ExceptionHandler.Response? {
val exceptionHandler = find { it.handles(ex) }
return exceptionHandler?.handle(taskName ?: "unspecified", ex)
}
fun TaskLevel.withTask(block: (StageExecution, TaskExecution) -> Unit) =
withStage { stage ->
stage
.taskById(taskId)
.let { task ->
if (task == null) {
log.error("InvalidTaskId: Unable to find task {} in stage '{}' while processing message {}", taskId, mapper.writeValueAsString(stage), this)
queue.push(InvalidTaskId(this))
} else {
block.invoke(stage, task)
}
}
}
fun StageLevel.withStage(block: (StageExecution) -> Unit) =
withExecution { execution ->
try {
execution
.stageById(stageId)
.also {
/**
* Mutates it.context in a required way (such as removing refId and requisiteRefIds from the
* context map) for some non-linear stage features.
*/
StageExecutionImpl(execution, it.type, it.context)
}
.let(block)
} catch (e: IllegalArgumentException) {
log.error("Failed to locate stage with id: {}", stageId, e)
queue.push(InvalidStageId(this))
}
}
fun ExecutionLevel.withExecution(block: (PipelineExecution) -> Unit) =
try {
val execution = repository.retrieve(executionType, executionId)
block.invoke(execution)
} catch (e: ExecutionNotFoundException) {
queue.push(InvalidExecutionId(this))
}
fun StageExecution.startNext() {
execution.let { execution ->
val downstreamStages = downstreamStages()
val phase = syntheticStageOwner
if (downstreamStages.isNotEmpty()) {
downstreamStages.forEach {
queue.push(StartStage(it))
}
} else if (phase != null) {
queue.ensure(ContinueParentStage(parent(), phase), Duration.ZERO)
} else {
queue.push(CompleteExecution(execution))
}
}
}
fun PipelineExecution.shouldQueue(): Boolean {
val configId = pipelineConfigId
return when {
configId == null -> false
!isLimitConcurrent -> {
return when {
maxConcurrentExecutions > 0 -> {
val criteria = ExecutionCriteria().setPageSize(maxConcurrentExecutions+MIN_PAGE_SIZE).setStatuses(RUNNING)
repository
.retrievePipelinesForPipelineConfigId(configId, criteria)
.filter { it.id != id }
.count()
.toBlocking()
.first() >= maxConcurrentExecutions
}
else -> false
}
}
else -> {
val criteria = ExecutionCriteria().setPageSize(MIN_PAGE_SIZE).setStatuses(RUNNING)
repository
.retrievePipelinesForPipelineConfigId(configId, criteria)
.filter { it.id != id }
.count()
.toBlocking()
.first() > 0
}
}
}
}
| orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/OrcaMessageHandler.kt | 1517628911 |
// IS_APPLICABLE: false
// WITH_STDLIB
fun test() {
val (i: Int, s: String)<caret> = Pair(1, "s")
} | plugins/kotlin/idea/tests/testData/intentions/specifyTypeExplicitlyInDestructuringAssignment/variableHasAllTypes.kt | 826640921 |
Subsets and Splits