repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/substring/ReplaceSubstringWithIndexingOperationInspection.kt | 3 | 2377 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.substring
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.psi.KtConstantExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
class ReplaceSubstringWithIndexingOperationInspection : ReplaceSubstringInspection() {
override fun inspectionText(element: KtDotQualifiedExpression): String =
KotlinBundle.message("inspection.replace.substring.with.indexing.operation.display.name")
override val defaultFixText: String get() = KotlinBundle.message("replace.substring.call.with.indexing.operation.call")
override val isAlwaysStable: Boolean = true
override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) {
val expression = element.callExpression?.valueArguments?.firstOrNull()?.getArgumentExpression() ?: return
element.replaceWith("$0[$1]", expression)
}
override fun isApplicableInner(element: KtDotQualifiedExpression): Boolean {
val arguments = element.callExpression?.valueArguments ?: return false
if (arguments.size != 2) return false
val arg1 = element.getValueArgument(0) ?: return false
val arg2 = element.getValueArgument(1) ?: return false
return arg1 + 1 == arg2
}
private fun KtDotQualifiedExpression.getValueArgument(index: Int): Int? {
val bindingContext = analyze()
val resolvedCall = callExpression.getResolvedCall(bindingContext) ?: return null
val expression = resolvedCall.call.valueArguments[index].getArgumentExpression() as? KtConstantExpression ?: return null
val constant = ConstantExpressionEvaluator.getConstant(expression, bindingContext) ?: return null
val constantType = bindingContext.getType(expression) ?: return null
return constant.getValue(constantType) as? Int
}
} | apache-2.0 | ceacc44ed497297d3696b8b260ec7331 | 53.045455 | 158 | 0.773244 | 5.07906 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/EntityPageTemplate.kt | 1 | 24837 | package alraune
import alraune.entity.*
import bolone.BiddingParamsDateValidationRanges
import bolone.BoFrontFuns
import bolone.TextField
import bolone.rp.new_BiddingParamsFields
import bolone.rp.new_BoloneRP_AssignWriter_Fields
import bolone.rp.new_OrderFields
import bolone.rp.nudgePaymentReminderTimeValidationRange
import pieces100.*
import vgrechka.*
class EntityPageTemplate {
private val alGetParams = GetParams()
val juan = EntityPageTemplate.Juan(this)
private val product = Product()
var pedro by notNullOnce<EntityPageTemplate.Pedro>()
var tabs = mutableListOf<Tab>()
val pencilButton by lazy {makePencilButton(juan.toLight())}
companion object {
val paramsTabID = "Params"
fun makePencilButton(lej: LightEptJuan): PencilButton<Any> = object : PencilButton<Any>({makePencilButton(lej)}) {
override fun makeFields() = EntityPageTemplate.makeFields()
override fun composeParamsModalBody(fields: BunchOfFields) = EntityPageTemplate.composeParamsModalBody(fields)
override fun hrefAfterParamsUpdated() = lej.reloadUrl
override fun makeMidAirComparisonPageHref(ourFields: BunchOfFields) = makeUsualMidAirComparisonPageHref_updatingUpdated {
val order1 = dbSelectOrderOrBailOut(lej.handle.id)
val order2 = cloneViaJson(order1)
populateEntityFromFields(order2, ourFields)
ooOrderParamsComparison_a2__killme(order1, order2)
}
override fun updateEntityParams(fields: BunchOfFields, forceOverwriteStale: Boolean) {
EntityPageTemplate.updateEntityParams(lej.handle, fields,
expectedOptimisticVersion = when {
forceOverwriteStale -> null
else -> lej.optimisticVersion
}
)
}
}
fun makeFields() = when {
isAdmin() -> OrderFields3__killme() // OrderFieldsForAdmin()
else -> OrderFields3__killme()
}
fun composeParamsModalBody(fields: BunchOfFields) =
composeOrderParamsFormBody_a2(fields as OrderFields3__killme)
fun updateEntityParams(handle: OrderHandle, fields: BunchOfFields, expectedOptimisticVersion: String? = null) {
doUpdateOrderParams__killme(handle, expectedOptimisticVersion, fields as OrderFields3__killme)
}
}
abstract class Pedro {
var juan by notNullOnce<Juan>()
abstract fun pageTitle(): String
open fun htmlHeadTitle() = pageTitle()
abstract fun pageSubTitle(): String?
abstract val noEntityWithIDMessage: String
open val noEntityWithUUIDMessage: String get() = imf("Override me")
abstract fun composeActionBannerBelowTitle(): Renderable
abstract fun shitIntoGetParams(p: GetParams)
abstract fun renderBelowActionBanner(): Renderable?
abstract fun addTabs(xs: MutableList<Tab>)
abstract fun canEditParams(): Boolean
abstract fun renderParamsTab(): Renderable
open fun isPagePrivate() = true
abstract fun impersonationMakesSense(impersonateAs: AlUserKind): Boolean // TODO:vgrechka Things like "writer looking at order in store?"
abstract fun pagePath(): String
abstract val table: String
open fun implicitEntityPO(): AlMaybe<Order> = imf("Override me")
open val uuidSupported = false
open fun shitIntoTopRightHamburgerDropdown(menu: MenuBuilder) {}
open fun renderingStuff1() = RenderingStuff1()
}
class Juan(val ept: EntityPageTemplate) {
var order by notNull<Order>()
var activeTab by notNullOnce<Tab>()
val afterEntityKnownActions = mutableListOf<() -> Unit>()
var initialParams by notNullOnce<GetParams>()
var skipIDs by notNull<List<Long>>()
val tabsTopRightContainer = div()
fun afterEntityKnown(f: () -> Unit) {
afterEntityKnownActions.add(f)
}
fun changeEntityStateAndReload(operationDescription: String, operationReason: String?, f: (Order) -> Unit) {
val entity = order
f(entity)
// TODO:vgrechka Operation
// entity.setOperation(AlOperationData_GenericEntityStateChange_V1.makeOperation(
// operationDescription, juan.entity.getEntity().getId(), operationReason));
rctx0.al.db2.update(entity)
btfEval(jsReload())
}
fun jsReload() = jsFreakingReload(ept.reloadUrl())
fun toLight(): LightEptJuan {
val order = order as Order
return LightEptJuan(handle = order.toHandle(), optimisticVersion = order.optimisticVersion,
reloadUrl = ept.reloadUrl(), reloadToFirstPageUrl = ept.reloadToFirstPageUrl(),
viewBucket = rctx0.al.viewBucketIfAdmin())
}
companion object {
fun jsFreakingReload(reloadUrl: String) = jsProgressyNavigate(reloadUrl, replaceState = true)
}
}
interface Tab {
fun id(): String
fun title(): String
fun addTopRightControls(trc: TopRightControls)
fun willRender() {}
fun render(): Renderable
}
class Product {
var spitPage by notNullOnce<SpitPage>()
}
var maybeEntity by notNullOnce<AlMaybe<Order>>()
fun maybeEntityPO(): AlMaybe<Order> {
val m = Order.Meta
val idParam = juan.initialParams.longId
val id = idParam.get()
val uuidParam = juan.initialParams.uuid
val uuid = uuidParam.get()
var column by notNullOnce<String>()
var displayColumn by notNullOnce<String>()
var value by notNullOnce<Any>()
when {
id != null -> {
column = m.id
displayColumn = "ID"
value = id
}
uuid != null -> {
column = m.uuid
displayColumn = "UUID"
value = uuid
}
else -> bailOutToLittleErrorPage(t("TOTE", "Я хочу в URL <b>${idParam.name}</b> либо <b>${uuidParam.name}</b>"))
}
fun displayColumnAndValue() = "$displayColumn <b>${escapeHtml(value.toString())}</b>"
val order = AlQueryBuilder()
.text("select * from ${m.table} where $column =", value)
.selectSimple(Order::class)
.oneOrNull()
?: bailOutToLittleErrorPage(rawHtml(t("TOTE", "Нет нихрена заказа с ${displayColumnAndValue()}")))
fun fuckYou(): Nothing = bailOutToLittleErrorPage(rawHtml(t("TOTE", "У тебя нет доступа к заказу с ${displayColumnAndValue()}")))
when (rctx0.al.site()) {
AlSite.BoloneCustomer -> {
if (uuid != null) {
// Always allow, if she knows UUID
} else {
imf("User should non-anonymous and order should be assigned to her")
}
}
AlSite.BoloneWriter -> {
val user = rctx0.al.maybeUser() ?: fuckYou()
val ass = order.data.assignment ?: fuckYou()
if (ass.writer.id != user.id) fuckYou()
}
AlSite.BoloneAdmin -> {}
}
return AlMaybe.Some(order)
}
fun entityId(entity: Order): Long = entity.id
fun build(pedro: EntityPageTemplate.Pedro): Product {
this.pedro = pedro
pedro.juan = juan
juan.initialParams = alGetParams.also {p->
if (isAdmin())
p.impersonate.defaultValue = AlUserKind.Admin
}
juan.skipIDs = juan.initialParams.skipIDs.bang()
// val addressingName = juan.initialParams.addressing.get()
// if (addressingName != null) {
// addressing = pedro.applicableEntityAddressings().find {it.name.equals(addressingName)} ?: imf("TODO:vgrechka Handle bad addressingName")
// }
maybeEntity = try {
maybeEntityPO()
} catch (e: AlShowUserDescriptiveFuckUpMessage) {
AlMaybe.None(e.renderable)
}
tabs.add(ParamsTab())
pedro.addTabs(tabs)
product.spitPage = object : SpitPage {
override fun spit() {
withNewContext1 {
val tabID = alGetParams.tab.get()
val tab = tabs.find {it.id().equals(tabID)} ?: tabs.first()
spitUsualPage {RenderTheFuckingPage(this@EntityPageTemplate, tab, false).ignite()}
}
}
override fun isPrivate() = pedro.isPagePrivate()
}
return product
}
inner class ParamsTab : Tab {
override fun id() = paramsTabID
override fun title() = t("Params", "Параметры")
override fun addTopRightControls(trc: TopRightControls) {
// if (pedro.canEditParams()) {
// pencilButton.addControl(trc, pedro.juan.order)
// }
}
override fun render(): Renderable {
val order = juan.order
// debug_showModel(title = "Model") {
// it.fart("entity", order)
// }
if (alConfig.debug.genericDebugFlag) {
!BoFrontFuns.AddJSONMonacoBelowFooter(
title = "Order model",
json = jsonize(order))
}
return pedro.renderParamsTab()
}
}
class RenderTheFuckingPage(
val ept: EntityPageTemplate,
activeTab: Tab,
val fuckIn: Boolean) {
val order get() = ept.juan.order as Order
init {
ept.juan.activeTab = activeTab
}
fun ignite(): Renderable {
return ept.maybeEntity.`when`(object : AlMaybe.Cases<Renderable, Order> {
override fun None(shit: AlMaybe.None<Order>): Renderable {
return Al.littleErrorPage(shit.message)
}
override fun Some(shit: AlMaybe.Some<Order>): Renderable {
return composePage(shit)
}
})
}
fun composePage(shit: AlMaybe.Some<Order>): Renderable {
ept.juan.order = shit.meat
ept.juan.activeTab.willRender()
ept.juan.afterEntityKnownActions.forEach {it()}
rctx0.htmlHeadTitle = ept.pedro.htmlHeadTitle()
// btfStartStalenessWatcher()
return div()
.className(fuckIn.thenElseEmpty {"fuckIn"})
.with {
oo(rctx0.shitToPlaceAtTheVeryTopOfThePage)
oo(div().className("container").with o@{
!OoEntityTitleShit(
pagePath = ept.pedro.pagePath(),
title = ept.pedro.pageTitle(),
shitIntoHamburger = ept.pedro::shitIntoTopRightHamburgerDropdown,
impersonationPillsUsage = ept.impersonationPillsUsage(),
shitIntoTopRight = {
if (isAdmin()) {
oo(composeOrderBucketPills(ept.pedro.pagePath(), ept.impersonationPillsUsage()!!.params()))
}
},
renderingStuff1 = ept.pedro.renderingStuff1())
.subTitle(ept.pedro.pageSubTitle())
val contentToRevealAfterInit = div().style("display: none;")
oo(contentToRevealAfterInit.with {
// oo(ept.pedro.composeActionBannerBelowTitle())
val actionBannerContainer = div()
oo(actionBannerContainer)
val frontFun = BoFrontFuns.InitOrderPageActionBanner(
orderHandle = order.toHandle().toJsonizable(),
reloadURL = ept.reloadUrl(),
actionBannerContainerDomid = actionBannerContainer.attrs.id,
contentToRevealAfterInitDomid = contentToRevealAfterInit.attrs.id,
orderState = order.state,
userKind = rctx0.al.pretending)
if (isAdmin() && order.state == Order.State.WaitingAdminApproval) {
val taskID = order.data.approvalTaskID!!
frontFun.adminTaskID = taskID.toString()
frontFun.adminTaskHref = OoAdminOneTaskPage.href(taskID)
val wasRejectionReason = order.data.wasRejectionReason
frontFun.wasRejectionReason = wasRejectionReason
if (wasRejectionReason != null) {
frontFun.whatChangedHref = OoCompareOperationsPage.href(
id1 = order.data.lastRejectedByOperationID!!,
id2 = order.data.lastSentForApprovalByOperationID!!)
}
val ranges = BiddingParamsDateValidationRanges()
val workDeadlineShownToWritersDuringBidding = order.deadline
val reminder = run {
val minHoursToReminder = 1
for (h in listOf(3 * 24, 2 * 24, 24, 12)) {
val reminder = workDeadlineShownToWritersDuringBidding.minusHours(h)
if (TimePile.diffHours_double(reminder, now()) >= minHoursToReminder) return@run reminder
}
null
}
frontFun.biddingParamsShit = BoFrontFuns.BiddingParamsShit(
workDeadlineShownToWritersDuringBiddingRange = ranges.workDeadlineShownToWritersDuringBidding.toFrontCalendarRange(),
closeBiddingReminderTimeRange = ranges.closeBiddingReminderTime.toFrontCalendarRange(),
fields = new_BiddingParamsFields(
minWriterMoney = TextField.noError(""),
maxWriterMoney = TextField.noError(""),
workDeadlineShownToWritersDuringBidding = DateTimeField.noError_backToFront(workDeadlineShownToWritersDuringBidding),
closeBiddingReminderTime = reminder?.let {DateTimeField.noError_backToFront(it)} ?: DateTimeField.blank_backToFront()))
}
if (order.state == Order.State.ReturnedToCustomerForFixing) {
frontFun.rejectionReason = order.data.rejectionReason
}
if (isAdmin() && order.state == Order.State.LookingForWriters) {
val bidding = order.data.bidding!!
frontFun.bidding = bidding
val ranges = BiddingParamsDateValidationRanges()
frontFun.biddingParamsShit = BoFrontFuns.BiddingParamsShit(
workDeadlineShownToWritersDuringBiddingRange = ranges.workDeadlineShownToWritersDuringBidding.toFrontCalendarRange(),
closeBiddingReminderTimeRange = ranges.closeBiddingReminderTime.toFrontCalendarRange(),
fields = new_BiddingParamsFields(
minWriterMoney = TextField.noError(bidding.minWriterMoney.toString()),
maxWriterMoney = TextField.noError(bidding.maxWriterMoney.toString()),
workDeadlineShownToWritersDuringBidding = DateTimeField.noError_backToFront(bidding.workDeadlineShownToWritersDuringBidding),
closeBiddingReminderTime = DateTimeField.noError_backToFront(bidding.closeBiddingReminder.time)))
frontFun.writerAssignmentShit = BoFrontFuns.WriterAssignmentShit(
nudgePaymentReminderTimeRange = nudgePaymentReminderTimeValidationRange().toFrontCalendarRange(),
fields = new_BoloneRP_AssignWriter_Fields(
customerPaysMoney = TextField.noError(""),
writerReceivesMoney = TextField.noError(""),
writerPledgeHours = TextField.noError(""),
customerFacingPledgeHours = TextField.noError(""),
writerID = TextField.noError(""),
nudgePaymentReminderTime = DateTimeField.noError_backToFront(now().plusHours(24))))
}
if (isAdmin() && order.state == Order.State.WaitingPayment) {
val asn = order.data.assignment!!
frontFun.writerAssignmentShit = BoFrontFuns.WriterAssignmentShit(
nudgePaymentReminderTimeRange = nudgePaymentReminderTimeValidationRange().toFrontCalendarRange(),
fields = new_BoloneRP_AssignWriter_Fields(
customerPaysMoney = TextField.noError(asn.customerPaysMoney.toString()),
writerReceivesMoney = TextField.noError(asn.writerReceivesMoney.toString()),
writerPledgeHours = TextField.noError(asn.writerPledgeHours.toString()),
customerFacingPledgeHours = TextField.noError(asn.customerFacingPledgeHours.toString()),
writerID = TextField.noError(asn.writer.id.toString()),
nudgePaymentReminderTime = DateTimeField.noError_backToFront(asn.nudgePaymentReminder.time)))
}
!frontFun
oo(ept.pedro.renderBelowActionBanner())
!OoTabs(activeTabId = ept.juan.activeTab.id(), ooNearTabs = {addTabStripControls()}) {
for (tab in ept.tabs) {
it.tab(id = tab.id(), title = tab.title(), href = ept.tabHref(tab.id()))
}
}
oo(ept.juan.activeTab.render())
})
ooDebugCorrespondingPages()
})
}
}
fun ooDebugCorrespondingPages() {
if (!alConfig.debug.genericLocalDebugFlag) return
fun fart() {
oo(span("Corresponding page for"))
val odl = OrderDebugLinks(order)
if (rctx0.al.site() != AlSite.BoloneCustomer)
odl.ooCustomer()
if (rctx0.al.site() != AlSite.BoloneAdmin)
odl.ooAdmin_order()
if (order.state == Order.State.LookingForWriters) {
for (tu in listOf(TestUsers.pushkin, TestUsers.shelley, TestUsers.tolst, TestUsers.flaubert)) {
if (rctx0.al.maybeUser()?.email != tu.email)
odl.ooWriter_biddingDetails(tu)
}
} else {
if (rctx0.al.site() != AlSite.BoloneWriter) {
order.data.assignment?.writer?.data?.testUser?.let {
odl.ooWriter_order(it)
}
}
}
}
btfDebugExpanderBelowFooter(initiallyOpen = true, title = "Links", shit = div().marginLeft1Em().with {
fart()
})
rctx0.compositionPlace.insideTimelineTitle?.let {it.with {
val cls = "x6d45ef19-644f-4ee2-9000-ceba1ae7b1a3"
oo(div().classes(cls).with {
oo(rawHtml("""<style>
.$cls {margin-left: 1.5em; border-left: 1px solid white; padding-left: 0.5em;}
.$cls a {color: white; text-decoration: underline;}
</style>"""))
fart()
})
}}
}
private fun addTabStripControls() {
val trc = TopRightControls()
ept.juan.activeTab.addTopRightControls(trc)
trc.controls += ept.juan.tabsTopRightContainer
val order = ept.juan.order
if (ept.juan.activeTab.id() == paramsTabID) {
!BoFrontFuns.InitOrderParamsPage(
editable = ept.pedro.canEditParams(),
orderHandle = order.toHandle().toJsonizable(),
tabsTopRightContainerDomid = ept.juan.tabsTopRightContainer.attrs.id,
reloadURL = ept.reloadUrl(),
orderParamsFields = new_OrderFields(
contactName = TextField.noError(order.data.contactName),
email = TextField.noError(order.data.email),
phone = TextField.noError(order.data.phone),
documentType = TextField.noError(order.data.documentType.name),
documentCategory = TextField.noError(order.data.documentCategory),
documentTitle = TextField.noError(order.data.documentTitle),
numPages = TextField.noError(order.data.numPages.toString()),
numSources = TextField.noError(order.data.numSources.toString()),
deadline = DateTimeField.noError_backToFront(order.deadline),
documentDetails = TextField.noError(order.data.documentDetails)),
piece1 = BoFrontFuns.Piece1.make())
}
oo(trc.compose())
}
}
fun tabHref(tabId: String): String {
val paramsToKeepAcrossTabs = replaceOrReloadParams
return makeUrlPart(pedro.pagePath(), paramsToKeepAcrossTabs.copy {p ->
pedro.shitIntoGetParams(p)
p.tab.set(tabId)
})
}
interface ImpersonationPillsUsage {
fun params(): GetParams
fun addTo(sink: ImpersonationPillsSink)
}
fun impersonationPillsUsage(): ImpersonationPillsUsage? {
if (!isAdmin()) return null
return object : ImpersonationPillsUsage {
override fun params() = replaceOrReloadParams
override fun addTo(sink: ImpersonationPillsSink) {
sink.add(AlUserKind.Admin)
if (pedro.impersonationMakesSense(AlUserKind.Customer))
sink.add(AlUserKind.Customer)
if (pedro.impersonationMakesSense(AlUserKind.Writer))
sink.add(AlUserKind.Writer)
}
}
}
val replaceOrReloadParams: GetParams
get() {
val params = outParamsBase().copy {p->
p.longId.set(juan.initialParams.longId.get())
p.uuid.set(juan.initialParams.uuid.get())
}
params.tab.set(juan.initialParams.tab.get())
params.page.set(juan.initialParams.page.get())
return params
}
fun outParamsBase(): GetParams {
return alGetParams.also {p->
if (isAdmin()) {
p.impersonate.set(juan.initialParams.impersonate.get())
p.bucket.set(juan.initialParams.bucket.get())
}
}
}
fun nextParams(): GetParams {
return outParamsBase().copy {p->
p.skipIDs.set(VList.ofBacking(juan.skipIDs + entityId(juan.order)))
p.longId.set(null)
}
}
fun reloadUrl(amend: (GetParams) -> Unit = {}) =
makeUrlPart(pedro.pagePath(), replaceOrReloadParams.copy(amend))
fun reloadToFirstPageUrl() = reloadUrl {it.page.set(1)}
}
interface ImpersonationPillsSink {
fun add(who: AlUserKind)
}
fun doUpdateOrderParams__killme(handle: OrderHandle, expectedOptimisticVersion: String?, fs: OrderFields3__killme) {
!object : UpdateOrder(handle, shortDescription = "Update order params") {
override fun specificUpdates() {
expectedOptimisticVersion?.let {
if (order.optimisticVersion != it)
throw MidAirCollision("Order params update clash")
}
populateEntityFromFields(order, fs)
order.optimisticVersion = uuid()
}
override fun makeOperationData(template: Order.Operation) =
new_Order_Operation_UpdateParams(template)
}
}
| apache-2.0 | bc751fee7fbe2d1c0ebd9d205d04a9b8 | 41.283276 | 161 | 0.557834 | 4.909451 | false | false | false | false |
chemickypes/Glitchy | app/src/main/java/me/bemind/glitchlibrary/Dialogs.kt | 1 | 3981 | package me.bemind.glitchlibrary
import android.content.Context
import android.support.design.widget.BottomSheetDialog
import android.view.LayoutInflater
import android.view.View
/**
* Created by angelomoroni on 09/04/17.
*/
abstract class GenericBottomSheet {
protected var mBottomSheet :BottomSheetDialog? = null
protected var context: Context? = null
fun dismiss() {
mBottomSheet?.dismiss()
}
abstract fun inflateView(view:View)
abstract fun getLayoutResource():Int
fun show(){
mBottomSheet = BottomSheetDialog(context!!)
val view = LayoutInflater.from(context)
.inflate(getLayoutResource(),null, false)
mBottomSheet?.setContentView(view)
mBottomSheet?.setOnDismissListener { mBottomSheet = null }
mBottomSheet?.show()
inflateView(view)
}
}
class PickPhotoBottomSheet private constructor() : GenericBottomSheet(){
private var listener: OnPickPhotoListener? = null
companion object Creator {
fun getPickPhotoBottomSheet(context:Context,listener: OnPickPhotoListener) : PickPhotoBottomSheet{
val pickPhotoBottmSheet = PickPhotoBottomSheet()
pickPhotoBottmSheet.context = context
pickPhotoBottmSheet.listener = listener
return pickPhotoBottmSheet
}
}
override fun getLayoutResource(): Int {
return R.layout.pick_photo_bottom_sheet
}
override fun inflateView(view: View) {
view.findViewById(R.id.camera_text_view).setOnClickListener { listener?.openCamera() }
view.findViewById(R.id.gallery_text_view).setOnClickListener { listener?.openGallery() }
}
interface OnPickPhotoListener{
fun openCamera()
fun openGallery()
}
}
class SaveImageBottomSheet private constructor() : GenericBottomSheet(){
private var listener : OnSaveImageListener? = null
companion object Creator {
fun getSaveImageBottomSheet(context:Context,listener: SaveImageBottomSheet.OnSaveImageListener) : SaveImageBottomSheet{
val saveImagebottomSheet = SaveImageBottomSheet()
saveImagebottomSheet.context = context
saveImagebottomSheet.listener = listener
return saveImagebottomSheet
}
}
override fun getLayoutResource() = R.layout.save_image_bottom_sheet
override fun inflateView(view: View) {
view.findViewById(R.id.share_text_view).setOnClickListener { listener?.shareImage() }
view.findViewById(R.id.save_text_view).setOnClickListener { listener?.saveImage() }
}
interface OnSaveImageListener{
fun saveImage()
fun shareImage()
}
}
class ShareAppBottomSheet private constructor() : GenericBottomSheet(){
private var listener: OnShareDialogClick? = null
companion object Creator {
fun getShareAppDialogFragment(context: Context,onShareDialogClick: OnShareDialogClick) : ShareAppBottomSheet{
val shareAppBS = ShareAppBottomSheet()
shareAppBS.listener = onShareDialogClick
shareAppBS.context = context
return shareAppBS
}
}
override fun inflateView(view: View) {
view.findViewById(R.id.share_text_view).setOnClickListener {
dismiss()
listener?.shareAppLink()
}
view.findViewById(R.id.instagram_text_view).setOnClickListener {
dismiss()
listener?.instagram()
}
view.findViewById(R.id.facebook_text_view).setOnClickListener {
dismiss()
listener?.facebook()
}
view.findViewById(R.id.rate_text_view).setOnClickListener {
dismiss()
listener?.rateApp()
}
}
override fun getLayoutResource() = R.layout.share_app_bottom_sheet
interface OnShareDialogClick{
fun rateApp()
fun instagram()
fun facebook()
fun shareAppLink()
}
}
| apache-2.0 | c69be806d433355e980fb21be5beeffc | 26.839161 | 127 | 0.668927 | 4.848965 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/old/tests/testData/fileOrElement/nullability/nullableField.kt | 13 | 790 | package test
import java.util.ArrayList
class Test {
private var myProp: String? = null
private var myIntProp: Int? = null
fun onCreate() {
myProp = ""
myIntProp = 1
}
fun test1() {
foo1(myProp!!)
}
fun test2() {
foo2(myProp)
}
fun test3() {
foo3(myProp)
}
fun test4() {
myProp!![myIntProp!!]
println(myProp)
}
fun test5() {
val b = "aaa" == myProp
val s = "aaa" + myProp!!
}
fun test6() {
myProp!!.compareTo(myProp!!, ignoreCase = true)
}
fun test7() {
val list = ArrayList<Int>()
list.remove(myIntProp)
}
fun foo1(s: String) {
}
fun foo2(s: String?) {
}
fun foo3(s: String?) {
}
} | apache-2.0 | 4bec80d3581c655f7ffe6d763db72930 | 13.125 | 55 | 0.477215 | 3.376068 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RemoveEmptyParenthesesFromAnnotationEntryInspection.kt | 5 | 2825 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtValueArgumentList
import org.jetbrains.kotlin.psi.valueArgumentListVisitor
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.annotationClass
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class RemoveEmptyParenthesesFromAnnotationEntryInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor =
valueArgumentListVisitor(fun(list) {
if (list.arguments.isNotEmpty()) return
val annotationEntry = list.parent as? KtAnnotationEntry ?: return
if (annotationEntry.typeArguments.isNotEmpty()) return
val annotationClassDescriptor = annotationEntry.getAnnotationClassDescriptor() ?: return
// if all annotation constructors must receive at least one argument
// then parentheses *are* necessary and inspection should not trigger
if (annotationClassDescriptor.constructors.all { it.hasParametersWithoutDefault() }) return
holder.registerProblem(
list,
KotlinBundle.message("parentheses.should.be.removed"),
RemoveEmptyParenthesesFromAnnotationEntryFix()
)
})
private fun KtAnnotationEntry.getAnnotationClassDescriptor(): ClassDescriptor? {
val context = analyze(BodyResolveMode.PARTIAL)
return context[BindingContext.ANNOTATION, this]?.annotationClass
}
private fun ClassConstructorDescriptor.hasParametersWithoutDefault() = valueParameters.any { !it.declaresDefaultValue() }
}
private class RemoveEmptyParenthesesFromAnnotationEntryFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.empty.parentheses.from.annotation.entry.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
(descriptor.psiElement as? KtValueArgumentList)?.delete()
}
}
| apache-2.0 | 4b7f564395b82d6da7cf61951a063735 | 43.84127 | 125 | 0.775929 | 5.411877 | false | false | false | false |
smmribeiro/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/PluginXmlPathResolver.kt | 2 | 8341 | // 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.ide.plugins
import com.intellij.openapi.diagnostic.Logger
import java.io.IOException
import java.nio.file.Path
import java.util.*
import java.util.zip.ZipFile
@Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty")
class PluginXmlPathResolver(private val pluginJarFiles: List<Path>) : PathResolver {
companion object {
// don't use Kotlin emptyList here
@JvmField val DEFAULT_PATH_RESOLVER: PathResolver = PluginXmlPathResolver(Collections.emptyList())
private fun loadUsingZipFile(readInto: RawPluginDescriptor,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
jarFile: Path,
relativePath: String,
includeBase: String?): Boolean {
val zipFile = ZipFile(jarFile.toFile())
try {
// do not use kotlin stdlib here
val entry = zipFile.getEntry(if (relativePath.startsWith("/")) relativePath.substring(1) else relativePath) ?: return false
readModuleDescriptor(input = zipFile.getInputStream(entry),
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase,
readInto = readInto,
locationSource = jarFile.toString())
return true
}
catch (e: IOException) {
Logger.getInstance(PluginXmlPathResolver::class.java).error("Corrupted jar file: $jarFile", e)
return false
}
finally {
zipFile.close()
}
}
internal fun getParentPath(path: String): String {
val end = path.lastIndexOf('/')
return if (end == -1) "" else path.substring(0, end)
}
internal fun toLoadPath(relativePath: String, base: String?): String {
return when {
relativePath[0] == '/' -> relativePath.substring(1)
relativePath.startsWith("intellij.") -> relativePath
base == null -> "META-INF/$relativePath"
else -> "$base/$relativePath"
}
}
internal fun getChildBase(base: String?, relativePath: String): String? {
val end = relativePath.lastIndexOf('/')
if (end <= 0 || relativePath.startsWith("/META-INF/")) {
return base
}
val childBase = relativePath.substring(0, end)
return if (base == null) childBase else "$base/$childBase"
}
}
override fun loadXIncludeReference(readInto: RawPluginDescriptor,
readContext: ReadModuleContext,
dataLoader: DataLoader,
base: String?,
relativePath: String): Boolean {
val path = toLoadPath(relativePath, base)
dataLoader.load(path)?.let {
readModuleDescriptor(input = it,
readContext = readContext,
pathResolver = this,
dataLoader = dataLoader,
includeBase = getChildBase(base = base, relativePath = relativePath),
readInto = readInto,
locationSource = null)
return true
}
if (findInJarFiles(readInto = readInto,
dataLoader = dataLoader,
readContext = readContext,
relativePath = path,
includeBase = getChildBase(base = base, relativePath = relativePath))) {
return true
}
// it is allowed to reference any platform XML file using href="/META-INF/EnforcedPlainText.xml"
if (path.startsWith("META-INF/")) {
PluginXmlPathResolver::class.java.classLoader.getResourceAsStream(path)?.let {
readModuleDescriptor(input = it,
readContext = readContext,
pathResolver = this,
dataLoader = dataLoader,
includeBase = null,
readInto = readInto,
locationSource = null)
return true
}
}
return false
}
override fun resolvePath(readContext: ReadModuleContext,
dataLoader: DataLoader,
relativePath: String,
readInto: RawPluginDescriptor?): RawPluginDescriptor? {
val path = toLoadPath(relativePath, null)
dataLoader.load(path)?.let {
return readModuleDescriptor(input = it,
readContext = readContext,
pathResolver = this,
dataLoader = dataLoader,
includeBase = null,
readInto = readInto,
locationSource = null)
}
val result = readInto ?: RawPluginDescriptor()
if (findInJarFiles(readInto = result, dataLoader = dataLoader, readContext = readContext, relativePath = path, includeBase = null)) {
return result
}
if (relativePath.startsWith("intellij.")) {
// module in a new file name format must be always resolved
throw RuntimeException("Cannot resolve $path (dataLoader=$dataLoader)")
}
return null
}
override fun resolveModuleFile(readContext: ReadModuleContext,
dataLoader: DataLoader,
path: String,
readInto: RawPluginDescriptor?): RawPluginDescriptor {
val input = dataLoader.load(path)
if (input == null) {
if (path == "intellij.profiler.clion") {
val descriptor = RawPluginDescriptor()
descriptor.`package` = "com.intellij.profiler.clion"
return descriptor
}
throw RuntimeException("Cannot resolve $path (dataLoader=$dataLoader, pluginJarFiles=${pluginJarFiles.joinToString(separator = "\n ")})")
}
return readModuleDescriptor(input = input,
readContext = readContext,
pathResolver = this,
dataLoader = dataLoader,
includeBase = null,
readInto = readInto,
locationSource = null)
}
private fun findInJarFiles(readInto: RawPluginDescriptor,
readContext: ReadModuleContext,
dataLoader: DataLoader,
relativePath: String,
includeBase: String?): Boolean {
val pool = dataLoader.pool
for (jarFile in pluginJarFiles) {
if (dataLoader.isExcludedFromSubSearch(jarFile)) {
continue
}
if (pool == null) {
if (loadUsingZipFile(readInto = readInto,
readContext = readContext,
pathResolver = this,
dataLoader = dataLoader,
jarFile = jarFile,
relativePath = relativePath,
includeBase = includeBase)) {
return true
}
}
else {
val resolver = try {
pool.load(jarFile)
}
catch (e: IOException) {
Logger.getInstance(PluginXmlPathResolver::class.java).error("Corrupted jar file: $jarFile", e)
continue
}
resolver.loadZipEntry(relativePath)?.let {
readModuleDescriptor(input = it,
readContext = readContext,
pathResolver = this,
dataLoader = dataLoader,
includeBase = includeBase,
readInto = readInto,
locationSource = jarFile.toString())
return true
}
}
}
return false
}
} | apache-2.0 | dcf05b0c49c8508dc96a8a3b59301921 | 39.692683 | 158 | 0.529912 | 6.173945 | false | false | false | false |
smmribeiro/intellij-community | platform/statistics/uploader/src/com/intellij/internal/statistic/eventLog/LogEventRecordRequest.kt | 9 | 5256 | // 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.internal.statistic.eventLog
import com.google.gson.JsonSyntaxException
import com.intellij.internal.statistic.config.EventLogOptions.DEFAULT_ID_REVISION
import com.intellij.internal.statistic.eventLog.filters.LogEventFilter
import com.jetbrains.fus.reporting.model.lion3.LogEvent
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.io.IOException
class LogEventRecordRequest(val recorder: String, val product : String, val device: String, val records: List<LogEventRecord>, val internal: Boolean) {
companion object {
private const val RECORD_SIZE = 1000 * 1000 // 1000KB
fun create(file: File, recorder: String, product: String, deviceId: String, filter: LogEventFilter,
internal: Boolean, logger: DataCollectorDebugLogger, machineId: MachineId): LogEventRecordRequest? {
try {
return create(file, recorder, product, deviceId, RECORD_SIZE, filter, internal, logger, machineId)
}
catch (e: Exception) {
logger.warn("Failed reading event log file", e)
return null
}
}
fun create(file: File,
recorder: String,
product: String,
user: String,
maxRecordSize: Int,
filter: LogEventFilter,
internal: Boolean,
logger: DataCollectorDebugLogger,
machineId: MachineId): LogEventRecordRequest? {
try {
val deserializer = LogEventDeserializer(logger)
val records = ArrayList<LogEventRecord>()
BufferedReader(FileReader(file.path)).use { reader ->
val sizeEstimator = LogEventRecordSizeEstimator(product, user)
var events = ArrayList<LogEvent>()
var line = fillNextBatch(reader, reader.readLine(), events, deserializer, sizeEstimator, maxRecordSize, filter, machineId)
while (!events.isEmpty()) {
records.add(LogEventRecord(events))
events = ArrayList()
line = fillNextBatch(reader, line, events, deserializer, sizeEstimator, maxRecordSize, filter, machineId)
}
}
return LogEventRecordRequest(recorder, product, user, records, internal)
}
catch (e: JsonSyntaxException) {
logger.warn(e.message ?: "", e)
}
catch (e: IOException) {
logger.warn(e.message ?: "", e)
}
return null
}
private fun fillNextBatch(reader: BufferedReader,
firstLine: String?,
events: MutableList<LogEvent>,
deserializer: LogEventDeserializer,
estimator: LogEventRecordSizeEstimator,
maxRecordSize: Int,
filter: LogEventFilter,
machineId: MachineId): String? {
var recordSize = 0
var line = firstLine
while (line != null && recordSize + estimator.estimate(line) < maxRecordSize) {
val event = deserializer.fromString(line)
if (event != null && filter.accepts(event)) {
recordSize += estimator.estimate(line)
fillMachineId(event, machineId)
events.add(event.escape())
}
line = reader.readLine()
}
return line
}
fun fillMachineId(event: LogEvent,
machineId: MachineId) {
val eventAction = event.event
val machineIdValue = machineId.id
val idRevision = machineId.revision
eventAction.data["system_machine_id"] = machineIdValue
if (idRevision != DEFAULT_ID_REVISION &&
machineId != MachineId.UNKNOWN &&
machineId != MachineId.DISABLED) {
eventAction.data["system_id_revision"] = idRevision
}
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEventRecordRequest
if (recorder != other.recorder) return false
if (product != other.product) return false
if (device != other.device) return false
if (internal != other.internal) return false
if (records != other.records) return false
return true
}
override fun hashCode(): Int {
var result = recorder.hashCode()
result = 31 * result + product.hashCode()
result = 31 * result + device.hashCode()
result = 31 * result + internal.hashCode()
result = 31 * result + records.hashCode()
return result
}
}
class LogEventRecord(val events: List<LogEvent>) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEventRecord
if (events != other.events) return false
return true
}
override fun hashCode(): Int {
return events.hashCode()
}
}
class LogEventRecordSizeEstimator(product : String, user: String) {
private val formatAdditionalSize = product.length + user.length + 2
fun estimate(line: String) : Int {
return line.length + formatAdditionalSize
}
} | apache-2.0 | dcfdb51a817a8d72b19a15d2840ee8b8 | 35.006849 | 158 | 0.637177 | 4.804388 | false | false | false | false |
shalupov/idea-cloudformation | src/main/kotlin/com/intellij/aws/cloudformation/CloudFormationReportSubmitter.kt | 1 | 5924 | package com.intellij.aws.cloudformation
import com.intellij.ide.DataManager
import com.intellij.ide.plugins.PluginManager
import com.intellij.idea.IdeaLogger
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.diagnostic.ErrorReportSubmitter
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.SubmittedReportInfo
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.Consumer
import com.intellij.util.io.HttpRequests
import com.intellij.util.text.DateFormatUtil
import java.awt.Component
import java.net.HttpURLConnection
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.UUID
class CloudFormationReportSubmitter : ErrorReportSubmitter() {
val LOG = Logger.getInstance(CloudFormationReportSubmitter::class.java)
val ENDPOINT = "https://classiq.diverse.org.ru/dav_feedback"
override fun getReportActionText(): String = "Report to plugin developers"
fun getExceptionText(event: IdeaLoggingEvent): String {
val throwable = event.throwable
return (if (throwable.javaClass != Throwable::class.java) (throwable.javaClass.simpleName + ": ") else "") +
event.message +
(if (throwable.message != event.message && throwable.message != null) (" (${throwable.message})") else "") + "\n" + StringUtil.getThrowableText(throwable)
}
private fun buildReportText(events: List<IdeaLoggingEvent>): String {
val builder = StringBuilder()
val appInfo = ApplicationInfoEx.getInstanceEx()
val appNamesInfo = ApplicationNamesInfo.getInstance()
val application = ApplicationManager.getApplication()
// Product coordinates
builder.appendln("JetBrains ${appNamesInfo.fullProductName} ${appInfo.majorVersion}.${appInfo.minorVersion} Build ${appInfo.apiVersion}")
// Plugin coordinates
val pluginId = PluginManager.getPluginByClassName(CloudFormationReportSubmitter::class.java.name)
val plugin = PluginManager.getPlugin(pluginId)
if (plugin != null) {
builder.appendln("Plugin Name: ${plugin.name}")
builder.appendln("Plugin Version: ${plugin.version}")
}
// Stacktrace
events.forEach {
builder.appendln("----------------------")
builder.appendln(getExceptionText(it))
}
builder.appendln("----------------------")
// Additional info
builder.appendln()
builder.appendln("last.action = ${IdeaLogger.ourLastActionId}")
builder.appendln()
builder.appendln("app.eap = ${appInfo.isEAP}")
builder.appendln("app.internal = ${application.isInternal}")
builder.appendln("app.build = ${appInfo.apiVersion}")
builder.appendln("app.version.major = ${appInfo.majorVersion}")
builder.appendln("app.version.minor = ${appInfo.minorVersion}")
builder.appendln("app.build.date = ${DateFormatUtil.getIso8601Format().format(appInfo.buildDate.time)}")
builder.appendln("app.build.date.release = ${DateFormatUtil.getIso8601Format().format(appInfo.majorReleaseBuildDate.time)}")
builder.appendln("app.build.date.release = ${DateFormatUtil.getIso8601Format().format(appInfo.majorReleaseBuildDate.time)}")
builder.appendln("app.product.code = ${appInfo.build.productCode}")
builder.appendln()
builder.appendln("os.name = ${SystemInfo.getOsNameAndVersion()}")
builder.appendln("java.version = ${SystemInfo.JAVA_VERSION}")
return builder.toString()
}
override fun submit(events: Array<out IdeaLoggingEvent>, additionalInfo: String?, parentComponent: Component, consumer: Consumer<SubmittedReportInfo>): Boolean {
val dataContext = DataManager.getInstance().getDataContext(parentComponent)
val project = CommonDataKeys.PROJECT.getData(dataContext) ?: return false
val now = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HHmm")
val reportId = now.format(formatter) + "-" + UUID.randomUUID().toString()
val reportedText = buildReportText(events.toList())
val reportBytes = reportedText.toByteArray()
val task = object : Task.Backgroundable(project, "Submitting exceptions", true, ALWAYS_BACKGROUND) {
override fun run(indicator: ProgressIndicator) {
try {
HttpRequests.request("$ENDPOINT/$reportId")
.tuner {
val con = it as HttpURLConnection
con.requestMethod = "PUT"
con.doOutput = true
con.useCaches = false
con.allowUserInteraction = false
con.setRequestProperty("Content-Type", "text/xml")
con.setFixedLengthStreamingMode(reportBytes.size)
val os = con.outputStream
os.write(reportBytes)
os.close()
}.connect {
val response = it.connection.inputStream.readBytes()
try {
LOG.info("Reporting endpoint answered: ${response.toString(Charsets.UTF_8)}")
} catch(t: Throwable) {
LOG.error(t)
}
}
val reportInfo = SubmittedReportInfo(null, "Submitted an Issue", SubmittedReportInfo.SubmissionStatus.NEW_ISSUE)
consumer.consume(reportInfo)
} catch (t: Throwable) {
try {
LOG.error("Submitting feedback error", t)
} catch (t: Throwable) {
LOG.error(t)
}
}
}
}
ProgressManager.getInstance().run(task)
return true
}
} | apache-2.0 | 11d59c1a77a62fd5efa741f3cc20fd73 | 39.862069 | 163 | 0.701047 | 4.735412 | false | false | false | false |
kunonx/ProspaceCore-Command | src/main/kotlin/net/prospacecraft/command/misc/CommandMessage.kt | 1 | 906 | package net.prospacecraft.command.misc
import net.prospacecraft.ProspaceCore.message.FancyMessage
import org.bukkit.ChatColor
import org.bukkit.command.CommandSender
internal class CommandMessage(var message : String, var desc : MutableList<String> = ArrayList())
{
private val messageBuilder : FancyMessage = FancyMessage(message)
fun getMessageBuilder() : FancyMessage = messageBuilder
fun getDescription() : MutableList<String> = desc
@Suppress("IMPLICIT_CAST_TO_ANY")
fun addMessage(message : String, index : Int = -1) : MutableList<String>
{
when (index)
{
-1 -> desc.add(ChatColor.translateAlternateColorCodes('&', message))
else -> desc.add(index, message)
}
return desc
}
fun send(sender : CommandSender)
{
messageBuilder.tooltip(desc.asIterable())
messageBuilder.send(sender)
}
} | mit | 11988b3150d12852e3ba3e6b8e473283 | 28.258065 | 97 | 0.681015 | 4.334928 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/ui/presenter/LoginPresenter.kt | 1 | 1714 | /*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* 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.zwq65.unity.ui.presenter
import com.zwq65.unity.data.DataManager
import com.zwq65.unity.ui._base.BasePresenter
import com.zwq65.unity.ui.contract.LoginContract
import javax.inject.Inject
/**
* ================================================
*
* Created by NIRVANA on 2017/06/29.
* Contact with <[email protected]>
* ================================================
*/
class LoginPresenter<V : LoginContract.View> @Inject
internal constructor(dataManager: DataManager) : BasePresenter<V>(dataManager), LoginContract.Presenter<V> {
override fun login(account: String, password: String) {
// if (TextUtils.isEmpty(account)) {
// getMvpView().onError("请输入账号");
// return;
// }
// if (TextUtils.isEmpty(password)) {
// getMvpView().onError("请输入密码");
// return;
// }
mvpView!!.openMainActivity()
}
override fun register() {
}
override fun forgotPsd() {
}
}
| apache-2.0 | 967033481c242327a2d64bca010bcb21 | 29.8 | 108 | 0.601535 | 4.235 | false | false | false | false |
hsz/idea-gitignore | src/main/kotlin/mobi/hsz/idea/gitignore/actions/AddTemplateAction.kt | 1 | 1229 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package mobi.hsz.idea.gitignore.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import mobi.hsz.idea.gitignore.IgnoreBundle
import mobi.hsz.idea.gitignore.psi.IgnoreFile
import mobi.hsz.idea.gitignore.ui.GeneratorDialog
/**
* Action that initiates adding new template to the selected .gitignore file.
*/
class AddTemplateAction :
AnAction(IgnoreBundle.message("action.addTemplate"), IgnoreBundle.message("action.addTemplate.description"), null) {
override fun actionPerformed(e: AnActionEvent) {
val project = e.getData(CommonDataKeys.PROJECT) ?: return
val file = e.getData(CommonDataKeys.PSI_FILE) as IgnoreFile
GeneratorDialog(project, file).show()
}
override fun update(e: AnActionEvent) {
val file = e.getData(CommonDataKeys.PSI_FILE)
if (file !is IgnoreFile) {
e.presentation.isVisible = false
return
}
templatePresentation.icon = file.fileType.icon
}
}
| mit | 86bab684730a583ece229d250c3adb30 | 37.40625 | 140 | 0.736371 | 4.342756 | false | false | false | false |
aosp-mirror/platform_frameworks_support | room/compiler/src/main/kotlin/androidx/room/solver/binderprovider/CursorQueryResultBinderProvider.kt | 1 | 1429 | /*
* Copyright (C) 2017 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.room.solver.binderprovider
import androidx.room.ext.AndroidTypeNames
import androidx.room.parser.ParsedQuery
import androidx.room.processor.Context
import androidx.room.solver.QueryResultBinderProvider
import androidx.room.solver.query.result.CursorQueryResultBinder
import androidx.room.solver.query.result.QueryResultBinder
import com.squareup.javapoet.TypeName
import javax.lang.model.type.DeclaredType
class CursorQueryResultBinderProvider(val context: Context) : QueryResultBinderProvider {
override fun provide(declared: DeclaredType, query: ParsedQuery): QueryResultBinder {
return CursorQueryResultBinder()
}
override fun matches(declared: DeclaredType): Boolean =
declared.typeArguments.size == 0 && TypeName.get(declared) == AndroidTypeNames.CURSOR
} | apache-2.0 | 77b559a128945980bd2cb3b77763e5d2 | 39.857143 | 93 | 0.783765 | 4.507886 | false | false | false | false |
chiken88/passnotes | app/src/main/java/com/ivanovsky/passnotes/data/repository/file/saf/SAFFileSystemProvider.kt | 1 | 8387 | package com.ivanovsky.passnotes.data.repository.file.saf
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.OpenableColumns
import com.ivanovsky.passnotes.data.entity.FSAuthority
import com.ivanovsky.passnotes.data.entity.FileDescriptor
import com.ivanovsky.passnotes.data.entity.OperationError
import com.ivanovsky.passnotes.data.entity.OperationError.MESSAGE_INCORRECT_USE_CASE
import com.ivanovsky.passnotes.data.entity.OperationError.newFileAccessError
import com.ivanovsky.passnotes.data.entity.OperationError.newFileNotFoundError
import com.ivanovsky.passnotes.data.entity.OperationError.newGenericIOError
import com.ivanovsky.passnotes.data.entity.OperationResult
import com.ivanovsky.passnotes.data.repository.file.FSOptions
import com.ivanovsky.passnotes.data.repository.file.FileSystemProvider
import com.ivanovsky.passnotes.data.repository.file.OnConflictStrategy
import com.ivanovsky.passnotes.util.FileUtils.ROOT_PATH
import com.ivanovsky.passnotes.util.Logger
import java.io.FileNotFoundException
import java.io.InputStream
import java.io.OutputStream
class SAFFileSystemProvider(
private val context: Context
) : FileSystemProvider {
private val authenticator = SAFFileSystemAuthenticator()
private val syncProcessor = SAFFileSystemSyncProcessor()
override fun getAuthenticator() = authenticator
override fun getSyncProcessor() = syncProcessor
override fun listFiles(dir: FileDescriptor): OperationResult<List<FileDescriptor>> {
return if (dir.isRoot) {
OperationResult.success(emptyList())
} else {
OperationResult.error(newGenericIOError(MESSAGE_INCORRECT_USE_CASE))
}
}
override fun getParent(file: FileDescriptor): OperationResult<FileDescriptor> {
return OperationResult.error(newGenericIOError(MESSAGE_INCORRECT_USE_CASE))
}
override fun getRootFile(): OperationResult<FileDescriptor> {
return OperationResult.success(ROOT_FILE)
}
override fun openFileForRead(
file: FileDescriptor,
onConflictStrategy: OnConflictStrategy,
options: FSOptions
): OperationResult<InputStream> {
val uri = file.getUri()
return try {
val stream = context.contentResolver.openInputStream(uri)
OperationResult.success(stream)
} catch (e: FileNotFoundException) {
Logger.printStackTrace(e)
OperationResult.error(failedToFindFile(uri))
} catch (e: SecurityException) {
Logger.printStackTrace(e)
OperationResult.error(failedToGetAccessTo(uri))
} catch (e: Exception) {
Logger.printStackTrace(e)
OperationResult.error(unknownError(e))
}
}
override fun openFileForWrite(
file: FileDescriptor,
onConflictStrategy: OnConflictStrategy,
options: FSOptions
): OperationResult<OutputStream> {
val uri = file.getUri()
if (Build.VERSION.SDK_INT >= 19) {
try {
context.contentResolver.takePersistableUriPermission(
uri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION
)
} catch (e: SecurityException) {
Logger.printStackTrace(e)
return OperationResult.error(failedToGetAccessTo(uri))
} catch (e: Exception) {
Logger.printStackTrace(e)
return OperationResult.error(unknownError(e))
}
}
val stream = try {
context.contentResolver.openOutputStream(uri)
} catch (e: FileNotFoundException) {
Logger.printStackTrace(e)
return OperationResult.error(failedToFindFile(uri))
} catch (e: SecurityException) {
Logger.printStackTrace(e)
return OperationResult.error(failedToGetAccessTo(uri))
} catch (e: Exception) {
Logger.printStackTrace(e)
return OperationResult.error(unknownError(e))
} ?: return OperationResult.error(failedToGetAccessTo(uri))
return OperationResult.success(SAFOutputStream(stream))
}
override fun exists(file: FileDescriptor): OperationResult<Boolean> {
val uri = file.getUri()
val cursor = try {
context.contentResolver.query(uri, null, null, null, null)
?: return OperationResult.error(failedToRetrieveData(uri))
} catch (e: SecurityException) {
Logger.printStackTrace(e)
return OperationResult.error(failedToGetAccessTo(uri))
} catch (e: Exception) {
Logger.printStackTrace(e)
return OperationResult.error(unknownError(e))
}
val fileSize = cursor.use {
if (it.count == 0) {
return OperationResult.error(failedToRetrieveData(uri))
}
if (!it.columnNames.contains(OpenableColumns.SIZE)) {
return OperationResult.error(failedToFindColumn(OpenableColumns.SIZE))
}
val sizeColumnIdx = it.getColumnIndex(OpenableColumns.SIZE)
it.moveToFirst()
it.getLong(sizeColumnIdx)
}
return OperationResult.success(fileSize > 0)
}
override fun getFile(path: String, options: FSOptions): OperationResult<FileDescriptor> {
val uri = Uri.parse(path)
val cursor = try {
context.contentResolver.query(uri, null, null, null, null)
?: return OperationResult.error(failedToRetrieveData(uri))
} catch (e: SecurityException) {
Logger.printStackTrace(e)
return OperationResult.error(failedToGetAccessTo(uri))
} catch (e: Exception) {
Logger.printStackTrace(e)
return OperationResult.error(unknownError(e))
}
val name = cursor.use {
if (it.count == 0) {
return OperationResult.error(failedToRetrieveData(uri))
}
if (!it.columnNames.contains(OpenableColumns.DISPLAY_NAME)) {
return OperationResult.error(failedToFindColumn(OpenableColumns.DISPLAY_NAME))
}
val displayNameColumnIdx = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
it.moveToFirst()
it.getString(displayNameColumnIdx)
}
return OperationResult.success(
FileDescriptor(
fsAuthority = FSAuthority.SAF_FS_AUTHORITY,
path = path,
uid = path,
name = name,
isDirectory = false,
isRoot = false,
modified = null
)
)
}
private fun failedToFindColumn(columnName: String): OperationError {
return newGenericIOError(
String.format(
OperationError.GENERIC_MESSAGE_FAILED_TO_FIND_COLUMN,
columnName
)
)
}
private fun failedToRetrieveData(uri: Uri): OperationError {
return newGenericIOError(
String.format(
OperationError.GENERIC_MESSAGE_FAILED_TO_RETRIEVE_DATA_BY_URI,
uri.toString()
)
)
}
private fun failedToGetAccessTo(uri: Uri): OperationError {
return newFileAccessError(
String.format(
OperationError.GENERIC_MESSAGE_FAILED_TO_GET_ACCESS_RIGHT_TO_URI,
uri.toString()
)
)
}
private fun failedToFindFile(uri: Uri): OperationError {
return newFileNotFoundError(
String.format(
OperationError.GENERIC_MESSAGE_FAILED_TO_FIND_FILE,
uri.toString()
)
)
}
private fun unknownError(error: Exception): OperationError {
return newGenericIOError(
OperationError.MESSAGE_UNKNOWN_ERROR,
error
)
}
private fun FileDescriptor.getUri(): Uri {
return Uri.parse(path)
}
companion object {
private val ROOT_FILE = FileDescriptor(
fsAuthority = FSAuthority.SAF_FS_AUTHORITY,
path = ROOT_PATH,
uid = ROOT_PATH,
name = ROOT_PATH,
isDirectory = true,
isRoot = true
)
}
} | gpl-2.0 | bb74ce7160861e1b5a70fbf5cede02c4 | 33.804979 | 94 | 0.633719 | 4.893232 | false | false | false | false |
kerubistan/kerub | src/test/kotlin/com/github/kerubistan/kerub/stories/planner/PlannerDefs.kt | 2 | 47347 | package com.github.kerubistan.kerub.stories.planner
import com.github.k0zka.finder4j.backtrack.BacktrackService
import com.github.k0zka.finder4j.backtrack.BacktrackServiceImpl
import com.github.kerubistan.kerub.model.ExpectationLevel
import com.github.kerubistan.kerub.model.FsStorageCapability
import com.github.kerubistan.kerub.model.GvinumStorageCapability
import com.github.kerubistan.kerub.model.GvinumStorageCapabilityDrive
import com.github.kerubistan.kerub.model.Host
import com.github.kerubistan.kerub.model.HostCapabilities
import com.github.kerubistan.kerub.model.LvmStorageCapability
import com.github.kerubistan.kerub.model.OperatingSystem
import com.github.kerubistan.kerub.model.Range
import com.github.kerubistan.kerub.model.SoftwarePackage
import com.github.kerubistan.kerub.model.StorageCapability
import com.github.kerubistan.kerub.model.Version
import com.github.kerubistan.kerub.model.VirtualMachine
import com.github.kerubistan.kerub.model.VirtualMachineStatus
import com.github.kerubistan.kerub.model.VirtualNetwork
import com.github.kerubistan.kerub.model.VirtualStorageDevice
import com.github.kerubistan.kerub.model.VirtualStorageLink
import com.github.kerubistan.kerub.model.config.HostConfiguration
import com.github.kerubistan.kerub.model.controller.config.ControllerConfig
import com.github.kerubistan.kerub.model.devices.NetworkDevice
import com.github.kerubistan.kerub.model.dynamic.CompositeStorageDeviceDynamic
import com.github.kerubistan.kerub.model.dynamic.CompositeStorageDeviceDynamicItem
import com.github.kerubistan.kerub.model.dynamic.HostDynamic
import com.github.kerubistan.kerub.model.dynamic.HostStatus
import com.github.kerubistan.kerub.model.dynamic.VirtualMachineDynamic
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageAllocation
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageDeviceDynamic
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageFsAllocation
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageGvinumAllocation
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageLvmAllocation
import com.github.kerubistan.kerub.model.dynamic.gvinum.ConcatenatedGvinumConfiguration
import com.github.kerubistan.kerub.model.dynamic.gvinum.SimpleGvinumConfiguration
import com.github.kerubistan.kerub.model.expectations.CacheSizeExpectation
import com.github.kerubistan.kerub.model.expectations.ChassisManufacturerExpectation
import com.github.kerubistan.kerub.model.expectations.ClockFrequencyExpectation
import com.github.kerubistan.kerub.model.expectations.CoreDedicationExpectation
import com.github.kerubistan.kerub.model.expectations.CpuArchitectureExpectation
import com.github.kerubistan.kerub.model.expectations.MemoryClockFrequencyExpectation
import com.github.kerubistan.kerub.model.expectations.NoMigrationExpectation
import com.github.kerubistan.kerub.model.expectations.NotSameHostExpectation
import com.github.kerubistan.kerub.model.expectations.NotSameStorageExpectation
import com.github.kerubistan.kerub.model.expectations.StorageAvailabilityExpectation
import com.github.kerubistan.kerub.model.expectations.StorageRedundancyExpectation
import com.github.kerubistan.kerub.model.expectations.VirtualMachineAvailabilityExpectation
import com.github.kerubistan.kerub.model.hardware.BlockDevice
import com.github.kerubistan.kerub.model.hardware.CacheInformation
import com.github.kerubistan.kerub.model.hardware.ChassisInformation
import com.github.kerubistan.kerub.model.hardware.MemoryInformation
import com.github.kerubistan.kerub.model.hardware.ProcessorInformation
import com.github.kerubistan.kerub.model.hypervisor.LibvirtArch
import com.github.kerubistan.kerub.model.hypervisor.LibvirtCapabilities
import com.github.kerubistan.kerub.model.hypervisor.LibvirtGuest
import com.github.kerubistan.kerub.model.io.BusType
import com.github.kerubistan.kerub.model.io.VirtualDiskFormat
import com.github.kerubistan.kerub.model.lom.IpmiInfo
import com.github.kerubistan.kerub.model.lom.WakeOnLanInfo
import com.github.kerubistan.kerub.model.messages.EntityUpdateMessage
import com.github.kerubistan.kerub.model.services.IscsiService
import com.github.kerubistan.kerub.planner.OperationalState
import com.github.kerubistan.kerub.planner.OperationalStateBuilder
import com.github.kerubistan.kerub.planner.Plan
import com.github.kerubistan.kerub.planner.PlanExecutor
import com.github.kerubistan.kerub.planner.PlanViolationDetectorImpl
import com.github.kerubistan.kerub.planner.Planner
import com.github.kerubistan.kerub.planner.PlannerImpl
import com.github.kerubistan.kerub.planner.issues.problems.CompositeProblemDetectorImpl
import com.github.kerubistan.kerub.planner.steps.base.AbstractUnAllocate
import com.github.kerubistan.kerub.planner.steps.host.powerdown.PowerDownHost
import com.github.kerubistan.kerub.planner.steps.host.recycle.RecycleHost
import com.github.kerubistan.kerub.planner.steps.host.security.generate.GenerateSshKey
import com.github.kerubistan.kerub.planner.steps.host.security.install.InstallPublicKey
import com.github.kerubistan.kerub.planner.steps.host.startup.AbstractWakeHost
import com.github.kerubistan.kerub.planner.steps.network.ovs.port.create.CreateOvsPort
import com.github.kerubistan.kerub.planner.steps.network.ovs.sw.create.CreateOvsSwitch
import com.github.kerubistan.kerub.planner.steps.storage.fs.create.CreateImage
import com.github.kerubistan.kerub.planner.steps.storage.gvinum.create.CreateGvinumVolume
import com.github.kerubistan.kerub.planner.steps.storage.lvm.create.CreateLv
import com.github.kerubistan.kerub.planner.steps.storage.lvm.create.CreateThinLv
import com.github.kerubistan.kerub.planner.steps.storage.lvm.duplicate.DuplicateToLvm
import com.github.kerubistan.kerub.planner.steps.storage.lvm.mirror.MirrorVolume
import com.github.kerubistan.kerub.planner.steps.storage.lvm.vg.RemoveDiskFromVG
import com.github.kerubistan.kerub.planner.steps.storage.migrate.dead.block.MigrateBlockAllocation
import com.github.kerubistan.kerub.planner.steps.storage.mount.MountNfs
import com.github.kerubistan.kerub.planner.steps.storage.remove.RemoveVirtualStorage
import com.github.kerubistan.kerub.planner.steps.storage.share.iscsi.AbstractIscsiShare
import com.github.kerubistan.kerub.planner.steps.storage.share.nfs.ShareNfs
import com.github.kerubistan.kerub.planner.steps.storage.share.nfs.daemon.StartNfsDaemon
import com.github.kerubistan.kerub.planner.steps.vm.migrate.kvm.KvmMigrateVirtualMachine
import com.github.kerubistan.kerub.planner.steps.vm.start.kvm.KvmStartVirtualMachine
import com.github.kerubistan.kerub.planner.steps.vm.start.virtualbox.VirtualBoxStartVirtualMachine
import com.github.kerubistan.kerub.stories.config.ControllerConfigDefs
import com.github.kerubistan.kerub.testVm
import com.github.kerubistan.kerub.utils.silent
import com.github.kerubistan.kerub.utils.toSize
import com.github.kerubistan.kerub.utils.update
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.doAnswer
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import cucumber.api.DataTable
import cucumber.api.PendingException
import cucumber.api.java.Before
import cucumber.api.java.en.And
import cucumber.api.java.en.Given
import cucumber.api.java.en.Then
import cucumber.api.java.en.When
import io.github.kerubistan.kroki.collections.concat
import io.github.kerubistan.kroki.collections.replace
import io.github.kerubistan.kroki.collections.skip
import io.github.kerubistan.kroki.size.GB
import io.github.kerubistan.kroki.time.now
import org.junit.Assert
import java.math.BigInteger
import java.util.UUID
import java.util.UUID.randomUUID
import java.util.concurrent.ForkJoinPool
import kotlin.test.assertTrue
/**
* Cucumber step definitions for Planner integration tests.
* The idea behind these step definitions is that here we create a complete representation of the
* state of the kerub installation the way the planner sees it, and then we can trigger the planner
* and we have other cucumber definitions here to check that the desired plans were created by
* the planner.
*
* In the beginning of course this class used to be small, but as the data model grew and the number
* of possible operations increased, it has became a kitchen-sink.
*
* It should be broken up to multiple classes handling separately
* - VMs
* - hosts
* - physical storage
* - physical networks
* - virtual networks
* - virtual disks
* - controller
*
* All the above functional areas should include their own verifications,
* and maybe only the invocation of the planner should remain here.
*/
class PlannerDefs {
var vnets = listOf<VirtualNetwork>()
var vms = listOf<VirtualMachine>()
var hosts = listOf<Host>()
private var vdisks = listOf<VirtualStorageDevice>()
var vmDyns = listOf<VirtualMachineDynamic>()
var hostDyns = listOf<HostDynamic>()
private var vstorageDyns = listOf<VirtualStorageDeviceDynamic>()
private var hostConfigs = listOf<HostConfiguration>()
private var controllerConfig = ControllerConfig()
private val backtrack: BacktrackService = BacktrackServiceImpl(ForkJoinPool(1))
val executor: PlanExecutor = mock()
private val builder: OperationalStateBuilder = mock()
val planner: Planner = PlannerImpl(
backtrack,
executor,
builder,
PlanViolationDetectorImpl
)
private var executedPlans = listOf<Plan>()
@Before
fun setup() {
whenever(builder.buildState()).then {
OperationalState.fromLists(
hosts = hosts,
hostDyns = hostDyns,
hostCfgs = hostConfigs,
vms = vms,
vmDyns = vmDyns,
vStorage = vdisks,
vStorageDyns = vstorageDyns,
virtualNetworks = vnets,
config = controllerConfig
)
}
doAnswer {
executedPlans = executedPlans + (it.arguments[0] as Plan)
Unit
}.whenever(executor).execute(any(), any())
}
@Given("^virtual networks:$")
fun setVirtualNetworks(vmsTable: DataTable) {
val raw = vmsTable.raw().skip()
vnets = raw.map {
VirtualNetwork(
name = it[0],
id = randomUUID()
)
}
}
@Given("^VMs:$")
fun setVms(vmsTable: DataTable) {
val raw = vmsTable.raw()
for (row in raw.filter { it != raw.first() }) {
val vm = VirtualMachine(
name = row[0],
memory = Range(
min = (row[1].toSize()),
max = (row[2].toSize())
),
nrOfCpus = row[3].toInt(),
expectations = listOf(
CpuArchitectureExpectation(
cpuArchitecture = row[4]
)
)
)
this.vms = this.vms + vm
}
}
@Given("^hosts:$")
fun hosts(hostsTable: DataTable) {
for (row in hostsTable.raw().filter { it != hostsTable.raw().first() }) {
val host = Host(
address = row[0],
dedicated = true,
publicKey = "",
capabilities = HostCapabilities(
os = OperatingSystem.valueOf(row[5]),
cpuArchitecture = row[4],
cpus = listOf(ProcessorInformation(
manufacturer = "Test",
coreCount = row[2].toInt(),
threadCount = row[3].toInt(),
flags = listOf(),
l1cache = null,
l2cache = null,
l3cache = null,
maxSpeedMhz = 3200,
socket = "",
version = "",
voltage = null
)
),
chassis = null,
distribution = SoftwarePackage(
name = silent { row[6] } ?: row[5],
version = silent { Version.fromVersionString(row[7]) }
?: Version.fromVersionString("1.0")
),
devices = listOf(),
installedSoftware = listOf(),
system = null,
totalMemory = row[1].toSize(),
hypervisorCapabilities = listOf(
LibvirtCapabilities(
guests = listOf(
LibvirtGuest(
osType = "hvm",
arch = LibvirtArch(
name = "x86_64",
wordsize = 64,
emulator = "/usr/bin/qemu-kvm"
)
)
)
)
)
)
)
hosts = hosts + host
}
}
@Given("host (\\S+) is scheduled for recycling")
fun setHoostRecycle(address: String) {
hosts = hosts.replace({ it.address == address }, {
it.copy(recycling = true)
})
}
@Given("host (\\S+) is (not\\s+)?dedicated")
fun setDedicated(address: String, yesNo: String?) {
hosts = hosts.replace({ it.address == address }, {
it.copy(dedicated = yesNo?.trim() != "not")
})
}
@Given("host (\\S+) filesystem is:")
fun setHostFilesystemCapabilities(hostAddr: String, mounts: DataTable) {
val fsCapabilities = mounts.raw().skip().map { row ->
FsStorageCapability(
size = row[1].toSize(),
mountPoint = row[0],
fsType = row[3]
)
}
hosts = hosts.replace({ it.address == hostAddr }, { host ->
host.copy(
capabilities = requireNotNull(host.capabilities).copy(
storageCapabilities = requireNotNull(host.capabilities).storageCapabilities + fsCapabilities
)
)
})
}
@Given("host (\\S+) gvinum disks are:")
fun setHostGvinumCapabilities(hostAddr: String, disks: DataTable) {
val diskCapabilities = listOf(
GvinumStorageCapability(
devices = disks.raw().skip().map { row ->
GvinumStorageCapabilityDrive(
name = row[0],
size = row[2].toSize(),
device = row[1]
)
}
)
)
disks.raw().skip().map { row ->
}
hosts = hosts.replace({ it.address == hostAddr }, { host ->
host.copy(
capabilities = host.capabilities!!.copy(
storageCapabilities = requireNotNull(host.capabilities?.storageCapabilities) + diskCapabilities
)
)
})
}
@Given("host (\\S+) volume groups are:")
fun setHostLvmCapabilities(hostAddr: String, vgs: DataTable) {
val lvmCapabilities = vgs.raw().skip().map { row ->
LvmStorageCapability(
id = UUID.randomUUID(),
physicalVolumes = row[2].split(",").map {
val (device, size) = it.trim().split(":")
device.trim() to size.trim().toSize()
}.toMap(),
size = row[1].toSize(),
volumeGroupName = row[0]
)
}
val host = hosts.first { it.address == hostAddr }
hosts = hosts.replace({ it.id == host.id }, { stat ->
stat.copy(
capabilities = requireNotNull(stat.capabilities).copy(
storageCapabilities = requireNotNull(requireNotNull(stat.capabilities).storageCapabilities) + lvmCapabilities,
blockDevices = stat.capabilities!!.blockDevices + lvmCapabilities.map {
it.physicalVolumes.map {
BlockDevice(
deviceName = it.key,
storageCapacity = it.value)
}
}.concat()
)
)
})
hostDyns = hostDyns.replace({ it.id == host.id }, { dyn ->
val blockDevices = lvmCapabilities.map { it.physicalVolumes.map { it.key to true } }.concat().toMap()
dyn.copy(
storageStatus = dyn.storageStatus + lvmCapabilities.map {
CompositeStorageDeviceDynamic(id = it.id, reportedFreeCapacity = it.size)
},
storageDeviceHealth = dyn.storageDeviceHealth + blockDevices
)
})
}
@Given("(\\S+) is running on (\\S+)")
fun setVmRunningOnHost(vmName: String, hostAddr: String) {
val vm = vms.first { it.name == vmName }
vms = vms.replace({ it.id == vm.id }, {
it.copy(
expectations = vm.expectations + listOf(
VirtualMachineAvailabilityExpectation(up = true))
)
})
val host = hosts.first { it.address == hostAddr }
vmDyns = vmDyns + VirtualMachineDynamic(
id = vm.id,
hostId = host.id,
status = VirtualMachineStatus.Up,
lastUpdated = now(),
memoryUsed = vm.memory.min
)
requireNotNull(hostDyns.firstOrNull { it.id == host.id }) { "host must be up, otherwise no vm!" }
hostDyns = hostDyns.replace({ it.id == host.id }, {
it.copy(
memFree = requireNotNull(it.memFree ?: host.capabilities?.totalMemory) - vm.memory.min,
memUsed = (it.memUsed ?: BigInteger.ZERO) + vm.memory.min
)
})
}
@Given("^VM (\\S+) has NIC of type (\\S+) connected to network (\\S+)$")
fun setVmNetworkCard(vmName: String, nicType: String, networkName: String) {
vms = vms.update(
selector = { it.name == vmName },
map = { vm ->
vm.copy(
devices = vm.devices + NetworkDevice(
networkId = vnets.single { vnet -> vnet.name == networkName }.id,
adapterType = enumValueOf(nicType)
)
)
}
)
}
@When("^VM (\\S+) is started$")
fun startVm(vm: String) {
vms = vms.map {
if (it.name == vm) {
it.copy(expectations = (
it.expectations
+ VirtualMachineAvailabilityExpectation(
level = ExpectationLevel.DealBreaker,
up = true
)
)
)
} else {
it
}
}
planner.onEvent(EntityUpdateMessage(
obj = vms.first { it.name == vm },
date = now()
))
}
@When("^VMs (\\S+) are started$")
fun startVms(vmNames: String) {
val vmsToStart = vmNames.split(",").toSet()
vms = vms.map {
if (it.name in vmsToStart) {
it.copy(expectations = (
it.expectations
+ VirtualMachineAvailabilityExpectation(
level = ExpectationLevel.DealBreaker,
up = true
)
)
)
} else {
it
}
}
planner.onEvent(
EntityUpdateMessage(
obj = vms.single { it.name == vmsToStart.toList().first() },
date = now()
))
}
@Then("^host (\\S+) will be recycled as step (\\d+)$")
fun verifyHostRecycleStep(hostAddress: String, stepNo: Int) {
Assert.assertTrue(executedPlans.any { plan ->
plan.steps[stepNo - 1].let { step ->
step is RecycleHost &&
step.host.address == hostAddress
}
})
}
@Then("^host (\\S+) will be recycled$")
fun verifyHostRecycle(hostAddress: String) {
Assert.assertTrue(executedPlans.any {
it.steps.any {
it is RecycleHost &&
it.host.address == hostAddress
}
})
}
@Then("^host (\\S+) will (not\\s+)?be powered down")
fun verifyHostPowerDown(hostAddress: String, yesNo: String?) {
val shouldPowerDown = yesNo?.trim() != "not"
Assert.assertEquals(shouldPowerDown, executedPlans.any {
it.steps.any {
it is PowerDownHost &&
it.host.address == hostAddress
}
})
}
@Then("^VM (\\S+) gets scheduled on host (\\S+) with kvm hypervisor$")
fun verifyVmScheduledOnHostWithKvm(vmName: String, hostAddress: String) {
assertTrue("plans are: $executedPlans") {
executedPlans.any {
it.steps.any {
it is KvmStartVirtualMachine
&& it.host.address == hostAddress
&& it.vm.name == vmName
}
}
}
}
@Then("^VM (\\S+) gets scheduled on host (\\S+) with virtualbox hypervisor$")
fun verifyVmScheduledOnHostWithVirtualBox(vmName: String, hostAddress: String) {
Assert.assertTrue(executedPlans.any {
it.steps.any {
it is VirtualBoxStartVirtualMachine
&& it.host.address == hostAddress
&& it.vm.name == vmName
}
})
}
@Then("(\\S+) must be shared with iscsi on host (\\S+) as step (\\d+)")
fun verifyDiskIscsiShare(diskName: String, hostName: String, stepNo: Int) {
val shareStep = executedPlans.first().steps[stepNo - 1]
Assert.assertTrue("step $stepNo is $shareStep", shareStep is AbstractIscsiShare)
Assert.assertEquals((shareStep as AbstractIscsiShare).host.address, hostName)
Assert.assertEquals(shareStep.vstorage.name, diskName)
}
@Then("nfs must be started on host (\\S+) as step (\\d+)")
fun verifyDirectoryNfsStart(hostName: String, stepNo: Int) {
val startStep = executedPlans.first().steps[stepNo - 1]
Assert.assertTrue("step $stepNo is $startStep", startStep is StartNfsDaemon)
Assert.assertEquals((startStep as StartNfsDaemon).host.address, hostName)
}
@Then("(\\S+) must be shared with nfs on host (\\S+) as step (\\d+)")
fun verifyDirectoryNfsShare(directory: String, hostName: String, stepNo: Int) {
val shareStep = executedPlans.first().steps[stepNo - 1]
Assert.assertTrue("step $stepNo is $shareStep", shareStep is ShareNfs)
Assert.assertEquals((shareStep as ShareNfs).host.address, hostName)
Assert.assertEquals(shareStep.directory, directory)
}
@Then("(\\S+):(\\S+) must be mounted on (\\S+) as step (\\d+)")
fun verifyDirectoryNfsMount(nfsHost: String, directory: String, hostName: String, stepNo: Int) {
val mountStep = executedPlans.first().steps[stepNo - 1]
Assert.assertTrue("step $stepNo is $mountStep", mountStep is MountNfs)
Assert.assertEquals((mountStep as MountNfs).host.address, hostName)
Assert.assertEquals(mountStep.remoteDirectory, directory)
Assert.assertEquals(mountStep.remoteHost.address, nfsHost)
}
@Then("^(\\S+) will be migrated to (\\S+) as step (\\d+)")
fun verifyVmMigration(vmName: String, targetHostAddr: String, stepNo: Int) {
val migrationStep = executedPlans.first().steps[stepNo - 1]
assertTrue("Migration step is $migrationStep") { migrationStep is KvmMigrateVirtualMachine }
Assert.assertEquals((migrationStep as KvmMigrateVirtualMachine).target.address, targetHostAddr)
Assert.assertEquals(migrationStep.vm.name, vmName)
}
@Then("virtual disk (\\S+) will be block dead-migrated from (\\S+) to (\\S+)")
fun verifyBlockDeadMigration(diskName: String, sourceHostAddr: String, targetHostAddr: String) {
Assert.assertTrue(executedPlans.any {
it.steps.any { step ->
step is MigrateBlockAllocation
&& step.virtualStorage.name == diskName
&& step.sourceHost.address == sourceHostAddr
&& step.targetHost.address == targetHostAddr
}
})
}
@Then("ovs switch will be created on host (\\S+) for network (\\S+)")
fun verifyVirtualSwitchCreated(hostAddr: String, networkName: String) {
assertTrue(executedPlans.first().steps.any { step ->
step is CreateOvsSwitch
&& step.host.address == hostAddr
&& step.network.name == networkName
})
}
@Then("ovs port will be created on host (\\S+) on network (\\S+) for (\\S+)")
fun verifyPortCreated(hostAddr: String, networkName: String, vmName: String) {
assertTrue(executedPlans.first().steps.any { step ->
step is CreateOvsPort
&& step.host.address == hostAddr
&& step.virtualNetwork == vnets.single { it.name == networkName }
&& step.portName == vms.single { it.name == vmName }.idStr
})
}
@Then("^VM (\\S+) gets scheduled on host (\\S+)$")
fun verifyVmGetsScheduled(vmName: String, targetHostAddr: String) {
assertTrue(executedPlans.first().steps.any { step ->
step is KvmStartVirtualMachine
&& step.host.address == targetHostAddr
&& step.vm.name == vmName
})
}
@Then("^VM (\\S+) gets scheduled on host (\\S+) as step (\\d+)$")
fun verifyVmGetsScheduledWithStepNumber(vmName: String, targetHostAddr: String, stepNo: Int) {
val startStep = executedPlans.first().steps[stepNo - 1]
Assert.assertTrue(startStep is KvmStartVirtualMachine)
Assert.assertEquals((startStep as KvmStartVirtualMachine).host.address, targetHostAddr)
Assert.assertEquals(startStep.vm.name, vmName)
}
@When("^optimization is triggered$")
fun optimization_is_triggered() {
throw PendingException()
}
@Then("^host (\\S+) should be go to power-save$")
fun host_should_be_go_to_power_save(host: String) {
throw PendingException()
}
@Given("^status:$")
fun status(vmstatus: DataTable) {
throw PendingException()
}
@Given("software installed on host (\\S+):")
fun setHostInstalledSoftware(hostAddr: String, software: DataTable) {
hosts = hosts.replace(
{ it.address == hostAddr },
{ host ->
val caps = requireNotNull(host.capabilities)
host.copy(
capabilities = caps.copy(
installedSoftware = software.raw().skip().map { row ->
row[0].split(",").map {
SoftwarePackage(name = it, version = Version.fromVersionString(row[1]))
}
}.concat()
)
)
}
)
}
@Given("^host (\\S+) is Up$")
fun setHostDyn(address: String) {
val host = getHostByAddr(address)
hostDyns += HostDynamic(
id = host.id,
status = HostStatus.Up,
memFree = host.capabilities?.totalMemory
)
}
@Given("^host (\\S+) is Down$")
fun setHostDown(hostAddress: String) {
val host = hosts.first { host ->
host.address == hostAddress
}
hostDyns = hostDyns.filter { dyn ->
dyn.id != host.id
}
}
@Then("^(\\S+) will be started as step (\\d+)$")
fun verifyHostStartedUp(hostAddr: String, stepNo: Int) {
val startStep = executedPlans.first().steps[stepNo - 1]
Assert.assertTrue(startStep is AbstractWakeHost)
Assert.assertEquals((startStep as AbstractWakeHost).host.address, hostAddr)
}
@Given("^virtual storage devices:$")
fun setVirtualStorageDevices(vstorage: DataTable) {
vdisks = vstorage.raw().filterNot { it[0] == "name" }.map {
VirtualStorageDevice(
name = it[0],
size = it[1].toSize(),
readOnly = it[2]!!.toBoolean()
)
}
}
@When("disk (\\S+) is recycled")
fun recycleVirtualStorage(name: String) {
vdisks = vdisks.map {
if (it.name == name) {
it.copy(recycling = true)
} else it
}
planner.onEvent(EntityUpdateMessage(
obj = vdisks.first { it.name == name },
date = now()
))
}
private fun createVirtualStorageAllocation(name: String,
hostAddr: String,
allocation: (Host,
VirtualStorageDevice,
VirtualStorageDeviceDynamic) -> VirtualStorageAllocation) {
val host = getHostByAddr(hostAddr)
val stat = vdisks.single { it.name == name }
val dyn = vstorageDyns.firstOrNull { it.id == stat.id } ?: VirtualStorageDeviceDynamic(
id = stat.id,
lastUpdated = now(),
allocations = listOf()
)
vstorageDyns = vstorageDyns - dyn + dyn.copy(
allocations = dyn.allocations + allocation(host, stat, dyn)
)
}
private inline fun <reified T : StorageCapability> getStorageCapability(hostAddr: String, selector : (T) -> Boolean) : T = requireNotNull(getHostByAddr(hostAddr).capabilities?.storageCapabilities)
.filterIsInstance<T>().single(selector)
private inline fun <reified T : StorageCapability> getStorageCapabilityId(hostAddr: String, selector : (T) -> Boolean) : UUID = getStorageCapability(hostAddr, selector).id
@Given("virtual storage (\\S+) allocated on host (\\S+) using fs mount point (\\S+)")
fun createVirtualStorageFsAllocation(name: String, hostAddr: String, mountPoint: String) {
createVirtualStorageAllocation(name, hostAddr) { host, stat, dyn ->
VirtualStorageFsAllocation(
hostId = host.id,
mountPoint = mountPoint,
actualSize = 10.GB,
fileName = "${mountPoint}/${stat.id}.qcow2",
type = VirtualDiskFormat.qcow2,
capabilityId = getStorageCapabilityId<FsStorageCapability>(hostAddr) {it.mountPoint == mountPoint}
)
}
}
@Given("virtual storage (\\S+) allocated on host (\\S+) using lvm volume group (\\S+)")
fun createVirtualStorageLvmAllocation(name: String, hostAddr: String, volGroup: String) {
createVirtualStorageAllocation(name, hostAddr) { host, stat, dyn ->
VirtualStorageLvmAllocation(
hostId = host.id,
path = "/dev/$volGroup/${dyn.id}",
actualSize = 10.GB,
vgName = volGroup,
capabilityId = getStorageCapabilityId<LvmStorageCapability>(hostAddr) { it.volumeGroupName == volGroup }
)
}
}
@Given("virtual storage (\\S+) allocated on host (\\S+) using simple gvinum disk name (.*)")
fun createVirtualStorageGvinumAllocation(name: String, hostAddr: String, diskName: String) {
createVirtualStorageAllocation(name, hostAddr) { host, stat, dyn ->
VirtualStorageGvinumAllocation(
hostId = host.id,
actualSize = 10.GB,
configuration = SimpleGvinumConfiguration(
diskName = diskName
),
capabilityId = getStorageCapabilityId<GvinumStorageCapability>(hostAddr) {
true /*there can be only one*/
}
)
}
}
private fun getHostByAddr(hostAddr: String) = hosts.single { it.address == hostAddr }
@Then("disk (\\S+) will be unallocated as step (\\d+)")
fun verifyDiskUnalloction(name: String, index: Int) {
executedPlans.first().steps[index - 1].let {
assertTrue(it is AbstractUnAllocate<*> && it.vstorage.name == name)
}
}
@Then("disk (\\S+) will be deleted as step (\\d+)")
fun verifyDiskRemove(name: String, index: Int) {
executedPlans.first().steps[index - 1].let {
assertTrue(it is RemoveVirtualStorage && it.virtualStorage.name == name)
}
}
@Given("^(\\S+) is attached to (\\S+)$")
fun attachDiskToVm(storageName: String, vmName: String) {
val storage = vdisks.first { it.name == storageName }
vms = vms.replace({ it.name == vmName }, {
it.copy(
virtualStorageLinks = it.virtualStorageLinks
+ VirtualStorageLink(
virtualStorageId = storage.id,
bus = BusType.sata
)
)
})
}
@Given("^(\\S+) is not yet created$")
fun removeVStorageDyn(storageName: String) {
val storage = vdisks.first { it.name == storageName }
vstorageDyns = vstorageDyns.filterNot { it.id == storage.id }
}
@Given("^the virtual disk (\\S+) is created on (\\S+)$")
fun createVStorageDynOld(storageName: String, hostAddr: String) {
createVStorageDyn(storageName, hostAddr, "/var")
}
@Given("^the virtual disk (\\S+) is created on (\\S+) at (\\S+)$")
fun createVStorageDyn(storageName: String, hostAddr: String, directory: String) {
val storage = vdisks.first { it.name == storageName }
val host = hosts.first { it.address == hostAddr }
vstorageDyns = vstorageDyns + VirtualStorageDeviceDynamic(
id = storage.id,
allocations = listOf(VirtualStorageFsAllocation(
hostId = host.id,
actualSize = storage.size,
mountPoint = directory,
type = VirtualDiskFormat.qcow2,
fileName = "$directory/${storage.id}.qcow2",
capabilityId = getStorageCapabilityId<FsStorageCapability>(hostAddr) {
it.mountPoint == directory
}
))
)
}
@Then("^the virtual disk (\\S+) must be allocated on (\\S+) under (\\S+)$")
fun verifyVirtualStorageCreatedOnFs(storageName: String, hostAddr: String, mountPoint: String) {
val storage = vdisks.first { it.name == storageName }
val host = hosts.first { it.address == hostAddr }
Assert.assertTrue(executedPlans.first().steps.any {
it is CreateImage &&
it.disk == storage &&
it.host == host &&
it.path == mountPoint
})
}
@Then("the virtual disk (\\S+) must be mirrored using lvm - (\\d+) mirrors as step (\\d+)")
fun verifyMirror(virtualDisk : String, nrOfMirrors : Int, stepNo: Int) {
Assert.assertTrue(executedPlans.first().steps[stepNo - 1].let {
it is MirrorVolume
&& it.mirrors.toInt() == nrOfMirrors
})
}
@Then("the virtual disk (\\S+) must be allocated on (\\S+) under on the volume group (\\S+)")
fun verifyVirtualStorageCreatedOnLvm(storageName: String, hostAddr: String, volumeGroup: String) {
Assert.assertTrue(executedPlans.first().steps.any {
it is CreateLv
&& it.disk.name == storageName
&& it.host.address == hostAddr
&& it.volumeGroupName == volumeGroup
})
}
@Then("the virtual disk (\\S+) must be thin-allocated on (\\S+) under on the volume group (\\S+)")
fun verifyVirtualStorageCreatedOnLvmThin(storageName: String, hostAddr: String, volumeGroup: String) {
Assert.assertTrue(executedPlans.first().steps.any {
it is CreateThinLv
&& it.disk.name == storageName
&& it.host.address == hostAddr
&& it.volumeGroupName == volumeGroup
})
}
@Then("the virtual disk (\\S+) must be allocated on (\\S+) under on the gvinum disks: (\\S+)")
fun checkGvinumConcatenated(storageName: String, hostAddr: String, diskNames: List<String>) {
assertTrue {
executedPlans.first().steps.any {
it is CreateGvinumVolume
&& it.disk.name == storageName
&& it.host.address == hostAddr
&& it.config is ConcatenatedGvinumConfiguration
}
}
}
@Then("the virtual disk (\\S+) must be allocated on (\\S+) under on the gvinum disk (\\S+)")
fun verifyVirtualStorageCreatedOnGvinum(storageName: String, hostAddr: String, diskName: String) {
Assert.assertTrue(executedPlans.first().steps.any {
it is CreateGvinumVolume
&& it.disk.name == storageName
&& it.host.address == hostAddr
// TODO: verify disk name
})
}
@Given("volume group (\\S+) on host (\\S+) has (\\S+) free capacity")
fun setVolumeGroupFreeCapacity(volumeGroupName: String, hostAddr: String, capacity: String) {
val host = hosts.first { it.address == hostAddr }
val volumeGroup = requireNotNull(
host
.capabilities
?.storageCapabilities
?.first {
it is LvmStorageCapability
&& it.volumeGroupName == volumeGroupName
}
) as LvmStorageCapability
setStorageCapabilityFreeCapacity(capacity, volumeGroup.id, host)
}
@Given("gvinum disk (\\S+) on host (\\S+) has (\\S+) free capacity")
fun setGvinumDiskFreeCapacity(diskName: String, hostAddr: String, capacity: String) {
val host = getHostByAddr(hostAddr)
val disk = requireNotNull(host.capabilities?.storageCapabilities?.filterIsInstance<GvinumStorageCapability>()?.single())
hostDyns = hostDyns.replace({ it.id == host.id }, { dyn ->
dyn.copy(
storageStatus = dyn.storageStatus.update(
selector = { it.id == disk.id },
default = { CompositeStorageDeviceDynamic(id = disk.id) },
map = {
it as CompositeStorageDeviceDynamic
it.copy(
items = it.items.filterNot { it.name == diskName } + CompositeStorageDeviceDynamicItem(
name = diskName,
freeCapacity = capacity.toSize()
)
)
}
)
)
})
}
private fun setStorageCapabilityFreeCapacity(capacity: String, capId: UUID, host: Host) {
hostDyns = hostDyns.replace({ it.id == host.id }, { dyn ->
dyn.copy(
storageStatus = dyn.storageStatus + CompositeStorageDeviceDynamic(
id = capId,
reportedFreeCapacity = capacity.toSize()
)
)
})
}
@Then("^the virtual disk (\\S+) must not be allocated$")
fun verifyNoStorageCreate(storageName: String) {
val storage = vdisks.first { it.name == storageName }
Assert.assertTrue(executedPlans.first().steps.none { it is CreateImage && it.disk == storage })
}
@Given("^no virtual machines$")
fun clearVirtualMachines() {
vms = listOf()
vmDyns = listOf()
}
@Given("(\\S+) manufaturer has NO L(\\d) cache")
fun setNoCache(hostAddress: String, cachelevel: Int) {
hosts = hosts.replace({ it.address == hostAddress }, { host ->
host.copy(
capabilities = host.capabilities!!.copy(
cpus = host.capabilities!!.cpus.replace({ true }, { cpu ->
cpu.copy(
l1cache = if (cachelevel == 1) null else cpu.l1cache,
l2cache = if (cachelevel == 2) null else cpu.l2cache
)
})
)
)
})
}
@Given("(\\S+) manufaturer has (\\S+\\s+\\S+) L(\\d) cache")
fun setCacheSize(hostAddress: String, amount: String, cachelevel: Int) {
val size = amount.toSize()
hosts = hosts.replace({ it.address == hostAddress }, { host ->
host.copy(
capabilities = host.capabilities!!.copy(
cpus = host.capabilities!!.cpus.replace({ true }, { cpu ->
val cacheInformation = CacheInformation(
size = size.toInt(),
errorCorrection = "",
operation = "",
socket = "",
speedNs = null
)
cpu.copy(
l1cache = if (cachelevel == 1) cacheInformation else cpu.l1cache,
l2cache = if (cachelevel == 2) cacheInformation else cpu.l2cache
)
})
)
)
})
}
@Given("^VM (\\S+) requires (\\S+\\s+\\S+) L1 cache$")
fun setVmCacheRequirement(vmName: String, amount: String) {
vms = vms.replace({ it.name == vmName }, { vm ->
vm.copy(
expectations = vm.expectations + CacheSizeExpectation(
minL1 = amount.toSize().toLong(),
level = ExpectationLevel.DealBreaker
)
)
})
}
@Given("^(\\S+) manufaturer is (\\S+)$")
fun setHostManufacturer(hostAddr: String, manufacturer: String) {
hosts = hosts.replace({ it.address == hostAddr }, { host ->
host.copy(
capabilities = host.capabilities?.copy(
chassis = host.capabilities?.chassis?.copy(manufacturer = manufacturer)
?: ChassisInformation(
manufacturer = manufacturer,
type = "BLADE",
height = null,
nrOfPowerCords = 1
)
)
)
})
}
@Given("^VM (\\S+) requires manufacturer (\\S+)$")
fun setVmHostManufacturerInformation(vmName: String, manufacturer: String) {
vms = vms.replace({ it.name == vmName }, { vm ->
vm.copy(
expectations = vm.expectations + ChassisManufacturerExpectation(
manufacturer = manufacturer
)
)
})
}
@Given("^(\\S+) has notsame host expectation against (\\S+)$")
fun addNotSameHostExpectation(vmName: String, otherVmName: String) {
val otherVm = vms.first { it.name == otherVmName }
vms = vms.replace({ it.name == vmName }, { vm ->
vm.copy(
expectations = vm.expectations + NotSameHostExpectation(
otherVmId = otherVm.id
)
)
})
}
@Given("^(\\S+) has cpu clock speed expectation (\\S+) Mhz$")
fun addCpuClockSpeedExpectation(vmName: String, freq: Int) {
vms = vms.replace({ it.name == vmName }, { vm ->
vm.copy(
expectations = vm.expectations + ClockFrequencyExpectation(
minimalClockFrequency = freq,
level = ExpectationLevel.Want
)
)
})
}
@Given("^(\\S+) cpu clockspeed is (\\S+) Mhz$")
fun setHostCpuSpeed(hostAddr: String, freq: Int) {
hosts = hosts.replace({ it.address == hostAddr }, { host ->
host.copy(
capabilities = host.capabilities?.copy(
cpus = host.capabilities?.cpus?.map {
it.copy(
maxSpeedMhz = freq
)
} ?: listOf()
)
)
})
}
@Given("^(\\S+) has ECC memory$")
fun setHostEccMemory(hostAddr: String) {
throw PendingException()
}
@Given("^(\\S+) does not have ECC memory$")
fun setHostNonEccMemory(hostAddr: String) {
throw PendingException()
}
@Given("(\\S+) has memory clock speed expectation (\\d+) Mhz")
fun addVmMemoryClockSpeedExpectation(vmName: String, speedMhz: Int) {
vms = vms.replace({ it.name == vmName }, { vm ->
vm.copy(
expectations = vm.expectations
+ MemoryClockFrequencyExpectation(level = ExpectationLevel.DealBreaker, min = speedMhz)
)
})
}
@Given("(\\S+) memory information is not known")
fun clearHostMemoryInformation(hostAddr: String) {
hosts = hosts.replace({ it.address == hostAddr }, { host ->
host.copy(
capabilities = host.capabilities?.copy(
memoryDevices = listOf()
)
)
})
}
@Given("(\\S+) memory clockspeed is (\\d+) Mhz")
fun setHostMemoryClockSpeed(hostAddr: String, speedMhz: Int) {
hosts = hosts.replace({ it.address == hostAddr }, { host ->
host.copy(
capabilities = host.capabilities!!.copy(
memoryDevices = listOf(
host.capabilities!!.memoryDevices.firstOrNull()
?: MemoryInformation(
size = 8.GB,
type = "",
formFactor = "SODIMM",
locator = "BANK-A",
speedMhz = speedMhz,
manufacturer = "DUCT TAPE INC",
partNumber = "",
configuredSpeedMhz = speedMhz,
serialNumber = "",
bankLocator = ""
)
)
)
)
})
}
@Given("virtual disk (\\S+) has not-same-storage expectation against (\\S+)")
fun addNotSameStorageExpectation(diskName: String, againstDiskName: String) {
val againstDisk = vdisks.first { it.name == againstDiskName }
vdisks = vdisks.replace({ it.name == diskName }, { vdisk ->
vdisk.copy(
expectations = vdisk.expectations + NotSameStorageExpectation(
level = ExpectationLevel.DealBreaker,
otherDiskId = againstDisk.id
)
)
})
}
@Given("(\\S+) requires dedicated cores")
fun addCoreDedicationExpectation(vmName: String) {
vms = vms.replace({ it.name == vmName }, {
it.copy(
expectations = it.expectations + CoreDedicationExpectation()
)
})
}
@Given("(\\S+) has no-migrate expectation")
fun addNoMigrateExpectation(vmName: String) {
vms = vms.replace({ it.name == vmName }, { vm ->
vm.copy(
expectations = vm.expectations + NoMigrationExpectation(userTimeoutMinutes = 60)
)
})
}
@Given("host (\\S+) has (\\S+) power management")
fun setPowerManagement(hostAddr: String, powerManagementType: String) {
val host = hosts.first { it.address == hostAddr }
val pm = when (powerManagementType) {
"wake-on-lan" -> WakeOnLanInfo()
"ipmi" -> IpmiInfo(
address = "",
password = "",
username = ""
)
else -> throw IllegalArgumentException("typo? $powerManagementType")
}
hosts = hosts.replace({ it.address == host.address }, {
host.copy(
capabilities = host.capabilities?.copy(
powerManagment = listOf(
pm
)
)
)
})
}
@And("(\\S+) has storage redundancy expectation: (\\d+) copies")
fun setStorageRedundancyExpectation(diskName: String, redundancyLevel : Int) {
vdisks = vdisks.replace({ it.name == diskName }, {
it.copy(
expectations = it.expectations + StorageRedundancyExpectation(nrOfCopies = redundancyLevel)
)
})
}
@When("virtual disk (\\S+) gets an availability expectation")
fun createVirtualStorageAvailabilityExpectation(diskName: String) {
vdisks = vdisks.replace({ it.name == diskName }, {
it.copy(
expectations = it.expectations + StorageAvailabilityExpectation(format = VirtualDiskFormat.raw)
)
})
val virtualStorage = vdisks.first { it.name == diskName }
planner.onEvent(EntityUpdateMessage(
obj = virtualStorage,
date = now()
))
}
@When("planner starts")
fun kickPlanner() {
planner.onEvent(EntityUpdateMessage(
obj = testVm,
date = now()
))
}
@Given("(\\S+) is allocated on host (\\S+) volume group (\\S+)")
fun createLvmAllocation(diskName: String, hostName: String, volumeGroup: String) {
val host = hosts.first { it.address == hostName }
val disk = vdisks.first { it.name == diskName }
val diskDyn = vstorageDyns.firstOrNull { it.id == disk.id }
if (diskDyn == null) {
vstorageDyns = vstorageDyns + VirtualStorageDeviceDynamic(
id = disk.id,
allocations = listOf(VirtualStorageLvmAllocation(
hostId = host.id,
actualSize = disk.size,
path = "/dev/test/" + disk.id,
vgName = volumeGroup,
capabilityId = requireNotNull(host.capabilities?.storageCapabilities)
.single { it is LvmStorageCapability && it.volumeGroupName == volumeGroup }.id
)),
lastUpdated = now()
)
}
}
@Given("(\\S+) is shared with iscsi on host (\\S+)")
fun createIscsiShare(diskName: String, hostName: String) {
val host = hosts.first { it.address == hostName }
val disk = vdisks.first { it.name == diskName }
val service = IscsiService(
vstorageId = disk.id
)
if (hostConfigs.any { it.id == host.id }) {
hostConfigs = hostConfigs.replace({ it.id == host.id }, {
it.copy(
services = it.services + service
)
})
} else {
hostConfigs = hostConfigs + HostConfiguration(
id = host.id,
services = listOf(service)
)
}
}
@Given("host (\\S+) CPUs are (\\S+):")
fun setHostCpus(addr: String, nrOfCpus: Int, cpuData: DataTable) {
val cpus = (1..nrOfCpus).map {
ProcessorInformation(
manufacturer = cpuData.raw()[1][0],
maxSpeedMhz = cpuData.raw()[1][1].toInt(),
flags = cpuData.raw()[1][3].split(","),
coreCount = cpuData.raw()[1].getOrNull(4)?.toInt(),
threadCount = cpuData.raw()[1].getOrNull(5)?.toInt(),
socket = "",
version = ""
)
}
hosts = hosts.replace(
{ it.address == addr },
{
it.copy(
capabilities = it.capabilities!!.copy(
cpus = cpus
)
)
}
)
}
@Given("Controller config enabled storage mounts are")
fun setConfigurationFsType(data: DataTable) {
this.controllerConfig = this.controllerConfig.copy(
storageTechnologies = this.controllerConfig.storageTechnologies.copy(
fsPathEnabled = data.raw().skip().map { it[0] }
)
)
}
@Given("Controller config filesystem type '(.*)' is (enabled|disabled)")
fun setConfigurationFsType(fstype: String, enabled: String) {
this.controllerConfig = this.controllerConfig.copy(
storageTechnologies = this.controllerConfig.storageTechnologies.copy(
fsTypeEnabled = if (enabled == "enabled") {
this.controllerConfig.storageTechnologies.fsTypeEnabled + fstype
} else {
this.controllerConfig.storageTechnologies.fsTypeEnabled.filter { it != fstype }
}
)
)
}
@Given("Controller configuration '(.*)' is (enabled|disabled)")
fun setConfigurationBoolean(configName: String, enabled: String) {
this.controllerConfig = requireNotNull(ControllerConfigDefs.configs[configName])
.invoke("enabled" == enabled, this.controllerConfig)
}
@Then("host ssh key must be generated on (\\S+) as step (\\d+)")
fun verifyHostSshGeneration(hostAddress: String, stepNr: Int) {
assertTrue("step $stepNr must be ssh key generation ") {
executedPlans.any {
it.steps.getOrNull(stepNr - 1)?.let {
it is GenerateSshKey &&
it.host.address == hostAddress
} ?: false
}
}
}
@Then("host ssh key of (\\S+) must be installed on (\\S+) as step (\\d+)")
fun verifyHostSShKeyInstall(sourceHostAddr: String, targetHostAddr: String, stepNr: Int) {
assertTrue("step $stepNr must be ssh key installation ") {
executedPlans.any { plan ->
plan.steps.getOrNull(stepNr - 1)?.let {
it is InstallPublicKey &&
it.sourceHost.address == sourceHostAddr
&& it.targetHost.address == targetHostAddr
} ?: false
}
}
}
@Then("the virtual disk (\\S+) must be duplicated to (\\S+) under volume group (\\S+) as step (\\d+)")
fun verifyDiskDuplicatedLvm(diskName: String,
targetHostAddr: String,
targetVg : String,
stepNr: Int) {
assertTrue("step $stepNr must be duplicate to lvm ") {
executedPlans.any {
it.steps.getOrNull(stepNr - 1)?.let {
it is DuplicateToLvm
&& it.targetHost.address == targetHostAddr
&& it.target.vgName == targetVg
&& it.virtualStorageDevice.name == diskName
} ?: false
}
}
}
@Then("no plan executed")
fun verifyNoPlanExecuted() {
assertTrue("There should not be any plans executed. \n $executedPlans") {
executedPlans.isEmpty()
}
}
@Then("no problem")
fun verifyNoProblems() {
val problems = CompositeProblemDetectorImpl.detect(Plan(builder.buildState()))
assertTrue("There should be no problems detected\n $problems") {
problems.isEmpty()
}
}
@When("disk (\\S+) in host (\\S+) signals failure")
fun setDiskFailing(device : String, hostAddress : String) {
val host = hosts.single { it.address == hostAddress }
hostDyns = hostDyns.update(selector = {it.id == host.id}, map = {
it.copy(
storageDeviceHealth = it.storageDeviceHealth + (device to false)
)
})
planner.onEvent(EntityUpdateMessage(
obj = hostDyns.single { it.id == host.id },
date = now()
))
}
@Then("disk (\\S+) in host (\\S+) will be removed from VG (\\S+) as step (\\d+)")
fun verifyPVRemove(device: String, hostAddr: String, volumeGroup: String, stepNr: Int) {
assertTrue("step $stepNr must be remove pv from vg") {
executedPlans.any { plan ->
plan.steps.getOrNull(stepNr - 1)?.let { step ->
step is RemoveDiskFromVG
&& step.device == device
&& step.host.address == hostAddr
&& step.capability.volumeGroupName == volumeGroup
} ?: false
}
}
}
}
| apache-2.0 | 0f8157d64ff505339a242df0a999738e | 32.891911 | 197 | 0.681923 | 3.585536 | false | false | false | false |
google/intellij-gn-plugin | src/main/java/com/google/idea/gn/completion/CompletionIdentifier.kt | 1 | 2174 | // Copyright (c) 2020 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package com.google.idea.gn.completion
import com.google.idea.gn.GnKeys
import com.intellij.codeInsight.AutoPopupController
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.icons.AllIcons
import com.intellij.ui.LayeredIcon
import javax.swing.Icon
interface CompletionIdentifier {
val identifierName: String
val autoSuggestOnInsertion: Boolean get() = false
val postInsertType: PostInsertType? get() = null
enum class PostInsertType(val extra: String, val caretShift: Int) {
CALL("()", 1),
CALL_WITH_STRING("(\"\")", 2);
}
enum class IdentifierType {
FUNCTION,
TARGET_FUNCTION,
VARIABLE,
FUNCTION_VARIABLE,
TEMPLATE;
val icon: Icon
get() = when (this) {
FUNCTION -> AllIcons.Nodes.Function
TARGET_FUNCTION -> LayeredIcon.create(AllIcons.Nodes.Target, AllIcons.Nodes.Shared)
VARIABLE -> AllIcons.Nodes.Variable
TEMPLATE -> AllIcons.Actions.Lightning
FUNCTION_VARIABLE -> LayeredIcon.create(AllIcons.Nodes.Variable, AllIcons.Nodes.StaticMark)
}
}
val identifierType: IdentifierType
val typeString: String? get() = null
fun gatherChildren(operator: (CompletionIdentifier) -> Unit) = Unit
fun addToResult(resultSet: CompletionResultSet) {
resultSet.startBatch()
val element = LookupElementBuilder.create(identifierName)
.withIcon(identifierType.icon)
.withTypeText(typeString)
.withInsertHandler { ctx, _ ->
postInsertType?.let {
ctx.document.insertString(ctx.tailOffset, it.extra)
ctx.editor.caretModel.primaryCaret.moveCaretRelatively(it.caretShift, 0, false, false)
}
if (autoSuggestOnInsertion) {
AutoPopupController.getInstance(ctx.project).scheduleAutoPopup(ctx.editor)
}
}
element.putUserData(GnKeys.IDENTIFIER_COMPLETION_TYPE, identifierType)
resultSet.addElement(element)
}
}
| bsd-3-clause | 3cdee824f4e93346d1405b4850d2d4e0 | 31.939394 | 99 | 0.713891 | 4.445808 | false | false | false | false |
stoichoandreev/TensorFlowHackaton | app/src/main/java/com/gumtree/tensorflowexample/preferences/ImagePreference.kt | 1 | 368 | package com.gumtree.tensorflowexample.preferences
object ImagePreference {
val INPUT_SIZE = 224
val IMAGE_MEAN = 117
val IMAGE_STD = 1f
val INPUT_NAME = "input"
val OUTPUT_NAME = "output"
val MODEL_FILE = "file:///android_asset/tensorflow_inception_graph.pb"
val LABEL_FILE = "file:///android_asset/imagenet_comp_graph_label_strings.txt"
} | apache-2.0 | 2e85d6b05e16e3fd1ceb1bd9501a2e90 | 32.545455 | 82 | 0.703804 | 3.439252 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/rest/service/RestResourceFitness.kt | 1 | 8397 | package org.evomaster.core.problem.rest.service
import com.google.inject.Inject
import org.evomaster.core.database.DbAction
import org.evomaster.core.problem.enterprise.EnterpriseActionGroup
import org.evomaster.core.problem.external.service.httpws.HttpExternalServiceAction
import org.evomaster.core.problem.external.service.httpws.HttpExternalServiceRequest
import org.evomaster.core.problem.rest.RestCallAction
import org.evomaster.core.problem.rest.RestCallResult
import org.evomaster.core.problem.rest.RestIndividual
import org.evomaster.core.search.ActionFilter
import org.evomaster.core.search.ActionResult
import org.evomaster.core.search.EvaluatedIndividual
import org.evomaster.core.search.FitnessValue
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* take care of calculating/collecting fitness of [RestIndividual]
*/
class RestResourceFitness : AbstractRestFitness<RestIndividual>() {
@Inject
private lateinit var dm: ResourceDepManageService
@Inject
private lateinit var rm: ResourceManageService
companion object {
private val log: Logger = LoggerFactory.getLogger(RestResourceFitness::class.java)
}
/*
add db check in term of each abstract resource
*/
override fun doCalculateCoverage(
individual: RestIndividual,
targets: Set<Int>
): EvaluatedIndividual<RestIndividual>? {
rc.resetSUT()
/*
there might some dbaction between rest actions.
This map is used to record the key mapping in SQL, e.g., PK, FK
*/
val sqlIdMap = mutableMapOf<Long, Long>()
val executedDbActions = mutableListOf<DbAction>()
val actionResults: MutableList<ActionResult> = mutableListOf()
//whether there exist some SQL execution failure
var failureBefore = doDbCalls(
individual.seeInitializingActions().filterIsInstance<DbAction>(),
sqlIdMap,
true,
executedDbActions,
actionResults
)
val cookies = getCookies(individual)
val tokens = getTokens(individual)
val fv = FitnessValue(individual.size().toDouble())
//used for things like chaining "location" paths
val chainState = mutableMapOf<String, String>()
//run the test, one action at a time
var indexOfAction = 0
val allServedHttpRequests = mutableListOf<HttpExternalServiceRequest>()
RCallsLoop@
for (call in individual.getResourceCalls()) {
val result = doDbCalls(
call.seeActions(ActionFilter.ONLY_SQL) as List<DbAction>,
sqlIdMap,
failureBefore,
executedDbActions,
actionResults
)
failureBefore = failureBefore || result
var terminated = false
for (a in call.getViewOfChildren().filterIsInstance<EnterpriseActionGroup>()) {
// Note: [indexOfAction] is used to register the action in RemoteController
// to map it to the ActionDto.
/*
Always need to reset WireMock.
Assume there no is External Action here. Still, the SUT could make a call to an external service
because new code is reached (eg due mutation of some genes).
We do not want such new call to re-use a mocking from a previous action which were left on.
So 2 options: (1) always reset before calling SUT, or (2) always reset after call in which external
setups were used.
*/
externalServiceHandler.resetServedRequests()
val externalServiceActions = a.getExternalServiceActions()
externalServiceActions.forEach { it.resetActive() }
externalServiceActions.filter { it.active }
.filterIsInstance<HttpExternalServiceAction>()
.forEach {
// TODO: Handling WireMock for ExternalServiceActions should be generalised
// to facilitate other cases such as RPC and GraphQL
it.buildResponse()
}
val restCallAction = a.getMainAction()
//TODO handling of inputVariables
registerNewAction(restCallAction, indexOfAction)
val ok: Boolean
if (restCallAction is RestCallAction) {
ok = handleRestCall(restCallAction, actionResults, chainState, cookies, tokens)
// update creation of resources regarding response status
val restActionResult = actionResults.filterIsInstance<RestCallResult>()[indexOfAction]
call.getResourceNode().confirmFailureCreationByPost(call, restCallAction, restActionResult)
restActionResult.stopping = !ok
} else {
throw IllegalStateException("Cannot handle: ${restCallAction.javaClass}")
}
// get visited wiremock instances
val requestedExternalServiceRequests = externalServiceHandler.getAllServedExternalServiceRequests()
allServedHttpRequests.addAll(requestedExternalServiceRequests)
if (requestedExternalServiceRequests.isNotEmpty()) {
fv.registerExternalServiceRequest(indexOfAction, requestedExternalServiceRequests)
}
val employedDefault = requestedExternalServiceRequests.map { it.wireMockSignature }.distinct().filter {
externalServiceActions.filterIsInstance<HttpExternalServiceAction>()
.none { a -> a.request.wireMockSignature == it }
}.associate {
val es = externalServiceHandler.getExternalService(it)
es.getRemoteHostName() to es
}
fv.registerExternalRequestToDefaultWM(indexOfAction, employedDefault)
externalServiceActions.filterIsInstance<HttpExternalServiceAction>()
.groupBy { it.request.absoluteURL }
.forEach { (url, actions) ->
// times of url has been accessed with this rest call
val count = requestedExternalServiceRequests.count { r-> r.absoluteURL == url}
actions.forEachIndexed { index, action ->
if (index < count) {
action.confirmUsed()
} else {
action.confirmNotUsed()
}
}
}
if (!ok) {
terminated = true
}
if (terminated)
break@RCallsLoop
indexOfAction++
}
}
val allRestResults = actionResults.filterIsInstance<RestCallResult>()
val dto = restActionResultHandling(individual, targets, allRestResults, fv) ?: return null
/*
harvest actual requests once all actions are executed
*/
harvestResponseHandler.addHttpRequests(allServedHttpRequests)
/*
TODO: Man shall we update the action cluster based on expanded action?
*/
individual.seeMainExecutableActions().forEach {
val node = rm.getResourceNodeFromCluster(it.path.toString())
node.updateActionsWithAdditionalParams(it)
}
/*
update dependency regarding executed dto
*/
if (config.extractSqlExecutionInfo && config.probOfEnablingResourceDependencyHeuristics > 0.0)
dm.updateResourceTables(individual, dto)
if (actionResults.size > individual.seeActions(ActionFilter.NO_EXTERNAL_SERVICE).size)
log.warn("Mismatch in action results: ${actionResults.size} > ${individual.seeActions(ActionFilter.NO_EXTERNAL_SERVICE).size}")
return EvaluatedIndividual(
fv,
individual.copy() as RestIndividual,
actionResults,
config = config,
trackOperator = individual.trackOperator,
index = time.evaluatedIndividuals
)
}
} | lgpl-3.0 | b01beaa3c561d1911d9f9ca5108609e0 | 37.522936 | 139 | 0.612481 | 5.716133 | false | false | false | false |
hhariri/mark-code | src/main/kotlin/com/hadihariri/markcode/codegen.kt | 1 | 2537 | package com.hadihariri.markcode
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
val EMPTY_SOURCE_METADATA = SourceMetadata(null, null, emptyList(), false, null, false, false, false, emptyList())
fun captionToFilename(caption: String, captionIndex: Int): String {
val name = StringBuilder()
var capitalize = true
caption.forEach {
if (it == ' ') {
capitalize = true
} else if (it.isLetterOrDigit()) {
name.append(if (capitalize) it.toUpperCase() else it)
capitalize = false
}
}
return name.toString() + (if (captionIndex == 0) "" else "$captionIndex")
}
val annotationRegex = Regex("<(\\d+)>")
fun String.startsWithAny(vararg prefixes: String) = prefixes.any { startsWith(it) }
fun extractChapterNumber(filename: String): Int {
if (filename.startsWith("ch")) {
return Integer.parseInt(filename.removePrefix("ch").substringBeforeLast("."))
}
return 0
}
fun writeVerifyAllSamples(chapters: List<Chapter>, outputDir: File) {
BufferedWriter(FileWriter(File(outputDir, "VerifyAllSamples.kt"))).use { outputFile ->
outputFile.write("import com.hadihariri.markcode.OutputVerifier\n")
val examples = mutableListOf<ExampleOutput>()
for (chapter in chapters) {
for (example in chapter.examples.values.filter { !it.skip && it.language is KotlinLanguage && it.hasOutputToVerify }) {
val fqName = example.packageName ?: continue
val import = fqName.replace('.', '_')
outputFile.write("import $fqName.main as $import\n")
examples.add(ExampleOutput(
import,
"${chapter.chapterCodeDir.name}/${example.expectedOutputFileName}",
"${example.chapter.chapterFile.name}:${example.expectedOutputStartLine ?: example.mainExample?.expectedOutputStartLine}"))
}
}
// TODO - make this actually read the file so we don't have to keep in sync
// (distZip right now needs proper path for this so that's why hacked right now)
outputFile.write("\n\nfun main(args: Array<String>) {\n")
outputFile.write(" val verifier = OutputVerifier()\n")
for ((function, expectedOutput, location) in examples) {
outputFile.write(" verifier.verifySample(::$function, \"$outputDir/$expectedOutput\", \"$location\")\n")
}
outputFile.write(" verifier.report()\n}\n")
}
}
| mit | ba04e4fda86046cd753d526f9f3c2ea8 | 38.640625 | 146 | 0.632243 | 4.474427 | false | false | false | false |
tmarsteel/kotlin-prolog | async/src/main/kotlin/com/github/prologdb/async/GeneratorLazySequence.kt | 1 | 1262 | package com.github.prologdb.async
internal class GeneratorLazySequence<T : Any>(
override val principal: Principal,
private val generator: () -> T?
) : LazySequence<T> {
var closed = false
var cached: T? = null
override fun step(): LazySequence.State {
if (closed) return LazySequence.State.DEPLETED
if (cached == null) {
cached = generator()
if (cached == null) {
closed = true
return LazySequence.State.DEPLETED
}
}
return LazySequence.State.RESULTS_AVAILABLE
}
override val state: LazySequence.State
get() = if (closed) LazySequence.State.DEPLETED else if (cached == null) LazySequence.State.PENDING else LazySequence.State.RESULTS_AVAILABLE
override fun tryAdvance(): T? {
if (closed) return null
when (step()) {
LazySequence.State.RESULTS_AVAILABLE -> {
val result = cached
cached = null
return result
}
LazySequence.State.DEPLETED -> return null
else -> throw IllegalStateException()
}
}
override fun close() {
closed = true
}
} | mit | 08db1e8530a8c7fb734128b74e826427 | 28.372093 | 149 | 0.55626 | 4.853846 | false | false | false | false |
NephyProject/Penicillin | src/main/kotlin/jp/nephy/penicillin/endpoints/oauth/AccessToken.kt | 1 | 5509 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Nephy Project Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
@file:Suppress("UNUSED", "PublicApiImplicitType")
package jp.nephy.penicillin.endpoints.oauth
import jp.nephy.penicillin.PenicillinClient
import jp.nephy.penicillin.core.request.formBody
import jp.nephy.penicillin.core.session.config.account
import jp.nephy.penicillin.core.session.config.application
import jp.nephy.penicillin.core.session.config.token
import jp.nephy.penicillin.core.session.post
import jp.nephy.penicillin.endpoints.OAuth
import jp.nephy.penicillin.endpoints.Option
import jp.nephy.penicillin.endpoints.oauth
import jp.nephy.penicillin.extensions.execute
/**
* Represents "/oauth/access_token" response.
*/
data class AccessTokenResponse(
/**
* Access token for this application.
*/
val accessToken: String,
/**
* Access token secret for this application.
*/
val accessTokenSecret: String,
/**
* User id of authenticated user.
*/
val userId: Long,
/**
* Screen name of authenticated user.
*/
val screenName: String
)
/**
* Allows a Consumer application to exchange the OAuth Request Token for an OAuth Access Token. This method fulfills [Section 6.3](http://oauth.net/core/1.0/#auth_step3) of the [OAuth 1.0 authentication](http://oauth.net/core/1.0/#anchor9) flow.
*
* [Twitter API reference](https://developer.twitter.com/en/docs/basics/authentication/api-reference/access_token)
*
* @param verifier If using the OAuth web-flow, set this parameter to the value of the oauth_verifier returned in the callback URL. If you are using out-of-band OAuth, set this value to the pin-code. For OAuth 1.0a compliance this parameter is required. OAuth 1.0a is strictly enforced and applications not using the oauth_verifier will fail to complete the OAuth flow.
* @param options Optional. Custom parameters of this request.
* @receiver [OAuth] endpoint instance.
* @return [AccessTokenResponse].
*/
suspend fun OAuth.accessToken(
consumerKey: String,
consumerSecret: String,
requestToken: String,
requestTokenSecret: String,
verifier: String,
vararg options: Option
): AccessTokenResponse {
val response = PenicillinClient {
account {
application(consumerKey, consumerSecret)
token(requestToken, requestTokenSecret)
}
}.use {
it.oauth.accessTokenInternal(verifier, *options).execute()
}
val result = response.content.split("&").map { parameter ->
parameter.split("=", limit = 2).let { it.first() to it.last() }
}.toMap()
val accessToken = result["oauth_token"] ?: throw IllegalStateException()
val accessTokenSecret = result["oauth_token_secret"] ?: throw IllegalStateException()
val userId = result["user_id"]?.toLongOrNull() ?: throw IllegalStateException()
val screenName = result["screen_name"] ?: throw IllegalStateException()
return AccessTokenResponse(accessToken, accessTokenSecret, userId, screenName)
}
/**
* Allows a Consumer application to exchange the OAuth Request Token for an OAuth Access Token. This method fulfills [Section 6.3](http://oauth.net/core/1.0/#auth_step3) of the [OAuth 1.0 authentication](http://oauth.net/core/1.0/#anchor9) flow.
*
* [Twitter API reference](https://developer.twitter.com/en/docs/basics/authentication/api-reference/access_token)
*
* @param verifier If using the OAuth web-flow, set this parameter to the value of the oauth_verifier returned in the callback URL. If you are using out-of-band OAuth, set this value to the pin-code. For OAuth 1.0a compliance this parameter is required. OAuth 1.0a is strictly enforced and applications not using the oauth_verifier will fail to complete the OAuth flow.
* @param options Optional. Custom parameters of this request.
* @receiver [OAuth] endpoint instance.
* @return [AccessTokenResponse].
*/
suspend fun OAuth.accessToken(
requestToken: String,
requestTokenSecret: String,
verifier: String,
vararg options: Option
) = accessToken(client.session.credentials.consumerKey!!, client.session.credentials.consumerSecret!!, requestToken, requestTokenSecret, verifier, *options)
private fun OAuth.accessTokenInternal(
verifier: String,
vararg options: Option
) = client.session.post("/oauth/access_token") {
formBody(
"oauth_verifier" to verifier,
*options
)
}.text()
| mit | f0c60d058be340d5800a30c76ccd1d0a | 41.376923 | 369 | 0.734979 | 4.290498 | false | false | false | false |
AlexanderDashkov/hpcourse | csc/2016/vsv_1/src/handlers/RequestExecutorService.kt | 3 | 6049 | package handlers
import communication.CommunicationProtos
import java.io.InputStream
import java.io.OutputStream
import java.net.Socket
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
import kotlin.concurrent.thread
class RequestExecutorService {
private val receivedTasks: MutableMap<Int, CommunicationProtos.ServerRequest> = LinkedHashMap()
private val completedTasks: MutableMap<Int, Long> = Collections.synchronizedMap(LinkedHashMap<Int, Long>())
private val runningTasksLock: MutableMap<Int, Object> = LinkedHashMap()
private var lastId = AtomicInteger(0)
fun execute(clientSocket: Socket) {
thread {
val request = getRequest(clientSocket.inputStream)
val response = if (request != null) handleRequest(request) else buildErrorResponse(null)
if (!clientSocket.isClosed) {
sendResponse(clientSocket.outputStream, response)
}
}
}
private fun handleRequest(request: CommunicationProtos.ServerRequest): CommunicationProtos.ServerResponse {
var _response: CommunicationProtos.ServerResponse? = null
if (request.hasSubmit()) {
println("Submit request received")
_response = TaskResultToResponseBuilder.fromSubmitTask(request.requestId, handleSubmit(request))
} else if (request.hasSubscribe()) {
println("Subscribe request received")
_response = TaskResultToResponseBuilder.fromSubscribeTask(request.requestId, handleSubscribe(request))
} else if (request.hasList()) {
println("List request received")
_response = TaskResultToResponseBuilder.fromListTask(request.requestId, handleList(request))
}
val response: CommunicationProtos.ServerResponse = _response ?: return buildErrorResponse(request)
println("Complete ${request.requestId} hadnling")
return response
}
private fun buildErrorResponse(request: CommunicationProtos.ServerRequest?): CommunicationProtos.ServerResponse {
val response = CommunicationProtos.ServerResponse.newBuilder()
if (request != null) {
response.requestId = request.requestId
}
return response.build()
}
private fun handleSubmit(request: CommunicationProtos.ServerRequest): CommunicationProtos.SubmitTaskResponse {
val id = getNextId()
thread {
println("Start calculation $id")
//register task, create lock
val monitor = Object()
synchronized(receivedTasks) {
println("Submit task blocked received task")
receivedTasks[id] = request
runningTasksLock[id] = monitor
}
println("Submit task released received task")
val handler = SubmitRequestHandler(id, { id -> waitAndGet(id) })
val taskResult = handler.handle(request.submit)
println("Got result for $id - $taskResult")
if (taskResult != null) {
println("Write result in completed task list")
completedTasks.put(id, taskResult)
}
runningTasksLock.remove(id)
synchronized(monitor, {
println("Submit task blocked monitor for $id task")
println("Notify all waiting for $id")
monitor.notifyAll()
})
println("Submit task released monitor for $id task")
println("$id calculation has finished")
}
return CommunicationProtos.SubmitTaskResponse.newBuilder()
.setSubmittedTaskId(id)
.setStatus(CommunicationProtos.Status.OK)
.build()
}
private fun handleSubscribe(_request: CommunicationProtos.ServerRequest): CommunicationProtos.SubscribeResponse {
val request = _request.subscribe
println("Get the monitor lock")
val result: Long = waitAndGet(request.taskId) ?: return buildSubscribeRequestError()
return CommunicationProtos.SubscribeResponse.newBuilder()
.setValue(result)
.setStatus(CommunicationProtos.Status.OK)
.build()
}
private fun buildSubscribeRequestError(): CommunicationProtos.SubscribeResponse {
return CommunicationProtos.SubscribeResponse.newBuilder()
.setStatus(CommunicationProtos.Status.ERROR)
.build()
}
private fun handleList(request: CommunicationProtos.ServerRequest): CommunicationProtos.ListTasksResponse {
//strange thing happened with handlers idea
val handler = ListRequestHandler(receivedTasks, completedTasks)
return handler.handle(request.list)
}
private fun getRequest(ism: InputStream): CommunicationProtos.ServerRequest? {
val wrappedMessage = CommunicationProtos.WrapperMessage.parseDelimitedFrom(ism)
if (!wrappedMessage.hasRequest()) {
return null
}
return wrappedMessage.request
}
private fun sendResponse(osm: OutputStream, response: CommunicationProtos.ServerResponse) {
val wm = CommunicationProtos.WrapperMessage.newBuilder()
.setResponse(response)
.build()
wm.writeDelimitedTo(osm)
}
private fun getNextId(): Int {
return lastId.incrementAndGet()
}
private fun waitAndGet(taskId: Int): Long? {
if (completedTasks.containsKey(taskId)) {
return completedTasks[taskId]
}
val monitor: Object = runningTasksLock[taskId] ?: return null
synchronized(monitor, {
println("Subscribe locked on $taskId monitor")
println("Subscribe starting to wait for $taskId")
while (!completedTasks.containsKey(taskId)) {
monitor.wait()
}
println("Subscribe awake to get $taskId result")
})
val result: Long = completedTasks[taskId] ?: return null
return result
}
}
| gpl-2.0 | 000fae2e7def6e38fba7b4d5704a6fd6 | 37.775641 | 117 | 0.651513 | 5.464318 | false | false | false | false |
duftler/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/ResumeStageHandlerTest.kt | 1 | 3206 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.ExecutionStatus.NOT_STARTED
import com.netflix.spinnaker.orca.ExecutionStatus.PAUSED
import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.ExecutionStatus.SUCCEEDED
import com.netflix.spinnaker.orca.fixture.pipeline
import com.netflix.spinnaker.orca.fixture.stage
import com.netflix.spinnaker.orca.fixture.task
import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.ResumeStage
import com.netflix.spinnaker.orca.q.ResumeTask
import com.netflix.spinnaker.q.Queue
import com.nhaarman.mockito_kotlin.check
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions
import com.nhaarman.mockito_kotlin.whenever
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP
import org.jetbrains.spek.subject.SubjectSpek
object ResumeStageHandlerTest : SubjectSpek<ResumeStageHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
subject(GROUP) {
ResumeStageHandler(queue, repository)
}
fun resetMocks() = reset(queue, repository)
describe("resuming a paused execution") {
val pipeline = pipeline {
application = "spinnaker"
status = RUNNING
stage {
refId = "1"
status = PAUSED
task {
id = "1"
status = SUCCEEDED
}
task {
id = "2"
status = PAUSED
}
task {
id = "3"
status = NOT_STARTED
}
}
}
val message = ResumeStage(pipeline.type, pipeline.id, pipeline.application, pipeline.stages.first().id)
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("sets the stage status to running") {
verify(repository).storeStage(check {
assertThat(it.id).isEqualTo(message.stageId)
assertThat(it.status).isEqualTo(RUNNING)
})
}
it("resumes all paused tasks") {
verify(queue).push(ResumeTask(message, "2"))
verifyNoMoreInteractions(queue)
}
}
})
| apache-2.0 | bbec0a9b8db86b4a807b3ada26062293 | 31.06 | 107 | 0.727074 | 4.174479 | false | false | false | false |
newbieandroid/AppBase | app/src/main/java/com/fuyoul/sanwenseller/helper/HttpDialogHelper.kt | 1 | 1626 | package com.fuyoul.sanwenseller.helper
import android.content.Context
import android.util.Log
import com.fuyoul.sanwenseller.R
import com.fuyoul.sanwenseller.widgets.WaitLoadingView
import com.fuyoul.sanwenseller.widgets.dialog.AbstractDialog
import com.fuyoul.sanwenseller.widgets.dialog.DialogViewHolder
/**
* @author: chen
* @CreatDate: 2017\10\24 0024
* @Desc: 网络请求显示的等待对话框
*/
object HttpDialogHelper {
private var dialog: AbstractDialog? = null
private var httpLoadingView: WaitLoadingView? = null
/**
* @param isShowDialog 是否显示等待对话框
* @param isCancleable 是否可以手动点击取消
*/
fun showDialog(context: Context, isShowDialog: Boolean, isCancleable: Boolean) {
if (!isShowDialog) {
return
}
if (dialog == null) {
dialog = object : AbstractDialog(context, R.layout.httploading) {
override fun convert(holder: DialogViewHolder?) {
httpLoadingView = holder?.getView(R.id.httpLoadingView)
httpLoadingView?.startAnimator()
}
}.setDialogDismissListener({
httpLoadingView?.stopAnimator()
}).setCancelAble(isCancleable).showDialog()
} else {
if (dialog?.isShow == false) {
dialog?.showDialog()
httpLoadingView?.startAnimator()
}
}
}
fun dismisss() {
if (dialog?.isShow == true) {
dialog?.dismiss()
}
dialog = null
httpLoadingView = null
}
} | apache-2.0 | 97fc8115c1dc504b79dc9d4a58845987 | 25.982759 | 84 | 0.609974 | 4.45584 | false | false | false | false |
cketti/k-9 | app/core/src/main/java/com/fsck/k9/job/MailSyncWorker.kt | 1 | 2424 | package com.fsck.k9.job
import android.content.ContentResolver
import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.fsck.k9.Account
import com.fsck.k9.K9
import com.fsck.k9.Preferences
import com.fsck.k9.controller.MessagingController
import com.fsck.k9.mail.AuthType
import timber.log.Timber
class MailSyncWorker(
private val messagingController: MessagingController,
private val preferences: Preferences,
context: Context,
parameters: WorkerParameters
) : Worker(context, parameters) {
override fun doWork(): Result {
val accountUuid = inputData.getString(EXTRA_ACCOUNT_UUID)
requireNotNull(accountUuid)
Timber.d("Executing periodic mail sync for account %s", accountUuid)
if (isBackgroundSyncDisabled()) {
Timber.d("Background sync is disabled. Skipping mail sync.")
return Result.success()
}
val account = preferences.getAccount(accountUuid)
if (account == null) {
Timber.e("Account %s not found. Can't perform mail sync.", accountUuid)
return Result.failure()
}
if (account.isPeriodicMailSyncDisabled) {
Timber.d("Periodic mail sync has been disabled for this account. Skipping mail sync.")
return Result.success()
}
if (account.incomingServerSettings.isMissingCredentials) {
Timber.d("Password for this account is missing. Skipping mail sync.")
return Result.success()
}
if (account.incomingServerSettings.authenticationType == AuthType.XOAUTH2 && account.oAuthState == null) {
Timber.d("Account requires sign-in. Skipping mail sync.")
return Result.success()
}
val success = messagingController.performPeriodicMailSync(account)
return if (success) Result.success() else Result.retry()
}
private fun isBackgroundSyncDisabled(): Boolean {
return when (K9.backgroundOps) {
K9.BACKGROUND_OPS.NEVER -> true
K9.BACKGROUND_OPS.ALWAYS -> false
K9.BACKGROUND_OPS.WHEN_CHECKED_AUTO_SYNC -> !ContentResolver.getMasterSyncAutomatically()
}
}
private val Account.isPeriodicMailSyncDisabled
get() = automaticCheckIntervalMinutes <= 0
companion object {
const val EXTRA_ACCOUNT_UUID = "accountUuid"
}
}
| apache-2.0 | a6ff09ef1b7825d398e1ecbd30655815 | 32.666667 | 114 | 0.676568 | 4.661538 | false | false | false | false |
rori-dev/lunchbox | backend-spring-kotlin/src/main/kotlin/lunchbox/domain/service/LunchOfferUpdateWorker.kt | 1 | 1393 | package lunchbox.domain.service
import lunchbox.domain.models.LunchOffer
import lunchbox.domain.models.LunchProvider
import lunchbox.domain.resolvers.LunchResolver
import lunchbox.repository.LunchOfferRepository
import mu.KotlinLogging
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Service
/**
* Aktualisiert die Mittagsangebote eines Anbieters.
* <p>
* Der Aufruf erfolgt asynchron.
*/
@Service
class LunchOfferUpdateWorker(
val repo: LunchOfferRepository,
val resolvers: List<LunchResolver>
) {
private val logger = KotlinLogging.logger {}
@Async
fun refreshOffersOf(provider: LunchProvider) {
val offers = resolve(provider)
val minDay = offers.map { it.day }.minOrNull()
?: return
repo.deleteFrom(minDay, provider.id)
repo.saveAll(offers)
}
private fun resolve(provider: LunchProvider): List<LunchOffer> {
val resolver = resolvers.find { it.provider == provider }
if (resolver == null) {
logger.error { "no resolver for $provider" }
return emptyList()
}
logger.info { "start resolving offers for $provider" }
return try {
val offers = resolver.resolve()
logger.info { "finished resolving offers for $provider" }
offers
} catch (e: Throwable) {
logger.error(e) { "failed resolving offers for $provider" }
emptyList()
}
}
}
| mit | ee3eb1e7f5ce0b044d28b57caab18312 | 25.283019 | 66 | 0.714286 | 3.968661 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/DeusCommand.kt | 1 | 1488 | package net.perfectdreams.loritta.morenitta.commands.vanilla.images
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.morenitta.api.commands.Command
import net.perfectdreams.loritta.morenitta.utils.extensions.readImage
import java.awt.image.BufferedImage
import java.io.File
class DeusCommand(loritta: LorittaBot) : AbstractCommand(loritta, "god", listOf("deus"), net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) {
override fun getDescriptionKey() = LocaleKeyData("commands.command.god.description")
override fun getExamplesKey() = Command.SINGLE_IMAGE_EXAMPLES_KEY
// TODO: Fix Usage
override fun needsToUploadFiles(): Boolean {
return true
}
override suspend fun run(context: CommandContext,locale: BaseLocale) {
val contextImage = context.getImageAt(0) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; }
val template = readImage(File(LorittaBot.ASSETS + "deus.png")) // Template
val scaled = contextImage.getScaledInstance(87, 87, BufferedImage.SCALE_SMOOTH)
template.graphics.drawImage(scaled, 1, 1, null)
context.sendFile(template, "deus.png", context.getAsMention(true))
}
} | agpl-3.0 | 1b6b9139c64b817f4bbb24a5b45896d9 | 44.121212 | 156 | 0.8125 | 4.087912 | false | false | false | false |
etesync/android | app/src/main/java/com/etesync/syncadapter/syncadapter/TasksSyncManager.kt | 1 | 5611 | /*
* Copyright © Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.syncadapter
import android.accounts.Account
import android.content.Context
import android.content.SyncResult
import android.os.Bundle
import at.bitfire.ical4android.Task
import com.etebase.client.Item
import com.etesync.syncadapter.AccountSettings
import com.etesync.syncadapter.Constants
import com.etesync.syncadapter.R
import com.etesync.journalmanager.JournalEntryManager
import com.etesync.syncadapter.log.Logger
import com.etesync.syncadapter.model.CollectionInfo
import com.etesync.journalmanager.model.SyncEntry
import com.etesync.syncadapter.resource.LocalTask
import com.etesync.syncadapter.resource.LocalTaskList
import okhttp3.HttpUrl
import java.io.StringReader
/**
* Synchronization manager for CalDAV collections; handles tasks (VTODO)
*/
class TasksSyncManager(
context: Context,
account: Account,
accountSettings: AccountSettings,
extras: Bundle,
authority: String,
syncResult: SyncResult,
taskList: LocalTaskList,
private val remote: HttpUrl
): SyncManager<LocalTask>(context, account, accountSettings, extras, authority, syncResult, taskList.url!!, CollectionInfo.Type.TASKS, account.name) {
override val syncErrorTitle: String
get() = context.getString(R.string.sync_error_tasks, account.name)
override val syncSuccessfullyTitle: String
get() = context.getString(R.string.sync_successfully_tasks, localTaskList().name!!,
account.name)
init {
localCollection = taskList
}
override fun notificationId(): Int {
return Constants.NOTIFICATION_TASK_SYNC
}
override fun prepare(): Boolean {
if (!super.prepare())
return false
if (isLegacy) {
journal = JournalEntryManager(httpClient.okHttpClient, remote, localTaskList().url!!)
}
return true
}
// helpers
private fun localTaskList(): LocalTaskList {
return localCollection as LocalTaskList
}
override fun processItem(item: Item) {
val local = localCollection!!.findByFilename(item.uid)
if (!item.isDeleted) {
val inputReader = StringReader(String(item.content))
val tasks = Task.tasksFromReader(inputReader)
if (tasks.size == 0) {
Logger.log.warning("Received VCard without data, ignoring")
return
} else if (tasks.size > 1) {
Logger.log.warning("Received multiple VCALs, using first one")
}
val task = tasks[0]
processTask(item, task, local)
} else {
if (local != null) {
Logger.log.info("Removing local record #" + local.id + " which has been deleted on the server")
local.delete()
} else {
Logger.log.warning("Tried deleting a non-existent record: " + item.uid)
}
}
}
override fun processSyncEntryImpl(cEntry: SyncEntry) {
val inputReader = StringReader(cEntry.content)
val tasks = Task.tasksFromReader(inputReader)
if (tasks.size == 0) {
Logger.log.warning("Received VCard without data, ignoring")
return
} else if (tasks.size > 1) {
Logger.log.warning("Received multiple VCALs, using first one")
}
val event = tasks[0]
val local = localCollection!!.findByUid(event.uid!!)
if (cEntry.isAction(SyncEntry.Actions.ADD) || cEntry.isAction(SyncEntry.Actions.CHANGE)) {
legacyProcessTask(event, local)
} else {
if (local != null) {
Logger.log.info("Removing local record #" + local.id + " which has been deleted on the server")
local.delete()
} else {
Logger.log.warning("Tried deleting a non-existent record: " + event.uid)
}
}
}
private fun processTask(item: Item, newData: Task, _localTask: LocalTask?): LocalTask {
var localTask = _localTask
// delete local Task, if it exists
if (localTask != null) {
Logger.log.info("Updating " + item.uid + " in local calendar")
localTask.eTag = item.etag
localTask.update(newData)
syncResult.stats.numUpdates++
} else {
Logger.log.info("Adding " + item.uid + " to local calendar")
localTask = LocalTask(localTaskList(), newData, item.uid, item.etag)
localTask.add()
syncResult.stats.numInserts++
}
return localTask
}
private fun legacyProcessTask(newData: Task, _localTask: LocalTask?): LocalTask {
var localTask = _localTask
// delete local Task, if it exists
if (localTask != null) {
Logger.log.info("Updating " + newData.uid + " in local calendar")
localTask.eTag = newData.uid
localTask.update(newData)
syncResult.stats.numUpdates++
} else {
Logger.log.info("Adding " + newData.uid + " to local calendar")
localTask = LocalTask(localTaskList(), newData, newData.uid, newData.uid)
localTask.add()
syncResult.stats.numInserts++
}
return localTask
}
} | gpl-3.0 | 1860d7b3b061600c3bd8f768eb04d1f2 | 33.850932 | 150 | 0.63066 | 4.583333 | false | false | false | false |
WonderBeat/dotablame | src/main/kotlin/org/wonderbeat/dota/api/http/SteamHttpParams.kt | 1 | 499 | package org.wonderbeat.dota.api.http
object SteamHttpParams {
val STEAM_SCHEMA = "https"
val STEAM_HOST = "api.steampowered.com"
val MATCH_API_PATH = "IDOTA2Match_570"
val GET_MATCH_HISTORY_PATH = "GetMatchHistory"
val GET_MATCH_DETAILS_PATH = "GetMatchDetails"
val STEAM_API_VERSION_PATH = "V001"
val START_MATCH_SEQ_PARAM = "start_at_match_seq_num"
val STEAM_ACCOUNT_ID_PARAM = "account_id"
val MATCH_ID_PARAM = "match_id"
val DEV_KEY_PARAM = "key"
}
| gpl-3.0 | c96abfd500c99ab76ebbd279bb95b97f | 25.263158 | 56 | 0.679359 | 2.901163 | false | false | false | false |
jitsi/jitsi-videobridge | rtp/src/main/kotlin/org/jitsi/rtp/rtcp/RtcpSdesPacket.kt | 1 | 7671 | /*
* Copyright @ 2018 - present 8x8, 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 org.jitsi.rtp.rtcp
import org.jitsi.rtp.extensions.bytearray.ByteArrayUtils
import org.jitsi.rtp.extensions.bytearray.toHex
import org.jitsi.rtp.util.BufferPool
import org.jitsi.rtp.util.RtpUtils
import org.jitsi.rtp.util.getByteAsInt
import org.jitsi.rtp.util.getIntAsLong
import java.nio.charset.StandardCharsets
/**
* https://tools.ietf.org/html/rfc3550#section-6.5
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* header |V=2|P| SC | PT=SDES=202 | length |
* +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
* chunk | SSRC/CSRC_1 |
* 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | SDES items |
* | ... |
* +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
* chunk | SSRC/CSRC_2 |
* 2 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | SDES items |
* | ... |
* +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
*
*
*/
class RtcpSdesPacket(
buffer: ByteArray,
offset: Int,
length: Int
) : RtcpPacket(buffer, offset, length) {
val sdesChunks: List<SdesChunk> by lazy {
getSdesChunks(buffer, offset, length)
}
override fun clone(): RtcpPacket = RtcpSdesPacket(cloneBuffer(0), 0, length)
companion object {
const val PT = 202
const val CHUNKS_OFFSET = 4
fun getSdesChunks(buf: ByteArray, baseOffset: Int, length: Int): List<SdesChunk> {
var currOffset = baseOffset + CHUNKS_OFFSET
val sdesChunks = mutableListOf<SdesChunk>()
while (currOffset < length) {
val sdesChunk = SdesChunk(buf, currOffset)
sdesChunks.add(sdesChunk)
currOffset += sdesChunk.sizeBytes
}
return sdesChunks
}
}
}
// Offset should point to the start of this sdes chunk
class SdesChunk(
buffer: ByteArray,
offset: Int
) {
val sizeBytes: Int by lazy {
val dataSize = 4 + sdesItems.map(SdesItem::sizeBytes).sum()
dataSize + RtpUtils.getNumPaddingBytes(dataSize)
}
val ssrc: Long by lazy { getSsrc(buffer, offset) }
val sdesItems: List<SdesItem> by lazy {
getSdesItems(buffer, offset)
}
companion object {
const val SSRC_OFFSET = 0
const val SDES_ITEMS_OFFSET = 4
fun getSsrc(buf: ByteArray, baseOffset: Int): Long =
buf.getIntAsLong(baseOffset + SSRC_OFFSET)
fun getSdesItems(buf: ByteArray, baseOffset: Int): List<SdesItem> {
var currOffset = baseOffset + SDES_ITEMS_OFFSET
val sdesItems = mutableListOf<SdesItem>()
while (true) {
val currItem = SdesItem.parse(buf, currOffset)
if (currItem == EmptySdesItem) {
break
}
sdesItems.add(currItem)
currOffset += currItem.sizeBytes
}
return sdesItems
}
}
}
enum class SdesItemType(val value: Int) {
EMPTY(0),
UNKNOWN(-1),
CNAME(1);
companion object {
private val map = SdesItemType.values().associateBy(SdesItemType::value)
fun fromInt(type: Int): SdesItemType = map.getOrDefault(type, UNKNOWN)
}
}
/**
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type | length | data ...
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* length = the length of the data field
*/
abstract class SdesItem(
val type: SdesItemType
) {
abstract val sizeBytes: Int
companion object {
const val SDES_ITEM_HEADER_SIZE = 2
const val TYPE_OFFSET = 0
const val LENGTH_OFFSET = 1
const val DATA_OFFSET = 2
fun getType(buf: ByteArray, baseOffset: Int): Int =
buf.getByteAsInt(baseOffset + TYPE_OFFSET)
fun getLength(buf: ByteArray, baseOffset: Int): Int =
buf.getByteAsInt(baseOffset + LENGTH_OFFSET)
fun copyData(buf: ByteArray, baseOffset: Int, dataLength: Int): ByteArray {
if (dataLength <= 0) {
return ByteArrayUtils.emptyByteArray
}
val copy = BufferPool.getArray(dataLength)
System.arraycopy(buf, baseOffset + DATA_OFFSET, copy, 0, dataLength)
return copy
}
/**
* [buf]'s current position should be at the beginning of
* the SDES item
*/
fun parse(buf: ByteArray, offset: Int): SdesItem {
val typeValue = getType(buf, offset)
val type = SdesItemType.fromInt(typeValue)
return when (type) {
SdesItemType.EMPTY -> EmptySdesItem
else -> {
val length = getLength(buf, offset)
return when (type) {
SdesItemType.CNAME -> CnameSdesItem(buf, offset, length)
else -> UnknownSdesItem(typeValue, buf, offset, length)
}
}
}
}
}
}
class UnknownSdesItem(
private val sdesTypeValue: Int,
buf: ByteArray,
offset: Int,
length: Int
) : SdesItem(SdesItemType.UNKNOWN) {
private val dataField = copyData(buf, offset, length)
override val sizeBytes: Int = SDES_ITEM_HEADER_SIZE + dataField.size
override fun toString(): String {
return "Unknown SDES type($sdesTypeValue) data = ${dataField.toHex()}"
}
}
object EmptySdesItem : SdesItem(SdesItemType.EMPTY) {
override val sizeBytes: Int = 1
}
/**
* https://tools.ietf.org/html/rfc3550#section-6.5.1
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | CNAME=1 | length | user and domain name ...
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
class CnameSdesItem(buf: ByteArray, offset: Int, length: Int) : SdesItem(SdesItemType.CNAME) {
private val dataField: ByteArray = copyData(buf, offset, length)
override val sizeBytes: Int = SDES_ITEM_HEADER_SIZE + dataField.size
val cname: String by lazy {
String(dataField, StandardCharsets.US_ASCII)
}
override fun toString(): String = "CNAME: $cname"
}
| apache-2.0 | b656f7a9529cf46fc6361a09e6958afa | 34.35023 | 94 | 0.503585 | 4.086841 | false | false | false | false |
wireapp/wire-android | storage/src/main/kotlin/com/waz/zclient/storage/db/clients/model/ClientEntity.kt | 1 | 1093 | package com.waz.zclient.storage.db.clients.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "client")
data class ClientEntity(
@ColumnInfo(name = "id")
@PrimaryKey
val id: String,
@ColumnInfo(name = "time", defaultValue = "")
val time: String,
@ColumnInfo(name = "label", defaultValue = "")
val label: String,
@ColumnInfo(name = "type", defaultValue = "")
val type: String,
@ColumnInfo(name = "class", defaultValue = "")
val clazz: String,
@ColumnInfo(name = "model", defaultValue = "")
val model: String,
@ColumnInfo(name = "lat", defaultValue = "0")
val lat: Double,
@ColumnInfo(name = "lon", defaultValue = "0")
val lon: Double,
@ColumnInfo(name = "locationName")
val locationName: String?,
@ColumnInfo(name = "verification", defaultValue = "")
val verification: String,
@ColumnInfo(name = "encKey", defaultValue = "")
val encKey: String,
@ColumnInfo(name = "macKey", defaultValue = "")
val macKey: String
)
| gpl-3.0 | 48bd06d11beca47ffacf4b9526b9945f | 23.288889 | 57 | 0.645014 | 3.974545 | false | false | false | false |
spark/photon-tinker-android | mesh/src/main/java/io/particle/mesh/bluetooth/BTCharacteristicWriter.kt | 1 | 4306 | package io.particle.mesh.bluetooth
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic
import android.os.Handler
import android.os.HandlerThread
import androidx.annotation.WorkerThread
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import io.particle.mesh.common.QATool
import io.particle.mesh.common.android.SimpleLifecycleOwner
import mu.KotlinLogging
import java.util.concurrent.ConcurrentLinkedQueue
// FIXME: the right way to get notified of successful packet writes is via a Channel!
@Volatile
private var HANDLER_THREAD_ID = 1
// FIXME: think more carefully about these numbers. What should they be?
private const val DELAY_BETWEEN_SENDS_MILLIS = 50
private const val WRITE_ATTEMPTS_BEFORE_CLOSING_CONNECTION = 10
class BTCharacteristicWriter(
private val gatt: BluetoothGatt,
private val writeCharacteristic: BluetoothGattCharacteristic,
private val onCharacteristicWrittenLD: LiveData<GATTStatusCode>
) {
private val log = KotlinLogging.logger {}
private val packetQueue = ConcurrentLinkedQueue<ByteArray>()
private val lifecycleOwner = SimpleLifecycleOwner()
private val handlerThread = HandlerThread("BLE_WRITE_HANDLER_" + HANDLER_THREAD_ID++)
private val workerThreadHandler: Handler
@Volatile
private var writeAttempts: Int = 0
@Volatile
private var active = true
@Volatile
private var dequeScheduled: Boolean = false
init {
handlerThread.start()
workerThreadHandler = Handler(handlerThread.looper)
lifecycleOwner.setNewState(Lifecycle.State.RESUMED)
onCharacteristicWrittenLD.observe(lifecycleOwner, Observer {
onCharacteristicWritten()
})
}
fun deactivate() {
active = false
lifecycleOwner.setNewState(Lifecycle.State.DESTROYED)
onCharacteristicWrittenLD.removeObservers(lifecycleOwner)
packetQueue.clear()
handlerThread.quitSafely()
}
fun writeToCharacteristic(value: ByteArray) {
if (!active) {
QATool.illegalState("Asked to accept command data on deactivated write channel")
return
}
packetQueue.add(value)
scheduleDeque()
}
private fun onCharacteristicWritten() {
workerThreadHandler.post { this.deque() }
}
@Synchronized
private fun scheduleDeque() {
workerThreadHandler.post { this.doScheduleDeque() }
}
@Synchronized
private fun doScheduleDeque() {
if (dequeScheduled) {
return
}
dequeScheduled = true
workerThreadHandler.postDelayed({
this.deque()
}, DELAY_BETWEEN_SENDS_MILLIS.toLong())
}
@WorkerThread
private fun deque() {
dequeScheduled = false
if (!active) {
QATool.log("Running deque op on inactive write channel!")
return
}
// retrieve the head from the queue WITHOUT removing it
val packet = packetQueue.peek() ?: return
val errMsg = writePacket(packet)
if (errMsg == null) { // success
writeAttempts = 0
packetQueue.poll() // like .remove() but doesn't throw if the queue is empty
} else {
writeAttempts++
if (writeAttempts > WRITE_ATTEMPTS_BEFORE_CLOSING_CONNECTION) {
log.error { "Exceeded maximum write attempts; invalidating connection!" }
return
}
val msg = "Error writing packet: $errMsg, writeAttempts=$writeAttempts"
if (writeAttempts > 3) {
log.warn { msg }
} else {
log.trace { msg }
}
scheduleDeque()
}
// the "onCharacteristicWritten()" call will prompt us to write the next packet...
}
private fun writePacket(packet: ByteArray): String? {
val valueSet = writeCharacteristic.setValue(packet)
if (!valueSet) {
return "Unable to set value on write characteristic"
}
val writeInitiated = gatt.writeCharacteristic(writeCharacteristic)
return if (writeInitiated) null else "Unable to write characteristic to BLE GATT"
}
} | apache-2.0 | 9880aa77cc5237b18882364240bdc139 | 28.703448 | 92 | 0.662332 | 4.949425 | false | false | false | false |
robinverduijn/gradle | subprojects/instant-execution/src/main/kotlin/org/gradle/instantexecution/InstantExecutionReport.kt | 1 | 7852 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.instantexecution
import groovy.json.JsonOutput
import org.gradle.api.logging.Logger
import org.gradle.instantexecution.serialization.PropertyKind
import org.gradle.instantexecution.serialization.PropertyProblem
import org.gradle.instantexecution.serialization.PropertyTrace
import org.gradle.instantexecution.serialization.unknownPropertyError
import org.gradle.internal.logging.ConsoleRenderer
import org.gradle.util.GFileUtils.copyURLToFile
import java.io.File
import java.io.PrintWriter
import java.io.StringWriter
import java.net.URL
class InstantExecutionReport(
private
val outputDirectory: File,
private
val logger: Logger,
private
val maxProblems: Int
) {
private
val problems = mutableListOf<PropertyProblem>()
fun add(problem: PropertyProblem) {
problems.add(problem)
if (problems.size > maxProblems) {
throw TooManyInstantExecutionProblemsException()
}
}
fun withExceptionHandling(block: () -> Unit): Throwable? {
val fatalError = runWithExceptionHandling(block)
if (problems.isEmpty()) {
require(fatalError == null)
return null
}
logSummary()
writeReportFiles()
return fatalError?.withSuppressed(errors())
?: instantExecutionExceptionForErrors()
}
private
fun runWithExceptionHandling(block: () -> Unit): Throwable? {
try {
block()
} catch (e: Throwable) {
when (e.cause ?: e) {
is TooManyInstantExecutionProblemsException -> return e
is StackOverflowError -> add(e)
is Error -> throw e
else -> add(e)
}
}
return null
}
private
fun add(e: Throwable) {
problems.add(
unknownPropertyError(e.message ?: e.javaClass.name, e)
)
}
private
fun instantExecutionExceptionForErrors(): Throwable? =
errors()
.takeIf { it.isNotEmpty() }
?.let { errors -> InstantExecutionErrorsException().withSuppressed(errors) }
private
fun Throwable.withSuppressed(errors: List<PropertyProblem.Error>) = apply {
errors.forEach {
addSuppressed(it.exception)
}
}
private
fun errors() =
problems.filterIsInstance<PropertyProblem.Error>()
private
fun logSummary() {
logger.lifecycle(summary())
}
private
fun writeReportFiles() {
outputDirectory.mkdirs()
copyReportResources()
writeJsReportData()
}
private
fun summary(): String {
val uniquePropertyProblems = problems.groupBy {
propertyDescriptionFor(it) to it.message
}
return StringBuilder().apply {
appendln("${uniquePropertyProblems.size} instant execution problems found:")
uniquePropertyProblems.keys.forEach { (property, message) ->
append(" - ")
append(property)
append(": ")
appendln(message)
}
appendln("See the complete report at ${clickableUrlFor(reportFile)}")
}.toString()
}
private
fun copyReportResources() {
listOf(
reportFile.name,
"instant-execution-report.js",
"instant-execution-report.css",
"kotlin.js"
).forEach { resourceName ->
copyURLToFile(
getResource(resourceName),
outputDirectory.resolve(resourceName)
)
}
}
private
fun writeJsReportData() {
outputDirectory.resolve("instant-execution-report-data.js").bufferedWriter().use { writer ->
writer.run {
appendln("function instantExecutionProblems() { return [")
problems.forEach {
append(
JsonOutput.toJson(
mapOf(
"trace" to traceListOf(it),
"message" to it.message.fragments,
"error" to stackTraceStringOf(it)
)
)
)
appendln(",")
}
appendln("];}")
}
}
}
private
fun stackTraceStringOf(problem: PropertyProblem): String? =
(problem as? PropertyProblem.Error)?.exception?.let {
stackTraceStringFor(it)
}
private
fun stackTraceStringFor(error: Throwable): String =
StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString()
private
fun traceListOf(problem: PropertyProblem): List<Map<String, Any>> =
problem.trace.sequence.map(::traceToMap).toList()
private
fun traceToMap(trace: PropertyTrace): Map<String, Any> = when (trace) {
is PropertyTrace.Property -> {
when (trace.kind) {
PropertyKind.Field -> mapOf(
"kind" to trace.kind.name,
"name" to trace.name,
"declaringType" to firstTypeFrom(trace.trace).name
)
else -> mapOf(
"kind" to trace.kind.name,
"name" to trace.name,
"task" to taskPathFrom(trace.trace)
)
}
}
is PropertyTrace.Task -> mapOf(
"kind" to "Task",
"path" to trace.path,
"type" to trace.type.name
)
is PropertyTrace.Bean -> mapOf(
"kind" to "Bean",
"type" to trace.type.name
)
PropertyTrace.Gradle -> mapOf(
"kind" to "Gradle"
)
PropertyTrace.Unknown -> mapOf(
"kind" to "Unknown"
)
}
private
fun propertyDescriptionFor(problem: PropertyProblem): String = problem.trace.run {
when (this) {
is PropertyTrace.Property -> simplePropertyDescription()
else -> toString()
}
}
private
fun getResource(path: String): URL = javaClass.getResource(path).also {
require(it != null) { "Resource `$path` could not be found!" }
}
private
fun PropertyTrace.Property.simplePropertyDescription(): String = when (kind) {
PropertyKind.Field -> "field '$name' from type '${firstTypeFrom(trace).name}'"
else -> "$kind '$name' of '${taskPathFrom(trace)}'"
}
private
fun taskPathFrom(trace: PropertyTrace): String =
trace.sequence.filterIsInstance<PropertyTrace.Task>().first().path
private
fun firstTypeFrom(trace: PropertyTrace): Class<*> =
trace.sequence.mapNotNull { typeFrom(it) }.first()
private
fun typeFrom(trace: PropertyTrace): Class<out Any>? = when (trace) {
is PropertyTrace.Bean -> trace.type
is PropertyTrace.Task -> trace.type
else -> null
}
private
val reportFile
get() = outputDirectory.resolve("instant-execution-report.html")
}
private
fun clickableUrlFor(file: File) = ConsoleRenderer().asClickableFileUrl(file)
| apache-2.0 | 415f98aeff49f9c7d8b8726180e20976 | 28.189591 | 100 | 0.583291 | 4.901373 | false | false | false | false |
square/leakcanary | leakcanary-android-instrumentation/src/androidTest/java/leakcanary/TestUtils.kt | 2 | 1320 | package leakcanary
import shark.HeapAnalysis
import shark.HeapAnalysisSuccess
object TestUtils {
fun assertLeak(expectedLeakClass: Class<*>) {
val heapAnalysis = detectLeaks()
val applicationLeaks = heapAnalysis.applicationLeaks
if (applicationLeaks.size != 1) {
throw AssertionError(
"Expected exactly one leak in $heapAnalysis"
)
}
val leak = applicationLeaks.first()
val leakTrace = leak.leakTraces.first()
val className = leakTrace.leakingObject.className
if (className != expectedLeakClass.name) {
throw AssertionError(
"Expected a leak of $expectedLeakClass, not $className in $heapAnalysis"
)
}
}
fun detectLeaks(): HeapAnalysisSuccess {
var heapAnalysisOrNull: HeapAnalysis? = null
AndroidDetectLeaksAssert { heapAnalysis ->
heapAnalysisOrNull = heapAnalysis
}.assertNoLeaks("")
if (heapAnalysisOrNull == null) {
throw AssertionError(
"Expected analysis to be performed but skipped"
)
}
val heapAnalysis = heapAnalysisOrNull
if (heapAnalysis !is HeapAnalysisSuccess) {
throw AssertionError(
"Expected analysis success not $heapAnalysis"
)
}
// Save disk space on emulator
heapAnalysis.heapDumpFile.delete()
return heapAnalysis
}
}
| apache-2.0 | bbe99460c1903d0470e15eed5fabdde9 | 25.938776 | 80 | 0.688636 | 4.731183 | false | false | false | false |
fython/PackageTracker | mobile/src/main/kotlin/info/papdt/express/helper/services/ReminderService.kt | 1 | 4924 | package info.papdt.express.helper.services
import android.app.IntentService
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.IBinder
import androidx.core.app.NotificationCompat
import android.util.Log
import info.papdt.express.helper.*
import info.papdt.express.helper.R
import java.text.ParseException
import java.text.SimpleDateFormat
import info.papdt.express.helper.dao.PackageDatabase
import info.papdt.express.helper.model.Kuaidi100Package
import info.papdt.express.helper.support.PushUtils
import info.papdt.express.helper.support.Settings
import info.papdt.express.helper.support.SettingsInstance
import info.papdt.express.helper.ui.HomeActivity
import info.papdt.express.helper.ui.launcher.AppWidgetProvider
import moe.feng.kotlinyan.common.*
import java.util.*
class ReminderService : IntentService(TAG) {
override fun onBind(intent: Intent): IBinder? {
return null
}
public override fun onHandleIntent(intent: Intent) {
val isEnabledDontDisturbMode = Settings.getInstance(applicationContext)
.getBoolean(Settings.KEY_NOTIFICATION_DO_NOT_DISTURB, true)
if (isEnabledDontDisturbMode && PushUtils.isDisturbTime(Calendar.getInstance())) {
Log.i(TAG, "现在是勿扰时间段,跳过检查。")
return
}
Log.i(TAG, "开始检查快递包裹")
val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val db = PackageDatabase.getInstance(applicationContext)
db.pullDataFromNetwork(SettingsInstance.forceUpdateAllPackages)
db.save()
AppWidgetProvider.updateManually(application)
for (i in 0 until db.size()) {
val p = db[i]
if (p.getState() != Kuaidi100Package.STATUS_FAILED && p.shouldPush) {
Log.i(TAG, "包裹 $i 需要产生通知")
val n = produceNotifications(this, i, p)
nm.notify(i + 20000, n)
p.shouldPush = false
}
}
db.save()
}
companion object {
private val TAG = ReminderService::class.java.simpleName
private val ID = 100000
private fun parseDefaults(context: Context): Int {
val settings = Settings.getInstance(context)
return (if (settings.getBoolean(Settings.KEY_NOTIFICATION_SOUND, true)) Notification.DEFAULT_SOUND else 0) or
(if (settings.getBoolean(Settings.KEY_NOTIFICATION_VIBRATE, true)) Notification.DEFAULT_VIBRATE else 0) or
Notification.DEFAULT_LIGHTS
}
private fun buildNotification(context: Context, title: String, subject: String, longText: String, time: Long, icon: Int, color: Int,
defaults: Int, contentIntent: PendingIntent, deleteIntent: PendingIntent?): Notification {
val n: Notification
val builder = NotificationCompat.Builder(context, CHANNEL_ID_PACKAGE_STATUS)
builder.setContentTitle(title)
builder.setContentText(subject)
builder.priority = NotificationCompat.PRIORITY_MAX
builder.setStyle(NotificationCompat.BigTextStyle(builder).bigText(longText))
builder.setDefaults(defaults)
builder.setSmallIcon(icon)
builder.setContentIntent(contentIntent)
if (time > 0) builder.setWhen(time)
builder.setAutoCancel(true)
builder.color = color
n = builder.build()
return n
}
fun produceNotifications(context: Context, position: Int, exp: Kuaidi100Package?): Notification? {
if (exp != null) {
val defaults = parseDefaults(context.applicationContext)
val pi = PendingIntent.getActivity(
context.applicationContext,
position,
Intent(context, HomeActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
action = ACTION_REQUEST_OPEN_DETAILS
this[EXTRA_DATA] = exp
},
PendingIntent.FLAG_UPDATE_CURRENT)
val title = exp.name
val subject: String = when (exp.getState()) {
Kuaidi100Package.STATUS_DELIVERED -> R.string.notification_delivered
Kuaidi100Package.STATUS_ON_THE_WAY -> R.string.notification_on_the_way
else -> R.string.notification_new_message
}.run(context::getString)
val smallIcon = when (exp.getState()) {
Kuaidi100Package.STATUS_DELIVERED -> R.drawable.ic_done_white_24dp
Kuaidi100Package.STATUS_ON_THE_WAY -> R.drawable.ic_local_shipping_white_24dp
else -> R.drawable.ic_assignment_returned_white_24dp
}
val myDate = exp.data!![0].time
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
var millis: Long = 0
try {
val date = sdf.parse(myDate)
millis = date.time
} catch (e: ParseException) {
e.printStackTrace()
}
val n = buildNotification(context.applicationContext,
title!!,
subject,
exp.data!![0].context!!,
millis,
smallIcon,
context.resources.getIntArray(R.array.statusColor)[exp.getState()],
defaults,
pi, null)
n.tickerText = title
return n
}
return null
}
}
}
| gpl-3.0 | db4085ea226b092be3e978bc111e00ae | 30.79085 | 134 | 0.73088 | 3.635277 | false | false | false | false |
google/horologist | paparazzi/src/main/java/com/google/android/horologist/paparazzi/a11y/A11ySnapshotHandler.kt | 1 | 8381 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.paparazzi.a11y
import app.cash.paparazzi.Snapshot
import app.cash.paparazzi.SnapshotHandler
import com.google.android.horologist.paparazzi.ExperimentalHorologistPaparazziApi
import java.awt.AlphaComposite
import java.awt.BasicStroke
import java.awt.Color
import java.awt.Composite
import java.awt.Graphics2D
import java.awt.image.BufferedImage
import kotlin.math.max
/**
* A Paparazzi SnapshotHandler that renders the snapshot, with a light coloured overlay,
* and adjacent to a legend with matching colours.
*/
@ExperimentalHorologistPaparazziApi
public class A11ySnapshotHandler(
private val delegate: SnapshotHandler,
private val accessibilityStateFn: () -> AccessibilityState,
private val overlayRenderer: (AccessibilityState, BufferedImage) -> BufferedImage =
{ accessibilityState, image ->
drawBoxes(accessibilityState, image)
},
private val legendRenderer: (AccessibilityState, BufferedImage) -> BufferedImage =
{ accessibilityState, image ->
drawLegend(accessibilityState, image)
}
) : SnapshotHandler {
override fun close() {
delegate.close()
}
override fun newFrameHandler(
snapshot: Snapshot,
frameCount: Int,
fps: Int
): SnapshotHandler.FrameHandler {
val delegateFrameHandler = delegate.newFrameHandler(snapshot, frameCount, fps)
return object : SnapshotHandler.FrameHandler {
override fun close() {
delegateFrameHandler.close()
}
override fun handle(image: BufferedImage) {
val accessibilityState = accessibilityStateFn()
val overlay = overlayRenderer(accessibilityState, image)
val legend = legendRenderer(accessibilityState, image)
val modifiedImage = concatImages(overlay, legend, image)
delegateFrameHandler.handle(modifiedImage)
}
}
}
public companion object {
private val colors =
listOf(
Color.BLUE,
Color.CYAN,
Color.GREEN,
Color.GRAY,
Color.PINK,
Color.MAGENTA,
Color.YELLOW,
Color.ORANGE
)
private fun concatImages(
overlay: BufferedImage,
legend: BufferedImage,
image: BufferedImage
): BufferedImage {
val modifiedImage =
BufferedImage(
overlay.width + legend.width,
max(overlay.height, legend.height),
image.type
)
modifiedImage.withGraphics2D {
drawImage(overlay, 0, 0, overlay.width, overlay.height, null)
drawImage(legend, overlay.width, 0, legend.width, legend.height, null)
}
return modifiedImage
}
private fun Graphics2D.withComposite(newComposite: Composite, fn: () -> Unit = {}) {
val current = composite
composite = newComposite
fn()
composite = current
}
private fun BufferedImage.withGraphics2D(fn: Graphics2D.() -> Unit = {}): BufferedImage {
createGraphics().apply {
try {
fn()
} finally {
dispose()
}
}
return this
}
internal fun drawBoxes(
accessibilityState: AccessibilityState,
image: BufferedImage
): BufferedImage {
val modifiedImage = BufferedImage(image.width, image.height, image.type)
val scale = 1000f / max(accessibilityState.height, accessibilityState.width)
return modifiedImage.withGraphics2D {
withComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f)) {
drawImage(image, 0, 0, image.width, image.height, null)
}
accessibilityState.elements.forEachIndexed { i, it ->
paint = colorForIndex(i)
stroke = BasicStroke(3f)
val element = it.scaleBy(scale)
drawRect(
element.displayBounds.left,
element.displayBounds.top,
element.displayBounds.width(),
element.displayBounds.height()
)
paint = Color(color.red, color.green, color.blue, 255 / 4)
fillRect(
element.displayBounds.left,
element.displayBounds.top,
element.displayBounds.width(),
element.displayBounds.height()
)
if (element.touchBounds != null) {
drawRect(
element.touchBounds.left,
element.touchBounds.top,
element.touchBounds.width(),
element.touchBounds.height()
)
}
}
}
}
internal fun drawLegend(
accessibilityState: AccessibilityState,
image: BufferedImage
): BufferedImage {
val modifiedImage = BufferedImage(600, image.height, image.type)
return modifiedImage.withGraphics2D {
paint = Color.WHITE
fillRect(0, 0, modifiedImage.width, modifiedImage.height)
font = font.deriveFont(20f)
stroke = BasicStroke(3f)
var index = 1
fun drawItem(s: String) {
drawString(s, 50f, 28f * index++)
}
accessibilityState.elements.forEachIndexed { i, it ->
paint = Color.BLACK
val start = index
if (it.role != null || it.disabled || it.heading) {
val role = if (it.role != null) "Role " + it.role + " " else ""
val heading = if (it.heading) "Heading " else ""
val disabled = if (it.disabled) "Disabled" else ""
drawItem(role + heading + disabled)
}
if (it.contentDescription != null) {
drawItem("Content Description \"${it.contentDescription.joinToString(", ")}\"")
} else if (it.text != null) {
drawItem("Text \"${it.text.joinToString(", ")}\"")
}
if (it.stateDescription != null) {
drawItem("State Description \"${it.stateDescription}\"")
}
if (it.onClickLabel != null) {
drawItem("On Click \"${it.onClickLabel}\"")
}
if (it.progress != null) {
drawItem("Progress \"${it.progress}\"")
}
if (it.customActions != null) {
it.customActions.forEach {
drawItem("Custom Action \"${it.label}\"")
}
}
val end = index
paint = colorForIndex(i)
drawRect(10, start * 28 - 21, modifiedImage.width - 20, (end - start) * 28)
index++
}
}
}
private fun colorForIndex(i: Int): Color {
return colors[i % colors.size]
}
}
}
| apache-2.0 | c1d7dc9c389fbcf376a06ddcf909ac8e | 34.969957 | 103 | 0.525594 | 5.358696 | false | false | false | false |
xfournet/intellij-community | java/java-analysis-api/src/com/intellij/lang/jvm/actions/methodRequests.kt | 3 | 2015 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.jvm.actions
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.types.JvmSubstitutor
import com.intellij.lang.jvm.types.JvmType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Pair
import com.intellij.psi.PsiJvmSubstitutor
import com.intellij.psi.PsiSubstitutor
import com.intellij.psi.PsiType
private class SimpleMethodRequest(
override val methodName: String,
override val modifiers: Collection<JvmModifier> = emptyList(),
override val returnType: ExpectedTypes = emptyList(),
override val annotations: Collection<AnnotationRequest> = emptyList(),
override val parameters: List<ExpectedParameter> = emptyList(),
override val targetSubstitutor: JvmSubstitutor
) : CreateMethodRequest {
override val isValid: Boolean = true
}
private class SimpleConstructorRequest(
override val parameters: ExpectedParameters,
override val targetSubstitutor: JvmSubstitutor
) : CreateConstructorRequest {
override val isValid: Boolean get() = true
override val modifiers: List<JvmModifier> get() = emptyList()
override val annotations: Collection<AnnotationRequest> = emptyList()
}
fun methodRequest(project: Project, methodName: String, modifier: JvmModifier, returnType: JvmType): CreateMethodRequest {
return SimpleMethodRequest(
methodName = methodName,
modifiers = listOf(modifier),
returnType = listOf(expectedType(returnType)),
targetSubstitutor = PsiJvmSubstitutor(project, PsiSubstitutor.EMPTY)
)
}
fun constructorRequest(project: Project, parameters: List<Pair<String, PsiType>>): CreateConstructorRequest {
val expectedParameters = parameters.map {
nameInfo(it.first) to expectedTypes(it.second)
}
return SimpleConstructorRequest(
parameters = expectedParameters,
targetSubstitutor = PsiJvmSubstitutor(project, PsiSubstitutor.EMPTY)
)
}
| apache-2.0 | 96675ea9533917a255bbec022129cfc5 | 39.3 | 140 | 0.792556 | 4.664352 | false | false | false | false |
jaydeepw/android-boilerplate | app/src/main/java/com/github/jaydeepw/boilerplate/views/adapters/Adapter.kt | 1 | 1845 | package com.github.jaydeepw.boilerplate.views.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.github.jaydeepw.boilerplate.R
import com.github.jaydeepw.boilerplate.contracts.MainContractInterface
import com.github.jaydeepw.pokemondirectory.models.dataclasses.Pokemon
import kotlinx.android.synthetic.main.list_item.view.*
class Adapter(val items : ArrayList<Pokemon>?, val context: Context
,var presenter: MainContractInterface.Presenter) : RecyclerView.Adapter<ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val viewHoldder = ViewHolder(LayoutInflater.from(context).inflate(R.layout.list_item, parent, false),
presenter)
return viewHoldder
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val pokemon = items?.get(position)
holder.itemView.tag = pokemon
holder.pokemonTitle.text = pokemon?.name?.capitalize()
}
// Gets the number of animals in the list
override fun getItemCount(): Int {
return items?.size!!
}
fun updateAll(newItems: List<Pokemon>) {
items?.clear()
items?.addAll(newItems)
notifyDataSetChanged()
}
}
/**
* Holds the TextView that will add each animal to
*/
class ViewHolder
(view: View, private var presenter: MainContractInterface.Presenter) : RecyclerView.ViewHolder(view), View.OnClickListener {
var pokemonTitle : TextView
init {
itemView.setOnClickListener(this)
pokemonTitle = view.textview_pokemon
}
override fun onClick(v: View?) {
presenter.onItemClick(itemView.tag as Pokemon)
}
} | mit | fb6116a630e2d1b8cc77ef060276c542 | 31.385965 | 128 | 0.723035 | 4.566832 | false | false | false | false |
icarumbas/bagel | core/src/ru/icarumbas/bagel/engine/systems/other/OpeningSystem.kt | 1 | 2153 | package ru.icarumbas.bagel.engine.systems.other
import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.core.Family
import com.badlogic.ashley.systems.IteratingSystem
import ru.icarumbas.bagel.engine.components.other.DoorComponent
import ru.icarumbas.bagel.engine.components.other.OpenComponent
import ru.icarumbas.bagel.engine.controller.UIController
import ru.icarumbas.bagel.engine.entities.EntityState
import ru.icarumbas.bagel.engine.entities.factories.EntityFactory
import ru.icarumbas.bagel.engine.world.RoomWorld
import ru.icarumbas.bagel.utils.*
class OpeningSystem (
private val uiController: UIController,
private val rm: RoomWorld,
private val entityFactory: EntityFactory,
private val playerEntity: Entity
): IteratingSystem(Family.all(OpenComponent::class.java).get()){
private fun isChestOpened(e: Entity): Boolean{
with (animation[e].animations[EntityState.OPENING]!!) {
return getKeyFrame(state[e].stateTime) == keyFrames.get(keyFrames.size - 2) && !door.has(e)
}
}
override fun processEntity(e: Entity, deltaTime: Float) {
if (e.inView(rm)) {
if (open[e].isCollidingWithPlayer){
if (uiController.isOpenPressed()) {
open[e].opening = true
}
}
if (state[e].currentState == EntityState.OPENING) {
if (animation[e].animations[EntityState.OPENING]!!.isAnimationFinished(state[e].stateTime)) {
if (door.has(e)) {
rm.currentMapId = roomId[engine.getEntitiesFor(Family.all(DoorComponent::class.java).get()).random()].id
}
}
if (isChestOpened(e)) {
engine.addEntity(entityFactory.lootEntity(
0,
body[e].body.position.x to body[e].body.position.y + .5f,
roomId[e].id,
playerEntity
))
state[e].stateTime -= deltaTime
}
}
}
}
} | apache-2.0 | 9bb646fe2986fc8b25981054e442b2fb | 36.137931 | 128 | 0.599164 | 4.402863 | false | false | false | false |
mustafa01ali/Dev-Tiles | app/src/main/kotlin/xyz/mustafaali/devqstiles/MainActivity.kt | 1 | 4218 | package xyz.mustafaali.devqstiles
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.view.Menu
import android.view.MenuItem
import com.google.android.gms.oss.licenses.OssLicensesMenuActivity
import kotlinx.android.synthetic.main.activity_main.*
import timber.log.Timber
import xyz.mustafaali.devqstiles.model.Feature
import xyz.mustafaali.devqstiles.ui.FeaturesAdapter
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initUi()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_help -> {
openHelpVideo()
true
}
R.id.menu_share_app -> {
shareApp()
true
}
R.id.menu_rate_app -> {
openStoreListing()
true
}
R.id.menu_request_feature -> {
openEmailClient()
true
}
R.id.menu_oss_licenses -> {
startActivity(Intent(this, OssLicensesMenuActivity::class.java))
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun openStoreListing() {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse("market://details?id=xyz.mustafaali.devqstiles")
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
Timber.e("Couldn't launch activity, maybe PlayStore is not installed")
}
}
private fun openHelpVideo() {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/watch?v=tdSAobQq1nQ")))
}
private fun openEmailClient() {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "message/rfc822"
intent.putExtra(android.content.Intent.EXTRA_EMAIL, arrayOf("[email protected]"))
intent.putExtra(Intent.EXTRA_SUBJECT, "[DevTiles] Feature Request")
startActivity(intent)
}
private fun initUi() {
copyButton.setOnClickListener({ sharePermissionsCommand() })
featuresRecyclerView.layoutManager = LinearLayoutManager(this)
featuresRecyclerView.setHasFixedSize(true)
featuresRecyclerView.adapter = FeaturesAdapter(getFeaturesList()) {}
}
private fun shareApp() {
share(R.string.msg_share_app)
}
private fun sharePermissionsCommand() {
share(R.string.permission_command)
}
private fun share(resId: Int) {
val sendIntent = Intent()
sendIntent.action = Intent.ACTION_SEND
sendIntent.putExtra(Intent.EXTRA_TEXT, getString(resId))
sendIntent.type = "text/plain"
startActivity(sendIntent)
}
private fun getFeaturesList(): List<Feature> {
return listOf(
Feature("Toggle USB Debugging", "Enable/disable USB debugging from your notification drawer", R.drawable.ic_toggle_usb_debugging),
Feature("Keep Screen On", "Keep screen on when connected via USB, but turn it off when connected to a charger", R.drawable.ic_toggle_keep_screen_on),
Feature("Show Touches", "Show touch points when you touch the screen, ideal for demos", R.drawable.ic_toggle_show_taps),
Feature("Demo Mode", "Cleans up the status bar for those perfect screenshots", R.drawable.ic_toggle_demo_mode),
Feature("Change Animator Duration", "Change the default animator duration to easily debug animations", R.drawable.ic_animator_duration),
Feature("Toggle Animation Scale", "Enable/disable all animations with one click, perfect for running Espresso tests", R.drawable.ic_animation)
)
}
}
| apache-2.0 | 41bd6e4800783358acf38832fac8c1b2 | 37 | 165 | 0.649834 | 4.51123 | false | false | false | false |
wuseal/JsonToKotlinClass | src/test/kotlin/extensions/ted/zeng/PropertyAnnotationLineSupportTest.kt | 1 | 1562 | package extensions.ted.zeng
import com.winterbe.expekt.should
import org.junit.Before
import org.junit.Test
import wu.seal.jsontokotlin.KotlinCodeMaker
import wu.seal.jsontokotlin.generateKotlinDataClass
import wu.seal.jsontokotlin.interceptor.annotations.fastjson.AddFastJsonAnnotationInterceptor
import wu.seal.jsontokotlin.test.TestConfig
/**
* Created by ted on 2019-06-13 18:21.
*/
class PropertyAnnotationLineSupportTest {
private val json = """{"a":"a","Int":2}"""
private val expectResult = """data class Test(
@JSONField(name = "a") val a: String, // a
@JSONField(name = "Int") val int: Int // 2
)"""
@Before
fun setUp() {
TestConfig.setToTestInitState()
}
@Test
fun interceptTest() {
val kotlinDataClass = json.generateKotlinDataClass()
PropertyAnnotationLineSupport.getTestHelper().setConfig("ted.zeng.property_annotation_in_same_line_enable", "true")
val result = kotlinDataClass.applyInterceptors(listOf(AddFastJsonAnnotationInterceptor(), PropertyAnnotationLineSupport)).getCode()
result.should.equal(expectResult)
}
@Test
fun finalClassCodeTest() {
val expectResult = """data class Test(
@SerializedName("a") val a: String = "", // a
@SerializedName("Int") val int: Int = 0 // 2
)"""
PropertyAnnotationLineSupport.getTestHelper().setConfig("ted.zeng.property_annotation_in_same_line_enable", "true")
val resultCode = KotlinCodeMaker("Test", json).makeKotlinData()
resultCode.should.be.equal(expectResult)
}
} | gpl-3.0 | b50073d73953bb8977d58532ca3b48b2 | 34.522727 | 139 | 0.708067 | 4.046632 | false | true | false | false |
letroll/githubbookmarkmanager | app/src/main/kotlin/fr/letroll/githubbookmarkmanager/flow/activity/MainActivity.kt | 1 | 1695 | package fr.letroll.githubbookmarkmanager.flow.activity
import android.os.Bundle
import android.widget.Button
import fr.letroll.githubbookmarkmanager.R
import fr.letroll.githubbookmarkmanager.api.GithubApi
import fr.letroll.kotlinandroidlib.findView
import rx.functions.Action1
/**
* Created by jquievreux on 26/11/14.
*/
open class MainActivity : BaseActivity() {
override val contentViewId: Int = R.layout.activity_login
override fun onCreate(savedInstanceState: Bundle?) {
super<BaseActivity>.onCreate(savedInstanceState)
setContentView(contentViewId);
val githubApi = GithubApi()
val service = githubApi.getService()
// val login = findView<AutoCompleteTextView>(R.id.email)
// val pass = findView<EditText>(R.id.password)
val email_sign_in_button = findView<Button>(R.id.email_sign_in_button)
email_sign_in_button.setOnClickListener({
// val tmp = arrayOf("repo"):Array<String>
//githubApi.getService().getAuthorizations(tmp, "toto", "http://test.com", "f562e3df7d57256f3884","6e90eafd7e6088af4f58170ef5118c64ea05ff50", cal)
//githubService.getAuthorizations(cal)
//githubApi.getService().listStarred("letroll", calR)
service.getAuthorizations().subscribe(
object : Action1<String> {
override fun call(t: String?) {
toast(t)
}
}, object : Action1<Throwable> {
override fun call(t: Throwable?) {
toast(t?.getMessage())
}
})
})
}
} | apache-2.0 | 0bda0f01784ce0c9468c394778e35a1d | 33.612245 | 158 | 0.614749 | 4.195545 | false | false | false | false |
rei-m/android_hyakuninisshu | state/src/main/java/me/rei_m/hyakuninisshu/state/exam/store/ExamFinisherStore.kt | 1 | 1820 | /*
* Copyright (c) 2020. Rei Matsushita
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package me.rei_m.hyakuninisshu.state.exam.store
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import me.rei_m.hyakuninisshu.state.core.Dispatcher
import me.rei_m.hyakuninisshu.state.core.Event
import me.rei_m.hyakuninisshu.state.core.Store
import me.rei_m.hyakuninisshu.state.exam.action.FinishExamAction
import javax.inject.Inject
/**
* 力試しの完了状態を管理する.
*/
class ExamFinisherStore @Inject constructor(dispatcher: Dispatcher) : Store() {
/**
* 力試しの完了を通知するイベント.
*/
private val _onFinishEvent = MutableLiveData<Event<Long>>()
val onFinishEvent: LiveData<Event<Long>> = _onFinishEvent
private val _isFailure = MutableLiveData(false)
val isFailure: LiveData<Boolean> = _isFailure
init {
register(dispatcher.on(FinishExamAction::class.java).subscribe {
when (it) {
is FinishExamAction.Success -> {
_onFinishEvent.value = Event(it.examResult.id)
_isFailure.value = false
}
is FinishExamAction.Failure -> {
_isFailure.value = true
}
}
})
}
}
| apache-2.0 | bf500460104fd0dad3c43ab069528569 | 33.588235 | 112 | 0.680839 | 4.121495 | false | false | false | false |
msebire/intellij-community | plugins/devkit/devkit-java-tests/testSrc/org/jetbrains/idea/devkit/inspections/missingApi/project/PluginProjectWithIdeaLibraryDescriptor.kt | 1 | 3240 | // 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 org.jetbrains.idea.devkit.inspections.missingApi.project
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleType
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ContentEntry
import com.intellij.openapi.roots.LanguageLevelModuleExtension
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.pom.java.LanguageLevel
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.idea.devkit.module.PluginModuleType
import java.io.File
/**
* Descriptor of an IDEA plugin project with configured IDEA library (not JDK).
*/
class PluginProjectWithIdeaLibraryDescriptor : LightProjectDescriptor() {
companion object {
private const val IDEA_LIBRARY_NAME = "IDEA library"
fun disposeIdeaLibrary(project: Project) {
val libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project)
val library = runReadAction {
libraryTable.getLibraryByName(IDEA_LIBRARY_NAME)
} ?: return
runWriteAction {
libraryTable.removeLibrary(library)
}
}
}
override fun getModuleType(): ModuleType<*> = PluginModuleType.getInstance()
override fun configureModule(module: Module, model: ModifiableRootModel, contentEntry: ContentEntry) {
super.configureModule(module, model, contentEntry)
val moduleExtension = model.getModuleExtension(LanguageLevelModuleExtension::class.java)
moduleExtension.languageLevel = LanguageLevel.HIGHEST
val library = createIdeaLibrary(module)
model.addLibraryEntry(library)
}
private fun createIdeaLibrary(module: Module): Library {
val libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(module.project)
val library = runWriteAction {
libraryTable.createLibrary(IDEA_LIBRARY_NAME)
}
runWriteAction {
val modifiableModel = library.modifiableModel
modifiableModel.addIdeaJarContainingClassToClassPath(Editor::class.java)
modifiableModel.addIdeaJarContainingClassToClassPath(BaseState::class.java)
modifiableModel.commit()
}
return library
}
override fun getSdk(): Sdk = IdeaTestUtil.getMockJdk18()
private fun Library.ModifiableModel.addIdeaJarContainingClassToClassPath(clazz: Class<*>) {
val jarFile = File(FileUtil.toSystemIndependentName(PathManager.getJarPathForClass(clazz)!!))
val virtualFile = VfsUtil.findFileByIoFile(jarFile, true)
addRoot(virtualFile!!, OrderRootType.CLASSES)
}
} | apache-2.0 | 0255cc290653189b8528d915608a0baa | 37.583333 | 140 | 0.796296 | 4.886878 | false | false | false | false |
square/duktape-android | zipline-gradle-plugin/src/test/kotlin/app/cash/zipline/gradle/ZiplineCompilerTest.kt | 1 | 7600 | /*
* Copyright (C) 2021 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.zipline.gradle
import app.cash.zipline.QuickJs
import app.cash.zipline.internal.DEFINE_JS
import app.cash.zipline.internal.loadJsModule
import app.cash.zipline.loader.CURRENT_ZIPLINE_VERSION
import app.cash.zipline.loader.ZiplineFile
import app.cash.zipline.loader.ZiplineManifest
import com.google.common.truth.Truth.assertThat
import java.io.File
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import okio.buffer
import okio.source
import org.junit.After
import org.junit.Before
import org.junit.Test
class ZiplineCompilerTest {
private val quickJs = QuickJs.create()
@Before
fun setUp() {
// Configure QuickJS to support module loading.
quickJs.evaluate(DEFINE_JS)
}
@After
fun after() {
quickJs.close()
}
@Test
fun `write to and read from zipline`() {
val moduleNameToFile = compile("src/test/resources/happyPath/", true)
for ((moduleName, ziplineFile) in moduleNameToFile) {
quickJs.loadJsModule(moduleName, ziplineFile.quickjsBytecode.toByteArray())
}
val exception = assertFailsWith<Exception> {
quickJs.evaluate("require('./hello.js').sayHello()", "test.js")
}
// .kt files in the stacktrace means that the sourcemap was applied correctly.
assertThat(exception.stackTraceToString()).startsWith(
"""
|app.cash.zipline.QuickJsException: boom!
| at JavaScript.goBoom1(throwException.kt)
| at JavaScript.goBoom2(throwException.kt:9)
| at JavaScript.goBoom3(throwException.kt:6)
| at JavaScript.sayHello(throwException.kt:3)
| at JavaScript.<eval>(test.js)
|""".trimMargin()
)
}
@Test
fun `no source map`() {
val moduleNameToFile = compile("src/test/resources/happyPathNoSourceMap/", false)
for ((_, ziplineFile) in moduleNameToFile) {
quickJs.execute(ziplineFile.quickjsBytecode.toByteArray())
}
assertEquals("Hello, guy!", quickJs.evaluate("greet('guy')", "test.js"))
}
@Test
fun `js with imports and exports`() {
val moduleNameToFile = compile("src/test/resources/jsWithImportsExports/", false)
for ((name, ziplineFile) in moduleNameToFile) {
quickJs.loadJsModule(name, ziplineFile.quickjsBytecode.toByteArray())
}
}
@Test
fun `incremental compile`() {
val rootProject = "src/test/resources/incremental"
val outputDir = File("$rootProject/base/build/zipline")
// Clean up dir from previous runs
if (outputDir.exists()) {
outputDir.deleteRecursively()
}
// Start with base compile to generate manifest and starting files
compile("$rootProject/base", false)
val moduleNameToFile = assertZiplineIncrementalCompile("$rootProject/base",
addedFiles = File("$rootProject/added").listFiles()!!.asList(),
modifiedFiles = File("$rootProject/modified").listFiles()!!.asList(),
removedFiles = File("$rootProject/removed").listFiles()!!.asList()
)
for ((_, ziplineFile) in moduleNameToFile) {
quickJs.execute(ziplineFile.quickjsBytecode.toByteArray())
}
// Jello file was removed
assertFalse(File("$outputDir/jello.zipline").exists())
// Bello file was added
quickJs.execute(readZiplineFile(File("$outputDir/bello.zipline")).quickjsBytecode.toByteArray())
assertEquals("Bello!", quickJs.evaluate("bello()", "test.js"))
// Hello file was replaced with bonjour
quickJs.execute(readZiplineFile(File("$outputDir/hello.zipline")).quickjsBytecode.toByteArray())
assertEquals("Bonjour, guy!", quickJs.evaluate("greet('guy')", "test.js"))
// Yello file remains untouched
quickJs.execute(readZiplineFile(File("$outputDir/yello.zipline")).quickjsBytecode.toByteArray())
assertEquals("HELLO", quickJs.evaluate("greet()", "test.js"))
}
private fun readZiplineFile(file: File): ZiplineFile {
val result = file.source().buffer().use { source ->
ZiplineFile.read(source)
}
assertEquals(CURRENT_ZIPLINE_VERSION, result.ziplineVersion)
return result
}
private fun compile(
rootProject: String,
dirHasSourceMaps: Boolean,
): Map<String, ZiplineFile> {
val inputDir = File("$rootProject/jsBuild")
val outputDir = File("$rootProject/build/zipline")
outputDir.mkdirs()
val mainModuleId = "./app.js"
val mainFunction = "zipline.ziplineMain"
ZiplineCompiler.compile(
inputDir = inputDir,
outputDir = outputDir,
mainFunction = mainFunction,
mainModuleId = mainModuleId,
manifestSigner = null,
version = null,
)
val expectedNumberFiles = if (dirHasSourceMaps) inputDir.listFiles()!!.size / 2 else inputDir.listFiles()!!.size
// Don't include Zipline manifest
val actualNumberFiles = (outputDir.listFiles()?.size ?: 0) - 1
assertEquals(expectedNumberFiles, actualNumberFiles)
return getCompileResult(outputDir, mainModuleId, mainFunction)
}
private fun assertZiplineIncrementalCompile(
rootProject: String,
modifiedFiles: List<File>,
addedFiles: List<File>,
removedFiles: List<File>,
): Map<String, ZiplineFile> {
val inputDir = File("$rootProject/jsBuild")
val outputDir = File("$rootProject/build/zipline")
outputDir.mkdirs()
val mainModuleId = "./app.js"
val mainFunction = "zipline.ziplineMain"
ZiplineCompiler.incrementalCompile(
outputDir = outputDir,
mainFunction = mainFunction,
mainModuleId = mainModuleId,
modifiedFiles = modifiedFiles,
addedFiles = addedFiles,
removedFiles = removedFiles,
manifestSigner = null,
version = null,
)
val expectedNumberFiles = inputDir.listFiles()!!.size + addedFiles.size - removedFiles.size
// Don't include Zipline manifest
val actualNumberFiles = (outputDir.listFiles()?.size ?: 0) - 1
assertEquals(expectedNumberFiles, actualNumberFiles)
return getCompileResult(outputDir, mainModuleId, mainFunction)
}
private fun getCompileResult(
outputDir: File,
mainModuleId: String,
mainFunction: String,
): Map<String, ZiplineFile> {
// Load and parse manifest
val manifestFile = File(outputDir, "manifest.zipline.json")
val manifestString = manifestFile.readText()
val manifest = Json.decodeFromString<ZiplineManifest>(manifestString)
// Confirm that mainModuleId and mainFunction have been added to the manifest
assertEquals(mainModuleId, manifest.mainModuleId)
assertEquals(mainFunction, manifest.mainFunction)
// Confirm that all manifest files are present in outputDir
outputDir.listFiles()!!.forEach { ziplineFile ->
manifest.modules.keys.contains(ziplineFile.path)
}
// Iterate over files by Manifest order
val result = mutableMapOf<String, ZiplineFile>()
for ((key, module) in manifest.modules) {
result[key] = readZiplineFile(File(outputDir, module.url))
}
return result
}
}
| apache-2.0 | 1f4b39bb966a097e177ee1824540cc04 | 33.703196 | 116 | 0.711842 | 4.231626 | false | true | false | false |
Aidanvii7/Toolbox | delegates-observable/src/main/java/com/aidanvii/toolbox/delegates/observable/MapDecorator.kt | 1 | 1809 | package com.aidanvii.toolbox.delegates.observable
import kotlin.reflect.KProperty
/**
* Returns an [ObservableProperty] that will transform the type [TT1] to [TT2] via the given [transform] function.
* @param transform a transformational function to apply to each item emitted by the receiver [ObservableProperty].
* @param ST the base type of the source observable ([ObservableProperty.Source]).
* @param TT1 the type on which the receiver [ObservableProperty] operates.
* @param TT2 the transformed type on which the resulting [ObservableProperty] operates (as dictacted be the [transform] function).
*/
infix fun <ST, TT1, TT2> ObservableProperty<ST, TT1>.map(
transform: (TT1) -> TT2
) = MapDecorator(this, transform)
class MapDecorator<ST, TT1, TT2>(
private val decorated: ObservableProperty<ST, TT1>,
private val transform: (TT1) -> TT2
) : ObservableProperty<ST, TT2> {
init {
decorated.afterChangeObservers += { property, oldValue, newValue ->
afterChangeObservers.forEach {
it(property, oldValue?.let { transform(it) }, transform(newValue))
}
}
}
override fun getValue(thisRef: Any?, property: KProperty<*>): ST =
decorated.getValue(thisRef, property)
override fun setValue(thisRef: Any?, property: KProperty<*>, value: ST) {
decorated.setValue(thisRef, property, value)
}
override val sourceValue: ST get() = decorated.sourceValue
override val source: ObservableProperty.Source<ST> get() = decorated.source
override val afterChangeObservers = mutableSetOf<AfterChange<TT2>>()
operator fun provideDelegate(thisRef: Any?, property: KProperty<*>): MapDecorator<ST, TT1, TT2> {
onProvideDelegate(thisRef, property)
return this
}
} | apache-2.0 | fed1b229c604293bdd944d08678ffac3 | 38.347826 | 131 | 0.695965 | 4.40146 | false | false | false | false |
rock3r/detekt | detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/RuleProviderTest.kt | 1 | 4111 | package io.gitlab.arturbosch.detekt.rules
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.MultiRule
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.RuleSetProvider
import io.gitlab.arturbosch.detekt.api.internal.BaseRule
import io.gitlab.arturbosch.detekt.api.internal.DefaultRuleSetProvider
import io.gitlab.arturbosch.detekt.core.rules.createRuleSet
import io.gitlab.arturbosch.detekt.rules.providers.CommentSmellProvider
import io.gitlab.arturbosch.detekt.rules.providers.ComplexityProvider
import io.gitlab.arturbosch.detekt.rules.providers.CoroutinesProvider
import io.gitlab.arturbosch.detekt.rules.providers.EmptyCodeProvider
import io.gitlab.arturbosch.detekt.rules.providers.ExceptionsProvider
import io.gitlab.arturbosch.detekt.rules.providers.NamingProvider
import io.gitlab.arturbosch.detekt.rules.providers.PerformanceProvider
import io.gitlab.arturbosch.detekt.rules.providers.PotentialBugProvider
import io.gitlab.arturbosch.detekt.rules.providers.StyleGuideProvider
import org.assertj.core.api.Assertions.assertThat
import org.reflections.Reflections
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.lang.reflect.Modifier
class RuleProviderTest : Spek({
describe("Rule Provider") {
it("checks whether all rules are called in the corresponding RuleSetProvider") {
val reflections = Reflections("io.gitlab.arturbosch.detekt.rules.providers")
val providers = reflections.getSubTypesOf(DefaultRuleSetProvider::class.java)
providers.forEach { providerType ->
val packageName = getRulesPackageNameForProvider(providerType)
val provider = providerType.getDeclaredConstructor().newInstance()
val rules = getRules(provider)
val classes = getClasses(packageName)
classes.forEach { clazz ->
val rule = rules.singleOrNull { it.javaClass.simpleName == clazz.simpleName }
assertThat(rule).withFailMessage(
"Rule $clazz is not called in the corresponding RuleSetProvider $providerType"
).isNotNull()
}
}
}
}
})
private val ruleMap = mapOf<Class<*>, String>(
CommentSmellProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.documentation",
ComplexityProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.complexity",
EmptyCodeProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.empty",
ExceptionsProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.exceptions",
NamingProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.naming",
PerformanceProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.performance",
PotentialBugProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.bugs",
StyleGuideProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.style",
CoroutinesProvider().javaClass to "io.gitlab.arturbosch.detekt.rules.coroutines"
)
private fun getRulesPackageNameForProvider(providerType: Class<out RuleSetProvider>): String {
val packageName = ruleMap[providerType]
assertThat(packageName)
.withFailMessage("No rules package for provider of type $providerType was defined in the ruleMap")
.isNotNull()
@Suppress("UnsafeCallOnNullableType")
return packageName!!
}
private fun getRules(provider: RuleSetProvider): List<BaseRule> {
@Suppress("UnsafeCallOnNullableType")
val ruleSet = provider.createRuleSet(Config.empty)
val rules = ruleSet.rules.flatMap { (it as? MultiRule)?.rules ?: listOf(it) }
assertThat(rules).isNotEmpty
return rules
}
private fun getClasses(packageName: String): List<Class<out Rule>> {
val classes = Reflections(packageName)
.getSubTypesOf(Rule::class.java)
.filterNot { "Test" in it.name }
.filter { !Modifier.isAbstract(it.modifiers) && !Modifier.isStatic(it.modifiers) }
assertThat(classes).isNotEmpty
return classes
}
| apache-2.0 | 8e5a8ead4212690a7d775b7d123d3929 | 47.940476 | 106 | 0.749209 | 4.562708 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/data/LocalDataHolder.kt | 1 | 3439 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.data
import org.lanternpowered.api.util.collections.immutableSetBuilderOf
import org.lanternpowered.api.util.uncheckedCast
import org.spongepowered.api.data.DataHolder
import org.spongepowered.api.data.Key
import org.spongepowered.api.data.value.Value
import java.util.Optional
interface LocalDataHolder : DataHolderBase {
/**
* Gets the [LocalKeyRegistry].
*
* @return The key registry
*/
val keyRegistry: LocalKeyRegistry<out DataHolder>
/**
* A convenient extension that applies changes as the caller type.
*/
@JvmDefault
fun <H : LocalDataHolder> H.keyRegistry(fn: LocalKeyRegistry<H>.() -> Unit): LocalKeyRegistry<H> {
return this.keyRegistry.forHolderUnchecked<H>().apply(fn)
}
@JvmDefault
override fun supports(key: Key<*>): Boolean = this.supportsKey(key.uncheckedCast<Key<Value<Any>>>())
/**
* Gets whether the [Key] is supported by this [LocalDataHolder].
*/
@JvmDefault
private fun <V : Value<E>, E : Any> supportsKey(key: Key<V>): Boolean {
val localRegistration = this.keyRegistry[key]
if (localRegistration != null)
return localRegistration.anyDataProvider().isSupported(this)
for (delegate in this.keyRegistry.delegates) {
if (delegate.supports(key))
return true
}
return super.supports(key)
}
@JvmDefault
override fun <E : Any, V : Value<E>> getValue(key: Key<V>): Optional<V> {
val localRegistration = this.keyRegistry[key]
if (localRegistration != null)
return localRegistration.dataProvider<V, E>().getValue(this)
for (delegate in this.keyRegistry.delegates) {
val result = delegate.getValue(key)
if (result.isPresent)
return result
}
return super.getValue(key)
}
@JvmDefault
override fun <E : Any> get(key: Key<out Value<E>>): Optional<E> {
val localRegistration = this.keyRegistry[key]
if (localRegistration != null)
return localRegistration.dataProvider<Value<E>, E>().get(this)
for (delegate in this.keyRegistry.delegates) {
val result = delegate.get(key)
if (result.isPresent)
return result
}
return super.get(key)
}
@JvmDefault
override fun getKeys(): Set<Key<*>> {
val keys = immutableSetBuilderOf<Key<*>>()
keys.addAll(this.keyRegistry.keys)
keys.addAll(super.getKeys())
for (delegate in this.keyRegistry.delegates)
keys.addAll(delegate.keys)
return keys.build()
}
@JvmDefault
override fun getValues(): Set<Value.Immutable<*>> {
val values = immutableSetBuilderOf<Value.Immutable<*>>()
values.addAll(super.getValues())
for (registration in this.keyRegistry.registrations) {
registration.anyDataProvider().getValue(this)
.ifPresent { value -> values.add(value.asImmutable()) }
}
return values.build()
}
}
| mit | 12cf5dd6a91af07faf75fd865a04131b | 30.550459 | 104 | 0.637395 | 4.245679 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/service/api/v2alpha/RequisitionsService.kt | 1 | 22159 | // Copyright 2020 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.service.api.v2alpha
import io.grpc.Status
import io.grpc.StatusException
import kotlin.math.min
import kotlinx.coroutines.flow.toList
import org.wfanet.measurement.api.Version
import org.wfanet.measurement.api.v2.alpha.ListRequisitionsPageToken
import org.wfanet.measurement.api.v2.alpha.ListRequisitionsPageTokenKt.previousPageEnd
import org.wfanet.measurement.api.v2.alpha.copy
import org.wfanet.measurement.api.v2.alpha.listRequisitionsPageToken
import org.wfanet.measurement.api.v2alpha.DataProviderCertificateKey
import org.wfanet.measurement.api.v2alpha.DataProviderKey
import org.wfanet.measurement.api.v2alpha.DataProviderPrincipal
import org.wfanet.measurement.api.v2alpha.FulfillDirectRequisitionRequest
import org.wfanet.measurement.api.v2alpha.FulfillDirectRequisitionResponse
import org.wfanet.measurement.api.v2alpha.ListRequisitionsRequest
import org.wfanet.measurement.api.v2alpha.ListRequisitionsResponse
import org.wfanet.measurement.api.v2alpha.MeasurementConsumerCertificateKey
import org.wfanet.measurement.api.v2alpha.MeasurementConsumerPrincipal
import org.wfanet.measurement.api.v2alpha.MeasurementKey
import org.wfanet.measurement.api.v2alpha.MeasurementPrincipal
import org.wfanet.measurement.api.v2alpha.MeasurementSpec
import org.wfanet.measurement.api.v2alpha.RefuseRequisitionRequest
import org.wfanet.measurement.api.v2alpha.Requisition
import org.wfanet.measurement.api.v2alpha.Requisition.DuchyEntry
import org.wfanet.measurement.api.v2alpha.Requisition.Refusal
import org.wfanet.measurement.api.v2alpha.Requisition.State
import org.wfanet.measurement.api.v2alpha.RequisitionKey
import org.wfanet.measurement.api.v2alpha.RequisitionKt.DuchyEntryKt.liquidLegionsV2
import org.wfanet.measurement.api.v2alpha.RequisitionKt.DuchyEntryKt.value
import org.wfanet.measurement.api.v2alpha.RequisitionKt.duchyEntry
import org.wfanet.measurement.api.v2alpha.RequisitionKt.refusal
import org.wfanet.measurement.api.v2alpha.RequisitionsGrpcKt.RequisitionsCoroutineImplBase
import org.wfanet.measurement.api.v2alpha.fulfillDirectRequisitionResponse
import org.wfanet.measurement.api.v2alpha.getProviderFromContext
import org.wfanet.measurement.api.v2alpha.listRequisitionsResponse
import org.wfanet.measurement.api.v2alpha.principalFromCurrentContext
import org.wfanet.measurement.api.v2alpha.requisition
import org.wfanet.measurement.api.v2alpha.signedData
import org.wfanet.measurement.common.base64UrlDecode
import org.wfanet.measurement.common.base64UrlEncode
import org.wfanet.measurement.common.grpc.failGrpc
import org.wfanet.measurement.common.grpc.grpcRequire
import org.wfanet.measurement.common.grpc.grpcRequireNotNull
import org.wfanet.measurement.common.identity.apiIdToExternalId
import org.wfanet.measurement.common.identity.externalIdToApiId
import org.wfanet.measurement.internal.common.Provider
import org.wfanet.measurement.internal.kingdom.FulfillRequisitionRequestKt.directRequisitionParams
import org.wfanet.measurement.internal.kingdom.Requisition as InternalRequisition
import org.wfanet.measurement.internal.kingdom.Requisition.DuchyValue
import org.wfanet.measurement.internal.kingdom.Requisition.Refusal as InternalRefusal
import org.wfanet.measurement.internal.kingdom.Requisition.State as InternalState
import org.wfanet.measurement.internal.kingdom.RequisitionKt as InternalRequisitionKt
import org.wfanet.measurement.internal.kingdom.RequisitionsGrpcKt.RequisitionsCoroutineStub
import org.wfanet.measurement.internal.kingdom.StreamRequisitionsRequest
import org.wfanet.measurement.internal.kingdom.StreamRequisitionsRequestKt
import org.wfanet.measurement.internal.kingdom.copy
import org.wfanet.measurement.internal.kingdom.fulfillRequisitionRequest
import org.wfanet.measurement.internal.kingdom.refuseRequisitionRequest
import org.wfanet.measurement.internal.kingdom.streamRequisitionsRequest
private const val MIN_PAGE_SIZE = 1
private const val DEFAULT_PAGE_SIZE = 50
private const val MAX_PAGE_SIZE = 100
private const val WILDCARD = "-"
class RequisitionsService(
private val allowMpcProtocolsForSingleDataProvider: Boolean,
private val internalRequisitionStub: RequisitionsCoroutineStub,
private val callIdentityProvider: () -> Provider = ::getProviderFromContext,
) : RequisitionsCoroutineImplBase() {
override suspend fun listRequisitions(
request: ListRequisitionsRequest
): ListRequisitionsResponse {
val principal: MeasurementPrincipal = principalFromCurrentContext
val listRequisitionsPageToken = request.toListRequisitionsPageToken()
var externalMeasurementConsumerId = 0L
when (principal) {
is DataProviderPrincipal -> {
if (
apiIdToExternalId(principal.resourceKey.dataProviderId) !=
listRequisitionsPageToken.externalDataProviderId
) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot list Requisitions belonging to other DataProviders"
}
}
}
is MeasurementConsumerPrincipal -> {
externalMeasurementConsumerId =
apiIdToExternalId(principal.resourceKey.measurementConsumerId)
if (
listRequisitionsPageToken.externalMeasurementConsumerId != 0L &&
listRequisitionsPageToken.externalMeasurementConsumerId != externalMeasurementConsumerId
) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot list Requisitions belonging to other MeasurementConsumers"
}
}
}
else -> {
failGrpc(Status.PERMISSION_DENIED) {
"Caller does not have permission to list Requisitions"
}
}
}
val streamRequest =
listRequisitionsPageToken.toStreamRequisitionsRequest().copy {
filter =
filter.copy {
// Filters for the caller's ID if the caller is an MC.
if (this.externalMeasurementConsumerId == 0L) {
this.externalMeasurementConsumerId = externalMeasurementConsumerId
}
// If no state filter set in public request, include all visible states.
if (states.isEmpty()) {
states += InternalState.UNFULFILLED
states += InternalState.FULFILLED
states += InternalState.REFUSED
}
}
}
val results: List<InternalRequisition> =
try {
internalRequisitionStub.streamRequisitions(streamRequest).toList()
} catch (ex: StatusException) {
throw when (ex.status.code) {
Status.Code.INVALID_ARGUMENT ->
Status.INVALID_ARGUMENT.withDescription("Required field unspecified or invalid")
Status.Code.DEADLINE_EXCEEDED -> Status.DEADLINE_EXCEEDED
else -> Status.UNKNOWN
}
.withCause(ex)
.asRuntimeException()
}
if (results.isEmpty()) {
return ListRequisitionsResponse.getDefaultInstance()
}
return listRequisitionsResponse {
requisitions +=
results.subList(0, min(results.size, listRequisitionsPageToken.pageSize)).map {
internalRequisition ->
internalRequisition.toRequisition(allowMpcProtocolsForSingleDataProvider)
}
if (results.size > listRequisitionsPageToken.pageSize) {
val pageToken =
listRequisitionsPageToken.copy {
lastRequisition = previousPageEnd {
externalDataProviderId = results[results.lastIndex - 1].externalDataProviderId
externalRequisitionId = results[results.lastIndex - 1].externalRequisitionId
}
}
nextPageToken = pageToken.toByteArray().base64UrlEncode()
}
}
}
override suspend fun refuseRequisition(request: RefuseRequisitionRequest): Requisition {
val key: RequisitionKey =
grpcRequireNotNull(RequisitionKey.fromName(request.name)) {
"Resource name unspecified or invalid"
}
when (val principal: MeasurementPrincipal = principalFromCurrentContext) {
is DataProviderPrincipal -> {
if (principal.resourceKey.dataProviderId != key.dataProviderId) {
failGrpc(Status.PERMISSION_DENIED) {
"Cannot refuse Requisitions belonging to other DataProviders"
}
}
}
else -> {
failGrpc(Status.PERMISSION_DENIED) {
"Caller does not have permission to refuse Requisitions"
}
}
}
grpcRequire(request.refusal.justification != Refusal.Justification.JUSTIFICATION_UNSPECIFIED) {
"Refusal details must be present"
}
val refuseRequest = refuseRequisitionRequest {
externalDataProviderId = apiIdToExternalId(key.dataProviderId)
externalRequisitionId = apiIdToExternalId(key.requisitionId)
refusal =
InternalRequisitionKt.refusal {
justification = request.refusal.justification.toInternal()
message = request.refusal.message
}
}
val result =
try {
internalRequisitionStub.refuseRequisition(refuseRequest)
} catch (ex: StatusException) {
when (ex.status.code) {
Status.Code.INVALID_ARGUMENT ->
failGrpc(Status.INVALID_ARGUMENT, ex) { "Required field unspecified or invalid." }
Status.Code.NOT_FOUND -> failGrpc(Status.NOT_FOUND, ex) { "Requisition not found." }
Status.Code.FAILED_PRECONDITION ->
failGrpc(Status.FAILED_PRECONDITION, ex) { "Requisition or Measurement state illegal." }
Status.Code.DEADLINE_EXCEEDED -> throw ex.status.withCause(ex).asRuntimeException()
else -> failGrpc(Status.UNKNOWN, ex) { "Unknown exception." }
}
}
return result.toRequisition(allowMpcProtocolsForSingleDataProvider)
}
override suspend fun fulfillDirectRequisition(
request: FulfillDirectRequisitionRequest
): FulfillDirectRequisitionResponse {
val key =
grpcRequireNotNull(RequisitionKey.fromName(request.name)) {
"Resource name unspecified or invalid."
}
grpcRequire(request.nonce != 0L) { "nonce unspecified" }
grpcRequire(!request.encryptedData.isEmpty) { "encrypted_data must be provided" }
// Ensure that the caller is the data_provider who owns this requisition.
val caller = callIdentityProvider()
if (
caller.type != Provider.Type.DATA_PROVIDER ||
externalIdToApiId(caller.externalId) != key.dataProviderId
) {
failGrpc(Status.PERMISSION_DENIED) {
"The data_provider id doesn't match the caller's identity."
}
}
val fulfillRequest = fulfillRequisitionRequest {
externalRequisitionId = apiIdToExternalId(key.requisitionId)
nonce = request.nonce
directParams = directRequisitionParams {
externalDataProviderId = apiIdToExternalId(key.dataProviderId)
encryptedData = request.encryptedData
}
}
try {
internalRequisitionStub.fulfillRequisition(fulfillRequest)
} catch (e: StatusException) {
throw when (e.status.code) {
Status.Code.NOT_FOUND -> Status.NOT_FOUND.withDescription("Requisition not found")
Status.Code.INVALID_ARGUMENT ->
Status.INVALID_ARGUMENT.withDescription("Required field unspecified or invalid")
Status.Code.FAILED_PRECONDITION ->
Status.FAILED_PRECONDITION.withDescription(
"Requisition or Measurement state illegal, or Duchy not found"
)
else -> Status.UNKNOWN
}
.withCause(e)
.asRuntimeException()
}
return fulfillDirectRequisitionResponse { state = State.FULFILLED }
}
}
/** Converts an internal [Requisition] to a public [Requisition]. */
private fun InternalRequisition.toRequisition(
allowMpcProtocolsForSingleDataProvider: Boolean,
): Requisition {
check(Version.fromString(parentMeasurement.apiVersion) == Version.V2_ALPHA) {
"Incompatible API version ${parentMeasurement.apiVersion}"
}
return requisition {
name =
RequisitionKey(
externalIdToApiId(externalDataProviderId),
externalIdToApiId(externalRequisitionId)
)
.toName()
measurement =
MeasurementKey(
externalIdToApiId(externalMeasurementConsumerId),
externalIdToApiId(externalMeasurementId)
)
.toName()
measurementConsumerCertificate =
MeasurementConsumerCertificateKey(
externalIdToApiId(externalMeasurementConsumerId),
externalIdToApiId(parentMeasurement.externalMeasurementConsumerCertificateId)
)
.toName()
measurementSpec = signedData {
data = parentMeasurement.measurementSpec
signature = parentMeasurement.measurementSpecSignature
}
val measurementTypeCase =
MeasurementSpec.parseFrom(parentMeasurement.measurementSpec).measurementTypeCase
protocolConfig =
try {
parentMeasurement.protocolConfig.toProtocolConfig(
measurementTypeCase,
parentMeasurement.dataProvidersCount,
allowMpcProtocolsForSingleDataProvider
)
} catch (e: Throwable) {
failGrpc(Status.INVALID_ARGUMENT) { e.message ?: "Failed to convert ProtocolConfig" }
}
encryptedRequisitionSpec = details.encryptedRequisitionSpec
dataProviderCertificate =
DataProviderCertificateKey(
externalIdToApiId(externalDataProviderId),
externalIdToApiId([email protected])
)
.toName()
dataProviderPublicKey = signedData {
data = details.dataProviderPublicKey
signature = details.dataProviderPublicKeySignature
}
nonce = details.nonce
duchies += duchiesMap.entries.map(Map.Entry<String, DuchyValue>::toDuchyEntry)
state = [email protected]()
if (state == State.REFUSED) {
refusal = refusal {
justification = details.refusal.justification.toRefusalJustification()
message = details.refusal.message
}
}
measurementState = [email protected]()
}
}
/** Converts an internal [InternalRefusal.Justification] to a public [Refusal.Justification]. */
private fun InternalRefusal.Justification.toRefusalJustification(): Refusal.Justification =
when (this) {
InternalRefusal.Justification.CONSENT_SIGNAL_INVALID ->
Refusal.Justification.CONSENT_SIGNAL_INVALID
InternalRefusal.Justification.SPECIFICATION_INVALID ->
Refusal.Justification.SPECIFICATION_INVALID
InternalRefusal.Justification.INSUFFICIENT_PRIVACY_BUDGET ->
Refusal.Justification.INSUFFICIENT_PRIVACY_BUDGET
InternalRefusal.Justification.UNFULFILLABLE -> Refusal.Justification.UNFULFILLABLE
InternalRefusal.Justification.DECLINED -> Refusal.Justification.DECLINED
InternalRefusal.Justification.JUSTIFICATION_UNSPECIFIED,
InternalRefusal.Justification.UNRECOGNIZED -> Refusal.Justification.JUSTIFICATION_UNSPECIFIED
}
/** Converts a public [Refusal.Justification] to an internal [InternalRefusal.Justification]. */
private fun Refusal.Justification.toInternal(): InternalRefusal.Justification =
when (this) {
Refusal.Justification.CONSENT_SIGNAL_INVALID ->
InternalRefusal.Justification.CONSENT_SIGNAL_INVALID
Refusal.Justification.SPECIFICATION_INVALID ->
InternalRefusal.Justification.SPECIFICATION_INVALID
Refusal.Justification.INSUFFICIENT_PRIVACY_BUDGET ->
InternalRefusal.Justification.INSUFFICIENT_PRIVACY_BUDGET
Refusal.Justification.UNFULFILLABLE -> InternalRefusal.Justification.UNFULFILLABLE
Refusal.Justification.DECLINED -> InternalRefusal.Justification.DECLINED
Refusal.Justification.JUSTIFICATION_UNSPECIFIED,
Refusal.Justification.UNRECOGNIZED -> InternalRefusal.Justification.JUSTIFICATION_UNSPECIFIED
}
/** Converts an internal [InternalState] to a public [State]. */
private fun InternalState.toRequisitionState(): State =
when (this) {
InternalState.PENDING_PARAMS,
InternalState.UNFULFILLED -> State.UNFULFILLED
InternalState.FULFILLED -> State.FULFILLED
InternalState.REFUSED -> State.REFUSED
InternalState.STATE_UNSPECIFIED,
InternalState.UNRECOGNIZED -> State.STATE_UNSPECIFIED
}
/** Converts a public [State] to an internal [InternalState]. */
private fun State.toInternal(): InternalState =
when (this) {
State.UNFULFILLED -> InternalState.UNFULFILLED
State.FULFILLED -> InternalState.FULFILLED
State.REFUSED -> InternalState.REFUSED
State.STATE_UNSPECIFIED,
State.UNRECOGNIZED -> InternalState.STATE_UNSPECIFIED
}
/** Converts an internal [DuchyValue] to a public [DuchyEntry.Value]. */
private fun DuchyValue.toDuchyEntryValue(): DuchyEntry.Value {
val value = this
return value {
duchyCertificate = externalIdToApiId(externalDuchyCertificateId)
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA")
when (value.protocolCase) {
DuchyValue.ProtocolCase.LIQUID_LEGIONS_V2 -> liquidLegionsV2 = liquidLegionsV2 {
elGamalPublicKey = signedData {
data = value.liquidLegionsV2.elGamalPublicKey
signature = value.liquidLegionsV2.elGamalPublicKeySignature
}
}
DuchyValue.ProtocolCase.PROTOCOL_NOT_SET -> {}
}
}
}
/** Converts an internal duchy map entry to a public [DuchyEntry]. */
private fun Map.Entry<String, DuchyValue>.toDuchyEntry(): DuchyEntry {
val mapEntry = this
return duchyEntry {
key = mapEntry.key
value = mapEntry.value.toDuchyEntryValue()
}
}
/** Converts a public [ListRequisitionsRequest] to an internal [ListRequisitionsPageToken]. */
private fun ListRequisitionsRequest.toListRequisitionsPageToken(): ListRequisitionsPageToken {
val source = this
val parentKey: DataProviderKey =
grpcRequireNotNull(DataProviderKey.fromName(source.parent)) {
"Parent is either unspecified or invalid"
}
grpcRequire(parentKey.dataProviderId != WILDCARD || source.filter.measurement.isNotBlank()) {
"Either parent data provider or measurement filter must be provided"
}
grpcRequire(source.pageSize >= 0) { "Page size cannot be less than 0" }
var externalMeasurementConsumerId = 0L
var externalMeasurementId = 0L
var externalDataProviderId = 0L
if (source.filter.measurement.isNotBlank()) {
val measurementKey: MeasurementKey =
grpcRequireNotNull(MeasurementKey.fromName(source.filter.measurement)) {
"Resource name invalid"
}
externalMeasurementConsumerId = apiIdToExternalId(measurementKey.measurementConsumerId)
externalMeasurementId = apiIdToExternalId(measurementKey.measurementId)
}
if (parentKey.dataProviderId != WILDCARD) {
externalDataProviderId = apiIdToExternalId(parentKey.dataProviderId)
}
val requisitionsStatesList = source.filter.statesList
val measurementsStatesList = source.filter.measurementStatesList
return if (source.pageToken.isNotBlank()) {
ListRequisitionsPageToken.parseFrom(source.pageToken.base64UrlDecode()).copy {
grpcRequire(externalMeasurementConsumerId == this.externalMeasurementConsumerId) {
"Arguments must be kept the same when using a page token"
}
grpcRequire(externalMeasurementId == this.externalMeasurementId) {
"Arguments must be kept the same when using a page token"
}
grpcRequire(externalDataProviderId == this.externalDataProviderId) {
"Arguments must be kept the same when using a page token"
}
grpcRequire(
states.containsAll(requisitionsStatesList) && requisitionsStatesList.containsAll(states)
) {
"Arguments must be kept the same when using a page token"
}
grpcRequire(
measurementStates.containsAll(measurementsStatesList) &&
measurementsStatesList.containsAll(measurementStates)
) {
"Arguments must be kept the same when using a page token"
}
if (source.pageSize in MIN_PAGE_SIZE..MAX_PAGE_SIZE) {
pageSize = source.pageSize
}
}
} else {
listRequisitionsPageToken {
pageSize =
when {
source.pageSize == 0 -> DEFAULT_PAGE_SIZE
source.pageSize > MAX_PAGE_SIZE -> MAX_PAGE_SIZE
else -> source.pageSize
}
this.externalMeasurementConsumerId = externalMeasurementConsumerId
this.externalMeasurementId = externalMeasurementId
this.externalDataProviderId = externalDataProviderId
states += requisitionsStatesList
measurementStates += measurementsStatesList
}
}
}
/** Converts an internal [ListRequisitionsPageToken] to an internal [StreamRequisitionsRequest]. */
private fun ListRequisitionsPageToken.toStreamRequisitionsRequest(): StreamRequisitionsRequest {
val source = this
return streamRequisitionsRequest {
// get 1 more than the actual page size for deciding whether to set page token
limit = source.pageSize + 1
filter =
StreamRequisitionsRequestKt.filter {
externalMeasurementConsumerId = source.externalMeasurementConsumerId
externalMeasurementId = source.externalMeasurementId
externalDataProviderId = source.externalDataProviderId
states += source.statesList.map { state -> state.toInternal() }
if (source.hasLastRequisition()) {
externalDataProviderIdAfter = source.lastRequisition.externalDataProviderId
externalRequisitionIdAfter = source.lastRequisition.externalRequisitionId
}
source.measurementStatesList.forEach { measurementStates += it.toInternalState() }
}
}
}
| apache-2.0 | 398e2d6511465c0327f76f5b3cbc1b02 | 40.496255 | 100 | 0.739835 | 4.738879 | false | false | false | false |
RoverPlatform/rover-android | core/src/main/kotlin/io/rover/sdk/core/events/contextproviders/FirebasePushTokenContextProvider.kt | 1 | 2543 | package io.rover.sdk.core.events.contextproviders
import io.rover.sdk.core.data.domain.DeviceContext
import io.rover.sdk.core.events.ContextProvider
import io.rover.sdk.core.events.PushTokenTransmissionChannel
import io.rover.sdk.core.logging.log
import io.rover.sdk.core.platform.LocalStorage
import io.rover.sdk.core.platform.whenNotNull
import java.util.Date
/**
* Captures and adds the Firebase push token to [DeviceContext]. As a [PushTokenTransmissionChannel], it
* expects to be informed of any changes to the push token.
*/
class FirebasePushTokenContextProvider(
localStorage: LocalStorage
) : ContextProvider, PushTokenTransmissionChannel {
override fun captureContext(deviceContext: DeviceContext): DeviceContext {
return deviceContext.copy(pushToken = token.whenNotNull {
DeviceContext.PushToken(
it,
timestampAsNeeded()
)
})
}
override fun setPushToken(token: String?) {
if (this.token != token) {
this.token = token
this.timestamp = null
timestampAsNeeded()
val elapsed = (Date().time - launchTime.time) / 1000
log.v("A new push token set after $elapsed seconds: $token")
} else {
log.v("Push token update received, token not changed.")
}
}
private val launchTime = Date()
private val keyValueStorage = localStorage.getKeyValueStorageFor(STORAGE_CONTEXT_IDENTIFIER)
private var token: String?
get() = keyValueStorage[TOKEN_KEY]
set(token) { keyValueStorage[TOKEN_KEY] = token }
private var timestamp: String?
get() = keyValueStorage[TIMESTAMP_KEY]
set(token) { keyValueStorage[TIMESTAMP_KEY] = token }
private fun timestampAsNeeded(): Date {
// retrieves the current timestamp value, setting it to now if it's missing (say, if running
// on an early 2.0 beta install where timestamp was not set).
if (timestamp == null) {
timestamp = (System.currentTimeMillis() / 1000L).toString()
}
return Date(timestamp!!.toLong() * 1000)
}
init {
if (token == null) {
log.i("No push token is set yet.")
} else {
log.i("Push token already set: $token")
}
}
companion object {
private const val STORAGE_CONTEXT_IDENTIFIER = "fcm-push-context-provider"
private const val TOKEN_KEY = "push-token"
private const val TIMESTAMP_KEY = "timestamp"
}
}
| apache-2.0 | c4b72a2b65af4af548f8a4b69c60740c | 33.364865 | 105 | 0.649233 | 4.317487 | false | false | false | false |
ykrank/S1-Next | library/src/main/java/com/github/ykrank/androidtools/ui/LibBaseFragment.kt | 1 | 3933 | package com.github.ykrank.androidtools.ui
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.annotation.CallSuper
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.github.ykrank.androidtools.R
import com.github.ykrank.androidtools.ui.internal.CoordinatorLayoutAnchorDelegate
import com.github.ykrank.androidtools.util.L
import com.github.ykrank.androidtools.widget.track.event.page.FragmentEndEvent
import com.github.ykrank.androidtools.widget.track.event.page.FragmentStartEvent
import com.google.android.material.snackbar.Snackbar
import java.lang.ref.WeakReference
/**
* Created by ykrank on 2017/10/27.
*/
abstract class LibBaseFragment : Fragment() {
protected var mCoordinatorLayoutAnchorDelegate: CoordinatorLayoutAnchorDelegate? = null
protected var mRetrySnackbar: WeakReference<Snackbar>? = null
protected var mUserVisibleHint = false
val mActivity
get() = super.getActivity() as AppCompatActivity?
@CallSuper
override fun onAttach(context: Context) {
super.onAttach(context)
mCoordinatorLayoutAnchorDelegate = context as CoordinatorLayoutAnchorDelegate
}
@CallSuper
override fun onDetach() {
mCoordinatorLayoutAnchorDelegate = null
super.onDetach()
}
@CallSuper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
L.leaveMsg("${this.javaClass.simpleName} onCreate")
}
@CallSuper
override fun onResume() {
super.onResume()
UiGlobalData.provider?.trackAgent?.post(FragmentStartEvent(this))
}
@CallSuper
override fun onPause() {
UiGlobalData.provider?.trackAgent?.post(FragmentEndEvent(this))
super.onPause()
}
@CallSuper
override fun onDestroy() {
L.leaveMsg("${this.javaClass.simpleName} onDestroy")
super.onDestroy()
}
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
mUserVisibleHint = isVisibleToUser
// see http://stackoverflow.com/a/9779971
if (isVisible && !isVisibleToUser) {
// dismiss retry Snackbar when current Fragment hid
// because this Snackbar is unrelated to other Fragments
dismissRetrySnackbarIfExist()
}
}
/**
* We must call this if used in [android.support.v4.view.ViewPager]
* otherwise leads memory leak.
*/
open fun destroyRetainedFragment() {
}
fun showRetrySnackbar(text: CharSequence, onClickListener: View.OnClickListener) {
mCoordinatorLayoutAnchorDelegate?.let {
val snackbar = it.showLongSnackbarIfVisible(
text, R.string.snackbar_action_retry, onClickListener
)
if (snackbar.isPresent) {
mRetrySnackbar = WeakReference(snackbar.get())
}
}
}
protected fun showShortSnackbar(text: CharSequence?) {
text?.let { mCoordinatorLayoutAnchorDelegate?.showShortSnackbar(it) }
}
protected fun showShortSnackbar(@StringRes resId: Int) {
mCoordinatorLayoutAnchorDelegate?.showShortSnackbar(resId)
}
protected fun showShortText(@StringRes resId: Int) {
mCoordinatorLayoutAnchorDelegate?.showToastText(getString(resId))
}
protected fun showLongSnackbar(@StringRes resId: Int) {
mCoordinatorLayoutAnchorDelegate?.showLongSnackbar(resId)
}
protected fun dismissRetrySnackbarIfExist() {
mRetrySnackbar?.let {
val snackbar = it.get()
if (snackbar != null && snackbar.isShownOrQueued) {
snackbar.dismiss()
}
mRetrySnackbar = null
}
}
protected fun leavePageMsg(msg: String) {
L.leaveMsg(msg)
}
} | apache-2.0 | 3ce56d9bc5f92fdee97ddf5a45b53076 | 30.472 | 91 | 0.692093 | 4.831695 | false | false | false | false |
grassrootza/grassroot-android-v2 | app/src/main/java/za/org/grassroot2/view/activity/MembersActivity.kt | 1 | 3262 | package za.org.grassroot2.view.activity
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.view.MenuItem
import kotlinx.android.synthetic.main.activity_group_members.*
import za.org.grassroot2.R
import za.org.grassroot2.dagger.activity.ActivityComponent
import za.org.grassroot2.view.dialog.GenericMessageDialog
import za.org.grassroot2.view.fragment.MemberListFragment
import za.org.grassroot2.view.fragment.MemberLogsFragment
/**
* Created by luke on 2017/12/10.
*/
class MembersActivity : GrassrootActivity() {
private var groupUid: String? = null
var menuItem: MenuItem? = null
override val layoutResourceId: Int
get(): Int = R.layout.activity_group_members
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
groupUid = intent.getStringExtra(GROUP_UID_FIELD)
contentPager.adapter = MembersDashboardFragmentAdapter(supportFragmentManager)
navigation.enableAnimation(false)
navigation.enableShiftingMode(false)
navigation.enableItemShiftingMode(false)
navigation.setOnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.members_list -> {
contentPager.currentItem = TAB_LIST
true
}
R.id.members_history -> {
contentPager.currentItem = TAB_HISTORY
true
}
R.id.members_permissions -> {
contentPager.currentItem = TAB_PERMISSIONS
true
}
else -> false
}
}
contentPager.addOnPageChangeListener(object: ViewPager.OnPageChangeListener {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { }
override fun onPageScrollStateChanged(state: Int) { }
override fun onPageSelected(position: Int) {
if (menuItem != null) menuItem?.setChecked(false) else navigation.menu.getItem(TAB_LIST).setChecked(false)
navigation.menu.getItem(position).setChecked(true)
menuItem = navigation.menu.getItem(position)
}
})
}
override fun onInject(component: ActivityComponent) {
component.inject(this)
}
inner class MembersDashboardFragmentAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
return when (position) {
TAB_LIST -> MemberListFragment.newInstance(groupUid!!)
TAB_HISTORY -> MemberLogsFragment.newInstance(groupUid!!)
TAB_PERMISSIONS -> MemberListFragment.newInstance(groupUid!!)
else -> GenericMessageDialog.newInstance("Huh")
}
}
override fun getCount(): Int = 2
}
companion object {
val GROUP_UID_FIELD = "group_uid"
private val TAB_LIST = 0;
private val TAB_HISTORY = 1;
private val TAB_PERMISSIONS = 2;
}
} | bsd-3-clause | 2ba0fe00b947941da40487fdbdb30ad8 | 34.086022 | 122 | 0.645616 | 4.912651 | false | false | false | false |
danrien/projectBlueWater | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/browsing/items/media/files/uri/GivenAFileThatIsAvailableRemotely/AndAvailableOnDisk/AndExistingFileUsageIsNotAllowed/WhenGettingTheUri.kt | 2 | 2477 | package com.lasthopesoftware.bluewater.client.browsing.items.media.files.uri.GivenAFileThatIsAvailableRemotely.AndAvailableOnDisk.AndExistingFileUsageIsNotAllowed
import android.net.Uri
import com.lasthopesoftware.bluewater.client.browsing.items.media.audio.uri.CachedAudioFileUriProvider
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.uri.BestMatchUriProvider
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.uri.RemoteFileUriProvider
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library
import com.lasthopesoftware.bluewater.client.stored.library.items.files.system.uri.MediaFileUriProvider
import com.lasthopesoftware.bluewater.client.stored.library.items.files.uri.StoredFileUriProvider
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.AssertionsForClassTypes.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import java.io.File
@RunWith(RobolectricTestRunner::class)
class WhenGettingTheUri {
companion object {
private val returnedFileUri by lazy {
val mockStoredFileUriProvider = mockk<StoredFileUriProvider>()
every { mockStoredFileUriProvider.promiseFileUri(any()) } returns Promise.empty()
val cachedAudioFileUriProvider = mockk<CachedAudioFileUriProvider>()
every { cachedAudioFileUriProvider.promiseFileUri(ServiceFile(3)) } returns Promise.empty()
val mockMediaFileUriProvider = mockk<MediaFileUriProvider>()
every { mockMediaFileUriProvider.promiseFileUri(any()) } returns Promise(Uri.fromFile(File("/a_media_path/to_a_file.mp3")))
val mockRemoteFileUriProvider = mockk<RemoteFileUriProvider>()
every { mockRemoteFileUriProvider.promiseFileUri(ServiceFile(3)) } returns Promise(Uri.parse("http://remote-url/to_a_file.mp3"))
val bestMatchUriProvider = BestMatchUriProvider(
Library(),
mockStoredFileUriProvider,
cachedAudioFileUriProvider,
mockMediaFileUriProvider,
mockRemoteFileUriProvider
)
bestMatchUriProvider
.promiseFileUri(ServiceFile(3))
.toFuture()
.get()
}
}
@Test
fun thenTheRemoteFileUriIsReturned() {
assertThat(returnedFileUri.toString())
.isEqualTo("http://remote-url/to_a_file.mp3")
}
}
| lgpl-3.0 | 8a6f0c7fd942efe34cc92ce328c29ed2 | 40.983051 | 162 | 0.821155 | 4.248714 | false | true | false | false |
didi/DoraemonKit | Android/dokit/src/main/java/com/didichuxing/doraemonkit/aop/method_stack/MethodInvokNode.kt | 1 | 1213 | package com.didichuxing.doraemonkit.aop.method_stack
import java.util.*
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2020/4/23-11:21
* 描 述:
* 修订历史:
* ================================================
*/
class MethodInvokNode {
var parent: MethodInvokNode? = null
var startTimeMillis: Long = 0
private var endTimeMillis: Long = 0
private var costTimeMillis = 0
var currentThreadName: String? = null
var className: String? = null
var methodName: String? = null
var level = 0
var children: MutableList<MethodInvokNode> = mutableListOf()
fun getEndTimeMillis(): Long {
return endTimeMillis
}
fun setEndTimeMillis(endTimeMillis: Long) {
this.endTimeMillis = endTimeMillis
costTimeMillis = (endTimeMillis - startTimeMillis).toInt()
}
fun getCostTimeMillis(): Int {
return (endTimeMillis - startTimeMillis).toInt()
}
fun addChild(methodInvokNode: MethodInvokNode) {
children.add(methodInvokNode)
}
fun setCostTimeMillis(costTimeMillis: Int) {
this.costTimeMillis = costTimeMillis
}
} | apache-2.0 | 2403d1cd7ab84ab091e5400654d78f1b | 23.851064 | 66 | 0.603256 | 4.322222 | false | false | false | false |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/tasks/FlipImageTask.kt | 1 | 1900 | /*
ParaTask Copyright (C) 2017 Nick Robinson>
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 uk.co.nickthecoder.paratask.tasks
import uk.co.nickthecoder.paratask.AbstractCommandTask
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.TaskParser
import uk.co.nickthecoder.paratask.parameters.ChoiceParameter
import uk.co.nickthecoder.paratask.parameters.FileParameter
import uk.co.nickthecoder.paratask.util.process.OSCommand
class FlipImageTask : AbstractCommandTask() {
override val taskD = TaskDescription("flipImage")
val inputFileP = FileParameter("inputFile", label = "Input Image")
val outputFileP = FileParameter("outputFile", label = "Output Image", mustExist = null)
val directionP = ChoiceParameter("direction", value = "x")
init {
directionP.addChoice("x", "x", "Mirror Left/Right")
directionP.addChoice("y", "y", "Upside Down")
taskD.addParameters(inputFileP, directionP, outputFileP, outputP)
}
override fun createCommand(): OSCommand {
val direction = if (directionP.value == "x") "-flop" else "-flip"
val osCommand = OSCommand("convert", inputFileP.value, direction, outputFileP.value)
return osCommand
}
}
fun main(args: Array<String>) {
TaskParser(FlipImageTask()).go(args)
}
| gpl-3.0 | 8472167ea11a62077a089f2274ff321e | 34.849057 | 92 | 0.747368 | 4.148472 | false | false | false | false |
BjoernPetersen/JMusicBot | src/main/kotlin/net/bjoernpetersen/musicbot/api/config/ConfigUi.kt | 1 | 3722 | package net.bjoernpetersen.musicbot.api.config
import java.io.File
import java.nio.file.Path
/**
* Base class for all UI node implementations.
*
* @param T the value type the associated config entry should have
*/
sealed class UiNode<T>
/**
* A simple, editable text box. For sensitive data, consider using [PasswordBox].
*/
object TextBox : UiNode<String>()
/**
* An editable text box that hides the actual value.
*/
object PasswordBox : UiNode<String>()
/**
* A CheckBox. Used by default for [Config.BooleanEntry].
*/
object CheckBox : UiNode<Boolean>()
/**
* A button that triggers some action.
*
* The actual entry value is shown in a read-only textbox.
*
* Note that, other than other node types, this one doesn't inherently change the value of the
* associated entry. It may actively change the value of any entry, or even multiple entries.
*
* The [action] is executed on a non-UI thread.
* Button implementations should make an effort to prevent the action from
* running multiple times at once.
*
* ### Example: "refresh OAuth token" button:
*
* - the label is "Refresh"
* - the backing entry contains an expiration date
* - the expiration date is displayed in the read-only textbox
* - the actual token is stored in another entry
* - the action performs an OAuth flow and updates the expiration date as well as the actual token entry
*
* @param label the label to display on the button
* @param descriptor a function that converts the entry value to a human-readable form
* @param action an action to perform when the button is clicked, returns true on success
*/
data class ActionButton<T>(
val label: String,
val descriptor: (T) -> String,
val action: suspend (Config.Entry<T>) -> Boolean
) : UiNode<T>()
/**
* Some form of input box that only accepts numbers.
*
* @param min the minimum value
* @param max the maximum value
*/
data class NumberBox @JvmOverloads constructor(val min: Int = 0, val max: Int = 100) : UiNode<Int>()
/**
* A combination of a "choose file/dir" button and a read-only textbox showing the chosen path.
*
* @param isDirectory whether a directory is chosen (otherwise a file is chosen)
* @param isOpen whether to show an open or a save dialog. Must be true if [isDirectory] is true.
*/
data class FileChooser(
val isDirectory: Boolean = true,
val isOpen: Boolean = true
) : UiNode<File>() {
init {
if (isDirectory && !isOpen)
throw IllegalArgumentException("isDirectory requires isOpen")
}
}
/**
* A combination of a "choose file/dir" button and a read-only textbox showing the chosen path.
*
* @param isDirectory whether a directory is chosen (otherwise a file is chosen)
* @param isOpen whether to show an open or a save dialog. Must be true if [isDirectory] is true.
*/
data class PathChooser(
val isDirectory: Boolean = true,
val isOpen: Boolean = true
) : UiNode<Path>() {
init {
if (isDirectory && !isOpen)
throw IllegalArgumentException("isDirectory requires isOpen")
}
}
/**
* A dropdown box containing multiple predefined items with no manual input option.
*
* The [refresh] function will not be called on a UI thread.
*
* @param descriptor converts items to a human-readable string
* @param refresh a function that is called to update the list of items.
* May return `null` if it fails to indicate that the old items should be kept.
* @param lazy whether to only load items if manually requested.
* Recommended for expensive refresh functions.
*/
data class ChoiceBox<T> @JvmOverloads constructor(
val descriptor: (T) -> String,
val refresh: suspend () -> List<T>?,
val lazy: Boolean = false
) : UiNode<T>()
| mit | 42c59519a858d58da2192ae7cc831a9b | 31.365217 | 104 | 0.706341 | 4.023784 | false | false | false | false |
DankBots/Mega-Gnar | src/main/kotlin/gg/octave/bot/commands/admin/Eval.kt | 1 | 1914 | package gg.octave.bot.commands.admin
import gg.octave.bot.Launcher
import me.devoxin.flight.api.Context
import me.devoxin.flight.api.annotations.Command
import me.devoxin.flight.api.annotations.Greedy
import me.devoxin.flight.api.entities.Cog
import org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngineFactory
import java.util.concurrent.CompletableFuture
class Eval : Cog {
private val engine = KotlinJsr223JvmLocalScriptEngineFactory().scriptEngine
@Command(description = "Evaluate Kotlin code.", developerOnly = true)
fun eval(ctx: Context, @Greedy code: String) {
if (code.isEmpty()) { // Can't remember if this is even possible with Flight lol
return ctx.send("Code can not be empty.") // TODO: Context methods like .send().issue()
}
val bindings = mapOf(
"ctx" to ctx,
"jda" to ctx.jda,
"sm" to ctx.jda.shardManager!!,
"bot" to Launcher
)
val bindString = bindings.map { "val ${it.key} = bindings[\"${it.key}\"] as ${it.value.javaClass.kotlin.qualifiedName}" }.joinToString("\n")
val bind = engine.createBindings()
bind.putAll(bindings)
try {
val result = engine.eval("$bindString\n$code", bind)
?: return ctx.message.addReaction("👌").queue()
if (result is CompletableFuture<*>) {
ctx.messageChannel.sendMessage("```\nCompletableFuture<Pending>```").queue { m ->
result.whenComplete { r, ex ->
val post = ex ?: r
m.editMessage("```\n$post```").queue()
}
}
} else {
ctx.send("```\n${result.toString().take(1950)}```")
}
} catch (e: Exception) {
ctx.send("An exception occurred.\n```\n${e.localizedMessage}```")
}
}
} | mit | b718c832e9c6be66ed3ee4d79189ab2c | 38.020408 | 148 | 0.586604 | 4.209251 | false | false | false | false |
gameofbombs/kt-postgresql-async | postgresql-async/src/test/kotlin/com/github/mauricio/async/db/postgresql/TransactionSpec.kt | 2 | 3567 | package com.github.mauricio.async.db.postgresql
import org.specs2.mutable.Specification
import com.github.mauricio.async.db.util.Log
import scala.concurrent.ExecutionContext.Implicits.global
import com.github.mauricio.async.db.postgresql.exceptions.GenericDatabaseException
class TransactionSpec extends Specification with DatabaseTestHelper {
val log = Log.get[TransactionSpec]
val tableCreate = "CREATE TEMP TABLE transaction_test (x integer PRIMARY KEY)"
fun tableInsert(x: Int) = "INSERT INTO transaction_test VALUES (" + x.toString + ")"
val tableSelect = "SELECT x FROM transaction_test ORDER BY x"
"transactions" should {
"commit simple inserts" in {
withHandler {
handler ->
executeDdl(handler, tableCreate)
await(handler.inTransaction {
conn ->
conn.sendQuery(tableInsert(1)).flatMap {
_ ->
conn.sendQuery(tableInsert(2))
}
})
val rows = executeQuery(handler, tableSelect).rows.get
rows.length === 2
rows(0)(0) === 1
rows(1)(0) === 2
}
}
"commit simple inserts with prepared statements" in {
withHandler {
handler ->
executeDdl(handler, tableCreate)
await(handler.inTransaction {
conn ->
conn.sendPreparedStatement(tableInsert(1)).flatMap {
_ ->
conn.sendPreparedStatement(tableInsert(2))
}
})
val rows = executePreparedStatement(handler, tableSelect).rows.get
rows.length === 2
rows(0)(0) === 1
rows(1)(0) === 2
}
}
"rollback on error" in {
withHandler {
handler ->
executeDdl(handler, tableCreate)
try {
await(handler.inTransaction {
conn ->
conn.sendQuery(tableInsert(1)).flatMap {
_ ->
conn.sendQuery(tableInsert(1))
}
})
failure("Should not have come here")
} catch {
case e: GenericDatabaseException -> {
e.errorMessage.message === "duplicate key value violates unique constraint \"transaction_test_pkey\""
}
}
val rows = executeQuery(handler, tableSelect).rows.get
rows.length === 0
}
}
"rollback explicitly" in {
withHandler {
handler ->
executeDdl(handler, tableCreate)
await(handler.inTransaction {
conn ->
conn.sendQuery(tableInsert(1)).flatMap {
_ ->
conn.sendQuery("ROLLBACK")
}
})
val rows = executeQuery(handler, tableSelect).rows.get
rows.length === 0
}
}
"rollback to savepoint" in {
withHandler {
handler ->
executeDdl(handler, tableCreate)
await(handler.inTransaction {
conn ->
conn.sendQuery(tableInsert(1)).flatMap {
_ ->
conn.sendQuery("SAVEPOINT one").flatMap {
_ ->
conn.sendQuery(tableInsert(2)).flatMap {
_ ->
conn.sendQuery("ROLLBACK TO SAVEPOINT one")
}
}
}
})
val rows = executeQuery(handler, tableSelect).rows.get
rows.length === 1
rows(0)(0) === 1
}
}
}
}
| apache-2.0 | 71b2323fe24f29e148eccd60def83080 | 26.651163 | 115 | 0.520606 | 4.913223 | false | false | false | false |
bozaro/git-as-svn | src/test/kotlin/svnserver/server/SvnCommitTest.kt | 1 | 9683 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.server
import org.testng.Assert
import org.testng.annotations.Test
import org.tmatesoft.svn.core.*
import org.tmatesoft.svn.core.io.SVNRepository
import svnserver.SvnTestHelper
import svnserver.SvnTestHelper.modifyFile
import svnserver.SvnTestServer
import svnserver.ext.gitlfs.storage.local.LfsLocalStorageTest
import svnserver.repository.git.EmptyDirsSupport
import svnserver.repository.git.GitWriter
/**
* Simple update tests.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class SvnCommitTest {
@Test
fun emptyDirDisabled() {
SvnTestServer.createEmpty(EmptyDirsSupport.Disabled).use { server ->
val repo: SVNRepository = server.openSvnRepository()
val editor = repo.getCommitEditor("Initial state", null, false, null)
editor.openRoot(-1)
editor.addDir("dir", null, -1)
editor.closeDir()
editor.closeDir()
try {
editor.closeEdit()
Assert.fail()
} catch (e: SVNCancelException) {
// Expected
}
}
}
@Test
fun createEmptyDir() {
SvnTestServer.createEmpty(EmptyDirsSupport.AutoCreateKeepFile).use { server ->
val repo: SVNRepository = server.openSvnRepository()
val editor = repo.getCommitEditor("Initial state", null, false, null)
editor.openRoot(-1)
editor.addDir("dir", null, -1)
editor.closeDir()
editor.closeDir()
Assert.assertNotNull(editor.closeEdit())
SvnTestHelper.checkFileContent(repo, "dir/" + GitWriter.keepFileName, GitWriter.keepFileContents)
}
}
@Test
fun emptyCommit() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
val editor = repo.getCommitEditor("Initial state", null, false, null)
editor.openRoot(-1)
editor.closeDir()
Assert.assertNotNull(editor.closeEdit())
Assert.assertEquals(emptyList<Any>(), repo.getDir("", repo.latestRevision, null, 0, ArrayList<SVNDirEntry>()))
}
}
@Test
fun removeAllFilesFromDir() {
SvnTestServer.createEmpty(EmptyDirsSupport.AutoCreateKeepFile).use { server ->
val repo: SVNRepository = server.openSvnRepository()
val editor = repo.getCommitEditor("Initial state", null, false, null)
editor.openRoot(-1)
editor.addDir("dir", null, -1)
editor.addFile("dir/file", null, 0)
SvnTestHelper.sendDeltaAndClose(editor, "dir/file", null, "text")
editor.closeDir()
editor.closeDir()
Assert.assertNotNull(editor.closeEdit())
SvnTestHelper.deleteFile(repo, "dir/file")
SvnTestHelper.checkFileContent(repo, "dir/" + GitWriter.keepFileName, GitWriter.keepFileContents)
}
}
/**
* Check file copy.
* <pre>
* svn copy README.md@45 README.copy
</pre> *
*/
@Test
fun copyFileFromRevisionTest() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
val srcFile = "/README.md"
val dstFile = "/README.copy"
val expectedContent = "New content 2"
SvnTestHelper.createFile(repo, srcFile, "Old content 1", emptyMap())
modifyFile(repo, srcFile, expectedContent, repo.latestRevision)
val srcRev = repo.latestRevision
modifyFile(repo, srcFile, "New content 3", repo.latestRevision)
val editor = repo.getCommitEditor("Copy file commit", null, false, null)
editor.openRoot(-1)
editor.addFile(dstFile, srcFile, srcRev)
editor.closeFile(dstFile, null)
editor.closeDir()
editor.closeEdit()
// compare content
SvnTestHelper.checkFileContent(repo, dstFile, expectedContent)
}
}
@Test
fun bigFile() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
val data: ByteArray = LfsLocalStorageTest.bigFile()
SvnTestHelper.createFile(repo, "bla.bin", data, SvnFilePropertyTest.propsBinary)
// compare content
SvnTestHelper.checkFileContent(repo, "bla.bin", data)
}
}
/**
* Check file copy.
* <pre>
* svn copy README.md@45 README.copy
</pre> *
*/
@Test
fun copyDirFromRevisionTest() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
run {
val editor = repo.getCommitEditor("Initial state", null, false, null)
editor.openRoot(-1)
editor.addDir("/src", null, -1)
editor.addDir("/src/main", null, -1)
editor.addFile("/src/main/source.txt", null, -1)
SvnTestHelper.sendDeltaAndClose(editor, "/src/main/source.txt", null, "Source content")
editor.closeDir()
editor.addDir("/src/test", null, -1)
editor.addFile("/src/test/test.txt", null, -1)
SvnTestHelper.sendDeltaAndClose(editor, "/src/test/test.txt", null, "Test content")
editor.closeDir()
editor.closeDir()
editor.closeDir()
editor.closeEdit()
}
SvnTestHelper.createFile(repo, "/src/main/copy-a.txt", "A content", emptyMap())
val srcDir = "/src/main"
val dstDir = "/copy"
val srcRev = repo.latestRevision
SvnTestHelper.createFile(repo, "/src/main/copy-b.txt", "B content", emptyMap())
modifyFile(repo, "/src/main/source.txt", "Updated content", repo.latestRevision)
run {
val editor = repo.getCommitEditor("Copy dir commit", null, false, null)
editor.openRoot(-1)
editor.addDir(dstDir, srcDir, srcRev)
editor.closeDir()
editor.closeDir()
editor.closeEdit()
}
// compare content
val srcList = repo.getDir(srcDir, srcRev, null, 0, ArrayList<SVNDirEntry>())
val dstList = repo.getDir(dstDir, repo.latestRevision, null, 0, ArrayList<SVNDirEntry>())
checkEquals(srcList, dstList)
}
}
private fun checkEquals(listA: Collection<SVNDirEntry>, listB: Collection<SVNDirEntry>) {
val entries = HashSet<String>()
for (entry in listA) {
entries.add(entry.name + '\t' + entry.kind + '\t' + entry.size)
}
for (entry in listB) {
Assert.assertTrue(entries.remove(entry.name + '\t' + entry.kind + '\t' + entry.size))
}
Assert.assertTrue(entries.isEmpty())
}
/**
* Check commit out-of-date.
*/
@Test
fun commitFileOufOfDateTest() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
SvnTestHelper.createFile(repo, "/README.md", "Old content", emptyMap())
val lastRevision = repo.latestRevision
modifyFile(repo, "/README.md", "New content 1", lastRevision)
try {
modifyFile(repo, "/README.md", "New content 2", lastRevision)
Assert.fail()
} catch (e: SVNException) {
Assert.assertEquals(e.errorMessage.errorCode, SVNErrorCode.WC_NOT_UP_TO_DATE)
}
}
}
/**
* Check commit up-to-date.
*/
@Test
fun commitFileUpToDateTest() {
SvnTestServer.createEmpty().use { server ->
val repo: SVNRepository = server.openSvnRepository()
SvnTestHelper.createFile(repo, "/README.md", "Old content 1", emptyMap())
SvnTestHelper.createFile(repo, "/build.gradle", "Old content 2", emptyMap())
val lastRevision = repo.latestRevision
modifyFile(repo, "/README.md", "New content 1", lastRevision)
modifyFile(repo, "/build.gradle", "New content 2", lastRevision)
}
}
/**
* Check commit without e-mail.
*/
@Test
fun commitWithoutEmail() {
SvnTestServer.createEmpty().use { server ->
val repo1: SVNRepository = server.openSvnRepository()
SvnTestHelper.createFile(repo1, "/README.md", "Old content 1", emptyMap())
SvnTestHelper.createFile(repo1, "/build.gradle", "Old content 2", emptyMap())
val repo2: SVNRepository = server.openSvnRepository(SvnTestServer.USER_NAME_NO_MAIL, SvnTestServer.PASSWORD)
val lastRevision = repo2.latestRevision
SvnTestHelper.checkFileContent(repo2, "/README.md", "Old content 1")
try {
modifyFile(repo2, "/README.md", "New content 1", lastRevision)
Assert.fail("Users with undefined email can't create commits")
} catch (e: SVNAuthenticationException) {
Assert.assertTrue(e.message!!.contains("Users with undefined email can't create commits"))
}
}
}
}
| gpl-2.0 | 436ed5fc654698d33a147664266b15dc | 39.012397 | 122 | 0.597439 | 4.361712 | false | true | false | false |
samtstern/quickstart-android | mlkit/app/src/main/java/com/google/firebase/samples/apps/mlkit/kotlin/objectdetection/ObjectDetectorProcessor.kt | 1 | 2340 | package com.google.firebase.samples.apps.mlkit.kotlin.objectdetection
import android.graphics.Bitmap
import android.util.Log
import com.google.android.gms.tasks.Task
import com.google.firebase.ml.vision.FirebaseVision
import com.google.firebase.ml.vision.common.FirebaseVisionImage
import com.google.firebase.ml.vision.objects.FirebaseVisionObject
import com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetector
import com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetectorOptions
import com.google.firebase.samples.apps.mlkit.common.CameraImageGraphic
import com.google.firebase.samples.apps.mlkit.common.FrameMetadata
import com.google.firebase.samples.apps.mlkit.common.GraphicOverlay
import com.google.firebase.samples.apps.mlkit.java.VisionProcessorBase
import java.io.IOException
/** A processor to run object detector. */
class ObjectDetectorProcessor(options: FirebaseVisionObjectDetectorOptions) :
VisionProcessorBase<List<FirebaseVisionObject>>() {
private val detector: FirebaseVisionObjectDetector
init {
detector = FirebaseVision.getInstance().getOnDeviceObjectDetector(options)
}
override fun stop() {
super.stop()
try {
detector.close()
} catch (e: IOException) {
Log.e(TAG, "Exception thrown while trying to close object detector: $e")
}
}
override fun detectInImage(image: FirebaseVisionImage): Task<List<FirebaseVisionObject>> {
return detector.processImage(image)
}
override fun onSuccess(
originalCameraImage: Bitmap?,
results: List<FirebaseVisionObject>,
frameMetadata: FrameMetadata,
graphicOverlay: GraphicOverlay
) {
graphicOverlay.clear()
if (originalCameraImage != null) {
val imageGraphic = CameraImageGraphic(graphicOverlay, originalCameraImage)
graphicOverlay.add(imageGraphic)
}
for (visionObject in results) {
val objectGraphic = ObjectGraphic(graphicOverlay, visionObject)
graphicOverlay.add(objectGraphic)
}
graphicOverlay.postInvalidate()
}
override fun onFailure(e: Exception) {
Log.e(TAG, "Object detection failed $e")
}
companion object {
private const val TAG = "ObjectDetectorProcessor"
}
}
| apache-2.0 | 290c371abc2e9de938e208b460ed1d9f | 33.925373 | 94 | 0.72735 | 4.756098 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-Basic/src/main/kotlin/me/ztiany/dsl/DSL.kt | 2 | 1330 | package me.ztiany.dsl
/** DSL
*
* 领域特定语言,用于针对某一个领域而构建的语言,比如 SQL 和 正则表达式。DSL 可以分为`外部 DSL` 和 `内部 DSL`。
*
* Kotlin DSL 构建,Kotlin 的 DSL 是完全静态的
*
* DSL 构建用到的关键特性:
*
* - 带接收者的函数字面
* - 中缀表达
* - 函数扩展
* - invoke 约定
* - gradle + kotlin
*
* */
open class Tag(val name: String) {
private val children = mutableListOf<Tag>()
protected fun <T : Tag> doInit(child: T, init: T.() -> Unit) {
child.init()
children.add(child)
}
override fun toString() = "<$name>${children.joinToString("")}</$name>"
}
fun table(init: TABLE.() -> Unit) = TABLE().apply(init)
class TABLE : Tag("table") {
fun tr(init: TR.() -> Unit) = doInit(TR(), init)
}
class TR : Tag("tr") {
fun td(init: TD.() -> Unit) = doInit(TD(), init)
}
class TD : Tag("td")
fun createTable() =
table {
tr {
td {
}
}
}
fun createAnotherTable() = table {
for (i in 1..2) {
tr {
td {
}
}
}
}
fun main(args: Array<String>) {
println(createTable())
println(createAnotherTable())
}
| apache-2.0 | 3db533649a15c2f7083df0a7ab2ae965 | 17.25 | 75 | 0.489726 | 3.065617 | false | false | false | false |
Egorand/kotlin-playground | src/me/egorand/kotlin/playground/misc/OperatorOverloading.kt | 1 | 2386 | /*
* Copyright 2016 Egor Andreevici
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package me.egorand.kotlin.playground.misc
import java.math.BigInteger
data class Fraction(val numerator: Int = 0, val denominator: Int = 1) {
companion object {
fun create(numerator: Int, denominator: Int): Fraction {
val gcd = BigInteger.valueOf(numerator.toLong())
.gcd(BigInteger.valueOf(denominator.toLong())).toInt()
return Fraction(numerator / gcd, denominator / gcd)
}
}
operator fun unaryPlus() = Fraction.create(+numerator, denominator)
operator fun unaryMinus() = Fraction.create(-numerator, denominator)
operator fun inc() = Fraction.create(numerator + 1, denominator)
operator fun dec() = Fraction.create(numerator - 1, denominator)
operator fun plus(b: Fraction) =
Fraction.create(numerator * b.denominator + b.numerator * denominator,
denominator * b.denominator)
operator fun minus(b: Fraction) =
Fraction.create(numerator * b.denominator - b.numerator * denominator,
denominator * b.denominator)
operator fun times(b: Fraction) =
Fraction.create(numerator * b.numerator, denominator * b.denominator)
operator fun div(b: Fraction) =
Fraction.create(numerator * b.denominator, b.numerator * denominator)
override fun toString(): String {
return "$numerator" + if (denominator > 1) "/$denominator" else ""
}
}
fun main(args: Array<String>) {
println(Fraction.create(1, 2))
println(+Fraction.create(-1, 2))
println(-Fraction.create(1, 2))
var frac1 = Fraction.create(3, 4)
frac1++
println(frac1)
frac1--
println(frac1)
val frac2 = Fraction.create(1, 3)
val frac3 = Fraction.create(1, 5)
println(frac2 + frac3)
println(frac2 - frac3)
println(frac2 * frac3)
println(frac2 / frac3)
} | apache-2.0 | 22ca9dc57c9e77972990f35a76072a04 | 30 | 80 | 0.687343 | 3.854604 | false | false | false | false |
edsilfer/star-wars-wiki | app/src/main/java/br/com/edsilfer/android/starwarswiki/infrastructure/retrofit/CallbackManager.kt | 1 | 3417 | package br.com.edsilfer.android.starwarswiki.infrastructure.retrofit
import android.util.Log
import br.com.edsilfer.android.starwarswiki.model.Character
import br.com.edsilfer.android.starwarswiki.model.ResponseWrapper
import br.com.edsilfer.android.starwarswiki.model.dictionary.CharacterDictionary
import br.com.edsilfer.android.starwarswiki.model.dictionary.MovieDictionary
import br.com.edsilfer.android.starwarswiki.model.dictionary.TMDBWrapperResponseDictionary
import br.com.edsilfer.android.starwarswiki.model.enum.EventCatalog
import br.com.edsilfer.kotlin_support.service.NotificationCenter.notify
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
/**
* Created by ferna on 2/19/2017.
*/
object CallbackManager {
class CMCharacter : Callback<CharacterDictionary?> {
val TAG = CMCharacter::class.simpleName
override fun onFailure(call: Call<CharacterDictionary?>?, t: Throwable?) {
notify(EventCatalog.e001, ResponseWrapper(false, null))
Log.e(TAG, "Request failed. Cause: ${t!!.message}")
}
override fun onResponse(call: Call<CharacterDictionary?>?, response: Response<CharacterDictionary?>?) {
if (response != null && response.isSuccessful) {
val character = response.body()
if (character != null) {
notify(EventCatalog.e001, ResponseWrapper(true, Character.parseDictionary(character)))
} else {
Log.e(TAG, "Character is null")
}
} else {
Log.e(TAG, "Response is null or unsuccessful")
}
}
}
class CMMovie : Callback<MovieDictionary?> {
val TAG = CMMovie::class.simpleName
override fun onFailure(call: Call<MovieDictionary?>?, t: Throwable?) {
notify(EventCatalog.e003, ResponseWrapper(false, null))
Log.e(TAG, "Request failed. Cause: ${t!!.message}")
}
override fun onResponse(call: Call<MovieDictionary?>?, response: Response<MovieDictionary?>?) {
if (response != null && response.isSuccessful) {
val movie = response.body()
if (movie != null) {
notify(EventCatalog.e003, ResponseWrapper(true, movie))
} else {
Log.e(TAG, "Movie is null")
}
} else {
Log.e(TAG, "Response is null or unsuccessful")
}
}
}
class CMTMDBMovie : Callback<TMDBWrapperResponseDictionary?> {
val TAG = CMTMDBMovie::class.simpleName
override fun onFailure(call: Call<TMDBWrapperResponseDictionary?>?, t: Throwable?) {
notify(EventCatalog.e003, ResponseWrapper(false, null))
Log.e(TAG, "Request failed. Cause: ${t!!.message}")
}
override fun onResponse(call: Call<TMDBWrapperResponseDictionary?>?, response: Response<TMDBWrapperResponseDictionary?>?) {
if (response != null && response.isSuccessful) {
val movie = response.body()
if (movie != null) {
notify(EventCatalog.e004, ResponseWrapper(true, movie))
} else {
Log.e(TAG, "Movie is null")
}
} else {
Log.e(TAG, "Response is null or unsuccessful")
}
}
}
}
| apache-2.0 | a7a04a3dd936d04dbba3e57210bbfd8d | 38.732558 | 131 | 0.613989 | 4.598923 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/settings/AboutActivity.kt | 1 | 3393 | package org.wikipedia.settings
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.forEach
import org.wikipedia.BuildConfig
import org.wikipedia.R
import org.wikipedia.activity.BaseActivity
import org.wikipedia.databinding.ActivityAboutBinding
import org.wikipedia.richtext.RichTextUtil
import org.wikipedia.util.FeedbackUtil.showMessage
import org.wikipedia.util.StringUtil.fromHtml
import org.wikipedia.util.log.L
class AboutActivity : BaseActivity() {
private lateinit var binding: ActivityAboutBinding
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAboutBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.aboutContributors.text = fromHtml(getString(R.string.about_contributors))
RichTextUtil.removeUnderlinesFromLinks(binding.aboutContributors)
binding.aboutTranslators.text = fromHtml(getString(R.string.about_translators_translatewiki))
RichTextUtil.removeUnderlinesFromLinks(binding.aboutTranslators)
binding.aboutWmf.text = fromHtml(getString(R.string.about_wmf))
RichTextUtil.removeUnderlinesFromLinks(binding.aboutWmf)
binding.aboutAppLicense.text = fromHtml(getString(R.string.about_app_license))
RichTextUtil.removeUnderlinesFromLinks(binding.aboutAppLicense)
binding.aboutVersionText.text = BuildConfig.VERSION_NAME
RichTextUtil.removeUnderlinesFromLinks(binding.activityAboutLibraries)
binding.aboutLogoImage.setOnClickListener(AboutLogoClickListener())
makeEverythingClickable(binding.aboutContainer)
binding.sendFeedbackText.setOnClickListener {
val intent = Intent()
.setAction(Intent.ACTION_SENDTO)
.setData(Uri.parse("mailto:[email protected]?subject=Android App ${BuildConfig.VERSION_NAME} Feedback"))
try {
startActivity(intent)
} catch (e: Exception) {
L.e(e)
}
}
}
private fun makeEverythingClickable(vg: ViewGroup) {
vg.forEach {
if (it is ViewGroup) {
makeEverythingClickable(it)
} else if (it is TextView) {
it.movementMethod = LinkMovementMethod.getInstance()
}
}
}
private class AboutLogoClickListener : View.OnClickListener {
private var mSecretClickCount = 0
override fun onClick(v: View) {
++mSecretClickCount
if (isSecretClickLimitMet) {
if (Prefs.isShowDeveloperSettingsEnabled) {
showMessage(v.context as Activity, R.string.show_developer_settings_already_enabled)
} else {
Prefs.isShowDeveloperSettingsEnabled = true
showMessage(v.context as Activity, R.string.show_developer_settings_enabled)
}
}
}
private val isSecretClickLimitMet: Boolean
get() = mSecretClickCount == SECRET_CLICK_LIMIT
companion object {
private const val SECRET_CLICK_LIMIT = 7
}
}
}
| apache-2.0 | efb486ff93e7399e2452cf0496d4815c | 38.917647 | 136 | 0.690539 | 4.799151 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/BasicInteraction.kt | 1 | 512 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.annotations.Internal
import com.vimeo.networking2.common.Interaction
/**
* Interaction with options and uri information.
*/
@Internal
@JsonClass(generateAdapter = true)
data class BasicInteraction(
@Internal
@Json(name = "options")
override val options: List<String>? = null,
@Internal
@Json(name = "uri")
override val uri: String? = null
) : Interaction
| mit | 23efa0297643244c2bde57a4d822c12d | 21.26087 | 49 | 0.738281 | 3.878788 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/surroundWith/expression/RsWithNotSurrounder.kt | 3 | 1334 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.surroundWith.expression
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RsExpr
import org.rust.lang.core.psi.RsParenExpr
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.RsUnaryExpr
import org.rust.lang.core.psi.ext.endOffset
import org.rust.lang.core.types.ty.TyBool
import org.rust.lang.core.types.type
class RsWithNotSurrounder : RsExpressionSurrounderBase<RsUnaryExpr>() {
@Suppress("DialogTitleCapitalization")
override fun getTemplateDescription(): String = "!(expr)"
override fun createTemplate(project: Project): RsUnaryExpr =
RsPsiFactory(project).createExpression("!(a)") as RsUnaryExpr
override fun getWrappedExpression(expression: RsUnaryExpr): RsExpr =
(expression.expr as RsParenExpr).expr!!
override fun isApplicable(expression: RsExpr): Boolean =
expression.type is TyBool
override fun doPostprocessAndGetSelectionRange(editor: Editor, expression: PsiElement): TextRange {
val offset = expression.endOffset
return TextRange.from(offset, 0)
}
}
| mit | 107a13e2d1015fb9df45ddc4de852732 | 34.105263 | 103 | 0.766117 | 4.261981 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/challenges/ChallengeFilterDialogHolder.kt | 1 | 3655 | package com.habitrpg.android.habitica.ui.fragments.social.challenges
import android.app.Activity
import android.app.AlertDialog
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.DialogChallengeFilterBinding
import com.habitrpg.android.habitica.models.social.Group
import com.habitrpg.android.habitica.ui.adapter.social.challenges.ChallengesFilterRecyclerViewAdapter
import com.habitrpg.android.habitica.utils.Action1
internal class ChallengeFilterDialogHolder private constructor(view: View, private val context: Activity) {
private val binding = DialogChallengeFilterBinding.bind(view)
private var dialog: AlertDialog? = null
private var filterGroups: List<Group>? = null
private var currentFilter: ChallengeFilterOptions? = null
private var selectedGroupsCallback: Action1<ChallengeFilterOptions>? = null
private var adapter: ChallengesFilterRecyclerViewAdapter? = null
init {
binding.challengeFilterButtonAll.setOnClickListener { allClicked() }
binding.challengeFilterButtonNone.setOnClickListener { noneClicked() }
}
fun bind(
builder: AlertDialog.Builder,
filterGroups: List<Group>,
currentFilter: ChallengeFilterOptions?,
selectedGroupsCallback: Action1<ChallengeFilterOptions>
) {
builder.setPositiveButton(context.getString(R.string.done)) { _, _ -> doneClicked() }
.show()
this.filterGroups = filterGroups
this.currentFilter = currentFilter
this.selectedGroupsCallback = selectedGroupsCallback
fillChallengeGroups()
if (currentFilter != null) {
binding.challengeFilterOwned.isChecked = currentFilter.showOwned
binding.challengeFilterNotOwned.isChecked = currentFilter.notOwned
}
}
private fun fillChallengeGroups() {
binding.challengeFilterRecyclerView.layoutManager = LinearLayoutManager(context)
adapter = filterGroups?.let { ChallengesFilterRecyclerViewAdapter(it) }
if (currentFilter != null && currentFilter?.showByGroups != null) {
adapter?.selectAll(currentFilter?.showByGroups ?: emptyList())
}
binding.challengeFilterRecyclerView.adapter = adapter
}
private fun doneClicked() {
val options = ChallengeFilterOptions()
options.showByGroups = this.adapter?.checkedEntries
options.showOwned = binding.challengeFilterOwned.isChecked
options.notOwned = binding.challengeFilterNotOwned.isChecked
selectedGroupsCallback?.call(options)
this.dialog?.hide()
}
private fun allClicked() {
this.adapter?.selectAll()
}
private fun noneClicked() {
this.adapter?.deSelectAll()
}
companion object {
fun showDialog(
activity: Activity,
filterGroups: List<Group>,
currentFilter: ChallengeFilterOptions?,
selectedGroupsCallback: Action1<ChallengeFilterOptions>
) {
val dialogLayout = activity.layoutInflater.inflate(R.layout.dialog_challenge_filter, null)
val challengeFilterDialogHolder = ChallengeFilterDialogHolder(dialogLayout, activity)
val builder = AlertDialog.Builder(activity)
.setTitle(R.string.filter)
.setView(dialogLayout)
challengeFilterDialogHolder.bind(builder, filterGroups, currentFilter, selectedGroupsCallback)
}
}
}
| gpl-3.0 | 438543a8d5e5ef79497eb1dfa3e9e990 | 37.301075 | 107 | 0.697127 | 5.191761 | false | false | false | false |
androidx/androidx | compose/animation/animation-core/src/commonMain/kotlin/androidx/compose/animation/core/AnimateAsState.kt | 3 | 23971 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.core
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
private val defaultAnimation = spring<Float>()
/**
* Fire-and-forget animation function for [Float]. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight when [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateFloatAsState] returns a [State] object. The value of the state object will continuously
* be updated by the animation until the animation finishes.
*
* Note, [animateFloatAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [Animatable] for cancelable animations.
*
* @sample androidx.compose.animation.core.samples.AlphaAnimationSample
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. [spring]
* will be used by default.
* @param visibilityThreshold An optional threshold for deciding when the animation value is
* considered close enough to the targetValue.
* @param label An optional label to differentiate from other animations in Android Studio.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateFloatAsState(
targetValue: Float,
animationSpec: AnimationSpec<Float> = defaultAnimation,
visibilityThreshold: Float = 0.01f,
label: String = "FloatAnimation",
finishedListener: ((Float) -> Unit)? = null
): State<Float> {
val resolvedAnimSpec =
if (animationSpec === defaultAnimation) {
remember(visibilityThreshold) { spring(visibilityThreshold = visibilityThreshold) }
} else {
animationSpec
}
return animateValueAsState(
targetValue,
Float.VectorConverter,
resolvedAnimSpec,
visibilityThreshold,
label,
finishedListener
)
}
/**
* Fire-and-forget animation function for [Dp]. This Composable function is overloaded for
* different parameter types such as [Float], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight when [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateDpAsState] returns a [State] object. The value of the state object will continuously be
* updated by the animation until the animation finishes.
*
* Note, [animateDpAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [Animatable] for cancelable animations.
*
* @sample androidx.compose.animation.core.samples.DpAnimationSample
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param label An optional label to differentiate from other animations in Android Studio.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateDpAsState(
targetValue: Dp,
animationSpec: AnimationSpec<Dp> = dpDefaultSpring,
label: String = "DpAnimation",
finishedListener: ((Dp) -> Unit)? = null
): State<Dp> {
return animateValueAsState(
targetValue,
Dp.VectorConverter,
animationSpec,
label = label,
finishedListener = finishedListener
)
}
private val dpDefaultSpring = spring<Dp>(visibilityThreshold = Dp.VisibilityThreshold)
/**
* Fire-and-forget animation function for [Size]. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight when [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateSizeAsState] returns a [State] object. The value of the state object will continuously be
* updated by the animation until the animation finishes.
*
* Note, [animateSizeAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [Animatable] for cancelable animations.
*
* val size: Size by animateSizeAsState(
* if (selected) Size(20f, 20f) else Size(10f, 10f))
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param label An optional label to differentiate from other animations in Android Studio.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateSizeAsState(
targetValue: Size,
animationSpec: AnimationSpec<Size> = sizeDefaultSpring,
label: String = "SizeAnimation",
finishedListener: ((Size) -> Unit)? = null
): State<Size> {
return animateValueAsState(
targetValue,
Size.VectorConverter,
animationSpec,
label = label,
finishedListener = finishedListener
)
}
private val sizeDefaultSpring = spring(visibilityThreshold = Size.VisibilityThreshold)
/**
* Fire-and-forget animation function for [Offset]. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Float],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight when [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateOffsetAsState] returns a [State] object. The value of the state object will
* continuously be updated by the animation until the animation finishes.
*
* Note, [animateOffsetAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [Animatable] for cancelable animations.
*
* @sample androidx.compose.animation.core.samples.AnimateOffsetSample
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param label An optional label to differentiate from other animations in Android Studio.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateOffsetAsState(
targetValue: Offset,
animationSpec: AnimationSpec<Offset> = offsetDefaultSpring,
label: String = "OffsetAnimation",
finishedListener: ((Offset) -> Unit)? = null
): State<Offset> {
return animateValueAsState(
targetValue,
Offset.VectorConverter,
animationSpec,
label = label,
finishedListener = finishedListener
)
}
private val offsetDefaultSpring = spring(visibilityThreshold = Offset.VisibilityThreshold)
/**
* Fire-and-forget animation function for [Rect]. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight when [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateRectAsState] returns a [State] object. The value of the state object will continuously be
* updated by the animation until the animation finishes.
*
* Note, [animateRectAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [Animatable] for cancelable animations.
*
* val bounds: Rect by animateRectAsState(
* if (enabled) Rect(0f, 0f, 100f, 100f) else Rect(8f, 8f, 80f, 80f))
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param label An optional label to differentiate from other animations in Android Studio.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateRectAsState(
targetValue: Rect,
animationSpec: AnimationSpec<Rect> = rectDefaultSpring,
label: String = "RectAnimation",
finishedListener: ((Rect) -> Unit)? = null
): State<Rect> {
return animateValueAsState(
targetValue,
Rect.VectorConverter,
animationSpec,
label = label,
finishedListener = finishedListener
)
}
private val rectDefaultSpring = spring(visibilityThreshold = Rect.VisibilityThreshold)
/**
* Fire-and-forget animation function for [Int]. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight when [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateIntAsState] returns a [State] object. The value of the state object will continuously be
* updated by the animation until the animation finishes.
*
* Note, [animateIntAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [Animatable] for cancelable animations.
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param label An optional label to differentiate from other animations in Android Studio.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateIntAsState(
targetValue: Int,
animationSpec: AnimationSpec<Int> = intDefaultSpring,
label: String = "IntAnimation",
finishedListener: ((Int) -> Unit)? = null
): State<Int> {
return animateValueAsState(
targetValue,
Int.VectorConverter,
animationSpec,
label = label,
finishedListener = finishedListener
)
}
private val intDefaultSpring = spring(visibilityThreshold = Int.VisibilityThreshold)
/**
* Fire-and-forget animation function for [IntOffset]. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight when [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateIntOffsetAsState] returns a [State] object. The value of the state object will
* continuously be updated by the animation until the animation finishes.
*
* Note, [animateIntOffsetAsState] cannot be canceled/stopped without removing this composable
* function from the tree. See [Animatable] for cancelable animations.
*
* @sample androidx.compose.animation.core.samples.AnimateOffsetSample
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param label An optional label to differentiate from other animations in Android Studio.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateIntOffsetAsState(
targetValue: IntOffset,
animationSpec: AnimationSpec<IntOffset> = intOffsetDefaultSpring,
label: String = "IntOffsetAnimation",
finishedListener: ((IntOffset) -> Unit)? = null
): State<IntOffset> {
return animateValueAsState(
targetValue,
IntOffset.VectorConverter,
animationSpec,
label = label,
finishedListener = finishedListener
)
}
private val intOffsetDefaultSpring = spring(visibilityThreshold = IntOffset.VisibilityThreshold)
/**
* Fire-and-forget animation function for [IntSize]. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight when [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateIntSizeAsState] returns a [State] object. The value of the state object will continuously
* be updated by the animation until the animation finishes.
*
* Note, [animateIntSizeAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [Animatable] for cancelable animations.
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param label An optional label to differentiate from other animations in Android Studio.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun animateIntSizeAsState(
targetValue: IntSize,
animationSpec: AnimationSpec<IntSize> = intSizeDefaultSpring,
label: String = "IntSizeAnimation",
finishedListener: ((IntSize) -> Unit)? = null
): State<IntSize> {
return animateValueAsState(
targetValue,
IntSize.VectorConverter,
animationSpec,
label = label,
finishedListener = finishedListener
)
}
private val intSizeDefaultSpring = spring(visibilityThreshold = IntSize.VisibilityThreshold)
/**
* Fire-and-forget animation function for any value. This Composable function is overloaded for
* different parameter types such as [Dp], [Color][androidx.compose.ui.graphics.Color], [Offset],
* etc. When the provided [targetValue] is changed, the animation will run automatically. If there
* is already an animation in-flight when [targetValue] changes, the on-going animation will adjust
* course to animate towards the new target value.
*
* [animateValueAsState] returns a [State] object. The value of the state object will continuously be
* updated by the animation until the animation finishes.
*
* Note, [animateValueAsState] cannot be canceled/stopped without removing this composable function
* from the tree. See [Animatable] for cancelable animations.
*
* @sample androidx.compose.animation.core.samples.ArbitraryValueTypeTransitionSample
*
* data class MySize(val width: Dp, val height: Dp)
*
* @param targetValue Target value of the animation
* @param animationSpec The animation that will be used to change the value through time. Physics
* animation will be used by default.
* @param visibilityThreshold An optional threshold to define when the animation value can be
* considered close enough to the targetValue to end the animation.
* @param label An optional label to differentiate from other animations in Android Studio.
* @param finishedListener An optional end listener to get notified when the animation is finished.
* @return A [State] object, the value of which is updated by animation.
*/
@Composable
fun <T, V : AnimationVector> animateValueAsState(
targetValue: T,
typeConverter: TwoWayConverter<T, V>,
animationSpec: AnimationSpec<T> = remember { spring() },
visibilityThreshold: T? = null,
label: String = "ValueAnimation",
finishedListener: ((T) -> Unit)? = null
): State<T> {
val toolingOverride = remember { mutableStateOf<State<T>?>(null) }
val animatable = remember { Animatable(targetValue, typeConverter, visibilityThreshold, label) }
val listener by rememberUpdatedState(finishedListener)
val animSpec: AnimationSpec<T> by rememberUpdatedState(
animationSpec.run {
if (visibilityThreshold != null && this is SpringSpec &&
this.visibilityThreshold != visibilityThreshold
) {
spring(dampingRatio, stiffness, visibilityThreshold)
} else {
this
}
}
)
val channel = remember { Channel<T>(Channel.CONFLATED) }
SideEffect {
channel.trySend(targetValue)
}
LaunchedEffect(channel) {
for (target in channel) {
// This additional poll is needed because when the channel suspends on receive and
// two values are produced before consumers' dispatcher resumes, only the first value
// will be received.
// It may not be an issue elsewhere, but in animation we want to avoid being one
// frame late.
val newTarget = channel.tryReceive().getOrNull() ?: target
launch {
if (newTarget != animatable.targetValue) {
animatable.animateTo(newTarget, animSpec)
listener?.invoke(animatable.value)
}
}
}
}
return toolingOverride.value ?: animatable.asState()
}
@Deprecated(
"animate*AsState APIs now have a new label parameter added.",
level = DeprecationLevel.HIDDEN
)
@Composable
fun animateFloatAsState(
targetValue: Float,
animationSpec: AnimationSpec<Float> = defaultAnimation,
visibilityThreshold: Float = 0.01f,
finishedListener: ((Float) -> Unit)? = null
): State<Float> = animateFloatAsState(
targetValue,
animationSpec,
visibilityThreshold,
finishedListener = finishedListener
)
@Deprecated(
"animate*AsState APIs now have a new label parameter added.",
level = DeprecationLevel.HIDDEN
)
@Composable
fun animateDpAsState(
targetValue: Dp,
animationSpec: AnimationSpec<Dp> = dpDefaultSpring,
finishedListener: ((Dp) -> Unit)? = null
): State<Dp> {
return animateValueAsState(
targetValue,
Dp.VectorConverter,
animationSpec,
finishedListener = finishedListener
)
}
@Deprecated(
"animate*AsState APIs now have a new label parameter added.",
level = DeprecationLevel.HIDDEN
)
@Composable
fun animateSizeAsState(
targetValue: Size,
animationSpec: AnimationSpec<Size> = sizeDefaultSpring,
finishedListener: ((Size) -> Unit)? = null
): State<Size> {
return animateValueAsState(
targetValue,
Size.VectorConverter,
animationSpec,
finishedListener = finishedListener
)
}
@Deprecated(
"animate*AsState APIs now have a new label parameter added.",
level = DeprecationLevel.HIDDEN
)
@Composable
fun animateOffsetAsState(
targetValue: Offset,
animationSpec: AnimationSpec<Offset> = offsetDefaultSpring,
finishedListener: ((Offset) -> Unit)? = null
): State<Offset> {
return animateValueAsState(
targetValue, Offset.VectorConverter, animationSpec, finishedListener = finishedListener
)
}
@Deprecated(
"animate*AsState APIs now have a new label parameter added.",
level = DeprecationLevel.HIDDEN
)
@Composable
fun animateRectAsState(
targetValue: Rect,
animationSpec: AnimationSpec<Rect> = rectDefaultSpring,
finishedListener: ((Rect) -> Unit)? = null
): State<Rect> {
return animateValueAsState(
targetValue, Rect.VectorConverter, animationSpec, finishedListener = finishedListener
)
}
@Deprecated(
"animate*AsState APIs now have a new label parameter added.",
level = DeprecationLevel.HIDDEN
)
@Composable
fun animateIntAsState(
targetValue: Int,
animationSpec: AnimationSpec<Int> = intDefaultSpring,
finishedListener: ((Int) -> Unit)? = null
): State<Int> {
return animateValueAsState(
targetValue, Int.VectorConverter, animationSpec, finishedListener = finishedListener
)
}
@Deprecated(
"animate*AsState APIs now have a new label parameter added.",
level = DeprecationLevel.HIDDEN
)
@Composable
fun animateIntOffsetAsState(
targetValue: IntOffset,
animationSpec: AnimationSpec<IntOffset> = intOffsetDefaultSpring,
finishedListener: ((IntOffset) -> Unit)? = null
): State<IntOffset> {
return animateValueAsState(
targetValue, IntOffset.VectorConverter, animationSpec, finishedListener = finishedListener
)
}
@Deprecated(
"animate*AsState APIs now have a new label parameter added.",
level = DeprecationLevel.HIDDEN
)
@Composable
fun animateIntSizeAsState(
targetValue: IntSize,
animationSpec: AnimationSpec<IntSize> = intSizeDefaultSpring,
finishedListener: ((IntSize) -> Unit)? = null
): State<IntSize> {
return animateValueAsState(
targetValue, IntSize.VectorConverter, animationSpec, finishedListener = finishedListener
)
}
@Deprecated(
"animate*AsState APIs now have a new label parameter added.",
level = DeprecationLevel.HIDDEN
)
@Composable
fun <T, V : AnimationVector> animateValueAsState(
targetValue: T,
typeConverter: TwoWayConverter<T, V>,
animationSpec: AnimationSpec<T> = remember { spring() },
visibilityThreshold: T? = null,
finishedListener: ((T) -> Unit)? = null
): State<T> = animateValueAsState(
targetValue = targetValue,
typeConverter = typeConverter,
animationSpec = animationSpec,
visibilityThreshold = visibilityThreshold,
label = "ValueAnimation",
finishedListener = finishedListener
)
| apache-2.0 | 619e5d920b9da875b05f08190d2543c0 | 40.116638 | 101 | 0.728756 | 4.637454 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/changenumber/ChangeNumberLockActivity.kt | 1 | 4455 | package org.thoughtcrime.securesms.components.settings.app.changenumber
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.kotlin.subscribeBy
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.MainActivity
import org.thoughtcrime.securesms.PassphraseRequiredActivity
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.logsubmit.SubmitDebugLogActivity
import org.thoughtcrime.securesms.phonenumbers.PhoneNumberFormatter
import org.thoughtcrime.securesms.util.DynamicNoActionBarTheme
import org.thoughtcrime.securesms.util.DynamicTheme
import org.thoughtcrime.securesms.util.LifecycleDisposable
import org.whispersystems.signalservice.api.push.PNI
import java.util.Objects
private val TAG: String = Log.tag(ChangeNumberLockActivity::class.java)
/**
* A captive activity that can determine if an interrupted/erred change number request
* caused a disparity between the server and our locally stored number.
*/
class ChangeNumberLockActivity : PassphraseRequiredActivity() {
private val dynamicTheme: DynamicTheme = DynamicNoActionBarTheme()
private val disposables: LifecycleDisposable = LifecycleDisposable()
private lateinit var changeNumberRepository: ChangeNumberRepository
override fun onCreate(savedInstanceState: Bundle?, ready: Boolean) {
dynamicTheme.onCreate(this)
disposables.bindTo(lifecycle)
setContentView(R.layout.activity_change_number_lock)
changeNumberRepository = ChangeNumberRepository()
checkWhoAmI()
}
override fun onResume() {
super.onResume()
dynamicTheme.onResume(this)
}
override fun onBackPressed() = Unit
private fun checkWhoAmI() {
disposables += changeNumberRepository
.whoAmI()
.flatMap { whoAmI ->
if (Objects.equals(whoAmI.number, SignalStore.account().e164)) {
Log.i(TAG, "Local and remote numbers match, nothing needs to be done.")
Single.just(false)
} else {
Log.i(TAG, "Local (${SignalStore.account().e164}) and remote (${whoAmI.number}) numbers do not match, updating local.")
Single
.just(true)
.flatMap { changeNumberRepository.changeLocalNumber(whoAmI.number, PNI.parseOrThrow(whoAmI.pni)) }
.compose(ChangeNumberRepository::acquireReleaseChangeNumberLock)
.map { true }
}
}
.observeOn(AndroidSchedulers.mainThread())
.subscribeBy(onSuccess = { onChangeStatusConfirmed() }, onError = this::onFailedToGetChangeNumberStatus)
}
private fun onChangeStatusConfirmed() {
SignalStore.misc().unlockChangeNumber()
SignalStore.misc().clearPendingChangeNumberMetadata()
MaterialAlertDialogBuilder(this)
.setTitle(R.string.ChangeNumberLockActivity__change_status_confirmed)
.setMessage(getString(R.string.ChangeNumberLockActivity__your_number_has_been_confirmed_as_s, PhoneNumberFormatter.prettyPrint(SignalStore.account().e164!!)))
.setPositiveButton(android.R.string.ok) { _, _ ->
startActivity(MainActivity.clearTop(this))
finish()
}
.setCancelable(false)
.show()
}
private fun onFailedToGetChangeNumberStatus(error: Throwable) {
Log.w(TAG, "Unable to determine status of change number", error)
MaterialAlertDialogBuilder(this)
.setTitle(R.string.ChangeNumberLockActivity__change_status_unconfirmed)
.setMessage(getString(R.string.ChangeNumberLockActivity__we_could_not_determine_the_status_of_your_change_number_request, error.javaClass.simpleName))
.setPositiveButton(R.string.ChangeNumberLockActivity__retry) { _, _ -> checkWhoAmI() }
.setNegativeButton(R.string.ChangeNumberLockActivity__leave) { _, _ -> finish() }
.setNeutralButton(R.string.ChangeNumberLockActivity__submit_debug_log) { _, _ ->
startActivity(Intent(this, SubmitDebugLogActivity::class.java))
finish()
}
.setCancelable(false)
.show()
}
companion object {
@JvmStatic
fun createIntent(context: Context): Intent {
return Intent(context, ChangeNumberLockActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
}
}
}
}
| gpl-3.0 | c4a5cfe2ac811b8c769d39c7f6e90ea6 | 39.135135 | 164 | 0.747475 | 4.611801 | false | false | false | false |
pedroSG94/rtmp-rtsp-stream-client-java | rtsp/src/main/java/com/pedro/rtsp/rtsp/RtpFrame.kt | 1 | 1746 | /*
* Copyright (C) 2021 pedroSG94.
*
* 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.pedro.rtsp.rtsp
import com.pedro.rtsp.utils.RtpConstants
/**
* Created by pedro on 7/11/18.
*/
data class RtpFrame(val buffer: ByteArray, val timeStamp: Long, val length: Int,
val rtpPort: Int, val rtcpPort: Int, val channelIdentifier: Int) {
fun isVideoFrame(): Boolean = channelIdentifier == RtpConstants.trackVideo
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as RtpFrame
if (!buffer.contentEquals(other.buffer)) return false
if (timeStamp != other.timeStamp) return false
if (length != other.length) return false
if (rtpPort != other.rtpPort) return false
if (rtcpPort != other.rtcpPort) return false
if (channelIdentifier != other.channelIdentifier) return false
return true
}
override fun hashCode(): Int {
var result = buffer.contentHashCode()
result = 31 * result + timeStamp.hashCode()
result = 31 * result + length
result = 31 * result + rtpPort
result = 31 * result + rtcpPort
result = 31 * result + channelIdentifier
return result
}
} | apache-2.0 | 2f8363432fc63b1227bb95180245a060 | 31.351852 | 86 | 0.699885 | 4.06993 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/data/checker/MergeActors.kt | 1 | 5603 | /*
* Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.data.checker
import android.provider.BaseColumns
import org.andstatus.app.data.MyProvider
import org.andstatus.app.database.table.ActivityTable
import org.andstatus.app.database.table.ActorTable
import org.andstatus.app.database.table.AudienceTable
import org.andstatus.app.database.table.NoteTable
import org.andstatus.app.net.social.AActivity
import org.andstatus.app.net.social.ActivityType
import org.andstatus.app.net.social.Actor
import org.andstatus.app.util.MyLog
import java.util.*
import java.util.concurrent.ConcurrentSkipListSet
import java.util.stream.IntStream
/**
* @author [email protected]
*/
internal class MergeActors : DataChecker() {
override fun fixInternal(): Long {
var changedCount = 0L
val actorsToMerge: MutableList<AActivity> = ArrayList(getActorsToMerge())
for (activity in actorsToMerge) {
MyLog.d(this, "Problems found: " + actorsToMerge.size)
IntStream.range(0, actorsToMerge.size)
.mapToObj { i: Int ->
(i.toString() + ". To merge " + actorsToMerge[i].getObjActor()
+ " with " + actorsToMerge[i].getActor())
}
.forEachOrdered { s: String? -> MyLog.d(this, s) }
if (!countOnly) {
mergeActor(activity)
}
changedCount++
}
return changedCount
}
private fun getActorsToMerge(): MutableSet<AActivity> {
val method = "getActorsToMerge"
val mergeActivities: MutableSet<AActivity> = ConcurrentSkipListSet()
val sql = ("SELECT " + BaseColumns._ID
+ ", " + ActorTable.ORIGIN_ID
+ ", " + ActorTable.ACTOR_OID
+ ", " + ActorTable.WEBFINGER_ID
+ " FROM " + ActorTable.TABLE_NAME
+ " ORDER BY " + ActorTable.ORIGIN_ID
+ ", " + ActorTable.ACTOR_OID)
var rowsCount: Long = 0
myContext.database?.rawQuery(sql, null)?.use { c ->
var prev: Actor = Actor.EMPTY
while (c.moveToNext()) {
rowsCount++
val actor: Actor = Actor.fromOid(myContext.origins.fromId(c.getLong(1)),
c.getString(2))
actor.actorId = c.getLong(0)
actor.setWebFingerId(c.getString(3))
prev = if (isTheSameActor(prev, actor)) {
val activity = whomToMerge(prev, actor)
mergeActivities.add(activity)
activity.getActor()
} else {
actor
}
}
}
logger.logProgress(method + " ended, " + rowsCount + " actors, " + mergeActivities.size + " to be merged")
return mergeActivities
}
private fun isTheSameActor(prev: Actor, actor: Actor): Boolean {
if (prev == null || actor == null) {
return false
}
if (prev.origin != actor.origin) {
return false
}
return prev.oid == actor.oid
}
private fun whomToMerge(prev: Actor, actor: Actor): AActivity {
val activity: AActivity = AActivity.from(Actor.EMPTY, ActivityType.UPDATE)
activity.setObjActor(actor)
var mergeWith = prev
if (myContext.accounts.fromActorId(actor.actorId).isValid) {
mergeWith = actor
activity.setObjActor(prev)
}
activity.setActor(mergeWith)
return activity
}
private fun mergeActor(activity: AActivity) {
val logMsg = "Merging " + activity.getObjActor() + " into " + activity.getActor()
logger.logProgress(logMsg)
updateColumn(logMsg, activity, ActivityTable.TABLE_NAME, ActivityTable.ACTOR_ID, false)
updateColumn(logMsg, activity, ActivityTable.TABLE_NAME, ActivityTable.OBJ_ACTOR_ID, false)
updateColumn(logMsg, activity, NoteTable.TABLE_NAME, NoteTable.AUTHOR_ID, false)
updateColumn(logMsg, activity, NoteTable.TABLE_NAME, NoteTable.IN_REPLY_TO_ACTOR_ID, false)
updateColumn(logMsg, activity, AudienceTable.TABLE_NAME, AudienceTable.ACTOR_ID, true)
MyProvider.deleteActor(myContext, activity.getObjActor().actorId)
}
private fun updateColumn(logMsg: String, activity: AActivity, tableName: String, column: String, ignoreError: Boolean) {
var sql = ""
try {
sql = ("UPDATE "
+ tableName
+ " SET "
+ column + "=" + activity.getActor().actorId
+ " WHERE "
+ column + "=" + activity.getObjActor().actorId)
myContext.database?.execSQL(sql)
} catch (e: Exception) {
if (!ignoreError) {
logger.logProgress("Error: " + e.message + ", SQL:" + sql)
MyLog.e(this, "$logMsg, SQL:$sql", e)
}
}
}
}
| apache-2.0 | 0f2ff7e7d3f1336acbddc74ecb6f50f4 | 39.89781 | 124 | 0.598608 | 4.387627 | false | false | false | false |
AndroidDeveloperLB/RootHelper | lib/src/main/java/com/lb/root_helper/lib/Root.kt | 1 | 5825 | package com.lb.root_helper.lib
import android.os.Build
import android.os.Handler
import android.os.Looper
import androidx.annotation.AnyThread
import androidx.annotation.UiThread
import androidx.annotation.WorkerThread
import com.topjohnwu.superuser.Shell
import java.io.InputStream
import java.nio.charset.Charset
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicBoolean
@Suppress("unused")
object Root {
private var rootSession: Shell? = null
private class SuResult(private val succeeded: Boolean, private val resultCode: Int, private val output: MutableList<String>, private val error: MutableList<String>) : Shell.Result() {
override fun getCode(): Int = resultCode
override fun getOut(): MutableList<String> = output
override fun isSuccess(): Boolean = succeeded
override fun getErr(): MutableList<String> = error
}
interface GotRootListener {
/**
* called when we know if you got root or not
*
* @param hasRoot true iff you got root.
*/
fun onGotRootResult(hasRoot: Boolean)
}
/**
* tries to gain root privilege.
*
* @return true iff got root
*/
@WorkerThread
@Synchronized
fun getRootPrivilege(): Boolean {
if (rootSession?.isRoot == true)
return true
val handler = Handler(Looper.getMainLooper())
val countDownLatch = CountDownLatch(1)
val gotRoot = AtomicBoolean()
handler.post {
getRootPrivilege(object : GotRootListener {
override fun onGotRootResult(hasRoot: Boolean) {
gotRoot.set(hasRoot)
if (hasRoot)
rootSession = Shell.getShell()
countDownLatch.countDown()
}
})
}
try {
countDownLatch.await()
} catch (e: InterruptedException) {
e.printStackTrace()
}
return gotRoot.get()
}
/**
* @return true iff you currently have root privilege and can perform root operations using this class
*/
@AnyThread
fun hasRoot(): Boolean = rootSession?.isRoot == true
/**
* tries to gain root privilege. Will call the listener when it's done
*/
@UiThread
fun getRootPrivilege(listener: GotRootListener) {
if (hasRoot()) {
listener.onGotRootResult(true)
return
}
Shell.getShell {
val success = it.isRoot
if (success)
rootSession = it
listener.onGotRootResult(success)
}
}
/**
* perform root operations.
*
* @return null if error or root not gained. Otherwise, a list of the strings that are the output of the commands
*/
@WorkerThread
@Synchronized
fun runCommands(commands: List<String>?): List<String>? {
return if (commands == null) null else runCommands(*commands.toTypedArray())
}
/**
* perform root operations.
*
* @return null if error or root not gained. Otherwise, a list of the strings that are the output of the commands
*/
@WorkerThread
@Synchronized
fun runCommands(vararg commands: String): List<String>? {
if (commands.isEmpty() || !hasRoot())
return null
return Shell.sh(*commands).exec().out
}
/**
* perform root operations.
*
* @return null if error or root not gained. Otherwise, a list of the strings that are the output of the commands, including errors if exists
*/
@WorkerThread
@Synchronized
fun runCommand(inputStream: InputStream, vararg commands: String): List<String>? {
if (commands.isEmpty() || !hasRoot())
return null
val process: Process = Runtime.getRuntime().exec(commands)
try {
process.outputStream.use { outputStream -> inputStream.copyTo(outputStream) }
} catch (e: Exception) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
process.destroyForcibly() else process.destroy()
throw RuntimeException(e)
}
process.waitFor()
val inputStr = process.inputStream.reader(Charset.defaultCharset()).readLines()
val errStr = process.errorStream.reader(Charset.defaultCharset()).readLines()
return ArrayList<String>(inputStr.size + errStr.size).apply {
addAll(inputStr)
addAll(errStr)
}
}
/**
* perform root operations.
*
* @return null if error or root not gained. Otherwise, a list of the strings that are the output of the commands, including detailed and specific result
*/
@WorkerThread
@Synchronized
fun runCommandWithDetailedResult(inputStream: InputStream? = null, vararg commands: String): Shell.Result? {
if (commands.isEmpty() || !hasRoot())
return null
if (inputStream == null)
return Shell.su(*commands).exec()
val process: Process = Runtime.getRuntime().exec(commands)
try {
process.outputStream.use { outputStream -> inputStream.copyTo(outputStream) }
} catch (e: Exception) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
process.destroyForcibly() else process.destroy()
throw RuntimeException(e)
}
process.waitFor()
val inputStr = process.inputStream.reader(Charset.defaultCharset()).readLines().toMutableList()
val errStr = process.errorStream.reader(Charset.defaultCharset()).readLines().toMutableList()
val exitValue = process.exitValue()
val isSucceeded = exitValue == 0
return SuResult(isSucceeded, exitValue, inputStr, errStr)
}
}
| apache-2.0 | 57aeed4cf9ff45bbf2b87d2c5c3d789e | 33.672619 | 187 | 0.622489 | 4.790296 | false | false | false | false |
handstandsam/ShoppingApp | shopping-cart/src/main/java/com/handstandsam/shoppingapp/cart/ActorStateFlowShoppingCartDao.kt | 1 | 2453 | package com.handstandsam.shoppingapp.cart
import com.handstandsam.shoppingapp.models.ItemWithQuantity
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.flow.MutableStateFlow
class ActorStateFlowShoppingCartDao : ShoppingCartDao {
/** Emits Changes, and allows us to set values internally */
override val allItems = MutableStateFlow<List<ItemWithQuantity>>(listOf())
/** We could also call these Messages */
sealed class Intention {
data class FindByLabel(
val label: String,
val deferred: CompletableDeferred<ItemWithQuantity?>
) : Intention()
data class Upsert(val itemWithQuantity: ItemWithQuantity) : Intention()
data class Remove(val itemWithQuantity: ItemWithQuantity) : Intention()
object Empty : Intention()
}
private val itemsInCart: MutableMap<String, ItemWithQuantity> = mutableMapOf()
/**
* Need to find a solution to replace the JVM Kotlin Actor we had.
* This here may be susceptible to concurrency issues.
* https://github.com/handstandsam/ShoppingApp/issues/51
*/
private fun send(intention: Intention) {
when (intention) {
is Intention.FindByLabel -> {
intention.deferred.complete(itemsInCart[intention.label])
}
is Intention.Upsert -> {
itemsInCart[intention.itemWithQuantity.item.label] = intention.itemWithQuantity
}
is Intention.Remove -> {
itemsInCart.remove(intention.itemWithQuantity.item.label)
}
is Intention.Empty -> {
itemsInCart.clear()
}
}
allItems.value = itemsInCart.asSortedList()
}
override suspend fun empty() {
send(Intention.Empty)
}
override suspend fun upsert(itemWithQuantity: ItemWithQuantity) {
send(Intention.Upsert(itemWithQuantity))
}
override suspend fun remove(itemWithQuantity: ItemWithQuantity) {
send(Intention.Remove(itemWithQuantity))
}
override suspend fun findByLabel(label: String): ItemWithQuantity? {
val deferred = CompletableDeferred<ItemWithQuantity?>()
send(
Intention.FindByLabel(
label = label,
deferred = deferred
)
)
return deferred.await()
}
}
| apache-2.0 | 8532fe96718f27371f6e76fd2b88dd4d | 32.148649 | 95 | 0.651447 | 5.344227 | false | false | false | false |
ohmae/DmsExplorer | mobile/src/main/java/net/mm2d/dmsexplorer/view/adapter/ContentListAdapter.kt | 1 | 4446 | /*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.dmsexplorer.view.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import net.mm2d.dmsexplorer.R
import net.mm2d.dmsexplorer.databinding.ContentListItemBinding
import net.mm2d.dmsexplorer.domain.entity.ContentEntity
import net.mm2d.dmsexplorer.util.FeatureUtils
import net.mm2d.dmsexplorer.viewmodel.ContentItemModel
/**
* CDSのコンテンツリストをRecyclerViewへ表示するためのAdapter。
*
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
class ContentListAdapter(context: Context) : RecyclerView.Adapter<ContentListAdapter.ViewHolder>() {
private val inflater: LayoutInflater = LayoutInflater.from(context)
private var clickListener: ((View, ContentEntity) -> Unit)? = null
private var longClickListener: ((View, ContentEntity) -> Unit)? = null
private var selectedEntity: ContentEntity? = null
private val hasTouchScreen: Boolean = FeatureUtils.hasTouchScreen(context)
private val translationZ: Float =
context.resources.getDimension(R.dimen.list_item_focus_elevation)
var list = emptyList<ContentEntity>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
DataBindingUtil.inflate(inflater, R.layout.content_list_item, parent, false)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.applyItem(list[position])
}
override fun getItemCount(): Int = list.size
fun setOnItemClickListener(listener: ((View, ContentEntity) -> Unit)?) {
clickListener = listener
}
fun setOnItemLongClickListener(listener: ((View, ContentEntity) -> Unit)?) {
longClickListener = listener
}
fun indexOf(entity: ContentEntity): Int = list.indexOf(entity)
fun getSelectedEntity(): ContentEntity? = selectedEntity
fun setSelectedEntity(entity: ContentEntity?): Boolean {
if (selectedEntity != null && selectedEntity == entity) {
return false
}
val previous = selectedEntity
selectedEntity = entity
notifyItemChangedIfPossible(previous)
notifyItemChangedIfPossible(entity)
return true
}
private fun notifyItemChangedIfPossible(entity: ContentEntity?) {
if (entity == null) {
return
}
val position = list.indexOf(entity)
if (position < 0) {
return
}
notifyItemChanged(position)
}
fun clearSelectedEntity() {
setSelectedEntity(null)
}
inner class ViewHolder(
private val binding: ContentListItemBinding
) : RecyclerView.ViewHolder(binding.root) {
private var contentEntity: ContentEntity? = null
init {
itemView.setOnClickListener(::onClick)
itemView.setOnLongClickListener(::onLongClick)
if (!hasTouchScreen) {
itemView.onFocusChangeListener =
View.OnFocusChangeListener { v, focus -> this.onFocusChange(v, focus) }
}
}
fun applyItem(entity: ContentEntity) {
contentEntity = entity
val selected = entity == selectedEntity
itemView.isSelected = selected
binding.model = ContentItemModel(itemView.context, entity, selected)
binding.executePendingBindings()
}
private fun onClick(v: View) {
contentEntity?.let {
clickListener?.invoke(v, it)
}
}
private fun onLongClick(v: View): Boolean {
contentEntity?.let {
longClickListener?.invoke(v, it)
}
return true
}
private fun onFocusChange(v: View, focus: Boolean) {
if (focus) {
v.scaleX = FOCUS_SCALE
v.scaleY = FOCUS_SCALE
} else {
v.scaleX = 1.0f
v.scaleY = 1.0f
}
v.translationZ = if (focus) translationZ else 0.0f
}
}
companion object {
private const val FOCUS_SCALE = 1.1f
}
}
| mit | 489ab886434ea2740ecec1b4d6bde522 | 30.826087 | 100 | 0.645036 | 4.748108 | false | false | false | false |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/quests/opening_hours/AddOpeningHours.kt | 1 | 3657 | package de.westnordost.streetcomplete.quests.opening_hours
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.SimpleOverpassQuestType
import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
class AddOpeningHours (o: OverpassMapDataDao) : SimpleOverpassQuestType<OpeningHoursAnswer>(o) {
/* See also AddWheelchairAccessBusiness and AddPlaceName, which has a similar list and is/should
be ordered in the same way for better overview */
override val tagFilters =
"nodes, ways, relations with ( shop and shop !~ no|vacant" +
" or amenity = bicycle_parking and bicycle_parking = building" +
" or amenity = parking and parking = multi-storey" +
" or amenity = recycling and recycling_type = centre" +
" or tourism = information and information = office" +
" or " +
mapOf(
"amenity" to arrayOf(
"restaurant", "cafe", "ice_cream", "fast_food", "bar", "pub", "biergarten", "food_court", "nightclub", // eat & drink
"cinema", "planetarium", "casino", "library", // amenities
"townhall", "courthouse", "embassy", "community_centre", "youth_centre", // civic
// not ATM because too often it's simply 24/7 and too often it is confused with
// a bank that might be just next door because the app does not tell the user what
// kind of object this is about
"bank", /*atm,*/ "bureau_de_change", "money_transfer", "post_office", "marketplace", "internet_cafe", // commercial
"car_wash", "car_rental", "boat_rental", "fuel", // car stuff
"dentist", "doctors", "clinic", "pharmacy", "veterinary" // health
),
"tourism" to arrayOf(
"zoo", "aquarium", "theme_park", "gallery", "museum"
// and tourism=information, see above
),
"leisure" to arrayOf(
"sports_centre", "fitness_centre", "dance", "golf_course", "water_park",
"miniature_golf", "bowling_alley", "horse_riding", "amusement_arcade",
"adult_gaming_centre", "tanning_salon"
),
"office" to arrayOf(
"insurance", "government", "estate_agent", "travel_agent"
)
).map { it.key + " ~ " + it.value.joinToString("|") }.joinToString(" or ") +
" )" +
" and !opening_hours and name and opening_hours:signed != no" +
" and (access !~ private|no)"
override val commitMessage = "Add opening hours"
override val icon = R.drawable.ic_quest_opening_hours
override fun getTitle(tags: Map<String, String>) = R.string.quest_openingHours_name_title
override fun createForm() = AddOpeningHoursForm()
override fun applyAnswerTo(answer: OpeningHoursAnswer, changes: StringMapChangesBuilder) {
when(answer) {
is RegularOpeningHours -> changes.add("opening_hours", answer.times.joinToString(";"))
is AlwaysOpen -> changes.add("opening_hours", "24/7")
is NoOpeningHoursSign -> changes.add("opening_hours:signed", "no")
is DescribeOpeningHours -> {
val text = answer.text.replace("\"","")
changes.add("opening_hours", "\"$text\"")
}
}
}
}
| gpl-3.0 | dd40b1c0059ce21d96e0b1133433bae2 | 54.409091 | 133 | 0.572874 | 4.3125 | false | false | false | false |
maddog05/MaddogUtilities | maddogutilities/src/main/java/com/maddog05/maddogutilities/view/VerticalTextView.kt | 1 | 1811 | package com.maddog05.maddogutilities.view
import android.content.Context
import android.graphics.Canvas
import androidx.appcompat.widget.AppCompatTextView
import android.util.AttributeSet
import com.maddog05.maddogutilities.R
/*
* Created by andreetorres on 10/02/18.
*/
class VerticalTextView : AppCompatTextView {
private var topDown = false
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
val attributes = context.obtainStyledAttributes(attrs, R.styleable.VerticalTextView)
topDown = attributes.getBoolean(R.styleable.VerticalTextView_vtv_alignBottomInStart, true)
attributes.recycle()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
val attributes = context.obtainStyledAttributes(attrs, R.styleable.VerticalTextView)
topDown = attributes.getBoolean(R.styleable.VerticalTextView_vtv_alignBottomInStart, true)
attributes.recycle()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(heightMeasureSpec, widthMeasureSpec)
setMeasuredDimension(measuredHeight, measuredWidth)
}
override fun onDraw(canvas: Canvas) {
val textPaint = paint
textPaint.color = currentTextColor
textPaint.drawableState = drawableState
canvas.save()
if (topDown) {
canvas.translate(width.toFloat(), 0f)
canvas.rotate(90f)
} else {
canvas.translate(0f, height.toFloat())
canvas.rotate(-90f)
}
canvas.translate(compoundPaddingLeft.toFloat(), extendedPaddingTop.toFloat())
layout.draw(canvas)
canvas.restore()
}
} | mit | 7673d96b7103dfeb259d733a075e5082 | 31.357143 | 113 | 0.705135 | 4.58481 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/stdlib/coroutines/SequenceBuilderTest/testLaziness.kt | 2 | 845 | import kotlin.test.*
import kotlin.coroutines.experimental.buildSequence
import kotlin.coroutines.experimental.buildIterator
fun box() {
var sharedVar = -2
val result = buildSequence {
while (true) {
when (sharedVar) {
-1 -> return@buildSequence
-2 -> error("Invalid state: -2")
else -> yield(sharedVar)
}
}
}
val iterator = result.iterator()
sharedVar = 1
assertTrue(iterator.hasNext())
assertEquals(1, iterator.next())
sharedVar = 2
assertTrue(iterator.hasNext())
assertEquals(2, iterator.next())
sharedVar = 3
assertTrue(iterator.hasNext())
assertEquals(3, iterator.next())
sharedVar = -1
assertFalse(iterator.hasNext())
assertFailsWith<NoSuchElementException> { iterator.next() }
}
| apache-2.0 | 4d7122c30ba8d200d90ffc72028c1023 | 23.142857 | 63 | 0.615385 | 4.617486 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/notifications/StepicFcmListenerService.kt | 2 | 5401 | package org.stepic.droid.notifications
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.app.NotificationCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.google.gson.Gson
import org.stepic.droid.BuildConfig
import org.stepic.droid.R
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.base.App
import org.stepic.droid.core.StepikDevicePoster
import org.stepic.droid.notifications.badges.NotificationsBadgesManager
import org.stepic.droid.notifications.handlers.RemoteMessageHandler
import org.stepic.droid.notifications.model.Notification
import org.stepic.droid.notifications.model.NotificationStatuses
import org.stepic.droid.notifications.model.StepikNotificationChannel
import org.stepic.droid.preferences.SharedPreferenceHelper
import org.stepic.droid.util.resolveColorAttribute
import org.stepik.android.domain.story_deeplink.model.StoryDeepLinkNotification
import org.stepik.android.view.notification.FcmNotificationHandler
import java.io.IOException
import javax.inject.Inject
class StepicFcmListenerService : FirebaseMessagingService() {
companion object {
private const val NOTIFICATION_TYPE = "notifications" // todo: refactor in message handlers
private const val NOTIFICATION_STATUSES_TYPE = "notification-statuses"
private const val STORY_TEMPLATES = "story-templates"
}
private val hacker = HackFcmListener()
override fun onMessageReceived(message: RemoteMessage) {
try {
message.data?.let { data ->
val userId: Long? = hacker.sharedPreferenceHelper.profile?.id
val userIdServerString = data["user_id"] ?: ""
val userIdServer = Integer.parseInt(userIdServerString)
if (userId == null || userIdServer.toLong() != userId) {
return
}
val rawMessageObject = data["object"]
val messageType = data["type"]
when (messageType) {
NOTIFICATION_TYPE -> processNotification(rawMessageObject)
NOTIFICATION_STATUSES_TYPE -> processNotificationStatuses(rawMessageObject)
STORY_TEMPLATES -> processStoryTemplatesDeeplink(rawMessageObject)
else -> hacker.handlers[messageType]?.handleMessage(this, rawMessageObject)
}
}
} catch (e: IOException) {
//internet is not available. just ignore, we can't show reach notification
} catch (e: Exception) {
hacker.analytic.reportError(Analytic.Error.NOTIFICATION_ERROR_PARSE, e)
}
}
private fun processNotification(rawMessageObject: String?) {
val stepikNotification = Gson().fromJson(rawMessageObject, Notification::class.java)
stepikNotification?.let {
hacker.fcmNotificationHandler.showNotification(it)
}
}
private fun processNotificationStatuses(rawMessageObject: String?) {
val notificationStatuses = Gson().fromJson(rawMessageObject, NotificationStatuses::class.java)
notificationStatuses?.let {
hacker.notificationsBadgesManager.syncCounter()
}
}
private fun processStoryTemplatesDeeplink(rawMessageObject: String?) {
val storyDeepLinkNotification = Gson().fromJson(rawMessageObject, StoryDeepLinkNotification::class.java)
val requestCode = 1233
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(storyDeepLinkNotification.storyUrl))
.setPackage(BuildConfig.APPLICATION_ID)
val notification = NotificationCompat.Builder(applicationContext, StepikNotificationChannel.user.channelId)
.setSmallIcon(R.drawable.ic_notification_icon_1)
.setContentTitle(storyDeepLinkNotification.title)
.setContentText(storyDeepLinkNotification.body)
.setColor(applicationContext.resolveColorAttribute(R.attr.colorSecondary))
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(applicationContext, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
notification.setStyle(NotificationCompat.BigTextStyle()
.bigText(storyDeepLinkNotification.body))
.setContentText(storyDeepLinkNotification.body)
val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(requestCode, notification.build())
}
override fun onNewToken(token: String) {
hacker.stepikDevicePoster.registerDevice()
}
}
class HackFcmListener {
@Inject
lateinit var sharedPreferenceHelper: SharedPreferenceHelper
@Inject
lateinit var analytic: Analytic
@Inject
lateinit var notificationsBadgesManager: NotificationsBadgesManager
@Inject
internal lateinit var handlers: Map<String, @JvmSuppressWildcards RemoteMessageHandler>
@Inject
internal lateinit var fcmNotificationHandler: FcmNotificationHandler
@Inject
lateinit var stepikDevicePoster: StepikDevicePoster
init {
App.component().inject(this)
}
} | apache-2.0 | 1b3ea9878123be02f11acb5830f8447b | 40.236641 | 132 | 0.727273 | 5.104915 | false | false | false | false |
ItsT-Mo/SnappyPark | app/src/main/java/de/dilello/www/snappypark/activities/SplashScreen.kt | 1 | 1370 | package de.dilello.www.snappypark.activities
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import de.dilello.www.snappypark.R
import de.dilello.www.snappypark.services.NotificationService
import de.dilello.www.snappypark.services.PreferencesService
class SplashScreen : AppCompatActivity() {
lateinit var preferencesService: PreferencesService
lateinit var notificationService: NotificationService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash_screen)
preferencesService = PreferencesService(this)
notificationService = NotificationService(this)
openNextActivity()
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationService.createNotificationChannel()
}
}
/**
* Start correct activity based on if onboarding was completed or not
*/
private fun openNextActivity() {
if (preferencesService.isOnboardingCompleted == false) {
val welcomeIntent = Intent(this, WelcomeActivity::class.java)
startActivity(welcomeIntent)
} else {
val mapsIntent = Intent(this, MapsActivity::class.java)
startActivity(mapsIntent)
}
}
}
| mpl-2.0 | a86ebd57015d2b9a217f222f58741352 | 34.128205 | 83 | 0.718248 | 4.612795 | false | false | false | false |
andrewoma/kwery | core/src/main/kotlin/com/github/andrewoma/kwery/core/dialect/PostgresDialect.kt | 1 | 2173 | /*
* Copyright (c) 2015 Andrew O'Malley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.andrewoma.kwery.core.dialect
import java.sql.Date
import java.sql.Time
import java.sql.Timestamp
import javax.xml.bind.DatatypeConverter
open class PostgresDialect : Dialect {
override fun bind(value: Any, limit: Int) = when (value) {
is String -> escapeSingleQuotedString(value.truncate(limit))
is Timestamp -> timestampFormat.get().format(value)
is Date -> "'$value'"
is Time -> "'$value'"
is java.sql.Array -> bindArray(value, limit, "array[", "]")
is ByteArray -> "decode('${DatatypeConverter.printBase64Binary(value.truncate(limit))}','base64')"
else -> value.toString()
}
override fun arrayBasedIn(name: String) = "= any(:$name)"
override val supportsArrayBasedIn = true
override val supportsAllocateIds = true
override fun allocateIds(count: Int, sequence: String, columnName: String) =
"select nextval('$sequence') as $columnName from generate_series(1, $count)"
override val supportsFetchingGeneratedKeysByName = true
}
| mit | 837de095e39c09b37f18056aaf5fb26f | 40.788462 | 106 | 0.724344 | 4.363454 | false | false | false | false |
da1z/intellij-community | java/compiler/impl/src/com/intellij/build/output/KotlincOutputParser.kt | 3 | 6370 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.build.output
import com.intellij.build.FilePosition
import com.intellij.build.events.MessageEvent
import com.intellij.build.events.impl.FileMessageEventImpl
import com.intellij.build.events.impl.MessageEventImpl
import com.intellij.openapi.util.text.StringUtil
import java.io.File
import java.lang.IllegalStateException
import java.util.function.Consumer
import java.util.regex.Pattern
/**
* TODO should be moved to the kotlin plugin
*
* Parses kotlinc's output.
*/
class KotlincOutputParser : BuildOutputParser {
companion object {
private val COMPILER_MESSAGES_GROUP = "Kotlin compiler"
}
override fun parse(line: String, reader: BuildOutputInstantReader, consumer: Consumer<MessageEvent>): Boolean {
val colonIndex1 = line.colon()
val severity = if (colonIndex1 >= 0) line.substringBeforeAndTrim(colonIndex1) else return false
if (!severity.startsWithSeverityPrefix()) return false
val lineWoSeverity = line.substringAfterAndTrim(colonIndex1)
val colonIndex2 = lineWoSeverity.colon().skipDriveOnWin(lineWoSeverity)
if (colonIndex2 >= 0) {
val path = lineWoSeverity.substringBeforeAndTrim(colonIndex2)
val file = File(path)
val fileExtension = file.extension.toLowerCase()
if (!file.isFile || (fileExtension != "kt" && fileExtension != "java")) {
return addMessage(createMessage(reader.buildId, getMessageKind(severity), lineWoSeverity.amendNextLinesIfNeeded(reader)), consumer)
}
val lineWoPath = lineWoSeverity.substringAfterAndTrim(colonIndex2)
val colonIndex3 = lineWoPath.colon()
if (colonIndex3 >= 0) {
val position = lineWoPath.substringBeforeAndTrim(colonIndex3)
val matcher = KOTLIN_POSITION_PATTERN.matcher(position).takeIf { it.matches() } ?: JAVAC_POSITION_PATTERN.matcher(position)
val message = lineWoPath.substringAfterAndTrim(colonIndex3).amendNextLinesIfNeeded(reader)
if (matcher.matches()) {
val lineNumber = matcher.group(1)
val symbolNumber = if (matcher.groupCount() >= 2) matcher.group(2) else "1"
if (lineNumber != null) {
val symbolNumberText = symbolNumber.toInt()
return addMessage(createMessageWithLocation(
reader.buildId, getMessageKind(severity), message, path, lineNumber.toInt(), symbolNumberText), consumer)
}
}
return addMessage(createMessage(reader.buildId, getMessageKind(severity), message), consumer)
}
else {
return addMessage(createMessage(reader.buildId, getMessageKind(severity), lineWoSeverity.amendNextLinesIfNeeded(reader)), consumer)
}
}
return false
}
private val COLON = ":"
private val KOTLIN_POSITION_PATTERN = Pattern.compile("\\(([0-9]*), ([0-9]*)\\)")
private val JAVAC_POSITION_PATTERN = Pattern.compile("([0-9]+)")
private fun String.amendNextLinesIfNeeded(reader: BuildOutputInstantReader): String {
var nextLine = reader.readLine()
val builder = StringBuilder(this)
while (nextLine != null && nextLine.isNextMessage().not()) {
builder.append("\n").append(nextLine)
nextLine = reader.readLine()
}
if (nextLine != null) {
// This code is needed for compatibility with AS 2.0 and IDEA 15.0, because of difference in android plugins
val positionField = try {
reader::class.java.getDeclaredField("myPosition")
}
catch (e: Throwable) {
null
}
if (positionField != null) {
positionField.isAccessible = true
positionField.setInt(reader, positionField.getInt(reader) - 1)
}
}
return builder.toString()
}
private fun String.isNextMessage(): Boolean {
val colonIndex1 = indexOf(COLON)
return colonIndex1 == 0
|| (colonIndex1 >= 0 && substring(0, colonIndex1).startsWithSeverityPrefix()) // Next Kotlin message
|| StringUtil.containsIgnoreCase(this, "FAILURE")
|| StringUtil.containsIgnoreCase(this, "FAILED")
}
private fun String.startsWithSeverityPrefix() = getMessageKind(this) != MessageEvent.Kind.SIMPLE
private fun getMessageKind(kind: String) = when (kind) {
"e" -> MessageEvent.Kind.ERROR
"w" -> MessageEvent.Kind.WARNING
"i" -> MessageEvent.Kind.INFO
"v" -> MessageEvent.Kind.SIMPLE
else -> MessageEvent.Kind.SIMPLE
}
private fun String.substringAfterAndTrim(index: Int) = substring(index + 1).trim()
private fun String.substringBeforeAndTrim(index: Int) = substring(0, index).trim()
private fun String.colon() = indexOf(COLON)
private fun Int.skipDriveOnWin(line: String): Int {
return if (this == 1) line.indexOf(COLON, this + 1) else this
}
private val KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT =
// KaptError::class.java.canonicalName + ": " + KaptError.Kind.ERROR_RAISED.message
"org.jetbrains.kotlin.kapt3.diagnostic.KaptError" + ": " + "Error while annotation processing"
private fun isKaptErrorWhileAnnotationProcessing(message: MessageEvent): Boolean {
if (message.kind != MessageEvent.Kind.ERROR) return false
val messageText = message.message
return messageText.startsWith(IllegalStateException::class.java.name)
&& messageText.contains(KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT)
}
private fun addMessage(message: MessageEvent, consumer: Consumer<MessageEvent>): Boolean {
// Ignore KaptError.ERROR_RAISED message from kapt. We already processed all errors from annotation processing
if (isKaptErrorWhileAnnotationProcessing(message)) return true
consumer.accept(message)
return true
}
private fun createMessage(buildId: Any, messageKind: MessageEvent.Kind, text: String): MessageEvent {
return MessageEventImpl(buildId, messageKind, COMPILER_MESSAGES_GROUP, text.trim())
}
private fun createMessageWithLocation(
buildId: Any,
messageKind: MessageEvent.Kind,
text: String,
file: String,
lineNumber: Int,
columnIndex: Int
): FileMessageEventImpl {
return FileMessageEventImpl(buildId, messageKind, COMPILER_MESSAGES_GROUP, text.trim(),
FilePosition(File(file), lineNumber - 1, columnIndex - 1))
}
} | apache-2.0 | 7619903712b6e61fa913dd604ef62028 | 38.571429 | 140 | 0.70832 | 4.656433 | false | false | false | false |
Heiner1/AndroidAPS | core/src/main/java/info/nightscout/androidaps/di/StaticInjector.kt | 1 | 802 | package info.nightscout.androidaps.di
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import java.lang.IllegalStateException
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class StaticInjector @Inject constructor(
private val injector: HasAndroidInjector
) : HasAndroidInjector {
companion object {
private var instance : StaticInjector? = null
@Deprecated("Use only for classes instantiated by 3rd party")
fun getInstance() : StaticInjector {
if (instance == null) throw IllegalStateException("StaticInjector not initialized")
return instance!!
}
}
init {
instance = this
}
override fun androidInjector(): AndroidInjector<Any> = injector.androidInjector()
} | agpl-3.0 | 14d27af8b96a0a38c03527dca8ee60d3 | 28.740741 | 95 | 0.723192 | 5.276316 | false | false | false | false |
sirixdb/sirix | bundles/sirix-kotlin-cli/src/test/kotlin/org/sirix/cli/commands/DropResourceTest.kt | 1 | 1758 | package org.sirix.cli.commands
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.sirix.access.Databases
import org.sirix.access.ResourceConfiguration
import org.sirix.cli.commands.CliCommandTestConstants.Companion.RESOURCE_LIST
import org.sirix.cli.commands.CliCommandTestConstants.Companion.TEST_USER
import org.slf4j.Logger
import org.slf4j.LoggerFactory
internal class DropResourceTest : CliCommandTest() {
companion object {
@JvmField
val LOGGER: Logger = LoggerFactory.getLogger(DropResourceTest::class.java)
}
@BeforeEach
fun setUp() {
createXmlDatabase()
}
@AfterEach
fun tearDown() {
removeTestDatabase(CreateResourceTest.LOGGER)
}
@Test
fun happyPath() {
// GIVEN
var database = Databases.openXmlDatabase(path())
database.use {
RESOURCE_LIST.forEach {
database.createResource(ResourceConfiguration.Builder(it).build())
}
}
val dropResourceList = RESOURCE_LIST.filterIndexed { index, _ -> (index % 2) == 0 }
val dropResourceCommand = DropResource(giveACliOptions(), dropResourceList, TEST_USER)
// WHEN
dropResourceCommand.execute()
// THEN
database = Databases.openXmlDatabase(path())
database.use {
for ((index, value) in RESOURCE_LIST.withIndex()) {
if (index % 2 == 0) {
Assertions.assertFalse(database.existsResource(value))
} else {
Assertions.assertTrue(database.existsResource(value))
}
}
}
}
}
| bsd-3-clause | 588c6753dd50892fc54a88401847dba8 | 28.79661 | 94 | 0.643914 | 4.507692 | false | true | false | false |
PolymerLabs/arcs | src/tools/tests/goldens/kt_generated-schemas.jvm.kt | 1 | 33091 | /* ktlint-disable */
@file:Suppress("PackageName", "TopLevelName")
package arcs.golden
//
// GENERATED CODE -- DO NOT EDIT
//
import arcs.core.data.Annotation
import arcs.core.data.expression.*
import arcs.core.data.expression.Expression.*
import arcs.core.data.expression.Expression.BinaryOp.*
import arcs.core.data.util.toReferencable
import arcs.sdk.ArcsDuration
import arcs.sdk.ArcsInstant
import arcs.sdk.BigInt
import arcs.sdk.Entity
import arcs.sdk.toBigInt
import javax.annotation.Generated
typealias KotlinPrimitivesGolden_Data_Ref = AbstractKotlinPrimitivesGolden.KotlinPrimitivesGolden_Data_Ref
typealias KotlinPrimitivesGolden_Data_Ref_Slice = AbstractKotlinPrimitivesGolden.KotlinPrimitivesGolden_Data_Ref_Slice
typealias KotlinPrimitivesGolden_Data_Thinglst = AbstractKotlinPrimitivesGolden.Thing
typealias KotlinPrimitivesGolden_Data_Thinglst_Slice = AbstractKotlinPrimitivesGolden.ThingSlice
typealias KotlinPrimitivesGolden_Data_Detail_Nested = AbstractKotlinPrimitivesGolden.Nested
typealias KotlinPrimitivesGolden_Data_Detail_Nested_Slice = AbstractKotlinPrimitivesGolden.NestedSlice
typealias KotlinPrimitivesGolden_Data_Colors = AbstractKotlinPrimitivesGolden.Color
typealias KotlinPrimitivesGolden_Data_Colors_Slice = AbstractKotlinPrimitivesGolden.ColorSlice
typealias KotlinPrimitivesGolden_Data_Products = AbstractKotlinPrimitivesGolden.Product
typealias KotlinPrimitivesGolden_Data_Products_Slice = AbstractKotlinPrimitivesGolden.ProductSlice
typealias KotlinPrimitivesGolden_Data_Detail = AbstractKotlinPrimitivesGolden.Detail
typealias KotlinPrimitivesGolden_Data_Detail_Slice = AbstractKotlinPrimitivesGolden.DetailSlice
typealias KotlinPrimitivesGolden_Data = AbstractKotlinPrimitivesGolden.KotlinPrimitivesGolden_Data
typealias KotlinPrimitivesGolden_Data_Slice = AbstractKotlinPrimitivesGolden.KotlinPrimitivesGolden_Data_Slice
@Generated("src/tools/schema2kotlin.ts")
abstract class AbstractKotlinPrimitivesGolden : arcs.sdk.BaseParticle() {
override val handles: Handles = Handles()
interface KotlinPrimitivesGolden_Data_Ref_Slice : arcs.sdk.Entity {
val val_: String
}
@Suppress("UNCHECKED_CAST")
class KotlinPrimitivesGolden_Data_Ref(
val_: String = "",
entityId: String? = null,
creationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP,
expirationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP
) : arcs.sdk.EntityBase(
"KotlinPrimitivesGolden_Data_Ref",
SCHEMA,
entityId,
creationTimestamp,
expirationTimestamp,
false
), KotlinPrimitivesGolden_Data_Ref_Slice {
override var val_: String
get() = super.getSingletonValue("val") as String? ?: ""
private set(_value) = super.setSingletonValue("val", _value)
init {
this.val_ = val_
}
/**
* Use this method to create a new, distinctly identified copy of the entity.
* Storing the copy will result in a new copy of the data being stored.
*/
fun copy(val_: String = this.val_) = KotlinPrimitivesGolden_Data_Ref(val_ = val_)
/**
* Use this method to create a new version of an existing entity.
* Storing the mutation will overwrite the existing entity in the set, if it exists.
*/
fun mutate(val_: String = this.val_) = KotlinPrimitivesGolden_Data_Ref(
val_ = val_,
entityId = entityId,
creationTimestamp = creationTimestamp,
expirationTimestamp = expirationTimestamp
)
companion object : arcs.sdk.EntitySpec<KotlinPrimitivesGolden_Data_Ref> {
override val SCHEMA = arcs.core.data.Schema(
setOf(),
arcs.core.data.SchemaFields(
singletons = mapOf("val" to arcs.core.data.FieldType.Text),
collections = emptyMap()
),
"a90c278182b80e5275b076240966fde836108a5b",
refinementExpression = true.asExpr(),
queryExpression = true.asExpr()
)
private val nestedEntitySpecs: Map<String, arcs.sdk.EntitySpec<out arcs.sdk.Entity>> =
emptyMap()
init {
arcs.core.data.SchemaRegistry.register(SCHEMA)
}
override fun deserialize(data: arcs.core.data.RawEntity) = KotlinPrimitivesGolden_Data_Ref().apply {
deserialize(data, nestedEntitySpecs)
}
}
}
interface ThingSlice : arcs.sdk.Entity {
val name: String
}
@Suppress("UNCHECKED_CAST")
class Thing(
name: String = "",
entityId: String? = null,
creationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP,
expirationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP
) : arcs.sdk.EntityBase("Thing", SCHEMA, entityId, creationTimestamp, expirationTimestamp, false), ThingSlice {
override var name: String
get() = super.getSingletonValue("name") as String? ?: ""
private set(_value) = super.setSingletonValue("name", _value)
init {
this.name = name
}
/**
* Use this method to create a new, distinctly identified copy of the entity.
* Storing the copy will result in a new copy of the data being stored.
*/
fun copy(name: String = this.name) = Thing(name = name)
/**
* Use this method to create a new version of an existing entity.
* Storing the mutation will overwrite the existing entity in the set, if it exists.
*/
fun mutate(name: String = this.name) = Thing(
name = name,
entityId = entityId,
creationTimestamp = creationTimestamp,
expirationTimestamp = expirationTimestamp
)
companion object : arcs.sdk.EntitySpec<Thing> {
override val SCHEMA = arcs.core.data.Schema(
setOf(arcs.core.data.SchemaName("Thing")),
arcs.core.data.SchemaFields(
singletons = mapOf("name" to arcs.core.data.FieldType.Text),
collections = emptyMap()
),
"503ee2172e4a0ec16b2c7245ae8b7dd30fe9315b",
refinementExpression = true.asExpr(),
queryExpression = true.asExpr()
)
private val nestedEntitySpecs: Map<String, arcs.sdk.EntitySpec<out arcs.sdk.Entity>> =
emptyMap()
init {
arcs.core.data.SchemaRegistry.register(SCHEMA)
}
override fun deserialize(data: arcs.core.data.RawEntity) = Thing().apply {
deserialize(data, nestedEntitySpecs)
}
}
}
interface NestedSlice : arcs.sdk.Entity {
val txt: String
val num: Double
}
@Suppress("UNCHECKED_CAST")
class Nested(
txt: String = "",
num: Double = 0.0,
entityId: String? = null,
creationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP,
expirationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP
) : arcs.sdk.EntityBase("Nested", SCHEMA, entityId, creationTimestamp, expirationTimestamp, false), NestedSlice {
override var txt: String
get() = super.getSingletonValue("txt") as String? ?: ""
private set(_value) = super.setSingletonValue("txt", _value)
override var num: Double
get() = super.getSingletonValue("num") as Double? ?: 0.0
private set(_value) = super.setSingletonValue("num", _value)
init {
this.txt = txt
this.num = num
}
/**
* Use this method to create a new, distinctly identified copy of the entity.
* Storing the copy will result in a new copy of the data being stored.
*/
fun copy(txt: String = this.txt, num: Double = this.num) = Nested(txt = txt, num = num)
/**
* Use this method to create a new version of an existing entity.
* Storing the mutation will overwrite the existing entity in the set, if it exists.
*/
fun mutate(txt: String = this.txt, num: Double = this.num) = Nested(
txt = txt,
num = num,
entityId = entityId,
creationTimestamp = creationTimestamp,
expirationTimestamp = expirationTimestamp
)
companion object : arcs.sdk.EntitySpec<Nested> {
override val SCHEMA = arcs.core.data.Schema(
setOf(arcs.core.data.SchemaName("Nested")),
arcs.core.data.SchemaFields(
singletons = mapOf(
"txt" to arcs.core.data.FieldType.Text,
"num" to arcs.core.data.FieldType.Number
),
collections = emptyMap()
),
"cc2db8971fd467a8bcec2462ef805da07dd27e2d",
refinementExpression = true.asExpr(),
queryExpression = true.asExpr()
)
private val nestedEntitySpecs: Map<String, arcs.sdk.EntitySpec<out arcs.sdk.Entity>> =
emptyMap()
init {
arcs.core.data.SchemaRegistry.register(SCHEMA)
}
override fun deserialize(data: arcs.core.data.RawEntity) = Nested().apply {
deserialize(data, nestedEntitySpecs)
}
}
}
interface ColorSlice : arcs.sdk.Entity {
val red: Char
val green: Char
val blue: Char
}
@Suppress("UNCHECKED_CAST")
class Color(
red: Char = '\u0000',
green: Char = '\u0000',
blue: Char = '\u0000',
entityId: String? = null,
creationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP,
expirationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP
) : arcs.sdk.EntityBase("Color", SCHEMA, entityId, creationTimestamp, expirationTimestamp, true), ColorSlice {
override var red: Char
get() = super.getSingletonValue("red") as Char? ?: '\u0000'
private set(_value) = super.setSingletonValue("red", _value)
override var green: Char
get() = super.getSingletonValue("green") as Char? ?: '\u0000'
private set(_value) = super.setSingletonValue("green", _value)
override var blue: Char
get() = super.getSingletonValue("blue") as Char? ?: '\u0000'
private set(_value) = super.setSingletonValue("blue", _value)
init {
this.red = red
this.green = green
this.blue = blue
}
/**
* Use this method to create a new, distinctly identified copy of the entity.
* Storing the copy will result in a new copy of the data being stored.
*/
fun copy(red: Char = this.red, green: Char = this.green, blue: Char = this.blue) = Color(red = red, green = green, blue = blue)
/**
* Use this method to create a new version of an existing entity.
* Storing the mutation will overwrite the existing entity in the set, if it exists.
*/
fun mutate(red: Char = this.red, green: Char = this.green, blue: Char = this.blue) = Color(
red = red,
green = green,
blue = blue,
entityId = entityId,
creationTimestamp = creationTimestamp,
expirationTimestamp = expirationTimestamp
)
companion object : arcs.sdk.EntitySpec<Color> {
override val SCHEMA = arcs.core.data.Schema(
setOf(arcs.core.data.SchemaName("Color")),
arcs.core.data.SchemaFields(
singletons = mapOf(
"red" to arcs.core.data.FieldType.Char,
"green" to arcs.core.data.FieldType.Char,
"blue" to arcs.core.data.FieldType.Char
),
collections = emptyMap()
),
"856b4433847f0d1c74bf68871fd1c28f6cd9bf09",
refinementExpression = true.asExpr(),
queryExpression = true.asExpr()
)
private val nestedEntitySpecs: Map<String, arcs.sdk.EntitySpec<out arcs.sdk.Entity>> =
emptyMap()
init {
arcs.core.data.SchemaRegistry.register(SCHEMA)
}
override fun deserialize(data: arcs.core.data.RawEntity) = Color().apply {
deserialize(data, nestedEntitySpecs)
}
}
}
interface ProductSlice : arcs.sdk.Entity {
val name: String
val price: Float
val stock: Int
}
@Suppress("UNCHECKED_CAST")
class Product(
name: String = "",
price: Float = 0.0f,
stock: Int = 0,
entityId: String? = null,
creationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP,
expirationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP
) : arcs.sdk.EntityBase("Product", SCHEMA, entityId, creationTimestamp, expirationTimestamp, true), ProductSlice {
override var name: String
get() = super.getSingletonValue("name") as String? ?: ""
private set(_value) = super.setSingletonValue("name", _value)
override var price: Float
get() = super.getSingletonValue("price") as Float? ?: 0.0f
private set(_value) = super.setSingletonValue("price", _value)
override var stock: Int
get() = super.getSingletonValue("stock") as Int? ?: 0
private set(_value) = super.setSingletonValue("stock", _value)
init {
this.name = name
this.price = price
this.stock = stock
}
/**
* Use this method to create a new, distinctly identified copy of the entity.
* Storing the copy will result in a new copy of the data being stored.
*/
fun copy(name: String = this.name, price: Float = this.price, stock: Int = this.stock) = Product(name = name, price = price, stock = stock)
/**
* Use this method to create a new version of an existing entity.
* Storing the mutation will overwrite the existing entity in the set, if it exists.
*/
fun mutate(name: String = this.name, price: Float = this.price, stock: Int = this.stock) = Product(
name = name,
price = price,
stock = stock,
entityId = entityId,
creationTimestamp = creationTimestamp,
expirationTimestamp = expirationTimestamp
)
companion object : arcs.sdk.EntitySpec<Product> {
override val SCHEMA = arcs.core.data.Schema(
setOf(arcs.core.data.SchemaName("Product")),
arcs.core.data.SchemaFields(
singletons = mapOf(
"name" to arcs.core.data.FieldType.Text,
"price" to arcs.core.data.FieldType.Float,
"stock" to arcs.core.data.FieldType.Int
),
collections = emptyMap()
),
"887f306a04d496325b82df4a6d34473f5a738a63",
refinementExpression = true.asExpr(),
queryExpression = true.asExpr()
)
private val nestedEntitySpecs: Map<String, arcs.sdk.EntitySpec<out arcs.sdk.Entity>> =
emptyMap()
init {
arcs.core.data.SchemaRegistry.register(SCHEMA)
}
override fun deserialize(data: arcs.core.data.RawEntity) = Product().apply {
deserialize(data, nestedEntitySpecs)
}
}
}
interface DetailSlice : arcs.sdk.Entity {
val nested: Nested
val txt: String
val num: Double
}
@Suppress("UNCHECKED_CAST")
class Detail(
nested: Nested = Nested(),
txt: String = "",
num: Double = 0.0,
entityId: String? = null,
creationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP,
expirationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP
) : arcs.sdk.EntityBase("Detail", SCHEMA, entityId, creationTimestamp, expirationTimestamp, false), DetailSlice {
override var nested: Nested
get() = super.getSingletonValue("nested") as Nested? ?: Nested()
private set(_value) = super.setSingletonValue("nested", _value)
override var txt: String
get() = super.getSingletonValue("txt") as String? ?: ""
private set(_value) = super.setSingletonValue("txt", _value)
override var num: Double
get() = super.getSingletonValue("num") as Double? ?: 0.0
private set(_value) = super.setSingletonValue("num", _value)
init {
this.nested = nested
this.txt = txt
this.num = num
}
/**
* Use this method to create a new, distinctly identified copy of the entity.
* Storing the copy will result in a new copy of the data being stored.
*/
fun copy(nested: Nested = this.nested, txt: String = this.txt, num: Double = this.num) = Detail(nested = nested, txt = txt, num = num)
/**
* Use this method to create a new version of an existing entity.
* Storing the mutation will overwrite the existing entity in the set, if it exists.
*/
fun mutate(nested: Nested = this.nested, txt: String = this.txt, num: Double = this.num) = Detail(
nested = nested,
txt = txt,
num = num,
entityId = entityId,
creationTimestamp = creationTimestamp,
expirationTimestamp = expirationTimestamp
)
companion object : arcs.sdk.EntitySpec<Detail> {
override val SCHEMA = arcs.core.data.Schema(
setOf(arcs.core.data.SchemaName("Detail")),
arcs.core.data.SchemaFields(
singletons = mapOf(
"nested" to arcs.core.data.FieldType.InlineEntity("cc2db8971fd467a8bcec2462ef805da07dd27e2d"),
"txt" to arcs.core.data.FieldType.Text,
"num" to arcs.core.data.FieldType.Number
),
collections = emptyMap()
),
"7b4eb3232440af99be999e1e39982c6eba5d1125",
refinementExpression = true.asExpr(),
queryExpression = true.asExpr()
)
private val nestedEntitySpecs: Map<String, arcs.sdk.EntitySpec<out arcs.sdk.Entity>> =
mapOf("cc2db8971fd467a8bcec2462ef805da07dd27e2d" to Nested)
init {
arcs.core.data.SchemaRegistry.register(SCHEMA)
}
override fun deserialize(data: arcs.core.data.RawEntity) = Detail().apply {
deserialize(data, nestedEntitySpecs)
}
}
}
interface KotlinPrimitivesGolden_Data_Slice : arcs.sdk.Entity {
val num: Double
val txt: String
val lnk: String
val flg: Boolean
val ref: arcs.sdk.Reference<KotlinPrimitivesGolden_Data_Ref>?
val bt: Byte
val shrt: Short
val integer: Int
val long_val: Long
val big: BigInt
val instant: ArcsInstant
val chr: Char
val flt: Float
val dbl: Double
val txtlst: List<String>
val lnglst: List<Long>
val thinglst: List<arcs.sdk.Reference<Thing>>
val detail: Detail
val colors: Set<Color>
val products: List<Product>
}
@Suppress("UNCHECKED_CAST")
class KotlinPrimitivesGolden_Data(
num: Double = 0.0,
txt: String = "",
lnk: String = "",
flg: Boolean = false,
ref: arcs.sdk.Reference<KotlinPrimitivesGolden_Data_Ref>? = null,
bt: Byte = 0.toByte(),
shrt: Short = 0.toShort(),
integer: Int = 0,
long_val: Long = 0L,
big: BigInt = BigInt.ZERO,
instant: ArcsInstant = ArcsInstant.ofEpochMilli(-1L),
chr: Char = '\u0000',
flt: Float = 0.0f,
dbl: Double = 0.0,
txtlst: List<String> = emptyList(),
lnglst: List<Long> = emptyList(),
thinglst: List<arcs.sdk.Reference<Thing>> = emptyList(),
detail: Detail = Detail(),
colors: Set<Color> = emptySet(),
products: List<Product> = emptyList(),
entityId: String? = null,
creationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP,
expirationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP
) : arcs.sdk.EntityBase(
"KotlinPrimitivesGolden_Data",
SCHEMA,
entityId,
creationTimestamp,
expirationTimestamp,
false
), KotlinPrimitivesGolden_Data_Slice {
override var num: Double
get() = super.getSingletonValue("num") as Double? ?: 0.0
private set(_value) = super.setSingletonValue("num", _value)
override var txt: String
get() = super.getSingletonValue("txt") as String? ?: ""
private set(_value) = super.setSingletonValue("txt", _value)
override var lnk: String
get() = super.getSingletonValue("lnk") as String? ?: ""
private set(_value) = super.setSingletonValue("lnk", _value)
override var flg: Boolean
get() = super.getSingletonValue("flg") as Boolean? ?: false
private set(_value) = super.setSingletonValue("flg", _value)
override var ref: arcs.sdk.Reference<KotlinPrimitivesGolden_Data_Ref>?
get() = super.getSingletonValue("ref") as arcs.sdk.Reference<KotlinPrimitivesGolden_Data_Ref>?
private set(_value) = super.setSingletonValue("ref", _value)
override var bt: Byte
get() = super.getSingletonValue("bt") as Byte? ?: 0.toByte()
private set(_value) = super.setSingletonValue("bt", _value)
override var shrt: Short
get() = super.getSingletonValue("shrt") as Short? ?: 0.toShort()
private set(_value) = super.setSingletonValue("shrt", _value)
override var integer: Int
get() = super.getSingletonValue("integer") as Int? ?: 0
private set(_value) = super.setSingletonValue("integer", _value)
override var long_val: Long
get() = super.getSingletonValue("long_val") as Long? ?: 0L
private set(_value) = super.setSingletonValue("long_val", _value)
override var big: BigInt
get() = super.getSingletonValue("big") as BigInt? ?: BigInt.ZERO
private set(_value) = super.setSingletonValue("big", _value)
override var instant: ArcsInstant
get() = super.getSingletonValue("instant") as ArcsInstant? ?: ArcsInstant.ofEpochMilli(-1L)
private set(_value) = super.setSingletonValue("instant", _value)
override var chr: Char
get() = super.getSingletonValue("chr") as Char? ?: '\u0000'
private set(_value) = super.setSingletonValue("chr", _value)
override var flt: Float
get() = super.getSingletonValue("flt") as Float? ?: 0.0f
private set(_value) = super.setSingletonValue("flt", _value)
override var dbl: Double
get() = super.getSingletonValue("dbl") as Double? ?: 0.0
private set(_value) = super.setSingletonValue("dbl", _value)
override var txtlst: List<String>
get() = super.getSingletonValue("txtlst") as List<String>? ?: emptyList()
private set(_value) = super.setSingletonValue("txtlst", _value)
override var lnglst: List<Long>
get() = super.getSingletonValue("lnglst") as List<Long>? ?: emptyList()
private set(_value) = super.setSingletonValue("lnglst", _value)
override var thinglst: List<arcs.sdk.Reference<Thing>>
get() = super.getSingletonValue("thinglst") as List<arcs.sdk.Reference<Thing>>? ?: emptyList()
private set(_value) = super.setSingletonValue("thinglst", _value)
override var detail: Detail
get() = super.getSingletonValue("detail") as Detail? ?: Detail()
private set(_value) = super.setSingletonValue("detail", _value)
override var colors: Set<Color>
get() = super.getCollectionValue("colors") as Set<Color>
private set(_value) = super.setCollectionValue("colors", _value)
override var products: List<Product>
get() = super.getSingletonValue("products") as List<Product>? ?: emptyList()
private set(_value) = super.setSingletonValue("products", _value)
init {
this.num = num
this.txt = txt
this.lnk = lnk
this.flg = flg
this.ref = ref
this.bt = bt
this.shrt = shrt
this.integer = integer
this.long_val = long_val
this.big = big
this.instant = instant
this.chr = chr
this.flt = flt
this.dbl = dbl
this.txtlst = txtlst
this.lnglst = lnglst
this.thinglst = thinglst
this.detail = detail
this.colors = colors
this.products = products
}
/**
* Use this method to create a new, distinctly identified copy of the entity.
* Storing the copy will result in a new copy of the data being stored.
*/
fun copy(
num: Double = this.num,
txt: String = this.txt,
lnk: String = this.lnk,
flg: Boolean = this.flg,
ref: arcs.sdk.Reference<KotlinPrimitivesGolden_Data_Ref>? = this.ref,
bt: Byte = this.bt,
shrt: Short = this.shrt,
integer: Int = this.integer,
long_val: Long = this.long_val,
big: BigInt = this.big,
instant: ArcsInstant = this.instant,
chr: Char = this.chr,
flt: Float = this.flt,
dbl: Double = this.dbl,
txtlst: List<String> = this.txtlst,
lnglst: List<Long> = this.lnglst,
thinglst: List<arcs.sdk.Reference<Thing>> = this.thinglst,
detail: Detail = this.detail,
colors: Set<Color> = this.colors,
products: List<Product> = this.products
) = KotlinPrimitivesGolden_Data(
num = num,
txt = txt,
lnk = lnk,
flg = flg,
ref = ref,
bt = bt,
shrt = shrt,
integer = integer,
long_val = long_val,
big = big,
instant = instant,
chr = chr,
flt = flt,
dbl = dbl,
txtlst = txtlst,
lnglst = lnglst,
thinglst = thinglst,
detail = detail,
colors = colors,
products = products
)
/**
* Use this method to create a new version of an existing entity.
* Storing the mutation will overwrite the existing entity in the set, if it exists.
*/
fun mutate(
num: Double = this.num,
txt: String = this.txt,
lnk: String = this.lnk,
flg: Boolean = this.flg,
ref: arcs.sdk.Reference<KotlinPrimitivesGolden_Data_Ref>? = this.ref,
bt: Byte = this.bt,
shrt: Short = this.shrt,
integer: Int = this.integer,
long_val: Long = this.long_val,
big: BigInt = this.big,
instant: ArcsInstant = this.instant,
chr: Char = this.chr,
flt: Float = this.flt,
dbl: Double = this.dbl,
txtlst: List<String> = this.txtlst,
lnglst: List<Long> = this.lnglst,
thinglst: List<arcs.sdk.Reference<Thing>> = this.thinglst,
detail: Detail = this.detail,
colors: Set<Color> = this.colors,
products: List<Product> = this.products
) = KotlinPrimitivesGolden_Data(
num = num,
txt = txt,
lnk = lnk,
flg = flg,
ref = ref,
bt = bt,
shrt = shrt,
integer = integer,
long_val = long_val,
big = big,
instant = instant,
chr = chr,
flt = flt,
dbl = dbl,
txtlst = txtlst,
lnglst = lnglst,
thinglst = thinglst,
detail = detail,
colors = colors,
products = products,
entityId = entityId,
creationTimestamp = creationTimestamp,
expirationTimestamp = expirationTimestamp
)
companion object : arcs.sdk.EntitySpec<KotlinPrimitivesGolden_Data> {
override val SCHEMA = arcs.core.data.Schema(
setOf(),
arcs.core.data.SchemaFields(
singletons = mapOf(
"num" to arcs.core.data.FieldType.Number,
"txt" to arcs.core.data.FieldType.Text,
"lnk" to arcs.core.data.FieldType.Text,
"flg" to arcs.core.data.FieldType.Boolean,
"ref" to arcs.core.data.FieldType.EntityRef("a90c278182b80e5275b076240966fde836108a5b"),
"bt" to arcs.core.data.FieldType.Byte,
"shrt" to arcs.core.data.FieldType.Short,
"integer" to arcs.core.data.FieldType.Int,
"long_val" to arcs.core.data.FieldType.Long,
"big" to arcs.core.data.FieldType.BigInt,
"instant" to arcs.core.data.FieldType.Instant,
"chr" to arcs.core.data.FieldType.Char,
"flt" to arcs.core.data.FieldType.Float,
"dbl" to arcs.core.data.FieldType.Double,
"txtlst" to arcs.core.data.FieldType.ListOf(arcs.core.data.FieldType.Text),
"lnglst" to arcs.core.data.FieldType.ListOf(arcs.core.data.FieldType.Long),
"thinglst" to arcs.core.data.FieldType.ListOf(arcs.core.data.FieldType.EntityRef("503ee2172e4a0ec16b2c7245ae8b7dd30fe9315b")),
"detail" to arcs.core.data.FieldType.InlineEntity("7b4eb3232440af99be999e1e39982c6eba5d1125"),
"products" to arcs.core.data.FieldType.ListOf(arcs.core.data.FieldType.InlineEntity("887f306a04d496325b82df4a6d34473f5a738a63"))
),
collections = mapOf(
"colors" to arcs.core.data.FieldType.InlineEntity("856b4433847f0d1c74bf68871fd1c28f6cd9bf09")
)
),
"e18bc5fd75a1244d8a04cfd965ed3ea66a2dd226",
refinementExpression = (((lookup<Number>("num") lt 1000.asExpr()) and (((lookup<Number>("long_val") lt NumberLiteralExpression(BigInt("100000"))) and ((lookup<Number>("long_val") gt NumberLiteralExpression(BigInt("10000"))) or (lookup<Number>("long_val") eq NumberLiteralExpression(BigInt("10000"))))) and ((lookup<Number>("integer") gt NumberLiteralExpression(BigInt("2"))) and (lookup<Number>("big") gt NumberLiteralExpression(BigInt("1")))))) and ((lookup<Number>("expirationTime()") gt lookup<Number>("creationTime()")) and ((now() gt lookup<Number>("creationTime()")) and (lookup<Number>("instant") lt (now() - NumberLiteralExpression(BigInt("259200000"))))))),
queryExpression = true.asExpr()
)
private val nestedEntitySpecs: Map<String, arcs.sdk.EntitySpec<out arcs.sdk.Entity>> =
mapOf(
"a90c278182b80e5275b076240966fde836108a5b" to KotlinPrimitivesGolden_Data_Ref,
"503ee2172e4a0ec16b2c7245ae8b7dd30fe9315b" to Thing,
"7b4eb3232440af99be999e1e39982c6eba5d1125" to Detail,
"856b4433847f0d1c74bf68871fd1c28f6cd9bf09" to Color,
"887f306a04d496325b82df4a6d34473f5a738a63" to Product
)
init {
arcs.core.data.SchemaRegistry.register(SCHEMA)
}
override fun deserialize(data: arcs.core.data.RawEntity) = KotlinPrimitivesGolden_Data().apply {
deserialize(data, nestedEntitySpecs)
}
}
}
class Handles : arcs.sdk.HandleHolderBase(
"KotlinPrimitivesGolden",
mapOf("data" to setOf(KotlinPrimitivesGolden_Data))
) {
val data: arcs.sdk.ReadSingletonHandle<KotlinPrimitivesGolden_Data> by handles
}
}
| bsd-3-clause | ec63d7c9b20de6843e66db7a52e0965f | 40.834387 | 690 | 0.585658 | 4.374223 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/component/HorizontalScrollBarBuilder.kt | 1 | 1291 | package org.hexworks.zircon.api.builder.component
import org.hexworks.zircon.api.component.ScrollBar
import org.hexworks.zircon.internal.component.impl.DefaultHorizontalScrollBar
import org.hexworks.zircon.internal.component.renderer.HorizontalScrollBarRenderer
import org.hexworks.zircon.internal.dsl.ZirconDsl
import kotlin.jvm.JvmStatic
/**
* Builder for a horizontal [ScrollBar]. By default, it creates a [ScrollBar] with
* - [itemsShownAtOnce]: `1`
* - [numberOfScrollableItems]: `100`
*/
@ZirconDsl
class HorizontalScrollBarBuilder private constructor() :
ScrollBarBuilder<ScrollBar, HorizontalScrollBarBuilder>(HorizontalScrollBarRenderer()) {
override fun build(): ScrollBar = DefaultHorizontalScrollBar(
componentMetadata = createMetadata(),
renderingStrategy = createRenderingStrategy(),
minValue = 0,
maxValue = numberOfScrollableItems,
itemsShownAtOnce = size.width,
numberOfSteps = size.width,
).attachListeners()
override fun createCopy() = newBuilder()
.withProps(props.copy())
.withItemsShownAtOnce(itemsShownAtOnce)
.withNumberOfScrollableItems(numberOfScrollableItems)
companion object {
@JvmStatic
fun newBuilder() = HorizontalScrollBarBuilder()
}
}
| apache-2.0 | 572cc162fb33e6f633d0536b8ceec5f9 | 33.891892 | 92 | 0.745159 | 4.763838 | false | false | false | false |
AcornUI/Acorn | acornui-core/src/main/kotlin/com/acornui/input/KeyToMouseBinding.kt | 1 | 4602 | /*
* Copyright 2020 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.
*/
@file:Suppress("UNUSED_PARAMETER")
package com.acornui.input
import com.acornui.Disposable
import com.acornui.collection.Filter
import com.acornui.component.UiComponent
import com.acornui.di.ContextImpl
import com.acornui.dom.handle
import com.acornui.dom.isFabricated
import com.acornui.dom.isHandled
import com.acornui.own
import com.acornui.signal.EventOptions
import com.acornui.signal.asWithEventTarget
import org.w3c.dom.events.EventTarget
import org.w3c.dom.events.KeyboardEvent
import org.w3c.dom.events.MouseEvent
import org.w3c.dom.events.MouseEventInit
import kotlinx.browser.window
/**
* Dispatches mouse events when using SPACE or ENTER key presses on the focused element.
*/
class KeyToMouseBinding(
host: UiComponent
) : ContextImpl(host) {
/**
* The filter for a key down interaction to determine if the mouse event should be triggered.
* Default is:
* `!event.hasAnyModifier && (event.keyCode == Ascii.SPACE || event.isEnterOrReturn)`
*/
var filter: Filter<KeyboardEvent> = { event ->
!event.hasAnyModifier && (event.keyCode == Ascii.SPACE || event.isEnterOrReturn)
}
private val win = window.asWithEventTarget()
init {
own(host.keyPressed.listen(EventOptions(isPassive = false), ::keyDownHandler))
}
private fun keyDownHandler(event: KeyboardEvent) {
if (event.isHandled) return
val isRepeat = event.repeat //&& target.downRepeatEnabled()
if ((downKey == null || isRepeat) && filter(event)) {
event.handle()
downKey = event.keyCode
val e = dispatchFakeMouseEvent(event.target!!, "mousedown")
if (e.isHandled)
event.handle()
event.preventDefault() // Prevent SPACE from scrolling, ENTER from navigating href, etc.
}
}
private fun keyUpHandler(event: KeyboardEvent) {
if (event.keyCode == downKey) {
event.handle()
downKey = null
val e = dispatchFakeMouseEvent(event.target!!, "mouseup")
if (e.isHandled)
event.handle()
if (e.defaultPrevented)
event.preventDefault()
dispatchFakeMouseEvent(event.target!!, "click")
}
}
private var keyUpWatch: Disposable? = null
private var downKey: Int? = null
set(value) {
val old = field
if (old == value) return
field = value
if ((old == null) != (value == null)) {
if (value != null)
keyUpWatch = win.keyReleased.listen(::keyUpHandler)
else
keyUpWatch?.dispose()
}
}
private fun dispatchFakeMouseEvent(target: EventTarget, type: String): MouseEvent {
val event = MouseEvent(type, MouseEventInit(button = WhichButton.LEFT, bubbles = true))
event.isFabricated = true
target.dispatchEvent(event)
return event
}
override fun dispose() {
downKey = null
super.dispose()
}
}
/**
* If ENTER, RETURN, or SPACE is pressed on the host, the host will receive a fabricated mouse event.
* @return Returns the binding, which may be disposed.
*/
fun UiComponent.mousePressOnKey(): KeyToMouseBinding {
return KeyToMouseBinding(this)
}
// TODO: Enter Target
///**
// * If an unhandled ENTER or RETURN is pressed on the host, the target will receive a fabricated click event.
// */
//class EnterTargetClickBinding(val host: UiComponent, var target: UiComponent?) : ManagedDisposable, DisposableBase() {
//
// private val stage = host.stage
//
// init {
// host.ownThis()
// own(stage.keyUp.listen(::stageKeyUpHandler))
// }
//
// private fun stageKeyUpHandler(event: KeyboardEvent) {
// if (!event.isHandled && !event.hasAnyModifier && event.isEnterOrReturn && host.isAncestorOf(event.target)) {
// target?.dispatchClick()
// }
// }
//
// override fun dispose() {
// super.dispose()
// target = null
//
// }
//}
//
///**
// * If ENTER or RETURN is pressed on the receiver, the target will receive a fabricated click event.
// * @return Returns a handle to dispose the binding or change the target. This will automatically be disposed when this
// * host is disposed.
// */
//fun UiComponent.enterTarget(target: UiComponent): EnterTargetClickBinding {
// return EnterTargetClickBinding(this, target)
//}
| apache-2.0 | b3525a01cd62eb9feadade5fbc4e6abd | 29.078431 | 120 | 0.720774 | 3.545455 | false | false | false | false |
nearbydelta/KoreanAnalyzer | rhino/src/main/kotlin/kr/bydelta/koala/rhino/proc.kt | 1 | 6837 | @file:JvmName("Util")
@file:JvmMultifileClass
package kr.bydelta.koala.rhino
import kr.bydelta.koala.POS
import kr.bydelta.koala.data.Morpheme
import kr.bydelta.koala.data.Sentence
import kr.bydelta.koala.data.Word
import kr.bydelta.koala.proc.CanExtractResource
import kr.bydelta.koala.proc.CanTagOnlyASentence
import rhino.FileAnalyzer
import rhino.RHINO
import rhino.datastructure.TST
import java.io.File
/**
* RHINO Resource를 불러들이는 부분입니다.
* 이 코드의 원본은 rhino.ExternInit 및 rhino.SetFileLists입니다.
*/
internal object RHINOTagger : CanExtractResource() {
override val modelName: String = "rhino"
@JvmStatic
val MORPH_MATCH = "([^\\s]+)/\\s*([A-Z]{2,3})".toRegex()
@JvmStatic
internal val tagger by lazy {
val fa = FileAnalyzer(RHINOTagger.getExtractedPath() + File.separator)
val coM = fa.MakeMethodsList("rhino.lexicon.combi.combi")
val ssM = fa.MakeMethodsList("rhino.lexicon.stem.stem")
val eM = fa.MakeMethodsList("rhino.lexicon.ending.ending")
val csN = fa.MakeFileAllContentsArray("complexStem_MethodDeleted.txt", 2)
val ssN = fa.MakeFileAllContentsArray("stem_MethodDeleted.txt", 2)
val eN = fa.MakeFileAllContentsArray("ending_MethodDeleted.txt", 3)
val anN = fa.MakeFileAllContentsArray("afterNumber_MethodDeleted.txt", 2)
val kN = fa.MakeFileAllContentsArray("koreanName.txt", 2)
val alsoxr = fa.MakeFileAllContentsArray("alsoXR.txt", 2)
// Initialize static variables in RHINO
RHINO.combi = TST()
RHINO.stem = TST()
RHINO.stemR = TST()
RHINO.stemM = TST()
RHINO.endingR = TST()
RHINO.endingM = TST()
RHINO.afterNum = TST()
RHINO.koreanName = TST()
RHINO.alsoXR = TST()
coM.forEach { RHINO.combi.insert(it, "coM") }
ssM.forEach { RHINO.stem.insert(it, "ssM") }
ssM.forEach { RHINO.stemR.insertR(it, "ssM", "N") }
ssM.forEach { RHINO.stemM.insert(it, "ssM") }
eM.forEach { RHINO.endingR.insertR(it, "eM", "N") }
eM.forEach { RHINO.endingM.insertR(it, "eM", "N") }
csN.forEach { RHINO.stem.insert(it[0], it[1]) }
csN.forEach { RHINO.stemR.insertR(it[0], it[1], "N") }
ssN.forEach { RHINO.stem.insert(it[0], it[1]) }
ssN.forEach { RHINO.stemR.insertR(it[0], it[1], "N") }
eN.forEach { RHINO.endingR.insertR(it[0], it[1], it[2]) }
anN.forEach { RHINO.afterNum.insert(it[0], it[1]) }
kN.forEach { RHINO.koreanName.insert(it[0], it[1]) }
alsoxr.forEach { RHINO.stem.insert(it[0], it[1]) }
alsoxr.forEach { RHINO.stemR.insertR(it[0], it[1], "N") }
RHINO()
}
@JvmStatic
internal fun tag(string: String): Sentence {
val wordsWithoutSpecials = synchronized(tagger) {
tagger.ExternCall(string).trim().split("\n").map { word ->
val (surface, morphemesString) = word.trim().split("\t")
val morphemes = translateOutputMorpheme(morphemesString)
Word(surface, morphemes)
}
}
// Rhino 특수문자 복원 전까지 수동 복원
val words = mutableListOf<Word>()
var remainingString = string
var wordId = 0
while (remainingString.isNotEmpty()) {
if (remainingString.startsWith(wordsWithoutSpecials[wordId].surface)) {
words.add(wordsWithoutSpecials[wordId])
remainingString = remainingString.substring(wordsWithoutSpecials[wordId].surface.length)
wordId += 1
} else {
val char = remainingString.substring(0, 1)
words.add(Word(char, listOf(Morpheme(surface = char, tag = POS.SW, originalTag = ""))))
remainingString = remainingString.substring(1)
}
}
return Sentence(words.toList())
}
@JvmStatic
private fun translateOutputMorpheme(morphStr: String) =
MORPH_MATCH.findAll(morphStr).map {
val surf = it.groupValues[1]
val raw = it.groupValues[2]
Morpheme(surf.trim(), POS.valueOf(raw), raw)
}.toList()
}
/**
* 라이노 형태소 분석기의 KoalaNLP Wrapper입니다.
*
* ## 참고
* **형태소**는 의미를 가지는 요소로서는 더 이상 분석할 수 없는 가장 작은 말의 단위로 정의됩니다.
*
* **형태소 분석**은 문장을 형태소의 단위로 나누는 작업을 의미합니다.
* 예) '문장을 형태소로 나눠봅시다'의 경우,
* * 문장/일반명사, -을/조사,
* * 형태소/일반명사, -로/조사,
* * 나누-(다)/동사, -어-/어미, 보-(다)/동사, -ㅂ시다/어미
* 로 대략 나눌 수 있습니다.
*
* 아래를 참고해보세요.
* * [Morpheme] 형태소를 저장하는 클래스입니다.
* * [POS] 형태소의 분류를 담은 Enum class
*
* ## 사용법 예제
*
* ### Kotlin
* ```kotlin
* val tagger = Tagger()
* val sentence = tagger.tagSentence("문장 1개입니다.")
* val sentences = tagger.tag("문장들입니다. 결과는 목록이 됩니다.")
* // 또는
* val sentences = tagger("문장들입니다. 결과는 목록이 됩니다.")
* ```
*
* ### Scala + [koalanlp-scala](https://koalanlp.github.io/scala-support/)
* ```scala
* import kr.bydelta.koala.Implicits._
* val tagger = new Tagger()
* val sentence = tagger.tagSentence("문장 1개입니다.")
* val sentences = tagger.tag("문장들입니다. 결과는 목록이 됩니다.")
* // 또는
* val sentences = tagger("문장들입니다. 결과는 목록이 됩니다.")
* ```
*
* ### Java
* ```java
* Tagger tagger = new Tagger()
* Sentence sentence = tagger.tagSentence("문장 1개입니다.")
* List<Sentence> sentences = tagger.tag("문장들입니다. 결과는 목록이 됩니다.")
* // 또는
* List<Sentence> sentences = tagger.invoke("문장들입니다. 결과는 목록이 됩니다.")
* ```
*
* @since 1.x
*/
class Tagger : CanTagOnlyASentence<List<Word>>() {
/**
* 변환되지않은, [text]의 분석결과 List<Word>를 반환합니다.
*
* @since 1.x
* @param text 분석할 String.
* @return 원본 분석기의 결과인 문장 1개
*/
override fun tagSentenceOriginal(text: String): List<Word> {
return RHINOTagger.tag(text)
}
/**
* List<Word> 타입의 분석결과 [result]를 변환, [Sentence]를 구성합니다.
*
* @since 1.x
* @param text 품사분석을 수행한 문단의 String입니다.
* @param result 변환할 분석결과.
* @return 변환된 [Sentence] 객체
*/
override fun convertSentence(text: String, result: List<Word>): Sentence {
return Sentence(result)
}
} | gpl-3.0 | b0828a55f1040719a3f60c00ab00363c | 32.153846 | 104 | 0.607989 | 2.807352 | false | false | false | false |
ingokegel/intellij-community | plugins/git4idea/src/git4idea/repo/GitSubmodule.kt | 12 | 1668 | // 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 git4idea.repo
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.vfs.VfsUtil
private val LOG = logger<GitSubmodule>()
class GitSubmodule(
val repository: GitRepository,
val parent: GitRepository)
fun GitRepository.asSubmodule() : GitSubmodule? {
val repositoryManager = GitRepositoryManager.getInstance(project)
val parent = repositoryManager.repositories.find { it.isParentRepositoryFor(this) }
return if (parent != null) GitSubmodule(this, parent) else null
}
private fun GitRepository.isParentRepositoryFor(submodule: GitRepository): Boolean {
return VfsUtil.isAncestor(root, submodule.root, true) &&
submodules.isNotEmpty() &&
runReadAction { submodules.any { module -> root.findFileByRelativePath(module.path) == submodule.root } }
}
fun GitRepository.isSubmodule(): Boolean = asSubmodule() != null
fun GitRepository.getDirectSubmodules(): Collection<GitRepository> {
return submodules.mapNotNull { module ->
val submoduleDir = runReadAction { root.findFileByRelativePath(module.path) }
if (submoduleDir == null) {
LOG.debug("submodule dir not found at declared path [${module.path}] of root [$root]")
return@mapNotNull null
}
val repository = GitRepositoryManager.getInstance(project).getRepositoryForRoot(submoduleDir)
if (repository == null) {
LOG.warn("Submodule not registered as a repository: $submoduleDir")
}
return@mapNotNull repository
}
}
| apache-2.0 | 64f72364fa64f1ef158a1e91117766a5 | 39.682927 | 140 | 0.754796 | 4.520325 | false | false | false | false |
squanchy-dev/squanchy-android | app/src/main/java/net/squanchy/analytics/DisabledAnalytics.kt | 1 | 1682 | package net.squanchy.analytics
import android.app.Activity
import net.squanchy.signin.SignInOrigin
import net.squanchy.wificonfig.WifiConfigOrigin
import timber.log.Timber
class DisabledAnalytics : Analytics {
override fun initializeStaticUserProperties() = Unit
override fun trackPageView(activity: Activity, screenName: String, screenClassOverride: String?) = Unit
override fun trackPageViewOnFirebaseAnalytics(activity: Activity, screenName: String, screenClassOverride: String?) = Unit
override fun trackPageViewOnCrashlytics(screenName: String) = Unit
override fun trackItemSelected(contentType: ContentType, itemId: String) = Unit
override fun trackItemSelectedOnFirebaseAnalytics(contentType: ContentType, itemId: String) = Unit
override fun trackItemSelectedOnCrashlytics(contentType: ContentType, itemId: String) = Unit
override fun setupExceptionLogging() {
Timber.forest()
.find { it is CrashlyticsErrorsTree }
?.let { Timber.uproot(it) }
}
override fun trackFirstStartUserNotLoggedIn() = Unit
override fun trackFirstStartNotificationsEnabled() = Unit
override fun trackNotificationsEnabled() = Unit
override fun trackNotificationsDisabled() = Unit
override fun trackFavoritesInScheduleEnabled() = Unit
override fun trackFavoritesInScheduleDisabled() = Unit
override fun trackUserNotLoggedIn() = Unit
override fun trackUserLoggedInFrom(signInOrigin: SignInOrigin) = Unit
override fun setUserLoginProperty(loginStatus: LoginStatus) = Unit
override fun trackWifiConfigurationEvent(isSuccess: Boolean, wifiConfigOrigin: WifiConfigOrigin) = Unit
}
| apache-2.0 | 3489f21f2f056131af6c4f7a9981a91e | 34.041667 | 126 | 0.774673 | 5.066265 | false | true | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/chapter-4/app/src/main/java/dev/mfazio/pennydrop/game/AI.kt | 2 | 958 | package dev.mfazio.pennydrop.game
import dev.mfazio.pennydrop.types.Slot
import dev.mfazio.pennydrop.types.fullSlots
data class AI(val name: String, val rollAgain: (slots: List<Slot>) -> Boolean) {
override fun toString() = name
companion object {
@JvmStatic
val basicAI = listOf(
AI("TwoFace") { slots -> slots.fullSlots() < 3 || (slots.fullSlots() == 3 && coinFlipIsHeads()) },
AI("No Go Noah") { slots -> slots.fullSlots() == 0 },
AI("Bail Out Beulah") { slots -> slots.fullSlots() <= 1 },
AI("Fearful Fred") { slots -> slots.fullSlots() <= 2 },
AI("Even Steven") { slots -> slots.fullSlots() <= 3 },
AI("Riverboat Ron") { slots -> slots.fullSlots() <= 4 },
AI("Sammy Sixes") { slots -> slots.fullSlots() <= 5 },
AI("Random Rachael") { coinFlipIsHeads() }
)
}
}
fun coinFlipIsHeads() = (Math.random() * 2).toInt() == 0 | apache-2.0 | 460f38bbb2889df2832de6f3acd92f45 | 37.36 | 110 | 0.56263 | 3.561338 | false | false | false | false |
JavaEden/Orchid-Core | plugins/OrchidSnippets/src/main/kotlin/adapter/EmbeddedSnippetsAdapter.kt | 2 | 4919 | package com.eden.orchid.snippets.adapter
import com.caseyjbrooks.clog.Clog
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.annotations.BooleanDefault
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.IntDefault
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.api.resources.resource.OrchidResource
import com.eden.orchid.api.resources.resource.StringResource
import com.eden.orchid.api.resources.resourcesource.LocalResourceSource
import com.eden.orchid.api.theme.pages.OrchidReference
import com.eden.orchid.snippets.models.SnippetConfig
import com.eden.orchid.utilities.readToString
@Description("Scan through files using regex to locate multiple snippets embedded inside each")
class EmbeddedSnippetsAdapter : SnippetsAdapter {
override fun getType(): String = "embedded"
@Option
@Description("The base directory in resources to look for snippets files in.")
@StringDefault("snippets")
lateinit var baseDirs: List<String>
@Option
@Description("File extensions to filter resources by.")
lateinit var fileExtensions: List<String>
@Option
@BooleanDefault(true)
@Description("Whether to search recursively")
var recursive: Boolean = true
@Option
@StringDefault("""^.*?snippet::(.+?)\[(.*?)]\s*?${'$'}""")
lateinit var startPattern: String
@Option
@StringDefault("""^.*?end::(.+?)?\s*?${'$'}""")
lateinit var endPattern: String
@Option
@IntDefault(1)
var patternNameGroup: Int = 1
@Option
@IntDefault(2)
var patternTagGroup: Int = 2
override fun addSnippets(context: OrchidContext): Sequence<SnippetConfig> = sequence {
baseDirs.forEach { baseDir ->
addSnippetsInDir(context, baseDir)
}
}
private suspend fun SequenceScope<SnippetConfig>.addSnippetsInDir(context: OrchidContext, baseDir: String) {
context
.getDefaultResourceSource(LocalResourceSource, null)
.getResourceEntries(
context,
baseDir,
fileExtensions.takeIf { it.isNotEmpty() }?.toTypedArray(),
recursive
)
.forEach {
addSnippet(context, it)
}
}
private suspend fun SequenceScope<SnippetConfig>.addSnippet(context: OrchidContext, resource: OrchidResource) {
val tagStartRegex = startPattern.toRegex()
val tagEndRegex = endPattern.toRegex()
val content = resource.getContentStream().readToString() ?: ""
val tagStack = mutableListOf<EmbeddedSnippet>()
content.lineSequence().forEachIndexed { lineIndex, line ->
val tagStartMatch = tagStartRegex.matchEntire(line)
val tagEndMatch = tagEndRegex.matchEntire(line)
if (tagStartMatch != null) {
val snippetName = tagStartMatch.groupValues[patternNameGroup].trim()
val tags = if (tagStartMatch.groupValues.size >= patternTagGroup + 1) {
tagStartMatch.groupValues[patternTagGroup].split(",").map { it.trim() }.dropWhile { it.isEmpty() }
} else {
emptyList()
}
tagStack.add(EmbeddedSnippet(snippetName, tags))
} else if (tagEndMatch != null) {
val snippetName = tagEndMatch.groupValues[patternNameGroup].trim()
val lastSnippet = if(tagStack.isNotEmpty()) {
tagStack.removeAt(tagStack.lastIndex)
} else null
if(lastSnippet != null) {
if(snippetName.isEmpty() || lastSnippet.name == snippetName) {
val snippetResource = StringResource(
OrchidReference(resource.reference),
lastSnippet.lines.joinToString(separator = "\n").trimIndent()
)
yield(
SnippetConfig(
context,
lastSnippet.name,
lastSnippet.tags,
snippetResource
)
)
}
else {
Clog.e("Mismatched snippet groups at line $lineIndex: expected close of '${lastSnippet.name}', found '$snippetName'")
}
}
} else {
if (tagStack.isNotEmpty()) {
tagStack.last().lines.add(line)
}
}
}
}
private data class EmbeddedSnippet(
val name: String,
val tags: List<String>,
val lines: MutableList<String> = mutableListOf()
)
}
| mit | 99a051f761f7c8d4ec668b78bbc5e689 | 35.708955 | 141 | 0.59565 | 5.055498 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/entity/settings/SettingType.kt | 4 | 7543 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.core.entity.settings
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.*
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem
import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
sealed class SettingType<out V : Any> {
abstract fun parse(context: ParsingContext, value: Any, name: String): TaskResult<V>
open val serializer: SettingSerializer<V> = SettingSerializer.None
}
object StringSettingType : SettingType<String>() {
override fun parse(context: ParsingContext, value: Any, name: String) =
value.parseAs<String>(name)
override val serializer: SettingSerializer<String> =
SettingSerializer.Serializer(fromString = { it })
class Builder(
path: String,
val title: String,
neededAtPhase: GenerationPhase
) : SettingBuilder<String, StringSettingType>(path, title, neededAtPhase) {
fun shouldNotBeBlank() {
validate(StringValidators.shouldNotBeBlank(title.capitalize()))
}
override val type = StringSettingType
}
}
object BooleanSettingType : SettingType<Boolean>() {
override fun parse(context: ParsingContext, value: Any, name: String) =
value.parseAs<Boolean>(name)
override val serializer: SettingSerializer<Boolean> =
SettingSerializer.Serializer(fromString = { it.toBoolean() })
class Builder(
path: String,
title: String,
neededAtPhase: GenerationPhase
) : SettingBuilder<Boolean, BooleanSettingType>(path, title, neededAtPhase) {
override val type = BooleanSettingType
}
}
class DropDownSettingType<V : DisplayableSettingItem>(
val values: List<V>,
val filter: DropDownSettingTypeFilter<V>,
val parser: Parser<V>
) : SettingType<V>() {
override fun parse(context: ParsingContext, value: Any, name: String): TaskResult<V> = with(context) {
computeM {
parser.parse(this, value, name)
}
}
override val serializer: SettingSerializer<V> =
SettingSerializer.Serializer(fromString = { value ->
ComputeContext.runInComputeContextWithState(
ParsingState.EMPTY
) {
parser.parse(this, value, "")
}.asNullable?.first
})
class Builder<V : DisplayableSettingItem>(
path: String,
title: String,
neededAtPhase: GenerationPhase,
private val parser: Parser<V>
) : SettingBuilder<V, DropDownSettingType<V>>(path, title, neededAtPhase) {
var values = emptyList<V>()
var filter: DropDownSettingTypeFilter<V> = { _, _ -> true }
override val type
get() = DropDownSettingType(
values,
filter,
parser
)
init {
defaultValue = dynamic { reference ->
values.first {
@Suppress("UNCHECKED_CAST")
filter(reference as SettingReference<V, DropDownSettingType<V>>, it)
}
}
}
}
}
class ValueSettingType<V : Any>(
private val parser: Parser<V>
) : SettingType<V>() {
override fun parse(context: ParsingContext, value: Any, name: String): TaskResult<V> = with(context) {
computeM {
parser.parse(this, value, name)
}
}
class Builder<V : Any>(
private val path: String,
title: String,
neededAtPhase: GenerationPhase,
private val parser: Parser<V>
) : SettingBuilder<V, ValueSettingType<V>>(path, title, neededAtPhase) {
init {
validate { value ->
if (value is Validatable<*>) (value.validator as SettingValidator<Any>).validate(this, value)
else ValidationResult.OK
}
}
override val type
get() = ValueSettingType(parser)
}
}
object VersionSettingType : SettingType<Version>() {
override fun parse(context: ParsingContext, value: Any, name: String): TaskResult<Version> = with(context) {
computeM {
Version.parser.parse(this, value, name)
}
}
class Builder(
path: String,
title: String,
neededAtPhase: GenerationPhase
) : SettingBuilder<Version, VersionSettingType>(path, title, neededAtPhase) {
override val type
get() = VersionSettingType
}
}
class ListSettingType<V : Any>(private val parser: Parser<V>) : SettingType<List<V>>() {
override fun parse(context: ParsingContext, value: Any, name: String): TaskResult<List<V>> = with(context) {
computeM {
val (list) = value.parseAs<List<*>>(name)
list.mapComputeM { parser.parse(this, it, name) }.sequence()
}
}
class Builder<V : Any>(
path: String,
title: String,
neededAtPhase: GenerationPhase,
parser: Parser<V>
) : SettingBuilder<List<V>, ListSettingType<V>>(path, title, neededAtPhase) {
init {
validate { values ->
values.fold(ValidationResult.OK as ValidationResult) { result, value ->
result and when (value) {
is Validatable<*> -> (value.validator as SettingValidator<Any>).validate(this, value).withTargetIfNull(value)
else -> ValidationResult.OK
}
}
}
}
override val type = ListSettingType(parser)
}
}
object PathSettingType : SettingType<Path>() {
override fun parse(context: ParsingContext, value: Any, name: String): TaskResult<Path> = with(context) {
computeM {
pathParser.parse(this, value, name)
}
}
override val serializer: SettingSerializer<Path> =
SettingSerializer.Serializer(fromString = { Paths.get(it) })
class Builder(
path: String,
private val title: String,
neededAtPhase: GenerationPhase
) : SettingBuilder<Path, PathSettingType>(path, title, neededAtPhase) {
init {
validate { pathValue ->
if (pathValue.toString().isBlank())
ValidationResult.ValidationError(
KotlinNewProjectWizardBundle.message(
"validation.should.not.be.blank",
title.capitalize()
)
)
else ValidationResult.OK
}
}
fun shouldExists() = validate { pathValue ->
if (isUnitTestMode) return@validate ValidationResult.OK
if (!Files.exists(pathValue))
ValidationResult.ValidationError(
KotlinNewProjectWizardBundle.message("validation.file.should.exist", title.capitalize())
)
else ValidationResult.OK
}
override val type = PathSettingType
}
}
typealias DropDownSettingTypeFilter <V> = Reader.(SettingReference<V, DropDownSettingType<V>>, V) -> Boolean | apache-2.0 | 8812d7e4bf988c127fe487a314d1de42 | 32.981982 | 158 | 0.616068 | 4.752993 | false | false | false | false |
GunoH/intellij-community | plugins/full-line/src/org/jetbrains/completion/full/line/settings/ui/components/SimpleComponents.kt | 2 | 6572 | package org.jetbrains.completion.full.line.settings.ui.components
import com.intellij.lang.Language
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.OnePixelDivider
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.SeparatorComponent
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.dsl.builder.MutableProperty
import com.intellij.ui.dsl.builder.bindText
import com.intellij.ui.dsl.builder.toMutableProperty
import com.intellij.ui.layout.*
import org.jetbrains.completion.full.line.models.ModelType
import org.jetbrains.completion.full.line.settings.MLServerCompletionBundle.Companion.message
import org.jetbrains.completion.full.line.settings.state.MLServerCompletionSettings
import org.jetbrains.completion.full.line.settings.ui.LANGUAGE_CHECKBOX_NAME
import java.awt.CardLayout
import java.awt.Dimension
import java.awt.event.ItemEvent
import javax.swing.JComponent
import javax.swing.JTextField
import kotlin.reflect.KMutableProperty0
// For some reason method intTextField() in com/intellij/ui/layout/Cell.kt
// throws java.lang.LinkageError: loader constraint violation: when resolving method,
// But it's copy works fine :/
@Deprecated("Use Kotlin UI DSL 2 instead, see com.intellij.ui.dsl.builder.Row.intTextField")
fun Cell.intTextFieldFixed(binding: PropertyBinding<Int>, columns: Int? = null, range: IntRange? = null): CellBuilder<JTextField> {
return textField(
{ binding.get().toString() },
{ value -> value.toIntOrNull()?.let { intValue -> binding.set(range?.let { intValue.coerceIn(it.first, it.last) } ?: intValue) } },
columns
).withValidationOnInput {
val value = it.text.toIntOrNull()
if (value == null)
error(message("full.line.int.text.field.error.valid.number"))
else if (range != null && value !in range)
error(message("full.line.int.text.field.error.range.number", range.first, range.last))
else null
}
}
@Deprecated("Use Kotlin UI DSL 2, see another doubleTextField in this file")
fun Cell.doubleTextField(binding: PropertyBinding<Double>, columns: Int? = null, range: IntRange? = null): CellBuilder<JTextField> {
return textField(
{ binding.get().toString() },
{ value ->
value.toDoubleOrNull()
?.let { intValue -> binding.set(range?.let { intValue.coerceIn(it.first.toDouble(), it.last.toDouble()) } ?: intValue) }
},
columns
).withValidationOnInput {
val value = it.text.toDoubleOrNull()
if (value == null)
error(message("full.line.double.text.field.error.valid.number"))
else if (range != null && (value < range.first || value > range.last))
error(message("full.line.double.text.field.error.range.number", range.first, range.last))
else null
}
}
fun com.intellij.ui.dsl.builder.Row.doubleTextField(prop: KMutableProperty0<Double>,
range: IntRange? = null): com.intellij.ui.dsl.builder.Cell<JTextField> {
return doubleTextField(prop.toMutableProperty(), range)
}
fun com.intellij.ui.dsl.builder.Row.doubleTextField(prop: MutableProperty<Double>,
range: IntRange? = null): com.intellij.ui.dsl.builder.Cell<JTextField> {
return textField()
.bindText({ prop.get().toString() },
{ value ->
value.toDoubleOrNull()
?.let { intValue -> prop.set(range?.let { intValue.coerceIn(it.first.toDouble(), it.last.toDouble()) } ?: intValue) }
})
.validationOnInput {
val value = it.text.toDoubleOrNull()
if (value == null)
error(message("full.line.double.text.field.error.valid.number"))
else if (range != null && (value < range.first || value > range.last))
error(message("full.line.double.text.field.error.range.number", range.first, range.last))
else null
}
}
@Deprecated("Use Kotlin UI DSL 2 instead, see com.intellij.ui.dsl.builder.Row.intTextField")
fun Cell.intTextFieldFixed(prop: KMutableProperty0<Int>, columns: Int? = null, range: IntRange? = null): CellBuilder<JTextField> {
return intTextFieldFixed(prop.toBinding(), columns, range)
}
@Deprecated("Use Kotlin UI DSL 2")
fun Row.separatorRow(): Row {
return row {
component(SeparatorComponent(0, OnePixelDivider.BACKGROUND, null))
}
}
fun languageComboBox(langPanel: DialogPanel): ComboBox<String> {
return ComboBox<String>().apply {
renderer = listCellRenderer { langId, _, _ ->
text = Language.findLanguageByID(langId)?.displayName ?: ""
}
addItemListener {
if (it.stateChange == ItemEvent.SELECTED) {
(langPanel.layout as CardLayout).show(langPanel, it.item.toString())
}
}
}
}
fun modelTypeComboBox(langPanel: DialogPanel): ComboBox<ModelType> {
return ComboBox<ModelType>().apply {
renderer = listCellRenderer { value, _, _ ->
@NlsSafe val valueName = value.name
text = valueName
icon = value.icon
}
addItemListener {
if (it.stateChange == ItemEvent.SELECTED) {
(langPanel.layout as CardLayout).show(langPanel, it.item.toString())
}
}
}
}
@Deprecated("Use Row.languageCheckBox method")
fun languageCheckBox(language: Language, biggestLang: String?): JBCheckBox {
return JBCheckBox(language.displayName, MLServerCompletionSettings.getInstance().getLangState(language).enabled).apply {
minimumSize = Dimension(36 + getFontMetrics(font).stringWidth(biggestLang ?: language.id), preferredSize.height)
name = LANGUAGE_CHECKBOX_NAME
}
}
fun com.intellij.ui.dsl.builder.Row.languageCheckBox(language: Language,
biggestLang: String?): com.intellij.ui.dsl.builder.Cell<JBCheckBox> {
return checkBox(language.displayName).applyToComponent {
isSelected = MLServerCompletionSettings.getInstance().getLangState(language).enabled
minimumSize = Dimension(36 + getFontMetrics(font).stringWidth(biggestLang ?: language.id), preferredSize.height)
name = LANGUAGE_CHECKBOX_NAME
}
}
@Deprecated("Use Kotlin UI DSL 2, see another loadingStatus in this file")
fun Cell.loadingStatus(loadingIcon: LoadingComponent): List<CellBuilder<JComponent>> {
return listOf(
component(loadingIcon.loadingIcon),
component(loadingIcon.statusText),
)
}
fun com.intellij.ui.dsl.builder.Row.loadingStatus(loadingIcon: LoadingComponent): List<com.intellij.ui.dsl.builder.Cell<JComponent>> {
return listOf(
cell(loadingIcon.loadingIcon),
cell(loadingIcon.statusText),
)
}
| apache-2.0 | 26c09a3b3ca392a5d88c446209936331 | 40.859873 | 135 | 0.709373 | 4.044308 | false | false | false | false |
jk1/intellij-community | plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/NewRootBunch.kt | 3 | 3269 | // 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 org.jetbrains.idea.svn.branchConfig
import com.intellij.openapi.application.ApplicationManager.getApplication
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcs.ProgressManagerQueue
import org.jetbrains.idea.svn.SvnVcs
import org.jetbrains.idea.svn.api.Url
private val LOG = logger<NewRootBunch>()
// synch is here
class NewRootBunch(private val myProject: Project, private val myBranchesLoader: ProgressManagerQueue) {
private val myLock = Any()
private val myMap = mutableMapOf<VirtualFile, InfoStorage<SvnBranchConfigurationNew>>()
val mapCopy: Map<VirtualFile, SvnBranchConfigurationNew> get() = synchronized(myLock) { myMap.mapValues { it.value.value } }
fun updateForRoot(root: VirtualFile, config: InfoStorage<SvnBranchConfigurationNew>, reload: Boolean): Unit = synchronized(myLock) {
val previous: SvnBranchConfigurationNew?
val override: Boolean
val existing = myMap[root]
if (existing == null) {
previous = null
override = true
myMap[root] = config
}
else {
previous = existing.value
override = existing.accept(config)
}
if (reload && override) {
myBranchesLoader.run { reloadBranches(root, previous, config.value) }
}
}
fun updateBranches(root: VirtualFile, branchesParent: Url, items: InfoStorage<List<SvnBranchItem>>): Unit = synchronized(myLock) {
val existing = myMap[root]
if (existing == null) {
LOG.info("cannot update branches, branches parent not found: ${branchesParent.toDecodedString()}")
}
else {
existing.value.updateBranch(branchesParent, items)
}
}
fun getConfig(root: VirtualFile): SvnBranchConfigurationNew = synchronized(myLock) {
val value = myMap[root]
val result: SvnBranchConfigurationNew
if (value == null) {
result = SvnBranchConfigurationNew()
myMap[root] = InfoStorage(result, InfoReliability.empty)
myBranchesLoader.run(DefaultBranchConfigInitializer(myProject, this, root))
}
else {
result = value.value
}
result
}
fun reloadBranchesAsync(root: VirtualFile, branchLocation: Url, reliability: InfoReliability) {
getApplication().executeOnPooledThread { reloadBranches(root, branchLocation, reliability, true) }
}
fun reloadBranches(root: VirtualFile, prev: SvnBranchConfigurationNew?, next: SvnBranchConfigurationNew) {
val oldUrls = prev?.branchLocations?.toSet() ?: emptySet()
val vcs = SvnVcs.getInstance(myProject)
if (!vcs.isVcsBackgroundOperationsAllowed(root)) return
for (newBranchUrl in next.branchLocations) {
// check if cancel had been put
if (!vcs.isVcsBackgroundOperationsAllowed(root)) return
if (newBranchUrl !in oldUrls) {
reloadBranches(root, newBranchUrl, InfoReliability.defaultValues, true)
}
}
}
fun reloadBranches(root: VirtualFile, branchLocation: Url, reliability: InfoReliability, passive: Boolean): Unit =
BranchesLoader(myProject, this, branchLocation, reliability, root, passive).run()
} | apache-2.0 | 0a2ab91175e26efe26541e985b90f5fb | 37.470588 | 140 | 0.733864 | 4.329801 | false | true | false | false |
ktorio/ktor | ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/plugins/CookiesMockTest.kt | 1 | 1926 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.tests.plugins
import io.ktor.client.call.*
import io.ktor.client.engine.mock.*
import io.ktor.client.plugins.cookies.*
import io.ktor.client.request.*
import io.ktor.client.tests.utils.*
import io.ktor.http.*
import kotlin.test.*
class CookiesMockTest {
@Test
fun testCompatibility() = testWithEngine(MockEngine) {
config {
engine {
addHandler { request ->
assertEquals("*/*", request.headers[HttpHeaders.Accept])
val rawCookies = request.headers[HttpHeaders.Cookie]!!
assertEquals(1, request.headers.getAll(HttpHeaders.Cookie)?.size!!)
assertEquals("first=\"1,2,3,4\"; second=abc", rawCookies)
respondOk()
}
}
install(HttpCookies) {
default {
addCookie("//localhost", Cookie("first", "1,2,3,4", encoding = CookieEncoding.DQUOTES))
addCookie("http://localhost", Cookie("second", "abc"))
}
}
}
test { client ->
client.prepareGet { }.execute { }
}
}
@Test
fun testAllowedCharacters() = testWithEngine(MockEngine) {
config {
engine {
addHandler { request ->
assertEquals("myServer=value:value", request.headers[HttpHeaders.Cookie])
respondOk()
}
}
install(HttpCookies) {
default {
addCookie("http://localhost", Cookie("myServer", "value:value", encoding = CookieEncoding.RAW))
}
}
}
test { client ->
client.get {}.body<String>()
}
}
}
| apache-2.0 | 4312c483e5127f1c7902e9b115c868f4 | 28.630769 | 118 | 0.524922 | 4.755556 | false | true | false | false |
helloworld1/FreeOTPPlus | app/src/main/java/org/fedorahosted/freeotp/ui/MainActivity.kt | 1 | 17900 | /*
* FreeOTP
*
* Authors: Nathaniel McCallum <[email protected]>
*
* Copyright (C) 2013 Nathaniel McCallum, Red Hat
*
* 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.
*/
/*
* Portions Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fedorahosted.freeotp.ui
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import android.widget.SearchView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView.AdapterDataObserver
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import org.fedorahosted.freeotp.R
import org.fedorahosted.freeotp.data.MigrationUtil
import org.fedorahosted.freeotp.data.OtpTokenDatabase
import org.fedorahosted.freeotp.data.OtpTokenFactory
import org.fedorahosted.freeotp.databinding.MainBinding
import org.fedorahosted.freeotp.data.legacy.ImportExportUtil
import org.fedorahosted.freeotp.util.Settings
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject
import kotlin.math.max
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject lateinit var importFromUtil: ImportExportUtil
@Inject lateinit var settings: Settings
@Inject lateinit var tokenMigrationUtil: MigrationUtil
@Inject lateinit var otpTokenDatabase: OtpTokenDatabase
@Inject lateinit var tokenListAdapter: TokenListAdapter
private val viewModel: MainViewModel by viewModels()
private lateinit var binding: MainBinding
private var searchQuery = ""
private var menu: Menu? = null
private var lastSessionEndTimestamp = 0L;
private val tokenListObserver: AdapterDataObserver = object: AdapterDataObserver() {
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
super.onItemRangeInserted(positionStart, itemCount)
binding.tokenList.scrollToPosition(positionStart)
}
}
private val dateFormatter : DateFormat = SimpleDateFormat("yyyyMMdd_HHmm")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
onNewIntent(intent)
binding = MainBinding.inflate(layoutInflater)
setContentView(binding.root)
viewModel.migrateOldData()
binding.tokenList.adapter = tokenListAdapter
// Used GridlayoutManager to support tablet mode for multiple columns
// Make sure one column has at least 320 DP
val columns = max(1, resources.configuration.screenWidthDp / 320)
binding.tokenList.layoutManager = GridLayoutManager(this, columns)
ItemTouchHelper(TokenTouchCallback(this, tokenListAdapter, otpTokenDatabase))
.attachToRecyclerView(binding.tokenList)
tokenListAdapter.registerAdapterDataObserver(tokenListObserver)
lifecycleScope.launch {
viewModel.getTokenList().collect { tokens ->
tokenListAdapter.submitList(tokens)
if (tokens.isEmpty()) {
binding.emptyView.visibility = View.VISIBLE
binding.tokenList.visibility = View.GONE
} else {
binding.emptyView.visibility = View.GONE
binding.tokenList.visibility = View.VISIBLE
}
}
}
lifecycleScope.launch {
viewModel.getAuthState().collect { authState ->
if (authState == MainViewModel.AuthState.UNAUTHENTICATED) {
verifyAuthentication()
}
}
}
setSupportActionBar(binding.toolbar)
binding.searchView.setOnQueryTextListener(object: SearchView.OnQueryTextListener, androidx.appcompat.widget.SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
viewModel.setTokenSearchQuery(query ?: "")
return true
}
override fun onQueryTextChange(query: String?): Boolean {
searchQuery = query ?: ""
viewModel.setTokenSearchQuery(query ?: "")
return true
}
})
binding.addTokenFab.setOnClickListener {
startActivity(Intent(this, ScanTokenActivity::class.java))
}
// Don't permit screenshots since these might contain OTP codes unless explicitly
// launched with screenshot mode
if (intent.extras?.getBoolean(SCREENSHOT_MODE_EXTRA) != true) {
window.setFlags(
WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE
)
}
}
override fun onDestroy() {
super.onDestroy()
tokenListAdapter.unregisterAdapterDataObserver(tokenListObserver)
lastSessionEndTimestamp = 0L;
}
override fun onStart() {
super.onStart()
viewModel.onSessionStart()
}
override fun onStop() {
super.onStop()
viewModel.onSessionStop()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main, menu)
this.menu = menu
refreshOptionMenu()
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_scan -> {
startActivity(Intent(this, ScanTokenActivity::class.java))
return true
}
R.id.action_add -> {
startActivity(Intent(this, AddActivity::class.java))
return true
}
R.id.action_import_json -> {
performFileSearch(READ_JSON_REQUEST_CODE)
return true
}
R.id.action_import_key_uri -> {
performFileSearch(READ_KEY_URI_REQUEST_CODE)
return true
}
R.id.action_export_json -> {
createFile("application/json", "freeotp-backup","json", WRITE_JSON_REQUEST_CODE)
return true
}
R.id.action_export_key_uri -> {
createFile("text/plain", "freeotp-backup","txt", WRITE_KEY_URI_REQUEST_CODE)
return true
}
R.id.use_dark_theme -> {
settings.darkMode = !settings.darkMode
if (settings.darkMode) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
recreate()
return true
}
R.id.copy_to_clipboard -> {
settings.copyToClipboard = !settings.copyToClipboard
item.isChecked = settings.copyToClipboard
refreshOptionMenu()
}
R.id.require_authentication -> {
// Make sure we also verify authentication before turning on the settings
if (!settings.requireAuthentication) {
viewModel.setAuthState(MainViewModel.AuthState.UNAUTHENTICATED)
} else {
settings.requireAuthentication = false
viewModel.setAuthState(MainViewModel.AuthState.AUTHENTICATED)
refreshOptionMenu()
}
return true
}
R.id.action_about -> {
startActivity(Intent(this, AboutActivity::class.java))
return true
}
R.id.quit_and_lock -> {
finish()
return true
}
}
return false
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
val uri = intent.data
if (uri != null) {
lifecycleScope.launch {
try {
otpTokenDatabase.otpTokenDao().insert(OtpTokenFactory.createFromUri(uri))
} catch (e: Exception) {
Snackbar.make(binding.rootView, R.string.invalid_token_uri_received, Snackbar.LENGTH_SHORT)
.show()
}
}
}
}
public override fun onActivityResult(requestCode: Int, resultCode: Int,
resultData: Intent?) {
super.onActivityResult(requestCode, resultCode, resultData)
if (resultCode != Activity.RESULT_OK) {
return
}
when (requestCode) {
WRITE_JSON_REQUEST_CODE -> {
lifecycleScope.launch {
val uri = resultData?.data ?: return@launch
importFromUtil.exportJsonFile(uri)
Snackbar.make(binding.rootView, R.string.export_succeeded_text, Snackbar.LENGTH_SHORT)
.show()
}
}
READ_JSON_REQUEST_CODE -> {
val uri = resultData?.data ?: return
MaterialAlertDialogBuilder(this)
.setTitle(R.string.import_json_file)
.setMessage(R.string.import_json_file_warning)
.setIcon(R.drawable.alert)
.setPositiveButton(R.string.ok_text) { _: DialogInterface, _: Int ->
lifecycleScope.launch {
try {
importFromUtil.importJsonFile(uri)
Snackbar.make(binding.rootView, R.string.import_succeeded_text, Snackbar.LENGTH_SHORT)
.show()
} catch (e: Exception) {
Log.e(TAG, "Import JSON failed", e)
Snackbar.make(binding.root, R.string.import_json_failed_text, Snackbar.LENGTH_SHORT)
.show()
}
}
}
.setNegativeButton(R.string.cancel_text, null)
.show()
}
WRITE_KEY_URI_REQUEST_CODE -> {
lifecycleScope.launch {
val uri = resultData?.data ?: return@launch
importFromUtil.exportKeyUriFile(uri)
Snackbar.make(binding.rootView, R.string.export_succeeded_text, Snackbar.LENGTH_SHORT)
.show()
}
}
READ_KEY_URI_REQUEST_CODE -> {
lifecycleScope.launch {
val uri = resultData?.data ?: return@launch
try {
importFromUtil.importKeyUriFile(uri)
Snackbar.make(binding.rootView, R.string.import_succeeded_text, Snackbar.LENGTH_SHORT)
.show()
} catch (e: Exception) {
Log.e(TAG, "Import Key uri failed", e)
Snackbar.make(binding.rootView, R.string.import_key_uri_failed_text, Snackbar.LENGTH_SHORT)
.show()
}
}
}
}
}
/**
* Fires an intent to spin up the "file chooser" UI and select an image.
*/
private fun performFileSearch(requestCode: Int) {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "*/*"
try {
startActivityForResult(intent, requestCode)
} catch (e: ActivityNotFoundException) {
Log.e(TAG, "Cannot find activity", e)
Toast.makeText(applicationContext,
getString(R.string.launch_file_browser_failure), Toast.LENGTH_SHORT).show();
}
}
private fun createFile(mimeType: String, fileName: String, fileExtension: String, requestCode: Int, appendTimestamp: Boolean = true) {
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
// Filter to only show results that can be "opened", such as
// a file (as opposed to a list of contacts or timezones).
intent.addCategory(Intent.CATEGORY_OPENABLE)
// Create a file with the requested MIME type.
intent.type = mimeType
intent.putExtra(Intent.EXTRA_TITLE, "$fileName${if(appendTimestamp) "_${dateFormatter.format(Date())}" else ""}.$fileExtension")
try {
startActivityForResult(intent, requestCode)
} catch (e: ActivityNotFoundException) {
Log.e(TAG, "Cannot find activity", e)
Toast.makeText(applicationContext,
getString(R.string.launch_file_browser_failure), Toast.LENGTH_SHORT).show();
}
}
private fun refreshOptionMenu() {
this.menu?.findItem(R.id.use_dark_theme)?.isChecked = settings.darkMode
this.menu?.findItem(R.id.copy_to_clipboard)?.isChecked = settings.copyToClipboard
this.menu?.findItem(R.id.require_authentication)?.isChecked = settings.requireAuthentication
}
private fun verifyAuthentication() {
val executor = ContextCompat.getMainExecutor(this)
val biometricPrompt = BiometricPrompt(this, executor,
object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(errorCode: Int,
errString: CharSequence) {
super.onAuthenticationError(errorCode, errString)
// Don't show error message toast if user pressed back button
if (errorCode != BiometricPrompt.ERROR_USER_CANCELED) {
Toast.makeText(applicationContext,
"${getString(R.string.authentication_error)} $errString", Toast.LENGTH_SHORT)
.show()
}
if (errorCode != BiometricPrompt.ERROR_NO_DEVICE_CREDENTIAL) {
finish()
}
}
override fun onAuthenticationSucceeded(
result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
viewModel.setAuthState(MainViewModel.AuthState.AUTHENTICATED)
if (!settings.requireAuthentication) {
settings.requireAuthentication = true
refreshOptionMenu()
}
}
override fun onAuthenticationFailed() {
// Invalid authentication, e.g. wrong fingerprint. Android auth UI shows an
// error, so no need for FreeOTP to show one
super.onAuthenticationFailed()
Toast.makeText(applicationContext,
R.string.unable_to_authenticate, Toast.LENGTH_SHORT)
.show()
}
})
val promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle(getString(R.string.authentication_dialog_title))
.setSubtitle(getString(R.string.authentication_dialog_subtitle))
.setAllowedAuthenticators(BiometricManager.Authenticators.DEVICE_CREDENTIAL or BiometricManager.Authenticators.BIOMETRIC_WEAK)
.build()
biometricPrompt.authenticate(promptInfo)
}
companion object {
private val TAG = MainActivity::class.java.simpleName
const val READ_JSON_REQUEST_CODE = 42
const val WRITE_JSON_REQUEST_CODE = 43
const val READ_KEY_URI_REQUEST_CODE = 44
const val WRITE_KEY_URI_REQUEST_CODE = 45
const val SCREENSHOT_MODE_EXTRA = "screenshot_mode"
}
}
| apache-2.0 | 32c83dce48a8f2cc404cc3f7ba6cc5cf | 37.577586 | 148 | 0.593296 | 5.267805 | false | false | false | false |
yole/deckjs-presentations | snippets/swingbuilders.kt | 1 | 608 | package demo
import javax.swing.*
import kotlin.swing.*
fun main(args: Array<String>): Unit {
val greeting = """
Welcome to Kotlin
Enter some text here!
"""
frame("Kool Kotlin Swing Demo") {
exitOnClose()
size = #(500, 300)
val textArea = JTextArea(greeting)
center = textArea
south = borderPanel {
west = button("Clear") {
textArea.setText("")
}
east = button("Restore") {
textArea.setText(greeting)
}
}
}.setVisible(true)
f.setLocationRelativeTo(null)
f.setVisible(true)
}
| mit | cfca1c31f47b325dfca684ebdde1d506 | 16.424242 | 38 | 0.560855 | 4.080537 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/database/mappers/HistoryTypeMapping.kt | 2 | 2494 | package eu.kanade.tachiyomi.data.database.mappers
import android.database.Cursor
import androidx.core.content.contentValuesOf
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 eu.kanade.tachiyomi.data.database.models.History
import eu.kanade.tachiyomi.data.database.models.HistoryImpl
import eu.kanade.tachiyomi.data.database.tables.HistoryTable.COL_CHAPTER_ID
import eu.kanade.tachiyomi.data.database.tables.HistoryTable.COL_ID
import eu.kanade.tachiyomi.data.database.tables.HistoryTable.COL_LAST_READ
import eu.kanade.tachiyomi.data.database.tables.HistoryTable.COL_TIME_READ
import eu.kanade.tachiyomi.data.database.tables.HistoryTable.TABLE
class HistoryTypeMapping : SQLiteTypeMapping<History>(
HistoryPutResolver(),
HistoryGetResolver(),
HistoryDeleteResolver()
)
open class HistoryPutResolver : DefaultPutResolver<History>() {
override fun mapToInsertQuery(obj: History) = InsertQuery.builder()
.table(TABLE)
.build()
override fun mapToUpdateQuery(obj: History) = UpdateQuery.builder()
.table(TABLE)
.where("$COL_ID = ?")
.whereArgs(obj.id)
.build()
override fun mapToContentValues(obj: History) =
contentValuesOf(
COL_ID to obj.id,
COL_CHAPTER_ID to obj.chapter_id,
COL_LAST_READ to obj.last_read,
COL_TIME_READ to obj.time_read
)
}
class HistoryGetResolver : DefaultGetResolver<History>() {
override fun mapFromCursor(cursor: Cursor): History = HistoryImpl().apply {
id = cursor.getLong(cursor.getColumnIndexOrThrow(COL_ID))
chapter_id = cursor.getLong(cursor.getColumnIndexOrThrow(COL_CHAPTER_ID))
last_read = cursor.getLong(cursor.getColumnIndexOrThrow(COL_LAST_READ))
time_read = cursor.getLong(cursor.getColumnIndexOrThrow(COL_TIME_READ))
}
}
class HistoryDeleteResolver : DefaultDeleteResolver<History>() {
override fun mapToDeleteQuery(obj: History) = DeleteQuery.builder()
.table(TABLE)
.where("$COL_ID = ?")
.whereArgs(obj.id)
.build()
}
| apache-2.0 | 91599a46f9d666417b5e39854449edbb | 37.96875 | 81 | 0.748998 | 4.135987 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/shadow/ShadowFinalInspection.kt | 1 | 1751 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.inspection.shadow
import com.demonwav.mcdev.platform.mixin.inspection.MixinInspection
import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.FINAL
import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.MUTABLE
import com.intellij.codeInsight.intention.AddAnnotationFix
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.JavaElementVisitor
import com.intellij.psi.PsiAssignmentExpression
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiModifierListOwner
import com.intellij.psi.PsiReferenceExpression
class ShadowFinalInspection : MixinInspection() {
override fun getStaticDescription() = "@Final annotated fields cannot be modified, as the field it is targeting is final. " +
"This can be overridden with @Mutable."
override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder)
private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() {
override fun visitAssignmentExpression(expression: PsiAssignmentExpression) {
val left = expression.lExpression as? PsiReferenceExpression ?: return
val resolved = left.resolve() as? PsiModifierListOwner ?: return
val modifiers = resolved.modifierList ?: return
if (modifiers.findAnnotation(FINAL) != null && modifiers.findAnnotation(MUTABLE) == null) {
holder.registerProblem(expression, "@Final fields cannot be modified",
AddAnnotationFix(MUTABLE, resolved))
}
}
}
}
| mit | 6c4d3f5208257a84a310b7a793428ee0 | 38.795455 | 129 | 0.747573 | 5.017192 | false | false | false | false |
jovr/imgui | core/src/main/kotlin/imgui/api/tables.kt | 2 | 37018 | package imgui.api
import glm_.has
import glm_.hasnt
import glm_.max
import glm_.min
import glm_.vec2.Vec2
import imgui.*
import imgui.ImGui.beginTableEx
import imgui.ImGui.buttonBehavior
import imgui.ImGui.calcTextSize
import imgui.ImGui.endChild
import imgui.ImGui.findRenderedTextEnd
import imgui.ImGui.getColorU32
import imgui.ImGui.getID
import imgui.ImGui.isItemHovered
import imgui.ImGui.isMouseDragging
import imgui.ImGui.isMouseReleased
import imgui.ImGui.itemAdd
import imgui.ImGui.itemSize
import imgui.ImGui.popID
import imgui.ImGui.popStyleColor
import imgui.ImGui.pushID
import imgui.ImGui.pushStyleColor
import imgui.ImGui.renderNavHighlight
import imgui.ImGui.renderText
import imgui.ImGui.renderTextEllipsis
import imgui.ImGui.setItemAllowOverlap
import imgui.ImGui.setTooltip
import imgui.ImGui.tableGetColumnNextSortDirection
import imgui.ImGui.tableGetHeaderRowHeight
import imgui.ImGui.tableGetHoveredColumn
import imgui.ImGui.tableOpenContextMenu
import imgui.ImGui.tableSetColumnSortDirection
import imgui.classes.TableSortSpecs
import imgui.internal.classes.*
import imgui.internal.floor
import imgui.internal.sections.ButtonFlag
import imgui.internal.sections.NavHighlightFlag
import imgui.TableColumnFlag as Tcf
import imgui.TableFlag as Tf
import imgui.TableRowFlag as Trf
// Tables
// [BETA API] API may evolve slightly! If you use this, please update to the next version when it comes out!
// - Full-featured replacement for old Columns API.
// - See Demo->Tables for demo code.
// - See top of imgui_tables.cpp for general commentary.
// - See ImGuiTableFlags_ and ImGuiTableColumnFlags_ enums for a description of available flags.
// The typical call flow is:
// - 1. Call BeginTable().
// - 2. Optionally call TableSetupColumn() to submit column name/flags/defaults.
// - 3. Optionally call TableSetupScrollFreeze() to request scroll freezing of columns/rows.
// - 4. Optionally call TableHeadersRow() to submit a header row. Names are pulled from TableSetupColumn() data.
// - 5. Populate contents:
// - In most situations you can use TableNextRow() + TableSetColumnIndex(N) to start appending into a column.
// - If you are using tables as a sort of grid, where every columns is holding the same type of contents,
// you may prefer using TableNextColumn() instead of TableNextRow() + TableSetColumnIndex().
// TableNextColumn() will automatically wrap-around into the next row if needed.
// - IMPORTANT: Comparatively to the old Columns() API, we need to call TableNextColumn() for the first column!
// - Summary of possible call flow:
// --------------------------------------------------------------------------------------------------------
// TableNextRow() -> TableSetColumnIndex(0) -> Text("Hello 0") -> TableSetColumnIndex(1) -> Text("Hello 1") // OK
// TableNextRow() -> TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK
// TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK: TableNextColumn() automatically gets to next row!
// TableNextRow() -> Text("Hello 0") // Not OK! Missing TableSetColumnIndex() or TableNextColumn()! Text will not appear!
// --------------------------------------------------------------------------------------------------------
// - 5. Call EndTable()
interface tables {
/** Read about "TABLE SIZING" at the top of this file. */
fun beginTable(strId: String, columns: Int, flags: TableFlags = Tf.None.i,
outerSize: Vec2 = Vec2(), innerWidth: Float = 0f): Boolean {
val id = getID(strId)
return beginTableEx(strId, id, columns, flags, outerSize, innerWidth)
}
/** only call EndTable() if BeginTable() returns true! */
fun endTable() {
val table = g.currentTable
check(table != null) { "Only call EndTable() if BeginTable() returns true!" }
// This assert would be very useful to catch a common error... unfortunately it would probably trigger in some
// cases, and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border)
//IM_ASSERT(table->IsLayoutLocked && "Table unused: never called TableNextRow(), is that the intent?");
// If the user never got to call TableNextRow() or TableNextColumn(), we call layout ourselves to ensure all our
// code paths are consistent (instead of just hoping that TableBegin/TableEnd will work), get borders drawn, etc.
if (!table.isLayoutLocked)
table.updateLayout()
val flags = table.flags
val innerWindow = table.innerWindow!!
val outerWindow = table.outerWindow!!
assert(innerWindow === g.currentWindow)
assert(outerWindow === innerWindow || outerWindow === innerWindow.parentWindow)
if (table.isInsideRow)
table.endRow()
// Context menu in columns body
if (flags has Tf.ContextMenuInBody)
if (table.hoveredColumnBody != -1 && !ImGui.isAnyItemHovered && ImGui.isMouseReleased(MouseButton.Right))
tableOpenContextMenu(table.hoveredColumnBody)
// Finalize table height
innerWindow.dc.prevLineSize put table.hostBackupPrevLineSize
innerWindow.dc.currLineSize put table.hostBackupCurrLineSize
innerWindow.dc.cursorMaxPos put table.hostBackupCursorMaxPos
val innerContentMaxY = table.rowPosY2
assert(table.rowPosY2 == innerWindow.dc.cursorPos.y)
if (innerWindow !== outerWindow)
innerWindow.dc.cursorMaxPos.y = innerContentMaxY
else if (flags hasnt Tf.NoHostExtendY) {
// Patch OuterRect/InnerRect height
table.outerRect.max.y = table.outerRect.max.y max innerContentMaxY
table.innerRect.max.y = table.outerRect.max.y
}
table.workRect.max.y = table.workRect.max.y max table.outerRect.max.y
table.lastOuterHeight = table.outerRect.height
// Setup inner scrolling range
// FIXME: This ideally should be done earlier, in BeginTable() SetNextWindowContentSize call, just like writing to inner_window->DC.CursorMaxPos.y,
// but since the later is likely to be impossible to do we'd rather update both axises together.
if (table.flags has Tf.ScrollX) {
val outerPaddingForBorder = if (table.flags has Tf.BordersOuterV) TABLE_BORDER_SIZE else 0f
val inner = table.innerWindow!!
var maxPosX = inner.dc.cursorMaxPos.x
if (table.rightMostEnabledColumn != -1)
maxPosX = maxPosX max (table.columns[table.rightMostEnabledColumn].workMaxX + table.cellPaddingX + table.outerPaddingX - outerPaddingForBorder)
if (table.resizedColumn != -1)
maxPosX = maxPosX max table.resizeLockMinContentsX2
inner.dc.cursorMaxPos.x = maxPosX
}
// Pop clipping rect
if (flags hasnt Tf.NoClip)
innerWindow.drawList.popClipRect()
innerWindow.clipRect put innerWindow.drawList._clipRectStack.last()
// Draw borders
if (flags has Tf.Borders)
table.drawBorders()
// #if 0
// // Strip out dummy channel draw calls
// // We have no way to prevent user submitting direct ImDrawList calls into a hidden column (but ImGui:: calls will be clipped out)
// // Pros: remove draw calls which will have no effect. since they'll have zero-size cliprect they may be early out anyway.
// // Cons: making it harder for users watching metrics/debugger to spot the wasted vertices.
// if (table->DummyDrawChannel != (ImGuiTableColumnIdx)-1)
// {
// ImDrawChannel* dummy_channel = &table->DrawSplitter._Channels[table->DummyDrawChannel]
// dummy_channel->_CmdBuffer.resize(0)
// dummy_channel->_IdxBuffer.resize(0)
// }
// #endif
// Flatten channels and merge draw calls
table.drawSplitter.setCurrentChannel(innerWindow.drawList, 0)
if (table.flags hasnt Tf.NoClip)
table.mergeDrawChannels()
table.drawSplitter.merge(innerWindow.drawList)
// Update ColumnsAutoFitWidth to get us ahead for host using our size to auto-resize without waiting for next BeginTable()
val widthSpacings = table.outerPaddingX * 2f + (table.cellSpacingX1 + table.cellSpacingX2) * (table.columnsEnabledCount - 1)
table.columnsAutoFitWidth = widthSpacings + (table.cellPaddingX * 2f) * table.columnsEnabledCount
for (columnN in 0 until table.columnsCount)
if (table.enabledMaskByIndex has (1L shl columnN)) {
val column = table.columns[columnN]
table.columnsAutoFitWidth += when {
column.flags has Tcf.WidthFixed && column.flags hasnt Tcf.NoResize -> column.widthRequest
else -> table getColumnWidthAuto column
}
}
// Update scroll
if (table.flags hasnt Tf.ScrollX && innerWindow !== outerWindow)
innerWindow.scroll.x = 0f
else if (table.lastResizedColumn != -1 && table.resizedColumn == -1 && innerWindow.scrollbar.x && table.instanceInteracted == table.instanceCurrent) {
// When releasing a column being resized, scroll to keep the resulting column in sight
val neighborWidthToKeepVisible = table.minColumnWidth + table.cellPaddingX * 2f
val column = table.columns[table.lastResizedColumn]
if (column.maxX < table.innerClipRect.min.x)
innerWindow.setScrollFromPosX(column.maxX - innerWindow.pos.x - neighborWidthToKeepVisible, 1f)
else if (column.maxX > table.innerClipRect.max.x)
innerWindow.setScrollFromPosX(column.maxX - innerWindow.pos.x + neighborWidthToKeepVisible, 1f)
}
// Apply resizing/dragging at the end of the frame
if (table.resizedColumn != -1 && table.instanceCurrent == table.instanceInteracted) {
val column = table.columns[table.resizedColumn]
val newX2 = g.io.mousePos.x - g.activeIdClickOffset.x + TABLE_RESIZE_SEPARATOR_HALF_THICKNESS
val newWidth = floor(newX2 - column.minX - table.cellSpacingX1 - table.cellPaddingX * 2f)
table.resizedColumnNextWidth = newWidth
}
// Pop from id stack
assert(innerWindow.idStack.last() == table.id + table.instanceCurrent) { "Mismatching PushID/PopID!" }
assert(outerWindow.dc.itemWidthStack.size >= table.hostBackupItemWidthStackSize) { "Too many PopItemWidth!" }
popID()
// Restore window data that we modified
val backupOuterMaxPos = Vec2(outerWindow.dc.cursorMaxPos)
innerWindow.workRect put table.hostBackupWorkRect
innerWindow.parentWorkRect put table.hostBackupParentWorkRect
innerWindow.skipItems = table.hostSkipItems
outerWindow.dc.cursorPos put table.outerRect.min
outerWindow.dc.itemWidth = table.hostBackupItemWidth
for (i in outerWindow.dc.itemWidthStack.size until table.hostBackupItemWidthStackSize)
outerWindow.dc.itemWidthStack += 0f
for (i in table.hostBackupItemWidthStackSize until outerWindow.dc.itemWidthStack.size)
outerWindow.dc.itemWidthStack.pop()
outerWindow.dc.columnsOffset = table.hostBackupColumnsOffset
// Layout in outer window
// (FIXME: To allow auto-fit and allow desirable effect of SameLine() we dissociate 'used' vs 'ideal' size by overriding
// CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414)
if (innerWindow != outerWindow)
endChild()
else {
itemSize(table.outerRect.size)
itemAdd(table.outerRect, 0)
}
// Override declared contents width/height to enable auto-resize while not needlessly adding a scrollbar
if (table.flags has Tf.NoHostExtendX) {
// FIXME-TABLE: Could we remove this section?
// ColumnsAutoFitWidth may be one frame ahead here since for Fixed+NoResize is calculated from latest contents
assert(table.flags hasnt Tf.ScrollX)
outerWindow.dc.cursorMaxPos.x = backupOuterMaxPos.x max (table.outerRect.min.x + table.columnsAutoFitWidth)
} else if (table.userOuterSize.x <= 0f) {
val decorationSize = if (table.flags has Tf.ScrollX) innerWindow.scrollbarSizes.x else 0f
outerWindow.dc.idealMaxPos.x = outerWindow.dc.idealMaxPos.x max (table.outerRect.min.x + table.columnsAutoFitWidth + decorationSize - table.userOuterSize.x)
outerWindow.dc.cursorMaxPos.x = backupOuterMaxPos.x max (table.outerRect.max.x min table.outerRect.min.x + table.columnsAutoFitWidth)
} else
outerWindow.dc.cursorMaxPos.x = backupOuterMaxPos.x max table.outerRect.max.x
if (table.userOuterSize.y <= 0f) {
val decorationSize = if (table.flags has Tf.ScrollY) innerWindow.scrollbarSizes.y else 0f
outerWindow.dc.idealMaxPos.y = outerWindow.dc.idealMaxPos.y max (innerContentMaxY + decorationSize - table.userOuterSize.y)
outerWindow.dc.cursorMaxPos.y = backupOuterMaxPos.y max (table.outerRect.max.y min innerContentMaxY)
} else
// OuterRect.Max.y may already have been pushed downward from the initial value (unless ImGuiTableFlags_NoHostExtendY is set)
outerWindow.dc.cursorMaxPos.y = backupOuterMaxPos.y max table.outerRect.max.y
// Override declared contents height
if (innerWindow === outerWindow && flags hasnt Tf.NoHostExtendY)
outerWindow.dc.cursorMaxPos.y = outerWindow.dc.cursorMaxPos.y max innerContentMaxY
// Save settings
if (table.isSettingsDirty)
table.saveSettings()
table.isInitializing = false
// Clear or restore current table, if any
assert(g.currentWindow === outerWindow && g.currentTable === table)
g.currentTableStack.pop()
g.currentTable = if (g.currentTableStack.isNotEmpty()) g.tables.getByIndex(g.currentTableStack.last().index) else null
outerWindow.dc.currentTableIdx = g.currentTable?.let { g.tables.getIndex(it).i } ?: -1
}
/** [Public] Starts into the first cell of a new row
*
* append into the first cell of a new row. */
fun tableNextRow(rowFlags: TableRowFlags = Trf.None.i, rowMinHeight: Float = 0f) {
val table = g.currentTable!!
if (!table.isLayoutLocked)
table.updateLayout()
if (table.isInsideRow)
table.endRow()
table.lastRowFlags = table.rowFlags
table.rowFlags = rowFlags
table.rowMinHeight = rowMinHeight
table.beginRow()
// We honor min_row_height requested by user, but cannot guarantee per-row maximum height,
// because that would essentially require a unique clipping rectangle per-cell.
table.rowPosY2 += table.cellPaddingY * 2f
table.rowPosY2 = table.rowPosY2 max (table.rowPosY1 + rowMinHeight)
// Disable output until user calls TableNextColumn()
table.innerWindow!!.skipItems = true
}
/** [Public] Append into the next column/cell
*
* append into the next column (or first column of next row if currently in last column). Return true when column is visible. */
fun tableNextColumn(): Boolean {
val table = g.currentTable ?: return false
if (table.isInsideRow && table.currentColumn + 1 < table.columnsCount) {
if (table.currentColumn != -1)
table.endCell()
table.beginCell(table.currentColumn + 1)
} else {
tableNextRow()
table.beginCell(0)
}
// Return whether the column is visible. User may choose to skip submitting items based on this return value,
// however they shouldn't skip submitting for columns that may have the tallest contribution to row height.
val columnN = table.currentColumn
return table.requestOutputMaskByIndex has (1L shl columnN)
}
/** [Public] Append into a specific column
*
* append into the specified column. Return true when column is visible. */
fun tableSetColumnIndex(columnN: Int): Boolean {
val table = g.currentTable ?: return false
if (table.currentColumn != columnN) {
if (table.currentColumn != -1)
table.endCell()
assert(columnN >= 0 && table.columnsCount != 0)
table beginCell columnN
}
// Return whether the column is visible. User may choose to skip submitting items based on this return value,
// however they shouldn't skip submitting for columns that may have the tallest contribution to row height.
return table.requestOutputMaskByIndex has (1L shl columnN)
}
// Tables: Headers & Columns declaration
// - Use TableHeadersRow() to create a header row and automatically submit a TableHeader() for each column.
// Headers are required to perform: reordering, sorting, and opening the context menu.
// The context menu can also be made available in columns body using ImGuiTableFlags_ContextMenuInBody.
// - You may manually submit headers using TableNextRow() + TableHeader() calls, but this is only useful in
// some advanced use cases (e.g. adding custom widgets in header row).
// - Use TableSetupScrollFreeze() to lock columns/rows so they stay visible when scrolled.
/** See "COLUMN SIZING POLICIES" comments at the top of this file
* If (init_width_or_weight <= 0.0f) it is ignored */
fun tableSetupColumn(label: String?, flags_: TableColumnFlags = Tcf.None.i, initWidthOrWeight: Float = 0f, userId: ID = 0) {
var flags = flags_
val table = g.currentTable
check(table != null) { "Need to call TableSetupColumn() after BeginTable()!" }
assert(!table.isLayoutLocked) { "Need to call call TableSetupColumn() before first row!" }
assert(flags hasnt Tcf.StatusMask_) { "Illegal to pass StatusMask values to TableSetupColumn()" }
if (table.declColumnsCount >= table.columnsCount) {
assert(table.declColumnsCount < table.columnsCount) { "Called TableSetupColumn() too many times!" }
return
}
val column = table.columns[table.declColumnsCount]
table.declColumnsCount++
// Assert when passing a width or weight if policy is entirely left to default, to avoid storing width into weight and vice-versa.
// Give a grace to users of ImGuiTableFlags_ScrollX.
if (table.isDefaultSizingPolicy && flags hasnt Tcf.WidthMask_ && flags hasnt Tf.ScrollX)
assert(initWidthOrWeight <= 0f) { "Can only specify width/weight if sizing policy is set explicitely in either Table or Column." }
// When passing a width automatically enforce WidthFixed policy
// (whereas TableSetupColumnFlags would default to WidthAuto if table is not Resizable)
if (flags hasnt Tcf.WidthMask_ && initWidthOrWeight > 0f)
(table.flags and Tf._SizingMask).let {
if (it == Tf.SizingFixedFit.i || it == Tf.SizingFixedSame.i)
flags = flags or Tcf.WidthFixed
}
table.setupColumnFlags(column, flags)
column.userID = userId
flags = column.flags
// Initialize defaults
column.initStretchWeightOrWidth = initWidthOrWeight
if (table.isInitializing) {
// Init width or weight
if (column.widthRequest < 0f && column.stretchWeight < 0f) {
if (flags has Tcf.WidthFixed && initWidthOrWeight > 0f)
column.widthRequest = initWidthOrWeight
if (flags has Tcf.WidthStretch)
column.stretchWeight = initWidthOrWeight.takeIf { it > 0f } ?: -1f
// Disable auto-fit if an explicit width/weight has been specified
if (initWidthOrWeight > 0f)
column.autoFitQueue = 0x00
}
// Init default visibility/sort state
if (flags has Tcf.DefaultHide && table.settingsLoadedFlags hasnt Tf.Hideable) {
column.isEnabled = false
column.isEnabledNextFrame = false
}
if (flags has Tcf.DefaultSort && table.settingsLoadedFlags hasnt Tf.Sortable) {
column.sortOrder = 0 // Multiple columns using _DefaultSort will be reassigned unique SortOrder values when building the sort specs.
column.sortDirection = when {
column.flags has Tcf.PreferSortDescending -> SortDirection.Descending
else -> SortDirection.Ascending
}
}
}
// Store name (append with zero-terminator in contiguous buffer)
column.nameOffset = -1
if (label != null && label.isNotEmpty()) {
column.nameOffset = table.columnsNames.size
table.columnsNames += label
}
}
/** [Public]
* lock columns/rows so they stay visible when scrolled. */
fun tableSetupScrollFreeze(columns: Int, rows: Int) {
val table = g.currentTable
check(table != null) { "Need to call TableSetupColumn() after BeginTable()!" }
assert(!table.isLayoutLocked) { "Need to call TableSetupColumn() before first row!" }
assert(columns in 0 until TABLE_MAX_COLUMNS)
assert(rows in 0..127) // Arbitrary limit
table.freezeColumnsRequest = if (table.flags has Tf.ScrollX) columns else 0
table.freezeColumnsCount = if (table.innerWindow!!.scroll.x != 0f) table.freezeColumnsRequest else 0
table.freezeRowsRequest = if (table.flags has Tf.ScrollY) rows else 0
table.freezeRowsCount = if (table.innerWindow!!.scroll.y != 0f) table.freezeRowsRequest else 0
table.isUnfrozenRows = table.freezeRowsCount == 0 // Make sure this is set before TableUpdateLayout() so ImGuiListClipper can benefit from it.b
}
/** [Public] This is a helper to output TableHeader() calls based on the column names declared in TableSetupColumn().
* The intent is that advanced users willing to create customized headers would not need to use this helper
* and can create their own! For example: TableHeader() may be preceeded by Checkbox() or other custom widgets.
* See 'Demo->Tables->Custom headers' for a demonstration of implementing a custom version of this.
* This code is constructed to not make much use of internal functions, as it is intended to be a template to copy.
* FIXME-TABLE: TableOpenContextMenu() and TableGetHeaderRowHeight() are not public.
*
* submit all headers cells based on data provided to TableSetupColumn() + submit context menu */
fun tableHeadersRow() {
val table = g.currentTable
check(table != null) { "Need to call TableHeadersRow() after BeginTable()!" }
// Layout if not already done (this is automatically done by TableNextRow, we do it here solely to facilitate stepping in debugger as it is frequent to step in TableUpdateLayout)
if (!table.isLayoutLocked)
table.updateLayout()
// Open row
val rowY1 = ImGui.cursorScreenPos.y
val rowHeight = tableGetHeaderRowHeight()
tableNextRow(Trf.Headers.i, rowHeight)
if (table.hostSkipItems) // Merely an optimization, you may skip in your own code.
return
val columnsCount = tableGetColumnCount()
for (columnN in 0 until columnsCount) {
if (!tableSetColumnIndex(columnN))
continue
// Push an id to allow unnamed labels (generally accidental, but let's behave nicely with them)
// - in your own code you may omit the PushID/PopID all-together, provided you know they won't collide
// - table->InstanceCurrent is only >0 when we use multiple BeginTable/EndTable calls with same identifier.
val name = tableGetColumnName(columnN)!!
pushID(table.instanceCurrent * table.columnsCount + columnN)
tableHeader(name)
popID()
}
// Allow opening popup from the right-most section after the last column.
val mousePos = ImGui.mousePos
if (isMouseReleased(1) && tableGetHoveredColumn() == columnsCount)
if (mousePos.y >= rowY1 && mousePos.y < rowY1 + rowHeight)
tableOpenContextMenu(-1) // Will open a non-column-specific popup.
}
/** Emit a column header (text + optional sort order)
* We cpu-clip text here so that all columns headers can be merged into a same draw call.
* Note that because of how we cpu-clip and display sorting indicators, you _cannot_ use SameLine() after a TableHeader()
*
* submit one header cell manually (rarely used) */
fun tableHeader(label: String = "") {
val window = g.currentWindow!!
if (window.skipItems)
return
val table = g.currentTable
check(table != null) { "Need to call TableHeader() after BeginTable()!" }
assert(table.currentColumn != -1)
val columnN = table.currentColumn
val column = table.columns[columnN]
// Label
// if (label == NULL) -> default parameter
// label = "";
val labelEnd = findRenderedTextEnd(label)
val labelSize = calcTextSize(label.toByteArray(), 0, labelEnd, true)
val labelPos = Vec2(window.dc.cursorPos)
// If we already got a row height, there's use that.
// FIXME-TABLE: Padding problem if the correct outer-padding CellBgRect strays off our ClipRect
val cellR = table getCellBgRect columnN
val labelHeight = labelSize.y max (table.rowMinHeight - table.cellPaddingY * 2f)
// Calculate ideal size for sort order arrow
var wArrow = 0f
var wSortText = 0f
var sortOrderSuf = ""
val ARROW_SCALE = 0.65f
if (table.flags has Tf.Sortable && column.flags hasnt Tcf.NoSort) {
wArrow = floor(g.fontSize * ARROW_SCALE + g.style.framePadding.x)
if (column.sortOrder > 0) {
sortOrderSuf = "${column.sortOrder + 1}"
wSortText = g.style.itemInnerSpacing.x + calcTextSize(sortOrderSuf).x
}
}
// We feed our unclipped width to the column without writing on CursorMaxPos, so that column is still considering for merging.
val maxPosX = labelPos.x + labelSize.x + wSortText + wArrow
column.contentMaxXHeadersUsed = column.contentMaxXHeadersUsed max column.workMaxX
column.contentMaxXHeadersIdeal = column.contentMaxXHeadersIdeal max maxPosX
// Keep header highlighted when context menu is open.
val selected = table.isContextPopupOpen && table.contextPopupColumn == columnN && table.instanceInteracted == table.instanceCurrent
val id = window.getID(label)
val bb = Rect(cellR.min.x, cellR.min.y, cellR.max.x, cellR.max.y max (cellR.min.y + labelHeight + g.style.cellPadding.y * 2f))
itemSize(Vec2(0f, labelHeight)) // Don't declare unclipped width, it'll be fed ContentMaxPosHeadersIdeal
if (!itemAdd(bb, id))
return
//GetForegroundDrawList()->AddRect(cell_r.Min, cell_r.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG]
//GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG]
// Using AllowItemOverlap mode because we cover the whole cell, and we want user to be able to submit subsequent items.
val (pressed, hovered, held) = buttonBehavior(bb, id, ButtonFlag.AllowItemOverlap.i)
if (g.activeId != id)
setItemAllowOverlap()
if (held || hovered || selected) {
val col = if (held) Col.HeaderActive else if (hovered) Col.HeaderHovered else Col.Header
//RenderFrame(bb.Min, bb.Max, col, false, 0.0f);
tableSetBgColor(TableBgTarget.CellBg, col.u32, table.currentColumn)
renderNavHighlight(bb, id, NavHighlightFlag.TypeThin or NavHighlightFlag.NoRounding)
} else // Submit single cell bg color in the case we didn't submit a full header row
if (table.rowFlags hasnt Trf.Headers)
tableSetBgColor(TableBgTarget.CellBg, Col.TableHeaderBg.u32, table.currentColumn)
if (held)
table.heldHeaderColumn = columnN
window.dc.cursorPos.y -= g.style.itemSpacing.y * 0.5f
// Drag and drop to re-order columns.
// FIXME-TABLE: Scroll request while reordering a column and it lands out of the scrolling zone.
if (held && table.flags has Tf.Reorderable && isMouseDragging(MouseButton.Left) && !g.dragDropActive) {
// While moving a column it will jump on the other side of the mouse, so we also test for MouseDelta.x
table.reorderColumn = columnN
table.instanceInteracted = table.instanceCurrent
// We don't reorder: through the frozen<>unfrozen line, or through a column that is marked with ImGuiTableColumnFlags_NoReorder.
if (g.io.mouseDelta.x < 0.0f && g.io.mousePos.x < cellR.min.x)
table.columns.getOrNull(column.prevEnabledColumn)?.let { prevColumn ->
if (((column.flags or prevColumn.flags) and Tcf.NoReorder) == 0)
if (column.indexWithinEnabledSet < table.freezeColumnsRequest == prevColumn.indexWithinEnabledSet < table.freezeColumnsRequest)
table.reorderColumnDir = -1
}
if (g.io.mouseDelta.x > 0f && g.io.mousePos.x > cellR.max.x)
table.columns.getOrNull(column.nextEnabledColumn)?.let { nextColumn ->
if (((column.flags or nextColumn.flags) and Tcf.NoReorder) == 0)
if (column.indexWithinEnabledSet < table.freezeColumnsRequest == nextColumn.indexWithinEnabledSet < table.freezeColumnsRequest)
table.reorderColumnDir = +1
}
}
// Sort order arrow
val ellipsisMax = cellR.max.x - wArrow - wSortText
if (table.flags has Tf.Sortable && column.flags hasnt Tcf.NoSort) {
if (column.sortOrder != -1) {
var x = cellR.min.x max (cellR.max.x - wArrow - wSortText)
val y = labelPos.y
if (column.sortOrder > 0) {
pushStyleColor(Col.Text, getColorU32(Col.Text, 0.7f))
renderText(Vec2(x + g.style.itemInnerSpacing.x, y), sortOrderSuf)
popStyleColor()
x += wSortText
}
window.drawList.renderArrow(Vec2(x, y), Col.Text.u32, if (column.sortDirection == SortDirection.Ascending) Dir.Up else Dir.Down, ARROW_SCALE)
}
// Handle clicking on column header to adjust Sort Order
if (pressed && table.reorderColumn != columnN) {
val sortDirection = tableGetColumnNextSortDirection(column)
tableSetColumnSortDirection(columnN, sortDirection, g.io.keyShift)
}
}
// Render clipped label. Clipping here ensure that in the majority of situations, all our header cells will
// be merged into a single draw call.
//window->DrawList->AddCircleFilled(ImVec2(ellipsis_max, label_pos.y), 40, IM_COL32_WHITE);
val posMax = Vec2(ellipsisMax, labelPos.y + labelHeight + g.style.framePadding.y)
renderTextEllipsis(window.drawList, labelPos, posMax, ellipsisMax, ellipsisMax, label.toByteArray(), labelEnd, labelSize)
val textClipped = labelSize.x > (ellipsisMax - labelPos.x)
if (textClipped && hovered && g.hoveredIdNotActiveTimer > g.tooltipSlowDelay)
setTooltip(label.substring(0, labelEnd))
// We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden
if (isMouseReleased(1) && isItemHovered())
tableOpenContextMenu(columnN)
}
// Tables: Sorting
// - Call TableGetSortSpecs() to retrieve latest sort specs for the table. NULL when not sorting.
// - When 'SpecsDirty == true' you should sort your data. It will be true when sorting specs have changed
// since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, else you may
// wastefully sort your data every frame!
// - Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable().
/** Return NULL if no sort specs (most often when ImGuiTableFlags_Sortable is not set)
* You can sort your data again when 'SpecsChanged == true'. It will be true with sorting specs have changed since
* last call, or the first time.
* Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable()!
*
* get latest sort specs for the table (NULL if not sorting). */
fun tableGetSortSpecs(): TableSortSpecs? {
val table = g.currentTable!!
if (table.flags hasnt Tf.Sortable)
return null
// Require layout (in case TableHeadersRow() hasn't been called) as it may alter IsSortSpecsDirty in some paths.
if (!table.isLayoutLocked)
table.updateLayout()
if (table.isSortSpecsDirty)
table.sortSpecsBuild()
return table.sortSpecs
}
// Tables: Miscellaneous functions
// - Functions args 'int column_n' treat the default value of -1 as the same as passing the current column index.
/** return number of columns (value passed to BeginTable) */
fun tableGetColumnCount(): Int = g.currentTable?.columnsCount ?: 0
/** return current column index. */
fun tableGetColumnIndex(): Int = g.currentTable?.currentColumn ?: 0
/** Note: for row coloring we use ->RowBgColorCounter which is the same value without counting header rows
*
* return current row index. */
fun tableGetRowIndex(): Int = g.currentTable?.currentRow ?: 0
/** return "" if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column. */
fun tableGetColumnName(columnN: Int = -1): String? {
val table = g.currentTable ?: return null
return table.getColumnName(if (columnN < 0) table.currentColumn else columnN)
}
/** We allow querying for an extra column in order to poll the IsHovered state of the right-most section
*
* return column flags so you can query their Enabled/Visible/Sorted/Hovered status flags. Pass -1 to use current column. */
fun tableGetColumnFlags(columnN_: Int = -1): TableColumnFlags {
val table = g.currentTable ?: return Tcf.None.i
val columnN = if (columnN_ < 0) table.currentColumn else columnN_
return when (columnN) {
table.columnsCount -> if (table.hoveredColumnBody == columnN) Tcf.IsHovered.i else Tcf.None.i
else -> table.columns[columnN].flags
}
}
/** change the color of a cell, row, or column. See ImGuiTableBgTarget_ flags for details. */
fun tableSetBgColor(target: TableBgTarget, color_: Int, columnN_: Int = -1) {
val table = g.currentTable!!
assert(target != TableBgTarget.None)
val color = if (color_ == COL32_DISABLE) 0 else color_
var columnN = columnN_
// We cannot draw neither the cell or row background immediately as we don't know the row height at this point in time.
when (target) {
TableBgTarget.CellBg -> {
if (table.rowPosY1 > table.innerClipRect.max.y) // Discard
return
if (columnN == -1)
columnN = table.currentColumn
if (table.visibleMaskByIndex hasnt (1L shl columnN))
return
if (table.rowCellDataCurrent < 0 || table.rowCellData[table.rowCellDataCurrent].column != columnN)
table.rowCellDataCurrent++
val cellData = table.rowCellData[table.rowCellDataCurrent]
cellData.bgColor = color
cellData.column = columnN
}
TableBgTarget.RowBg0, TableBgTarget.RowBg1 -> {
if (table.rowPosY1 > table.innerClipRect.max.y) // Discard
return
assert(columnN == -1)
val bgIdx = if (target == TableBgTarget.RowBg1) 1 else 0
table.rowBgColor[bgIdx] = color
}
else -> assert(false)
}
}
} | mit | 4c7ac50756da5854c0abb47a28c83f76 | 51.733618 | 200 | 0.653088 | 4.248106 | false | false | false | false |
fabianonline/telegram_backup | src/main/kotlin/de/fabianonline/telegram_backup/LoginManager.kt | 1 | 3359 | package de.fabianonline.telegram_backup
import com.github.badoualy.telegram.api.Kotlogram
import com.github.badoualy.telegram.api.TelegramApp
import com.github.badoualy.telegram.api.TelegramClient
import com.github.badoualy.telegram.tl.api.TLUser
import com.github.badoualy.telegram.tl.api.account.TLPassword
import com.github.badoualy.telegram.tl.api.auth.TLSentCode
import com.github.badoualy.telegram.tl.core.TLBytes
import com.github.badoualy.telegram.tl.exception.RpcErrorException
import java.security.MessageDigest
import java.util.*
class LoginManager(val app: TelegramApp, val target_dir: String, val phoneToUse: String?) {
fun run() {
var phone: String
if (phoneToUse == null) {
println("Please enter your phone number in international format.")
println("Example: +4917077651234")
phone = getLine()
} else {
phone = phoneToUse
}
val file_base = CommandLineController.build_file_base(target_dir, phone)
// We now have an account, so we can create an ApiStorage and TelegramClient.
val storage = ApiStorage(file_base)
val client = Kotlogram.getDefaultClient(app, storage, Kotlogram.PROD_DC4, null)
val sent_code = send_code_to_phone_number(client, phone)
println("Telegram sent you a code. Please enter it here.")
val code = getLine()
try {
verify_code(client, phone, sent_code, code)
} catch(e: PasswordNeededException) {
println("We also need your account password. Please enter it now. It should not be printed, so it's okay if you see nothing while typing it.")
val pw = getPassword()
verify_password(client, pw)
}
System.out.println("Everything seems fine. Please run this tool again with '--account ${phone} to use this account.")
}
private fun send_code_to_phone_number(client: TelegramClient, phone: String): TLSentCode {
return client.authSendCode(false, phone, true)
}
private fun verify_code(client: TelegramClient, phone: String, sent_code: TLSentCode, code: String): TLUser {
try {
val auth = client.authSignIn(phone, sent_code.getPhoneCodeHash(), code)
return auth.getUser().getAsUser()
} catch (e: RpcErrorException) {
if (e.getCode() == 401 && e.getTag()=="SESSION_PASSWORD_NEEDED") {
throw PasswordNeededException()
} else {
throw e
}
}
}
private fun verify_password(client: TelegramClient, password: String): TLUser {
val pw = password.toByteArray(charset = Charsets.UTF_8)
val salt = (client.accountGetPassword() as TLPassword).getCurrentSalt().getData()
val md = MessageDigest.getInstance("SHA-256")
val salted = ByteArray(2 * salt.size + pw.size)
System.arraycopy(salt, 0, salted, 0, salt.size)
System.arraycopy(pw, 0, salted, salt.size, pw.size)
System.arraycopy(salt, 0, salted, salt.size + pw.size, salt.size)
val hash = md.digest(salted)
val auth = client.authCheckPassword(TLBytes(hash))
return auth.getUser().getAsUser()
}
private fun getLine(): String {
if (System.console() != null) {
return System.console().readLine("> ")
} else {
print("> ")
return Scanner(System.`in`).nextLine()
}
}
private fun getPassword(): String {
if (System.console() != null) {
return String(System.console().readPassword("> "))
} else {
return getLine()
}
}
}
class PasswordNeededException: Exception("A password is needed to be able to login to this account.") {}
| gpl-3.0 | 80551b9fcd6ac6c8a8de29561e23d177 | 33.989583 | 145 | 0.718964 | 3.431052 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.