repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bbodi/KotlinReactSpringBootstrap | frontend/src/com/github/andrewoma/flux/flux.kt | 1 | 4390 | package com.github.andrewoma.flux
public abstract class Store {
private val changeListeners: MutableMap<Any, () -> Unit> = hashMapOf()
fun <PAYLOAD> register(dispatcher: Dispatcher, actionDef: ActionDef<PAYLOAD>, callback: DispatchCallbackBody.(PAYLOAD) -> Unit): RegisteredActionHandler {
return dispatcher.register(this, actionDef, callback)
}
fun unRegister(dispatcher: Dispatcher, token: RegisteredActionHandler) {
dispatcher.unRegister(token)
}
public fun addChangeListener(self: Any, callback: () -> Unit) {
changeListeners.put(self, callback)
}
protected fun emitChange() {
changeListeners.values.forEach { it() }
}
fun removeListener(self: Any) {
changeListeners.remove(self)
}
}
public class ActionDef<PAYLOAD> {
public operator fun invoke(dispatcher: Dispatcher, payload: PAYLOAD) {
dispatcher.dispatch(this, payload)
}
}
private class ActionHandlers(val handlers: MutableList<RegisteredActionHandler> = arrayListOf()) {
}
public class RegisteredActionHandler internal constructor(val store: Store, val actionDef: ActionDef<*>, val callback: DispatchCallbackBody.(Any?) -> Unit) {
var pending = false
var handled = false
}
public class DispatchCallbackBody(val dispatcher: Dispatcher, val store: Store) {
fun waitFor(vararg registeredActionHandlers: Store) {
dispatcher.waitFor(registeredActionHandlers)
}
}
class Dispatcher {
private var pendingPayload: Any? = null
private var pendingActionDef: ActionDef<*>? = null
private val actionHandlersList: MutableMap<ActionDef<*>, ActionHandlers> = hashMapOf()
private var dispatching = false
fun <PAYLOAD> register(store: Store, action: ActionDef<PAYLOAD>, callback: DispatchCallbackBody.(PAYLOAD) -> Unit): RegisteredActionHandler {
val actionHandlers = actionHandlersList.getOrPut(action, { ActionHandlers() })
val registeredActionHandler = RegisteredActionHandler(store, action, callback as (DispatchCallbackBody.(Any?) -> Unit) )
actionHandlers.handlers.add(registeredActionHandler)
return registeredActionHandler
}
fun unRegister(registeredActionHandler: RegisteredActionHandler) {
actionHandlersList[registeredActionHandler.actionDef]?.handlers?.remove(registeredActionHandler)
}
fun waitFor(stores: Array<out Store>) {
require(dispatching) { "Dispatcher.waitFor(...): Must be invoked while dispatching." }
val handlersForCurrentAction = actionHandlersList[pendingActionDef]?.handlers.orEmpty()
val (pendingHandlers, nonPendingHandlers) = handlersForCurrentAction.filter { stores.contains(it.store) }.partition { it.pending || it.handled }
val unhandledHandlers = pendingHandlers.firstOrNull { !it.handled }
require(unhandledHandlers == null) { "Dispatcher.waitFor(...): Circular dependency detected while waiting for $unhandledHandlers." }
nonPendingHandlers.forEach {
require(actionHandlersList[it.actionDef]?.handlers?.contains(it) ?: false) { "Dispatcher.waitFor(...): $it does not map to a registered callback." }
invokeCallback(it)
}
}
fun <PAYLOAD> dispatch(action: ActionDef<PAYLOAD>, payload: PAYLOAD) {
require(!dispatching) { "Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch." }
this.startDispatching(action, payload);
try {
actionHandlersList[action]?.handlers?.forEach {
if (!it.pending) {
invokeCallback(it)
}
}
} finally {
this.stopDispatching();
}
}
private fun invokeCallback(it: RegisteredActionHandler) {
it.pending = true
val body = DispatchCallbackBody(this, it.store)
val callback = it.callback
body.callback(pendingPayload)
it.handled = true
}
private fun <PAYLOAD> startDispatching(action: ActionDef<PAYLOAD>, payload: PAYLOAD) {
actionHandlersList[action]?.handlers?.forEach {
it.pending = false
it.handled = false
}
pendingPayload = payload
pendingActionDef = action
dispatching = true
}
private fun stopDispatching() {
pendingActionDef = null
pendingPayload = null
dispatching = false
}
} | mit | b64fb9e78d0d83d9ace299366c4733ce | 36.529915 | 160 | 0.681321 | 5.045977 | false | false | false | false |
equeim/tremotesf-android | app/src/main/kotlin/org/equeim/tremotesf/ui/serversettingsfragment/ServerSettingsFragment.kt | 1 | 4993 | /*
* Copyright (C) 2017-2022 Alexey Rochev <[email protected]>
*
* This file is part of Tremotesf.
*
* Tremotesf 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.
*
* Tremotesf 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 org.equeim.tremotesf.ui.serversettingsfragment
import android.os.Bundle
import android.view.View
import android.widget.ArrayAdapter
import androidx.annotation.LayoutRes
import androidx.annotation.StringRes
import com.google.android.material.snackbar.Snackbar
import org.equeim.libtremotesf.RpcConnectionState
import org.equeim.tremotesf.R
import org.equeim.tremotesf.databinding.ServerSettingsFragmentBinding
import org.equeim.tremotesf.rpc.GlobalRpc
import org.equeim.tremotesf.rpc.statusString
import org.equeim.tremotesf.torrentfile.rpc.Rpc
import org.equeim.tremotesf.ui.NavigationFragment
import org.equeim.tremotesf.ui.utils.*
class ServerSettingsFragment : NavigationFragment(
R.layout.server_settings_fragment,
R.string.server_settings
) {
private val binding by viewLifecycleObject(ServerSettingsFragmentBinding::bind)
private var connectSnackbar: Snackbar? by viewLifecycleObjectNullable()
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
binding.listView.apply {
adapter = ArrayAdapter(
requireContext(),
R.layout.server_settings_fragment_list_item,
resources.getStringArray(R.array.server_settings_items)
)
divider = null
setSelector(android.R.color.transparent)
setOnItemClickListener { _, _, position, _ ->
val directions = when (position) {
0 -> ServerSettingsFragmentDirections.toDownloadingFragment()
1 -> ServerSettingsFragmentDirections.toSeedingFragment()
2 -> ServerSettingsFragmentDirections.toQueueFragment()
3 -> ServerSettingsFragmentDirections.toSpeedFragment()
4 -> ServerSettingsFragmentDirections.toNetworkFragment()
else -> null
}
if (directions != null) {
navigate(directions)
}
}
}
GlobalRpc.status.launchAndCollectWhenStarted(viewLifecycleOwner, ::updateView)
}
private fun updateView(status: Rpc.Status) {
when (status.connectionState) {
RpcConnectionState.Disconnected -> {
connectSnackbar = binding.root.showSnackbar(
message = "",
length = Snackbar.LENGTH_INDEFINITE,
actionText = R.string.connect,
action = GlobalRpc.nativeInstance::connect
) {
if (connectSnackbar == it) {
connectSnackbar = null
}
}
binding.placeholder.text = status.statusString
hideKeyboard()
}
RpcConnectionState.Connecting -> {
binding.placeholder.text = getString(R.string.connecting)
connectSnackbar?.dismiss()
connectSnackbar = null
}
RpcConnectionState.Connected -> {
connectSnackbar?.dismiss()
connectSnackbar = null
}
}
with(binding) {
if (status.connectionState == RpcConnectionState.Connected) {
listView.visibility = View.VISIBLE
placeholderLayout.visibility = View.GONE
} else {
placeholderLayout.visibility = View.VISIBLE
listView.visibility = View.GONE
}
progressBar.visibility = if (status.connectionState == RpcConnectionState.Connecting) {
View.VISIBLE
} else {
View.GONE
}
}
}
open class BaseFragment(
@LayoutRes contentLayoutId: Int,
@StringRes titleRes: Int
) : NavigationFragment(contentLayoutId, titleRes) {
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
GlobalRpc.isConnected.launchAndCollectWhenStarted(viewLifecycleOwner) {
if (!it) {
navController.popBackStack()
}
}
}
}
}
| gpl-3.0 | aaab6a688fe145bce5ad5ad6133e06c1 | 37.407692 | 99 | 0.625275 | 5.468784 | false | false | false | false |
cjkent/osiris | core/src/test/kotlin/ws/osiris/core/MatchTest.kt | 1 | 5906 | package ws.osiris.core
import org.testng.annotations.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
@Test
class MatchTest {
class Components : ComponentsProvider
private val req = Request(HttpMethod.GET, "notUsed", Params(), Params(), Params(), Params(), null)
private val comps = Components()
fun fixedRoute() {
val handler: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val route = LambdaRoute(HttpMethod.GET, "/foo", handler)
val node = RouteNode.create(route)
assertNull(node.match(HttpMethod.GET, "/"))
assertNull(node.match(HttpMethod.GET, "/bar"))
assertNull(node.match(HttpMethod.POST, "/foo"))
assertEquals("1", node.match(HttpMethod.GET, "/foo")!!.handler(comps, req).body)
}
fun fixedRouteMultipleMethods() {
val handler1: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val handler2: RequestHandler<Components> = { req -> req.responseBuilder().build("2") }
val route1 = LambdaRoute(HttpMethod.GET, "/foo", handler1)
val route2 = LambdaRoute(HttpMethod.POST, "/foo", handler2)
val node = RouteNode.create(route1, route2)
assertNull(node.match(HttpMethod.GET, "/"))
assertEquals("1", node.match(HttpMethod.GET, "/foo")!!.handler(comps, req).body)
assertEquals("2", node.match(HttpMethod.POST, "/foo")!!.handler(comps, req).body)
}
fun multipleFixedRoutes() {
val handler1: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val handler2: RequestHandler<Components> = { req -> req.responseBuilder().build("2") }
val route1 = LambdaRoute(HttpMethod.GET, "/foo", handler1)
val route2 = LambdaRoute(HttpMethod.POST, "/bar/baz", handler2)
val node = RouteNode.create(route1, route2)
assertNull(node.match(HttpMethod.GET, "/"))
assertNull(node.match(HttpMethod.GET, "/foo/baz"))
assertEquals("1", node.match(HttpMethod.GET, "/foo")!!.handler(comps, req).body)
assertEquals("2", node.match(HttpMethod.POST, "/bar/baz")!!.handler(comps, req).body)
}
fun variableRoute() {
val handler: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val route = LambdaRoute(HttpMethod.GET, "/{foo}", handler)
val node = RouteNode.create(route)
assertNull(node.match(HttpMethod.GET, "/"))
assertNull(node.match(HttpMethod.POST, "/bar"))
val match = node.match(HttpMethod.GET, "/bar")
val response = match!!.handler(comps, req)
assertEquals("1", response.body)
assertEquals(mapOf("foo" to "bar"), match.vars)
}
fun variableRouteMultipleMethods() {
val handler1: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val handler2: RequestHandler<Components> = { req -> req.responseBuilder().build("2") }
val route1 = LambdaRoute(HttpMethod.GET, "/{foo}", handler1)
val route2 = LambdaRoute(HttpMethod.POST, "/{foo}", handler2)
val node = RouteNode.create(route1, route2)
assertNull(node.match(HttpMethod.GET, "/"))
val match1 = node.match(HttpMethod.GET, "/bar")
val response1 = match1!!.handler(comps, req)
assertEquals("1", response1.body)
assertEquals(mapOf("foo" to "bar"), match1.vars)
val match2 = node.match(HttpMethod.POST, "/bar")
val response2 = match2!!.handler(comps, req)
assertEquals("2", response2.body)
assertEquals(mapOf("foo" to "bar"), match2.vars)
}
fun variableRouteMultipleVariables() {
val handler: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val route = LambdaRoute(HttpMethod.GET, "/{foo}/bar/{baz}", handler)
val node = RouteNode.create(route)
val match = node.match(HttpMethod.GET, "/abc/bar/def")
val response = match!!.handler(comps, req)
assertEquals(mapOf("foo" to "abc", "baz" to "def"), match.vars)
assertEquals("1", response.body)
}
fun multipleVariableRoutes() {
val handler1: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val handler2: RequestHandler<Components> = { req -> req.responseBuilder().build("2") }
val route1 = LambdaRoute(HttpMethod.GET, "/{foo}", handler1)
val route2 = LambdaRoute(HttpMethod.POST, "/{foo}/baz", handler2)
val node = RouteNode.create(route1, route2)
val match1 = node.match(HttpMethod.GET, "/bar")
val response1 = match1!!.handler(comps, req)
assertEquals("1", response1.body)
assertEquals(mapOf("foo" to "bar"), match1.vars)
val match2 = node.match(HttpMethod.POST, "/bar/baz")
val response2 = match2!!.handler(comps, req)
assertEquals("2", response2.body)
assertEquals(mapOf("foo" to "bar"), match2.vars)
assertNull(node.match(HttpMethod.POST, "/bar/qux"))
}
fun fixedTakesPriority() {
val handler1: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val handler2: RequestHandler<Components> = { req -> req.responseBuilder().build("2") }
val route1 = LambdaRoute(HttpMethod.GET, "/{foo}", handler1)
val route2 = LambdaRoute(HttpMethod.GET, "/foo", handler2)
val node = RouteNode.create(route1, route2)
assertEquals("2", node.match(HttpMethod.GET, "/foo")!!.handler(comps, req).body)
}
fun handlerAtRoot() {
val handler: RequestHandler<Components> = { req -> req.responseBuilder().build("1") }
val route = LambdaRoute(HttpMethod.GET, "/", handler)
val node = RouteNode.create(route)
assertNull(node.match(HttpMethod.GET, "/foo"))
assertEquals("1", node.match(HttpMethod.GET, "/")!!.handler(comps, req).body)
}
}
| apache-2.0 | 4858111d9f5a36bc7870284080c4c986 | 48.216667 | 102 | 0.638673 | 4.020422 | false | false | false | false |
tbrooks8/quasar | quasar-kotlin/src/test/kotlin/co/paralleluniverse/kotlin/actors/PingPongWithDefer.kt | 1 | 5244 | /*
* Quasar: lightweight threads and actors for the JVM.
* Copyright (c) 2015, Parallel Universe Software Co. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 3.0
* as published by the Free Software Foundation.
*/
package co.paralleluniverse.kotlin.actors
import co.paralleluniverse.actors.*
import co.paralleluniverse.actors.behaviors.BehaviorActor
import co.paralleluniverse.actors.behaviors.ProxyServerActor
import co.paralleluniverse.actors.behaviors.Supervisor
import co.paralleluniverse.actors.behaviors.Supervisor.*
import co.paralleluniverse.actors.behaviors.Supervisor.ChildMode
import co.paralleluniverse.actors.behaviors.Supervisor.ChildMode.*
import co.paralleluniverse.actors.behaviors.SupervisorActor
import co.paralleluniverse.actors.behaviors.SupervisorActor.*
import co.paralleluniverse.actors.behaviors.SupervisorActor.RestartStrategy.*
import co.paralleluniverse.fibers.Suspendable
import org.junit.Test
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit.*
import co.paralleluniverse.kotlin.Actor
import co.paralleluniverse.kotlin.Actor.Companion.Timeout
import co.paralleluniverse.kotlin.*
import java.text.SimpleDateFormat
import java.util.*
/**
* @author circlespainter
*/
// This example is meant to be a translation of the canonical
// Erlang [ping-pong example](http://www.erlang.org/doc/getting_started/conc_prog.html#id67347).
data class Msg(val txt: String, val from: ActorRef<Any?>)
val sdfDate = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
fun now(): String = "[${sdfDate.format(Date())}]"
class Ping(val n: Int) : Actor() {
@Suspendable override fun doRun() {
val pong: ActorRef<Any> = ActorRegistry.getActor("pong")
for(i in 1..n) {
val msg = Msg("ping$i", self())
println("${now()} Ping sending '$msg' to '$pong'")
pong.send(msg) // Fiber-blocking
println("${now()} Ping sent '$msg' to '$pong'")
println("${now()} Ping sending garbage 'aaa' to '$pong'")
pong.send("aaa") // Fiber-blocking
println("${now()} Ping sent garbage 'aaa' to '$pong'")
println("${now()} Ping receiving without timeout")
receive { // Fiber-blocking
println("${now()} Ping received '$it' (${it.javaClass})")
when (it) {
is String -> {
if (!it.startsWith("pong")) {
println("${now()} Ping discarding string '$it'")
null
}
}
else -> {
println("${now()} Ping discarding non-string '$it'")
null // Discard
}
}
}
}
println("${now()} Ping sending 'finished' to '$pong'")
pong.send("finished") // Fiber-blocking
println("${now()} Ping sent 'finished' to '$pong', exiting")
}
}
class Pong() : Actor() {
@Suspendable override fun doRun() {
var discardGarbage = false
while (true) {
println("${now()} Pong receiving with 1 sec timeout")
receive(1, SECONDS) { // Fiber-blocking
println("${now()} Pong received '$it' ('${it.javaClass}')")
when (it) {
is Msg -> {
if (it.txt.startsWith("ping")) {
val msg = "pong for ${it.txt}"
println("${now()} Pong sending '$msg' to '${it.from}'")
it.from.send(msg) // Fiber-blocking
println("${now()} Pong sent '$msg' to ${it.from}")
}
}
"finished" -> {
println("${now()} Pong received 'finished', exiting")
return // Non-local return, exit actor
}
is Timeout -> {
println("${now()} Pong timeout in 'receive', exiting")
return // Non-local return, exit actor
}
else -> {
if (discardGarbage) {
println("${now()} Pong discarding '$it'")
null
} else {
discardGarbage = true // Net times discard
println("${now()} Pong deferring '$it'")
defer()
}
}
}
}
}
}
}
public class KotlinPingPongActorTestWithDefer {
@Test public fun testActors() {
val pong = spawn(register("pong", Pong()))
val ping = spawn(Ping(3))
LocalActor.join(pong)
LocalActor.join(ping)
}
}
| gpl-3.0 | 1cb803f9cb20b6865592bb4824bb21ae | 39.338462 | 96 | 0.530702 | 4.873606 | false | false | false | false |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/view/PaymentMethodsAdapter.kt | 1 | 14190 | package com.stripe.android.view
import android.content.Context
import android.content.res.ColorStateList
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.ViewCompat
import androidx.core.widget.ImageViewCompat
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.RecyclerView
import com.stripe.android.R
import com.stripe.android.databinding.AddPaymentMethodRowBinding
import com.stripe.android.databinding.GooglePayRowBinding
import com.stripe.android.databinding.MaskedCardRowBinding
import com.stripe.android.model.PaymentMethod
/**
* A [RecyclerView.Adapter] that holds a set of [MaskedCardView] items for a given set
* of [PaymentMethod] objects.
*/
internal class PaymentMethodsAdapter constructor(
intentArgs: PaymentMethodsActivityStarter.Args,
private val addableTypes: List<PaymentMethod.Type> = listOf(PaymentMethod.Type.Card),
initiallySelectedPaymentMethodId: String? = null,
private val shouldShowGooglePay: Boolean = false,
private val useGooglePay: Boolean = false,
private val canDeletePaymentMethods: Boolean = true
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
internal val paymentMethods = mutableListOf<PaymentMethod>()
internal var selectedPaymentMethodId: String? = initiallySelectedPaymentMethodId
internal val selectedPaymentMethod: PaymentMethod?
get() {
return selectedPaymentMethodId?.let { selectedPaymentMethodId ->
paymentMethods.firstOrNull { it.id == selectedPaymentMethodId }
}
}
internal var listener: Listener? = null
private val googlePayCount = 1.takeIf { shouldShowGooglePay } ?: 0
private val _addPaymentMethodArgs = MutableLiveData<AddPaymentMethodActivityStarter.Args>()
val addPaymentMethodArgs: LiveData<AddPaymentMethodActivityStarter.Args> = _addPaymentMethodArgs
internal val addCardArgs = AddPaymentMethodActivityStarter.Args.Builder()
.setBillingAddressFields(intentArgs.billingAddressFields)
.setShouldAttachToCustomer(true)
.setIsPaymentSessionActive(intentArgs.isPaymentSessionActive)
.setPaymentMethodType(PaymentMethod.Type.Card)
.setAddPaymentMethodFooter(intentArgs.addPaymentMethodFooterLayoutId)
.setPaymentConfiguration(intentArgs.paymentConfiguration)
.setWindowFlags(intentArgs.windowFlags)
.build()
internal val addFpxArgs = AddPaymentMethodActivityStarter.Args.Builder()
.setIsPaymentSessionActive(intentArgs.isPaymentSessionActive)
.setPaymentMethodType(PaymentMethod.Type.Fpx)
.setPaymentConfiguration(intentArgs.paymentConfiguration)
.build()
init {
setHasStableIds(true)
}
@JvmSynthetic
internal fun setPaymentMethods(paymentMethods: List<PaymentMethod>) {
this.paymentMethods.clear()
this.paymentMethods.addAll(paymentMethods)
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return paymentMethods.size + addableTypes.size + googlePayCount
}
override fun getItemViewType(position: Int): Int {
return when {
isGooglePayPosition(position) -> ViewType.GooglePay.ordinal
isPaymentMethodsPosition(position) -> {
val type = getPaymentMethodAtPosition(position).type
if (PaymentMethod.Type.Card == type) {
ViewType.Card.ordinal
} else {
super.getItemViewType(position)
}
}
else -> {
val paymentMethodType =
addableTypes[getAddableTypesPosition(position)]
return when (paymentMethodType) {
PaymentMethod.Type.Card -> ViewType.AddCard.ordinal
PaymentMethod.Type.Fpx -> ViewType.AddFpx.ordinal
else ->
throw IllegalArgumentException(
"Unsupported PaymentMethod type: ${paymentMethodType.code}"
)
}
}
}
}
private fun isGooglePayPosition(position: Int): Boolean {
return shouldShowGooglePay && position == 0
}
private fun isPaymentMethodsPosition(position: Int): Boolean {
val range = if (shouldShowGooglePay) {
1..paymentMethods.size
} else {
0 until paymentMethods.size
}
return position in range
}
override fun getItemId(position: Int): Long {
return when {
isGooglePayPosition(position) ->
GOOGLE_PAY_ITEM_ID
isPaymentMethodsPosition(position) ->
getPaymentMethodAtPosition(position).hashCode().toLong()
else ->
addableTypes[getAddableTypesPosition(position)].code.hashCode().toLong()
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is ViewHolder.PaymentMethodViewHolder -> {
val paymentMethod = getPaymentMethodAtPosition(position)
holder.setPaymentMethod(paymentMethod)
holder.setSelected(paymentMethod.id == selectedPaymentMethodId)
holder.itemView.setOnClickListener {
onPositionClicked(holder.bindingAdapterPosition)
}
}
is ViewHolder.GooglePayViewHolder -> {
holder.itemView.setOnClickListener {
selectedPaymentMethodId = null
listener?.onGooglePayClick()
}
holder.bind(useGooglePay)
}
is ViewHolder.AddCardPaymentMethodViewHolder -> {
holder.itemView.setOnClickListener {
_addPaymentMethodArgs.value = addCardArgs
}
}
is ViewHolder.AddFpxPaymentMethodViewHolder -> {
holder.itemView.setOnClickListener {
_addPaymentMethodArgs.value = addFpxArgs
}
}
}
}
@JvmSynthetic
internal fun onPositionClicked(position: Int) {
updateSelectedPaymentMethod(position)
listener?.onPaymentMethodClick(getPaymentMethodAtPosition(position))
}
private fun updateSelectedPaymentMethod(position: Int) {
val currentlySelectedPosition = paymentMethods.indexOfFirst {
it.id == selectedPaymentMethodId
}
if (currentlySelectedPosition != position) {
// selected a new Payment Method
notifyItemChanged(currentlySelectedPosition)
selectedPaymentMethodId = paymentMethods.getOrNull(position)?.id
}
// Notify the current position even if it's the currently selected position so that the
// ItemAnimator defined in PaymentMethodActivity is triggered.
notifyItemChanged(position)
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RecyclerView.ViewHolder {
return when (ViewType.values()[viewType]) {
ViewType.Card -> createPaymentMethodViewHolder(parent)
ViewType.AddCard -> createAddCardPaymentMethodViewHolder(parent)
ViewType.AddFpx -> createAddFpxPaymentMethodViewHolder(parent)
ViewType.GooglePay -> createGooglePayViewHolder(parent)
}
}
private fun createAddCardPaymentMethodViewHolder(
parent: ViewGroup
): ViewHolder.AddCardPaymentMethodViewHolder {
return ViewHolder.AddCardPaymentMethodViewHolder(parent.context, parent)
}
private fun createAddFpxPaymentMethodViewHolder(
parent: ViewGroup
): ViewHolder.AddFpxPaymentMethodViewHolder {
return ViewHolder.AddFpxPaymentMethodViewHolder(parent.context, parent)
}
private fun createPaymentMethodViewHolder(
parent: ViewGroup
): ViewHolder.PaymentMethodViewHolder {
val viewHolder = ViewHolder.PaymentMethodViewHolder(parent)
if (canDeletePaymentMethods) {
ViewCompat.addAccessibilityAction(
viewHolder.itemView,
parent.context.getString(R.string.delete_payment_method)
) { _, _ ->
listener?.onDeletePaymentMethodAction(
paymentMethod = getPaymentMethodAtPosition(viewHolder.bindingAdapterPosition)
)
true
}
}
return viewHolder
}
private fun createGooglePayViewHolder(
parent: ViewGroup
): ViewHolder.GooglePayViewHolder {
return ViewHolder.GooglePayViewHolder(parent.context, parent)
}
@JvmSynthetic
internal fun deletePaymentMethod(paymentMethod: PaymentMethod) {
getPosition(paymentMethod)?.let {
paymentMethods.remove(paymentMethod)
notifyItemRemoved(it)
}
}
@JvmSynthetic
internal fun resetPaymentMethod(paymentMethod: PaymentMethod) {
getPosition(paymentMethod)?.let {
notifyItemChanged(it)
}
}
/**
* Given an adapter position, translate to a `paymentMethods` element
*/
@JvmSynthetic
internal fun getPaymentMethodAtPosition(position: Int): PaymentMethod {
return paymentMethods[getPaymentMethodIndex(position)]
}
/**
* Given an adapter position, translate to a `paymentMethods` index
*/
private fun getPaymentMethodIndex(position: Int): Int {
return position - googlePayCount
}
/**
* Given a Payment Method, get its adapter position. For example, if the Google Pay button is
* being shown, the 2nd element in [paymentMethods] is actually the 3rd item in the adapter.
*/
internal fun getPosition(paymentMethod: PaymentMethod): Int? {
return paymentMethods.indexOf(paymentMethod).takeIf { it >= 0 }?.let {
it + googlePayCount
}
}
private fun getAddableTypesPosition(position: Int): Int {
return position - paymentMethods.size - googlePayCount
}
internal sealed class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
internal class AddCardPaymentMethodViewHolder(
viewBinding: AddPaymentMethodRowBinding
) : RecyclerView.ViewHolder(viewBinding.root) {
constructor(context: Context, parent: ViewGroup) : this(
AddPaymentMethodRowBinding.inflate(
LayoutInflater.from(context),
parent,
false
)
)
init {
itemView.id = R.id.stripe_payment_methods_add_card
itemView.contentDescription =
itemView.resources.getString(R.string.payment_method_add_new_card)
viewBinding.label.text =
itemView.resources.getString(R.string.payment_method_add_new_card)
}
}
internal class AddFpxPaymentMethodViewHolder(
viewBinding: AddPaymentMethodRowBinding
) : RecyclerView.ViewHolder(viewBinding.root) {
constructor(context: Context, parent: ViewGroup) : this(
AddPaymentMethodRowBinding.inflate(
LayoutInflater.from(context),
parent,
false
)
)
init {
itemView.id = R.id.stripe_payment_methods_add_fpx
itemView.contentDescription =
itemView.resources.getString(R.string.payment_method_add_new_fpx)
viewBinding.label.text =
itemView.resources.getString(R.string.payment_method_add_new_fpx)
}
}
internal class GooglePayViewHolder(
private val viewBinding: GooglePayRowBinding
) : RecyclerView.ViewHolder(viewBinding.root) {
constructor(context: Context, parent: ViewGroup) : this(
GooglePayRowBinding.inflate(
LayoutInflater.from(context),
parent,
false
)
)
private val themeConfig = ThemeConfig(itemView.context)
init {
ImageViewCompat.setImageTintList(
viewBinding.checkIcon,
ColorStateList.valueOf(themeConfig.getTintColor(true))
)
}
fun bind(isSelected: Boolean) {
viewBinding.label.setTextColor(
ColorStateList.valueOf(themeConfig.getTextColor(isSelected))
)
viewBinding.checkIcon.visibility = if (isSelected) {
View.VISIBLE
} else {
View.INVISIBLE
}
itemView.isSelected = isSelected
}
}
internal class PaymentMethodViewHolder constructor(
private val viewBinding: MaskedCardRowBinding
) : ViewHolder(viewBinding.root) {
constructor(parent: ViewGroup) : this(
MaskedCardRowBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
fun setPaymentMethod(paymentMethod: PaymentMethod) {
viewBinding.maskedCardItem.setPaymentMethod(paymentMethod)
}
fun setSelected(selected: Boolean) {
viewBinding.maskedCardItem.isSelected = selected
itemView.isSelected = selected
}
}
}
internal interface Listener {
fun onPaymentMethodClick(paymentMethod: PaymentMethod)
fun onGooglePayClick()
fun onDeletePaymentMethodAction(paymentMethod: PaymentMethod)
}
internal enum class ViewType {
Card,
AddCard,
AddFpx,
GooglePay
}
internal companion object {
internal val GOOGLE_PAY_ITEM_ID = "pm_google_pay".hashCode().toLong()
}
}
| mit | db373b82c3e6efefc1a9ece233d8e682 | 35.761658 | 100 | 0.629951 | 5.952181 | false | false | false | false |
congwiny/KotlinBasic | src/main/kotlin/reflection/ReflectionTest.kt | 1 | 3607 | package reflection
import kotlin.reflect.KFunction2
import kotlin.reflect.full.memberProperties
var counter = 0
fun main(args: Array<String>) {
val person = Person("Alice", 29)
//返回一个KClass<Person>的实例
val kClass = person.javaClass.kotlin
println(kClass === Person::class) //true
println(kClass.simpleName) //Person
kClass.memberProperties.forEach {
println(it.name)
} //age, name
//反射调用foo函数
val kFunction = ::foo
kFunction.call(42)
kFunction.invoke(42)
kFunction(42) //不用显示的invoke就可以调用kFunction
/**
* KFunction2的类型称为合成的编译器生成类型,在kotlin.reflect中找不到他们的声明。
* 这意味着你可以使用任意数量参数的函数接口。
* 合成类型的方式减小了kotlin-reflect.jar的尺寸,同时避免了对函数类型参数数量的人为限制。
*
* KFunctionN每一个类型都继承了KFunction并加上一个额外的成员invoke,它拥有数量刚好的参数。
* 例如,KFunction2 声明了operator fun invoke (pl : P1, p2 : P2) : R,
* 其中P1和P2 代表着函数的参数类型,而R代表着函数的返回类型。
*
* 因此,如果你有这样一个具体类型的KFunction ,它的形参类型和返回类型是确定的,
* 那么应该优先使用这个具体类型的invoke 方法。
* call 方法是对所有类型都有效的通用手段,但是它不提供类型安全性。
*/
val kFunction2: KFunction2<Int, Int, Int> = ::sum
println(kFunction2.invoke(1, 2) + kFunction2(3, 4)) //10
/**
* 你也可以在一个KProperty实例上调用call方法,它会调用该属性的getter。
* 但是属性接口为你提供了一个更好的获取属性值的方式:get方法。
*
* 要访问get方法,你需要根据属性声明的方式来使用正确的属性接口。
* 顶层属性表示为KProperty0接口的实例,它有一个无参数的get方法:
*/
val kProperty = ::counter
kProperty.setter.call(21) //通过反射调用setter,把21作为实参传递
println(kProperty.call()) //通过“call”获取属性的值
println(kProperty.get()) //通过“get”获取属性的值
/**
* 一个成员属性由KProperty1的实例表示,它拥有一个单参数的get方法。
* 要访问该属性的值,必须提供你需要的值所属的那个对象实例。
*
* KProperty1是一个泛型类。变量memberProperty的类型是KProperty<Person, Int> ,
* 其中第一个类型参数表示接收者的类型,而第二个类型参数代表了属性的类型。
* 这样你只能对正确类型的接收者调用它的get方法。而memberProperty.get("Amanda")这样的调用不会通过编译。
* 还有一点值得注意,只能使用反射访问定义在最外层或者类中的属性,而不能访问函数的局部变量。
* 如果你定义了一个局部变量x并试图使用::x来获得它的引用,你会得到一个编译期的错误:
* "References to variables aren't supported yet" (现在还不支持对变量的引用〉。
*/
val person2 = Person("Amanda", 28)
val memberProperty = Person::age //在memberProperty变量中存储了一个指向属性的引用
println(memberProperty.get(person2)) //memberProperty.get(person)来获取属于具体person实例的这个属性的值。
}
fun sum(x: Int, y: Int) = x + y
fun foo(x: Int) = println(x)
class Person(val name: String, val age: Int) | apache-2.0 | 1a87cde9bd6a4d75f16190997447ef5a | 30.944444 | 92 | 0.700739 | 2.714286 | false | false | false | false |
stripe/stripe-android | stripe-test-e2e/src/test/java/com/stripe/android/test/e2e/Request.kt | 1 | 817 | package com.stripe.android.test.e2e
import com.squareup.moshi.Json
import com.stripe.android.core.ApiVersion
sealed class Request {
data class CreatePaymentIntentParams(
@field:Json(name = "create_params") val createParams: CreateParams,
@field:Json(name = "account") val account: String? = null,
@field:Json(name = "version") val version: String = ApiVersion.API_VERSION_CODE
)
data class CreateSetupIntentParams(
@field:Json(name = "create_params") val createParams: CreateParams,
@field:Json(name = "account") val account: String? = null,
@field:Json(name = "version") val version: String = ApiVersion.API_VERSION_CODE
)
data class CreateParams(
@field:Json(name = "payment_method_types") val paymentMethodTypes: List<String>
)
}
| mit | 9ee63be6e68ab9ed7358475f98c72ef0 | 36.136364 | 87 | 0.689106 | 3.890476 | false | false | false | false |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/events/CustomItemGenerationEvent.kt | 1 | 1921 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tealcube.minecraft.bukkit.mythicdrops.events
import com.tealcube.minecraft.bukkit.mythicdrops.api.events.MythicDropsCancellableEvent
import com.tealcube.minecraft.bukkit.mythicdrops.api.items.CustomItem
import org.bukkit.event.HandlerList
import org.bukkit.inventory.ItemStack
class CustomItemGenerationEvent(var customItem: CustomItem, result: ItemStack) :
MythicDropsCancellableEvent() {
companion object {
@JvmStatic
val handlerList = HandlerList()
}
var isModified: Boolean = false
private set
var result: ItemStack = result
set(value) {
field = value
isModified = true
}
override fun getHandlers(): HandlerList = handlerList
}
| mit | ef648df5dc864752405e45967184f1c5 | 41.688889 | 105 | 0.749089 | 4.731527 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/modules/api/components/pagerview/ViewPagerAdapter.kt | 2 | 1484 | package abi43_0_0.host.exp.exponent.modules.api.components.pagerview
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.recyclerview.widget.RecyclerView.Adapter
import java.util.*
class ViewPagerAdapter() : Adapter<ViewPagerViewHolder>() {
private val childrenViews: ArrayList<View> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewPagerViewHolder {
return ViewPagerViewHolder.create(parent)
}
override fun onBindViewHolder(holder: ViewPagerViewHolder, index: Int) {
val container: FrameLayout = holder.container
val child = getChildAt(index)
if (container.childCount > 0) {
container.removeAllViews()
}
if (child.parent != null) {
(child.parent as FrameLayout).removeView(child)
}
container.addView(child)
}
override fun getItemCount(): Int {
return childrenViews.size
}
fun addChild(child: View, index: Int) {
childrenViews.add(index, child)
notifyItemInserted(index)
}
fun getChildAt(index: Int): View {
return childrenViews[index]
}
fun removeChild(child: View) {
val index = childrenViews.indexOf(child)
removeChildAt(index)
}
fun removeAll() {
val removedChildrenCount = childrenViews.size
childrenViews.clear()
notifyItemRangeRemoved(0, removedChildrenCount)
}
fun removeChildAt(index: Int) {
childrenViews.removeAt(index)
notifyItemRemoved(index)
}
}
| bsd-3-clause | 96719af4e2e81fbd5dfc963b24b8a607 | 24.152542 | 90 | 0.727763 | 4.390533 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/macros/MacroExpansionVfsBatch.kt | 2 | 2996 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.macros
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.RefreshQueue
import org.jetbrains.annotations.TestOnly
import org.rust.lang.core.crate.CratePersistentId
import org.rust.lang.core.macros.MacroExpansionFileSystem.FSItem
import org.rust.openapiext.findNearestExistingFile
class MacroExpansionVfsBatch(private val contentRoot: String) {
/**
* Should be used if file was just created and there is no corresponding [VirtualFile] yet.
* If we have [VirtualFile], then [VfsUtil.markDirty] should be used directly.
*/
private val pathsToMarkDirty: MutableSet<String> = hashSetOf()
var hasChanges: Boolean = false
private set
private val expansionFileSystem: MacroExpansionFileSystem = MacroExpansionFileSystem.getInstance()
class Path(val path: String) {
fun toVirtualFile(): VirtualFile? =
MacroExpansionFileSystem.getInstance().findFileByPath(path)
}
fun createFile(crate: CratePersistentId, expansionName: String, content: String, implicit: Boolean = false): Path {
val path = "${crate}/${expansionNameToPath(expansionName)}"
return createFile(path, content, implicit)
}
fun createFile(relativePath: String, content: String, implicit: Boolean = false): Path {
val path = "$contentRoot/$relativePath"
if (implicit) {
expansionFileSystem.createFileWithImplicitContent(path, content.toByteArray().size, mkdirs = true)
} else {
expansionFileSystem.createFileWithExplicitContent(path, content.toByteArray(), mkdirs = true)
}
val parent = path.substring(0, path.lastIndexOf('/'))
pathsToMarkDirty += parent
hasChanges = true
return Path(path)
}
fun deleteFile(file: FSItem) {
file.delete()
val virtualFile = expansionFileSystem.findFileByPath(file.absolutePath())
virtualFile?.let { markDirty(it) }
hasChanges = true
}
@TestOnly
fun deleteFile(file: VirtualFile) {
MacroExpansionFileSystem.getInstance().deleteFile(file.path)
markDirty(file)
hasChanges = true
}
@TestOnly
fun writeFile(file: VirtualFile, content: String) {
MacroExpansionFileSystem.getInstance().setFileContent(file.path, content.toByteArray())
markDirty(file)
hasChanges = true
}
fun applyToVfs(async: Boolean, callback: Runnable? = null) {
val root = expansionFileSystem.findFileByPath("/") ?: return
for (path in pathsToMarkDirty) {
markDirty(root.findNearestExistingFile(path).first)
}
RefreshQueue.getInstance().refresh(async, true, callback, root)
}
private fun markDirty(file: VirtualFile) {
VfsUtil.markDirty(false, false, file)
}
}
| mit | 0704a7008250b63380f5253b53ccd8a1 | 33.436782 | 119 | 0.691923 | 4.847896 | false | false | false | false |
MeilCli/Twitter4HK | library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/aclog/api/tweets/Show.kt | 1 | 941 | package com.twitter.meil_mitu.twitter4hk.aclog.api.tweets
import com.twitter.meil_mitu.twitter4hk.AbsOauth
import com.twitter.meil_mitu.twitter4hk.OauthType
import com.twitter.meil_mitu.twitter4hk.aclog.AbsAclogGet
import com.twitter.meil_mitu.twitter4hk.aclog.converter.IAclogStatusConverter
import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException
class Show<TAclogStatus>(
oauth: AbsOauth,
protected val json: IAclogStatusConverter<TAclogStatus>,
id: Long) : AbsAclogGet<TAclogStatus>(oauth) {
var authorization: Boolean = false
override val isAuthorization = authorization
var id: Long?by longParam("id")
override val url = "$host/api/tweets/show.json"
override val allowOauthType = OauthType.oauthEcho
init {
this.id = id
}
@Throws(Twitter4HKException::class)
override fun call(): TAclogStatus {
return json.toStatus(oauth.get(this))
}
}
| mit | c49fc50141734fdc2f462d67432745fd | 32.607143 | 77 | 0.741764 | 3.88843 | false | false | false | false |
jorjoluiso/QuijoteLui | src/main/kotlin/com/quijotelui/electronico/comprobantes/nota/debito/NotaDebito.kt | 1 | 1610 | package com.quijotelui.electronico.comprobantes.nota.debito
import com.quijotelui.electronico.comprobantes.InformacionTributaria
import comprobantes.InformacionAdicional
import javax.xml.bind.annotation.XmlAttribute
import javax.xml.bind.annotation.XmlElement
import javax.xml.bind.annotation.XmlRootElement
import javax.xml.bind.annotation.XmlType
@XmlRootElement
@XmlType(propOrder = arrayOf("infoTributaria", "infoNotaDebito", "motivos", "infoAdicional"))
class NotaDebito {
@XmlAttribute
private var id : String? = null
@XmlAttribute
private var version : String? = null
@XmlElement(name = "infoTributaria")
private var informacionTributaria = InformacionTributaria()
@XmlElement(name = "infoNotaDebito")
private var informacionNotaDebito = InformacionNotaDebito()
@XmlElement
private var motivos = Motivos()
@XmlElement(name = "infoAdicional")
private var informacionAdicional = InformacionAdicional()
fun setId(id : String) {
this.id = id
}
fun setVersion(version : String) {
this.version = version
}
fun setInformacionTributaria(informacionTributaria : InformacionTributaria) {
this.informacionTributaria = informacionTributaria
}
fun setInformacionNotaCredito(informacionFactura : InformacionNotaDebito) {
this.informacionNotaDebito = informacionFactura
}
fun setMotivos(motivos: Motivos) {
this.motivos = motivos
}
fun setInformacionAdicional(informacionAdicional: InformacionAdicional) {
this.informacionAdicional = informacionAdicional
}
} | gpl-3.0 | d3bbfe9d1f7af703aae1c7c35683c68b | 27.767857 | 93 | 0.745963 | 4.721408 | false | false | false | false |
RSDT/Japp16 | app/src/main/java/nl/rsdt/japp/jotial/auth/Authentication.kt | 1 | 3814 | package nl.rsdt.japp.jotial.auth
import android.app.Activity
import android.content.Intent
import com.google.gson.annotations.SerializedName
import nl.rsdt.japp.R
import nl.rsdt.japp.application.Japp
import nl.rsdt.japp.application.JappPreferences
import nl.rsdt.japp.application.activities.LoginActivity
import nl.rsdt.japp.jotial.net.apis.AuthApi
import org.acra.ktx.sendWithAcra
import retrofit2.Call
import retrofit2.Callback
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 13-7-2016
* Description...
*/
class Authentication : Callback<Authentication.KeyObject> {
private var callback: OnAuthenticationCompletedCallback? = null
private var username: String = ""
private var password: String = ""
fun executeAsync() {
val api = Japp.getApi(AuthApi::class.java)
api.login(LoginBody(username, password)).enqueue(this)
}
override fun onResponse(call: Call<KeyObject>, response: retrofit2.Response<KeyObject>) {
if (response.code() == 200) {
val key = response.body()?.key
/**
* Change the key in the release_preferences.
*/
val pEditor = JappPreferences.visiblePreferences.edit()
pEditor.putString(JappPreferences.ACCOUNT_KEY, key)
pEditor.apply()
callback?.onAuthenticationCompleted(AuthenticationResult(key, 200, Japp.getString(R.string.login_succes)))
} else {
val message: String = if (response.code() == 404) {
Japp.getString(R.string.wrong_data)
} else {
Japp.getString(R.string.error_on_login)
}
callback?.onAuthenticationCompleted(AuthenticationResult("", response.code(), message))
}
}
override fun onFailure(call: Call<KeyObject>, t: Throwable) {
t.sendWithAcra()
callback?.onAuthenticationCompleted(AuthenticationResult("", 0, Japp.getString(R.string.error_on_login)))
}
class AuthenticationResult(val key: String?, val code: Int, val message: String) {
val isSucceeded: Boolean
get() = key != null && !key.isEmpty()
}
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 2-9-2016
* Description...
*/
inner class LoginBody(private val gebruiker: String, private val ww: String)
inner class KeyObject {
@SerializedName("SLEUTEL")
public val key: String = ""
}
inner class ValidateObject {
@SerializedName("exists")
private val exists: Boolean = false
fun exists(): Boolean {
return exists
}
}
class Builder {
internal var buffer = Authentication()
fun setCallback(callback: OnAuthenticationCompletedCallback): Builder {
buffer.callback = callback
return this
}
fun setUsername(username: String): Builder {
buffer.username = username
return this
}
fun setPassword(password: String): Builder {
buffer.password = AeSimpleSHA1.trySHA1(password)
return this
}
fun create(): Authentication {
return buffer
}
}
interface OnAuthenticationCompletedCallback {
fun onAuthenticationCompleted(result: AuthenticationResult)
}
companion object {
val REQUEST_TAG = "Authentication"
/**
* TODO: don't use final here
*/
fun validate(activity: Activity) {
val api = Japp.getApi(AuthApi::class.java)
}
fun startLoginActivity(activity: Activity) {
val intent = Intent(activity, LoginActivity::class.java)
activity.startActivity(intent)
activity.finish()
}
}
}
| apache-2.0 | 972cade31e9a18f173adcb2bb29435b9 | 26.438849 | 118 | 0.621657 | 4.617433 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/ui/view/MaxLineFlexboxLayout.kt | 2 | 3263 | package me.proxer.app.ui.view
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.View.MeasureSpec.AT_MOST
import android.view.View.MeasureSpec.UNSPECIFIED
import android.view.View.MeasureSpec.makeMeasureSpec
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.FrameLayout
import androidx.appcompat.widget.AppCompatButton
import androidx.core.content.withStyledAttributes
import com.google.android.flexbox.FlexboxLayout
import com.jakewharton.rxbinding3.view.clicks
import com.uber.autodispose.android.ViewScopeProvider
import com.uber.autodispose.autoDisposable
import io.reactivex.subjects.PublishSubject
import me.proxer.app.R
import me.proxer.app.util.extension.resolveColor
/**
* @author Ruben Gees
*/
class MaxLineFlexboxLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FlexboxLayout(context, attrs, defStyleAttr) {
val showAllEvents: PublishSubject<Unit> = PublishSubject.create()
var maxLines = Int.MAX_VALUE
private var currentWidth: Int = 0
private var currentLine: Int = 1
private var isShowAllButtonEnabled = false
init {
if (attrs != null) {
context.withStyledAttributes(attrs, R.styleable.MaxLineFlexboxLayout) {
maxLines = getInt(R.styleable.MaxLineFlexboxLayout_maxLines, Int.MAX_VALUE)
}
}
}
override fun removeAllViews() {
isShowAllButtonEnabled = false
currentWidth = 0
currentLine = 1
super.removeAllViews()
}
override fun addView(child: View) {
if (canAddView(child)) {
if (currentWidth + child.measuredWidth > width) {
currentWidth = child.measuredWidth
currentLine++
} else {
currentWidth += child.measuredWidth
}
super.addView(child)
}
}
fun canAddView(view: View): Boolean {
require(width != 0) { "Only call this method after this view has been laid out." }
if (view.measuredWidth == 0) {
view.measure(makeMeasureSpec(width, AT_MOST), makeMeasureSpec(0, UNSPECIFIED))
}
return currentWidth + view.measuredWidth <= width || currentLine + 1 <= maxLines
}
fun enableShowAllButton() {
if (isShowAllButtonEnabled) return
val container = FrameLayout(context)
val button = AppCompatButton(context, null, android.R.attr.borderlessButtonStyle)
button.text = context.getString(R.string.fragment_media_info_show_all)
button.layoutParams = FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT, Gravity.CENTER)
button.setTextColor(context.resolveColor(R.attr.colorSecondary))
button.clicks()
.doOnNext { maxLines = Int.MAX_VALUE }
.autoDisposable(ViewScopeProvider.from(this))
.subscribe(showAllEvents)
container.layoutParams = LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply {
isWrapBefore = true
}
container.addView(button)
super.addView(container)
}
}
| gpl-3.0 | 5dde8fe2a4ff4ee9e63caca86dafba01 | 31.306931 | 98 | 0.689243 | 4.654779 | false | false | false | false |
yt-tkhs/Search-Filter-UI | app/src/main/java/jp/yitt/filter/TopBottomMarginItemDecoration.kt | 1 | 652 | package jp.yitt.filter
import android.graphics.Rect
import android.support.v7.widget.RecyclerView
import android.view.View
class TopBottomMarginItemDecoration(val topMarginPx: Int, val bottomMarginPx: Int) :
RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val itemCount = parent.adapter.itemCount
val position = parent.getChildAdapterPosition(view)
if (position == 0) {
outRect.top = topMarginPx
}
if (position == itemCount - 1) {
outRect.bottom = bottomMarginPx
}
}
}
| apache-2.0 | 096643c5bdd419efc4b4063be0846e8c | 28.636364 | 109 | 0.679448 | 4.496552 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/navigation/BottomNavigationItem.kt | 1 | 3166 | package com.habitrpg.android.habitica.ui.views.navigation
import android.content.Context
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.BottomNavigationItemBinding
import com.habitrpg.common.habitica.extensions.getThemeColor
import com.habitrpg.common.habitica.extensions.isUsingNightModeResources
import com.habitrpg.common.habitica.extensions.layoutInflater
import com.habitrpg.android.habitica.extensions.setTintWith
class BottomNavigationItem @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {
private var selectedIcon: Drawable? = null
private var icon: Drawable? = null
private val binding = BottomNavigationItemBinding.inflate(context.layoutInflater, this)
private var selectedVisibility = View.VISIBLE
private var deselectedVisibility = View.VISIBLE
var isActive = false
set(value) {
field = value
if (isActive) {
binding.selectedTitleView.visibility = selectedVisibility
binding.titleView.visibility = View.GONE
binding.iconView.setImageDrawable(selectedIcon)
if (context.isUsingNightModeResources()) {
binding.iconView.drawable.setTintWith(context.getThemeColor(R.attr.colorPrimaryDistinct), PorterDuff.Mode.SRC_ATOP)
} else {
binding.iconView.drawable.setTintWith(ContextCompat.getColor(context, R.color.white), PorterDuff.Mode.SRC_ATOP)
}
} else {
binding.selectedTitleView.visibility = View.GONE
binding.iconView.setImageDrawable(icon)
binding.titleView.visibility = deselectedVisibility
binding.iconView.drawable.setTintWith(context.getThemeColor(R.attr.textColorPrimaryDark), PorterDuff.Mode.SRC_ATOP)
}
}
var badgeCount: Int = 0
set(value) {
field = value
if (value == 0) {
binding.badge.visibility = View.INVISIBLE
} else {
binding.badge.visibility = View.VISIBLE
binding.badge.text = value.toString()
}
}
init {
val attributes = context.theme?.obtainStyledAttributes(
attrs,
R.styleable.BottomNavigationItem,
0, 0
)
if (attributes != null) {
icon = attributes.getDrawable(R.styleable.BottomNavigationItem_iconDrawable)
selectedIcon = attributes.getDrawable(R.styleable.BottomNavigationItem_selectedIconDrawable)
binding.iconView.setImageDrawable(icon)
binding.titleView.text = attributes.getString(R.styleable.BottomNavigationItem_title)
binding.selectedTitleView.text = attributes.getString(R.styleable.BottomNavigationItem_title)
}
}
}
| gpl-3.0 | f3c80d73daa7951166b221054cee1f2e | 41.783784 | 135 | 0.685723 | 5.190164 | false | false | false | false |
farmerbb/Notepad | app/src/main/java/com/farmerbb/notepad/ui/content/NoteListContent.kt | 1 | 5285 | /* Copyright 2021 Braden Farmer
*
* 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:OptIn(ExperimentalFoundationApi::class)
package com.farmerbb.notepad.ui.content
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.text.BasicText
import androidx.compose.material.Divider
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.farmerbb.notepad.R
import com.farmerbb.notepad.model.NoteMetadata
import com.farmerbb.notepad.ui.components.RtlTextWrapper
import com.farmerbb.notepad.ui.previews.NoteListPreview
import com.farmerbb.notepad.utils.safeGetOrDefault
import java.text.DateFormat
import java.util.Date
private val Date.noteListFormat: String get() = DateFormat
.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
.format(this)
@Composable
fun NoteListContent(
notes: List<NoteMetadata>,
selectedNotes: Map<Long, Boolean> = emptyMap(),
textStyle: TextStyle = TextStyle(),
dateStyle: TextStyle = TextStyle(),
showDate: Boolean = false,
rtlLayout: Boolean = false,
onNoteLongClick: (Long) -> Unit = {},
onNoteClick: (Long) -> Unit = {}
) {
when (notes.size) {
0 -> Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(id = R.string.no_notes_found),
color = colorResource(id = R.color.primary),
fontWeight = FontWeight.Thin,
fontSize = 30.sp
)
}
else -> LazyColumn {
itemsIndexed(notes) { _, note ->
val isSelected = selectedNotes.safeGetOrDefault(note.metadataId, false)
Column(modifier = Modifier
.then(
if (isSelected) {
Modifier.background(color = colorResource(id = R.color.praise_duarte))
} else Modifier
)
.combinedClickable(
onClick = { onNoteClick(note.metadataId) },
onLongClick = { onNoteLongClick(note.metadataId) }
)
) {
RtlTextWrapper(note.title, rtlLayout) {
BasicText(
text = note.title,
style = textStyle,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.fillMaxWidth()
.padding(
start = 16.dp,
end = 16.dp,
top = if (showDate) 8.dp else 12.dp,
bottom = if (showDate) 0.dp else 12.dp
)
)
}
if (showDate) {
BasicText(
text = note.date.noteListFormat,
style = dateStyle,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.align(Alignment.End)
.padding(
start = 16.dp,
end = 16.dp,
bottom = 8.dp
)
)
}
Divider()
}
}
}
}
}
@Preview
@Composable
fun NoteListContentPreview() = NoteListPreview() | apache-2.0 | 9bfec83ba7d9318e45f9671b85a8066a | 37.583942 | 98 | 0.575591 | 5.176298 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCategoryAdapter.kt | 1 | 5882 | package eu.kanade.tachiyomi.ui.library
import com.pushtorefresh.storio.sqlite.queries.RawQuery
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.tables.MangaTable
import exh.isLewdSource
import exh.metadata.sql.tables.SearchMetadataTable
import exh.search.SearchEngine
import exh.util.await
import exh.util.cancellable
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.toList
import timber.log.Timber
import uy.kohesive.injekt.injectLazy
/**
* Adapter storing a list of manga in a certain category.
*
* @param view the fragment containing this adapter.
*/
class LibraryCategoryAdapter(val view: LibraryCategoryView) :
FlexibleAdapter<LibraryItem>(null, view, true) {
// EXH -->
private val db: DatabaseHelper by injectLazy()
private val searchEngine = SearchEngine()
private var lastFilterJob: Job? = null
// Keep compatibility as searchText field was replaced when we upgraded FlexibleAdapter
var searchText
get() = getFilter(String::class.java) ?: ""
set(value) { setFilter(value) }
// EXH <--
/**
* The list of manga in this category.
*/
private var mangas: List<LibraryItem> = emptyList()
/**
* Sets a list of manga in the adapter.
*
* @param list the list to set.
*/
suspend fun setItems(cScope: CoroutineScope, list: List<LibraryItem>) {
// A copy of manga always unfiltered.
mangas = list.toList()
performFilter(cScope)
}
/**
* Returns the position in the adapter for the given manga.
*
* @param manga the manga to find.
*/
fun indexOf(manga: Manga): Int {
return currentItems.indexOfFirst { it.manga.id == manga.id }
}
// EXH -->
// Note that we cannot use FlexibleAdapter's built in filtering system as we cannot cancel it
// (well technically we can cancel it by invoking filterItems again but that doesn't work when
// we want to perform a no-op filter)
suspend fun performFilter(cScope: CoroutineScope) {
lastFilterJob?.cancel()
if(mangas.isNotEmpty() && searchText.isNotBlank()) {
val savedSearchText = searchText
val job = cScope.launch(Dispatchers.IO) {
val newManga = try {
// Prepare filter object
val parsedQuery = searchEngine.parseQuery(savedSearchText)
val sqlQuery = searchEngine.queryToSql(parsedQuery)
val queryResult = db.lowLevel().rawQuery(RawQuery.builder()
.query(sqlQuery.first)
.args(*sqlQuery.second.toTypedArray())
.build())
ensureActive() // Fail early when cancelled
val mangaWithMetaIdsQuery = db.getIdsOfFavoriteMangaWithMetadata().await()
val mangaWithMetaIds = LongArray(mangaWithMetaIdsQuery.count)
if(mangaWithMetaIds.isNotEmpty()) {
val mangaIdCol = mangaWithMetaIdsQuery.getColumnIndex(MangaTable.COL_ID)
mangaWithMetaIdsQuery.moveToFirst()
while (!mangaWithMetaIdsQuery.isAfterLast) {
ensureActive() // Fail early when cancelled
mangaWithMetaIds[mangaWithMetaIdsQuery.position] = mangaWithMetaIdsQuery.getLong(mangaIdCol)
mangaWithMetaIdsQuery.moveToNext()
}
}
ensureActive() // Fail early when cancelled
val convertedResult = LongArray(queryResult.count)
if(convertedResult.isNotEmpty()) {
val mangaIdCol = queryResult.getColumnIndex(SearchMetadataTable.COL_MANGA_ID)
queryResult.moveToFirst()
while (!queryResult.isAfterLast) {
ensureActive() // Fail early when cancelled
convertedResult[queryResult.position] = queryResult.getLong(mangaIdCol)
queryResult.moveToNext()
}
}
ensureActive() // Fail early when cancelled
// Flow the mangas to allow cancellation of this filter operation
mangas.asFlow().cancellable().filter { item ->
if(isLewdSource(item.manga.source)) {
val mangaId = item.manga.id ?: -1
if(convertedResult.binarySearch(mangaId) < 0) {
// Check if this manga even has metadata
if(mangaWithMetaIds.binarySearch(mangaId) < 0) {
// No meta? Filter using title
item.filter(savedSearchText)
} else false
} else true
} else {
item.filter(savedSearchText)
}
}.toList()
} catch (e: Exception) {
// Do not catch cancellations
if(e is CancellationException) throw e
Timber.w(e, "Could not filter mangas!")
mangas
}
withContext(Dispatchers.Main) {
updateDataSet(newManga)
}
}
lastFilterJob = job
job.join()
} else {
updateDataSet(mangas)
}
}
// EXH <--
}
| apache-2.0 | a81ccdcf6ff3e59f08027322a05f1b2e | 38.743243 | 120 | 0.564094 | 5.612595 | false | false | false | false |
Heiner1/AndroidAPS | omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/StringLengthPrefixEncodingTest.kt | 1 | 828 | package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message
import com.google.crypto.tink.subtle.Hex
import info.nightscout.androidaps.extensions.toHex
import org.junit.Assert.assertEquals
import org.junit.Test
class StringLengthPrefixEncodingTest {
private val p0Payload = Hex.decode("50,30,3d,00,01,a5".replace(",", "")) // from logs
private val p0Content = Hex.decode("a5")
@Test fun testFormatKeysP0() {
val payload = StringLengthPrefixEncoding.formatKeys(arrayOf("P0="), arrayOf(p0Content))
assertEquals(p0Payload.toHex(), payload.toHex())
}
@Test fun testParseKeysP0() {
val parsed = StringLengthPrefixEncoding.parseKeys(arrayOf("P0="), p0Payload)
assertEquals(parsed.size, 1)
assertEquals(parsed[0].toHex(), p0Content.toHex())
}
}
| agpl-3.0 | 5eb59764dea08e7b7b09b0f3fd356bc1 | 35 | 95 | 0.719807 | 3.696429 | false | true | false | false |
Heiner1/AndroidAPS | core/src/test/java/info/nightscout/androidaps/data/DetailedBolusInfoTest.kt | 1 | 4287 | package info.nightscout.androidaps.data
import android.content.Context
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.database.entities.Bolus
import info.nightscout.androidaps.database.entities.BolusCalculatorResult
import info.nightscout.androidaps.database.entities.TherapyEvent
import org.apache.commons.lang3.builder.EqualsBuilder
import org.junit.Assert
import org.junit.Test
import org.mockito.Mock
class DetailedBolusInfoTest : TestBase() {
@Mock lateinit var context: Context
@Test fun toStringShouldBeOverloaded() {
val detailedBolusInfo = DetailedBolusInfo()
Assert.assertEquals(true, detailedBolusInfo.toString().contains("insulin"))
}
@Test fun copyShouldCopyAllProperties() {
val d1 = DetailedBolusInfo()
d1.deliverAtTheLatest = 123
val d2 = d1.copy()
Assert.assertEquals(true, EqualsBuilder.reflectionEquals(d2, d1))
}
@Test
fun shouldAllowSerialization() {
val detailedBolusInfo = DetailedBolusInfo()
detailedBolusInfo.bolusCalculatorResult = createBolusCalculatorResult()
detailedBolusInfo.context = context
detailedBolusInfo.eventType = DetailedBolusInfo.EventType.BOLUS_WIZARD
val serialized = detailedBolusInfo.toJsonString()
val deserialized = DetailedBolusInfo.fromJsonString(serialized)
Assert.assertEquals(1L, deserialized.bolusCalculatorResult?.timestamp)
Assert.assertEquals(DetailedBolusInfo.EventType.BOLUS_WIZARD, deserialized.eventType)
// Context should be excluded
Assert.assertNull(deserialized.context)
}
@Test
fun generateTherapyEventTest() {
val detailedBolusInfo = DetailedBolusInfo()
detailedBolusInfo.timestamp = 1000
detailedBolusInfo.notes = "note"
detailedBolusInfo.mgdlGlucose = 180.0
detailedBolusInfo.glucoseType = DetailedBolusInfo.MeterType.FINGER
val therapyEvent = detailedBolusInfo.createTherapyEvent()
Assert.assertEquals(1000L, therapyEvent.timestamp)
Assert.assertEquals(TherapyEvent.Type.MEAL_BOLUS, therapyEvent.type)
Assert.assertEquals(TherapyEvent.GlucoseUnit.MGDL, therapyEvent.glucoseUnit)
Assert.assertEquals("note", therapyEvent.note)
Assert.assertEquals(180.0, therapyEvent.glucose)
Assert.assertEquals(TherapyEvent.MeterType.FINGER, therapyEvent.glucoseType)
}
@Test
fun generateBolus() {
val detailedBolusInfo = DetailedBolusInfo()
detailedBolusInfo.timestamp = 1000
detailedBolusInfo.bolusType = DetailedBolusInfo.BolusType.SMB
detailedBolusInfo.insulin = 7.0
val bolus = detailedBolusInfo.createBolus()
Assert.assertEquals(1000L, bolus?.timestamp)
Assert.assertEquals(Bolus.Type.SMB, bolus?.type)
Assert.assertEquals(7.0, bolus?.amount)
}
@Test
fun generateCarbs() {
val detailedBolusInfo = DetailedBolusInfo()
detailedBolusInfo.timestamp = 1000
detailedBolusInfo.carbs = 6.0
val carbs = detailedBolusInfo.createCarbs()
Assert.assertEquals(1000L, carbs?.timestamp)
Assert.assertEquals(6.0, carbs?.amount)
}
private fun createBolusCalculatorResult(): BolusCalculatorResult =
BolusCalculatorResult(
timestamp = 1,
targetBGLow = 5.0,
targetBGHigh = 5.0,
isf = 5.0,
ic = 5.0,
bolusIOB = 1.0,
wasBolusIOBUsed = true,
basalIOB = 1.0,
wasBasalIOBUsed = true,
glucoseValue = 10.0,
wasGlucoseUsed = true,
glucoseDifference = 1.0,
glucoseInsulin = 1.0,
glucoseTrend = 1.0,
wasTrendUsed = true,
trendInsulin = 1.0,
cob = 10.0,
wasCOBUsed = true,
cobInsulin = 1.0,
carbs = 5.0,
wereCarbsUsed = true,
carbsInsulin = 1.0,
otherCorrection = 1.0,
wasSuperbolusUsed = true,
superbolusInsulin = 1.0,
wasTempTargetUsed = true,
totalInsulin = 15.0,
percentageCorrection = 50,
profileName = "profile",
note = ""
)
} | agpl-3.0 | 05416ddd02356c219457d5630068dba0 | 35.649573 | 93 | 0.665734 | 4.984884 | false | true | false | false |
jkcclemens/khttp | src/test/kotlin/khttp/structures/authorization/BasicAuthorizationSpec.kt | 1 | 1515 | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package khttp.structures.authorization
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.util.Base64
import kotlin.test.assertEquals
class BasicAuthorizationSpec : Spek({
describe("a BasicAuthorization object") {
val username = "test"
val password = "hunter2"
val base64 = "Basic " + Base64.getEncoder().encode("$username:$password".toByteArray()).toString(Charsets.UTF_8)
val auth = BasicAuthorization(username, password)
context("checking the username") {
val authUsername = auth.user
it("should equal the original") {
assertEquals(username, authUsername)
}
}
context("checking the password") {
val authPassword = auth.password
it("should equal the original") {
assertEquals(password, authPassword)
}
}
context("checking the header") {
val (header, value) = auth.header
it("should have a first value of \"Authorization\"") {
assertEquals("Authorization", header)
}
it("should have a second value of the Base64 encoding") {
assertEquals(base64, value)
}
}
}
})
| mpl-2.0 | bda1d829cbbda89d25e540569203ff93 | 35.95122 | 120 | 0.613861 | 4.618902 | false | false | false | false |
faruktoptas/news-mvp | app/src/main/java/me/toptas/rssreader/model/Error.kt | 1 | 370 | package me.toptas.rssreader.model
/**
* Created by ftoptas on 24/07/18.
*/
data class Error(val code: Int = 0,
var message: String = "") {
companion object {
const val ERROR_GENERIC = -1
const val ERROR_NETWORK = -2
fun generic() = Error(code = ERROR_GENERIC)
fun network() = Error(code = ERROR_NETWORK)
}
} | apache-2.0 | 5c290c3a1ae5de8b4f5701624b4e31a4 | 20.823529 | 51 | 0.575676 | 3.737374 | false | false | false | false |
redutan/nbase-arc-monitoring | src/main/kotlin/io/redutan/nbasearc/monitoring/collector/Stat.kt | 1 | 959 | package io.redutan.nbasearc.monitoring.collector
import io.redutan.nbasearc.monitoring.collector.parser.ByteValue
import io.redutan.nbasearc.monitoring.collector.parser.EMPTY_BYTE_VALUE
import java.time.LocalDateTime
val UNKNOWN_STAT: Stat = Stat(LocalDateTime.MIN)
data class Stat(override val loggedAt: LocalDateTime,
val redis: Long,
val pg: Long,
val connection: Long,
val mem: ByteValue,
val ops: Long,
val hits: Long,
val misses: Long,
val keys: Long,
val expires: Long,
override val errorDescription: String = "")
: NbaseArcLog {
constructor(loggedAt: LocalDateTime, errorDescription: String = "")
: this(loggedAt, -1, -1, -1, EMPTY_BYTE_VALUE, -1, -1, -1, -1, -1, errorDescription)
override fun isUnknown(): Boolean {
return this == UNKNOWN_STAT
}
}
| apache-2.0 | 9848482a9879bc3babb6b6e393141466 | 33.25 | 96 | 0.604797 | 4.359091 | false | false | false | false |
Maccimo/intellij-community | platform/vcs-impl/src/com/intellij/util/ui/JButtonAction.kt | 3 | 2473 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.ui
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.NlsActions.ActionDescription
import com.intellij.openapi.util.NlsActions.ActionText
import javax.swing.Icon
import javax.swing.JButton
import javax.swing.JComponent
abstract class JButtonAction(text: @ActionText String?, @ActionDescription description: String? = null, icon: Icon? = null)
: DumbAwareAction(text, description, icon), CustomComponentAction {
override fun createCustomComponent(presentation: Presentation, place: String): JComponent {
val button = createButton()
button.addActionListener {
performAction(button, place, presentation)
}
button.text = presentation.getText(true)
return button
}
protected fun performAction(component: JComponent, place: String, presentation: Presentation) {
val dataContext = ActionToolbar.getDataContextFor(component)
val event = AnActionEvent.createFromInputEvent(null, place, presentation, dataContext)
if (ActionUtil.lastUpdateAndCheckDumb(this, event, true)) {
ActionUtil.performActionDumbAwareWithCallbacks(this, event)
}
}
protected open fun createButton(): JButton = JButton().configureForToolbar()
protected fun JButton.configureForToolbar(): JButton =
apply {
isFocusable = false
font = JBUI.Fonts.toolbarFont()
putClientProperty("ActionToolbar.smallVariant", true)
}
override fun updateCustomComponent(component: JComponent, presentation: Presentation) {
if (component is JButton) {
updateButtonFromPresentation(component, presentation)
}
}
protected open fun updateButtonFromPresentation(button: JButton, presentation: Presentation) {
button.isEnabled = presentation.isEnabled
button.isVisible = presentation.isVisible
button.text = presentation.getText(true)
button.icon = presentation.icon
button.mnemonic = presentation.mnemonic
button.displayedMnemonicIndex = presentation.displayedMnemonicIndex
button.toolTipText = presentation.description
}
} | apache-2.0 | 0637da4dd3d2b24baf0fa573c5f3bd8a | 38.903226 | 123 | 0.782855 | 5.03666 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/jvm-debugger/util/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinDebuggerCaches.kt | 2 | 6024 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.evaluate
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.engine.evaluation.EvaluateException
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.containers.MultiMap
import org.jetbrains.annotations.TestOnly
import org.jetbrains.eval4j.Value
import org.jetbrains.kotlin.codegen.inline.SMAP
import org.jetbrains.kotlin.idea.debugger.BinaryCacheKey
import org.jetbrains.kotlin.idea.debugger.createWeakBytecodeDebugInfoStorage
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CompiledDataDescriptor
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.KtCodeFragment
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.types.KotlinType
import java.util.*
import java.util.concurrent.ConcurrentHashMap
class KotlinDebuggerCaches(project: Project) {
private val cachedCompiledData = CachedValuesManager.getManager(project).createCachedValue(
{
CachedValueProvider.Result<MultiMap<String, CompiledDataDescriptor>>(
MultiMap.create(), PsiModificationTracker.MODIFICATION_COUNT
)
}, false
)
private val cachedClassNames = CachedValuesManager.getManager(project).createCachedValue(
{
CachedValueProvider.Result<MutableMap<PsiElement, List<String>>>(
ConcurrentHashMap(),
PsiModificationTracker.MODIFICATION_COUNT
)
}, false
)
private val debugInfoCache = CachedValuesManager.getManager(project).createCachedValue(
{
CachedValueProvider.Result(
createWeakBytecodeDebugInfoStorage(),
PsiModificationTracker.MODIFICATION_COUNT
)
}, false
)
companion object {
private val LOG = Logger.getInstance(KotlinDebuggerCaches::class.java)
@get:TestOnly
var LOG_COMPILATIONS: Boolean = false
fun getInstance(project: Project): KotlinDebuggerCaches = project.service()
fun compileCodeFragmentCacheAware(
codeFragment: KtCodeFragment,
sourcePosition: SourcePosition?,
compileCode: () -> CompiledDataDescriptor,
force: Boolean = false
): Pair<CompiledDataDescriptor, Boolean> {
if (sourcePosition == null) {
return Pair(compileCode(), false)
}
val evaluateExpressionCache = getInstance(codeFragment.project)
val text = "${codeFragment.importsToString()}\n${codeFragment.text}"
val cachedResults = synchronized<Collection<CompiledDataDescriptor>>(evaluateExpressionCache.cachedCompiledData) {
evaluateExpressionCache.cachedCompiledData.value[text]
}
val existingResult = cachedResults.firstOrNull { it.sourcePosition == sourcePosition }
if (existingResult != null) {
if (force) {
synchronized(evaluateExpressionCache.cachedCompiledData) {
evaluateExpressionCache.cachedCompiledData.value.remove(text, existingResult)
}
} else {
return Pair(existingResult, true)
}
}
val newCompiledData = compileCode()
if (LOG_COMPILATIONS) {
LOG.debug("Compile bytecode for ${codeFragment.text}")
}
synchronized(evaluateExpressionCache.cachedCompiledData) {
evaluateExpressionCache.cachedCompiledData.value.putValue(text, newCompiledData)
}
return Pair(newCompiledData, false)
}
fun <T : PsiElement> getOrComputeClassNames(psiElement: T?, create: (T) -> ComputedClassNames): List<String> {
if (psiElement == null) return Collections.emptyList()
val cache = getInstance(runReadAction { psiElement.project })
val classNamesCache = cache.cachedClassNames.value
val cachedValue = classNamesCache[psiElement]
if (cachedValue != null) return cachedValue
val computedClassNames = create(psiElement)
if (computedClassNames.shouldBeCached) {
classNamesCache[psiElement] = computedClassNames.classNames
}
return computedClassNames.classNames
}
fun getSmapCached(project: Project, jvmName: JvmClassName, file: VirtualFile): SMAP? {
return getInstance(project).debugInfoCache.value[BinaryCacheKey(project, jvmName, file)]
}
}
data class Parameter(val callText: String, val type: KotlinType, val value: Value? = null, val error: EvaluateException? = null)
class ComputedClassNames(val classNames: List<String>, val shouldBeCached: Boolean) {
@Suppress("FunctionName")
companion object {
val EMPTY = Cached(emptyList())
fun Cached(classNames: List<String>) = ComputedClassNames(classNames, true)
fun Cached(className: String) = ComputedClassNames(Collections.singletonList(className), true)
fun NonCached(classNames: List<String>) = ComputedClassNames(classNames, false)
}
fun isEmpty() = classNames.isEmpty()
fun distinct() = ComputedClassNames(classNames.distinct(), shouldBeCached)
operator fun plus(other: ComputedClassNames) = ComputedClassNames(
classNames + other.classNames, shouldBeCached && other.shouldBeCached
)
}
} | apache-2.0 | d371b7baa7df355d5ec8ddbcaadcf0c7 | 38.900662 | 132 | 0.683765 | 5.456522 | false | false | false | false |
Tandrial/Advent_of_Code | src/aoc2017/kot/Day21.kt | 1 | 3082 | package aoc2017.kot
import java.io.File
object Day21 {
fun solve(start: String, input: List<String>, iter: Int): Int {
val lookUp = parsePatterns(input)
var current = start.split("/").map { it.toCharArray() }.toTypedArray()
repeat(iter) {
val chunkSize = if (current.size % 2 == 0) 2 else 3
val listOfBlocks = splitIntoBlocks(current, chunkSize)
current = mergeBlocks(listOfBlocks.map { lookUp[it.contentDeepHashCode()]!! })
}
return current.sumBy { it.count { it == '#' } }
}
private fun splitIntoBlocks(current: Array<CharArray>, chunkSize: Int): List<Array<CharArray>> {
if (current.size == chunkSize) return listOf(current)
val blockCount = (current.size * current.size) / (chunkSize * chunkSize)
val blocks = Array(blockCount) { Array(chunkSize) { CharArray(chunkSize) { '.' } } }
for (y in 0 until current.size) {
for (x in 0 until current.size) {
val bOff = x / blocks[0].size + (y / blocks[0].size) * Math.sqrt(blockCount.toDouble()).toInt()
val xOff = x % blocks[0].size
val yOff = y % blocks[0].size
blocks[bOff][xOff][yOff] = current[x][y]
}
}
return blocks.toList()
}
private fun mergeBlocks(blocks: List<Array<CharArray>>): Array<CharArray> {
if (blocks.size == 1) return blocks[0]
val size = Math.sqrt((blocks.size * blocks[0].size * blocks[0].size).toDouble()).toInt()
val result = Array(size) { CharArray(size) { '.' } }
for (y in 0 until result.size) {
for (x in 0 until result.size) {
val bOff = x / blocks[0].size + (y / blocks[0].size) * Math.sqrt(blocks.size.toDouble()).toInt()
val xOff = x % blocks[0].size
val yOff = y % blocks[0].size
result[x][y] = blocks[bOff][xOff][yOff]
}
}
return result
}
private fun parsePatterns(input: List<String>): Map<Int, Array<CharArray>> {
val patterns = mutableMapOf<Int, Array<CharArray>>()
input.forEach {
val (lhs, rhs) = it.split(" => ").map { it.split("/") }
val rhsArr = rhs.map { it.toCharArray() }.toTypedArray()
val permutations = generatePermutations(lhs).map { it.contentDeepHashCode() to rhsArr }
patterns.putAll(permutations)
}
return patterns
}
private fun generatePermutations(s: List<String>): List<Array<CharArray>> {
val result = mutableSetOf<List<String>>()
var next = s
repeat(4) {
result.add(next)
result.add(next.reversed())
result.add(next.map { it.reversed() })
next = rot(next)
}
return result.map { it.map { it.toCharArray() }.toTypedArray() }
}
private fun rot(grid: List<String>): List<String> = flip2DArray(grid).reversed()
private fun flip2DArray(arr: List<String>): List<String> = arr.mapIndexed { index, _ -> arr.map { it[index] }.joinToString(separator = "") }
}
fun main(args: Array<String>) {
val input = File("./input/2017/Day21_input.txt").readLines()
val start = ".#./..#/###"
println("Part One = ${Day21.solve(start, input, 5)}")
println("Part Two = ${Day21.solve(start, input, 18)}")
}
| mit | e13b9be393b344732255ec99b6789762 | 38.012658 | 142 | 0.623297 | 3.534404 | false | false | false | false |
Maccimo/intellij-community | platform/lang-impl/testSources/com/intellij/util/indexing/diagnostic/ProjectIndexingHistoryImplTest.kt | 3 | 6450 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.indexing.diagnostic
import com.intellij.openapi.command.impl.DummyProject
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertTrue
import org.junit.Test
import java.time.Duration
import java.time.Instant
class ProjectIndexingHistoryImplTest {
@Test
fun `test observation missed the start of suspension (IDEA-281514)`() {
val history = ProjectIndexingHistoryImpl(DummyProject.getInstance(), "test", ScanningType.FULL)
val time = Instant.now()
history.stopSuspendingStages(time)
history.startStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(1))
history.stopStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(2))
history.indexingFinished()
assertTrue(history.times.indexingDuration > Duration.ZERO)
assertEquals(history.times.suspendedDuration, Duration.ZERO)
assertEquals(history.times.scanFilesDuration, Duration.ZERO)
assertEquals(history.times.pushPropertiesDuration, Duration.ZERO)
}
@Test
fun `test there may be actions after suspension`() {
val history = ProjectIndexingHistoryImpl(DummyProject.getInstance(), "test", ScanningType.FULL)
val time = Instant.now()
history.startStage(ProjectIndexingHistoryImpl.Stage.Indexing, time)
history.suspendStages(time.plusNanos(1))
history.stopStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(2))
history.indexingFinished()
assertTrue(history.times.indexingDuration > Duration.ZERO)
assertEquals(history.times.suspendedDuration, Duration.ZERO)
assertEquals(history.times.scanFilesDuration, Duration.ZERO)
assertEquals(history.times.pushPropertiesDuration, Duration.ZERO)
}
@Test
fun `test there may be actions after suspension 2`() {
val history = ProjectIndexingHistoryImpl(DummyProject.getInstance(), "test", ScanningType.FULL)
val time = Instant.now()
history.startStage(ProjectIndexingHistoryImpl.Stage.Indexing, time)
history.suspendStages(time.plusNanos(1))
history.stopStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(2))
history.stopSuspendingStages(time.plusNanos(3))
history.indexingFinished()
assertTrue(history.times.indexingDuration > Duration.ZERO)
assertTrue(history.times.suspendedDuration > Duration.ZERO)
assertEquals(history.times.scanFilesDuration, Duration.ZERO)
assertEquals(history.times.pushPropertiesDuration, Duration.ZERO)
}
@Test
fun `test there may be actions after suspension 3`() {
val history = ProjectIndexingHistoryImpl(DummyProject.getInstance(), "test", ScanningType.FULL)
val time = Instant.now()
history.suspendStages(time)
history.startStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(1))
history.stopSuspendingStages(time.plusNanos(2))
history.stopStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(3))
history.indexingFinished()
assertTrue(history.times.indexingDuration > Duration.ZERO)
assertTrue(history.times.suspendedDuration > Duration.ZERO)
assertEquals(history.times.scanFilesDuration, Duration.ZERO)
assertEquals(history.times.pushPropertiesDuration, Duration.ZERO)
}
@Test
fun `test there may be actions after suspension 4`() {
val history = ProjectIndexingHistoryImpl(DummyProject.getInstance(), "test", ScanningType.FULL)
val time = Instant.now()
history.startStage(ProjectIndexingHistoryImpl.Stage.Indexing, time)
history.stopSuspendingStages(time.plusNanos(1))
history.stopStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(2))
history.indexingFinished()
assertTrue(history.times.indexingDuration > Duration.ZERO)
assertTrue(history.times.suspendedDuration > Duration.ZERO)
assertEquals(history.times.scanFilesDuration, Duration.ZERO)
assertEquals(history.times.pushPropertiesDuration, Duration.ZERO)
}
@Test
fun `test there may be actions after suspension 5`() {
val history = ProjectIndexingHistoryImpl(DummyProject.getInstance(), "test", ScanningType.FULL)
val time = Instant.now()
history.startStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(1))
history.stopSuspendingStages(time.plusNanos(2))
history.stopStage(ProjectIndexingHistoryImpl.Stage.Indexing, time.plusNanos(3))
history.suspendStages(time.plusNanos(4))
history.stopSuspendingStages(time.plusNanos(5))
history.indexingFinished()
assertTrue(history.times.indexingDuration > Duration.ZERO)
assertTrue(history.times.suspendedDuration > Duration.ZERO)
assertEquals(history.times.scanFilesDuration, Duration.ZERO)
assertEquals(history.times.pushPropertiesDuration, Duration.ZERO)
}
@Test
fun `test basic workflow`() {
val history = ProjectIndexingHistoryImpl(DummyProject.getInstance(), "test", ScanningType.FULL)
val instant = Instant.now()
history.startStage(ProjectIndexingHistoryImpl.Stage.PushProperties, instant)
history.stopStage(ProjectIndexingHistoryImpl.Stage.PushProperties, instant.plusNanos(1))
history.startStage(ProjectIndexingHistoryImpl.Stage.Scanning, instant.plusNanos(2))
history.stopStage(ProjectIndexingHistoryImpl.Stage.Scanning, instant.plusNanos(5))
history.indexingFinished()
assertEquals(history.times.indexingDuration, Duration.ZERO)
assertEquals(history.times.suspendedDuration, Duration.ZERO)
assertEquals(history.times.pushPropertiesDuration, Duration.ofNanos(1))
assertEquals(history.times.scanFilesDuration, Duration.ofNanos(3))
}
@Test
fun `test stage with suspension inside`() {
val history = ProjectIndexingHistoryImpl(DummyProject.getInstance(), "test", ScanningType.FULL)
val instant = Instant.now()
history.startStage(ProjectIndexingHistoryImpl.Stage.PushProperties, instant)
history.suspendStages(instant.plusNanos(1))
history.stopSuspendingStages(instant.plusNanos(4))
history.stopStage(ProjectIndexingHistoryImpl.Stage.PushProperties, instant.plusNanos(5))
history.indexingFinished()
assertEquals(history.times.indexingDuration, Duration.ZERO)
assertEquals(history.times.scanFilesDuration, Duration.ZERO)
assertEquals(history.times.suspendedDuration, Duration.ofNanos(3))
assertEquals(history.times.pushPropertiesDuration, Duration.ofNanos(2))
}
} | apache-2.0 | e5dd8734faaa39839ce998fd51ff74db | 45.746377 | 120 | 0.784341 | 4.890068 | false | true | false | false |
Tiofx/semester_6 | MIT/MIT_lab_7/app/src/main/java/com/example/andrej/mit_lab_7/util.kt | 1 | 5812 | package com.example.andrej.mit_lab_7
import android.app.Activity
import android.app.DownloadManager
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.os.Handler
import android.os.Message
import android.support.v4.content.FileProvider
import android.util.Log
import android.widget.Toast
import org.apache.http.client.ClientProtocolException
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpHead
import org.apache.http.impl.client.DefaultHttpClient
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.Socket
import java.net.URL
object Util {
fun getFile(context: Context, fileName: String) = getPath(context)
.let { File(it, "$fileName.pdf") }
fun getPath(context: Context) = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
fun downloadFile(main: Context, uri: String, fileName: String) =
DownloadManager.Request(Uri.parse(uri))
.apply {
setDestinationInExternalFilesDir(main, Environment.DIRECTORY_DOWNLOADS,
"$fileName.pdf")
setMimeType("application/pdf")
allowScanningByMediaScanner()
setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE or
DownloadManager.Request.NETWORK_WIFI)
}
.let {
(main.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager)
.enqueue(it)
}
fun showPdf(main: Activity, fileName: String) {
try {
val uri = getFile(main, fileName)
.let {
FileProvider.getUriForFile(main,
"${main.applicationContext.packageName}.provider",
it)
}
val intent = Intent(Intent.ACTION_VIEW)
.apply {
setDataAndType(uri, "application/pdf")
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
main.startActivity(intent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(main, "Приложение для открытия pdf файлов отсутствует\n$e", Toast.LENGTH_LONG).show()
} catch (e: Exception) {
Toast.makeText(main, e.toString(), Toast.LENGTH_LONG).show()
}
}
fun httpExists(url: String): Boolean {
val client = DefaultHttpClient()
val request = HttpGet(url)
val response = try {
client.execute(request)
} catch (e: ClientProtocolException) {
e.printStackTrace()
null
} catch (e: IOException) {
e.printStackTrace()
null
}
return response?.statusLine?.statusCode == HttpURLConnection.HTTP_OK
}
fun setPreference(context: Context, name: String, value: Boolean) = with(context) {
this.getSharedPreferences(this.javaClass.toString(), Context.MODE_PRIVATE)
.edit()
.putBoolean(name, value)
.apply()
}
fun getPreference(context: Context, name: String) = with(context) {
this.getSharedPreferences(this.javaClass.toString(), Context.MODE_PRIVATE)
.getBoolean(name, false)
}
fun clearPreference(c: Context) = with(c) {
this.getSharedPreferences(this.javaClass.toString(), Context.MODE_PRIVATE)
.edit()
.clear()
.apply()
}
}
object TaskTwo {
fun downloadUrl(myUrl: String, length: Int = 500): String = try {
with(URL(myUrl).openConnection() as HttpURLConnection) {
readTimeout = 1e4.toInt()
connectTimeout = 1.5e4.toInt()
requestMethod = "GET"
doInput = true
Log.d("DEBUG_TAG", "The response is: $responseCode")
inputStream.use { readIt(it, length) }
}
} catch (e: Exception) {
e.toString()
}
fun readIt(stream: InputStream, length: Int) = CharArray(length).let {
stream.reader(charset("UTF-8")).read(it, 0, length)
String(it)
}
fun httpGET(url: String): String {
val client = DefaultHttpClient()
val request = HttpHead(url)
// val request = HttpGet(url)
val response = try {
client.execute(request)
} catch (e: ClientProtocolException) {
e.printStackTrace()
null
} catch (e: IOException) {
e.printStackTrace()
null
}
Log.d("Response of GET request", response?.statusLine?.toString() ?: "Произошла ошибка")
return response?.statusLine?.toString() ?: "Произошла ошибка"
}
class Requester() : Thread() {
val h by lazy { Handler() }
override fun run() {
try {
Socket("remote.servername.com", 13).use { requestSocket ->
h.sendMessage(Message().apply {
obj = InputStreamReader(requestSocket.getInputStream(), "ISO-8859-1")
.readText()
what = 0
})
}
} catch (e: Exception) {
Log.d("sample application", "failed to read data ${e.message}")
}
}
}
} | gpl-3.0 | 2e2e95f1f9bcd47144eb292143bd0253 | 33.608434 | 112 | 0.570334 | 4.704341 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/model/preferences/OtherPreferencesHolder.kt | 1 | 3071 | package forpdateam.ru.forpda.model.preferences
import android.content.SharedPreferences
import com.f2prateek.rx.preferences2.RxSharedPreferences
import forpdateam.ru.forpda.common.Preferences
import io.reactivex.Observable
class OtherPreferencesHolder(
private val sharedPreferences: SharedPreferences
) {
private val rxPreferences = RxSharedPreferences.create(sharedPreferences)
private val appFirstStart by lazy {
rxPreferences.getBoolean(Preferences.Other.APP_FIRST_START, true)
}
private val appVersionsHistory by lazy {
rxPreferences.getString(Preferences.Other.APP_VERSIONS_HISTORY)
}
private val searchSettings by lazy {
rxPreferences.getString(Preferences.Other.SEARCH_SETTINGS)
}
private val messagePanelBbCodes by lazy {
rxPreferences.getString(Preferences.Other.MESSAGE_PANEL_BBCODES_SORT)
}
private val showReportWarning by lazy {
rxPreferences.getBoolean(Preferences.Other.SHOW_REPORT_WARNING, true)
}
private val tooltipSearchSettings by lazy {
rxPreferences.getBoolean(Preferences.Other.TOOLTIP_SEARCH_SETTINGS, true)
}
private val tooltipMessagePanelSorting by lazy {
rxPreferences.getBoolean(Preferences.Other.TOOLTIP_MESSAGE_PANEL_SORTING, true)
}
fun observeAppFirstStart(): Observable<Boolean> = appFirstStart.asObservable()
fun observeAppVersionsHistory(): Observable<String> = appVersionsHistory.asObservable()
fun observeSearchSettings(): Observable<String> = searchSettings.asObservable()
fun observeMessagePanelBbCodes(): Observable<String> = messagePanelBbCodes.asObservable()
fun observeShowReportWarning(): Observable<Boolean> = showReportWarning.asObservable()
fun observeTooltipSearchSettings(): Observable<Boolean> = tooltipSearchSettings.asObservable()
fun observeTooltipMessagePanelSorting(): Observable<Boolean> = tooltipMessagePanelSorting.asObservable()
fun setAppFirstStart(value: Boolean) = appFirstStart.set(value)
fun setAppVersionsHistory(value: String) = appVersionsHistory.set(value)
fun setSearchSettings(value: String) = searchSettings.set(value)
fun setMessagePanelBbCodes(value: String) = messagePanelBbCodes.set(value)
fun setShowReportWarning(value: Boolean) = showReportWarning.set(value)
fun setTooltipSearchSettings(value: Boolean) = tooltipSearchSettings.set(value)
fun setTooltipMessagePanelSorting(value: Boolean) = tooltipMessagePanelSorting.set(value)
fun deleteMessagePanelBbCodes() = messagePanelBbCodes.delete()
fun getAppFirstStart(): Boolean = appFirstStart.get()
fun getAppVersionsHistory(): String = appVersionsHistory.get()
fun getSearchSettings(): String = searchSettings.get()
fun getMessagePanelBbCodes(): String = messagePanelBbCodes.get()
fun getShowReportWarning(): Boolean = showReportWarning.get()
fun getTooltipSearchSettings(): Boolean = tooltipSearchSettings.get()
fun getTooltipMessagePanelSorting(): Boolean = tooltipMessagePanelSorting.get()
} | gpl-3.0 | 210d153fd4121176f63762875724b19e | 33.133333 | 108 | 0.771736 | 5.178752 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/models/usecases/UnifiedCommentsListHandler.kt | 1 | 2877 | package org.wordpress.android.models.usecases
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.merge
import org.wordpress.android.models.usecases.BatchModerateCommentsUseCase.ModerateCommentsAction.OnModerateComments
import org.wordpress.android.models.usecases.BatchModerateCommentsUseCase.Parameters.ModerateCommentsParameters
import org.wordpress.android.models.usecases.ModerateCommentWithUndoUseCase.ModerateCommentsAction.OnModerateComment
import org.wordpress.android.models.usecases.ModerateCommentWithUndoUseCase.ModerateCommentsAction.OnPushComment
import org.wordpress.android.models.usecases.ModerateCommentWithUndoUseCase.ModerateCommentsAction.OnUndoModerateComment
import org.wordpress.android.models.usecases.ModerateCommentWithUndoUseCase.Parameters.ModerateCommentParameters
import org.wordpress.android.models.usecases.ModerateCommentWithUndoUseCase.Parameters.ModerateWithFallbackParameters
import org.wordpress.android.models.usecases.PaginateCommentsUseCase.PaginateCommentsAction.OnGetPage
import org.wordpress.android.models.usecases.PaginateCommentsUseCase.PaginateCommentsAction.OnReloadFromCache
import org.wordpress.android.models.usecases.PaginateCommentsUseCase.Parameters.GetPageParameters
import org.wordpress.android.models.usecases.PaginateCommentsUseCase.Parameters.ReloadFromCacheParameters
import javax.inject.Inject
class UnifiedCommentsListHandler @Inject constructor(
private val paginateCommentsUseCase: PaginateCommentsUseCase,
private val batchModerationUseCase: BatchModerateCommentsUseCase,
private val moderationWithUndoUseCase: ModerateCommentWithUndoUseCase
) {
private val useCases = listOf(paginateCommentsUseCase, batchModerationUseCase, moderationWithUndoUseCase)
@OptIn(ExperimentalCoroutinesApi::class)
fun subscribe() = useCases.map { it.subscribe() }.merge()
suspend fun requestPage(parameters: GetPageParameters) = paginateCommentsUseCase.manageAction(
OnGetPage(parameters)
)
suspend fun moderateComments(parameters: ModerateCommentsParameters) = batchModerationUseCase.manageAction(
OnModerateComments(parameters)
)
suspend fun preModerateWithUndo(parameters: ModerateCommentParameters) = moderationWithUndoUseCase.manageAction(
OnModerateComment(parameters)
)
suspend fun moderateAfterUndo(parameters: ModerateWithFallbackParameters) = moderationWithUndoUseCase.manageAction(
OnPushComment(parameters)
)
suspend fun undoCommentModeration(parameters: ModerateWithFallbackParameters) =
moderationWithUndoUseCase.manageAction(
OnUndoModerateComment(parameters)
)
suspend fun refreshFromCache(parameters: ReloadFromCacheParameters) = paginateCommentsUseCase.manageAction(
OnReloadFromCache(parameters)
)
}
| gpl-2.0 | be93eda5f46065853d89ce3926c3f749 | 54.326923 | 120 | 0.837678 | 5.765531 | false | false | false | false |
alexander-schmidt/ihh | ihh-server/src/main/kotlin/com/asurasdevelopment/ihh/server/tasks/LeagueUpdateManager.kt | 1 | 1262 | package com.asurasdevelopment.ihh.server.tasks
import org.slf4j.LoggerFactory
import com.asurasdevelopment.ihh.server.persistence.dao.League
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
class LeagueUpdateManager(var list: List<League>, var poolSize : Int = 5, var taskNumber : Int = 5,
var interval : Long = 10) {
private val winston = LoggerFactory.getLogger(LeagueUpdateManager::class.java)
private lateinit var queue : CircularQueue<League>
private lateinit var updatePool : ScheduledExecutorService
fun start() {
winston.info("starting updates with poolSize: $poolSize, taskNumber: $taskNumber, interval: $interval")
queue = CircularQueue(list.toMutableList())
updatePool = Executors.newScheduledThreadPool(poolSize)
for (i in 1..taskNumber) {
updatePool.scheduleAtFixedRate(LeagueUpdateTask(queue), 0, interval, TimeUnit.SECONDS)
}
}
fun stop() {
winston.info("stopping updates")
updatePool.shutdown()
winston.info("updates stopped")
}
fun restart() {
winston.info("restarting updates")
stop()
start()
}
} | apache-2.0 | 767df51ced9e300b5fe7817e4798e9bd | 33.135135 | 111 | 0.693344 | 4.639706 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/breakpoints/breakpointTypeUtils.kt | 1 | 7864 | // 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.debugger.breakpoints
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.ui.breakpoints.JavaLineBreakpointType
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.xdebugger.XDebuggerUtil
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.impl.XSourcePositionImpl
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.psi.getLineNumber
import org.jetbrains.kotlin.idea.base.psi.getTopmostElementAtOffset
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.util.findElementsOfClassInRange
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.inline.INLINE_ONLY_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance
import java.util.*
import org.jetbrains.kotlin.idea.debugger.core.findElementAtLine
interface KotlinBreakpointType
class ApplicabilityResult(val isApplicable: Boolean, val shouldStop: Boolean) {
companion object {
@JvmStatic
fun definitely(result: Boolean) = ApplicabilityResult(result, shouldStop = true)
@JvmStatic
fun maybe(result: Boolean) = ApplicabilityResult(result, shouldStop = false)
@JvmField
val UNKNOWN = ApplicabilityResult(isApplicable = false, shouldStop = false)
@JvmField
val DEFINITELY_YES = ApplicabilityResult(isApplicable = true, shouldStop = true)
@JvmField
val DEFINITELY_NO = ApplicabilityResult(isApplicable = false, shouldStop = true)
@JvmField
val MAYBE_YES = ApplicabilityResult(isApplicable = true, shouldStop = false)
}
}
fun isBreakpointApplicable(file: VirtualFile, line: Int, project: Project, checker: (PsiElement) -> ApplicabilityResult): Boolean {
val psiFile = PsiManager.getInstance(project).findFile(file)
if (psiFile == null || psiFile.virtualFile?.fileType != KotlinFileType.INSTANCE) {
return false
}
val document = FileDocumentManager.getInstance().getDocument(file) ?: return false
return runReadAction {
var isApplicable = false
val checked = HashSet<PsiElement>()
XDebuggerUtil.getInstance().iterateLine(
project, document, line,
fun(element: PsiElement): Boolean {
if (element is PsiWhiteSpace || element.getParentOfType<PsiComment>(false) != null || !element.isValid) {
return true
}
val parent = getTopmostParentOnLineOrSelf(element, document, line)
if (!checked.add(parent)) {
return true
}
val result = checker(parent)
if (result.shouldStop && !result.isApplicable) {
isApplicable = false
return false
}
isApplicable = isApplicable or result.isApplicable
return !result.shouldStop
},
)
return@runReadAction isApplicable
}
}
private fun getTopmostParentOnLineOrSelf(element: PsiElement, document: Document, line: Int): PsiElement {
var current = element
var parent = current.parent
while (parent != null && parent !is PsiFile) {
val offset = parent.textOffset
if (offset > document.textLength) break
if (offset >= 0 && document.getLineNumber(offset) != line) break
current = parent
parent = current.parent
}
return current
}
fun computeLineBreakpointVariants(
project: Project,
position: XSourcePosition,
kotlinBreakpointType: KotlinLineBreakpointType,
): List<JavaLineBreakpointType.JavaBreakpointVariant> {
val file = PsiManager.getInstance(project).findFile(position.file) as? KtFile ?: return emptyList()
val pos = SourcePosition.createFromLine(file, position.line)
val lambdas = getLambdasAtLineIfAny(pos)
if (lambdas.isEmpty()) return emptyList()
val result = LinkedList<JavaLineBreakpointType.JavaBreakpointVariant>()
val elementAt = pos.elementAt.parentsWithSelf.firstIsInstance<KtElement>()
val mainMethod = PsiTreeUtil.getParentOfType(elementAt, KtFunction::class.java, false)
var mainMethodAdded = false
if (mainMethod != null) {
val bodyExpression = mainMethod.bodyExpression
val isLambdaResult = bodyExpression is KtLambdaExpression && bodyExpression.functionLiteral in lambdas
if (!isLambdaResult) {
val variantElement = getTopmostElementAtOffset(elementAt, pos.offset)
result.add(kotlinBreakpointType.LineKotlinBreakpointVariant(position, variantElement, -1))
mainMethodAdded = true
}
}
lambdas.forEachIndexed { ordinal, lambda ->
val positionImpl = XSourcePositionImpl.createByElement(lambda.bodyExpression)
if (positionImpl != null) {
result.add(kotlinBreakpointType.LambdaJavaBreakpointVariant(positionImpl, lambda, ordinal))
}
}
if (mainMethodAdded && result.size > 1) {
result.add(kotlinBreakpointType.KotlinBreakpointVariant(position, lambdas.size))
}
return result
}
fun getLambdasAtLineIfAny(sourcePosition: SourcePosition): List<KtFunction> {
val file = sourcePosition.file as? KtFile ?: return emptyList()
return getLambdasAtLineIfAny(file, sourcePosition.line)
}
inline fun <reified T : PsiElement> getElementsAtLineIfAny(file: KtFile, line: Int): List<T> {
val lineElement = findElementAtLine(file, line) as? KtElement ?: return emptyList()
val start = lineElement.startOffset
var end = lineElement.endOffset
var nextSibling = lineElement.nextSibling
while (nextSibling != null && line == nextSibling.getLineNumber()) {
end = nextSibling.endOffset
nextSibling = nextSibling.nextSibling
}
return findElementsOfClassInRange(file, start, end, T::class.java).filterIsInstance<T>()
}
fun getLambdasAtLineIfAny(file: KtFile, line: Int): List<KtFunction> {
val allLiterals = getElementsAtLineIfAny<KtFunction>(file, line)
// filter function literals and functional expressions
.filter { it is KtFunctionLiteral || it.name == null }
.toSet()
return allLiterals.filter {
val statement = it.bodyBlockExpression?.statements?.firstOrNull() ?: it
statement.getLineNumber() == line && statement.getLineNumber(false) == line
}
}
internal fun KtCallableDeclaration.isInlineOnly(): Boolean {
if (!hasModifier(KtTokens.INLINE_KEYWORD)) {
return false
}
val inlineOnlyAnnotation = annotationEntries
.firstOrNull { it.shortName == INLINE_ONLY_ANNOTATION_FQ_NAME.shortName() }
?: return false
return runReadAction f@{
val bindingContext = inlineOnlyAnnotation.analyze(BodyResolveMode.PARTIAL)
val annotationDescriptor = bindingContext[BindingContext.ANNOTATION, inlineOnlyAnnotation] ?: return@f false
return@f annotationDescriptor.fqName == INLINE_ONLY_ANNOTATION_FQ_NAME
}
}
| apache-2.0 | e60bbe489087dc6341a5f37883d6ad8d | 37.54902 | 158 | 0.718591 | 4.924233 | false | false | false | false |
mdaniel/intellij-community | platform/build-scripts/groovy/org/jetbrains/intellij/build/BuildOptions.kt | 1 | 15642 | // 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.intellij.build
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.util.SystemProperties
import org.jetbrains.annotations.ApiStatus.Internal
import java.nio.file.Path
import java.util.concurrent.ThreadLocalRandom
/**
* Pass comma-separated names of build steps (see below) to this system property to skip them.
*/
private const val BUILD_STEPS_TO_SKIP_PROPERTY = "intellij.build.skip.build.steps"
class BuildOptions {
companion object {
/**
* Use this property to change the project compiled classes output directory.
*
* @see {@link org.jetbrains.intellij.build.impl.CompilationContextImpl.getProjectOutputDirectory}
*/
const val PROJECT_CLASSES_OUTPUT_DIRECTORY_PROPERTY = "intellij.project.classes.output.directory"
const val OS_LINUX = "linux"
const val OS_WINDOWS = "windows"
const val OS_MAC = "mac"
const val OS_ALL = "all"
const val OS_CURRENT = "current"
/**
* If this value is set no distributions of the product will be produced, only [non-bundled plugins][ProductModulesLayout.setPluginModulesToPublish]
* will be built.
*/
const val OS_NONE = "none"
/** Pre-builds SVG icons for all SVG resource files to speedup icons loading at runtime */
const val SVGICONS_PREBUILD_STEP = "svg_icons_prebuild"
/** Build actual searchableOptions.xml file. If skipped; the (possibly outdated) source version of the file will be used. */
const val SEARCHABLE_OPTIONS_INDEX_STEP = "search_index"
const val BROKEN_PLUGINS_LIST_STEP = "broken_plugins_list"
const val PROVIDED_MODULES_LIST_STEP = "provided_modules_list"
const val GENERATE_JAR_ORDER_STEP = "jar_order"
const val SOURCES_ARCHIVE_STEP = "sources_archive"
const val SCRAMBLING_STEP = "scramble"
const val NON_BUNDLED_PLUGINS_STEP = "non_bundled_plugins"
/** Build Maven artifacts for IDE modules. */
const val MAVEN_ARTIFACTS_STEP = "maven_artifacts"
/** Build macOS artifacts. */
const val MAC_ARTIFACTS_STEP = "mac_artifacts"
/** Build .dmg file for macOS. If skipped, only .sit archive will be produced. */
const val MAC_DMG_STEP = "mac_dmg"
/**
* Publish .sit file for macOS. If skipped, only .dmg archive will be produced.
* If skipped together with [MAC_DMG_STEP], only .zip archive will be produced.
*
* Note: .sit is required to build patches.
*/
const val MAC_SIT_PUBLICATION_STEP = "mac_sit"
/** Sign macOS distribution. */
const val MAC_SIGN_STEP = "mac_sign"
/** Build Linux artifacts. */
const val LINUX_ARTIFACTS_STEP = "linux_artifacts"
/** Build Linux tar.gz artifact without bundled JRE. */
const val LINUX_TAR_GZ_WITHOUT_BUNDLED_JRE_STEP = "linux_tar_gz_without_jre"
/** Build *.exe installer for Windows distribution. If skipped, only .zip archive will be produced. */
const val WINDOWS_EXE_INSTALLER_STEP = "windows_exe_installer"
/** Sign *.exe files in Windows distribution. */
const val WIN_SIGN_STEP = "windows_sign"
@JvmField
@Internal
val WIN_SIGN_OPTIONS = System.getProperty("intellij.build.win.sign.options", "")
.split(';')
.dropLastWhile { it.isEmpty() }
.asSequence()
.filter { !it.isBlank() }
.associate {
val item = it.split('=', limit = 2)
require(item.size == 2) { "Could not split by '=': $it" }
item[0] to item[1]
}
/** Build Frankenstein artifacts. */
const val CROSS_PLATFORM_DISTRIBUTION_STEP = "cross_platform_dist"
/** Toolbox links generator step */
const val TOOLBOX_LITE_GEN_STEP = "toolbox_lite_gen"
/** Generate files containing lists of used third-party libraries */
const val THIRD_PARTY_LIBRARIES_LIST_STEP = "third_party_libraries"
/** Build community distributives */
const val COMMUNITY_DIST_STEP = "community_dist"
const val OS_SPECIFIC_DISTRIBUTIONS_STEP = "os_specific_distributions"
const val PREBUILD_SHARED_INDEXES = "prebuild_shared_indexes"
const val SETUP_BUNDLED_MAVEN = "setup_bundled_maven"
const val VERIFY_CLASS_FILE_VERSIONS = "verify_class_file_versions"
/**
* Publish artifacts to TeamCity storage while the build is still running, immediately after the artifacts are built.
* Comprises many small publication steps.
* Note: skipping this step won't affect publication of 'Artifact paths' in TeamCity build settings and vice versa
*/
const val TEAMCITY_ARTIFACTS_PUBLICATION_STEP = "teamcity_artifacts_publication"
/**
* @see org.jetbrains.intellij.build.fus.StatisticsRecorderBundledMetadataProvider
*/
const val FUS_METADATA_BUNDLE_STEP = "fus_metadata_bundle_step"
/**
* @see org.jetbrains.intellij.build.impl.support.RepairUtilityBuilder
*/
const val REPAIR_UTILITY_BUNDLE_STEP = "repair_utility_bundle_step"
/**
* Pass 'true' to this system property to produce an additional .dmg and .sit archives for macOS without Runtime.
*/
const val BUILD_MAC_ARTIFACTS_WITHOUT_RUNTIME = "intellij.build.dmg.without.bundled.jre"
/**
* Pass 'false' to this system property to skip building .dmg and .sit with bundled Runtime.
*/
const val BUILD_MAC_ARTIFACTS_WITH_RUNTIME = "intellij.build.dmg.with.bundled.jre"
/**
* By default, build cleanup output folder before compilation, use this property to change this behaviour.
*/
const val CLEAN_OUTPUT_FOLDER_PROPERTY = "intellij.build.clean.output.root"
/**
* If `false` build scripts compile project classes to a special output directory (to not interfere with the default project output if
* invoked on a developer machine).
* If `true` compilation step is skipped and compiled classes from the project output are used instead.
* True if [BuildOptions.isInDevelopmentMode] is enabled.
*
* @see {@link org.jetbrains.intellij.build.impl.CompilationContextImpl.getProjectOutputDirectory}
*/
const val USE_COMPILED_CLASSES_PROPERTY = "intellij.build.use.compiled.classes"
/**
* Enables module structure validation, false by default
*/
const val VALIDATE_MODULES_STRUCTURE_PROPERTY = "intellij.build.module.structure"
/**
* Verify whether class files have a forbidden subpaths in them, false by default
*/
const val VALIDATE_CLASSFILE_SUBPATHS_PROPERTY = "intellij.verify.classfile.subpaths"
/**
* Max attempts of dependencies resolution on fault. "1" means no retries.
*
* @see {@link org.jetbrains.intellij.build.impl.JpsCompilationRunner.resolveProjectDependencies}
*/
const val RESOLVE_DEPENDENCIES_MAX_ATTEMPTS_PROPERTY = "intellij.build.dependencies.resolution.retry.max.attempts"
/**
* Initial delay in milliseconds between dependencies resolution retries on fault. Default is 1000
*
* @see {@link org.jetbrains.intellij.build.impl.JpsCompilationRunner.resolveProjectDependencies}
*/
const val RESOLVE_DEPENDENCIES_DELAY_MS_PROPERTY = "intellij.build.dependencies.resolution.retry.delay.ms"
const val TARGET_OS_PROPERTY = "intellij.build.target.os"
}
var projectClassesOutputDirectory: String? = System.getProperty(PROJECT_CLASSES_OUTPUT_DIRECTORY_PROPERTY)
/**
* Specifies for which operating systems distributions should be built.
*/
var targetOs: String
/**
* Specifies for which arch distributions should be built. null means all
*/
var targetArch: JvmArchitecture? = null
/**
* Pass comma-separated names of build steps (see below) to [BUILD_STEPS_TO_SKIP_PROPERTY] system property to skip them when building locally.
*/
var buildStepsToSkip: MutableSet<String> = System.getProperty(BUILD_STEPS_TO_SKIP_PROPERTY, "")
.split(',')
.dropLastWhile { it.isEmpty() }
.asSequence()
.filter { s: String -> !s.isBlank() }
.toHashSet()
var buildMacArtifactsWithoutRuntime = SystemProperties.getBooleanProperty(BUILD_MAC_ARTIFACTS_WITHOUT_RUNTIME,
SystemProperties.getBooleanProperty("artifact.mac.no.jdk", false))
var buildMacArtifactsWithRuntime = SystemProperties.getBooleanProperty(BUILD_MAC_ARTIFACTS_WITH_RUNTIME, true)
/**
* Pass 'true' to this system property to produce .snap packages.
* A build configuration should have "docker.version >= 17" in requirements.
*/
var buildUnixSnaps = SystemProperties.getBooleanProperty("intellij.build.unix.snaps", false)
/**
* Image for snap package creation. Default is "snapcore/snapcraft:stable", but can be modified mostly due to problems
* with new versions of snapcraft.
*/
var snapDockerImage: String = System.getProperty("intellij.build.snap.docker.image", "snapcore/snapcraft:stable")
var snapDockerBuildTimeoutMin: Long = System.getProperty("intellij.build.snap.timeoutMin", "20").toLong()
/**
* Path to a zip file containing 'production' and 'test' directories with compiled classes of the project modules inside.
*/
var pathToCompiledClassesArchive: Path? = System.getProperty("intellij.build.compiled.classes.archive")?.let { Path.of(it) }
/**
* Path to a metadata file containing urls with compiled classes of the project modules inside.
* Metadata is a [org.jetbrains.intellij.build.impl.compilation.CompilationPartsMetadata] serialized into json format
*/
var pathToCompiledClassesArchivesMetadata: String? = System.getProperty("intellij.build.compiled.classes.archives.metadata")
/**
* If `true` the project modules will be compiled incrementally
*/
var incrementalCompilation = SystemProperties.getBooleanProperty("intellij.build.incremental.compilation", false)
/**
* By default, some build steps are executed in parallel threads. Set this property to `false` to disable this.
*/
var runBuildStepsInParallel = SystemProperties.getBooleanProperty("intellij.build.run.steps.in.parallel", true)
/**
* Build number without product code (e.g. '162.500.10'), if `null` '<baseline>.SNAPSHOT' will be used. Use [BuildContext.buildNumber] to
* get the actual build number in build scripts.
*/
var buildNumber: String? = System.getProperty("build.number")
/**
* By default, build process produces temporary and resulting files under projectHome/out/productName directory, use this property to
* change the output directory.
*/
var outputRootPath: String? = System.getProperty("intellij.build.output.root")
var logPath: String? = System.getProperty("intellij.build.log.root")
/**
* If `true` write a separate compilation.log for all compilation messages
*/
var compilationLogEnabled = SystemProperties.getBooleanProperty("intellij.build.compilation.log.enabled", true)
var cleanOutputFolder = SystemProperties.getBooleanProperty(CLEAN_OUTPUT_FOLDER_PROPERTY, true)
/**
* If `true` the build is running in 'Development mode' i.e. its artifacts aren't supposed to be used in production. In development
* mode build scripts won't fail if some non-mandatory dependencies are missing and will just show warnings.
*
* By default, 'development mode' is enabled if build is not running under continuous integration server (TeamCity).
*/
var isInDevelopmentMode = SystemProperties.getBooleanProperty("intellij.build.dev.mode", System.getenv("TEAMCITY_VERSION") == null)
var useCompiledClassesFromProjectOutput = SystemProperties.getBooleanProperty(USE_COMPILED_CLASSES_PROPERTY, isInDevelopmentMode)
/**
* If `true` the build is running as a unit test
*/
var isTestBuild = SystemProperties.getBooleanProperty("intellij.build.test.mode", false)
var skipDependencySetup = false
/**
* Specifies list of names of directories of bundled plugins which shouldn't be included into the product distribution. This option can be
* used to speed up updating the IDE from sources.
*/
val bundledPluginDirectoriesToSkip = getSetProperty("intellij.build.bundled.plugin.dirs.to.skip")
/**
* Specifies list of names of directories of non-bundled plugins (determined by [ProductModulesLayout.pluginsToPublish] and
* [ProductModulesLayout.buildAllCompatiblePlugins]) which should be actually built. This option can be used to speed up updating
* the IDE from sources. By default, all plugins determined by [ProductModulesLayout.pluginsToPublish] and
* [ProductModulesLayout.buildAllCompatiblePlugins] are built. In order to skip building all non-bundled plugins, set the property to
* `none`.
*/
val nonBundledPluginDirectoriesToInclude = getSetProperty("intellij.build.non.bundled.plugin.dirs.to.include")
/**
* Specifies [org.jetbrains.intellij.build.JetBrainsRuntimeDistribution] build to be bundled with distributions. If `null` then `runtimeBuild` from gradle.properties will be used.
*/
var bundledRuntimeBuild: String? = System.getProperty("intellij.build.bundled.jre.build")
/**
* Specifies a prefix to use when looking for an artifact of a [org.jetbrains.intellij.build.JetBrainsRuntimeDistribution] to be bundled with distributions.
* If `null`, `"jbr_jcef-"` will be used.
*/
var bundledRuntimePrefix: String? = System.getProperty("intellij.build.bundled.jre.prefix")
/**
* Enables fastdebug runtime
*/
var runtimeDebug = parseBooleanValue(System.getProperty("intellij.build.bundled.jre.debug", "false"))
/**
* Specifies an algorithm to build distribution checksums.
*/
val hashAlgorithm = "SHA-384"
var validateModuleStructure = parseBooleanValue(System.getProperty(VALIDATE_MODULES_STRUCTURE_PROPERTY, "false"))
var validateClassFileSubpaths = parseBooleanValue(System.getProperty(VALIDATE_CLASSFILE_SUBPATHS_PROPERTY, "false"))
@Internal
var compressNonBundledPluginArchive = true
var resolveDependenciesMaxAttempts = System.getProperty(RESOLVE_DEPENDENCIES_MAX_ATTEMPTS_PROPERTY, "2").toInt()
var resolveDependenciesDelayMs = System.getProperty(RESOLVE_DEPENDENCIES_DELAY_MS_PROPERTY, "1000").toLong()
/**
* See https://reproducible-builds.org/specs/source-date-epoch/
*/
var buildDateInSeconds: Long = 0
var randomSeedNumber: Long = 0
init {
var targetOs = System.getProperty(TARGET_OS_PROPERTY, OS_ALL)
if (targetOs == OS_CURRENT) {
targetOs = when {
SystemInfoRt.isWindows -> OS_WINDOWS
SystemInfoRt.isMac -> OS_MAC
SystemInfoRt.isLinux -> OS_LINUX
else -> throw RuntimeException("Unknown OS")
}
}
else if (targetOs.isEmpty()) {
targetOs = OS_ALL
}
this.targetOs = targetOs
val sourceDateEpoch = System.getenv("SOURCE_DATE_EPOCH")
buildDateInSeconds = sourceDateEpoch?.toLong() ?: (System.currentTimeMillis() / 1000)
val randomSeedString = System.getProperty("intellij.build.randomSeed")
randomSeedNumber = if (randomSeedString == null || randomSeedString.isBlank()) {
ThreadLocalRandom.current().nextLong()
}
else {
randomSeedString.toLong()
}
}
}
private fun parseBooleanValue(text: String): Boolean {
return when {
text.toBoolean() -> true
text.equals(java.lang.Boolean.FALSE.toString(), ignoreCase = true) -> false
else -> throw IllegalArgumentException("Could not parse as boolean, accepted values are only 'true' or 'false': $text")
}
}
private fun getSetProperty(name: String): Set<String> {
return java.util.Set.copyOf((System.getProperty(name) ?: return emptySet()).split(','))
}
| apache-2.0 | ce0f95b0a4046952471946ad7c6f61b6 | 42.571031 | 181 | 0.719473 | 4.315034 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/troika/TroikaBlock.kt | 1 | 10784 | package au.id.micolous.metrodroid.transit.troika
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.Parcelable
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.*
import au.id.micolous.metrodroid.transit.Subscription
import au.id.micolous.metrodroid.transit.TransitBalance
import au.id.micolous.metrodroid.transit.TransitIdentity
import au.id.micolous.metrodroid.transit.Trip
import au.id.micolous.metrodroid.ui.ListItem
import au.id.micolous.metrodroid.util.NumberUtils
import au.id.micolous.metrodroid.util.ImmutableByteArray
abstract class TroikaBlock private constructor(private val mSerial: Long,
protected val mLayout: Int,
protected val mTicketType: Int,
/**
* Last transport type
*/
private val mLastTransportLeadingCode: Int?,
private val mLastTransportLongCode: Int?,
private val mLastTransportRaw: String?,
/**
* ID of the last validator.
*/
protected val mLastValidator: Int?,
/**
* Validity length in minutes.
*/
protected val mValidityLengthMinutes: Int?,
/**
* Expiry date of the card.
*/
protected val mExpiryDate: Timestamp?,
/**
* Time of the last validation.
*/
protected val mLastValidationTime: TimestampFull?,
/**
* Start of validity period
*/
private val mValidityStart: Timestamp?,
/**
* End of validity period
*/
protected val mValidityEnd: Timestamp?,
/**
* Number of trips remaining
*/
private val mRemainingTrips: Int?,
/**
* Last transfer in minutes after validation
*/
protected val mLastTransfer: Int?,
/**
* Text description of last fare.
*/
private val mFareDesc: String?) : Parcelable {
val serialNumber: String
get() = formatSerial(mSerial)
open val subscription: Subscription?
get() = TroikaSubscription(mExpiryDate, mValidityStart, mValidityEnd,
mRemainingTrips, mValidityLengthMinutes, mTicketType)
open val info: List<ListItem>?
get() = null
val trips: List<Trip>
get() {
val t = mutableListOf<Trip>()
val rawTransport = mLastTransportRaw ?: (mLastTransportLeadingCode?.shl(8)?.or(mLastTransportLongCode ?: 0))?.toString(16)
if (mLastValidationTime != null) {
if (mLastTransfer != null && mLastTransfer != 0) {
val lastTransfer = mLastValidationTime.plus(Duration.mins(mLastTransfer))
t.add(TroikaTrip(lastTransfer, getTransportType(true), mLastValidator, rawTransport, mFareDesc))
t.add(TroikaTrip(mLastValidationTime, getTransportType(false), null, rawTransport, mFareDesc))
} else
t.add(TroikaTrip(mLastValidationTime, getTransportType(true), mLastValidator, rawTransport, mFareDesc))
}
return t
}
val cardName: String
get() = Localizer.localizeString(R.string.card_name_troika)
open val balance: TransitBalance?
get() = null
constructor(rawData: ImmutableByteArray,
mLastTransportLeadingCode: Int? = null,
mLastTransportLongCode: Int? = null,
mLastTransportRaw: String? = null,
mLastValidator: Int? = null,
mValidityLengthMinutes: Int? = null,
mExpiryDate: Timestamp? = null,
mLastValidationTime: TimestampFull? = null,
mValidityStart: Timestamp? = null,
mValidityEnd: Timestamp? = null,
mRemainingTrips: Int? = null,
mLastTransfer: Int? = null,
mFareDesc: String? = null) : this(
mSerial = getSerial(rawData),
mLayout = getLayout(rawData),
mTicketType = getTicketType(rawData),
mLastTransportLeadingCode = mLastTransportLeadingCode,
mLastTransportLongCode = mLastTransportLongCode,
mLastTransportRaw = mLastTransportRaw,
mLastValidator = mLastValidator,
mValidityLengthMinutes = mValidityLengthMinutes,
mExpiryDate = mExpiryDate,
mLastValidationTime = mLastValidationTime,
mValidityStart = mValidityStart,
mValidityEnd = mValidityEnd,
mRemainingTrips = mRemainingTrips,
mLastTransfer = mLastTransfer,
mFareDesc = mFareDesc
)
internal enum class TroikaTransportType {
NONE,
UNKNOWN,
SUBWAY,
MONORAIL,
GROUND,
MCC
}
internal open fun getTransportType(getLast: Boolean): TroikaTransportType? {
when (mLastTransportLeadingCode) {
0 -> return TroikaTransportType.NONE
1 -> {
}
2 -> {
return if (getLast) TroikaTransportType.GROUND else TroikaTransportType.UNKNOWN
}
/* Fallthrough */
else -> return TroikaTransportType.UNKNOWN
}
if (mLastTransportLongCode == 0 || mLastTransportLongCode == null)
return TroikaTransportType.UNKNOWN
// This is actually 4 fields used in sequence.
var first: TroikaTransportType? = null
var last: TroikaTransportType? = null
var i = 6
var found = 0
while (i >= 0) {
val shortCode = mLastTransportLongCode shr i and 3
if (shortCode == 0) {
i -= 2
continue
}
var type: TroikaTransportType? = null
when (shortCode) {
1 -> type = TroikaTransportType.SUBWAY
2 -> type = TroikaTransportType.MONORAIL
3 -> type = TroikaTransportType.MCC
}
if (first == null)
first = type
last = type
found++
i -= 2
}
if (found == 1 && !getLast)
return TroikaTransportType.UNKNOWN
return if (getLast) last else first
}
companion object {
private val TROIKA_EPOCH_1992 = Epoch.local(1992, MetroTimeZone.MOSCOW)
private val TROIKA_EPOCH_2016 = Epoch.local(2016, MetroTimeZone.MOSCOW)
fun convertDateTime1992(days: Int, mins: Int): TimestampFull? {
if (days == 0 && mins == 0)
return null
return TROIKA_EPOCH_1992.dayMinute(days - 1, mins)
}
fun convertDateTime1992(days: Int): Daystamp? {
if (days == 0)
return null
return TROIKA_EPOCH_1992.days(days - 1)
}
fun convertDateTime2016(days: Int, mins: Int): TimestampFull? {
if (days == 0 && mins == 0)
return null
return TROIKA_EPOCH_2016.dayMinute(days - 1, mins)
}
fun formatSerial(sn: Long): String {
return NumberUtils.formatNumber(sn, " ", 4, 3, 3)
}
fun getSerial(rawData: ImmutableByteArray): Long {
return rawData.getBitsFromBuffer(20, 32).toLong() and 0xffffffffL
}
private fun getTicketType(rawData: ImmutableByteArray): Int {
return rawData.getBitsFromBuffer(4, 16)
}
private fun getLayout(rawData: ImmutableByteArray): Int {
return rawData.getBitsFromBuffer(52, 4)
}
fun parseTransitIdentity(rawData: ImmutableByteArray): TransitIdentity {
return TransitIdentity(Localizer.localizeString(R.string.card_name_troika),
formatSerial(getSerial(rawData)))
}
fun getHeader(ticketType: Int): String {
when (ticketType) {
0x5d3d, 0x5d3e, 0x5d48, 0x2135 ->
// This should never be shown to user, don't localize.
return "Empty ticket holder"
0x183d, 0x2129 -> return Localizer.localizeString(R.string.troika_druzhinnik_card)
0x5d9b -> return troikaRides(1)
0x5d9c -> return troikaRides(2)
0x5da0 -> return troikaRides(20)
0x5db1 ->
// This should never be shown to user, don't localize.
return "Troika purse"
0x5dd3 -> return troikaRides(60)
}
return Localizer.localizeString(R.string.troika_unknown_ticket, ticketType.toString(16))
}
private fun troikaRides(rides: Int): String {
return Localizer.localizePlural(R.plurals.troika_rides, rides, rides)
}
fun check(rawData: ImmutableByteArray): Boolean =
rawData.getBitsFromBuffer(0, 10) in listOf(0x117, 0x108, 0x106)
fun parseBlock(rawData: ImmutableByteArray): TroikaBlock {
val layout = getLayout(rawData)
when (layout) {
0x2 -> return TroikaLayout2(rawData)
0xa -> return TroikaLayoutA(rawData)
0xd -> return TroikaLayoutD(rawData)
0xe -> {
val sublayout = rawData.getBitsFromBuffer(56, 5)
when (sublayout) {
2 -> return TroikaLayoutE(rawData)
3 -> return TroikaPurse(rawData)
}
}
}
return TroikaUnknownBlock(rawData)
}
}
}
| gpl-3.0 | 6c1163b382e8ada9196b320656ab4771 | 38.940741 | 134 | 0.51428 | 5.851329 | false | false | false | false |
JavaEden/Orchid-Core | plugins/OrchidForms/src/main/kotlin/com/eden/orchid/forms/FormsGenerator.kt | 2 | 1699 | package com.eden.orchid.forms
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.generators.OrchidGenerator
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.forms.model.Form
import com.eden.orchid.forms.model.FormsModel
import com.eden.orchid.utilities.OrchidUtils
@Description("Indexes form definitions so they can be easily referenced from components on different pages.",
name = "Forms"
)
class FormsGenerator : OrchidGenerator<FormsModel>(GENERATOR_KEY, Stage.CONTENT) {
companion object {
const val GENERATOR_KEY = "forms"
}
@Option
@StringDefault("forms")
@Description("The base directory in local resources to look for forms in.")
lateinit var baseDir: String
override fun startIndexing(context: OrchidContext): FormsModel {
val forms = getFormsByDatafiles(context)
return FormsModel(forms)
}
private fun getFormsByDatafiles(context: OrchidContext) : List<Form> {
return context
.getDefaultResourceSource(null, null)
.getResourceEntries(
context,
OrchidUtils.normalizePath(baseDir),
context.parserExtensions.toTypedArray(),
false
)
.map { resource ->
resource.reference.isUsePrettyUrl = false
val fileData = context.parse(resource.reference.extension, resource.content)
val key = resource.reference.originalFileName
Form(context, key, fileData)
}
}
}
| mit | 23f49a8a6d6e4f81c84aa8ef22c8646a | 33.673469 | 109 | 0.683343 | 4.667582 | false | false | false | false |
hzsweers/CatchUp | app/src/debug/kotlin/io/sweers/catchup/ui/debug/NonConsumingScrimInsetsFrameLayout.kt | 1 | 3499 | /*
* Copyright (C) 2019. Zac Sweers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sweers.catchup.ui.debug
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.widget.FrameLayout
import androidx.core.content.res.use
import androidx.core.view.ViewCompat
import io.sweers.catchup.R
/**
* A layout that draws something in the insets passed to [.fitSystemWindows], i.e. the
* area above UI chrome (status and navigation bars, overlay action bars).
*
*
* Unlike the `ScrimInsetsFrameLayout` in the design support library, this variant does not
* consume the insets.
*/
class NonConsumingScrimInsetsFrameLayout : FrameLayout {
private var insetForeground: Drawable? = null
private var insets: Rect? = null
private val tempRect = Rect()
constructor(context: Context) : super(context) {
init(context, null, 0)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(context, attrs, 0)
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(
context,
attrs,
defStyle
) {
init(context, attrs, defStyle)
}
private fun init(context: Context, attrs: AttributeSet?, defStyle: Int) {
context.obtainStyledAttributes(
attrs,
R.styleable.NonConsumingScrimInsetsView,
defStyle,
0
).use {
insetForeground = it.getDrawable(R.styleable.NonConsumingScrimInsetsView_insetForeground)
}
setWillNotDraw(true)
}
override fun fitSystemWindows(insets: Rect): Boolean {
this.insets = Rect(insets)
setWillNotDraw(insetForeground == null)
ViewCompat.postInvalidateOnAnimation(this)
return false // Do not consume insets.
}
override fun draw(canvas: Canvas) {
super.draw(canvas)
val width = width
val height = height
if (insets != null && insetForeground != null) {
val sc = canvas.save()
canvas.translate(scrollX.toFloat(), scrollY.toFloat())
// Top
tempRect.set(0, 0, width, insets!!.top)
insetForeground!!.bounds = tempRect
insetForeground!!.draw(canvas)
// Bottom
tempRect.set(0, height - insets!!.bottom, width, height)
insetForeground!!.bounds = tempRect
insetForeground!!.draw(canvas)
// Left
tempRect.set(0, insets!!.top, insets!!.left, height - insets!!.bottom)
insetForeground!!.bounds = tempRect
insetForeground!!.draw(canvas)
// Right
tempRect.set(width - insets!!.right, insets!!.top, width, height - insets!!.bottom)
insetForeground!!.bounds = tempRect
insetForeground!!.draw(canvas)
canvas.restoreToCount(sc)
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
insetForeground?.callback = this
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
insetForeground?.callback = null
}
}
| apache-2.0 | 805b87f08d3af93fea69ae7fd9a63214 | 28.652542 | 95 | 0.702772 | 4.35199 | false | false | false | false |
google/accompanist | swiperefresh/src/main/java/com/google/accompanist/swiperefresh/Slingshot.kt | 1 | 2941 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.accompanist.swiperefresh
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.pow
/**
* A utility function that calculates various aspects of 'slingshot' behavior.
* Adapted from SwipeRefreshLayout#moveSpinner method.
*
* TODO: Investigate replacing this with a spring.
*
* @param offsetY The current y offset.
* @param maxOffsetY The max y offset.
* @param height The height of the item to slingshot.
*/
@Composable
internal fun rememberUpdatedSlingshot(
offsetY: Float,
maxOffsetY: Float,
height: Int
): Slingshot {
val offsetPercent = min(1f, offsetY / maxOffsetY)
val adjustedPercent = max(offsetPercent - 0.4f, 0f) * 5 / 3
val extraOffset = abs(offsetY) - maxOffsetY
// Can accommodate custom start and slingshot distance here
val slingshotDistance = maxOffsetY
val tensionSlingshotPercent = max(
0f, min(extraOffset, slingshotDistance * 2) / slingshotDistance
)
val tensionPercent = (
(tensionSlingshotPercent / 4) -
(tensionSlingshotPercent / 4).pow(2)
) * 2
val extraMove = slingshotDistance * tensionPercent * 2
val targetY = height + ((slingshotDistance * offsetPercent) + extraMove).toInt()
val offset = targetY - height
val strokeStart = adjustedPercent * 0.8f
val startTrim = 0f
val endTrim = strokeStart.coerceAtMost(MaxProgressArc)
val rotation = (-0.25f + 0.4f * adjustedPercent + tensionPercent * 2) * 0.5f
val arrowScale = min(1f, adjustedPercent)
return remember { Slingshot() }.apply {
this.offset = offset
this.startTrim = startTrim
this.endTrim = endTrim
this.rotation = rotation
this.arrowScale = arrowScale
}
}
@Stable
internal class Slingshot {
var offset: Int by mutableStateOf(0)
var startTrim: Float by mutableStateOf(0f)
var endTrim: Float by mutableStateOf(0f)
var rotation: Float by mutableStateOf(0f)
var arrowScale: Float by mutableStateOf(0f)
}
internal const val MaxProgressArc = 0.8f
| apache-2.0 | 8c6c3ee6a324cd93f1e2ed0b99299e12 | 32.420455 | 84 | 0.724243 | 4.113287 | false | false | false | false |
marius-m/wt4 | components/src/main/java/lt/markmerkk/ViewProvider.kt | 1 | 1088 | package lt.markmerkk
/**
* Thin layer to get the available view
* Ex.1 Useful when presenter is initialized, when view is not available yet
* The view is passed through lambda, thus functions only trigger when view is available
*/
abstract class ViewProvider<T> {
abstract fun get(): T?
/**
* It is easy to get the view from Kotlin and do a null check.
* This is not the case on Java.
* This convenience function will trigger function *only when view is available*
*/
fun invoke(block: T.() -> Unit) {
val view: T? = get()
if (view != null) {
block.invoke(view)
}
}
/**
* More java-like lambda consumable function
* Successor of [invoke]
*/
fun invokeJ(block: OnViewAvailableListener<T>) {
val view: T? = get()
if (view != null) {
block.invokeOnView(view)
}
}
}
class ViewProviderEmpty<T> : ViewProvider<T>() {
override fun get(): T? = null
}
@FunctionalInterface
interface OnViewAvailableListener<T> {
fun invokeOnView(view: T)
}
| apache-2.0 | 729c087c9512bab873a0a07826c955da | 24.904762 | 93 | 0.613971 | 4.04461 | false | false | false | false |
marklemay/IntelliJATS | src/main/kotlin/com/atslangplugin/experimantal/ATSTokenTypes.kt | 1 | 16221 |
//TODO: seems to corespond to datatype token_node in pats_lexing.sats,
// a more stable solution might be to generate this from the ATS compiler source,
// in theory the lexer could be implemented that way
// now that abstract datatypes are finally a thing in Java land
//TODO: these Int's are likely infinite precision,
//TODO: handle the "bad char"
// TODO: transpose the comments into "javadoc" style comments
package com.atslangplugin.experimantal
import com.atslangplugin.ATSLanguage
import com.intellij.psi.tree.IElementType
import org.jetbrains.annotations.NonNls
//TODO: object
//from pats_basics.sats
sealed class Fxtykind {
class FXK_infix() : Fxtykind()
class FXK_infixl() : Fxtykind()
class FXK_infixr() : Fxtykind()
class FXK_prefix() : Fxtykind()
class FXK_postfix() : Fxtykind()
}
sealed class Caskind {
/** case */
class CK_case() : Caskind()
/** case+ */
class CK_case_pos : Caskind()
/** case- */
class CK_case_neg : Caskind()
}
sealed class Funkind {
//TODO: javadoc
// nonrec fun
class FK_fn() : Funkind()
// tailrec fun
class FK_fnx() : Funkind()
// recursive fun
class FK_fun() : Funkind()
// nonrec proof fun
class FK_prfn() : Funkind()
// recursive proof fun
class FK_prfun() : Funkind()
// proof axiom
class FK_praxi() : Funkind()
// casting fun
class FK_castfn() : Funkind()
}
//TODO: rename to be consistent with sata
sealed class ATSTokenType(@NonNls debugName: String) : IElementType(debugName, ATSLanguage) {
//TODO: needed?
override fun toString(): String {
return "ATSTokenType." + super.toString()
}
/** // dummy */
class T_NONE() : ATSTokenType("T_NONE")
/** // @ */
class T_AT() : ATSTokenType("T_AT")
/** // | */
class T_BAR() : ATSTokenType("T_BAR")
/** // ! */
class T_BANG() : ATSTokenType("T_BANG")
/** // ` */
class T_BQUOTE() : ATSTokenType("T_BQUOTE")
/** // \ */
class T_BACKSLASH() : ATSTokenType("T_BACKSLASH")
/** // : */
class T_COLON() : ATSTokenType("T_COLON")
/** // :< */
class T_COLONLT() : ATSTokenType("T_COLONLT")
/** // $ */
class T_DOLLAR() : ATSTokenType("T_DOLLAR")
/** // . */
class T_DOT() : ATSTokenType("T_DOT")
/** // .. */
class T_DOTDOT() : ATSTokenType("T_DOTDOT")
/** // ... */
class T_DOTDOTDOT() : ATSTokenType("T_DOTDOTDOT")
/** .[0-9]+ */
class T_DOTINT(val i: Int) : ATSTokenType("T_DOTINT")
/** // = */
class T_EQ() : ATSTokenType("T_EQ")
/** // => */
class T_EQGT() : ATSTokenType("T_EQGT")
/** // =< */
class T_EQLT() : ATSTokenType("T_EQLT")
/** // =<> */
class T_EQLTGT() : ATSTokenType("T_EQLTGT")
/** // =/=> */
class T_EQSLASHEQGT() : ATSTokenType("T_EQSLASHEQGT")
/** // =>> */
class T_EQGTGT() : ATSTokenType("T_EQGTGT")
/** // =/=>> */
class T_EQSLASHEQGTGT() : ATSTokenType("T_EQSLASHEQGTGT")
/** // # */
class T_HASH() : ATSTokenType("T_HASH")
/** // < // for opening a tmparg */
class T_LT() : ATSTokenType("T_LT")
/** // > // for closing a tmparg */
class T_GT() : ATSTokenType("T_GT")
/** // <> */
class T_GTLT() : ATSTokenType("T_GTLT")
/** // .< // opening termetric */
class T_DOTLT() : ATSTokenType("T_DOTLT")
/** // >. // closing termetric */
class T_GTDOT() : ATSTokenType("T_GTDOT")
/** // .<>. // for empty termetric */
class T_DOTLTGTDOT() : ATSTokenType("T_DOTLTGTDOT")
/** // -> */
class T_MINUSGT() : ATSTokenType("T_MINUSGT")
/** // -< */
class T_MINUSLT() : ATSTokenType("T_MINUSLT")
/** // -<> */
class T_MINUSLTGT() : ATSTokenType("T_MINUSLTGT")
/** // ~ // often for 'not', 'free', etc. */
class T_TILDE() : ATSTokenType("T_TILDE")
// HX: for absprop, abstype, abst@ype;
/** absview, absvtype, absvt@ype*/
class T_ABSTYPE(val i: Int) : ATSTokenType("T_ABSTYPE")
/** // for implementing abstypes */
class T_ASSUME() : ATSTokenType("T_ASSUME")
/** // for re-assuming abstypes */
class T_REASSUME() : ATSTokenType("T_REASSUME")
/** // as // for refas-pattern */
class T_AS() : ATSTokenType("T_AS")
/** // and */
class T_AND() : ATSTokenType("T_AND")
/** // begin // initiating a sequence */
class T_BEGIN() : ATSTokenType("T_BEGIN")
/** case, case-, case+, prcase */
class T_CASE(val caskind: Caskind) : ATSTokenType("T_CASE")
/** // classdec */
class T_CLASSDEC() : ATSTokenType("T_CLASSDEC")
/** // datasort */
class T_DATASORT() : ATSTokenType("T_DATASORT")
/** datatype, dataprop, dataview, dataviewtype */
class T_DATATYPE(val i: Int) : ATSTokenType("T_DATATYPE")
/** // [do] */
class T_DO() : ATSTokenType("T_DO")
/** // [else] */
class T_ELSE() : ATSTokenType("T_ELSE")
/** // the [end] keyword */
class T_END() : ATSTokenType("T_END")
/** // [exception] */
class T_EXCEPTION() : ATSTokenType("T_EXCEPTION")
/** // extern */
class T_EXTERN() : ATSTokenType("T_EXTERN")
/** // externally named type */
class T_EXTYPE() : ATSTokenType("T_EXTYPE")
/** // externally named variable */
class T_EXTVAR() : ATSTokenType("T_EXTVAR")
/** fix and fix@ */
class T_FIX(val i: Int) : ATSTokenType("T_FIX")
/** infix, infixl, infixr, prefix, postfix */
class T_FIXITY(fxtykind: Fxtykind) : ATSTokenType("T_FIXITY")
/** // for */
class T_FOR() : ATSTokenType("T_FOR")
/** // for* */
class T_FORSTAR() : ATSTokenType("T_FORSTAR")
/** fn, fnx, fun, prfn and prfun */
class T_FUN(valfunkind: Funkind) : ATSTokenType("T_FUN")
/** // (dynamic) if */
class T_IF() : ATSTokenType("T_IF")
/** // (dynamic) ifcase */
class T_IFCASE() : ATSTokenType("T_IFCASE")
/** */
class T_IMPLEMENT(val i: Int) // 0/1/2: implmnt/implement/primplmnt :ATSTokenType("T_IMPLEMENT")
/** // import (for packages) */
class T_IMPORT() : ATSTokenType("T_IMPORT")
/** // in */
class T_IN() : ATSTokenType("T_IN")
/** lam, llam (linear lam) and lam@ (flat lam) */
class T_LAM(val i: Int) : ATSTokenType("T_LAM")
/** // let */
class T_LET() : ATSTokenType("T_LET")
/** // local */
class T_LOCAL() : ATSTokenType("T_LOCAL")
/** 0/1: macdef/macrodef */
class T_MACDEF(val i: Int) : ATSTokenType("T_MACDEF")
/** // nonfix */
class T_NONFIX() : ATSTokenType("T_NONFIX")
/** // overload */
class T_OVERLOAD() : ATSTokenType("T_OVERLOAD")
/** // of */
class T_OF() : ATSTokenType("T_OF")
/** // op // HX: taken from ML */
class T_OP() : ATSTokenType("T_OP")
/** // rec */
class T_REC() : ATSTokenType("T_REC")
/** // static if */
class T_SIF() : ATSTokenType("T_SIF")
/** // static case */
class T_SCASE() : ATSTokenType("T_SCASE")
/** // stacst */
class T_STACST() : ATSTokenType("T_STACST")
/** // stadef */
class T_STADEF() : ATSTokenType("T_STADEF")
/** // static */
class T_STATIC() : ATSTokenType("T_STATIC")
/** // sortdef */
class T_SORTDEF() : ATSTokenType("T_SORTDEF")
/** // symelim // symbol elimination */
class T_SYMELIM() : ATSTokenType("T_SYMELIM")
/** // symintr // symbol introduction */
class T_SYMINTR() : ATSTokenType("T_SYMINTR")
/** // the [then] keyword */
class T_THEN() : ATSTokenType("T_THEN")
/** // tkindef // for introducting tkinds */
class T_TKINDEF() : ATSTokenType("T_TKINDEF")
/** // try */
class T_TRY() : ATSTokenType("T_TRY")
/** type, type+, type- */
class T_TYPE(val i: Int) : ATSTokenType("T_TYPE")
/** typedef, propdef, viewdef, viewtypedef */
class T_TYPEDEF(val i: Int) : ATSTokenType("T_TYPEDEF")
//TODO: and so on...
// /** val, val+, val-, prval */
// class T_VAL(valkind) : ATSTokenType("T_VAL")
//
// //TODO:Mark: why not bool?
// /** knd = 0/1: var/prvar*/
// class T_VAR(val knd: Int) : ATSTokenType("T_VAR")
//
// /** // when */
// class T_WHEN() : ATSTokenType("T_WHEN")
//
// /** // where */
// class T_WHERE() : ATSTokenType("T_WHERE")
//
// /** // while */
// class T_WHILE() : ATSTokenType("T_WHILE")
//
// /** // while* */
// class T_WHILESTAR() : ATSTokenType("T_WHILESTAR")
//
// /** // with */
// class T_WITH() : ATSTokenType("T_WITH")
//
// /** */
// class T_WITHTYPE(int) // withtype, withprop, withview, withviewtype :ATSTokenType("T_WITHTYPE")
// // end of [T_WITHTYPE] // HX: it is from DML and now rarely used
//
// /** // addr@ */
// class T_ADDRAT() : ATSTokenType("T_ADDRAT")
//
// /** // fold@ */
// class T_FOLDAT() : ATSTokenType("T_FOLDAT")
//
// /** // free@ */
// class T_FREEAT() : ATSTokenType("T_FREEAT")
//
// /** // view@ */
// class T_VIEWAT() : ATSTokenType("T_VIEWAT")
//
// /** */ class T_DLRDELAY (int(*lin*)) // $delay/$ldelay :ATSTokenType("T_DLRDELAY")
//
// /** // $arrpsz/$arrptrsize */ class T_DLRARRPSZ () :ATSTokenType("T_DLRARRPSZ")
//
// /** // $tyrep(SomeType) */ class T_DLRTYREP () :ATSTokenType("T_DLRTYREP")
// /** // $d2ctype(foo/foo<...>) */ class T_DLRD2CTYPE () :ATSTokenType("T_DLRD2CTYPE")
//
// /** // $effmask */ class T_DLREFFMASK () :ATSTokenType("T_DLREFFMASK")
// /** */ class T_DLREFFMASK_ARG (int) // ntm(0), exn(1), ref(2), wrt(3), all(4) :ATSTokenType("T_DLREFFMASK_ARG")
//
// /** // $extern */ class T_DLREXTERN () :ATSTokenType("T_DLREXTERN")
// /** // externally named type */ class T_DLREXTYPE () :ATSTokenType("T_DLREXTYPE")
// /** // $extkind */ class T_DLREXTKIND () :ATSTokenType("T_DLREXTKIND")
// /** // externally named struct */ class T_DLREXTYPE_STRUCT () :ATSTokenType("T_DLREXTYPE_STRUCT")
//
// /** // externally named value */ class T_DLREXTVAL () :ATSTokenType("T_DLREXTVAL")
// /** // externally named fun-call */ class T_DLREXTFCALL () :ATSTokenType("T_DLREXTFCALL")
// /** // externally named method-call */ class T_DLREXTMCALL () :ATSTokenType("T_DLREXTMCALL")
//
// /** // $literal */ class T_DLRLITERAL () :ATSTokenType("T_DLRLITERAL")
//
// /** // $myfilename */ class T_DLRMYFILENAME () :ATSTokenType("T_DLRMYFILENAME")
// /** // $mylocation */ class T_DLRMYLOCATION () :ATSTokenType("T_DLRMYLOCATION")
// /** // $myfunction */ class T_DLRMYFUNCTION () :ATSTokenType("T_DLRMYFUNCTION")
//
// /** */ class T_DLRLST int // $lst and $lst_t and $lst_vt :ATSTokenType("T_DLRLST")
// /** */ class T_DLRREC int // $rec and $rec_t and $rec_vt :ATSTokenType("T_DLRREC")
// /** */ class T_DLRTUP int // $tup and $tup_t and $tup_vt :ATSTokenType("T_DLRTUP")
//
// /** // $break */ class T_DLRBREAK () :ATSTokenType("T_DLRBREAK")
// /** // $continue */ class T_DLRCONTINUE () :ATSTokenType("T_DLRCONTINUE")
//
// /** // $raise // raising exceptions */ class T_DLRRAISE () :ATSTokenType("T_DLRRAISE")
//
// /** // $showtype // for debugging purpose */ class T_DLRSHOWTYPE () :ATSTokenType("T_DLRSHOWTYPE")
//
// /** */ class T_DLRVCOPYENV (int) // $vcopyenv_v(v)/$vcopyenv_vt(vt) :ATSTokenType("T_DLRVCOPYENV")
//
// /** // $tempenver // for adding environvar */ class T_DLRTEMPENVER () :ATSTokenType("T_DLRTEMPENVER")
//
// /** // $solver_assert // assert(d2e_prf) */ class T_DLRSOLASSERT () :ATSTokenType("T_DLRSOLASSERT")
// /** // $solver_verify // verify(s2e_prop) */ class T_DLRSOLVERIFY () :ATSTokenType("T_DLRSOLVERIFY")
//
// /** // #if */ class T_SRPIF () :ATSTokenType("T_SRPIF")
// /** // #ifdef */ class T_SRPIFDEF () :ATSTokenType("T_SRPIFDEF")
// /** // #ifndef */ class T_SRPIFNDEF () :ATSTokenType("T_SRPIFNDEF")
//
// /** // #then */ class T_SRPTHEN () :ATSTokenType("T_SRPTHEN")
//
// /** // #elif */ class T_SRPELIF () :ATSTokenType("T_SRPELIF")
// /** // #elifdef */ class T_SRPELIFDEF () :ATSTokenType("T_SRPELIFDEF")
// /** // #elifndef */ class T_SRPELIFNDEF () :ATSTokenType("T_SRPELIFNDEF")
// /** // #else */ class T_SRPELSE () :ATSTokenType("T_SRPELSE")
//
// /** // #endif */ class T_SRPENDIF () :ATSTokenType("T_SRPENDIF")
//
// /** // #error */ class T_SRPERROR () :ATSTokenType("T_SRPERROR")
// /** // #prerr */ class T_SRPPRERR () :ATSTokenType("T_SRPPRERR")
// /** // #print */ class T_SRPPRINT () :ATSTokenType("T_SRPPRINT")
//
// /** // #assert */ class T_SRPASSERT () :ATSTokenType("T_SRPASSERT")
//
// /** // #undef */ class T_SRPUNDEF () :ATSTokenType("T_SRPUNDEF")
// /** // #define */ class T_SRPDEFINE () :ATSTokenType("T_SRPDEFINE")
//
// /** // #include */ class T_SRPINCLUDE () :ATSTokenType("T_SRPINCLUDE")
//
// /** // #staload */ class T_SRPSTALOAD () :ATSTokenType("T_SRPSTALOAD")
// /** // #dynload */ class T_SRPDYNLOAD () :ATSTokenType("T_SRPDYNLOAD")
//
// /** // #require */ class T_SRPREQUIRE () :ATSTokenType("T_SRPREQUIRE")
//
// /** // #pragma */ class T_SRPPRAGMA () :ATSTokenType("T_SRPPRAGMA")
// /** // #codegen2 */ class T_SRPCODEGEN2 () :ATSTokenType("T_SRPCODEGEN2")
// /** // #codegen3 */ class T_SRPCODEGEN3 () :ATSTokenType("T_SRPCODEGEN3")
//
// /** */ class T_IDENT_alp string // alnum :ATSTokenType("T_IDENT_alp")
// /** */ class T_IDENT_sym string // symbol :ATSTokenType("T_IDENT_sym")
// /** */ class T_IDENT_arr string // A[...] :ATSTokenType("T_IDENT_arr")
// /** */ class T_IDENT_tmp string // A<...> :ATSTokenType("T_IDENT_tmp")
// /** */ class T_IDENT_dlr string // $alnum :ATSTokenType("T_IDENT_dlr")
// /** */ class T_IDENT_srp string // #alnum :ATSTokenType("T_IDENT_srp")
// /** */ class T_IDENT_ext string // alnum! :ATSTokenType("T_IDENT_ext")
//
// /** */ class T_INT (int(*base*), string(*rep*), uint(*suffix*)) :ATSTokenType("T_INT")
//
// /** */ class T_CHAR char (* character *) :ATSTokenType("T_CHAR")
//
// /** */ class T_FLOAT (int(*base*), string(*rep*), uint(*suffix*)) :ATSTokenType("T_FLOAT")
//
// /** */ class {n:int} T_CDATA (arrayref(char, n), size_t(n)) // for binaries :ATSTokenType("{n:int} T_CDATA")
// /** */ class T_STRING (string) :ATSTokenType("T_STRING")
//
// /** // , */ class T_COMMA () :ATSTokenType("T_COMMA")
// /** // ; */ class T_SEMICOLON () :ATSTokenType("T_SEMICOLON")
//
// /** // ( */ class T_LPAREN () :ATSTokenType("T_LPAREN")
// /** // ) */ class T_RPAREN () :ATSTokenType("T_RPAREN")
// /** // [ */ class T_LBRACKET () :ATSTokenType("T_LBRACKET")
// /** // ] */ class T_RBRACKET () :ATSTokenType("T_RBRACKET")
// /** // { */ class T_LBRACE () :ATSTokenType("T_LBRACE")
// /** // } */ class T_RBRACE () :ATSTokenType("T_RBRACE")
//
// /** */ class T_ATLPAREN () // @( :ATSTokenType("T_ATLPAREN")
// /** // '( */ class T_QUOTELPAREN () :ATSTokenType("T_QUOTELPAREN")
// /** // @[ */ class T_ATLBRACKET () :ATSTokenType("T_ATLBRACKET")
// /** // '[ */ class T_QUOTELBRACKET () :ATSTokenType("T_QUOTELBRACKET")
// /** // #[ */ class T_HASHLBRACKET () :ATSTokenType("T_HASHLBRACKET")
// /** // @{ */ class T_ATLBRACE () :ATSTokenType("T_ATLBRACE")
// /** // '{ */ class T_QUOTELBRACE () :ATSTokenType("T_QUOTELBRACE")
//
// /** // `( // macro syntax */ class T_BQUOTELPAREN () :ATSTokenType("T_BQUOTELPAREN")
// /** */ class T_COMMALPAREN () // ,( // macro syntax :ATSTokenType("T_COMMALPAREN")
// /** // %( // macro syntax */ class T_PERCENTLPAREN () :ATSTokenType("T_PERCENTLPAREN")
//
// /** */ class T_EXTCODE (int(*kind*), string) // external code :ATSTokenType("T_EXTCODE")
//
// /** // line comment */ class T_COMMENT_line () :ATSTokenType("T_COMMENT_line")
// /** // block comment */ class T_COMMENT_block () :ATSTokenType("T_COMMENT_block")
// /** // rest-of-file comment */ class T_COMMENT_rest () :ATSTokenType("T_COMMENT_rest")
//
// /** // for errors */ class T_ERR () :ATSTokenType("T_ERR")
//
// /** // end-of-file */ class T_EOF () :ATSTokenType("T_EOF")
}
sealed class CreateSubscriptionResult {
/** asd */
class Success(val subscription: Int) : CreateSubscriptionResult()
class Failure(val errors: List<String>) : CreateSubscriptionResult()
}
| gpl-3.0 | a1ef21218e04ccb1054aac3e6283713a | 32.239754 | 118 | 0.564392 | 2.879127 | false | false | false | false |
dahlstrom-g/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ParentEntityImpl.kt | 3 | 8360 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ParentEntityImpl: ParentEntity, WorkspaceEntityBase() {
companion object {
internal val CHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentEntity::class.java, ChildEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
CHILD_CONNECTION_ID,
)
}
@JvmField var _parentData: String? = null
override val parentData: String
get() = _parentData!!
override val child: ChildEntity
get() = snapshot.extractOneToOneChild(CHILD_CONNECTION_ID, this)!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ParentEntityData?): ModifiableWorkspaceEntityBase<ParentEntity>(), ParentEntity.Builder {
constructor(): this(ParentEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ParentEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isParentDataInitialized()) {
error("Field ParentEntity#parentData should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field ParentEntity#entitySource should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToOneChild<WorkspaceEntityBase>(CHILD_CONNECTION_ID, this) == null) {
error("Field ParentEntity#child should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] == null) {
error("Field ParentEntity#child should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var parentData: String
get() = getEntityData().parentData
set(value) {
checkModificationAllowed()
getEntityData().parentData = value
changedProperty.add("parentData")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var child: ChildEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(CHILD_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)]!! as ChildEntity
} else {
this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)]!! as ChildEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(CHILD_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] = value
}
changedProperty.add("child")
}
override fun getEntityData(): ParentEntityData = result ?: super.getEntityData() as ParentEntityData
override fun getEntityClass(): Class<ParentEntity> = ParentEntity::class.java
}
}
class ParentEntityData : WorkspaceEntityData<ParentEntity>() {
lateinit var parentData: String
fun isParentDataInitialized(): Boolean = ::parentData.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ParentEntity> {
val modifiable = ParentEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ParentEntity {
val entity = ParentEntityImpl()
entity._parentData = parentData
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ParentEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ParentEntityData
if (this.parentData != other.parentData) return false
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ParentEntityData
if (this.parentData != other.parentData) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + parentData.hashCode()
return result
}
} | apache-2.0 | 87f92f4f7975a1e71ff7e47c44719c65 | 38.438679 | 174 | 0.616268 | 5.967166 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/action/GHPRReviewSubmitAction.kt | 5 | 11663 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.action
import com.intellij.collaboration.async.CompletableFutureUtil.errorOnEdt
import com.intellij.collaboration.async.CompletableFutureUtil.successOnEdt
import com.intellij.collaboration.ui.codereview.InlineIconButton
import com.intellij.icons.AllIcons
import com.intellij.ide.ui.laf.darcula.ui.DarculaButtonUI
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.actions.IncrementalFindAction
import com.intellij.openapi.fileTypes.FileTypes
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.ui.ComponentContainer
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.EditorTextField
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.SideBorder
import com.intellij.ui.components.panels.HorizontalBox
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JButtonAction
import com.intellij.util.ui.UIUtil
import icons.CollaborationToolsIcons
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.jetbrains.plugins.github.api.data.GHPullRequestReviewEvent
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestPendingReview
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRReviewDataProvider
import org.jetbrains.plugins.github.ui.component.GHHtmlErrorPanel
import org.jetbrains.plugins.github.ui.component.GHSimpleErrorPanelModel
import java.awt.FlowLayout
import java.awt.Font
import java.awt.event.ActionListener
import javax.swing.*
class GHPRReviewSubmitAction : JButtonAction(StringUtil.ELLIPSIS, GithubBundle.message("pull.request.review.submit.action.description")) {
override fun update(e: AnActionEvent) {
val dataProvider = e.getData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER)
if (dataProvider == null) {
e.presentation.isEnabledAndVisible = false
return
}
val reviewData = dataProvider.reviewData
val details = dataProvider.detailsData.loadedDetails
e.presentation.isVisible = true
val pendingReviewFuture = reviewData.loadPendingReview()
e.presentation.isEnabled = pendingReviewFuture.isDone && details != null
e.presentation.putClientProperty(PROP_PREFIX, getPrefix(e.place))
if (e.presentation.isEnabledAndVisible) {
val review = try {
pendingReviewFuture.getNow(null)
}
catch (e: Exception) {
null
}
val pendingReview = review != null
val comments = review?.comments?.totalCount
e.presentation.text = getText(comments)
e.presentation.putClientProperty(DarculaButtonUI.DEFAULT_STYLE_KEY, pendingReview)
}
}
private fun getPrefix(place: String) = if (place == ActionPlaces.DIFF_TOOLBAR) GithubBundle.message("pull.request.review.submit")
else GithubBundle.message("pull.request.review.submit.review")
@NlsSafe
private fun getText(pendingComments: Int?): String {
val builder = StringBuilder()
if (pendingComments != null) builder.append(" ($pendingComments)")
builder.append(StringUtil.ELLIPSIS)
return builder.toString()
}
override fun actionPerformed(e: AnActionEvent) {
val dataProvider = e.getRequiredData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER)
val details = dataProvider.detailsData.loadedDetails ?: return
val reviewDataProvider = dataProvider.reviewData
val pendingReviewFuture = reviewDataProvider.loadPendingReview()
if (!pendingReviewFuture.isDone) return
val pendingReview = try {
pendingReviewFuture.getNow(null)
}
catch (e: Exception) {
null
}
val parentComponent = e.presentation.getClientProperty(CustomComponentAction.COMPONENT_KEY) ?: return
var cancelRunnable: (() -> Unit)? = null
val cancelActionListener = ActionListener {
cancelRunnable?.invoke()
}
val container = createPopupComponent(reviewDataProvider, reviewDataProvider.submitReviewCommentDocument,
cancelActionListener, pendingReview,
details.viewerDidAuthor)
val popup = JBPopupFactory.getInstance()
.createComponentPopupBuilder(container.component, container.preferredFocusableComponent)
.setFocusable(true)
.setRequestFocus(true)
.setResizable(true)
.createPopup()
cancelRunnable = { popup.cancel() }
popup.showUnderneathOf(parentComponent)
}
private fun createPopupComponent(reviewDataProvider: GHPRReviewDataProvider,
document: Document,
cancelActionListener: ActionListener,
pendingReview: GHPullRequestPendingReview?,
viewerIsAuthor: Boolean): ComponentContainer {
return object : ComponentContainer {
private val editor = createEditor(document)
private val errorModel = GHSimpleErrorPanelModel(GithubBundle.message("pull.request.review.submit.error"))
private val approveButton = if (!viewerIsAuthor) JButton(GithubBundle.message("pull.request.review.submit.approve.button")).apply {
addActionListener(createSubmitButtonActionListener(GHPullRequestReviewEvent.APPROVE))
}
else null
private val rejectButton = if (!viewerIsAuthor) JButton(GithubBundle.message("pull.request.review.submit.request.changes")).apply {
addActionListener(createSubmitButtonActionListener(GHPullRequestReviewEvent.REQUEST_CHANGES))
}
else null
private val commentButton = JButton(GithubBundle.message("pull.request.review.submit.comment.button")).apply {
toolTipText = GithubBundle.message("pull.request.review.submit.comment.description")
addActionListener(createSubmitButtonActionListener(GHPullRequestReviewEvent.COMMENT))
}
private fun createSubmitButtonActionListener(event: GHPullRequestReviewEvent): ActionListener = ActionListener { e ->
editor.isEnabled = false
approveButton?.isEnabled = false
rejectButton?.isEnabled = false
commentButton.isEnabled = false
discardButton?.isEnabled = false
val reviewId = pendingReview?.id
if (reviewId == null) {
reviewDataProvider.createReview(EmptyProgressIndicator(), event, editor.text)
}
else {
reviewDataProvider.submitReview(EmptyProgressIndicator(), reviewId, event, editor.text)
}.successOnEdt {
cancelActionListener.actionPerformed(e)
runWriteAction { document.setText("") }
}.errorOnEdt {
errorModel.error = it
editor.isEnabled = true
approveButton?.isEnabled = true
rejectButton?.isEnabled = true
commentButton.isEnabled = true
discardButton?.isEnabled = true
}
}
private val discardButton: InlineIconButton?
init {
discardButton = pendingReview?.let { review ->
val button = InlineIconButton(icon = CollaborationToolsIcons.Delete, hoveredIcon = CollaborationToolsIcons.DeleteHovered,
tooltip = GithubBundle.message("pull.request.discard.pending.comments"))
button.actionListener = ActionListener {
if (MessageDialogBuilder.yesNo(GithubBundle.message("pull.request.discard.pending.comments.dialog.title"),
GithubBundle.message("pull.request.discard.pending.comments.dialog.msg")).ask(button)) {
reviewDataProvider.deleteReview(EmptyProgressIndicator(), review.id)
}
}
button
}
}
override fun getComponent(): JComponent {
val titleLabel = JLabel(GithubBundle.message("pull.request.review.submit.review")).apply {
font = font.deriveFont(font.style or Font.BOLD)
}
val titlePanel = HorizontalBox().apply {
border = JBUI.Borders.empty(4, 4, 4, 4)
add(titleLabel)
if (pendingReview != null) {
val commentsCount = pendingReview.comments.totalCount!!
add(Box.createRigidArea(JBDimension(5, 0)))
add(JLabel(GithubBundle.message("pull.request.review.pending.comments.count", commentsCount))).apply {
foreground = UIUtil.getContextHelpForeground()
}
}
add(Box.createHorizontalGlue())
discardButton?.let { add(it) }
add(InlineIconButton(AllIcons.Actions.Close, AllIcons.Actions.CloseHovered).apply {
actionListener = cancelActionListener
})
}
val errorPanel = GHHtmlErrorPanel.create(errorModel, SwingConstants.LEFT).apply {
border = JBUI.Borders.empty(4)
}
val buttonsPanel = JPanel(FlowLayout(FlowLayout.LEFT, 0, 0)).apply {
border = JBUI.Borders.empty(4)
if (!viewerIsAuthor) add(approveButton)
if (!viewerIsAuthor) add(rejectButton)
add(commentButton)
}
return JPanel(MigLayout(LC().gridGap("0", "0")
.insets("0", "0", "0", "0")
.fill().flowY().noGrid())).apply {
isOpaque = false
preferredSize = JBDimension(450, 165)
add(titlePanel, CC().growX())
add(editor, CC().growX().growY()
.gap("0", "0", "0", "0"))
add(errorPanel, CC().minHeight("${JBUIScale.scale(32)}").growY().growPrioY(0).hideMode(3)
.gap("0", "0", "0", "0"))
add(buttonsPanel, CC().alignX("right"))
}
}
private fun createEditor(document: Document) = EditorTextField(document, null, FileTypes.PLAIN_TEXT).apply {
setOneLineMode(false)
putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
setPlaceholder(GithubBundle.message("pull.request.review.comment.empty.text"))
addSettingsProvider {
it.settings.isUseSoftWraps = true
it.setVerticalScrollbarVisible(true)
it.scrollPane.border = IdeBorderFactory.createBorder(SideBorder.TOP or SideBorder.BOTTOM)
it.scrollPane.viewportBorder = JBUI.Borders.emptyLeft(4)
it.putUserData(IncrementalFindAction.SEARCH_DISABLED, true)
}
}
override fun getPreferredFocusableComponent() = editor
override fun dispose() {}
}
}
override fun updateButtonFromPresentation(button: JButton, presentation: Presentation) {
super.updateButtonFromPresentation(button, presentation)
val prefix = presentation.getClientProperty(PROP_PREFIX) as? String ?: GithubBundle.message("pull.request.review.submit.review")
button.text = prefix + presentation.text
UIUtil.putClientProperty(button, DarculaButtonUI.DEFAULT_STYLE_KEY, presentation.getClientProperty(DarculaButtonUI.DEFAULT_STYLE_KEY))
}
companion object {
private const val PROP_PREFIX = "PREFIX"
}
} | apache-2.0 | 4f4fda1b7494c25a06b1f4a376fc0e4b | 42.360595 | 140 | 0.704621 | 4.979932 | false | false | false | false |
dahlstrom-g/intellij-community | platform/lang-impl/src/com/intellij/codeInspection/ui/actions/ExportToXMLAction.kt | 8 | 3713 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInspection.ui.actions
import com.intellij.codeInspection.InspectionsBundle
import com.intellij.codeInspection.InspectionsResultUtil
import com.intellij.codeInspection.ex.GlobalInspectionContextImpl
import com.intellij.codeInspection.ex.InspectionProfileImpl
import com.intellij.codeInspection.ex.InspectionToolWrapper
import com.intellij.codeInspection.ex.ScopeToolState
import com.intellij.codeInspection.ui.InspectionNode
import com.intellij.codeInspection.ui.InspectionTree
import com.intellij.codeInspection.ui.InspectionTreeModel
import com.intellij.icons.AllIcons
import com.intellij.openapi.project.Project
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.MultiMap
import java.io.IOException
import java.nio.file.Path
import java.util.function.Supplier
@Suppress("ComponentNotRegistered")
class ExportToXMLAction : InspectionResultsExportActionProvider(Supplier { "XML" },
InspectionsBundle.messagePointer("inspection.action.export.xml.description"),
AllIcons.FileTypes.Xml) {
override val progressTitle: String = InspectionsBundle.message("inspection.generating.xml.progress.title")
override fun writeResults(tree: InspectionTree,
profile: InspectionProfileImpl,
globalInspectionContext: GlobalInspectionContextImpl,
project: Project,
outputPath: Path) {
dumpToXml(profile, tree, project, globalInspectionContext, outputPath)
}
companion object {
fun dumpToXml(profile: InspectionProfileImpl, tree: InspectionTree, project: Project, globalInspectionContext: GlobalInspectionContextImpl, outputPath: Path) {
val singleTool = profile.singleTool
val shortName2Wrapper = MultiMap<String, InspectionToolWrapper<*, *>>()
if (singleTool != null) {
shortName2Wrapper.put(singleTool, getWrappersForAllScopes(singleTool, globalInspectionContext))
}
else {
val model: InspectionTreeModel = tree.inspectionTreeModel
model
.traverse(model.root)
.filter(InspectionNode::class.java)
.filter { !it.isExcluded }
.map { obj: InspectionNode -> obj.toolWrapper }
.forEach { w: InspectionToolWrapper<*, *> -> shortName2Wrapper.putValue(w.shortName, w) }
}
for (entry in shortName2Wrapper.entrySet()) {
val shortName: String = entry.key
val wrappers: Collection<InspectionToolWrapper<*, *>> = entry.value
InspectionsResultUtil.writeInspectionResult(project, shortName, wrappers, outputPath) {
wrapper: InspectionToolWrapper<*, *> -> globalInspectionContext.getPresentation(wrapper)
}
}
val descriptionsFile: Path = outputPath.resolve(InspectionsResultUtil.DESCRIPTIONS + InspectionsResultUtil.XML_EXTENSION)
try {
InspectionsResultUtil.describeInspections(descriptionsFile, profile.name, profile)
}
catch (e: javax.xml.stream.XMLStreamException) {
throw IOException(e)
}
}
private fun getWrappersForAllScopes(shortName: String,
context: GlobalInspectionContextImpl): Collection<InspectionToolWrapper<*, *>> {
return when (val tools = context.tools[shortName]) {
null -> emptyList() //dummy entry points tool
else -> ContainerUtil.map(tools.tools) { obj: ScopeToolState -> obj.tool }
}
}
}
} | apache-2.0 | cb367afcfa9734ca2c7b7693df6150fa | 47.868421 | 163 | 0.70105 | 5.229577 | false | false | false | false |
Virtlink/aesi | paplj/src/main/kotlin/com/virtlink/paplj/syntaxcoloring/AntlrSyntaxColorizer.kt | 1 | 2788 | package com.virtlink.paplj.syntaxcoloring
import com.google.inject.Inject
import com.virtlink.editorservices.*
import com.virtlink.editorservices.resources.IResourceManager
import com.virtlink.editorservices.syntaxcoloring.*
import com.virtlink.logging.logger
import com.virtlink.paplj.syntax.PapljAntlrLexer
import org.antlr.v4.runtime.ANTLRInputStream
import java.net.URI
class AntlrSyntaxColorizer @Inject constructor(
private val resourceManager: IResourceManager)
: ISyntaxColoringService {
@Suppress("PrivatePropertyName")
private val LOG by logger()
override fun configure(configuration: ISyntaxColoringConfiguration) {
// Nothing to do.
}
override fun getSyntaxColoringInfo(document: URI, span: Span, cancellationToken: ICancellationToken?): ISyntaxColoringInfo? {
val tokens = mutableListOf<IToken>()
val content = this.resourceManager.getContent(document)
if (content == null) {
LOG.warn("$document: Could not get content.")
return SyntaxColoringInfo(emptyList())
}
val input = ANTLRInputStream(content.text)
val lexer = PapljAntlrLexer(input)
var token = lexer.nextToken()
while (token.type != org.antlr.v4.runtime.Token.EOF) {
val scope = getTokenScope(token)
val startOffset = token.startIndex
val endOffset = token.stopIndex + 1
tokens.add(Token(Span(startOffset.toLong(), endOffset.toLong()), ScopeNames(scope)))
token = lexer.nextToken()
}
return SyntaxColoringInfo(tokens)
}
private val keywords = arrayOf("PROGRAM", "RUN", "IMPORT", "CLASS", "EXTENDS", "IF", "ELSE", "LET", "IN",
"AS", "TRUE", "FALSE", "THIS", "NULL", "NEW")
private val operators = arrayOf("EQ", "NEQ", "LTE", "GTE", "LT", "GT",
"OR", "AND", "ASSIGN", "PLUS", "MIN", "MUL", "DIV", "NOT")
private fun getTokenScope(token: org.antlr.v4.runtime.Token): String {
val tokenName = if (token.type > 0 && token.type <= PapljAntlrLexer.ruleNames.size) PapljAntlrLexer.ruleNames[token.type - 1] else null
return when (tokenName) {
in keywords -> "keyword"
in operators -> "keyword.operator"
"LBRACE", "RBRACE" -> "meta.braces"
"LPAREN", "RPAREN" -> "meta.parens"
"DOT", "DOTSTAR" -> "punctuation.accessor"
"COMMA" -> "punctuation.separator"
"SEMICOLON" -> "punctuation.terminator"
"ID" -> "entity.name" // Not really correct
"INT" -> "constant.numeric"
"COMMENT" -> "comment.block"
"LINE_COMMENT" -> "comment.line"
"WS" -> "text.whitespace"
else -> "invalid.illegal"
}
}
} | apache-2.0 | fe4cc2407e91ba2369616c387b78c877 | 38.28169 | 143 | 0.628407 | 4.186186 | false | false | false | false |
google/intellij-community | java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/inference/preContracts.kt | 8 | 8615 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.dataFlow.inference
import com.intellij.codeInsight.Nullability
import com.intellij.codeInsight.NullableNotNullManager
import com.intellij.codeInspection.dataFlow.ContractReturnValue
import com.intellij.codeInspection.dataFlow.JavaMethodContractUtil
import com.intellij.codeInspection.dataFlow.NullabilityUtil
import com.intellij.codeInspection.dataFlow.StandardMethodContract
import com.intellij.codeInspection.dataFlow.StandardMethodContract.ValueConstraint.*
import com.intellij.codeInspection.dataFlow.inference.ContractInferenceInterpreter.withConstraint
import com.intellij.codeInspection.dataFlow.java.inst.MethodCallInstruction
import com.intellij.psi.*
import com.intellij.psi.util.PsiUtil
import com.siyeh.ig.psiutils.SideEffectChecker
/**
* @author peter
*/
interface PreContract {
fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<StandardMethodContract>
fun negate(): PreContract? = NegatingContract(
this)
}
internal data class KnownContract(val contract: StandardMethodContract) : PreContract {
override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock) = listOf(contract)
override fun negate() = negateContract(contract)?.let(::KnownContract)
}
internal data class DelegationContract(internal val expression: ExpressionRange, internal val negated: Boolean) : PreContract {
override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<StandardMethodContract> {
val call : PsiMethodCallExpression = expression.restoreExpression(body())
val result = call.resolveMethodGenerics()
val targetMethod = result.element as PsiMethod? ?: return emptyList()
if (targetMethod == method) return emptyList()
val parameters = targetMethod.parameterList.parameters
val arguments = call.argumentList.expressions
val qualifier = call.methodExpression.qualifierExpression
val varArgCall = MethodCallInstruction.isVarArgCall(targetMethod, result.substitutor, arguments, parameters)
val methodContracts = StandardMethodContract.toNonIntersectingStandardContracts(JavaMethodContractUtil.getMethodContracts(targetMethod))
?: return emptyList()
val fromDelegate = methodContracts.mapNotNull { dc ->
convertDelegatedMethodContract(method, parameters, qualifier, arguments, varArgCall, dc)
}.toMutableList()
while (fromDelegate.isNotEmpty() && fromDelegate[fromDelegate.size - 1].returnValue == ContractReturnValue.returnAny()) {
fromDelegate.removeAt(fromDelegate.size - 1)
}
if (NullableNotNullManager.isNotNull(targetMethod)) {
fromDelegate += listOf(
StandardMethodContract(emptyConstraints(method), ContractReturnValue.returnNotNull()))
}
return StandardMethodContract.toNonIntersectingStandardContracts(fromDelegate) ?: emptyList()
}
private fun convertDelegatedMethodContract(callerMethod: PsiMethod,
targetParameters: Array<PsiParameter>,
qualifier: PsiExpression?,
callArguments: Array<PsiExpression>,
varArgCall: Boolean,
targetContract: StandardMethodContract): StandardMethodContract? {
var answer: Array<StandardMethodContract.ValueConstraint>? = emptyConstraints(callerMethod)
for (i in 0 until targetContract.parameterCount) {
if (i >= callArguments.size) return null
val argConstraint = targetContract.getParameterConstraint(i)
if (argConstraint != ANY_VALUE) {
if (varArgCall && i >= targetParameters.size - 1) {
if (argConstraint == NULL_VALUE) {
return null
}
break
}
val argument = PsiUtil.skipParenthesizedExprDown(callArguments[i]) ?: return null
val paramIndex = resolveParameter(callerMethod, argument)
if (paramIndex >= 0) {
answer = withConstraint(answer, paramIndex, argConstraint) ?: return null
}
else if (argConstraint != getLiteralConstraint(argument)) {
return null
}
}
}
var returnValue = targetContract.returnValue
returnValue = when (returnValue) {
is ContractReturnValue.BooleanReturnValue -> {
if (negated) returnValue.negate() else returnValue
}
is ContractReturnValue.ParameterReturnValue -> {
mapReturnValue(callerMethod, callArguments[returnValue.parameterNumber])
}
ContractReturnValue.returnThis() -> {
mapReturnValue(callerMethod, qualifier)
}
else -> returnValue
}
return answer?.let { StandardMethodContract(it, returnValue) }
}
private fun mapReturnValue(callerMethod: PsiMethod, argument: PsiExpression?): ContractReturnValue? {
val stripped = PsiUtil.skipParenthesizedExprDown(argument)
val paramIndex = resolveParameter(callerMethod, stripped)
return when {
paramIndex >= 0 -> ContractReturnValue.returnParameter(paramIndex)
stripped is PsiLiteralExpression -> when (stripped.value) {
null -> ContractReturnValue.returnNull()
true -> ContractReturnValue.returnTrue()
false -> ContractReturnValue.returnFalse()
else -> ContractReturnValue.returnNotNull()
}
stripped is PsiThisExpression && stripped.qualifier == null -> ContractReturnValue.returnThis()
stripped is PsiNewExpression -> ContractReturnValue.returnNew()
NullabilityUtil.getExpressionNullability(stripped) == Nullability.NOT_NULL -> ContractReturnValue.returnNotNull()
else -> ContractReturnValue.returnAny()
}
}
private fun emptyConstraints(method: PsiMethod) = StandardMethodContract.createConstraintArray(
method.parameterList.parametersCount)
private fun returnNotNull(mc: StandardMethodContract): StandardMethodContract {
return if (mc.returnValue.isFail) mc else mc.withReturnValue(ContractReturnValue.returnNotNull())
}
private fun getLiteralConstraint(argument: PsiExpression) = when (argument) {
is PsiLiteralExpression -> ContractInferenceInterpreter.getLiteralConstraint(
argument.getFirstChild().node.elementType)
is PsiNewExpression, is PsiPolyadicExpression, is PsiFunctionalExpression -> NOT_NULL_VALUE
else -> null
}
private fun resolveParameter(method: PsiMethod, expr: PsiExpression?): Int {
val target = if (expr is PsiReferenceExpression && !expr.isQualified) expr.resolve() else null
return if (target is PsiParameter && target.parent === method.parameterList) method.parameterList.getParameterIndex(target) else -1
}
}
internal data class SideEffectFilter(internal val expressionsToCheck: List<ExpressionRange>, internal val contracts: List<PreContract>) : PreContract {
override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<StandardMethodContract> {
if (expressionsToCheck.any { d -> mayHaveSideEffects(body(), d) }) {
return emptyList()
}
return contracts.flatMap { c -> c.toContracts(method, body) }
}
private fun mayHaveSideEffects(body: PsiCodeBlock, range: ExpressionRange) =
range.restoreExpression<PsiExpression>(body).let { SideEffectChecker.mayHaveSideEffects(it) }
}
internal data class NegatingContract(internal val negated: PreContract) : PreContract {
override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock) = negated.toContracts(method, body).mapNotNull(::negateContract)
}
private fun negateContract(c: StandardMethodContract): StandardMethodContract? {
val ret = c.returnValue
return if (ret is ContractReturnValue.BooleanReturnValue) c.withReturnValue(ret.negate())
else null
}
@Suppress("EqualsOrHashCode")
internal data class MethodCallContract(internal val call: ExpressionRange, internal val states: List<List<StandardMethodContract.ValueConstraint>>) : PreContract {
override fun hashCode() = call.hashCode() * 31 + states.flatten().map { it.ordinal }.hashCode()
override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<StandardMethodContract> {
val target = call.restoreExpression<PsiMethodCallExpression>(body()).resolveMethod()
if (target != null && target != method && NullableNotNullManager.isNotNull(target)) {
return ContractInferenceInterpreter.toContracts(states.map { it.toTypedArray() }, ContractReturnValue.returnNotNull())
}
return emptyList()
}
}
| apache-2.0 | 7273a561aa100d7699c7b10dbab69fb8 | 47.948864 | 163 | 0.734997 | 5.459442 | false | false | false | false |
google/intellij-community | platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.kt | 1 | 24117 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.ui
import com.intellij.diagnostic.LoadingState
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponentWithModificationTracker
import com.intellij.openapi.components.SettingsCategory
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.options.advanced.AdvancedSettings
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.registry.Registry
import com.intellij.serviceContainer.NonInjectable
import com.intellij.ui.JreHiDpiUtil
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ComponentTreeEventDispatcher
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.UIUtil
import com.intellij.util.xmlb.annotations.Transient
import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.RenderingHints
import javax.swing.JComponent
import javax.swing.SwingConstants
private val LOG = logger<UISettings>()
@State(name = "UISettings", storages = [(Storage("ui.lnf.xml"))], useLoadedStateAsExisting = false, category = SettingsCategory.UI)
class UISettings @NonInjectable constructor(private val notRoamableOptions: NotRoamableUiSettings) : PersistentStateComponentWithModificationTracker<UISettingsState> {
constructor() : this(ApplicationManager.getApplication().getService(NotRoamableUiSettings::class.java))
private var state = UISettingsState()
private val myTreeDispatcher = ComponentTreeEventDispatcher.create(UISettingsListener::class.java)
var ideAAType: AntialiasingType
get() = notRoamableOptions.state.ideAAType
set(value) {
notRoamableOptions.state.ideAAType = value
}
var editorAAType: AntialiasingType
get() = notRoamableOptions.state.editorAAType
set(value) {
notRoamableOptions.state.editorAAType = value
}
val allowMergeButtons: Boolean
get() = Registry.`is`("ide.allow.merge.buttons", true)
val animateWindows: Boolean
get() = Registry.`is`("ide.animate.toolwindows", false)
var colorBlindness: ColorBlindness?
get() = state.colorBlindness
set(value) {
state.colorBlindness = value
}
var useContrastScrollbars: Boolean
get() = state.useContrastScrollBars
set(value) {
state.useContrastScrollBars = value
}
var hideToolStripes: Boolean
get() = state.hideToolStripes
set(value) {
state.hideToolStripes = value
}
val hideNavigationOnFocusLoss: Boolean
get() = Registry.`is`("ide.hide.navigation.on.focus.loss", false)
var reuseNotModifiedTabs: Boolean
get() = state.reuseNotModifiedTabs
set(value) {
state.reuseNotModifiedTabs = value
}
var openTabsInMainWindow: Boolean
get() = state.openTabsInMainWindow
set(value) {
state.openTabsInMainWindow = value
}
var openInPreviewTabIfPossible: Boolean
get() = state.openInPreviewTabIfPossible
set(value) {
state.openInPreviewTabIfPossible = value
}
var disableMnemonics: Boolean
get() = state.disableMnemonics
set(value) {
state.disableMnemonics = value
}
var disableMnemonicsInControls: Boolean
get() = state.disableMnemonicsInControls
set(value) {
state.disableMnemonicsInControls = value
}
var dndWithPressedAltOnly: Boolean
get() = state.dndWithPressedAltOnly
set(value) {
state.dndWithPressedAltOnly = value
}
var separateMainMenu: Boolean
get() = (SystemInfoRt.isWindows || SystemInfoRt.isXWindow) && state.separateMainMenu
set(value) {
state.separateMainMenu = value
state.showMainToolbar = value
}
var useSmallLabelsOnTabs: Boolean
get() = state.useSmallLabelsOnTabs
set(value) {
state.useSmallLabelsOnTabs = value
}
var smoothScrolling: Boolean
get() = state.smoothScrolling
set(value) {
state.smoothScrolling = value
}
val animatedScrolling: Boolean
get() = state.animatedScrolling
val animatedScrollingDuration: Int
get() = state.animatedScrollingDuration
val animatedScrollingCurvePoints: Int
get() = state.animatedScrollingCurvePoints
val closeTabButtonOnTheRight: Boolean
get() = state.closeTabButtonOnTheRight
val cycleScrolling: Boolean
get() = AdvancedSettings.getBoolean("ide.cycle.scrolling")
val scrollTabLayoutInEditor: Boolean
get() = state.scrollTabLayoutInEditor
var showToolWindowsNumbers: Boolean
get() = state.showToolWindowsNumbers
set(value) {
state.showToolWindowsNumbers = value
}
var showEditorToolTip: Boolean
get() = state.showEditorToolTip
set(value) {
state.showEditorToolTip = value
}
var showNavigationBar: Boolean
get() = state.showNavigationBar
set(value) {
state.showNavigationBar = value
}
var navBarLocation : NavBarLocation
get() = state.navigationBarLocation
set(value) {
state.navigationBarLocation = value
}
val showNavigationBarInBottom : Boolean
get() = showNavigationBar && navBarLocation == NavBarLocation.BOTTOM
var showMembersInNavigationBar: Boolean
get() = state.showMembersInNavigationBar
set(value) {
state.showMembersInNavigationBar = value
}
var showStatusBar: Boolean
get() = state.showStatusBar
set(value) {
state.showStatusBar = value
}
var showMainMenu: Boolean
get() = state.showMainMenu
set(value) {
state.showMainMenu = value
}
val showIconInQuickNavigation: Boolean
get() = Registry.`is`("ide.show.icons.in.quick.navigation", false)
var showTreeIndentGuides: Boolean
get() = state.showTreeIndentGuides
set(value) {
state.showTreeIndentGuides = value
}
var compactTreeIndents: Boolean
get() = state.compactTreeIndents
set(value) {
state.compactTreeIndents = value
}
var showMainToolbar: Boolean
get() = state.showMainToolbar
set(value) {
state.showMainToolbar = value
val toolbarSettingsState = ToolbarSettings.getInstance().state!!
toolbarSettingsState.showNewMainToolbar = !value && toolbarSettingsState.showNewMainToolbar
}
var showIconsInMenus: Boolean
get() = state.showIconsInMenus
set(value) {
state.showIconsInMenus = value
}
var sortLookupElementsLexicographically: Boolean
get() = state.sortLookupElementsLexicographically
set(value) {
state.sortLookupElementsLexicographically = value
}
val hideTabsIfNeeded: Boolean
get() = state.hideTabsIfNeeded || editorTabPlacement == SwingConstants.LEFT || editorTabPlacement == SwingConstants.RIGHT
var showFileIconInTabs: Boolean
get() = state.showFileIconInTabs
set(value) {
state.showFileIconInTabs = value
}
var hideKnownExtensionInTabs: Boolean
get() = state.hideKnownExtensionInTabs
set(value) {
state.hideKnownExtensionInTabs = value
}
var leftHorizontalSplit: Boolean
get() = state.leftHorizontalSplit
set(value) {
state.leftHorizontalSplit = value
}
var rightHorizontalSplit: Boolean
get() = state.rightHorizontalSplit
set(value) {
state.rightHorizontalSplit = value
}
var wideScreenSupport: Boolean
get() = state.wideScreenSupport
set(value) {
state.wideScreenSupport = value
}
var sortBookmarks: Boolean
get() = state.sortBookmarks
set(value) {
state.sortBookmarks = value
}
val showCloseButton: Boolean
get() = state.showCloseButton
var presentationMode: Boolean
get() = state.presentationMode
set(value) {
state.presentationMode = value
}
var presentationModeFontSize: Int
get() = state.presentationModeFontSize
set(value) {
state.presentationModeFontSize = value
}
var editorTabPlacement: Int
get() = state.editorTabPlacement
set(value) {
state.editorTabPlacement = value
}
var editorTabLimit: Int
get() = state.editorTabLimit
set(value) {
state.editorTabLimit = value
}
var recentFilesLimit: Int
get() = state.recentFilesLimit
set(value) {
state.recentFilesLimit = value
}
var recentLocationsLimit: Int
get() = state.recentLocationsLimit
set(value) {
state.recentLocationsLimit = value
}
var maxLookupWidth: Int
get() = state.maxLookupWidth
set(value) {
state.maxLookupWidth = value
}
var maxLookupListHeight: Int
get() = state.maxLookupListHeight
set(value) {
state.maxLookupListHeight = value
}
var overrideLafFonts: Boolean
get() = state.overrideLafFonts
set(value) {
state.overrideLafFonts = value
}
var fontFace: @NlsSafe String?
get() = notRoamableOptions.state.fontFace
set(value) {
notRoamableOptions.state.fontFace = value
}
var fontSize: Int
get() = (notRoamableOptions.state.fontSize + 0.5).toInt()
set(value) {
notRoamableOptions.state.fontSize = value.toFloat()
}
var fontSize2D: Float
get() = notRoamableOptions.state.fontSize
set(value) {
notRoamableOptions.state.fontSize = value
}
var fontScale: Float
get() = notRoamableOptions.state.fontScale
set(value) {
notRoamableOptions.state.fontScale = value
}
var showDirectoryForNonUniqueFilenames: Boolean
get() = state.showDirectoryForNonUniqueFilenames
set(value) {
state.showDirectoryForNonUniqueFilenames = value
}
var pinFindInPath: Boolean
get() = state.pinFindInPath
set(value) {
state.pinFindInPath = value
}
var activeRightEditorOnClose: Boolean
get() = state.activeRightEditorOnClose
set(value) {
state.activeRightEditorOnClose = value
}
var showTabsTooltips: Boolean
get() = state.showTabsTooltips
set(value) {
state.showTabsTooltips = value
}
var markModifiedTabsWithAsterisk: Boolean
get() = state.markModifiedTabsWithAsterisk
set(value) {
state.markModifiedTabsWithAsterisk = value
}
var overrideConsoleCycleBufferSize: Boolean
get() = state.overrideConsoleCycleBufferSize
set(value) {
state.overrideConsoleCycleBufferSize = value
}
var consoleCycleBufferSizeKb: Int
get() = state.consoleCycleBufferSizeKb
set(value) {
state.consoleCycleBufferSizeKb = value
}
var consoleCommandHistoryLimit: Int
get() = state.consoleCommandHistoryLimit
set(value) {
state.consoleCommandHistoryLimit = value
}
var sortTabsAlphabetically: Boolean
get() = state.sortTabsAlphabetically
set(value) {
state.sortTabsAlphabetically = value
}
var alwaysKeepTabsAlphabeticallySorted: Boolean
get() = state.alwaysKeepTabsAlphabeticallySorted
set(value) {
state.alwaysKeepTabsAlphabeticallySorted = value
}
var openTabsAtTheEnd: Boolean
get() = state.openTabsAtTheEnd
set(value) {
state.openTabsAtTheEnd = value
}
var showInplaceComments: Boolean
get() = state.showInplaceComments
set(value) {
state.showInplaceComments = value
}
val showInplaceCommentsInternal: Boolean
get() = showInplaceComments && ApplicationManager.getApplication()?.isInternal ?: false
var fullPathsInWindowHeader: Boolean
get() = state.fullPathsInWindowHeader
set(value) {
state.fullPathsInWindowHeader = value
}
var mergeMainMenuWithWindowTitle: Boolean
get() = state.mergeMainMenuWithWindowTitle
set(value) {
state.mergeMainMenuWithWindowTitle = value
}
var showVisualFormattingLayer: Boolean
get() = state.showVisualFormattingLayer
set(value) {
state.showVisualFormattingLayer = value
}
companion object {
init {
if (JBUIScale.SCALE_VERBOSE) {
LOG.info(String.format("defFontSize=%.1f, defFontScale=%.2f", defFontSize, defFontScale))
}
}
const val ANIMATION_DURATION = 300 // Milliseconds
/** Not tabbed pane. */
const val TABS_NONE = 0
@Volatile
private var cachedInstance: UISettings? = null
@JvmStatic
fun getInstance(): UISettings {
var result = cachedInstance
if (result == null) {
LoadingState.CONFIGURATION_STORE_INITIALIZED.checkOccurred()
result = ApplicationManager.getApplication().getService(UISettings::class.java)!!
cachedInstance = result
}
return result
}
@JvmStatic
val instanceOrNull: UISettings?
get() {
val result = cachedInstance
if (result == null && LoadingState.CONFIGURATION_STORE_INITIALIZED.isOccurred) {
return getInstance()
}
return result
}
/**
* Use this method if you are not sure whether the application is initialized.
* @return persisted UISettings instance or default values.
*/
@JvmStatic
val shadowInstance: UISettings
get() = instanceOrNull ?: UISettings(NotRoamableUiSettings())
private fun calcFractionalMetricsHint(registryKey: String, defaultValue: Boolean): Any {
val hint: Boolean
if (LoadingState.APP_STARTED.isOccurred) {
val registryValue = Registry.get(registryKey)
if (registryValue.isMultiValue) {
val option = registryValue.selectedOption
if (option.equals("Enabled")) hint = true
else if (option.equals("Disabled")) hint = false
else hint = defaultValue
}
else {
hint = if (registryValue.isBoolean && registryValue.asBoolean()) true else defaultValue
}
}
else hint = defaultValue
return if (hint) RenderingHints.VALUE_FRACTIONALMETRICS_ON else RenderingHints.VALUE_FRACTIONALMETRICS_OFF
}
fun getPreferredFractionalMetricsValue(): Any {
val enableByDefault = SystemInfo.isMacOSCatalina || (FontSubpixelResolution.ENABLED
&& AntialiasingType.getKeyForCurrentScope(false) ==
RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
return calcFractionalMetricsHint("ide.text.fractional.metrics", enableByDefault)
}
@JvmStatic
val editorFractionalMetricsHint: Any
get() {
val enableByDefault = FontSubpixelResolution.ENABLED
&& AntialiasingType.getKeyForCurrentScope(true) == RenderingHints.VALUE_TEXT_ANTIALIAS_ON
return calcFractionalMetricsHint("editor.text.fractional.metrics", enableByDefault)
}
@JvmStatic
fun setupFractionalMetrics(g2d: Graphics2D) {
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, getPreferredFractionalMetricsValue())
}
/**
* This method must not be used for set up antialiasing for editor components. To make sure antialiasing settings are taken into account
* when preferred size of component is calculated, [.setupComponentAntialiasing] method should be called from
* `updateUI()` or `setUI()` method of component.
*/
@JvmStatic
fun setupAntialiasing(g: Graphics) {
g as Graphics2D
g.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST, UIUtil.getLcdContrastValue())
if (LoadingState.CONFIGURATION_STORE_INITIALIZED.isOccurred && ApplicationManager.getApplication() == null) {
// cannot use services while Application has not been loaded yet, so let's apply the default hints
GraphicsUtil.applyRenderingHints(g)
return
}
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AntialiasingType.getKeyForCurrentScope(false))
setupFractionalMetrics(g)
}
@JvmStatic
fun setupComponentAntialiasing(component: JComponent) {
GraphicsUtil.setAntialiasingType(component, AntialiasingType.getAAHintForSwingComponent())
}
@JvmStatic
fun setupEditorAntialiasing(component: JComponent) {
GraphicsUtil.setAntialiasingType(component, getInstance().editorAAType.textInfo)
}
/**
* Returns the default font scale, which depends on the HiDPI mode (see [com.intellij.ui.scale.ScaleType]).
* <p>
* The font is represented:
* - in relative (dpi-independent) points in the JRE-managed HiDPI mode, so the method returns 1.0f
* - in absolute (dpi-dependent) points in the IDE-managed HiDPI mode, so the method returns the default screen scale
*
* @return the system font scale
*/
@JvmStatic
val defFontScale: Float
get() = when {
JreHiDpiUtil.isJreHiDPIEnabled() -> 1f
else -> JBUIScale.sysScale()
}
/**
* Returns the default font size scaled by #defFontScale
*
* @return the default scaled font size
*/
@JvmStatic
val defFontSize: Float
get() = UISettingsState.defFontSize
@Deprecated("Use {@link #restoreFontSize(Float, Float?)} instead")
@JvmStatic
fun restoreFontSize(readSize: Int, readScale: Float?): Int {
return restoreFontSize(readSize.toFloat(), readScale).toInt()
}
@JvmStatic
fun restoreFontSize(readSize: Float, readScale: Float?): Float {
var size = readSize
if (readScale == null || readScale <= 0) {
if (JBUIScale.SCALE_VERBOSE) LOG.info("Reset font to default")
// Reset font to default on switch from IDE-managed HiDPI to JRE-managed HiDPI. Doesn't affect OSX.
if (!SystemInfoRt.isMac && JreHiDpiUtil.isJreHiDPIEnabled()) {
size = UISettingsState.defFontSize
}
}
else if (readScale != defFontScale) {
size = (readSize / readScale) * defFontScale
}
if (JBUIScale.SCALE_VERBOSE) LOG.info("Loaded: fontSize=$readSize, fontScale=$readScale; restored: fontSize=$size, fontScale=$defFontScale")
return size
}
const val MERGE_MAIN_MENU_WITH_WINDOW_TITLE_PROPERTY = "ide.win.frame.decoration"
@JvmStatic
val mergeMainMenuWithWindowTitleOverrideValue = System.getProperty(MERGE_MAIN_MENU_WITH_WINDOW_TITLE_PROPERTY)?.toBoolean()
val isMergeMainMenuWithWindowTitleOverridden = mergeMainMenuWithWindowTitleOverrideValue != null
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Please use {@link UISettingsListener#TOPIC}")
@ScheduledForRemoval
fun addUISettingsListener(listener: UISettingsListener, parentDisposable: Disposable) {
ApplicationManager.getApplication().messageBus.connect(parentDisposable).subscribe(UISettingsListener.TOPIC, listener)
}
/**
* Notifies all registered listeners that UI settings has been changed.
*/
fun fireUISettingsChanged() {
updateDeprecatedProperties()
// todo remove when all old properties will be converted
state._incrementModificationCount()
IconLoader.setFilter(ColorBlindnessSupport.get(state.colorBlindness)?.filter)
// if this is the main UISettings instance (and not on first call to getInstance) push event to bus and to all current components
if (this === cachedInstance) {
myTreeDispatcher.multicaster.uiSettingsChanged(this)
ApplicationManager.getApplication().messageBus.syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(this)
}
}
@Suppress("DEPRECATION")
private fun updateDeprecatedProperties() {
HIDE_TOOL_STRIPES = hideToolStripes
SHOW_MAIN_TOOLBAR = showMainToolbar
SHOW_CLOSE_BUTTON = showCloseButton
PRESENTATION_MODE = presentationMode
OVERRIDE_NONIDEA_LAF_FONTS = overrideLafFonts
PRESENTATION_MODE_FONT_SIZE = presentationModeFontSize
CONSOLE_COMMAND_HISTORY_LIMIT = state.consoleCommandHistoryLimit
FONT_SIZE = fontSize
FONT_FACE = fontFace
EDITOR_TAB_LIMIT = editorTabLimit
}
override fun getState() = state
override fun loadState(state: UISettingsState) {
this.state = state
updateDeprecatedProperties()
migrateOldSettings()
if (migrateOldFontSettings()) {
notRoamableOptions.fixFontSettings()
}
// Check tab placement in editor
val editorTabPlacement = state.editorTabPlacement
if (editorTabPlacement != TABS_NONE &&
editorTabPlacement != SwingConstants.TOP &&
editorTabPlacement != SwingConstants.LEFT &&
editorTabPlacement != SwingConstants.BOTTOM &&
editorTabPlacement != SwingConstants.RIGHT) {
state.editorTabPlacement = SwingConstants.TOP
}
// Check that alpha delay and ratio are valid
if (state.alphaModeDelay < 0) {
state.alphaModeDelay = 1500
}
if (state.alphaModeRatio < 0.0f || state.alphaModeRatio > 1.0f) {
state.alphaModeRatio = 0.5f
}
fireUISettingsChanged()
}
override fun getStateModificationCount(): Long {
return state.modificationCount
}
@Suppress("DEPRECATION")
private fun migrateOldSettings() {
if (state.ideAAType != AntialiasingType.SUBPIXEL) {
ideAAType = state.ideAAType
state.ideAAType = AntialiasingType.SUBPIXEL
}
if (state.editorAAType != AntialiasingType.SUBPIXEL) {
editorAAType = state.editorAAType
state.editorAAType = AntialiasingType.SUBPIXEL
}
if (!state.allowMergeButtons) {
Registry.get("ide.allow.merge.buttons").setValue(false)
state.allowMergeButtons = true
}
}
@Suppress("DEPRECATION")
private fun migrateOldFontSettings(): Boolean {
var migrated = false
if (state.fontSize != 0) {
fontSize2D = restoreFontSize(state.fontSize.toFloat(), state.fontScale)
state.fontSize = 0
migrated = true
}
if (state.fontScale != 0f) {
fontScale = state.fontScale
state.fontScale = 0f
migrated = true
}
if (state.fontFace != null) {
fontFace = state.fontFace
state.fontFace = null
migrated = true
}
return migrated
}
//<editor-fold desc="Deprecated stuff.">
@Suppress("PropertyName")
@Deprecated("Use fontFace", replaceWith = ReplaceWith("fontFace"))
@JvmField
@Transient
var FONT_FACE: String? = null
@Suppress("PropertyName")
@Deprecated("Use fontSize", replaceWith = ReplaceWith("fontSize"))
@JvmField
@Transient
var FONT_SIZE: Int? = 0
@Suppress("PropertyName")
@Deprecated("Use hideToolStripes", replaceWith = ReplaceWith("hideToolStripes"))
@JvmField
@Transient
var HIDE_TOOL_STRIPES = true
@Suppress("PropertyName")
@Deprecated("Use consoleCommandHistoryLimit", replaceWith = ReplaceWith("consoleCommandHistoryLimit"))
@JvmField
@Transient
var CONSOLE_COMMAND_HISTORY_LIMIT = 300
@Suppress("unused", "PropertyName")
@Deprecated("Use cycleScrolling", replaceWith = ReplaceWith("cycleScrolling"), level = DeprecationLevel.ERROR)
@JvmField
@Transient
var CYCLE_SCROLLING = true
@Suppress("PropertyName")
@Deprecated("Use showMainToolbar", replaceWith = ReplaceWith("showMainToolbar"))
@JvmField
@Transient
var SHOW_MAIN_TOOLBAR = false
@Suppress("PropertyName")
@Deprecated("Use showCloseButton", replaceWith = ReplaceWith("showCloseButton"))
@JvmField
@Transient
var SHOW_CLOSE_BUTTON = true
@Suppress("PropertyName")
@Deprecated("Use presentationMode", replaceWith = ReplaceWith("presentationMode"))
@JvmField
@Transient
var PRESENTATION_MODE = false
@Suppress("PropertyName", "SpellCheckingInspection")
@Deprecated("Use overrideLafFonts", replaceWith = ReplaceWith("overrideLafFonts"))
@JvmField
@Transient
var OVERRIDE_NONIDEA_LAF_FONTS = false
@Suppress("PropertyName")
@Deprecated("Use presentationModeFontSize", replaceWith = ReplaceWith("presentationModeFontSize"))
@JvmField
@Transient
var PRESENTATION_MODE_FONT_SIZE = 24
@Suppress("PropertyName")
@Deprecated("Use editorTabLimit", replaceWith = ReplaceWith("editorTabLimit"))
@JvmField
@Transient
var EDITOR_TAB_LIMIT = editorTabLimit
//</editor-fold>
}
| apache-2.0 | 6ac629a4bb2e2bf9312a1512dcd84270 | 29.412358 | 167 | 0.708463 | 4.958265 | false | false | false | false |
androidessence/RichTextView | lib/src/main/java/com/androidessence/lib/CustomBulletSpan.kt | 1 | 1423 | package com.androidessence.lib
import android.graphics.Canvas
import android.graphics.Paint
import android.text.Layout
import android.text.Spanned
import android.text.style.LeadingMarginSpan
/**
* Allows a number of rows in a TextView to have bullets in front of them.
*
* Created by Raghunandan on 28-11-2016.
*/
class CustomBulletSpan(private val mGapWidth: Int, private val mIgnoreSpan: Boolean, private val bulletColor: Int, private val bulletRadius: Int) : LeadingMarginSpan {
override fun getLeadingMargin(first: Boolean): Int {
return mGapWidth//mIgnoreSpan ? 0 : Math.max(Math.round(mWidth + 2), mGapWidth);
}
override fun drawLeadingMargin(c: Canvas, p: Paint, x: Int, dir: Int, top: Int, baseline: Int, bottom: Int,
text: CharSequence, start: Int, end: Int, first: Boolean, l: Layout) {
val spanned = text as Spanned
if (!mIgnoreSpan && spanned.getSpanStart(this) == start) {
// set paint
val oldStyle = p.style
val oldcolor = p.color
p.style = Paint.Style.FILL
p.color = bulletColor
c.drawCircle((x + dir * 10).toFloat(), (top + bottom) / 2.0f,
bulletRadius.toFloat(), p)
// this is required if not the color and style is carried to other spans.
p.color = oldcolor
p.style = oldStyle
}
}
} | mit | 324d8e33c7ba91247eb99a42ce086700 | 34.6 | 167 | 0.631764 | 4.042614 | false | false | false | false |
googlecodelabs/android-performance | benchmarking/app/src/main/java/com/example/macrobenchmark_codelab/ui/home/search/Results.kt | 1 | 8181 | /*
* 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.example.macrobenchmark_codelab.ui.home.search
import android.content.res.Configuration
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Add
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ChainStyle
import androidx.constraintlayout.compose.ConstraintLayout
import com.example.macrobenchmark_codelab.R
import com.example.macrobenchmark_codelab.model.Filter
import com.example.macrobenchmark_codelab.model.Snack
import com.example.macrobenchmark_codelab.model.snacks
import com.example.macrobenchmark_codelab.ui.components.FilterBar
import com.example.macrobenchmark_codelab.ui.components.JetsnackButton
import com.example.macrobenchmark_codelab.ui.components.JetsnackDivider
import com.example.macrobenchmark_codelab.ui.components.JetsnackSurface
import com.example.macrobenchmark_codelab.ui.components.SnackImage
import com.example.macrobenchmark_codelab.ui.theme.JetsnackTheme
import com.example.macrobenchmark_codelab.ui.utils.formatPrice
@Composable
fun SearchResults(
searchResults: List<Snack>,
filters: List<Filter>,
onSnackClick: (Long) -> Unit
) {
Column {
FilterBar(filters, onShowFilters = {})
Text(
text = stringResource(R.string.search_count, searchResults.size),
style = MaterialTheme.typography.h6,
color = JetsnackTheme.colors.textPrimary,
modifier = Modifier.padding(horizontal = 24.dp, vertical = 4.dp)
)
LazyColumn {
itemsIndexed(searchResults) { index, snack ->
SearchResult(snack, onSnackClick, index != 0)
}
}
}
}
@Composable
private fun SearchResult(
snack: Snack,
onSnackClick: (Long) -> Unit,
showDivider: Boolean,
modifier: Modifier = Modifier
) {
ConstraintLayout(
modifier = modifier
.fillMaxWidth()
.clickable { onSnackClick(snack.id) }
.padding(horizontal = 24.dp)
) {
val (divider, image, name, tag, priceSpacer, price, add) = createRefs()
createVerticalChain(name, tag, priceSpacer, price, chainStyle = ChainStyle.Packed)
if (showDivider) {
JetsnackDivider(
Modifier.constrainAs(divider) {
linkTo(start = parent.start, end = parent.end)
top.linkTo(parent.top)
}
)
}
SnackImage(
imageUrl = snack.imageUrl,
contentDescription = null,
modifier = Modifier
.size(100.dp)
.constrainAs(image) {
linkTo(
top = parent.top,
topMargin = 16.dp,
bottom = parent.bottom,
bottomMargin = 16.dp
)
start.linkTo(parent.start)
}
)
Text(
text = snack.name,
style = MaterialTheme.typography.subtitle1,
color = JetsnackTheme.colors.textSecondary,
modifier = Modifier.constrainAs(name) {
linkTo(
start = image.end,
startMargin = 16.dp,
end = add.start,
endMargin = 16.dp,
bias = 0f
)
}
)
Text(
text = snack.tagline,
style = MaterialTheme.typography.body1,
color = JetsnackTheme.colors.textHelp,
modifier = Modifier.constrainAs(tag) {
linkTo(
start = image.end,
startMargin = 16.dp,
end = add.start,
endMargin = 16.dp,
bias = 0f
)
}
)
Spacer(
Modifier
.height(8.dp)
.constrainAs(priceSpacer) {
linkTo(top = tag.bottom, bottom = price.top)
}
)
Text(
text = formatPrice(snack.price),
style = MaterialTheme.typography.subtitle1,
color = JetsnackTheme.colors.textPrimary,
modifier = Modifier.constrainAs(price) {
linkTo(
start = image.end,
startMargin = 16.dp,
end = add.start,
endMargin = 16.dp,
bias = 0f
)
}
)
JetsnackButton(
onClick = { /* todo */ },
shape = CircleShape,
contentPadding = PaddingValues(0.dp),
modifier = Modifier
.size(36.dp)
.constrainAs(add) {
linkTo(top = parent.top, bottom = parent.bottom)
end.linkTo(parent.end)
}
) {
Icon(
imageVector = Icons.Outlined.Add,
contentDescription = stringResource(R.string.label_add)
)
}
}
}
@Composable
fun NoResults(
query: String,
modifier: Modifier = Modifier
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier
.fillMaxSize()
.wrapContentSize()
.padding(24.dp)
) {
Image(
painterResource(R.drawable.empty_state_search),
contentDescription = null
)
Spacer(Modifier.height(24.dp))
Text(
text = stringResource(R.string.search_no_matches, query),
style = MaterialTheme.typography.subtitle1,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
Spacer(Modifier.height(16.dp))
Text(
text = stringResource(R.string.search_no_matches_retry),
style = MaterialTheme.typography.body2,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
}
}
@Preview("default")
@Preview("dark theme", uiMode = Configuration.UI_MODE_NIGHT_YES)
@Preview("large font", fontScale = 2f)
@Composable
private fun SearchResultPreview() {
JetsnackTheme {
JetsnackSurface {
SearchResult(
snack = snacks[0],
onSnackClick = { },
showDivider = false
)
}
}
}
| apache-2.0 | 0b85052bfbd56e738586f67d10eaeae2 | 33.665254 | 90 | 0.607627 | 4.835106 | false | false | false | false |
leafclick/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/execution/build/output/GradleOutputDispatcherFactory.kt | 1 | 8568 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.execution.build.output
import com.intellij.build.BuildProgressListener
import com.intellij.build.events.BuildEvent
import com.intellij.build.events.DuplicateMessageAware
import com.intellij.build.events.FinishEvent
import com.intellij.build.events.StartEvent
import com.intellij.build.events.impl.OutputBuildEventImpl
import com.intellij.build.output.BuildOutputInstantReaderImpl
import com.intellij.build.output.BuildOutputParser
import com.intellij.build.output.LineProcessor
import com.intellij.openapi.externalSystem.service.execution.AbstractOutputMessageDispatcher
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemOutputDispatcherFactory
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemOutputMessageDispatcher
import org.apache.commons.lang.ClassUtils
import org.gradle.api.logging.LogLevel
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
import java.util.concurrent.CompletableFuture
class GradleOutputDispatcherFactory : ExternalSystemOutputDispatcherFactory {
override val externalSystemId: Any? = GradleConstants.SYSTEM_ID
override fun create(buildId: Any,
buildProgressListener: BuildProgressListener,
appendOutputToMainConsole: Boolean,
parsers: List<BuildOutputParser>): ExternalSystemOutputMessageDispatcher {
return GradleOutputMessageDispatcher(buildId, buildProgressListener, appendOutputToMainConsole, parsers)
}
private class GradleOutputMessageDispatcher(private val buildId: Any,
private val myBuildProgressListener: BuildProgressListener,
private val appendOutputToMainConsole: Boolean,
private val parsers: List<BuildOutputParser>) : AbstractOutputMessageDispatcher(
myBuildProgressListener) {
override var stdOut: Boolean = true
private val lineProcessor: LineProcessor
private val myRootReader: BuildOutputInstantReaderImpl
private var myCurrentReader: BuildOutputInstantReaderImpl
private val tasksOutputReaders = mutableMapOf<String, BuildOutputInstantReaderImpl>()
private val tasksEventIds = mutableMapOf<String, Any>()
init {
val deferredRootEvents = mutableListOf<BuildEvent>()
myRootReader = object : BuildOutputInstantReaderImpl(buildId, buildId, BuildProgressListener { _: Any, event: BuildEvent ->
var buildEvent = event
val parentId = buildEvent.parentId
if (parentId != buildId && parentId is String) {
val taskEventId = tasksEventIds[parentId]
if (taskEventId != null) {
buildEvent = BuildEventInvocationHandler.wrap(event, taskEventId)
}
}
if (buildEvent is DuplicateMessageAware) {
deferredRootEvents += buildEvent
}
else {
myBuildProgressListener.onEvent(buildId, buildEvent)
}
}, parsers) {
override fun closeAndGetFuture(): CompletableFuture<Unit> =
super.closeAndGetFuture().whenComplete { _, _ -> deferredRootEvents.forEach { myBuildProgressListener.onEvent(buildId, it) } }
}
var isBuildException = false
myCurrentReader = myRootReader
lineProcessor = object : LineProcessor() {
override fun process(line: String) {
val cleanLine = removeLoggerPrefix(line)
// skip Gradle test runner output
if (cleanLine.startsWith("<ijLog>")) return
if (cleanLine.startsWith("> Task :")) {
isBuildException = false
val taskName = cleanLine.removePrefix("> Task ").substringBefore(' ')
myCurrentReader = tasksOutputReaders[taskName] ?: myRootReader
}
else if (cleanLine.startsWith("> Configure") ||
cleanLine.startsWith("FAILURE: Build failed") ||
cleanLine.startsWith("CONFIGURE SUCCESSFUL") ||
cleanLine.startsWith("BUILD SUCCESSFUL")) {
isBuildException = false
myCurrentReader = myRootReader
}
if (cleanLine == "* Exception is:") isBuildException = true
if (isBuildException && myCurrentReader == myRootReader) return
myCurrentReader.appendln(cleanLine)
if (myCurrentReader != myRootReader) {
val parentEventId = myCurrentReader.parentEventId
myBuildProgressListener.onEvent(buildId, OutputBuildEventImpl(parentEventId, line + '\n', stdOut))
}
}
}
}
override fun onEvent(buildId: Any, event: BuildEvent) {
super.onEvent(buildId, event)
if (event.parentId != buildId) return
if (event is StartEvent) {
tasksOutputReaders[event.message]?.close() // multiple invocations of the same task during the build session
val parentEventId = event.id
tasksOutputReaders[event.message] = BuildOutputInstantReaderImpl(buildId, parentEventId, myBuildProgressListener, parsers)
tasksEventIds[event.message] = parentEventId
}
else if (event is FinishEvent) {
// unreceived output is still possible after finish task event but w/o long pauses between chunks
// also no output expected for up-to-date tasks
tasksOutputReaders[event.message]?.disableActiveReading()
}
}
override fun closeAndGetFuture(): CompletableFuture<*> {
lineProcessor.close()
val futures = mutableListOf<CompletableFuture<Unit>>()
tasksOutputReaders.forEach { (_, reader) -> reader.closeAndGetFuture().let { futures += it } }
futures += myRootReader.closeAndGetFuture()
tasksOutputReaders.clear()
return CompletableFuture.allOf(*futures.toTypedArray())
}
override fun append(csq: CharSequence): Appendable {
if (appendOutputToMainConsole) {
myBuildProgressListener.onEvent(buildId, OutputBuildEventImpl(buildId, csq.toString(), stdOut))
}
lineProcessor.append(csq)
return this
}
override fun append(csq: CharSequence, start: Int, end: Int): Appendable {
if (appendOutputToMainConsole) {
myBuildProgressListener.onEvent(buildId, OutputBuildEventImpl(buildId, csq.subSequence(start, end).toString(), stdOut))
}
lineProcessor.append(csq, start, end)
return this
}
override fun append(c: Char): Appendable {
if (appendOutputToMainConsole) {
myBuildProgressListener.onEvent(buildId, OutputBuildEventImpl(buildId, c.toString(), stdOut))
}
lineProcessor.append(c)
return this
}
private fun removeLoggerPrefix(line: String): String {
val list = mutableListOf<String>()
list += line.split(' ', limit = 3)
if (list.size < 3) return line
if (!list[1].startsWith('[') || !list[1].endsWith(']')) return line
if (!list[2].startsWith('[')) return line
if (!list[2].endsWith(']')) {
val i = list[2].indexOf(']')
if (i == -1) return line
list[2] = list[2].substring(0, i + 1)
if (!list[2].endsWith(']')) return line
}
try {
LogLevel.valueOf(list[1].drop(1).dropLast(1))
}
catch (e: Exception) {
return line
}
return line.drop(list.sumBy { it.length } + 2).trimStart()
}
private class BuildEventInvocationHandler(private val buildEvent: BuildEvent,
private val parentEventId: Any) : InvocationHandler {
override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?): Any? {
if (method?.name.equals("getParentId")) return parentEventId
return method?.invoke(buildEvent, *args ?: arrayOfNulls<Any>(0))
}
companion object {
fun wrap(buildEvent: BuildEvent, parentEventId: Any): BuildEvent {
val classLoader = buildEvent.javaClass.classLoader
val interfaces = ClassUtils.getAllInterfaces(buildEvent.javaClass)
.filterIsInstance(Class::class.java)
.toTypedArray()
val invocationHandler = BuildEventInvocationHandler(buildEvent, parentEventId)
return Proxy.newProxyInstance(classLoader, interfaces, invocationHandler) as BuildEvent
}
}
}
}
}
| apache-2.0 | 58fa1dc866f95763cd29794a0ba4de66 | 43.858639 | 140 | 0.680556 | 5.38191 | false | false | false | false |
Raizlabs/DBFlow | lib/src/main/kotlin/com/dbflow5/query/BaseQueriable.kt | 1 | 2974 | package com.dbflow5.query
import com.dbflow5.config.FlowLog
import com.dbflow5.database.DatabaseStatement
import com.dbflow5.database.DatabaseStatementWrapper
import com.dbflow5.database.DatabaseWrapper
import com.dbflow5.database.FlowCursor
import com.dbflow5.database.SQLiteException
import com.dbflow5.longForQuery
import com.dbflow5.runtime.NotifyDistributor
import com.dbflow5.stringForQuery
import com.dbflow5.structure.ChangeAction
/**
* Description: Base implementation of something that can be queried from the database.
*/
abstract class BaseQueriable<TModel : Any> protected constructor(
/**
* @return The table associated with this INSERT
*/
val table: Class<TModel>) : Queriable, Actionable {
abstract override val primaryAction: ChangeAction
override fun longValue(databaseWrapper: DatabaseWrapper): Long {
try {
val query = query
FlowLog.log(FlowLog.Level.V, "Executing query: $query")
return longForQuery(databaseWrapper, query)
} catch (sde: SQLiteException) {
// catch exception here, log it but return 0;
FlowLog.logWarning(sde)
}
return 0
}
override fun stringValue(databaseWrapper: DatabaseWrapper): String? {
try {
val query = query
FlowLog.log(FlowLog.Level.V, "Executing query: $query")
return stringForQuery(databaseWrapper, query)
} catch (sde: SQLiteException) {
// catch exception here, log it but return null;
FlowLog.logWarning(sde)
}
return null
}
override fun hasData(databaseWrapper: DatabaseWrapper): Boolean = longValue(databaseWrapper) > 0
override fun cursor(databaseWrapper: DatabaseWrapper): FlowCursor? {
if (primaryAction == ChangeAction.INSERT) {
// inserting, let's compile and insert
compileStatement(databaseWrapper).use { it.executeInsert() }
} else {
val query = query
FlowLog.log(FlowLog.Level.V, "Executing query: " + query)
databaseWrapper.execSQL(query)
}
return null
}
override fun executeInsert(databaseWrapper: DatabaseWrapper): Long =
compileStatement(databaseWrapper).use { it.executeInsert() }
override fun execute(databaseWrapper: DatabaseWrapper) {
val cursor = cursor(databaseWrapper)
if (cursor != null) {
cursor.close()
} else {
// we dont query, we're executing something here.
NotifyDistributor.get().notifyTableChanged(table, primaryAction)
}
}
override fun compileStatement(databaseWrapper: DatabaseWrapper): DatabaseStatement {
val query = query
FlowLog.log(FlowLog.Level.V, "Compiling Query Into Statement: " + query)
return DatabaseStatementWrapper(databaseWrapper.compileStatement(query), this)
}
override fun toString(): String = query
}
| mit | 539fabbef98e263b049ad72e2b270a65 | 33.988235 | 100 | 0.673167 | 4.940199 | false | false | false | false |
code-helix/slatekit | test/coroutine-tests/src/main/kotlin/app.kt | 1 | 4987 | /**
<slate_header>
url: www.slatekit.com
git: www.github.com/code-helix/slatekit
org: www.codehelix.co
author: Kishore Reddy
copyright: 2016 CodeHelix Solutions Inc.
license: refer to website and/or github
about: A Kotlin utility library, tool-kit and server backend.
mantra: Simplicity above all else
</slate_header>
*/
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import slatekit.async.coroutines.AsyncContextCoroutine
import slatekit.async.futures.AsyncContextFuture
import slatekit.entities.repo.EntityRepo
import slatekit.entities.services.EntityService
import slatekit.async.futures.Future
import slatekit.async.futures.await
import java.time.LocalDateTime
import java.util.concurrent.CompletableFuture
import kotlin.system.measureTimeMillis
suspend fun main(args:Array<String>) {
testCompose_Via_Futures().await()
println("\n====================")
testCompose_Via_Coroutines().await()
}
suspend fun testCoRoutines() {
val asyncScope = AsyncContextCoroutine()
val svc = EntityService<User>(EntityRepo<User>(mutableListOf(), asyncScope), asyncScope)
val futures = listOf(
svc.create(User(0, "user_1")),
svc.create(User(0, "user_2")),
svc.create(User(0, "user_3"))
)
futures.forEach{ it.await() }
val member = EntityService::class.members.first { it.name == "all" }
val result = member.call(svc)
when(result) {
is Future<*> -> {
val v = result.await()
println(v)
}
else -> println(result)
}
svc.all().await().forEach { println(it) }
//svc.all().forEach { println(it) }
println("done with suspend")
}
fun testCompose_Via_Futures(): Future<String> {
val f0 = CompletableFuture.supplyAsync {
println("JAVA FUTURES ================\n")
val f1 = CompletableFuture.supplyAsync {
println("f1: loading user : begin : " + LocalDateTime.now().toString())
Thread.sleep(2000L)
println("f1: loaded user : end : " + LocalDateTime.now().toString())
"user_01"
}
val f2 = f1.thenApply { it ->
println("\n")
println("f2: updating user : begin : " + LocalDateTime.now().toString())
Thread.sleep(3000L)
println("f2: updated user : end : " + LocalDateTime.now().toString())
"f2: updated user: $it"
}
val f3 = f2.thenCompose { it ->
println("\n")
println("f3: logging user : begin : " + LocalDateTime.now().toString())
Thread.sleep(2000L)
println("f3: logged user : end : " + LocalDateTime.now().toString())
CompletableFuture.completedFuture("f3:logged: $it")
}
val result = f3.get()
println()
println(result)
result
}
return f0
}
suspend fun testCompose_Via_Coroutines(): Deferred<String> {
val f0 = GlobalScope.async {
println("KOTLIN COROUTINES ================\n")
val f1 = GlobalScope.async {
println("f1: loading user : begin : " + LocalDateTime.now().toString())
delay(2000L)
println("f1: loaded user : end : " + LocalDateTime.now().toString())
"user_01"
}
val f1Result = f1.await()
val f2 = GlobalScope.async {
val it = f1Result
println("\n")
println("f2: updating user : begin : " + LocalDateTime.now().toString())
delay(3000L)
println("f2: updated user : end : " + LocalDateTime.now().toString())
"f2: updated user: $it"
}
val f2Result = f2.await()
val f3 = GlobalScope.async {
val it = f2Result
println("\n")
println("f3: logging user : begin : " + LocalDateTime.now().toString())
delay(2000L)
println("f3: logged user : end : " + LocalDateTime.now().toString())
"f3:logged: $it"
}
val result = f3.await()
println()
println(result)
result
}
return f0
}
fun testFutures(){
val f1 = CompletableFuture.completedFuture(123)
val f2 = f1.thenApply { it -> it + 1 }
val f3 = f1.thenCompose { v -> CompletableFuture.completedFuture(v + 2) }
val f4 = f1.thenAccept { it -> it + 3 }
f3.handle { t, x ->
println(t)
println(x)
}
val f1Val = f1.get()
val f2Val = f2.get()
val f3Val = f3.get()
val f4Val = f4.get()
println(f1Val)
println(f2Val)
println(f3Val)
println(f4Val)
}
suspend fun testMeasure(){
val time = measureTimeMillis {
println("before 1")
val one = doSomethingUsefulOne()
println("before 2")
val two = doSomethingUsefulTwo()
println("The answer is ${one + two}")
}
//test_runBlocking()
//Thread.sleep(2000)
}
| apache-2.0 | 30bb28f82995dda0022c9e6f12c06099 | 26.860335 | 92 | 0.587528 | 3.926772 | false | false | false | false |
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/ndrei/teslacorelib/gui/TeslaCoreGuiProxy.kt | 1 | 1432 | package net.ndrei.teslacorelib.gui
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
import net.minecraftforge.fml.common.network.IGuiHandler
import net.ndrei.teslacorelib.capabilities.TeslaCoreCapabilities
/**
* Created by CF on 2017-06-28.
*/
class TeslaCoreGuiProxy : IGuiHandler {
override fun getServerGuiElement(id: Int, player: EntityPlayer, world: World, x: Int, y: Int, z: Int): Any? {
val pos = BlockPos(x, y, z)
val te = world.getTileEntity(pos)
if (te != null && te.hasCapability(TeslaCoreCapabilities.CAPABILITY_GUI_CONTAINER, null)) {
val provider = te.getCapability(TeslaCoreCapabilities.CAPABILITY_GUI_CONTAINER, null)
if (provider != null) {
return provider.getContainer(id, player)
}
}
return null
}
override fun getClientGuiElement(id: Int, player: EntityPlayer, world: World, x: Int, y: Int, z: Int): Any? {
val pos = BlockPos(x, y, z)
val te = world.getTileEntity(pos)
if (te != null && te.hasCapability(TeslaCoreCapabilities.CAPABILITY_GUI_CONTAINER, null)) {
val provider = te.getCapability(TeslaCoreCapabilities.CAPABILITY_GUI_CONTAINER, null)
if (provider != null) {
return provider.getGuiContainer(id, player)
}
}
return null
}
}
| mit | 58950324661424d8a805849ddca1925b | 38.777778 | 113 | 0.659218 | 4.211765 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/boxInline/nonLocalReturns/propertyAccessors.kt | 5 | 558 | // FILE: 1.kt
package test
inline fun <R> doCall(p: () -> R) {
p()
}
// FILE: 2.kt
import test.*
class A {
var result = 0;
var field: Int
get() {
doCall { return 1 }
return 2
}
set(v: Int) {
doCall {
result = v / 2
return
}
result = v
}
}
fun box(): String {
val a = A()
if (a.field != 1) return "fail 1: ${a.field}"
a.field = 4
if (a.result != 2) return "fail 2: ${a.result}"
return "OK"
}
| apache-2.0 | 1fd0143f1e67c34f6ba6396486475bb1 | 12.95 | 51 | 0.401434 | 3.301775 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/codeInsight/codeVision/TooManyUsagesAndInheritors.kt | 12 | 636 | // MODE: usages-&-inheritors
// USAGES-LIMIT: 3
// INHERITORS-LIMIT: 2
<# block [ 3+ Usages 2+ Inheritors] #>
open class SomeClass {
class NestedDerivedClass: SomeClass() {} // <== (1): nested class
}
<# block [ 1 Usage 1 Inheritor] #>
open class DerivedClass : SomeClass {} // <== (2): direct derived one
class AnotherDerivedClass : SomeClass {} // <== (3): yet another derived one
class DerivedDerivedClass : DerivedClass { // <== (): indirect inheritor of SomeClass
fun main() {
val someClassInstance = object : SomeClass() // { <== (4): anonymous derived one
val somethingHere = ""
}
}
} | apache-2.0 | 4ae198fbfbda975859a4755a4eec0f83 | 34.388889 | 88 | 0.624214 | 4.156863 | false | false | false | false |
smmribeiro/intellij-community | plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/id/ElementKeyForIdProvider.kt | 1 | 1546 | package com.intellij.ide.actions.searcheverywhere.ml.id
import com.intellij.openapi.extensions.ExtensionPointName
internal abstract class ElementKeyForIdProvider {
companion object {
private val EP_NAME = ExtensionPointName.create<ElementKeyForIdProvider>("com.intellij.searcheverywhere.ml.elementKeyForIdProvider")
fun isElementSupported(element: Any) = getKeyOrNull(element) != null
/**
* Returns key that will be used by [SearchEverywhereMlItemIdProvider].
* The method may throw a [UnsupportedElementTypeException] if no provider was found for the element,
* therefore [isElementSupported] should be used before to make sure that calling this method is safe.
* @return Key for ID
*/
fun getKey(element: Any) = getKeyOrNull(element) ?: throw UnsupportedElementTypeException(element::class.java)
private fun getKeyOrNull(element: Any): Any? {
EP_NAME.extensionList.forEach {
val key = it.getKey(element)
if (key != null) {
return key
}
}
return null
}
}
/**
* Returns a unique key that will be used by [SearchEverywhereMlItemIdProvider] to obtain
* an id of the element.
*
* If the element type is not supported by the provider, it will return null.
* @return Unique key based on the [element] or null if not supported
*/
protected abstract fun getKey(element: Any): Any?
}
internal class UnsupportedElementTypeException(elementType: Class<*>): Exception("No provider found for element type: ${elementType}")
| apache-2.0 | 52308a0412e5184918f48bf3fa0b3b8b | 36.707317 | 136 | 0.719276 | 4.628743 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/decompiler/common/incompatibleAbiVersion.kt | 2 | 1331 | // 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.decompiler.common
import org.jetbrains.kotlin.idea.decompiler.textBuilder.DecompiledText
import org.jetbrains.kotlin.idea.decompiler.textBuilder.DecompiledTextIndex
import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion
private const val FILE_ABI_VERSION_MARKER: String = "FILE_ABI"
private const val CURRENT_ABI_VERSION_MARKER: String = "CURRENT_ABI"
const val INCOMPATIBLE_ABI_VERSION_GENERAL_COMMENT: String =
"// This class file was compiled with different version of Kotlin compiler and can't be decompiled."
private const val INCOMPATIBLE_ABI_VERSION_COMMENT: String = "$INCOMPATIBLE_ABI_VERSION_GENERAL_COMMENT\n" +
"//\n" +
"// Current compiler ABI version is $CURRENT_ABI_VERSION_MARKER\n" +
"// File ABI version is $FILE_ABI_VERSION_MARKER"
fun <V : BinaryVersion> createIncompatibleAbiVersionDecompiledText(expectedVersion: V, actualVersion: V): DecompiledText = DecompiledText(
INCOMPATIBLE_ABI_VERSION_COMMENT.replace(CURRENT_ABI_VERSION_MARKER, expectedVersion.toString())
.replace(FILE_ABI_VERSION_MARKER, actualVersion.toString()),
DecompiledTextIndex.Empty
)
| apache-2.0 | 94fecad7645e414d4339d32aa439b6fb | 54.458333 | 158 | 0.778362 | 4.238854 | false | false | false | false |
smmribeiro/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/statistics/ExternalSystemSyncActionsCollector.kt | 1 | 5217 | // 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.openapi.externalSystem.statistics
import com.intellij.featureStatistics.fusCollectors.EventsRateThrottle
import com.intellij.featureStatistics.fusCollectors.ThrowableDescription
import com.intellij.ide.plugins.PluginUtil
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventFields.Boolean
import com.intellij.internal.statistic.eventLog.events.EventFields.DurationMs
import com.intellij.internal.statistic.eventLog.events.EventFields.Int
import com.intellij.internal.statistic.eventLog.events.EventFields.StringValidatedByCustomRule
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.internal.statistic.utils.getPluginInfoById
import com.intellij.internal.statistic.utils.platformPlugin
import com.intellij.openapi.externalSystem.model.ExternalSystemException
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
enum class Phase { GRADLE_CALL, PROJECT_RESOLVERS, DATA_SERVICES }
/**
* Collect gradle import stats.
*
* This collector is an internal implementation aimed gather data on
* the Gradle synchronization duration. Phases are also
* specific to Gradle build system.
*/
@ApiStatus.Internal
class ExternalSystemSyncActionsCollector : CounterUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
companion object {
private val GROUP = EventLogGroup("build.gradle.import", 4)
val activityIdField = EventFields.Long("ide_activity_id")
val importPhaseField = EventFields.Enum<Phase>("phase")
private val syncStartedEvent = GROUP.registerEvent("gradle.sync.started", activityIdField)
private val syncFinishedEvent = GROUP.registerEvent("gradle.sync.finished", activityIdField, Boolean("sync_successful"))
private val phaseStartedEvent = GROUP.registerEvent("phase.started", activityIdField, importPhaseField)
private val phaseFinishedEvent = GROUP.registerVarargEvent("phase.finished",
activityIdField,
importPhaseField,
DurationMs,
Int("error_count"))
val errorField = StringValidatedByCustomRule("error", "class_name")
val severityField = EventFields.String("severity", listOf("fatal", "warning"))
val errorHashField = Int("error_hash")
val tooManyErrorsField = Boolean("too_many_errors")
private val errorEvent = GROUP.registerVarargEvent("error",
activityIdField,
errorField,
severityField,
errorHashField,
EventFields.PluginInfo,
tooManyErrorsField)
private val ourErrorsRateThrottle = EventsRateThrottle(100, 5L * 60 * 1000) // 100 errors per 5 minutes
@JvmStatic
fun logSyncStarted(project: Project?, activityId: Long) = syncStartedEvent.log(project, activityId)
@JvmStatic
fun logSyncFinished(project: Project?, activityId: Long, success: Boolean) = syncFinishedEvent.log(project, activityId, success)
@JvmStatic
fun logPhaseStarted(project: Project?, activityId: Long, phase: Phase) = phaseStartedEvent.log(project, activityId, phase)
@JvmStatic
fun logPhaseFinished(project: Project?, activityId: Long, phase: Phase, durationMs: Long, errorCount: Int = 0) =
phaseFinishedEvent.log(project, activityIdField.with(activityId), importPhaseField.with(phase), DurationMs.with(durationMs),
EventPair(Int("error_count"), errorCount))
@JvmStatic
fun logError(project: Project?, activityId: Long, throwable: Throwable) {
val description = ThrowableDescription(throwable)
val framesHash = if (throwable is ExternalSystemException) {
throwable.originalReason.hashCode()
} else {
description.getLastFrames(50).hashCode()
}
val data = ArrayList<EventPair<*>>()
data.add(activityIdField.with(activityId))
data.add(severityField.with("fatal"))
val pluginId = PluginUtil.getInstance().findPluginId(throwable)
data.add(EventFields.PluginInfo.with(if (pluginId == null) platformPlugin else getPluginInfoById(pluginId)))
data.add(errorField.with(description.className))
if (ourErrorsRateThrottle.tryPass(System.currentTimeMillis())) {
data.add(errorHashField.with(framesHash))
}
else {
data.add(tooManyErrorsField.with(true))
}
errorEvent.log(project, *data.toTypedArray())
}
}
}
| apache-2.0 | 459f645be98d9cbe13baa38808149c12 | 49.650485 | 158 | 0.689477 | 5.129794 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/unifier/equivalence/expressions/conventions/invoke/invokeOnConst.kt | 13 | 135 | // DISABLE-ERRORS
fun Int.invoke() = this + 1
val a = <selection>1()</selection>
val b = 1.invoke()
val c = invoke(1)
val d = 1.plus() | apache-2.0 | 92607c2922ff87b60eb58ce800799cdf | 18.428571 | 34 | 0.622222 | 2.7 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/pipeline/shadermodel/UtilityNodes.kt | 1 | 9621 | package de.fabmax.kool.pipeline.shadermodel
import de.fabmax.kool.math.Vec2f
import de.fabmax.kool.math.Vec3f
import de.fabmax.kool.math.Vec4f
import de.fabmax.kool.pipeline.Attribute
import de.fabmax.kool.pipeline.GlslType
import de.fabmax.kool.pipeline.ShaderStage
class FlipBacksideNormalNode(graph: ShaderGraph) :
ShaderNode("flipBacksideNormal_${graph.nextNodeId}", graph, ShaderStage.FRAGMENT_SHADER.mask) {
var inNormal = ShaderNodeIoVar(ModelVar3fConst(Vec3f.Y_AXIS))
val outNormal: ShaderNodeIoVar = ShaderNodeIoVar(ModelVar3f("${name}_outNormal"), this)
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(inNormal)
}
override fun generateCode(generator: CodeGenerator) {
super.generateCode(generator)
generator.appendMain("""
${outNormal.declare()} = ${inNormal.ref3f()} * (float(gl_FrontFacing) * 2.0 - 1.0);
""")
}
}
class SplitNode(val outChannels: String, graph: ShaderGraph) : ShaderNode("split_${graph.nextNodeId}", graph) {
var input = ShaderNodeIoVar(ModelVar4fConst(Vec4f.ZERO))
val output: ShaderNodeIoVar = when (outChannels.length) {
1 -> ShaderNodeIoVar(ModelVar1f("${name}_out"), this)
2 -> ShaderNodeIoVar(ModelVar2f("${name}_out"), this)
3 -> ShaderNodeIoVar(ModelVar3f("${name}_out"), this)
4 -> ShaderNodeIoVar(ModelVar4f("${name}_out"), this)
else -> throw IllegalArgumentException("outChannels parameter must be between 1 and 4 characters long (e.g. 'xyz')")
}
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(input)
}
override fun generateCode(generator: CodeGenerator) {
generator.appendMain("${output.declare()} = ${input.name}.$outChannels;")
}
}
class CombineNode(outType: GlslType, graph: ShaderGraph) : ShaderNode("combine_${graph.nextNodeId}", graph) {
var inX = ShaderNodeIoVar(ModelVar1fConst(0f))
var inY = ShaderNodeIoVar(ModelVar1fConst(0f))
var inZ = ShaderNodeIoVar(ModelVar1fConst(0f))
var inW = ShaderNodeIoVar(ModelVar1fConst(0f))
var output = when (outType) {
GlslType.VEC_2F -> ShaderNodeIoVar(ModelVar2f("${name}_out"), this)
GlslType.VEC_3F -> ShaderNodeIoVar(ModelVar3f("${name}_out"), this)
GlslType.VEC_4F -> ShaderNodeIoVar(ModelVar4f("${name}_out"), this)
else -> throw IllegalArgumentException("Only allowed out types are VEC_2F, VEC_3F and VEC_4F")
}
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(inX, inY, inZ, inW)
}
override fun generateCode(generator: CodeGenerator) {
when (output.variable.type) {
GlslType.VEC_2F -> generator.appendMain("${output.declare()} = vec2(${inX.ref1f()}, ${inY.ref1f()});")
GlslType.VEC_3F -> generator.appendMain("${output.declare()} = vec3(${inX.ref1f()}, ${inY.ref1f()}, ${inZ.ref1f()});")
GlslType.VEC_4F -> generator.appendMain("${output.declare()} = vec4(${inX.ref1f()}, ${inY.ref1f()}, ${inZ.ref1f()}, ${inW.ref1f()});")
else -> throw IllegalArgumentException("Only allowed out types are VEC_2F, VEC_3F and VEC_4F")
}
}
}
class Combine31Node(graph: ShaderGraph) : ShaderNode("combine31_${graph.nextNodeId}", graph) {
var inXyz = ShaderNodeIoVar(ModelVar3fConst(Vec3f.ZERO))
var inW = ShaderNodeIoVar(ModelVar1fConst(0f))
var output = ShaderNodeIoVar(ModelVar4f("${name}_out"), this)
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(inXyz, inW)
}
override fun generateCode(generator: CodeGenerator) {
generator.appendMain("${output.declare()} = vec4(${inXyz.ref3f()}, ${inW.ref1f()});")
}
}
class AttributeNode(val attribute: Attribute, graph: ShaderGraph) :
ShaderNode(attribute.name, graph, ShaderStage.VERTEX_SHADER.mask) {
val output = ShaderNodeIoVar(ModelVar(attribute.name, attribute.type), this)
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
shaderGraph as VertexShaderGraph
shaderGraph.requiredVertexAttributes += attribute
}
}
class InstanceAttributeNode(val attribute: Attribute, graph: ShaderGraph) :
ShaderNode(attribute.name, graph, ShaderStage.VERTEX_SHADER.mask) {
val output = ShaderNodeIoVar(ModelVar(attribute.name, attribute.type), this)
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
shaderGraph as VertexShaderGraph
shaderGraph.requiredInstanceAttributes += attribute
}
}
class StageInterfaceNode(val name: String, vertexGraph: ShaderGraph, fragmentGraph: ShaderGraph) {
// written in source stage (i.e. vertex shader)
var input = ShaderNodeIoVar(ModelVar1fConst(0f))
set(value) {
output = ShaderNodeIoVar(ModelVar(name, value.variable.type), fragmentNode)
field = value
}
// accessible in target stage (i.e. fragment shader)
var output = ShaderNodeIoVar(ModelVar1f(name))
private set
var isFlat = false
private lateinit var ifVar: ShaderInterfaceIoVar
val vertexNode = InputNode(vertexGraph)
val fragmentNode = OutputNode(fragmentGraph)
inner class InputNode(graph: ShaderGraph) : ShaderNode(name, graph, ShaderStage.VERTEX_SHADER.mask) {
val ifNode = this@StageInterfaceNode
var input: ShaderNodeIoVar
get() = ifNode.input
set(value) { ifNode.input = value }
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(input)
ifVar = shaderGraph.addStageOutput(output.variable, isFlat)
}
override fun generateCode(generator: CodeGenerator) {
generator.appendMain("${output.name} = ${input.refAsType(output.variable.type)};")
}
}
inner class OutputNode(graph: ShaderGraph) : ShaderNode(name, graph, ShaderStage.FRAGMENT_SHADER.mask) {
val ifNode = this@StageInterfaceNode
val output: ShaderNodeIoVar
get() = ifNode.output
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
shaderGraph.inputs += ifVar
}
}
}
class ScreenCoordNode(graph: ShaderGraph) : ShaderNode("screenCoord_${graph.nextNodeId}", graph, ShaderStage.FRAGMENT_SHADER.mask) {
var inViewport = ShaderNodeIoVar(ModelVar4fConst(Vec4f.ZERO))
val outScreenCoord = ShaderNodeIoVar(ModelVar4f("gl_FragCoord"), this)
val outNormalizedScreenCoord = ShaderNodeIoVar(ModelVar3f("${name}_outNormalizedCoord"), this)
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(inViewport)
}
override fun generateCode(generator: CodeGenerator) {
generator.appendMain("""
${outNormalizedScreenCoord.declare()} = ${outScreenCoord.ref3f()};
$outNormalizedScreenCoord.xy - ${inViewport.ref2f()};
$outNormalizedScreenCoord.xy /= ${inViewport.ref4f()}.zw;
""")
}
}
class FullScreenQuadTexPosNode(graph: ShaderGraph) : ShaderNode("fullScreenQuad_${graph.nextNodeId}", graph) {
var inTexCoord = ShaderNodeIoVar(ModelVar2fConst(Vec2f.ZERO))
var inDepth = ShaderNodeIoVar(ModelVar1fConst(0.999f))
val outQuadPos = ShaderNodeIoVar(ModelVar4f("${name}_outPos"), this)
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(inTexCoord, inDepth)
}
override fun generateCode(generator: CodeGenerator) {
generator.appendMain("${outQuadPos.declare()} = vec4(${inTexCoord.ref2f()} * 2.0 - 1.0, ${inDepth.ref1f()}, 1.0);")
}
}
class GetMorphWeightNode(val iWeight: Int, graph: ShaderGraph) : ShaderNode("getMorphWeight_${graph.nextNodeId}", graph) {
var inWeights0 = ShaderNodeIoVar(ModelVar4fConst(Vec4f.ZERO))
var inWeights1 = ShaderNodeIoVar(ModelVar4fConst(Vec4f.ZERO))
val outWeight = ShaderNodeIoVar(ModelVar1f("${name}_outW"), this)
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(inWeights0, inWeights1)
}
override fun generateCode(generator: CodeGenerator) {
val inW = if (iWeight < 4) { inWeights0 } else { inWeights1 }
val c = when (iWeight % 4) {
0 -> "x"
1 -> "y"
2 -> "z"
else -> "w"
}
generator.appendMain("${outWeight.declare()} = ${inW.ref4f()}.$c;")
}
}
class NamedVariableNode(name: String, graph: ShaderGraph) : ShaderNode(name, graph) {
var input = ShaderNodeIoVar(ModelVar1fConst(0f))
set(value) {
field = value
output = ShaderNodeIoVar(ModelVar(name, value.variable.type), this)
}
var output = ShaderNodeIoVar(ModelVar(name, GlslType.FLOAT), this)
private set
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(input)
}
override fun generateCode(generator: CodeGenerator) {
generator.appendMain("${output.declare()} = $input;")
}
}
class PointSizeNode(graph: ShaderGraph) : ShaderNode("pointSz", graph, ShaderStage.VERTEX_SHADER.mask) {
var inSize = ShaderNodeIoVar(ModelVar1fConst(1f))
override fun setup(shaderGraph: ShaderGraph) {
super.setup(shaderGraph)
dependsOn(inSize)
}
override fun generateCode(generator: CodeGenerator) {
generator.appendMain("gl_PointSize = ${inSize.ref1f()};")
}
} | apache-2.0 | df965fef8c646f65895a79aa84ee72d4 | 37.18254 | 146 | 0.670616 | 4.195813 | false | false | false | false |
siosio/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/ProjectSettingsTracker.kt | 1 | 10698 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.autoimport
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ModificationType.EXTERNAL
import com.intellij.openapi.externalSystem.autoimport.changes.AsyncFilesChangesListener.Companion.subscribeOnDocumentsAndVirtualFilesChanges
import com.intellij.openapi.externalSystem.autoimport.changes.FilesChangesListener
import com.intellij.openapi.externalSystem.autoimport.changes.NewFilesListener.Companion.whenNewFilesCreated
import com.intellij.openapi.externalSystem.autoimport.settings.*
import com.intellij.openapi.externalSystem.util.calculateCrc
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.LocalTimeCounter.currentTime
import org.jetbrains.annotations.ApiStatus
import java.nio.file.Path
import java.util.concurrent.Executor
import java.util.concurrent.atomic.AtomicReference
@ApiStatus.Internal
class ProjectSettingsTracker(
private val project: Project,
private val projectTracker: AutoImportProjectTracker,
private val backgroundExecutor: Executor,
private val projectAware: ExternalSystemProjectAware,
private val parentDisposable: Disposable
) {
private val status = ProjectStatus(debugName = "Settings ${projectAware.projectId.readableName}")
private val settingsFilesStatus = AtomicReference(SettingsFilesStatus())
private val applyChangesOperation = AnonymousParallelOperationTrace(debugName = "Apply changes operation")
private val settingsAsyncSupplier = SettingsFilesAsyncSupplier()
private fun calculateSettingsFilesCRC(settingsFiles: Set<String>): Map<String, Long> {
val localFileSystem = LocalFileSystem.getInstance()
return settingsFiles
.mapNotNull { localFileSystem.findFileByPath(it) }
.associate { it.path to calculateCrc(it) }
}
private fun calculateCrc(file: VirtualFile): Long {
val fileDocumentManager = FileDocumentManager.getInstance()
val document = fileDocumentManager.getCachedDocument(file)
if (document != null) return document.calculateCrc(project, projectAware.projectId.systemId, file)
return file.calculateCrc(project, projectAware.projectId.systemId)
}
fun isUpToDate() = status.isUpToDate()
fun getModificationType() = status.getModificationType()
fun getSettingsContext(): ExternalSystemSettingsFilesReloadContext = settingsFilesStatus.get()
private fun createSettingsFilesStatus(
oldSettingsFilesCRC: Map<String, Long>,
newSettingsFilesCRC: Map<String, Long>
): SettingsFilesStatus {
val updatedFiles = oldSettingsFilesCRC.keys.intersect(newSettingsFilesCRC.keys)
.filterTo(HashSet()) { oldSettingsFilesCRC[it] != newSettingsFilesCRC[it] }
val createdFiles = newSettingsFilesCRC.keys.minus(oldSettingsFilesCRC.keys)
val deletedFiles = oldSettingsFilesCRC.keys.minus(newSettingsFilesCRC.keys)
return SettingsFilesStatus(oldSettingsFilesCRC, newSettingsFilesCRC, updatedFiles, createdFiles, deletedFiles)
}
/**
* Usually all crc hashes must be previously calculated
* => this apply will be fast
* => collisions is a rare thing
*/
private fun applyChanges() {
applyChangesOperation.startTask()
submitSettingsFilesRefreshAndCRCCalculation("applyChanges") { newSettingsFilesCRC ->
settingsFilesStatus.set(SettingsFilesStatus(newSettingsFilesCRC))
status.markSynchronized(currentTime())
applyChangesOperation.finishTask()
}
}
/**
* Applies changes for newly registered files
* Needed to cases: tracked files are registered during project reload
*/
private fun applyUnknownChanges() {
applyChangesOperation.startTask()
submitSettingsFilesRefreshAndCRCCalculation("applyUnknownChanges") { newSettingsFilesCRC ->
val settingsFilesStatus = settingsFilesStatus.updateAndGet {
createSettingsFilesStatus(newSettingsFilesCRC + it.oldCRC, newSettingsFilesCRC)
}
if (!settingsFilesStatus.hasChanges()) {
status.markSynchronized(currentTime())
}
applyChangesOperation.finishTask()
}
}
fun refreshChanges() {
submitSettingsFilesRefreshAndCRCCalculation("refreshChanges") { newSettingsFilesCRC ->
val settingsFilesStatus = settingsFilesStatus.updateAndGet {
createSettingsFilesStatus(it.oldCRC, newSettingsFilesCRC)
}
LOG.info("Settings file status: ${settingsFilesStatus}")
when (settingsFilesStatus.hasChanges()) {
true -> status.markDirty(currentTime(), EXTERNAL)
else -> status.markReverted(currentTime())
}
projectTracker.scheduleChangeProcessing()
}
}
fun getState() = State(status.isDirty(), settingsFilesStatus.get().oldCRC.toMap())
fun loadState(state: State) {
if (state.isDirty) status.markDirty(currentTime(), EXTERNAL)
settingsFilesStatus.set(SettingsFilesStatus(state.settingsFiles.toMap()))
}
private fun submitSettingsFilesRefreshAndCRCCalculation(id: Any, callback: (Map<String, Long>) -> Unit) {
submitSettingsFilesRefresh { settingsPaths ->
submitSettingsFilesCRCCalculation(id, settingsPaths, callback)
}
}
@Suppress("SameParameterValue")
private fun submitSettingsFilesCRCCalculation(id: Any, callback: (Map<String, Long>) -> Unit) {
settingsAsyncSupplier.supply({ settingsPaths ->
submitSettingsFilesCRCCalculation(id, settingsPaths, callback)
}, parentDisposable)
}
private fun submitSettingsFilesRefresh(callback: (Set<String>) -> Unit) {
EdtAsyncSupplier.invokeOnEdt(projectTracker::isAsyncChangesProcessing, {
val fileDocumentManager = FileDocumentManager.getInstance()
fileDocumentManager.saveAllDocuments()
settingsAsyncSupplier.invalidate()
settingsAsyncSupplier.supply({ settingsPaths ->
val localFileSystem = LocalFileSystem.getInstance()
val settingsFiles = settingsPaths.map { Path.of(it) }
localFileSystem.refreshNioFiles(settingsFiles, projectTracker.isAsyncChangesProcessing, false) {
callback(settingsPaths)
}
}, parentDisposable)
}, parentDisposable)
}
private fun submitSettingsFilesCRCCalculation(id: Any, settingsPaths: Set<String>, callback: (Map<String, Long>) -> Unit) {
ReadAsyncSupplier.Builder { calculateSettingsFilesCRC(settingsPaths) }
.shouldKeepTasksAsynchronous { projectTracker.isAsyncChangesProcessing }
.coalesceBy(this, id)
.build(backgroundExecutor)
.supply(callback, parentDisposable)
}
fun beforeApplyChanges(listener: () -> Unit) = applyChangesOperation.beforeOperation(listener)
fun afterApplyChanges(listener: () -> Unit) = applyChangesOperation.afterOperation(listener)
init {
val projectRefreshListener = object : ExternalSystemProjectRefreshListener {
override fun beforeProjectRefresh() {
applyChangesOperation.startTask()
applyChanges()
}
override fun afterProjectRefresh(status: ExternalSystemRefreshStatus) {
applyUnknownChanges()
applyChangesOperation.finishTask()
}
}
projectAware.subscribe(projectRefreshListener, parentDisposable)
}
init {
whenNewFilesCreated(settingsAsyncSupplier::invalidate, parentDisposable)
subscribeOnDocumentsAndVirtualFilesChanges(settingsAsyncSupplier, ProjectSettingsListener(), parentDisposable)
}
companion object {
private val LOG = Logger.getInstance("#com.intellij.openapi.externalSystem.autoimport")
}
data class State(var isDirty: Boolean = true, var settingsFiles: Map<String, Long> = emptyMap())
private data class SettingsFilesStatus(
val oldCRC: Map<String, Long> = emptyMap(),
val newCRC: Map<String, Long> = emptyMap(),
override val updated: Set<String> = emptySet(),
override val created: Set<String> = emptySet(),
override val deleted: Set<String> = emptySet()
) : ExternalSystemSettingsFilesReloadContext {
constructor(CRC: Map<String, Long>) : this(oldCRC = CRC)
fun hasChanges() = updated.isNotEmpty() || created.isNotEmpty() || deleted.isNotEmpty()
}
private inner class ProjectSettingsListener : FilesChangesListener {
override fun onFileChange(path: String, modificationStamp: Long, modificationType: ModificationType) {
logModificationAsDebug(path, modificationStamp, modificationType)
if (applyChangesOperation.isOperationCompleted()) {
status.markModified(currentTime(), modificationType)
}
else {
status.markDirty(currentTime(), modificationType)
}
}
override fun apply() {
submitSettingsFilesCRCCalculation("apply") { newSettingsFilesCRC ->
val settingsFilesStatus = settingsFilesStatus.updateAndGet {
createSettingsFilesStatus(it.oldCRC, newSettingsFilesCRC)
}
if (!settingsFilesStatus.hasChanges()) {
status.markReverted(currentTime())
}
projectTracker.scheduleChangeProcessing()
}
}
private fun logModificationAsDebug(path: String, modificationStamp: Long, type: ModificationType) {
if (LOG.isDebugEnabled) {
val projectPath = projectAware.projectId.externalProjectPath
val relativePath = FileUtil.getRelativePath(projectPath, path, '/') ?: path
LOG.debug("File $relativePath is modified at ${modificationStamp} as $type")
}
}
}
private inner class SettingsFilesAsyncSupplier : AsyncSupplier<Set<String>> {
private val cachingAsyncSupplier = CachingAsyncSupplier(
BackgroundAsyncSupplier.Builder(projectAware::settingsFiles)
.shouldKeepTasksAsynchronous(projectTracker::isAsyncChangesProcessing)
.build(backgroundExecutor))
private val supplier = BackgroundAsyncSupplier.Builder(cachingAsyncSupplier)
.shouldKeepTasksAsynchronous(projectTracker::isAsyncChangesProcessing)
.build(backgroundExecutor)
override fun supply(consumer: (Set<String>) -> Unit, parentDisposable: Disposable) {
supplier.supply({ consumer(it + settingsFilesStatus.get().oldCRC.keys) }, parentDisposable)
}
fun invalidate() = cachingAsyncSupplier.invalidate()
}
} | apache-2.0 | 1fa88b4a3c6d9231804a6076b1ca0c13 | 41.967871 | 140 | 0.757151 | 5.690426 | false | false | false | false |
petuhovskiy/JValuer-CLI | src/main/kotlin/com/petukhovsky/jvaluer/cli/JValuer.kt | 1 | 10263 | package com.petukhovsky.jvaluer.cli
import com.fasterxml.jackson.annotation.JsonIgnore
import com.petukhovsky.jvaluer.JValuer
import com.petukhovsky.jvaluer.commons.builtin.JValuerBuiltin
import com.petukhovsky.jvaluer.commons.checker.Checker
import com.petukhovsky.jvaluer.commons.compiler.CompilationResult
import com.petukhovsky.jvaluer.commons.data.StringData
import com.petukhovsky.jvaluer.commons.data.TestData
import com.petukhovsky.jvaluer.commons.exe.Executable
import com.petukhovsky.jvaluer.commons.gen.Generator
import com.petukhovsky.jvaluer.commons.invoker.DefaultInvoker
import com.petukhovsky.jvaluer.commons.invoker.Invoker
import com.petukhovsky.jvaluer.commons.lang.Language
import com.petukhovsky.jvaluer.commons.lang.Languages
import com.petukhovsky.jvaluer.commons.run.*
import com.petukhovsky.jvaluer.commons.source.Source
import com.petukhovsky.jvaluer.impl.JValuerImpl
import com.petukhovsky.jvaluer.lang.LanguagesImpl
import com.petukhovsky.jvaluer.run.RunnerBuilder
import com.petukhovsky.jvaluer.run.SafeRunner
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
import java.time.Instant
class DefInvokerBuiltin(
val invoker: Invoker,
val chain: JValuerBuiltin
) : JValuerBuiltin {
override fun checker(s: String?): Checker = chain.checker(s)
override fun generator(s: String?): Generator = chain.generator(s)
override fun invoker(s: String?): Invoker = if (s == "default") invoker else chain.invoker(s)
}
class MyJValuer(
languages: Languages,
path: Path,
forceInvoker: String?
) : JValuerImpl(languages, path, null) {
val myBuiltin by lazy {
if (forceInvoker == null) super.builtin()
else {
DefInvokerBuiltin(
super.builtin()
.invoker(forceInvoker) ?: throw NullPointerException("runexe invoker not supported"),
super.builtin()
)
}
}
override fun builtin(): JValuerBuiltin = myBuiltin
override fun invokeDefault(runOptions: RunOptions?): RunInfo {
val def = myBuiltin.invoker("default") ?: throw UnsupportedOperationException("can't find default invoker")
return invoke(def, runOptions)
}
}
val jValuer by lazy {
try {
val config = jValuerConfig.get()!!
if (config.forceInvoker == null) {
JValuerImpl(langConfig.get()!!.toLanguages(), configDir.resolve("jvaluer/"), null)
} else {
MyJValuer(langConfig.get()!!.toLanguages(), configDir.resolve("jvaluer/"), config.forceInvoker)
}
} catch (e: Exception) {
println("Can't initialize jValuer. Check your config, run 'jv init' if you still haven't")
throw e
}
}
fun createRunnerBuilder(): RunnerBuilder = RunnerBuilder(jValuer).trusted(jValuerConfig.get()!!.trusted)
fun RunnerBuilder.buildSafe(path: Path, lang: Language) = this.buildSafe(path, lang.invoker())
fun RunnerBuilder.buildSafe(path: Path, invoker: Invoker) = this.buildSafe(Executable(path, invoker))!!
fun compileSrc(src: Source, liveProgress: Boolean = true, allInfo: Boolean = true): MyExecutable {
val dbSrc = dbSource(src)
val srcInfo = dbSrc.get()!!
if (srcInfo.exe != null) {
if (allInfo) println("Already compiled at ${srcInfo.compiled}")
return MyExecutable(getObject(srcInfo.exe!!), src.language.invoker(), null, true)
}
val result: CompilationResult
if (!liveProgress) {
println("Compiling...")
result = jValuer.compile(src)
} else {
result = object : LiveProcess<CompilationResult>() {
override fun update() {
val passed = (ended ?: now()) - started
val seconds = passed / 1000
val ms = passed % 1000
print("\rCompil")
if (ended == null) {
print("ing")
for (i in 0..2) print(if (i < seconds % 4) '.' else ' ')
} else {
print("ed! ")
}
print(" ")
print("[${seconds}s ${String.format("%03d", ms)}ms]")
}
override fun run(): CompilationResult = jValuer.compile(src)
}.execute()
println()
}
if (result.isSuccess) {
srcInfo.compiled = Instant.now()
srcInfo.exe = saveObject(result.exe)
dbSrc.save(srcInfo)
}
return MyExecutable(result.exe, src.language.invoker(), result, result.isSuccess)
}
fun runExe(exe: Executable,
test: TestData = StringData(""),
limits: RunLimits = RunLimits.unlimited(),
io: RunInOut = RunInOut.std(),
args: String? = null,
liveProgress: Boolean = true,
prefix: String = ""
): InvocationResult {
val runner = createRunnerBuilder().inOut(io).limits(limits).buildSafe(exe)
return runner.runLive(test, args, liveProgress, prefix = prefix)
}
fun runExe(exe: ExeInfo,
test: TestData = StringData(""),
args: String? = null,
liveProgress: Boolean = true,
allInfo: Boolean = true,
prefix: String = ""
) =
runExe(
exe.toExecutable(allInfo = allInfo, liveProgress = liveProgress)!!,
test,
exe.createLimits(),
exe.io,
args,
liveProgress,
prefix = prefix
)
fun SafeRunner.runLive(
test: TestData,
args: String? = null,
liveProgress: Boolean = true,
prefix: String = "",
ln: Boolean = true
): InvocationResult {
fun verdictSign(verdict: RunVerdict): String =
if (verdict == RunVerdict.SUCCESS) ui.okSign else ui.wrongSign
fun verdictString(verdict: RunVerdict): String =
if (verdict == RunVerdict.SUCCESS) "Ok" else verdict.toString()
val result: InvocationResult
val argsArr = if (args == null) arrayOf() else arrayOf(args)
if (!liveProgress) {
result = this.run(test, *argsArr)
} else {
result = object : LiveProcess<InvocationResult>() {
val running = listOf("\\", "|", "/", "-")
override fun update() {
val time: Long
val message: String
print("\r$prefix")
if (ended == null) {
time = now() - started
print("[${running[(time / 300).toInt() % 4]}]")
message = "Running..."
} else {
time = this.result!!.run.userTime
print("[${verdictSign(this.result!!.run.runVerdict)}]")
message = verdictString(this.result!!.run.runVerdict)
}
print(String.format(" %-13s ", message))
if (ended == null) {
print("[${RunLimits.timeString(time)}]")
} else {
val run = this.result!!.run
print(run.shortInfo)
}
}
override fun run(): InvocationResult = [email protected](test, *argsArr)
}.execute()
}
if (ln) println()
return result
}
class MyExecutable(path: Path?, invoker: Invoker?, val compilation: CompilationResult?, val compilationSuccess: Boolean) : Executable(path, invoker) {
fun exists(): Boolean = path != null && !Files.exists(path)
fun printLog() = compilation?.printLog()
}
fun CompilationResult.printLog() = println("Compilation log: $comment")
enum class FileType {
src,
exe,
auto
}
class ExeInfo(
val file: String,
val type: FileType,
val lang: String?,
val tl: String?,
val ml: String?,
val `in`: String,
val out: String
) : Script() {
fun createLimits(): RunLimits = RunLimits.of(tl, ml)
val path: Path
@JsonIgnore get() = resolve(file)
val io: RunInOut
@JsonIgnore get() = RunInOut(`in`, out)
val name: String
@JsonIgnore get() = path.fileName.toString()
fun toExecutable(
liveProgress: Boolean = true,
allInfo: Boolean = true
): MyExecutable? {
val type: FileType
val lang: Language?
when (this.type) {
FileType.auto -> {
lang = jValuer.languages.findByName(this.lang) ?: jValuer.languages.findByPath(path)
if (lang != null) {
if (allInfo) println("Detected language: ${lang.name()}")
type = FileType.src
} else {
println("Language not found. Assuming file is exe")
type = FileType.exe
}
}
FileType.exe -> {
lang = jValuer.languages.findByName(this.lang)
type = FileType.exe
}
FileType.src -> {
type = FileType.src
lang = jValuer.languages.findByName(this.lang)
if (lang == null) {
println("Language ${this.lang} not found")
println("Available languages: " + langConfig.get()!!.map(Lang::id).toString())
return null
}
}
}
assert(type != FileType.auto) { "Wat, report to GitHub." }
val exe: MyExecutable
if (type == FileType.src) {
exe = compileSrc(Source(path, lang), allInfo = allInfo, liveProgress = liveProgress)
exe.printLog()
if (!exe.compilationSuccess) {
println("Compilation failed")
return null
}
} else {
exe = MyExecutable(path, if (lang == null) DefaultInvoker() else lang.invoker(), null, true)
}
return exe
}
override fun execute() {
toExecutable()
}
}
fun TestData.copyIfNotNull(path: Path?) {
Files.copy(this.path, path ?: return, StandardCopyOption.REPLACE_EXISTING)
}
fun InvocationResult.isSuccess() = this.run.runVerdict == RunVerdict.SUCCESS
fun InvocationResult.notSuccess() = !this.isSuccess()
val RunInfo.shortInfo: String
get() = "[$timeString; $memoryString]" | mit | 8d7e3a9fbcaafcdfac40d2fadc27faa5 | 33.213333 | 150 | 0.586086 | 4.503291 | false | false | false | false |
jwren/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ModifiableRootModelBridgeImpl.kt | 1 | 28162 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots
import com.intellij.configurationStore.serializeStateInto
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.*
import com.intellij.openapi.roots.impl.ModuleOrderEnumerator
import com.intellij.openapi.roots.impl.RootConfigurationAccessor
import com.intellij.openapi.roots.impl.RootModelBase.CollectDependentModules
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryTable
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.ArrayUtilRt
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.getInstance
import com.intellij.workspaceModel.ide.impl.legacyBridge.LegacyBridgeModifiableBase
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridge
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridgeImpl
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryNameGenerator
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleEntity
import com.intellij.workspaceModel.ide.legacyBridge.ModifiableRootModelBridge
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.ide.legacyBridge.ModuleExtensionBridge
import com.intellij.workspaceModel.storage.CachedValue
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jdom.Element
import org.jetbrains.jps.model.module.JpsModuleSourceRoot
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import java.util.concurrent.ConcurrentHashMap
internal class ModifiableRootModelBridgeImpl(
diff: WorkspaceEntityStorageBuilder,
override val moduleBridge: ModuleBridge,
override val accessor: RootConfigurationAccessor,
cacheStorageResult: Boolean = true
) : LegacyBridgeModifiableBase(diff, cacheStorageResult), ModifiableRootModelBridge, ModuleRootModelBridge {
/*
We save the module entity for the following case:
- Modifiable model created
- module disposed
- modifiable model used
This case can appear, for example, during maven import
moduleEntity would be removed from this diff after module disposing
*/
private var savedModuleEntity: ModuleEntity
init {
savedModuleEntity = getModuleEntity(entityStorageOnDiff.current, module)
?: error("Cannot find module entity for ${module.moduleEntityId}. Bridge: '$moduleBridge'. Store: $diff")
}
private fun getModuleEntity(current: WorkspaceEntityStorage, myModuleBridge: ModuleBridge): ModuleEntity? {
// Try to get entity by module id
// In some cases this won't work. These cases can happen during maven or gradle import where we provide a general builder.
// The case: we rename the module. Since the changes not yet committed, the module will remain with the old persistentId. After that
// we try to get modifiableRootModel. In general case it would work fine because the builder will be based on main store, but
// in case of gradle/maven import we take the builder that was used for renaming. So, the old name cannot be found in the new store.
return current.resolve(myModuleBridge.moduleEntityId) ?: current.findModuleEntity(myModuleBridge)
}
override fun getModificationCount(): Long = diff.modificationCount
private val extensionsDisposable = Disposer.newDisposable()
private val virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManager.getInstance(project)
private val extensionsDelegate = lazy {
RootModelBridgeImpl.loadExtensions(storage = entityStorageOnDiff, module = module, diff = diff, writable = true,
parentDisposable = extensionsDisposable)
}
private val extensions by extensionsDelegate
private val sourceRootPropertiesMap = ConcurrentHashMap<VirtualFileUrl, JpsModuleSourceRoot>()
internal val moduleEntity: ModuleEntity
get() {
val actualModuleEntity = getModuleEntity(entityStorageOnDiff.current, module) ?: return savedModuleEntity
savedModuleEntity = actualModuleEntity
return actualModuleEntity
}
private val moduleLibraryTable = ModifiableModuleLibraryTableBridge(this)
/**
* Contains instances of OrderEntries edited via [ModifiableRootModel] interfaces; we need to keep references to them to update their indices;
* it should be used for modifications only, in order to read actual state one need to use [orderEntriesArray].
*/
private val mutableOrderEntries: ArrayList<OrderEntryBridge> by lazy {
ArrayList<OrderEntryBridge>().also { addOrderEntries(moduleEntity.dependencies, it) }
}
/**
* Provides cached value for [mutableOrderEntries] converted to an array to avoid creating array each time [getOrderEntries] is called;
* also it updates instances in [mutableOrderEntries] when underlying entities are changed via [WorkspaceModel] interface (e.g. when a
* library referenced from [LibraryOrderEntry] is renamed).
*/
private val orderEntriesArrayValue: CachedValue<Array<OrderEntry>> = CachedValue { storage ->
val dependencies = storage.findModuleEntity(module)?.dependencies ?: return@CachedValue emptyArray()
if (mutableOrderEntries.size == dependencies.size) {
//keep old instances of OrderEntries if possible (i.e. if only some properties of order entries were changes via WorkspaceModel)
for (i in mutableOrderEntries.indices) {
if (dependencies[i] != mutableOrderEntries[i].item && dependencies[i].javaClass == mutableOrderEntries[i].item.javaClass) {
mutableOrderEntries[i].item = dependencies[i]
}
}
}
else {
mutableOrderEntries.clear()
addOrderEntries(dependencies, mutableOrderEntries)
}
mutableOrderEntries.toTypedArray()
}
private val orderEntriesArray
get() = entityStorageOnDiff.cachedValue(orderEntriesArrayValue)
private fun addOrderEntries(dependencies: List<ModuleDependencyItem>, target: MutableList<OrderEntryBridge>) =
dependencies.mapIndexedTo(target) { index, item ->
RootModelBridgeImpl.toOrderEntry(item, index, this, this::updateDependencyItem)
}
private val contentEntriesImplValue: CachedValue<List<ModifiableContentEntryBridge>> = CachedValue { storage ->
val moduleEntity = storage.findModuleEntity(module) ?: return@CachedValue emptyList<ModifiableContentEntryBridge>()
val contentEntries = moduleEntity.contentRoots.sortedBy { it.url.url }.toList()
contentEntries.map {
ModifiableContentEntryBridge(
diff = diff,
contentEntryUrl = it.url,
modifiableRootModel = this
)
}
}
private fun updateDependencyItem(index: Int, transformer: (ModuleDependencyItem) -> ModuleDependencyItem) {
val oldItem = moduleEntity.dependencies[index]
val newItem = transformer(oldItem)
if (oldItem == newItem) return
diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) {
val copy = dependencies.toMutableList()
copy[index] = newItem
dependencies = copy
}
}
override val storage: WorkspaceEntityStorage
get() = entityStorageOnDiff.current
override fun getOrCreateJpsRootProperties(sourceRootUrl: VirtualFileUrl, creator: () -> JpsModuleSourceRoot): JpsModuleSourceRoot {
return sourceRootPropertiesMap.computeIfAbsent(sourceRootUrl) { creator() }
}
override fun removeCachedJpsRootProperties(sourceRootUrl: VirtualFileUrl) {
sourceRootPropertiesMap.remove(sourceRootUrl)
}
private val contentEntries
get() = entityStorageOnDiff.cachedValue(contentEntriesImplValue)
override fun getProject(): Project = moduleBridge.project
override fun addContentEntry(root: VirtualFile): ContentEntry =
addContentEntry(root.url)
override fun addContentEntry(url: String): ContentEntry {
assertModelIsLive()
val virtualFileUrl = virtualFileManager.fromUrl(url)
val existingEntry = contentEntries.firstOrNull { it.contentEntryUrl == virtualFileUrl }
if (existingEntry != null) {
return existingEntry
}
diff.addContentRootEntity(
module = moduleEntity,
excludedUrls = emptyList(),
excludedPatterns = emptyList(),
url = virtualFileUrl
)
// TODO It's N^2 operations since we need to recreate contentEntries every time
return contentEntries.firstOrNull { it.contentEntryUrl == virtualFileUrl }
?: error("addContentEntry: unable to find content entry after adding: $url to module ${moduleEntity.name}")
}
override fun removeContentEntry(entry: ContentEntry) {
assertModelIsLive()
val entryImpl = entry as ModifiableContentEntryBridge
val contentEntryUrl = entryImpl.contentEntryUrl
val entity = currentModel.contentEntities.firstOrNull { it.url == contentEntryUrl }
?: error("ContentEntry $entry does not belong to modifiableRootModel of module ${moduleBridge.name}")
entry.clearSourceFolders()
diff.removeEntity(entity)
if (assertChangesApplied && contentEntries.any { it.url == contentEntryUrl.url }) {
error("removeContentEntry: removed content entry url '$contentEntryUrl' still exists after removing")
}
}
override fun addOrderEntry(orderEntry: OrderEntry) {
assertModelIsLive()
when (orderEntry) {
is LibraryOrderEntryBridge -> {
if (orderEntry.isModuleLevel) {
moduleLibraryTable.addLibraryCopy(orderEntry.library as LibraryBridgeImpl, orderEntry.isExported,
orderEntry.libraryDependencyItem.scope)
}
else {
appendDependency(orderEntry.libraryDependencyItem)
}
}
is ModuleOrderEntry -> orderEntry.module?.let { addModuleOrderEntry(it) } ?: error("Module is empty: $orderEntry")
is ModuleSourceOrderEntry -> appendDependency(ModuleDependencyItem.ModuleSourceDependency)
is InheritedJdkOrderEntry -> appendDependency(ModuleDependencyItem.InheritedSdkDependency)
is ModuleJdkOrderEntry -> appendDependency((orderEntry as SdkOrderEntryBridge).sdkDependencyItem)
else -> error("OrderEntry should not be extended by external systems")
}
}
override fun addLibraryEntry(library: Library): LibraryOrderEntry {
appendDependency(ModuleDependencyItem.Exportable.LibraryDependency(
library = library.libraryId,
exported = false,
scope = ModuleDependencyItem.DependencyScope.COMPILE
))
return (mutableOrderEntries.lastOrNull() as? LibraryOrderEntry ?: error("Unable to find library orderEntry after adding"))
}
private val Library.libraryId: LibraryId
get() {
val libraryId = if (this is LibraryBridge) libraryId
else {
val libraryName = name
if (libraryName.isNullOrEmpty()) {
error("Library name is null or empty: $this")
}
LibraryId(libraryName, LibraryNameGenerator.getLibraryTableId(table.tableLevel))
}
return libraryId
}
override fun addLibraryEntries(libraries: List<Library>, scope: DependencyScope, exported: Boolean) {
val dependencyScope = scope.toEntityDependencyScope()
appendDependencies(libraries.map {
ModuleDependencyItem.Exportable.LibraryDependency(it.libraryId, exported, dependencyScope)
})
}
override fun addInvalidLibrary(name: String, level: String): LibraryOrderEntry {
val libraryDependency = ModuleDependencyItem.Exportable.LibraryDependency(
library = LibraryId(name, LibraryNameGenerator.getLibraryTableId(level)),
exported = false,
scope = ModuleDependencyItem.DependencyScope.COMPILE
)
appendDependency(libraryDependency)
return (mutableOrderEntries.lastOrNull() as? LibraryOrderEntry ?: error("Unable to find library orderEntry after adding"))
}
override fun addModuleOrderEntry(module: Module): ModuleOrderEntry {
val moduleDependency = ModuleDependencyItem.Exportable.ModuleDependency(
module = (module as ModuleBridge).moduleEntityId,
productionOnTest = false,
exported = false,
scope = ModuleDependencyItem.DependencyScope.COMPILE
)
appendDependency(moduleDependency)
return mutableOrderEntries.lastOrNull() as? ModuleOrderEntry ?: error("Unable to find module orderEntry after adding")
}
override fun addModuleEntries(modules: MutableList<Module>, scope: DependencyScope, exported: Boolean) {
val dependencyScope = scope.toEntityDependencyScope()
appendDependencies(modules.map {
ModuleDependencyItem.Exportable.ModuleDependency((it as ModuleBridge).moduleEntityId, exported, dependencyScope, productionOnTest = false)
})
}
override fun addInvalidModuleEntry(name: String): ModuleOrderEntry {
val moduleDependency = ModuleDependencyItem.Exportable.ModuleDependency(
module = ModuleId(name),
productionOnTest = false,
exported = false,
scope = ModuleDependencyItem.DependencyScope.COMPILE
)
appendDependency(moduleDependency)
return mutableOrderEntries.lastOrNull() as? ModuleOrderEntry ?: error("Unable to find module orderEntry after adding")
}
internal fun appendDependency(dependency: ModuleDependencyItem) {
mutableOrderEntries.add(RootModelBridgeImpl.toOrderEntry(dependency, mutableOrderEntries.size, this, this::updateDependencyItem))
entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue)
diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) {
dependencies = dependencies + dependency
}
}
internal fun appendDependencies(dependencies: List<ModuleDependencyItem>) {
for (dependency in dependencies) {
mutableOrderEntries.add(RootModelBridgeImpl.toOrderEntry(dependency, mutableOrderEntries.size, this, this::updateDependencyItem))
}
entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue)
diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) {
this.dependencies = this.dependencies + dependencies
}
}
internal fun insertDependency(dependency: ModuleDependencyItem, position: Int): OrderEntryBridge {
val last = position == mutableOrderEntries.size
val newEntry = RootModelBridgeImpl.toOrderEntry(dependency, position, this, this::updateDependencyItem)
if (last) {
mutableOrderEntries.add(newEntry)
}
else {
mutableOrderEntries.add(position, newEntry)
for (i in position + 1 until mutableOrderEntries.size) {
mutableOrderEntries[i].updateIndex(i)
}
}
entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue)
diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) {
dependencies = if (last) dependencies + dependency
else dependencies.subList(0, position) + dependency + dependencies.subList(position, dependencies.size)
}
return newEntry
}
internal fun removeDependencies(filter: (Int, ModuleDependencyItem) -> Boolean) {
val newDependencies = ArrayList<ModuleDependencyItem>()
val newOrderEntries = ArrayList<OrderEntryBridge>()
val oldDependencies = moduleEntity.dependencies
for (i in oldDependencies.indices) {
if (!filter(i, oldDependencies[i])) {
newDependencies.add(oldDependencies[i])
val entryBridge = mutableOrderEntries[i]
entryBridge.updateIndex(newOrderEntries.size)
newOrderEntries.add(entryBridge)
}
}
mutableOrderEntries.clear()
mutableOrderEntries.addAll(newOrderEntries)
entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue)
diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) {
dependencies = newDependencies
}
}
override fun findModuleOrderEntry(module: Module): ModuleOrderEntry? {
return orderEntries.filterIsInstance<ModuleOrderEntry>().firstOrNull { module == it.module }
}
override fun findLibraryOrderEntry(library: Library): LibraryOrderEntry? {
if (library is LibraryBridge) {
val libraryIdToFind = library.libraryId
return orderEntries
.filterIsInstance<LibraryOrderEntry>()
.firstOrNull { libraryIdToFind == (it.library as? LibraryBridge)?.libraryId }
}
else {
return orderEntries.filterIsInstance<LibraryOrderEntry>().firstOrNull { it.library == library }
}
}
override fun removeOrderEntry(orderEntry: OrderEntry) {
assertModelIsLive()
val entryImpl = orderEntry as OrderEntryBridge
val item = entryImpl.item
if (mutableOrderEntries.none { it.item == item }) {
LOG.error("OrderEntry $item does not belong to modifiableRootModel of module ${moduleBridge.name}")
return
}
if (orderEntry is LibraryOrderEntryBridge && orderEntry.isModuleLevel) {
moduleLibraryTable.removeLibrary(orderEntry.library as LibraryBridge)
}
else {
val itemIndex = entryImpl.currentIndex
removeDependencies { index, _ -> index == itemIndex }
}
}
override fun rearrangeOrderEntries(newOrder: Array<out OrderEntry>) {
val newOrderEntries = newOrder.mapTo(ArrayList()) { it as OrderEntryBridge }
val newEntities = newOrderEntries.map { it.item }
if (newEntities.toSet() != moduleEntity.dependencies.toSet()) {
error("Expected the same entities as existing order entries, but in a different order")
}
mutableOrderEntries.clear()
mutableOrderEntries.addAll(newOrderEntries)
for (i in mutableOrderEntries.indices) {
mutableOrderEntries[i].updateIndex(i)
}
entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue)
diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) {
dependencies = newEntities
}
}
override fun clear() {
for (library in moduleLibraryTable.libraries) {
moduleLibraryTable.removeLibrary(library)
}
val currentSdk = sdk
val jdkItem = currentSdk?.let { ModuleDependencyItem.SdkDependency(it.name, it.sdkType.name) }
if (moduleEntity.dependencies != listOfNotNull(jdkItem, ModuleDependencyItem.ModuleSourceDependency)) {
removeDependencies { _, _ -> true }
if (jdkItem != null) {
appendDependency(jdkItem)
}
appendDependency(ModuleDependencyItem.ModuleSourceDependency)
}
for (contentRoot in moduleEntity.contentRoots) {
diff.removeEntity(contentRoot)
}
}
fun collectChangesAndDispose(): WorkspaceEntityStorageBuilder? {
assertModelIsLive()
Disposer.dispose(moduleLibraryTable)
if (!isChanged) {
moduleLibraryTable.restoreLibraryMappingsAndDisposeCopies()
disposeWithoutLibraries()
return null
}
if (extensionsDelegate.isInitialized() && extensions.any { it.isChanged }) {
val element = Element("component")
for (extension in extensions) {
if (extension is ModuleExtensionBridge) continue
extension.commit()
if (extension is PersistentStateComponent<*>) {
serializeStateInto(extension, element)
}
else {
@Suppress("DEPRECATION")
extension.writeExternal(element)
}
}
val elementAsString = JDOMUtil.writeElement(element)
val customImlDataEntity = moduleEntity.customImlData
if (customImlDataEntity?.rootManagerTagCustomData != elementAsString) {
when {
customImlDataEntity == null && !JDOMUtil.isEmpty(element) -> diff.addModuleCustomImlDataEntity(
module = moduleEntity,
rootManagerTagCustomData = elementAsString,
customModuleOptions = emptyMap(),
source = moduleEntity.entitySource
)
customImlDataEntity == null && JDOMUtil.isEmpty(element) -> Unit
customImlDataEntity != null && customImlDataEntity.customModuleOptions.isEmpty() && JDOMUtil.isEmpty(element) ->
diff.removeEntity(customImlDataEntity)
customImlDataEntity != null && customImlDataEntity.customModuleOptions.isNotEmpty() && JDOMUtil.isEmpty(element) ->
diff.modifyEntity(ModifiableModuleCustomImlDataEntity::class.java, customImlDataEntity) {
rootManagerTagCustomData = null
}
customImlDataEntity != null && !JDOMUtil.isEmpty(element) -> diff.modifyEntity(ModifiableModuleCustomImlDataEntity::class.java,
customImlDataEntity) {
rootManagerTagCustomData = elementAsString
}
else -> error("Should not be reached")
}
}
}
if (!sourceRootPropertiesMap.isEmpty()) {
for (sourceRoot in moduleEntity.sourceRoots) {
val actualSourceRootData = sourceRootPropertiesMap[sourceRoot.url] ?: continue
SourceRootPropertiesHelper.applyChanges(diff, sourceRoot, actualSourceRootData)
}
}
disposeWithoutLibraries()
return diff
}
private fun areSourceRootPropertiesChanged(): Boolean {
if (sourceRootPropertiesMap.isEmpty()) return false
return moduleEntity.sourceRoots.any { sourceRoot ->
val actualSourceRootData = sourceRootPropertiesMap[sourceRoot.url]
actualSourceRootData != null && !SourceRootPropertiesHelper.hasEqualProperties(sourceRoot, actualSourceRootData)
}
}
override fun commit() {
val diff = collectChangesAndDispose() ?: return
val moduleDiff = module.diff
if (moduleDiff != null) {
moduleDiff.addDiff(diff)
}
else {
WorkspaceModel.getInstance(project).updateProjectModel {
it.addDiff(diff)
}
}
postCommit()
}
override fun prepareForCommit() {
collectChangesAndDispose()
}
override fun postCommit() {
moduleLibraryTable.disposeOriginalLibrariesAndUpdateCopies()
}
override fun dispose() {
disposeWithoutLibraries()
moduleLibraryTable.restoreLibraryMappingsAndDisposeCopies()
Disposer.dispose(moduleLibraryTable)
}
private fun disposeWithoutLibraries() {
if (!modelIsCommittedOrDisposed) {
Disposer.dispose(extensionsDisposable)
}
// No assertions here since it is ok to call dispose twice or more
modelIsCommittedOrDisposed = true
}
override fun getModuleLibraryTable(): LibraryTable = moduleLibraryTable
override fun setSdk(jdk: Sdk?) {
if (jdk == null) {
setSdkItem(null)
if (assertChangesApplied && sdkName != null) {
error("setSdk: expected sdkName is null, but got: $sdkName")
}
}
else {
if (ModifiableRootModelBridge.findSdk(jdk.name, jdk.sdkType.name) == null) {
error("setSdk: sdk '${jdk.name}' type '${jdk.sdkType.name}' is not registered in ProjectJdkTable")
}
setInvalidSdk(jdk.name, jdk.sdkType.name)
}
}
override fun setInvalidSdk(sdkName: String, sdkType: String) {
setSdkItem(ModuleDependencyItem.SdkDependency(sdkName, sdkType))
if (assertChangesApplied && getSdkName() != sdkName) {
error("setInvalidSdk: expected sdkName '$sdkName' but got '${getSdkName()}' after doing a change")
}
}
override fun inheritSdk() {
if (isSdkInherited) return
setSdkItem(ModuleDependencyItem.InheritedSdkDependency)
if (assertChangesApplied && !isSdkInherited) {
error("inheritSdk: Sdk is still not inherited after inheritSdk()")
}
}
// TODO compare by actual values
override fun isChanged(): Boolean {
if (!diff.isEmpty()) return true
if (extensionsDelegate.isInitialized() && extensions.any { it.isChanged }) return true
if (areSourceRootPropertiesChanged()) return true
return false
}
override fun isWritable(): Boolean = true
override fun <T : OrderEntry?> replaceEntryOfType(entryClass: Class<T>, entry: T) =
throw NotImplementedError("Not implemented since it was used only by project model implementation")
override fun getSdkName(): String? = orderEntries.filterIsInstance<JdkOrderEntry>().firstOrNull()?.jdkName
// TODO
override fun isDisposed(): Boolean = modelIsCommittedOrDisposed
private fun setSdkItem(item: ModuleDependencyItem?) {
removeDependencies { _, it -> it is ModuleDependencyItem.InheritedSdkDependency || it is ModuleDependencyItem.SdkDependency }
if (item != null) {
insertDependency(item, 0)
}
}
private val modelValue = CachedValue { storage ->
RootModelBridgeImpl(
moduleEntity = getModuleEntity(storage, moduleBridge),
storage = entityStorageOnDiff,
itemUpdater = null,
rootModel = this,
updater = { transformer -> transformer(diff) }
)
}
internal val currentModel
get() = entityStorageOnDiff.cachedValue(modelValue)
override fun getExcludeRoots(): Array<VirtualFile> = currentModel.excludeRoots
override fun orderEntries(): OrderEnumerator = ModuleOrderEnumerator(this, null)
override fun <T : Any?> getModuleExtension(klass: Class<T>): T? {
return extensions.filterIsInstance(klass).firstOrNull()
}
override fun getDependencyModuleNames(): Array<String> {
val result = orderEntries().withoutSdk().withoutLibraries().withoutModuleSourceEntries().process(CollectDependentModules(), ArrayList())
return ArrayUtilRt.toStringArray(result)
}
override fun getModule(): ModuleBridge = moduleBridge
override fun isSdkInherited(): Boolean = orderEntriesArray.any { it is InheritedJdkOrderEntry }
override fun getOrderEntries(): Array<OrderEntry> = orderEntriesArray
override fun getSourceRootUrls(): Array<String> = currentModel.sourceRootUrls
override fun getSourceRootUrls(includingTests: Boolean): Array<String> = currentModel.getSourceRootUrls(includingTests)
override fun getContentEntries(): Array<ContentEntry> = contentEntries.toTypedArray()
override fun getExcludeRootUrls(): Array<String> = currentModel.excludeRootUrls
override fun <R : Any?> processOrder(policy: RootPolicy<R>, initialValue: R): R {
var result = initialValue
for (orderEntry in orderEntries) {
result = orderEntry.accept(policy, result)
}
return result
}
override fun getSdk(): Sdk? = (orderEntriesArray.find { it is JdkOrderEntry } as JdkOrderEntry?)?.jdk
override fun getSourceRoots(): Array<VirtualFile> = currentModel.sourceRoots
override fun getSourceRoots(includingTests: Boolean): Array<VirtualFile> = currentModel.getSourceRoots(includingTests)
override fun getSourceRoots(rootType: JpsModuleSourceRootType<*>): MutableList<VirtualFile> = currentModel.getSourceRoots(rootType)
override fun getSourceRoots(rootTypes: MutableSet<out JpsModuleSourceRootType<*>>): MutableList<VirtualFile> = currentModel.getSourceRoots(rootTypes)
override fun getContentRoots(): Array<VirtualFile> = currentModel.contentRoots
override fun getContentRootUrls(): Array<String> = currentModel.contentRootUrls
override fun getModuleDependencies(): Array<Module> = getModuleDependencies(true)
override fun getModuleDependencies(includeTests: Boolean): Array<Module> {
var result: MutableList<Module>? = null
for (entry in orderEntriesArray) {
if (entry is ModuleOrderEntry) {
val scope = entry.scope
if (includeTests || scope.isForProductionCompile || scope.isForProductionRuntime) {
val module = entry.module
if (module != null) {
if (result == null) {
result = ArrayList()
}
result.add(module)
}
}
}
}
return if (result.isNullOrEmpty()) Module.EMPTY_ARRAY else result.toTypedArray()
}
companion object {
private val LOG = logger<ModifiableRootModelBridgeImpl>()
}
}
| apache-2.0 | 14b84bdfbe47fc97a8b2d445f9c8906a | 39.346705 | 151 | 0.739862 | 5.573323 | false | false | false | false |
google/iosched | shared/src/main/java/com/google/samples/apps/iosched/shared/data/db/SessionFtsEntity.kt | 4 | 1989 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.shared.data.db
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Fts4
import com.google.samples.apps.iosched.model.Session
/**
* This class represents [Session] data for searching with FTS.
*
* The [ColumnInfo] name is explicitly declared to allow flexibility for renaming the data class
* properties without requiring changing the column name.
*/
@Entity(tableName = "sessionsFts")
@Fts4
data class SessionFtsEntity(
/**
* An FTS entity table always has a column named rowid that is the equivalent of an
* INTEGER PRIMARY KEY index. Therefore, an FTS entity can only have a single field
* annotated with PrimaryKey, it must be named rowid and must be of INTEGER affinity.
*
* The field can be optionally omitted in the class (as is done here),
* but can still be used in queries.
*/
/**
* Unique string identifying this session.
*/
@ColumnInfo(name = "sessionId")
val sessionId: String,
/**
* Session title.
*/
@ColumnInfo(name = "title")
val title: String,
/**
* Body of text with the session's description.
*/
@ColumnInfo(name = "description")
val description: String,
/**
* The session speaker(s), stored as a CSV String.
*/
@ColumnInfo(name = "speakers")
val speakers: String
)
| apache-2.0 | 228d930af9f462a5ffdb868629e52202 | 29.136364 | 96 | 0.695827 | 4.25 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/MediaSelectionActivity.kt | 1 | 16695 | package org.thoughtcrime.securesms.mediasend.v2
import android.animation.ValueAnimator
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.KeyEvent
import android.widget.FrameLayout
import android.widget.TextView
import androidx.activity.OnBackPressedCallback
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatDelegate
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.content.ContextCompat
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import androidx.navigation.fragment.NavHostFragment
import androidx.transition.AutoTransition
import androidx.transition.TransitionManager
import com.google.android.material.animation.ArgbEvaluatorCompat
import org.signal.core.util.BreakIteratorCompat
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.PassphraseRequiredActivity
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.emoji.EmojiEventListener
import org.thoughtcrime.securesms.contacts.paged.ContactSearchKey
import org.thoughtcrime.securesms.conversation.MessageSendType
import org.thoughtcrime.securesms.keyboard.emoji.EmojiKeyboardPageFragment
import org.thoughtcrime.securesms.keyboard.emoji.search.EmojiSearchFragment
import org.thoughtcrime.securesms.linkpreview.LinkPreviewUtil
import org.thoughtcrime.securesms.mediasend.CameraDisplay
import org.thoughtcrime.securesms.mediasend.Media
import org.thoughtcrime.securesms.mediasend.MediaSendActivityResult
import org.thoughtcrime.securesms.mediasend.v2.review.MediaReviewFragment
import org.thoughtcrime.securesms.mediasend.v2.text.TextStoryPostCreationViewModel
import org.thoughtcrime.securesms.mediasend.v2.text.send.TextStoryPostSendRepository
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.safety.SafetyNumberBottomSheet
import org.thoughtcrime.securesms.stories.Stories
import org.thoughtcrime.securesms.util.FullscreenHelper
import org.thoughtcrime.securesms.util.WindowUtil
import org.thoughtcrime.securesms.util.navigation.safeNavigate
import org.thoughtcrime.securesms.util.visible
class MediaSelectionActivity :
PassphraseRequiredActivity(),
MediaReviewFragment.Callback,
EmojiKeyboardPageFragment.Callback,
EmojiEventListener,
EmojiSearchFragment.Callback {
private var animateInShadowLayerValueAnimator: ValueAnimator? = null
private var animateInTextColorValueAnimator: ValueAnimator? = null
private var animateOutShadowLayerValueAnimator: ValueAnimator? = null
private var animateOutTextColorValueAnimator: ValueAnimator? = null
lateinit var viewModel: MediaSelectionViewModel
private val textViewModel: TextStoryPostCreationViewModel by viewModels(
factoryProducer = {
TextStoryPostCreationViewModel.Factory(TextStoryPostSendRepository())
}
)
private val destination: MediaSelectionDestination
get() = MediaSelectionDestination.fromBundle(requireNotNull(intent.getBundleExtra(DESTINATION)))
private val isStory: Boolean
get() = intent.getBooleanExtra(IS_STORY, false)
private val shareToTextStory: Boolean
get() = intent.getBooleanExtra(AS_TEXT_STORY, false)
private val draftText: CharSequence?
get() = intent.getCharSequenceExtra(MESSAGE)
override fun attachBaseContext(newBase: Context) {
delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_YES
super.attachBaseContext(newBase)
}
override fun onCreate(savedInstanceState: Bundle?, ready: Boolean) {
setContentView(R.layout.media_selection_activity)
FullscreenHelper.showSystemUI(window)
WindowUtil.setNavigationBarColor(this, 0x01000000)
WindowUtil.setStatusBarColor(window, Color.TRANSPARENT)
val sendType: MessageSendType = requireNotNull(intent.getParcelableExtra(MESSAGE_SEND_TYPE))
val initialMedia: List<Media> = intent.getParcelableArrayListExtra(MEDIA) ?: listOf()
val message: CharSequence? = if (shareToTextStory) null else draftText
val isReply: Boolean = intent.getBooleanExtra(IS_REPLY, false)
val factory = MediaSelectionViewModel.Factory(destination, sendType, initialMedia, message, isReply, isStory, MediaSelectionRepository(this))
viewModel = ViewModelProvider(this, factory)[MediaSelectionViewModel::class.java]
val textStoryToggle: ConstraintLayout = findViewById(R.id.switch_widget)
val cameraDisplay = CameraDisplay.getDisplay(this)
textStoryToggle.updateLayoutParams<FrameLayout.LayoutParams> {
bottomMargin = cameraDisplay.getToggleBottomMargin()
}
val cameraSelectedConstraintSet = ConstraintSet().apply {
clone(textStoryToggle)
}
val textSelectedConstraintSet = ConstraintSet().apply {
clone(this@MediaSelectionActivity, R.layout.media_selection_activity_text_selected_constraints)
}
val textSwitch: TextView = findViewById(R.id.text_switch)
val cameraSwitch: TextView = findViewById(R.id.camera_switch)
textSwitch.setOnClickListener {
viewModel.sendCommand(HudCommand.GoToText)
}
cameraSwitch.setOnClickListener {
viewModel.sendCommand(HudCommand.GoToCapture)
}
if (savedInstanceState == null) {
if (shareToTextStory) {
initializeTextStory()
}
cameraSwitch.isSelected = true
val navHostFragment = NavHostFragment.create(R.navigation.media)
supportFragmentManager
.beginTransaction()
.replace(R.id.fragment_container, navHostFragment, NAV_HOST_TAG)
.commitNowAllowingStateLoss()
navigateToStartDestination()
} else {
viewModel.onRestoreState(savedInstanceState)
textViewModel.restoreFromInstanceState(savedInstanceState)
}
(supportFragmentManager.findFragmentByTag(NAV_HOST_TAG) as NavHostFragment).navController.addOnDestinationChangedListener { _, d, _ ->
when (d.id) {
R.id.mediaCaptureFragment -> {
textStoryToggle.visible = canDisplayStorySwitch()
animateTextStyling(cameraSwitch, textSwitch, 200)
TransitionManager.beginDelayedTransition(textStoryToggle, AutoTransition().setDuration(200))
cameraSelectedConstraintSet.applyTo(textStoryToggle)
}
R.id.textStoryPostCreationFragment -> {
textStoryToggle.visible = canDisplayStorySwitch()
animateTextStyling(textSwitch, cameraSwitch, 200)
TransitionManager.beginDelayedTransition(textStoryToggle, AutoTransition().setDuration(200))
textSelectedConstraintSet.applyTo(textStoryToggle)
}
else -> textStoryToggle.visible = false
}
}
onBackPressedDispatcher.addCallback(OnBackPressed())
}
private fun animateTextStyling(selectedSwitch: TextView, unselectedSwitch: TextView, duration: Long) {
val offTextColor = ContextCompat.getColor(this, R.color.signal_colorOnSurface)
val onTextColor = ContextCompat.getColor(this, R.color.signal_colorSecondaryContainer)
animateInShadowLayerValueAnimator?.cancel()
animateInTextColorValueAnimator?.cancel()
animateOutShadowLayerValueAnimator?.cancel()
animateOutTextColorValueAnimator?.cancel()
animateInShadowLayerValueAnimator = ValueAnimator.ofFloat(selectedSwitch.shadowRadius, 0f).apply {
this.duration = duration
addUpdateListener { selectedSwitch.setShadowLayer(it.animatedValue as Float, 0f, 0f, Color.BLACK) }
start()
}
animateInTextColorValueAnimator = ValueAnimator.ofObject(ArgbEvaluatorCompat(), selectedSwitch.currentTextColor, onTextColor).apply {
setEvaluator(ArgbEvaluatorCompat.getInstance())
this.duration = duration
addUpdateListener { selectedSwitch.setTextColor(it.animatedValue as Int) }
start()
}
animateOutShadowLayerValueAnimator = ValueAnimator.ofFloat(unselectedSwitch.shadowRadius, 3f).apply {
this.duration = duration
addUpdateListener { unselectedSwitch.setShadowLayer(it.animatedValue as Float, 0f, 0f, Color.BLACK) }
start()
}
animateOutTextColorValueAnimator = ValueAnimator.ofObject(ArgbEvaluatorCompat(), unselectedSwitch.currentTextColor, offTextColor).apply {
setEvaluator(ArgbEvaluatorCompat.getInstance())
this.duration = duration
addUpdateListener { unselectedSwitch.setTextColor(it.animatedValue as Int) }
start()
}
}
private fun initializeTextStory() {
val message = draftText?.toString() ?: return
val firstLink = LinkPreviewUtil.findValidPreviewUrls(message).findFirst()
val firstLinkUrl = firstLink.map { it.url }.orElse(null)
val iterator = BreakIteratorCompat.getInstance()
iterator.setText(message)
val trimmedMessage = iterator.take(700).toString()
if (firstLinkUrl == message) {
textViewModel.setLinkPreview(firstLinkUrl)
} else if (firstLinkUrl != null) {
textViewModel.setLinkPreview(firstLinkUrl)
textViewModel.setBody(trimmedMessage.replace(firstLinkUrl, "").trim())
} else {
textViewModel.setBody(trimmedMessage.trim())
}
}
private fun canDisplayStorySwitch(): Boolean {
return Stories.isFeatureEnabled() &&
isCameraFirst() &&
!viewModel.hasSelectedMedia() &&
destination == MediaSelectionDestination.ChooseAfterMediaSelection
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
viewModel.onSaveState(outState)
textViewModel.saveToInstanceState(outState)
}
override fun onSentWithResult(mediaSendActivityResult: MediaSendActivityResult) {
setResult(
RESULT_OK,
Intent().apply {
putExtra(MediaSendActivityResult.EXTRA_RESULT, mediaSendActivityResult)
}
)
finish()
overridePendingTransition(R.anim.stationary, R.anim.camera_slide_to_bottom)
}
override fun onSentWithoutResult() {
val intent = Intent()
setResult(RESULT_OK, intent)
finish()
overridePendingTransition(R.anim.stationary, R.anim.camera_slide_to_bottom)
}
override fun onSendError(error: Throwable) {
if (error is UntrustedRecords.UntrustedRecordsException) {
Log.w(TAG, "Send failed due to untrusted identities.")
SafetyNumberBottomSheet
.forIdentityRecordsAndDestinations(error.untrustedRecords, error.destinations.toList())
.show(supportFragmentManager)
} else {
setResult(RESULT_CANCELED)
// TODO [alex] - Toast
Log.w(TAG, "Failed to send message.", error)
finish()
overridePendingTransition(R.anim.stationary, R.anim.camera_slide_to_bottom)
}
}
override fun onNoMediaSelected() {
Log.w(TAG, "No media selected. Exiting.")
setResult(RESULT_CANCELED)
finish()
overridePendingTransition(R.anim.stationary, R.anim.camera_slide_to_bottom)
}
override fun onPopFromReview() {
if (isCameraFirst()) {
viewModel.removeCameraFirstCapture()
}
if (!navigateToStartDestination()) {
finish()
}
}
private fun navigateToStartDestination(navHostFragment: NavHostFragment? = null): Boolean {
val hostFragment: NavHostFragment = navHostFragment ?: supportFragmentManager.findFragmentByTag(NAV_HOST_TAG) as NavHostFragment
val startDestination: Int = intent.getIntExtra(START_ACTION, -1)
return if (startDestination > 0) {
hostFragment.navController.safeNavigate(
startDestination,
Bundle().apply {
putBoolean("first", true)
}
)
true
} else {
false
}
}
private fun isCameraFirst(): Boolean = intent.getIntExtra(START_ACTION, -1) == R.id.action_directly_to_mediaCaptureFragment
override fun openEmojiSearch() {
viewModel.sendCommand(HudCommand.OpenEmojiSearch)
}
override fun onEmojiSelected(emoji: String?) {
viewModel.sendCommand(HudCommand.EmojiInsert(emoji))
}
override fun onKeyEvent(keyEvent: KeyEvent?) {
viewModel.sendCommand(HudCommand.EmojiKeyEvent(keyEvent))
}
override fun closeEmojiSearch() {
viewModel.sendCommand(HudCommand.CloseEmojiSearch)
}
private inner class OnBackPressed : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
val navController = Navigation.findNavController(this@MediaSelectionActivity, R.id.fragment_container)
if (shareToTextStory && navController.currentDestination?.id == R.id.textStoryPostCreationFragment) {
finish()
}
if (!navController.popBackStack()) {
finish()
}
}
}
companion object {
private val TAG = Log.tag(MediaSelectionActivity::class.java)
private const val NAV_HOST_TAG = "NAV_HOST"
private const val START_ACTION = "start.action"
private const val MESSAGE_SEND_TYPE = "message.send.type"
private const val MEDIA = "media"
private const val MESSAGE = "message"
private const val DESTINATION = "destination"
private const val IS_REPLY = "is_reply"
private const val IS_STORY = "is_story"
private const val AS_TEXT_STORY = "as_text_story"
@JvmStatic
fun camera(context: Context): Intent {
return camera(context, false)
}
@JvmStatic
fun camera(context: Context, isStory: Boolean): Intent {
return buildIntent(
context = context,
startAction = R.id.action_directly_to_mediaCaptureFragment,
isStory = isStory
)
}
@JvmStatic
fun camera(
context: Context,
messageSendType: MessageSendType,
recipientId: RecipientId,
isReply: Boolean
): Intent {
return buildIntent(
context = context,
startAction = R.id.action_directly_to_mediaCaptureFragment,
messageSendType = messageSendType,
destination = MediaSelectionDestination.SingleRecipient(recipientId),
isReply = isReply
)
}
@JvmStatic
fun gallery(
context: Context,
messageSendType: MessageSendType,
media: List<Media>,
recipientId: RecipientId,
message: CharSequence?,
isReply: Boolean
): Intent {
return buildIntent(
context = context,
startAction = R.id.action_directly_to_mediaGalleryFragment,
messageSendType = messageSendType,
media = media,
destination = MediaSelectionDestination.SingleRecipient(recipientId),
message = message,
isReply = isReply
)
}
@JvmStatic
fun editor(
context: Context,
messageSendType: MessageSendType,
media: List<Media>,
recipientId: RecipientId,
message: CharSequence?
): Intent {
return buildIntent(
context = context,
messageSendType = messageSendType,
media = media,
destination = MediaSelectionDestination.SingleRecipient(recipientId),
message = message
)
}
@JvmStatic
fun editor(
context: Context,
media: List<Media>,
): Intent {
return buildIntent(
context = context,
media = media
)
}
@JvmStatic
fun share(
context: Context,
messageSendType: MessageSendType,
media: List<Media>,
recipientSearchKeys: List<ContactSearchKey.RecipientSearchKey>,
message: CharSequence?,
asTextStory: Boolean
): Intent {
return buildIntent(
context = context,
messageSendType = messageSendType,
media = media,
destination = MediaSelectionDestination.MultipleRecipients(recipientSearchKeys),
message = message,
asTextStory = asTextStory,
startAction = if (asTextStory) R.id.action_directly_to_textPostCreationFragment else -1,
isStory = recipientSearchKeys.any { it.isStory }
)
}
private fun buildIntent(
context: Context,
startAction: Int = -1,
messageSendType: MessageSendType = MessageSendType.SignalMessageSendType,
media: List<Media> = listOf(),
destination: MediaSelectionDestination = MediaSelectionDestination.ChooseAfterMediaSelection,
message: CharSequence? = null,
isReply: Boolean = false,
isStory: Boolean = false,
asTextStory: Boolean = false
): Intent {
return Intent(context, MediaSelectionActivity::class.java).apply {
putExtra(START_ACTION, startAction)
putExtra(MESSAGE_SEND_TYPE, messageSendType)
putParcelableArrayListExtra(MEDIA, ArrayList(media))
putExtra(MESSAGE, message)
putExtra(DESTINATION, destination.toBundle())
putExtra(IS_REPLY, isReply)
putExtra(IS_STORY, isStory)
putExtra(AS_TEXT_STORY, asTextStory)
}
}
}
}
| gpl-3.0 | 7c4224728bb333ce7a30f9f6ca007259 | 34.221519 | 145 | 0.736388 | 5.039239 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/sealedSubClassToObject/GenerateIdentityEqualsFix.kt | 3 | 1948 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.sealedSubClassToObject
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtPsiFactory.CallableBuilder
import org.jetbrains.kotlin.psi.KtPsiFactory.CallableBuilder.Target.FUNCTION
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
class GenerateIdentityEqualsFix : LocalQuickFix {
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val klass = descriptor.psiElement.getParentOfType<KtClass>(false) ?: return
val factory = KtPsiFactory(klass)
val equalsFunction = factory.createFunction(
CallableBuilder(FUNCTION).apply {
modifier(KtTokens.OVERRIDE_KEYWORD.value)
typeParams()
name("equals")
param("other", "Any?")
returnType("Boolean")
blockBody("return this === other")
}.asString()
)
klass.addDeclaration(equalsFunction)
val hashCodeFunction = factory.createFunction(
CallableBuilder(FUNCTION).apply {
modifier(KtTokens.OVERRIDE_KEYWORD.value)
typeParams()
name("hashCode")
returnType("Int")
blockBody("return System.identityHashCode(this)")
}.asString()
)
klass.addDeclaration(hashCodeFunction)
}
override fun getFamilyName() = KotlinBundle.message("generate.identity.equals.fix.family.name")
} | apache-2.0 | 6975d3bf4ee6de99f40b80fe8372c1a5 | 41.369565 | 158 | 0.695585 | 5.086162 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/MethodCallExpression.kt | 4 | 2233 | // 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.j2k.ast
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.j2k.CodeBuilder
import org.jetbrains.kotlin.j2k.append
class MethodCallExpression(
val methodExpression: Expression,
val argumentList: ArgumentList,
val typeArguments: List<Type>,
override val isNullable: Boolean
) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, methodExpression).append(typeArguments, ", ", "<", ">")
builder.append(argumentList)
}
companion object {
fun buildNonNull(
receiver: Expression?,
methodName: String,
argumentList: ArgumentList = ArgumentList.withNoPrototype(),
typeArguments: List<Type> = emptyList(),
dotPrototype: PsiElement? = null
): MethodCallExpression = build(receiver, methodName, argumentList, typeArguments, false, dotPrototype)
fun buildNullable(
receiver: Expression?,
methodName: String,
argumentList: ArgumentList = ArgumentList.withNoPrototype(),
typeArguments: List<Type> = emptyList(),
dotPrototype: PsiElement? = null
): MethodCallExpression = build(receiver, methodName, argumentList, typeArguments, true, dotPrototype)
fun build(
receiver: Expression?,
methodName: String,
argumentList: ArgumentList,
typeArguments: List<Type>,
isNullable: Boolean,
dotPrototype: PsiElement? = null
): MethodCallExpression {
val identifier = Identifier.withNoPrototype(methodName, isNullable = false)
val methodExpression = if (receiver != null)
QualifiedExpression(receiver, identifier, dotPrototype).assignNoPrototype()
else
identifier
return MethodCallExpression(methodExpression, argumentList, typeArguments, isNullable)
}
}
}
| apache-2.0 | 1654a44775a46dfaa86d2023b45b5fc3 | 40.351852 | 158 | 0.637259 | 5.830287 | false | false | false | false |
dpisarenko/econsim-tr01 | src/main/java/cc/altruix/econsimtr01/Utils.kt | 1 | 8689 | /*
* Copyright 2012-2016 Dmitri Pisarenko
*
* WWW: http://altruix.cc
* E-Mail: [email protected]
* Skype: dp118m (voice calls must be scheduled in advance)
*
* Physical address:
*
* 4-i Rostovskii pereulok 2/1/20
* 119121 Moscow
* Russian Federation
*
* This file is part of econsim-tr01.
*
* econsim-tr01 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.
*
* econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cc.altruix.econsimtr01
import alice.tuprolog.Prolog
import cc.altruix.econsimtr01.ch03.ValidationResult
import cc.altruix.javaprologinterop.PlUtils
import net.sourceforge.plantuml.SourceStringReader
import org.fest.assertions.Assertions
import org.joda.time.DateTime
import org.joda.time.DateTimeConstants
import org.joda.time.Duration
import org.slf4j.LoggerFactory
import java.io.File
import java.util.*
/**
* @author Dmitri Pisarenko ([email protected])
* @version $Id$
* @since 1.0
*/
fun secondsToDuration(seconds: Long) = Duration(0, seconds * 1000)
fun composeHourMinuteFiringFunction(hours:Int, minutes:Int): (DateTime) -> Boolean {
val fire: (DateTime) -> Boolean = { t ->
val curHours = t.hourOfDay
val curMinutes = t.minuteOfHour
val curSeconds = t.secondOfMinute
if ((curHours > 0) && (hours > 0) && ((curHours % hours) == 0) && (curMinutes == minutes) && (curSeconds == 0)) {
true
} else if ((curHours == 0) && (hours == 0) && (curMinutes == minutes) && (curSeconds == 0)) {
true
}
else {
false
}
}
return fire
}
fun StringBuilder.newLine() {
this.append('\n')
}
fun Int.toFixedLengthString(len:Int):String {
return String.format("%0" + "$len" + "d", this)
}
fun dailyAtMidnight() = daily(0, 0)
fun daily(hour:Int, minute:Int) = {
time:DateTime ->
((time.hourOfDay == hour) && (time.minuteOfHour == minute) && (time.secondOfMinute == 0))
}
fun String.removeSingleQuotes():String {
return PlUtils.removeSingleQuotes(this)
}
fun String.toSequenceDiagramFile(file: File) {
val reader = SourceStringReader(this)
reader.generateImage(file)
}
fun Long.millisToSimulationDateTime(): DateTime {
val period = Duration(0, this).toPeriod()
val t0 = t0()
val t = t0.plus(period)
return t
}
fun Long.secondsToSimulationDateTime(): DateTime = (this * 1000L).millisToSimulationDateTime()
fun t0() = DateTime(0, 1, 1, 0, 0, 0, 0)
fun DateTime.isEqualTo(expected:DateTime) {
Assertions.assertThat(this).isEqualTo(expected)
}
fun Long.toSimulationDateTimeString():String =
this.millisToSimulationDateTime().toSimulationDateTimeString()
fun DateTime.toSimulationDateTimeString():String {
val hours = this.hourOfDay.toFixedLengthString(2)
val minutes = this.minuteOfHour.toFixedLengthString(2)
val year = this.year.toFixedLengthString(4)
val months = this.monthOfYear.toFixedLengthString(2)
val days = this.dayOfMonth.toFixedLengthString(2)
return "$year-$months-$days $hours:$minutes"
}
fun String.toPrologTheory(): Prolog {
val prolog = PlUtils.createEngine()
PlUtils.loadPrologTheoryAsText(prolog, this)
return prolog
}
fun Prolog.getResults(query:String, varName:String):List<String> {
return PlUtils.getResults(this, query, varName)
}
fun Prolog.getResults(query: String, vararg varNames:String):List<Map<String, String>> {
return PlUtils.getResults(this, query, varNames)
}
fun String?.emptyIfNull():String {
if (this == null) {
return ""
}
return this
}
fun DateTime.millisSinceT0():Long {
return this.minus(t0().millis).millis
}
fun DateTime.secondsSinceT0():Long {
return this.millisSinceT0()/1000L
}
fun DateTime.toDayOfWeekName():String {
when (this.dayOfWeek) {
DateTimeConstants.MONDAY -> return "Monday"
DateTimeConstants.TUESDAY -> return "Tuesday"
DateTimeConstants.WEDNESDAY -> return "Wednesday"
DateTimeConstants.THURSDAY -> return "Thursday"
DateTimeConstants.FRIDAY -> return "Friday"
DateTimeConstants.SATURDAY -> return "Saturday"
DateTimeConstants.SUNDAY -> return "Sunday"
}
return ""
}
fun Prolog.extractSingleDouble(query: String, varName:String):Double {
val result = PlUtils.getResults(this, query, varName)?.firstOrNull()
if (result != null) {
return result.toDouble()
}
LoggerFactory.getLogger(Prolog::class.java).error(
"Can't find double value. Query: '$query', variable: '$varName"
)
return -1.0
}
fun Prolog.extractSingleInt(query: String, varName:String):Int {
val result = PlUtils.getResults(this, query, varName)?.firstOrNull()
if (result != null) {
return result.toInt()
}
LoggerFactory.getLogger(Prolog::class.java).error(
"Can't find int value. Query: '$query', variable: '$varName"
)
return -1
}
fun getSubscriberCount(prolog: Prolog, time: Long, interactions: Int): Double {
val resId = String.format("r%02d-pc%d", (5 + interactions), interactions)
val subscriberResourceLevel =
prolog.extractSingleDouble(
"resourceLevel($time, 'list', '$resId', Val).",
"Val"
)
return subscriberResourceLevel
}
fun findAgent(id: String, agentList: List<IAgent>) =
agentList
.filter { x -> x.id().equals(id) }
.firstOrNull()
fun DateTime.isBusinessDay():Boolean = when (this.dayOfWeek) {
DateTimeConstants.SATURDAY, DateTimeConstants.SUNDAY -> false
else -> true
}
fun <T>List<T>.extractRandomElements(percentageToExtract:Double,
random:Random):List<T> {
val elementsCount = (this.size * percentageToExtract).toInt()
val processedIndices = ArrayList<Int>(elementsCount)
for (i in 1..elementsCount) {
var elemIdx = random.nextInt(this.size)
while (processedIndices.contains(elemIdx)) {
elemIdx = random.nextInt(this.size)
}
processedIndices.add(elemIdx)
}
return processedIndices.map { this.get(it) }.toList()
}
// We need to set the seed in order to always get the same random numbers
fun createRandom():java.util.Random =
java.util.Random(8682522807148012L)
fun randomEventWithProbability(probability:Double) =
Random.nextDouble() <= probability
fun createCorrectValidationResult():ValidationResult =
ValidationResult(true, "")
fun createIncorrectValidationResult(msg:String):ValidationResult =
ValidationResult(false, msg)
fun String.parseDayMonthString() : DayAndMonth {
val parts = this.split(".")
return DayAndMonth(parts[0].toInt(), parts[1].toInt())
}
fun DayAndMonth.toDateTime() : DateTime {
var day = 0L.millisToSimulationDateTime()
day = day.plusMonths(this.month - 1)
day = day.plusDays(this.day - 1)
return day
}
fun calculateBusinessDays(
start: DayAndMonth,
end: DayAndMonth
): Int {
var day = start.toDateTime()
val end = end.toDateTime()
var businessDays = 0
do {
if ((day.dayOfWeek != DateTimeConstants.SATURDAY) && (day
.dayOfWeek != DateTimeConstants.SUNDAY)) {
businessDays++
}
day = day.plusDays(1)
} while (day.isBefore(end) || day.isEqual(end))
return businessDays
}
fun DayAndMonth.toDateTime(year:Int) = DateTime(year, this.month, this.day,
0, 0)
fun DateTime.between(start:DayAndMonth, end:DayAndMonth):Boolean {
val startDateTime = start.toDateTime(this.year)
val endDateTime = end.toDateTime(this.year)
return (startDateTime.isBefore(this) || startDateTime.isEqual(this)) &&
(endDateTime.isAfter(this) || endDateTime.isEqual(this))
}
fun DateTime.evenHourAndMinute(hour:Int, minute:Int):Boolean =
(this.hourOfDay == hour) && (this.minuteOfHour == minute)
| gpl-3.0 | 8ae1ef5c277134d84d81901e4d82703f | 29.596364 | 121 | 0.654506 | 4.00046 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/file/structure/FileElementFactory.kt | 2 | 2325 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.fir.low.level.api.file.structure
import org.jetbrains.kotlin.fir.declarations.FirDeclaration
import org.jetbrains.kotlin.fir.declarations.FirFile
import org.jetbrains.kotlin.fir.declarations.FirProperty
import org.jetbrains.kotlin.fir.declarations.FirSimpleFunction
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtProperty
internal object FileElementFactory {
/**
* should be consistent with [isReanalyzableContainer]
*/
fun createFileStructureElement(
firDeclaration: FirDeclaration,
ktDeclaration: KtDeclaration,
firFile: FirFile,
): FileStructureElement = when {
ktDeclaration is KtNamedFunction && ktDeclaration.isReanalyzableContainer() -> ReanalyzableFunctionStructureElement(
firFile,
ktDeclaration,
(firDeclaration as FirSimpleFunction).symbol,
ktDeclaration.modificationStamp
)
ktDeclaration is KtProperty && ktDeclaration.isReanalyzableContainer() -> ReanalyzablePropertyStructureElement(
firFile,
ktDeclaration,
(firDeclaration as FirProperty).symbol,
ktDeclaration.modificationStamp
)
else -> NonReanalyzableDeclarationStructureElement(
firFile,
firDeclaration,
ktDeclaration,
)
}
/**
* should be consistent with [createFileStructureElement]
*/
fun isReanalyzableContainer(
ktDeclaration: KtDeclaration,
): Boolean = when (ktDeclaration) {
is KtNamedFunction -> ktDeclaration.isReanalyzableContainer()
is KtProperty -> ktDeclaration.isReanalyzableContainer()
else -> false
}
private fun KtNamedFunction.isReanalyzableContainer() =
name != null && hasExplicitTypeOrUnit
private fun KtProperty.isReanalyzableContainer() =
name != null && typeReference != null
private val KtNamedFunction.hasExplicitTypeOrUnit
get() = hasBlockBody() || typeReference != null
} | apache-2.0 | 94fd047e5478aa3ef60809c9f327bc3f | 34.784615 | 124 | 0.707097 | 5.60241 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/bolone/rp/BoloneRP_CopyOrderFileToBucket.kt | 1 | 1202 | package bolone.rp
import alraune.*
import alraune.entity.*
import aplight.GelNew
import bolone.nextOrderFileID
import vgrechka.*
class BoloneRP_CopyOrderFileToBucket(val p: Params) : Dancer<Any> {
// TODO:vgrechka b14c4503-0611-42c7-a192-fb1208c1fedd
@GelNew class Params {
var orderHandle by place<JsonizableOrderHandle>()
var fileID by place<Long>()
var toBucket by place<String>()
}
override fun dance(): Any {
clog("p", freakingToStringKotlin(p))
rpCheckAdmin()
!object : UpdateOrder(p.orderHandle.toNormal(), "Copy file #${p.fileID} to bucket `${p.toBucket}`") {
override fun specificUpdates() {
val bf = order.bucketAndFileByID(p.fileID)
val toBucket = order.bucket(p.toBucket)
toBucket.files.add(cloneViaJson(bf.file).also {
it.id = nextOrderFileID()
it.copiedFrom = new_Order_File_Reference(bucketName = bf.bucket.name, fileID = bf.file.id)})
}
override fun makeOperationData(template: Order.Operation) = new_Order_Operation_Generic(template)
}
return GenericCoolRPResult()
}
}
| apache-2.0 | 433c9848009edc36a138972e7cd45c1c | 31.486486 | 112 | 0.631448 | 3.953947 | false | false | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/openapi/client/ClientAwareComponentManager.kt | 3 | 4623 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.client
import com.intellij.codeWithMe.ClientId
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl
import com.intellij.openapi.application.Application
import com.intellij.openapi.components.ServiceDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.progress.ProgressIndicatorProvider
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.serviceContainer.PrecomputedExtensionModel
import com.intellij.serviceContainer.throwAlreadyDisposedError
import org.jetbrains.annotations.ApiStatus
import java.util.concurrent.CompletableFuture
@ApiStatus.Internal
abstract class ClientAwareComponentManager @JvmOverloads constructor(
internal val parent: ComponentManagerImpl?,
setExtensionsRootArea: Boolean = parent == null) : ComponentManagerImpl(parent, setExtensionsRootArea) {
override fun <T : Any> getService(serviceClass: Class<T>): T? {
return getFromSelfOrCurrentSession(serviceClass, true)
}
override fun <T : Any> getServiceIfCreated(serviceClass: Class<T>): T? {
return getFromSelfOrCurrentSession(serviceClass, false)
}
override fun <T : Any> getServices(serviceClass: Class<T>, includeLocal: Boolean): List<T> {
val sessionsManager = super.getService(ClientSessionsManager::class.java)!!
return sessionsManager.getSessions(includeLocal)
.mapNotNull { (it as? ClientSessionImpl)?.doGetService(serviceClass, true, false) }
}
private fun <T : Any> getFromSelfOrCurrentSession(serviceClass: Class<T>, createIfNeeded: Boolean): T? {
val fromSelf = if (createIfNeeded) {
super.getService(serviceClass)
}
else {
super.getServiceIfCreated(serviceClass)
}
if (fromSelf != null) return fromSelf
val sessionsManager = if (containerState.get() == ContainerState.DISPOSE_COMPLETED) {
if (createIfNeeded) {
throwAlreadyDisposedError(serviceClass.name, this, ProgressIndicatorProvider.getGlobalProgressIndicator())
}
super.doGetService(ClientSessionsManager::class.java, false)
}
else {
super.getService(ClientSessionsManager::class.java)
}
val session = sessionsManager?.getSession(ClientId.current) as? ClientSessionImpl
return session?.doGetService(serviceClass, createIfNeeded, false)
}
override fun registerComponents(modules: Sequence<IdeaPluginDescriptorImpl>,
app: Application?,
precomputedExtensionModel: PrecomputedExtensionModel?,
listenerCallbacks: MutableList<in Runnable>?) {
super.registerComponents(modules, app, precomputedExtensionModel, listenerCallbacks)
val sessionsManager = super.getService(ClientSessionsManager::class.java)!!
for (session in sessionsManager.getSessions(true)) {
(session as? ClientSessionImpl)?.registerComponents(modules, app, precomputedExtensionModel, listenerCallbacks)
}
}
override fun unloadServices(services: List<ServiceDescriptor>, pluginId: PluginId) {
super.unloadServices(services, pluginId)
val sessionsManager = super.getService(ClientSessionsManager::class.java)!!
for (session in sessionsManager.getSessions(true)) {
(session as? ClientSessionImpl)?.unloadServices(services, pluginId)
}
}
override fun preloadServices(modules: Sequence<IdeaPluginDescriptorImpl>,
activityPrefix: String,
onlyIfAwait: Boolean): PreloadServicesResult {
val result = super.preloadServices(modules, activityPrefix, onlyIfAwait)
val sessionsManager = super.getService(ClientSessionsManager::class.java)!!
val syncPreloadFutures = mutableListOf<CompletableFuture<*>>()
val asyncPreloadFutures = mutableListOf<CompletableFuture<*>>()
for (session in sessionsManager.getSessions(true)) {
session as? ClientSessionImpl ?: continue
val sessionResult = session.preloadServices(modules, activityPrefix, onlyIfAwait)
syncPreloadFutures.add(sessionResult.sync)
asyncPreloadFutures.add(sessionResult.async)
}
return PreloadServicesResult(
sync = CompletableFuture.allOf(result.sync, *syncPreloadFutures.toTypedArray()),
async = CompletableFuture.allOf(result.async, *asyncPreloadFutures.toTypedArray())
)
}
override fun isPreInitialized(component: Any): Boolean {
return super.isPreInitialized(component) || component is ClientSessionsManager<*>
}
} | apache-2.0 | a534451c45b58ee1acd6fbc07ad50d15 | 43.461538 | 120 | 0.748864 | 5.319908 | false | false | false | false |
jwren/intellij-community | python/src/com/jetbrains/python/sdk/PySdkRendering.kt | 1 | 5936 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.sdk
import com.intellij.icons.AllIcons
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkType
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.LayeredIcon
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.SimpleTextAttributes
import com.jetbrains.python.PyBundle
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor
import org.jetbrains.annotations.Nls
import javax.swing.Icon
val noInterpreterMarker: String = "<${PyBundle.message("python.sdk.there.is.no.interpreter")}>"
fun name(sdk: Sdk): Triple<String?, String, String?> = name(sdk, sdk.name)
/**
* Returns modifier that shortly describes that is wrong with passed [sdk], [name] and additional info.
*/
fun name(sdk: Sdk, name: String): Triple<String?, String, String?> {
val modifier = when {
PythonSdkUtil.isInvalid(sdk) || PythonSdkType.hasInvalidRemoteCredentials(sdk) -> "invalid"
PythonSdkType.isIncompleteRemote(sdk) -> "incomplete"
!LanguageLevel.SUPPORTED_LEVELS.contains(PythonSdkType.getLanguageLevelForSdk(sdk)) -> "unsupported"
else -> null
}
val providedForSdk = PySdkProvider.EP_NAME.extensions.firstNotNullOfOrNull { it.getSdkAdditionalText(sdk) }
val secondary = providedForSdk ?: if (PythonSdkType.isRunAsRootViaSudo(sdk)) "[sudo]" else null
return Triple(modifier, name, secondary)
}
/**
* Returns a path to be rendered as the sdk's path.
*
* Initial value is taken from the [sdk],
* then it is converted to a path relative to the user home directory.
*
* Returns null if the initial path or the relative value are presented in the sdk's name.
*
* @see FileUtil.getLocationRelativeToUserHome
*/
fun path(sdk: Sdk): String? {
val name = sdk.name
val homePath = sdk.homePath ?: return null
if (sdk.isTargetBased()) {
return homePath.removePrefix("target://")
}
if (sdk.sdkAdditionalData is PyRemoteSdkAdditionalDataMarker) {
return homePath.takeIf { homePath !in name }
}
return homePath.let { FileUtil.getLocationRelativeToUserHome(it) }.takeIf { homePath !in name && it !in name }
}
/**
* Returns an icon to be used as the sdk's icon.
*
* Result is wrapped with [AllIcons.Actions.Cancel]
* if the sdk is local and does not exist, or remote and incomplete or has invalid credentials, or is not supported.
*
* @see PythonSdkUtil.isInvalid
* @see PythonSdkType.isIncompleteRemote
* @see PythonSdkType.hasInvalidRemoteCredentials
* @see LanguageLevel.SUPPORTED_LEVELS
*/
fun icon(sdk: Sdk): Icon? {
val flavor: PythonSdkFlavor? = when (sdk.sdkAdditionalData) {
!is PyRemoteSdkAdditionalDataMarker -> PythonSdkFlavor.getPlatformIndependentFlavor(sdk.homePath)
else -> null
}
val icon = flavor?.icon ?: ((sdk.sdkType as? SdkType)?.icon ?: return null)
val providedIcon = PySdkProvider.EP_NAME.extensions.firstNotNullOfOrNull { it.getSdkIcon(sdk) }
return when {
PythonSdkUtil.isInvalid(sdk) ||
PythonSdkType.isIncompleteRemote(sdk) ||
PythonSdkType.hasInvalidRemoteCredentials(sdk) ||
!LanguageLevel.SUPPORTED_LEVELS.contains(PythonSdkType.getLanguageLevelForSdk(sdk)) ->
wrapIconWithWarningDecorator(icon)
sdk is PyDetectedSdk -> IconLoader.getTransparentIcon(icon)
providedIcon != null -> providedIcon
else -> icon
}
}
/**
* Groups valid sdks associated with the [module] by types.
* Virtual environments, pipenv and conda environments are considered as [PyRenderedSdkType.VIRTUALENV].
* Remote interpreters are considered as [PyRenderedSdkType.REMOTE].
* All the others are considered as [PyRenderedSdkType.SYSTEM].
*
* @see Sdk.isAssociatedWithAnotherModule
* @see PythonSdkUtil.isVirtualEnv
* @see PythonSdkUtil.isCondaVirtualEnv
* @see PythonSdkUtil.isRemote
* @see PyRenderedSdkType
*/
fun groupModuleSdksByTypes(allSdks: List<Sdk>, module: Module?, invalid: (Sdk) -> Boolean): Map<PyRenderedSdkType, List<Sdk>> {
return allSdks
.asSequence()
.filter { !it.isAssociatedWithAnotherModule(module) && !invalid(it) }
.groupBy {
when {
PythonSdkUtil.isVirtualEnv(it) || PythonSdkUtil.isCondaVirtualEnv(it) -> PyRenderedSdkType.VIRTUALENV
PythonSdkUtil.isRemote(it) -> PyRenderedSdkType.REMOTE
else -> PyRenderedSdkType.SYSTEM
}
}
}
/**
* Order is important, sdks are rendered in the same order as the types are defined.
*
* @see groupModuleSdksByTypes
*/
enum class PyRenderedSdkType {
VIRTUALENV, SYSTEM, REMOTE
}
private fun wrapIconWithWarningDecorator(icon: Icon): LayeredIcon =
LayeredIcon(2).apply {
setIcon(icon, 0)
setIcon(AllIcons.Actions.Cancel, 1)
}
internal fun SimpleColoredComponent.customizeWithSdkValue(value: Any?, nullSdkName: @Nls String, nullSdkValue: Sdk?) {
when (value) {
is PySdkToInstall -> {
value.renderInList(this)
}
is Sdk -> {
appendName(value, name(value))
icon = icon(value)
}
is String -> append(value)
null -> {
if (nullSdkValue != null) {
appendName(nullSdkValue, name(nullSdkValue, nullSdkName))
icon = icon(nullSdkValue)
}
else {
append(nullSdkName)
}
}
}
}
private fun SimpleColoredComponent.appendName(sdk: Sdk, name: Triple<String?, String, String?>) {
val (modifier, primary, secondary) = name
if (modifier != null) {
append("[$modifier] $primary", SimpleTextAttributes.ERROR_ATTRIBUTES)
}
else {
append(primary)
}
if (secondary != null) {
append(" $secondary", SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES)
}
path(sdk)?.let { append(" $it", SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES) }
} | apache-2.0 | bb1ef233526d291b8bf52eb9fd20c90f | 33.317919 | 140 | 0.730627 | 4.276657 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/runtime/text/string_builder0.kt | 2 | 10973 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.text.string_builder0
import kotlin.test.*
// Utils ====================================================================================================
fun assertTrue(cond: Boolean) {
if (!cond)
throw AssertionError("Condition expected to be true")
}
fun assertFalse(cond: Boolean) {
if (cond)
throw AssertionError("Condition expected to be false")
}
fun assertEquals(value1: String, value2: String) {
if (value1 != value2)
throw AssertionError("FAIL: '" + value1 + "' != '" + value2 + "'")
}
fun assertEquals(value1: Int, value2: Int) {
if (value1 != value2)
throw AssertionError("FAIL" + value1.toString() + " != " + value2.toString())
}
fun assertEquals(builder: StringBuilder, content: String) = assertEquals(builder.toString(), content)
// IndexOutOfBoundsException.
fun assertException(body: () -> Unit) {
try {
body()
throw AssertionError ("Test failed: no IndexOutOfBoundsException on wrong indices")
} catch (e: IndexOutOfBoundsException) {
} catch (e: IllegalArgumentException) {}
}
// Insert ===================================================================================================
fun testInsertString(initial: String, index: Int, toInsert: String, expected: String) {
assertEquals(StringBuilder(initial).insert(index, toInsert), expected)
assertEquals(StringBuilder(initial).insert(index, toInsert.toCharArray()), expected)
assertEquals(StringBuilder(initial).insert(index, toInsert as CharSequence), expected)
}
fun testInsertStringException(initial: String, index: Int, toInsert: String) {
assertException { StringBuilder(initial).insert(index, toInsert) }
assertException { StringBuilder(initial).insert(index, toInsert.toCharArray()) }
assertException { StringBuilder(initial).insert(index, toInsert as CharSequence) }
}
fun testInsertSingle(value: Byte) {
assertEquals(StringBuilder("abcd").insert(0, value), value.toString() + "abcd")
assertEquals(StringBuilder("abcd").insert(4, value), "abcd" + value.toString())
assertEquals(StringBuilder("abcd").insert(2, value), "ab" + value.toString() + "cd")
assertEquals(StringBuilder("").insert(0, value), value.toString())
}
fun testInsertSingle(value: Short) {
assertEquals(StringBuilder("abcd").insert(0, value), value.toString() + "abcd")
assertEquals(StringBuilder("abcd").insert(4, value), "abcd" + value.toString())
assertEquals(StringBuilder("abcd").insert(2, value), "ab" + value.toString() + "cd")
assertEquals(StringBuilder("").insert(0, value), value.toString())
}
fun testInsertSingle(value: Int) {
assertEquals(StringBuilder("abcd").insert(0, value), value.toString() + "abcd")
assertEquals(StringBuilder("abcd").insert(4, value), "abcd" + value.toString())
assertEquals(StringBuilder("abcd").insert(2, value), "ab" + value.toString() + "cd")
assertEquals(StringBuilder("").insert(0, value), value.toString())
}
fun testInsertSingle(value: Long) {
assertEquals(StringBuilder("abcd").insert(0, value), value.toString() + "abcd")
assertEquals(StringBuilder("abcd").insert(4, value), "abcd" + value.toString())
assertEquals(StringBuilder("abcd").insert(2, value), "ab" + value.toString() + "cd")
assertEquals(StringBuilder("").insert(0, value), value.toString())
}
fun testInsertSingle(value: Float) {
assertEquals(StringBuilder("abcd").insert(0, value), value.toString() + "abcd")
assertEquals(StringBuilder("abcd").insert(4, value), "abcd" + value.toString())
assertEquals(StringBuilder("abcd").insert(2, value), "ab" + value.toString() + "cd")
assertEquals(StringBuilder("").insert(0, value), value.toString())
}
fun testInsertSingle(value: Double) {
assertEquals(StringBuilder("abcd").insert(0, value), value.toString() + "abcd")
assertEquals(StringBuilder("abcd").insert(4, value), "abcd" + value.toString())
assertEquals(StringBuilder("abcd").insert(2, value), "ab" + value.toString() + "cd")
assertEquals(StringBuilder("").insert(0, value), value.toString())
}
fun testInsertSingle(value: Any?) {
assertEquals(StringBuilder("abcd").insert(0, value), value.toString() + "abcd")
assertEquals(StringBuilder("abcd").insert(4, value), "abcd" + value.toString())
assertEquals(StringBuilder("abcd").insert(2, value), "ab" + value.toString() + "cd")
assertEquals(StringBuilder("").insert(0, value), value.toString())
}
fun testInsertSingle(value: Char) {
assertEquals(StringBuilder("abcd").insert(0, value), value.toString() + "abcd")
assertEquals(StringBuilder("abcd").insert(4, value), "abcd" + value.toString())
assertEquals(StringBuilder("abcd").insert(2, value), "ab" + value.toString() + "cd")
assertEquals(StringBuilder("").insert(0, value), value.toString())
}
fun testInsert() {
// String/CharSequence/CharArray.
testInsertString("abcd", 0, "12", "12abcd")
testInsertString("abcd", 4, "12", "abcd12")
testInsertString("abcd", 2, "12", "ab12cd")
testInsertString("", 0, "12", "12")
testInsertStringException("a", -1, "1")
testInsertStringException("a", 2, "1")
// Null inserting.
assertEquals(StringBuilder("abcd").insert(0, null as CharSequence?), "nullabcd")
assertEquals(StringBuilder("abcd").insert(4, null as CharSequence?), "abcdnull")
assertEquals(StringBuilder("abcd").insert(2, null as CharSequence?), "abnullcd")
assertEquals(StringBuilder("").insert(0, null as CharSequence?), "null")
// Subsequence of CharSequence.
// Insert in the beginning.
assertEquals(StringBuilder("abcd").insert(0, "1234", 0, 0), "abcd") // 0 symbols
assertEquals(StringBuilder("abcd").insert(0, "1234", 0, 1), "1abcd") // 1 symbol
assertEquals(StringBuilder("abcd").insert(0, "1234", 1, 3), "23abcd") // 2 symbols
assertEquals(StringBuilder("abcd").insert(0, null as CharSequence?, 1, 3), "ulabcd") // 2 symbols of null
// Insert in the end.
assertEquals(StringBuilder("abcd").insert(4, "1234", 0, 0), "abcd")
assertEquals(StringBuilder("abcd").insert(4, "1234", 0, 1), "abcd1")
assertEquals(StringBuilder("abcd").insert(4, "1234", 1, 3), "abcd23")
assertEquals(StringBuilder("abcd").insert(4, null as CharSequence?, 1, 3), "abcdul")
// Insert in the middle.
assertEquals(StringBuilder("abcd").insert(2, "1234", 0, 0), "abcd")
assertEquals(StringBuilder("abcd").insert(2, "1234", 0, 1), "ab1cd")
assertEquals(StringBuilder("abcd").insert(2, "1234", 1, 3), "ab23cd")
assertEquals(StringBuilder("abcd").insert(2, null as CharSequence?, 1, 3), "abulcd")
// Incorrect indices.
assertException { StringBuilder("a").insert(-1, "1", 0, 0) }
assertException { StringBuilder("a").insert(2, "1", 0, 0) }
assertException { StringBuilder("a").insert(1, "1", -1, 0) }
assertException { StringBuilder("a").insert(1, "1", 0, 2) }
assertException { StringBuilder("a").insert(1, "123", 2, 0) }
// Other types.
testInsertSingle(true)
testInsertSingle(42.toByte())
testInsertSingle(42.toShort())
testInsertSingle(42.toInt())
testInsertSingle(42.toLong())
testInsertSingle(42.2.toFloat())
testInsertSingle(42.2.toDouble())
testInsertSingle(object {
override fun toString(): String {
return "Object"
}
})
testInsertSingle('a')
}
// Reverse ==================================================================================================
fun testReverse(original: String, reversed: String, reversedBack: String) {
assertEquals(StringBuilder(original).reverse(), reversed)
assertEquals(StringBuilder(reversed).reverse(), reversedBack)
}
fun testReverse() {
var builder = StringBuilder("123456")
assertTrue(builder === builder.reverse())
assertEquals(builder, "654321")
builder.setLength(1)
assertEquals(builder, "6")
builder.setLength(0)
assertEquals(builder, "")
var str: String = "a"
testReverse(str, str, str)
str = "ab"
testReverse(str, "ba", str)
str = "abcdef"
testReverse(str, "fedcba", str)
str = "abcdefg"
testReverse(str, "gfedcba", str)
str = "\ud800\udc00"
testReverse(str, str, str)
str = "\udc00\ud800"
testReverse(str, "\ud800\udc00", "\ud800\udc00")
str = "a\ud800\udc00"
testReverse(str, "\ud800\udc00a", str)
str = "ab\ud800\udc00"
testReverse(str, "\ud800\udc00ba", str)
str = "abc\ud800\udc00"
testReverse(str, "\ud800\udc00cba", str)
str = "\ud800\udc00\udc01\ud801\ud802\udc02"
testReverse(str, "\ud802\udc02\ud801\udc01\ud800\udc00",
"\ud800\udc00\ud801\udc01\ud802\udc02")
str = "\ud800\udc00\ud801\udc01\ud802\udc02"
testReverse(str, "\ud802\udc02\ud801\udc01\ud800\udc00", str)
str = "\ud800\udc00\udc01\ud801a"
testReverse(str, "a\ud801\udc01\ud800\udc00",
"\ud800\udc00\ud801\udc01a")
str = "a\ud800\udc00\ud801\udc01"
testReverse(str, "\ud801\udc01\ud800\udc00a", str)
str = "\ud800\udc00\udc01\ud801ab"
testReverse(str, "ba\ud801\udc01\ud800\udc00",
"\ud800\udc00\ud801\udc01ab")
str = "ab\ud800\udc00\ud801\udc01"
testReverse(str, "\ud801\udc01\ud800\udc00ba", str)
str = "\ud800\udc00\ud801\udc01"
testReverse(str, "\ud801\udc01\ud800\udc00", str)
str = "a\ud800\udc00z\ud801\udc01"
testReverse(str, "\ud801\udc01z\ud800\udc00a", str)
str = "a\ud800\udc00bz\ud801\udc01"
testReverse(str, "\ud801\udc01zb\ud800\udc00a", str)
str = "abc\ud802\udc02\ud801\udc01\ud800\udc00"
testReverse(str, "\ud800\udc00\ud801\udc01\ud802\udc02cba", str)
str = "abcd\ud802\udc02\ud801\udc01\ud800\udc00"
testReverse(str, "\ud800\udc00\ud801\udc01\ud802\udc02dcba", str)
}
// Basic ====================================================================================================
fun testBasic() {
val sb = StringBuilder()
assertEquals(0, sb.length)
assertEquals("", sb.toString())
sb.append(1)
assertEquals(1, sb.length)
assertEquals("1", sb.toString())
sb.append(", ")
assertEquals(3, sb.length)
assertEquals("1, ", sb.toString())
sb.append(true)
assertEquals(7, sb.length)
assertEquals("1, true", sb.toString())
sb.append(12345678L)
assertEquals(15, sb.length)
assertEquals("1, true12345678", sb.toString())
sb.append(null as CharSequence?)
assertEquals(19, sb.length)
assertEquals("1, true12345678null", sb.toString())
sb.setLength(0)
assertEquals(0, sb.length)
assertEquals("", sb.toString())
}
@Test fun runTest() {
testBasic()
testInsert()
testReverse()
println("OK")
} | apache-2.0 | 7974fabad5704665fc438250fc6de8c7 | 38.192857 | 111 | 0.636562 | 3.741221 | false | true | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/planner/steps/host/startup/WakeHostExecutor.kt | 2 | 2129 | package com.github.kerubistan.kerub.planner.steps.host.startup
import com.github.kerubistan.kerub.data.dynamic.HostDynamicDao
import com.github.kerubistan.kerub.host.HostManager
import com.github.kerubistan.kerub.host.lom.WakeOnLan
import com.github.kerubistan.kerub.model.Host
import com.github.kerubistan.kerub.model.dynamic.HostStatus
import com.github.kerubistan.kerub.planner.execution.AbstractStepExecutor
import com.github.kerubistan.kerub.utils.getLogger
open class WakeHostExecutor(
private val hostManager: HostManager,
private val hostDynDao: HostDynamicDao,
private val tries: Int = defaultMaxRetries,
private val wait: Long = defaultWaitBetweenTries
) : AbstractStepExecutor<AbstractWakeHost, Unit>() {
companion object {
private val logger = getLogger()
private const val defaultMaxRetries = 8
private const val defaultWaitBetweenTries = 30000.toLong()
}
override fun perform(step: AbstractWakeHost) {
var lastException: Exception? = null
for (nr in 0..tries) {
if (hostDynDao[step.host.id]?.status == HostStatus.Up) {
//host connected
return
}
try {
logger.debug("attempt {} - waking host {} {}", nr, step.host.address, step.host.id)
when (step) {
is WolWakeHost -> {
wakeOnLoan(step.host)
}
else -> TODO()
}
logger.debug("attempt {} - connecting host {} {}", nr, step.host.address, step.host.id)
hostManager.connectHost(step.host)
logger.debug("attempt {} - host {} {} connected", nr, step.host.address, step.host.id)
return
} catch (e: Exception) {
logger.debug("attempt {} - connecting {} {}: failed - waiting {} ms before retry",
nr, step.host.address, step.host.id, wait)
Thread.sleep(wait)
lastException = e
}
}
throw WakeHostException(
"Could not connect host ${step.host.address} ${step.host.id} in $defaultMaxRetries attempts",
lastException)
}
internal open fun wakeOnLoan(host: Host) {
WakeOnLan(host).on()
}
override fun update(step: AbstractWakeHost, updates: Unit) {
hostDynDao.update(step.host.id) { dyn ->
dyn.copy(
status = HostStatus.Up
)
}
}
} | apache-2.0 | 1bce31ad9ff0da9080c79776877f2dde | 30.791045 | 97 | 0.710193 | 3.433871 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/propertyFiles/propertyUsages.1.kt | 12 | 1088 | import org.jetbrains.annotations.PropertyKey
fun message(@PropertyKey(resourceBundle = "propertyUsages.0") key: String) = key
infix fun String.infixMessage(@PropertyKey(resourceBundle = "propertyUsages.0") key: String) = key
infix fun @receiver:PropertyKey(resourceBundle = "propertyUsages.0") String.infixMessage2(s: String) = this
operator fun @receiver:PropertyKey(resourceBundle = "propertyUsages.0") String.unaryMinus() = this
operator fun Int.get(@PropertyKey(resourceBundle = "propertyUsages.0") key: String) = this
operator fun @receiver:PropertyKey(resourceBundle = "propertyUsages.0") String.get(s: String) = this
fun test() {
@PropertyKey(resourceBundle = "propertyUsages.0") val s1 = "foo.bar"
@PropertyKey(resourceBundle = "propertyUsages.0") val s2 = "foo.baz"
message("foo.bar")
message("foo.baz")
"test" infixMessage "foo.bar"
"foo.bar" infixMessage "test"
"foo.bar" infixMessage2 "test"
"test" infixMessage2 "foo.bar"
"foo.bar".infixMessage2("test")
-"foo.bar"
1["foo.bar"]
"foo.bar"["test"]
"test"["foo.bar"]
} | apache-2.0 | 03f64c72ac56476610fe5a005e72c1e4 | 35.3 | 107 | 0.712316 | 3.602649 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/test/testData/evaluation/multipleBreakpoints/extensionMemberProperty.kt | 13 | 2909 | package extensionMemberProperty
fun main(args: Array<String>) {
MemberClass().testMember(ExtClass())
MemberClass.testCompanion(ExtClass())
}
class MemberClass {
fun testMember(extClass: ExtClass) {
// EXPRESSION: extClass.testPublic
// RESULT: 1: I
//Breakpoint!
extClass.testPublic
with(extClass) {
// EXPRESSION: testPublic
// RESULT: 1: I
//Breakpoint!
testPublic
}
// EXPRESSION: extClass.testPrivate
// RESULT: 1: I
//Breakpoint!
extClass.testPrivate
with(extClass) {
// EXPRESSION: testPrivate
// RESULT: 1: I
//Breakpoint!
testPrivate
}
extClass.testExtMember()
}
fun ExtClass.testExtMember() {
// EXPRESSION: testPublic
// RESULT: 1: I
//Breakpoint!
testPublic
// EXPRESSION: this.testPublic
// RESULT: 1: I
//Breakpoint!
this.testPublic
// EXPRESSION: testPrivate
// RESULT: 1: I
//Breakpoint!
testPrivate
// EXPRESSION: this.testPrivate
// RESULT: 1: I
//Breakpoint!
this.testPrivate
}
public val ExtClass.testPublic: Int
get() = a
private val ExtClass.testPrivate: Int
get() = a
companion object {
public val ExtClass.testCompPublic: Int
get() = a
private val ExtClass.testCompPrivate: Int
get() = a
fun testCompanion(extClass: ExtClass) {
// EXPRESSION: extClass.testCompPublic
// RESULT: 1: I
//Breakpoint!
extClass.testCompPublic
with(extClass) {
// EXPRESSION: testCompPublic
// RESULT: 1: I
//Breakpoint!
testCompPublic
}
// EXPRESSION: extClass.testCompPrivate
// RESULT: 1: I
//Breakpoint!
extClass.testCompPrivate
with(extClass) {
// EXPRESSION: testCompPrivate
// RESULT: 1: I
//Breakpoint!
testCompPrivate
}
extClass.testExtCompanion()
}
fun ExtClass.testExtCompanion() {
// EXPRESSION: testCompPublic
// RESULT: 1: I
//Breakpoint!
testCompPublic
// EXPRESSION: this.testCompPublic
// RESULT: 1: I
//Breakpoint!
this.testCompPublic
// EXPRESSION: testCompPrivate
// RESULT: 1: I
//Breakpoint!
testCompPrivate
// EXPRESSION: this.testCompPrivate
// RESULT: 1: I
//Breakpoint!
this.testCompPrivate
}
}
}
class ExtClass {
val a = 1
} | apache-2.0 | d628fac8e96eaf55712a6071413cda01 | 22.467742 | 51 | 0.501547 | 5.437383 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinCreateTestIntention.kt | 2 | 10680 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.testIntegration
import com.intellij.CommonBundle
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInsight.navigation.NavigationUtil
import com.intellij.ide.util.PropertiesComponent
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScopesCore
import com.intellij.psi.util.PsiUtil
import com.intellij.testIntegration.createTest.CreateTestAction
import com.intellij.testIntegration.createTest.CreateTestUtils.computeTestRoots
import com.intellij.testIntegration.createTest.TestGenerators
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.findFacadeClass
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.actions.JavaToKotlinAction
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.getPackage
import org.jetbrains.kotlin.idea.core.util.toPsiDirectory
import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.j2k.j2k
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.idea.util.runWhenSmart
import org.jetbrains.kotlin.idea.util.runWithAlternativeResolveEnabled
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.hasExpectModifier
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class KotlinCreateTestIntention : SelfTargetingRangeIntention<KtNamedDeclaration>(
KtNamedDeclaration::class.java,
KotlinBundle.lazyMessage("create.test")
) {
override fun applicabilityRange(element: KtNamedDeclaration): TextRange? {
if (element.hasExpectModifier() || element.nameIdentifier == null) return null
if (ModuleUtilCore.findModuleForPsiElement(element) == null) return null
if (element is KtClassOrObject) {
if (element.isLocal) return null
if (element is KtEnumEntry) return null
if (element is KtClass && (element.isAnnotation() || element.isInterface())) return null
if (element.resolveToDescriptorIfAny() == null) return null
val virtualFile = PsiUtil.getVirtualFile(element)
if (virtualFile == null ||
ProjectRootManager.getInstance(element.project).fileIndex.isInTestSourceContent(virtualFile)) return null
return TextRange(
element.startOffset,
element.getSuperTypeList()?.startOffset ?: element.body?.startOffset ?: element.endOffset
)
}
if (element.parent !is KtFile) return null
if (element is KtNamedFunction) {
return TextRange((element.funKeyword ?: element.nameIdentifier!!).startOffset, element.nameIdentifier!!.endOffset)
}
if (element is KtProperty) {
if (element.getter == null && element.delegate == null) return null
return TextRange(element.valOrVarKeyword.startOffset, element.nameIdentifier!!.endOffset)
}
return null
}
override fun startInWriteAction() = false
override fun applyTo(element: KtNamedDeclaration, editor: Editor?) {
if (editor == null) throw IllegalArgumentException("This intention requires an editor")
val lightClass = when (element) {
is KtClassOrObject -> element.toLightClass()
else -> element.containingKtFile.findFacadeClass()
} ?: return
object : CreateTestAction() {
// Based on the com.intellij.testIntegration.createTest.JavaTestGenerator.createTestClass()
private fun findTestClass(targetDirectory: PsiDirectory, className: String): PsiClass? {
val psiPackage = targetDirectory.getPackage() ?: return null
val scope = GlobalSearchScopesCore.directoryScope(targetDirectory, false)
val klass = psiPackage.findClassByShortName(className, scope).firstOrNull() ?: return null
if (!FileModificationService.getInstance().preparePsiElementForWrite(klass)) return null
return klass
}
private fun getTempJavaClassName(project: Project, kotlinFile: VirtualFile): String {
val baseName = kotlinFile.nameWithoutExtension
val psiDir = kotlinFile.parent!!.toPsiDirectory(project)!!
return generateSequence(0) { it + 1 }
.map { "$baseName$it" }
.first { psiDir.findFile("$it.java") == null && findTestClass(psiDir, it) == null }
}
// Based on the com.intellij.testIntegration.createTest.CreateTestAction.CreateTestAction.invoke()
override fun invoke(project: Project, editor: Editor?, element: PsiElement) {
val srcModule = ModuleUtilCore.findModuleForPsiElement(element) ?: return
val propertiesComponent = PropertiesComponent.getInstance()
val testFolders = computeTestRoots(srcModule)
if (testFolders.isEmpty() && !propertiesComponent.getBoolean("create.test.in.the.same.root")) {
if (Messages.showOkCancelDialog(
project,
KotlinBundle.message("test.integration.message.text.create.test.in.the.same.source.root"),
KotlinBundle.message("test.integration.title.no.test.roots.found"),
Messages.getQuestionIcon()
) != Messages.OK
) return
propertiesComponent.setValue("create.test.in.the.same.root", true)
}
val srcClass = getContainingClass(element) ?: return
val srcDir = element.containingFile.containingDirectory
val srcPackage = JavaDirectoryService.getInstance().getPackage(srcDir)
val dialog = KotlinCreateTestDialog(project, text, srcClass, srcPackage, srcModule)
if (!dialog.showAndGet()) return
val existingClass = (findTestClass(dialog.targetDirectory, dialog.className) as? KtLightClass)?.kotlinOrigin
if (existingClass != null) {
// TODO: Override dialog method when it becomes protected
val answer = Messages.showYesNoDialog(
project,
KotlinBundle.message("test.integration.message.text.kotlin.class", existingClass.name.toString()),
CommonBundle.getErrorTitle(),
KotlinBundle.message("test.integration.button.text.rewrite"),
KotlinBundle.message("test.integration.button.text.cancel"),
Messages.getErrorIcon()
)
if (answer == Messages.NO) return
}
val generatedClass = project.executeCommand(CodeInsightBundle.message("intention.create.test"), this) {
val generator = TestGenerators.INSTANCE.forLanguage(dialog.selectedTestFrameworkDescriptor.language)
project.runWithAlternativeResolveEnabled {
if (existingClass != null) {
dialog.explicitClassName = getTempJavaClassName(project, existingClass.containingFile.virtualFile)
}
generator.generateTest(project, dialog)
}
} as? PsiClass ?: return
project.runWhenSmart {
val generatedFile = generatedClass.containingFile as? PsiJavaFile ?: return@runWhenSmart
if (generatedClass.language == JavaLanguage.INSTANCE) {
project.executeCommand<Unit>(
KotlinBundle.message("convert.class.0.to.kotlin", generatedClass.name.toString()),
this
) {
runWriteAction {
generatedClass.methods.forEach {
it.throwsList.referenceElements.forEach { referenceElement -> referenceElement.delete() }
}
}
if (existingClass != null) {
runWriteAction {
val existingMethodNames = existingClass
.declarations
.asSequence()
.filterIsInstance<KtNamedFunction>()
.mapTo(HashSet()) { it.name }
generatedClass
.methods
.filter { it.name !in existingMethodNames }
.forEach { it.j2k()?.let { declaration -> existingClass.addDeclaration(declaration) } }
generatedClass.delete()
}
NavigationUtil.activateFileWithPsiElement(existingClass)
} else {
with(PsiDocumentManager.getInstance(project)) {
getDocument(generatedFile)?.let { doPostponedOperationsAndUnblockDocument(it) }
}
JavaToKotlinAction.convertFiles(
listOf(generatedFile),
project,
srcModule,
false,
forceUsingOldJ2k = true
).singleOrNull()
}
}
}
}
}
}.invoke(element.project, editor, lightClass)
}
} | apache-2.0 | bf87d2c2a7312adb883d73969682b953 | 50.849515 | 127 | 0.607584 | 6.020293 | false | true | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/ui/keystore/KeyStoreController.kt | 1 | 8385 | /**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 5/20/20.
* Copyright (c) 2020 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.keystore
import android.app.Activity
import android.app.ActivityManager
import android.app.admin.DevicePolicyManager
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.core.app.ShareCompat
import androidx.core.content.getSystemService
import com.bluelinelabs.conductor.RouterTransaction
import com.breadwallet.BuildConfig
import com.breadwallet.R
import com.breadwallet.databinding.ControllerKeystoreBinding
import com.breadwallet.logger.logDebug
import com.breadwallet.logger.logError
import com.breadwallet.tools.security.BrdUserManager
import com.breadwallet.tools.security.BrdUserState.KeyStoreInvalid
import com.breadwallet.ui.BaseController
import com.breadwallet.ui.controllers.AlertDialogController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.kodein.di.erased.instance
private const val DIALOG_WIPE = "keystore_wipe"
private const val DIALOG_UNINSTALL = "keystore_uninstall"
private const val DIALOG_LOCK = "keystore_lock"
private const val BRD_SUPPORT_EMAIL = "[email protected]"
private const val BRD_EMAIL_SUBJECT = "Android Key Store Error"
private const val PACKAGE_PREFIX = "package:"
private const val SET_AUTH_REQ_CODE = 5713
class KeyStoreController(
args: Bundle? = null
) : BaseController(args), AlertDialogController.Listener {
private val brdUser by instance<BrdUserManager>()
@Suppress("unused")
private val binding by viewBinding(ControllerKeystoreBinding::inflate)
override fun onAttach(view: View) {
super.onAttach(view)
brdUser.stateChanges()
.onEach { state ->
when (state) {
is KeyStoreInvalid -> showKeyStoreDialog(state)
else -> restartApp()
}
}
.flowOn(Dispatchers.Main)
.launchIn(viewAttachScope)
}
override fun onPositiveClicked(
dialogId: String,
controller: AlertDialogController,
result: AlertDialogController.DialogInputResult
) {
when (dialogId) {
DIALOG_WIPE -> wipeDevice()
DIALOG_LOCK -> devicePassword()
DIALOG_UNINSTALL -> uninstall()
}
}
override fun onNegativeClicked(
dialogId: String,
controller: AlertDialogController,
result: AlertDialogController.DialogInputResult
) {
when (dialogId) {
DIALOG_UNINSTALL, DIALOG_WIPE -> contactSupport()
DIALOG_LOCK -> checkNotNull(activity).finish()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == SET_AUTH_REQ_CODE && resultCode == Activity.RESULT_OK) {
checkNotNull(activity).recreate()
}
}
private fun showKeyStoreDialog(state: KeyStoreInvalid) {
val topController = router.backstack.lastOrNull()?.controller
val currentDialog = (topController as? AlertDialogController)?.dialogId
val res = checkNotNull(resources)
val controller = when (state) {
KeyStoreInvalid.Wipe -> {
if (currentDialog == DIALOG_WIPE) return
AlertDialogController(
dialogId = DIALOG_WIPE,
dismissible = false,
message = res.getString(R.string.Alert_keystore_invalidated_wipe_android),
title = res.getString(R.string.Alert_keystore_title_android),
positiveText = res.getString(R.string.Button_wipe_android),
negativeText = res.getString(R.string.Button_contactSupport_android)
)
}
KeyStoreInvalid.Uninstall -> {
if (currentDialog == DIALOG_UNINSTALL) return
AlertDialogController(
dialogId = DIALOG_UNINSTALL,
dismissible = false,
title = res.getString(R.string.Alert_keystore_title_android),
message = res.getString(R.string.Alert_keystore_invalidated_uninstall_android),
positiveText = res.getString(R.string.Button_uninstall_android),
negativeText = res.getString(R.string.Button_contactSupport_android)
)
}
KeyStoreInvalid.Lock -> {
if (currentDialog == DIALOG_LOCK) return
AlertDialogController(
dialogId = DIALOG_LOCK,
dismissible = false,
title = res.getString(R.string.JailbreakWarnings_title),
message = res.getString(R.string.Prompts_NoScreenLock_body_android),
positiveText = res.getString(R.string.Button_securitySettings_android),
negativeText = res.getString(R.string.AccessibilityLabels_close)
)
}
}
val transaction = RouterTransaction.with(controller)
if (currentDialog.isNullOrBlank()) {
router.pushController(transaction)
} else {
router.replaceTopController(transaction)
}
}
private fun devicePassword() {
val activity = checkNotNull(activity)
val intent = Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD)
if (intent.resolveActivity(activity.packageManager) == null) {
logError("showEnableDevicePasswordDialog: Security Settings button failed.")
} else {
startActivityForResult(intent, SET_AUTH_REQ_CODE)
}
}
private fun wipeDevice() {
logDebug("showKeyStoreInvalidDialogAndWipe: Clearing app data.")
val activity = checkNotNull(activity)
activity.getSystemService<ActivityManager>()?.clearApplicationUserData()
}
private fun uninstall() {
logError("showKeyStoreInvalidDialogAndUninstall: Uninstalling")
val activity = checkNotNull(activity)
val intent = Intent(Intent.ACTION_DELETE).apply {
data = Uri.parse(PACKAGE_PREFIX + BuildConfig.APPLICATION_ID)
}
if (intent.resolveActivity(activity.packageManager) == null) {
logError("showKeyStoreInvalidDialogAndUninstall: Uninstall button failed.")
} else {
startActivity(intent)
}
}
private fun contactSupport() {
val activity = checkNotNull(activity)
try {
ShareCompat.IntentBuilder.from(activity)
.setType("message/rfc822")
.addEmailTo(BRD_SUPPORT_EMAIL)
.setSubject(BRD_EMAIL_SUBJECT)
.startChooser()
} catch (e: ActivityNotFoundException) {
logError("No email clients found", e)
toast(R.string.ErrorMessages_emailUnavailableTitle)
}
}
private fun restartApp() {
router.setBackstack(emptyList(), null)
checkNotNull(activity).recreate()
}
}
| mit | 01e72ae95e084a426c2e43f2cba6862c | 39.3125 | 99 | 0.663447 | 4.97331 | false | false | false | false |
AlmasB/Zephyria | src/main/kotlin/com/almasb/zeph/character/components/CharacterChildViewComponent.kt | 1 | 3914 | package com.almasb.zeph.character.components
import com.almasb.fxgl.dsl.components.view.ChildViewComponent
import com.almasb.fxgl.ui.ProgressBar
import com.almasb.zeph.Config
import com.almasb.zeph.EntityType
import com.almasb.zeph.character.CharacterClass
import com.almasb.zeph.character.CharacterEntity
import javafx.beans.property.SimpleStringProperty
import javafx.scene.Group
import javafx.scene.Node
import javafx.scene.paint.Color
import javafx.scene.text.Font
import javafx.scene.text.Text
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class CharacterChildViewComponent : ChildViewComponent(0.0, 10.0, isTransformApplied = false) {
private lateinit var char: CharacterComponent
override fun onAdded() {
super.onAdded()
val view = makeView()
viewRoot.children += view
if ((entity as CharacterEntity).data.charClass == CharacterClass.MONSTER) {
viewRoot.visibleProperty().bind(entity.viewComponent.parent.hoverProperty())
}
}
private fun makeView(): Node {
val barHP = makeHPBar()
val barSP = makeSkillBar()
barHP.translateX = 0.0
barHP.translateY = 55.0
barHP.setWidth(Config.SPRITE_SIZE * 1.0)
barHP.setHeight(6.0)
barHP.isLabelVisible = false
barSP.translateX = 0.0
barSP.translateY = barHP.translateY + 6
barSP.setWidth(Config.SPRITE_SIZE * 1.0)
barSP.setHeight(6.0)
barSP.isLabelVisible = false
barHP.maxValueProperty().bind(char.hp.maxValueProperty())
barHP.currentValueProperty().bind(char.hp.valueProperty())
barSP.maxValueProperty().bind(char.sp.maxValueProperty())
barSP.currentValueProperty().bind(char.sp.valueProperty())
val text = Text()
text.font = Font.font(14.0)
text.fill = Color.WHITE
text.textProperty().bind(SimpleStringProperty((entity as CharacterEntity).data.description.name).concat(" Lv. ").concat(char.baseLevel))
text.translateX = Config.SPRITE_SIZE.toDouble() / 2 - text.layoutBounds.width / 2
text.translateY = 85.0
return Group(barHP, barSP).also {
if ((entity as CharacterEntity).data.charClass == CharacterClass.MONSTER) {
it.children += text
}
}
}
private fun makeHPBar(): ProgressBar {
val bar = ProgressBar(false)
bar.innerBar.stroke = Color.GRAY
bar.innerBar.arcWidthProperty().unbind()
bar.innerBar.arcHeightProperty().unbind()
bar.innerBar.arcWidthProperty().value = 0.0
bar.innerBar.arcHeightProperty().value = 0.0
bar.innerBar.heightProperty().unbind()
bar.innerBar.heightProperty().value = 6.0
bar.backgroundBar.effect = null
bar.backgroundBar.fill = null
bar.backgroundBar.strokeWidth = 0.25
with(bar) {
setHeight(25.0)
setFill(Color.GREEN.brighter())
setTraceFill(Color.GREEN.brighter())
isLabelVisible = true
}
bar.innerBar.effect = null
return bar
}
private fun makeSkillBar(): ProgressBar {
val bar = ProgressBar(false)
bar.innerBar.stroke = Color.GRAY
bar.innerBar.arcWidthProperty().unbind()
bar.innerBar.arcHeightProperty().unbind()
bar.innerBar.arcWidthProperty().value = 0.0
bar.innerBar.arcHeightProperty().value = 0.0
bar.innerBar.heightProperty().unbind()
bar.innerBar.heightProperty().value = 6.0
bar.backgroundBar.effect = null
bar.backgroundBar.fill = null
bar.backgroundBar.strokeWidth = 0.25
with(bar) {
setHeight(25.0)
setFill(Color.BLUE.brighter().brighter())
setTraceFill(Color.BLUE)
isLabelVisible = true
}
bar.innerBar.effect = null
return bar
}
} | gpl-2.0 | 144cbecca9641dcc71618f7b00335bee | 31.355372 | 144 | 0.649463 | 4.378076 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/item/CustomSingleActionFragment.kt | 1 | 9683 | /*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.action.item
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.snackbar.Snackbar
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.legacy.action.Action
import jp.hazuki.yuzubrowser.legacy.action.ActionNameArray
import jp.hazuki.yuzubrowser.legacy.action.SingleAction
import jp.hazuki.yuzubrowser.legacy.action.view.ActionActivity
import jp.hazuki.yuzubrowser.legacy.databinding.ActionCustomBinding
import jp.hazuki.yuzubrowser.ui.widget.recycler.ArrayRecyclerAdapter
import jp.hazuki.yuzubrowser.ui.widget.recycler.DividerItemDecoration
import jp.hazuki.yuzubrowser.ui.widget.recycler.OnRecyclerListener
import jp.hazuki.yuzubrowser.ui.widget.recycler.RecyclerMenu
class CustomSingleActionFragment : Fragment(), OnRecyclerListener, RecyclerMenu.OnRecyclerMenuListener {
private lateinit var adapter: ActionAdapter
private lateinit var actionNameArray: ActionNameArray
private lateinit var binding: ActionCustomBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = ActionCustomBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val activity = activity ?: return
binding.recyclerView.run {
layoutManager = LinearLayoutManager(activity)
addItemDecoration(DividerItemDecoration(activity))
val helper = ItemTouchHelper(Touch())
helper.attachToRecyclerView(this)
addItemDecoration(helper)
}
val arguments = arguments ?: return
val actions = arguments.getParcelable(ARG_ACTION) ?: Action()
val name = arguments.getString(ARG_NAME) ?: ""
actionNameArray = arguments.getParcelable(ActionNameArray.INTENT_EXTRA)
?: ActionNameArray(activity)
adapter = ActionAdapter(activity, actions, actionNameArray, this, this).apply {
isSortMode = true
}
binding.recyclerView.adapter = adapter
binding.editText.setText(name)
binding.okButton.setOnClickListener {
var newName: String? = binding.editText.text.toString()
if (TextUtils.isEmpty(newName) && adapter.itemCount > 0) {
newName = adapter[0].toString(actionNameArray)
}
val result = Intent()
result.putExtra(CustomSingleActionActivity.EXTRA_NAME, newName)
result.putExtra(CustomSingleActionActivity.EXTRA_ACTION, Action(adapter.items) as Parcelable)
activity.setResult(Activity.RESULT_OK, result)
activity.finish()
}
binding.cancelButton.setOnClickListener { activity.finish() }
binding.addButton.setOnClickListener {
val intent = ActionActivity.Builder(activity)
.setTitle(R.string.add)
.setActionNameArray(actionNameArray)
.create()
startActivityForResult(intent, RESULT_REQUEST_PREFERENCE)
}
}
override fun onRecyclerItemClicked(v: View, position: Int) {
val bundle = Bundle()
bundle.putInt(ARG_POSITION, position)
val intent = ActionActivity.Builder(activity ?: return)
.setTitle(R.string.edit_action)
.setDefaultAction(Action(adapter[position]))
.setActionNameArray(actionNameArray)
.setReturnData(bundle)
.create()
startActivityForResult(intent, RESULT_REQUEST_EDIT)
}
override fun onRecyclerItemLongClicked(v: View, position: Int): Boolean {
return false
}
override fun onDeleteClicked(position: Int) {
adapter.remove(position)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
RESULT_REQUEST_PREFERENCE -> {
val action = ActionActivity.getActionFromIntent(resultCode, data) ?: return
adapter.addAll(action)
adapter.notifyDataSetChanged()
}
RESULT_REQUEST_EDIT -> {
if (resultCode != Activity.RESULT_OK || data == null) {
return
}
val action = ActionActivity.getActionFromIntent(resultCode, data)
val returnData = ActionActivity.getReturnData(data)
if (action == null || returnData == null) {
return
}
val position = returnData.getInt(ARG_POSITION)
if (action.size == 1) {
adapter[position] = action[0]
adapter.notifyItemChanged(position)
} else {
adapter.remove(position)
for (i in action.indices.reversed()) {
adapter.add(position, action[i])
}
adapter.notifyDataSetChanged()
}
}
}
}
private inner class Touch : ItemTouchHelper.Callback() {
override fun getMovementFlags(recyclerView: androidx.recyclerview.widget.RecyclerView, viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder): Int {
return makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) or ItemTouchHelper.Callback.makeFlag(ItemTouchHelper.ACTION_STATE_DRAG, ItemTouchHelper.DOWN or ItemTouchHelper.UP)
}
override fun onMove(recyclerView: androidx.recyclerview.widget.RecyclerView, viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder, target: androidx.recyclerview.widget.RecyclerView.ViewHolder): Boolean {
adapter.move(viewHolder.adapterPosition, target.adapterPosition)
return true
}
override fun onSwiped(viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.adapterPosition
val action = adapter.remove(position)
Snackbar.make(binding.rootLayout, R.string.deleted, Snackbar.LENGTH_SHORT)
.setAction(R.string.undo) {
adapter.add(position, action)
adapter.notifyItemInserted(position)
}
.show()
}
}
private class ActionAdapter constructor(private val context: Context, list: Action, private val nameArray: ActionNameArray, private val menuListener: RecyclerMenu.OnRecyclerMenuListener, listener: OnRecyclerListener) : ArrayRecyclerAdapter<SingleAction, ActionAdapter.AVH>(context, list, listener), RecyclerMenu.OnRecyclerMoveListener {
override fun onBindViewHolder(holder: AVH, item: SingleAction, position: Int) {
holder.title.text = item.toString(nameArray)
holder.menu.setOnClickListener { v -> RecyclerMenu(context, v, holder.adapterPosition, menuListener, this@ActionAdapter).show() }
}
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup?, viewType: Int): AVH {
return AVH(inflater.inflate(R.layout.action_custom_item, parent, false), this)
}
override fun onMoveUp(position: Int) {
if (position > 0) {
move(position, position - 1)
}
}
override fun onMoveDown(position: Int) {
if (position < itemCount - 1) {
move(position, position + 1)
}
}
class AVH(itemView: View, adapter: ActionAdapter) : ArrayRecyclerAdapter.ArrayViewHolder<SingleAction>(itemView, adapter) {
internal val title: TextView = itemView.findViewById(R.id.titleTextView)
internal val menu: ImageButton = itemView.findViewById(R.id.menu)
}
}
companion object {
private const val RESULT_REQUEST_PREFERENCE = 1
private const val RESULT_REQUEST_EDIT = 2
private const val ARG_ACTION = "action"
private const val ARG_NAME = "name"
private const val ARG_POSITION = "position"
fun newInstance(actionList: Action?, name: String?, actionNameArray: ActionNameArray): CustomSingleActionFragment {
return CustomSingleActionFragment().apply {
arguments = Bundle().apply {
putParcelable(ARG_ACTION, actionList)
putString(ARG_NAME, name)
putParcelable(ActionNameArray.INTENT_EXTRA, actionNameArray)
}
}
}
}
}
| apache-2.0 | e9db8f1cf84bd9d7208e3f1042a39719 | 40.917749 | 340 | 0.663431 | 5.131426 | false | false | false | false |
Eluinhost/anonymous | src/main/kotlin/JoinLeaveListener.kt | 1 | 2112 | package gg.uhc.anonymous
import net.md_5.bungee.api.ChatColor
import net.md_5.bungee.api.chat.TranslatableComponent
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.event.player.PlayerQuitEvent
import org.bukkit.plugin.Plugin
private const val JOIN_TRANSLATION_STRING = "multiplayer.player.joined"
private const val QUIT_TRANSLATION_STRING = "multiplayer.player.left"
/**
* A Bukkit event listener that listens on leave/join events and cancels the messages. It then sends a reformatted
* message to each player with the player's display name instead. Uses Minecraft translatable messages to send the
* message to clients for their own language. Players with the [JOIN_LEAVE_BYPASS_PERMISSION] will see the original
* messages instead.
*
* @param plugin used to send messages to online players
*/
class JoinLeaveListener(protected val plugin: Plugin) : Listener {
@EventHandler fun on(event: PlayerJoinEvent) {
event.joinMessage = ""
val actual = TranslatableComponent(JOIN_TRANSLATION_STRING, event.player.name)
actual.color = ChatColor.YELLOW
val modified = TranslatableComponent(JOIN_TRANSLATION_STRING, event.player.displayName)
modified.color = ChatColor.YELLOW
plugin.server.onlinePlayers.forEach {
it.spigot().sendMessage(when {
it.hasPermission(JOIN_LEAVE_BYPASS_PERMISSION) -> actual
else -> modified
})
}
}
@EventHandler fun on(event: PlayerQuitEvent) {
event.quitMessage = ""
val actual = TranslatableComponent(QUIT_TRANSLATION_STRING, event.player.name)
actual.color = ChatColor.YELLOW
val modified = TranslatableComponent(QUIT_TRANSLATION_STRING, event.player.displayName)
modified.color = ChatColor.YELLOW
plugin.server.onlinePlayers.forEach {
it.spigot().sendMessage(when {
it.hasPermission(JOIN_LEAVE_BYPASS_PERMISSION) -> actual
else -> modified
})
}
}
}
| mit | 2b4ef695515673572246d4ab2316b06c | 38.111111 | 115 | 0.707386 | 4.522484 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/utils/compat/Utils.kt | 1 | 1268 | package com.gmail.blueboxware.libgdxplugin.utils.compat
import com.intellij.util.castSafelyTo
import org.jetbrains.kotlin.idea.references.SyntheticPropertyAccessorReference
import kotlin.reflect.KProperty1
import kotlin.reflect.full.memberProperties
/*
* Copyright 2020 Blue Box Ware
*
* 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.
*/
fun SyntheticPropertyAccessorReference.isGetter(): Boolean {
if (this::class.simpleName == "Getter") {
return true
} else if (this::class.simpleName == "Setter") {
return false
}
return this::class
.memberProperties
.firstOrNull { it.name == "getter" }
?.castSafelyTo<KProperty1<SyntheticPropertyAccessorReference, Boolean>>()
?.get(this)
?: false
}
| apache-2.0 | 0d30a990c62d4a47ac7c40f7e38ec6cd | 34.222222 | 81 | 0.727129 | 4.512456 | false | false | false | false |
UnderMybrella/Visi | src/main/kotlin/org/abimon/visi/io/DataSource.kt | 1 | 4129 | package org.abimon.visi.io
import java.io.*
import java.net.HttpURLConnection
import java.net.URL
import java.nio.channels.Channels
import java.util.*
import java.util.function.Supplier
interface DataSource {
/**
* Get an input stream associated with this data source.
*/
val inputStream: InputStream
val seekableInputStream: InputStream
val location: String
val data: ByteArray
val size: Long
fun <T> use(action: (InputStream) -> T): T = inputStream.use(action)
fun <T> seekableUse(action: (InputStream) -> T): T = seekableInputStream.use(action)
fun pipe(out: OutputStream): Unit = use { it.copyTo(out) }
}
class FileDataSource(val file: File) : DataSource {
override val location: String = file.absolutePath
override val data: ByteArray
get() = file.readBytes()
override val inputStream: InputStream
get() = FileInputStream(file)
override val seekableInputStream: InputStream
get() = RandomAccessFileInputStream(file)
override val size: Long
get() = file.length()
}
class HTTPDataSource(val url: URL, val userAgent: String) : DataSource {
constructor(url: URL) : this(url, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:44.0) Gecko/20100101 Firefox/44.0")
override val location: String = url.toExternalForm()
override val data: ByteArray
get() = use { stream -> stream.readBytes() }
override val inputStream: InputStream
get() {
val http = url.openConnection() as HttpURLConnection
http.requestMethod = "GET"
http.setRequestProperty("User-Agent", userAgent)
return if (http.responseCode < 400) http.inputStream else http.errorStream
}
override val seekableInputStream: InputStream
get() {
val http = url.openConnection() as HttpURLConnection
http.requestMethod = "GET"
http.setRequestProperty("User-Agent", userAgent)
val stream = if (http.responseCode < 400) http.inputStream else http.errorStream
val tmp = File.createTempFile(UUID.randomUUID().toString(), "tmp")
tmp.deleteOnExit()
FileOutputStream(tmp).use { out -> stream.use { inStream -> inStream.copyTo(out) } }
return Channels.newInputStream(RandomAccessFile(tmp, "r").channel)
}
override val size: Long
get() = use { it.available().toLong() }
}
class FunctionalDataSource(val dataSupplier: Supplier<ByteArray>) : DataSource {
override val location: String = "Supplier " + dataSupplier.toString()
override val data: ByteArray
get() = dataSupplier.get()
override val inputStream: InputStream
get() = ByteArrayInputStream(data)
override val seekableInputStream: InputStream
get() = ByteArrayInputStream(data)
override val size: Long
get() = data.size.toLong()
}
class FunctionDataSource(val dataFunc: () -> ByteArray): DataSource {
override val location: String = dataFunc.toString()
override val data: ByteArray
get() = dataFunc()
override val inputStream: InputStream
get() = ByteArrayInputStream(dataFunc())
override val seekableInputStream: InputStream
get() = ByteArrayInputStream(dataFunc())
override val size: Long
get() = dataFunc().size.toLong()
}
class ByteArrayDataSource(override val data: ByteArray): DataSource {
override val inputStream: InputStream
get() = ByteArrayInputStream(data)
override val seekableInputStream: InputStream
get() = ByteArrayInputStream(data)
override val location: String = "Byte Array $data"
override val size: Long = data.size.toLong()
}
/** One time use */
class InputStreamDataSource(val stream: InputStream) : DataSource {
override val location: String = stream.toString()
override val data: ByteArray
get() = stream.use { it.readBytes() }
override val inputStream: InputStream = stream
override val seekableInputStream: InputStream = stream
override val size: Long
get() = stream.available().toLong()
} | mit | 872c542a32d2f0ea250c54355e7d9446 | 31.777778 | 123 | 0.674013 | 4.670814 | false | false | false | false |
tingtingths/jukebot | app/src/main/java/com/jukebot/jukebot/message/CommandUpdateHandler.kt | 1 | 2324 | package com.jukebot.jukebot.message
import com.google.gson.Gson
import com.jukebot.jukebot.command.*
import com.jukebot.jukebot.logging.Logger
import com.jukebot.jukebot.pojo.Command
import com.jukebot.jukebot.util.Util
import com.pengrad.telegrambot.model.Message
import com.pengrad.telegrambot.model.MessageEntity
import com.pengrad.telegrambot.model.Update
/**
* Created by Ting.
*/
class CommandUpdateHandler : UpdateHandler() {
/*
bind - Bind to this chat. /bind <password>
playlist - Get playlist
now - Get now playing
next - Play next
play - Play
pause - Pause
shuffle - Shuffle playlist
top - Move track to top
rm - Remove track from playlist
clear - Clear playlist
*/
private val initHandler = BindCommandHandler // first handler to call
init {
// chain of responsibility
initHandler
.chain(PlaylistCommandHandler)
.chain(NowCommandHandler)
.chain(NextCommandHandler)
.chain(PlayCommandHandler)
.chain(PauseCommandHandler)
.chain(ShuffleCommandHandler)
.chain(TopCommandHandler)
.chain(RemoveCommandHandler)
.chain(ClearCommandHandler)
Logger.log(this.javaClass.simpleName, "chainedCommands=${initHandler.getChainedCommands()}")
}
override fun responsible(update: Update): Any? {
if (update.message()?.entities()?.get(0)?.type() == MessageEntity.Type.bot_command) {
val text: String = update.message().text()
val command: Command = Util.parseCmd(text)
Logger.log(this.javaClass.simpleName, "cmd=${command.cmd}")
if (initHandler.getChainedCommands().contains(command.cmd))
return command
}
return null
}
override fun handle(pair: Pair<Message, Any>) {
val msg: Message = pair.first
if (pair.second is Command) {
val command: Command = pair.second as Command
Logger.log(this.javaClass.simpleName, "handle(cmd = ${Gson().toJson(command)})")
initHandler.handle(command, msg)
}
}
}
| mit | b77dbe2c1c369e78b4296a7ef984d6ea | 33.176471 | 100 | 0.599828 | 4.694949 | false | false | false | false |
universum-studios/gradle_github_plugin | plugin/src/releases/kotlin/universum/studios/gradle/github/release/task/ListReleasesTask.kt | 1 | 4971 | /*
* *************************************************************************************************
* Copyright 2017 Universum Studios
* *************************************************************************************************
* 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 universum.studios.gradle.github.release.task
import universum.studios.gradle.github.release.service.model.RemoteRelease
import universum.studios.gradle.github.task.output.TaskOutputCreator
/**
* A [ReleaseTask] implementation which is used as base for all release task which request a set or
* single [RemoteRelease]/-s from the GitHub server.
*
* @author Martin Albedinsky
* @since 1.0
*/
abstract class ListReleasesTask : ReleaseTask() {
/*
* Companion ===================================================================================
*/
/*
* Interface ===================================================================================
*/
/*
* Members =====================================================================================
*/
/**
* Default output creator which may be used by inheritance hierarchies of this task class for
* creation of logging output for received [RemoteRelease]s.
*/
private val outputCreator = OutputCreator()
/*
* Constructors ================================================================================
*/
/*
* Methods =====================================================================================
*/
/**
* Returns the default output creator for this task.
*
* @return Default output creator.
*/
internal fun getOutputCreator(): OutputCreator {
this.outputCreator.clear()
return outputCreator
}
/*
* Inner classes ===============================================================================
*/
/**
* A [TaskOutputCreator] implementation which may be used by inheritance hierarchies of
* [ListReleasesTask] to create logging output for received [RemoteRelease]s.
*
* @author Martin Albedinsky
* @since 1.0
*/
internal open class OutputCreator : TaskOutputCreator {
/**
* List containing all releases added into this creator is its input.
*/
private val releases = mutableListOf<RemoteRelease>()
/**
* Adds all the given *releases* as input into this creator.
*
* @param releases The desired list of releases to add as input.
*/
fun addReleases(releases: List<RemoteRelease>) {
this.releases.addAll(releases)
}
/**
* Adds the given *release* as input into this creator.
*
* @param release The desired release to add as input.
*/
fun addRelease(release: RemoteRelease) {
this.releases.add(release)
}
/*
*/
override fun clear() {
this.releases.clear()
}
/*
*/
override fun createOutput(): String {
var output = ""
val releasesIterator = releases.iterator()
while (releasesIterator.hasNext()) {
output += createReleaseOutput(releasesIterator.next())
if (releasesIterator.hasNext()) {
output += ",\n"
}
}
return output
}
/**
* Creates an output string for the specified *release*.
*
* @param release The release for which to create output string.
* @return The output string representing the given release.
*/
fun createReleaseOutput(release: RemoteRelease) =
"Release{\n" +
" tagName: ${release.tag_name},\n" +
" name: ${release.name},\n" +
" body: ${release.body},\n" +
" draft: ${release.draft},\n" +
" preRelease: ${release.prerelease},\n" +
" createdAt: ${release.created_at},\n" +
" publishedAt: ${release.published_at}\n" +
"}"
}
} | apache-2.0 | fbd3c6641f5dad8f1bf8c5e528af52ac | 34.014085 | 101 | 0.471334 | 5.726959 | false | false | false | false |
zhengjiong/ZJ_KotlinStudy | src/main/kotlin/com/zj/example/kotlin/basicsknowledge/2.0ExtendExample继承.kt | 1 | 3399 | package com.zj.example.kotlin.basicsknowledge
/**
*
* CreateTime: 17/9/8 17:39
* @author 郑炯
*/
/**
* 必须要open才可以被继承, 不写默认是final
*/
private open class Animal2(open val name: String) {
}
/**
* 这里name不能加val或者var, 不然会提示需要加override字段,
* 因为加了val或者var就相当于给Cat2加了一个字段, 所以如果要
* 重写父类的字段需要加override, (见Cat3)
*/
private class Cat2(name: String, val age: Int) : Animal2(name) {
}
/**
* 如果子类没有主构造函数,那么每个次构造函数必须使用 super 关键字初始化其基类型,
* 或委托给另一个构造函数做到这一点。 注意,在这种情况下,不同的次构造函数可以
* 调用基类型的不同的构造函数:
*/
private class Cat2_1 : Animal2 {
/**
* 对于var的int,float等基本类型如果不想初始化,就必须在构造函数中初始化或者
* 是在下面的次级构造函数中初始化(包含每一个次级构造函数),不然编译器会报错,
* 或者加上get方法也是可以的(见Cat2_2)
*/
var age: Int//下面有次级构造函数, 这里可以不用初始化
/**
* 对于非基本类型的var属性字段, 可以用lateinit
*/
lateinit var color: String
/*var height2: Int
get() = 0//get() = height2不能这样写 是会报错的, 应该用field
set(value) {
println("set value=" + value)
println("height2 = $height2")
2
}*/
/**
* 对于val的属性, 可以用by lazy来延迟初始化
*/
val color2: String by lazy {
""
}
/**
* 对于val的属性, 可以用by lazy来延迟初始化
*/
val height: Int by lazy {
1
}
/**
* 对于val也可以使用get来初始化
*/
val weight: Float
get() = height * 0.5f
constructor(name: String) : super(name) {
this.age = 0
}
constructor(name: String, age: Int) : super(name) {
this.age = age
}
}
private class Cat2_2 : Animal2 {
var age: Int
lateinit var color: String
constructor(name: String) : this(name, 0) {
this.age = 0
}
constructor(name: String, age: Int) : super(name) {
this.age = age
}
}
//重写父类的字段需要加override, (见Cat3)
private class Cat3(override val name: String, val age: Int) : Animal2(name) {
}
private class Cat4(name: String) : Animal2(name) {
/**
* 因为是val所以不能使用lateinit,必须初始化值,或者使用by lazy(见Cat5), 或者重写get方法(见Cat6)
*/
override val name: String = ""
}
private class Cat5(name: String) : Animal2(name) {
//通过by lazy延迟设置name的值
override val name: String by lazy {
""
}
}
private class Cat6(name: String) : Animal2(name) {
/**
* 键盘输入override,然后选择name后, idea会自动生成get方法,
* get方法有两种写法(方法2见Cat7)
* 方法1:
*
*/
override val name: String
/**
* 如果只有一行代码,直接返回值, 可以直接使用=,
*/
get() = super.name
}
private class Cat7(name: String) : Animal2(name) {
/**
* 方法2:
*/
override val name: String
get() {
return ""
}
}
| mit | e7521b43c016765b926d46f4868c2ca0 | 17.582734 | 77 | 0.573364 | 2.979239 | false | false | false | false |
jabbink/PokemonGoBot | src/main/kotlin/ink/abb/pogo/scraper/util/data/PokemonData.kt | 2 | 5991 | /**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper.util.data
import POGOProtos.Enums.PokemonMoveOuterClass
import com.google.common.geometry.S2CellId
import com.google.common.geometry.S2LatLng
import ink.abb.pogo.api.cache.BagPokemon
import ink.abb.pogo.api.util.PokemonMoveMetaRegistry
import ink.abb.pogo.scraper.util.pokemon.*
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
data class PokemonData(
var id: String? = null,
var pokemonId: Int? = null,
var name: String? = null,
var nickname: String? = null,
var pclass: String? = null,
var type1: String? = null,
var type2: String? = null,
var cp: Int? = null,
var iv: Int? = null,
var stats: String? = null,
var favorite: Boolean? = null,
var cpMultiplier: Float? = null,
var heightM: Float? = null,
var weightKg: Float? = null,
var individualStamina: Int? = null,
var individualAttack: Int? = null,
var individualDefense: Int? = null,
var candy: Int? = null,
var candiesToEvolve: Int? = null,
var level: Float? = null,
var move1: String? = null,
var move1Type: String? = null,
var move1Power: Int? = null,
var move1Accuracy: Int? = null,
var move1CritChance: Double? = null,
var move1Time: Int? = null,
var move1Energy: Int? = null,
var move2: String? = null,
var move2Type: String? = null,
var move2Power: Int? = null,
var move2Accuracy: Int? = null,
var move2CritChance: Double? = null,
var move2Time: Int? = null,
var move2Energy: Int? = null,
var deployedFortId: String? = null,
var stamina: Int? = null,
var maxStamina: Int? = null,
var maxCp: Int? = null,
var absMaxCp: Int? = null,
var maxCpFullEvolveAndPowerup: Int? = null,
var candyCostsForPowerup: Int? = null,
var stardustCostsForPowerup: Int? = null,
var creationTime: String? = null,
var creationTimeMs: Long? = null,
var creationLatDegrees: Double? = null,
var creationLngDegrees: Double? = null,
var baseCaptureRate: Double? = null,
var baseFleeRate: Double? = null,
var battlesAttacked: Int? = null,
var battlesDefended: Int? = null,
var isInjured: Boolean? = null,
var isFainted: Boolean? = null,
var cpAfterPowerup: Int? = null
) {
fun buildFromPokemon(bagPokemon: BagPokemon): PokemonData {
val pokemon = bagPokemon.pokemonData
val latLng = S2LatLng(S2CellId(pokemon.capturedCellId).toPoint())
val dateFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val pmeta = pokemon.meta
val pmmeta1 = PokemonMoveMetaRegistry.getMeta(PokemonMoveOuterClass.PokemonMove.forNumber(pokemon.move1.number))
val pmmeta2 = PokemonMoveMetaRegistry.getMeta(PokemonMoveOuterClass.PokemonMove.forNumber(pokemon.move2.number))
this.id = pokemon.id.toString()
this.pokemonId = pokemon.pokemonId.number
this.name = pokemon.pokemonId.name
this.nickname = pokemon.nickname
this.pclass = pmeta.pokemonClass.name
this.type1 = pmeta.type1.name
this.type2 = pmeta.type2.name
this.cp = pokemon.cp
this.iv = pokemon.getIvPercentage()
this.stats = pokemon.getStatsFormatted()
this.favorite = pokemon.favorite > 0
this.cpMultiplier = pokemon.cpMultiplier
this.heightM = pokemon.heightM
this.weightKg = pokemon.weightKg
this.individualStamina = pokemon.individualStamina
this.individualAttack = pokemon.individualAttack
this.individualDefense = pokemon.individualDefense
this.candy = bagPokemon.poGoApi.inventory.candies.getOrPut(pmeta.family, { AtomicInteger(0) }).get()
this.candiesToEvolve = pmeta.candyToEvolve
this.level = pokemon.level
this.move1 = pokemon.move1.name
this.move1Type = pmmeta1.type.name
this.move1Power = pmmeta1.power
this.move1Accuracy = pmmeta1.accuracy
this.move1CritChance = pmmeta1.critChance
this.move1Time = pmmeta1.time
this.move1Energy = pmmeta1.energy
this.move2 = pokemon.move2.name
this.move2Type = pmmeta2.type.name
this.move2Power = pmmeta2.power
this.move2Accuracy = pmmeta2.accuracy
this.move2CritChance = pmmeta2.critChance
this.move2Time = pmmeta2.time
this.move2Energy = pmmeta2.energy
this.deployedFortId = pokemon.deployedFortId
this.stamina = pokemon.stamina
this.maxStamina = pokemon.staminaMax
this.maxCp = pokemon.maxCp
this.absMaxCp = pokemon.absoluteMaxCp
this.maxCpFullEvolveAndPowerup = pokemon.cpFullEvolveAndPowerup
this.candyCostsForPowerup = pokemon.candyCostsForPowerup
this.stardustCostsForPowerup = pokemon.stardustCostsForPowerup
this.creationTime = dateFormatter.format(Date(pokemon.creationTimeMs))
this.creationTimeMs = pokemon.creationTimeMs
this.creationLatDegrees = latLng.latDegrees()
this.creationLngDegrees = latLng.lngDegrees()
this.baseCaptureRate = pmeta.baseCaptureRate
this.baseFleeRate = pmeta.baseFleeRate
this.battlesAttacked = pokemon.battlesAttacked
this.battlesDefended = pokemon.battlesDefended
this.isInjured = pokemon.injured
this.isFainted = pokemon.fainted
this.cpAfterPowerup = pokemon.cpAfterPowerup
return this
}
}
| gpl-3.0 | 31d54909b4d431ba187a20ea8b08785d | 38.414474 | 120 | 0.665999 | 3.986028 | false | false | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/cargo/toolchain/Rustup.kt | 1 | 2951 | package org.rust.cargo.toolchain
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.process.ProcessOutput
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.annotations.TestOnly
import org.rust.utils.fullyRefreshDirectory
import org.rust.utils.runAndTerminate
import org.rust.utils.seconds
private val LOG = Logger.getInstance(Rustup::class.java)
class Rustup(
private val pathToRustupExecutable: String,
private val pathToRustcExecutable: String,
private val projectDirectory: String
) {
sealed class DownloadResult {
class Ok(val library: VirtualFile) : DownloadResult()
class Err(val error: String) : DownloadResult()
}
fun downloadStdlib(): DownloadResult {
val downloadProcessOutput = GeneralCommandLine(pathToRustupExecutable)
.withWorkDirectory(projectDirectory)
.withParameters("component", "add", "rust-src")
.exec()
return if (downloadProcessOutput.exitCode != 0) {
DownloadResult.Err("rustup failed: `${downloadProcessOutput.stderr}`")
} else {
val sources = getStdlibFromSysroot() ?: return DownloadResult.Err("Failed to find stdlib in sysroot")
fullyRefreshDirectory(sources)
DownloadResult.Ok(sources)
}
}
fun getStdlibFromSysroot(): VirtualFile? {
val sysroot = GeneralCommandLine(pathToRustcExecutable)
.withWorkDirectory(projectDirectory)
.withParameters("--print", "sysroot")
.exec(5.seconds)
.stdout.trim()
val fs = LocalFileSystem.getInstance()
return fs.refreshAndFindFileByPath(FileUtil.join(sysroot, "lib/rustlib/src/rust/src"))
}
@TestOnly
fun activeToolchain(): String? {
val output = GeneralCommandLine(pathToRustupExecutable)
.withWorkDirectory(projectDirectory)
// See https://github.com/rust-lang-nursery/rustup.rs/issues/450
.withParameters("show")
.exec(1.seconds)
if (output.exitCode != 0) return null
return output.stdoutLines.dropLastWhile { it.isBlank() }.lastOrNull()
}
private fun GeneralCommandLine.exec(timeoutInMilliseconds: Int? = null): ProcessOutput {
val handler = CapturingProcessHandler(this)
LOG.info("Executing `$commandLineString`")
val output = handler.runAndTerminate(timeoutInMilliseconds)
if (output.exitCode != 0) {
LOG.warn("Failed to execute `$commandLineString`" +
"\ncode : ${output.exitCode}" +
"\nstdout:\n${output.stdout}" +
"\nstderr:\n${output.stderr}")
}
return output
}
}
| mit | 7064e477dbe154b7e99f5654cfaa9311 | 34.987805 | 113 | 0.678753 | 4.943049 | false | false | false | false |
googlecodelabs/odml-pathways | product-search/codelab1/android/final/app/src/main/java/com/google/codelabs/productimagesearch/ObjectDetectorActivity.kt | 2 | 10258 | /**
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.codelabs.productimagesearch
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.google.codelabs.productimagesearch.databinding.ActivityObjectDetectorBinding
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.objects.DetectedObject
import com.google.mlkit.vision.objects.ObjectDetection
import com.google.mlkit.vision.objects.defaults.ObjectDetectorOptions
import com.google.mlkit.vision.objects.defaults.PredefinedCategory
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
class ObjectDetectorActivity : AppCompatActivity() {
companion object {
private const val REQUEST_IMAGE_CAPTURE = 1000
private const val REQUEST_IMAGE_GALLERY = 1001
private const val TAKEN_BY_CAMERA_FILE_NAME = "MLKitDemo_"
private const val IMAGE_PRESET_1 = "Preset1.jpg"
private const val IMAGE_PRESET_2 = "Preset2.jpg"
private const val IMAGE_PRESET_3 = "Preset3.jpg"
private const val TAG = "MLKit-ODT"
}
private lateinit var viewBinding: ActivityObjectDetectorBinding
private var cameraPhotoUri: Uri? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewBinding = ActivityObjectDetectorBinding.inflate(layoutInflater)
setContentView(viewBinding.root)
initViews()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// After taking camera, display to Preview
if (resultCode == RESULT_OK) {
when (requestCode) {
REQUEST_IMAGE_CAPTURE -> cameraPhotoUri?.let {
this.setViewAndDetect(
getBitmapFromUri(it)
)
}
REQUEST_IMAGE_GALLERY -> data?.data?.let { this.setViewAndDetect(getBitmapFromUri(it)) }
}
}
}
private fun initViews() {
with(viewBinding) {
ivPreset1.setImageBitmap(getBitmapFromAsset(IMAGE_PRESET_1))
ivPreset2.setImageBitmap(getBitmapFromAsset(IMAGE_PRESET_2))
ivPreset3.setImageBitmap(getBitmapFromAsset(IMAGE_PRESET_3))
ivCapture.setOnClickListener { dispatchTakePictureIntent() }
ivGalleryApp.setOnClickListener { choosePhotoFromGalleryApp() }
ivPreset1.setOnClickListener { setViewAndDetect(getBitmapFromAsset(IMAGE_PRESET_1)) }
ivPreset2.setOnClickListener { setViewAndDetect(getBitmapFromAsset(IMAGE_PRESET_2)) }
ivPreset3.setOnClickListener { setViewAndDetect(getBitmapFromAsset(IMAGE_PRESET_3)) }
// Callback received when the user taps on any of the detected objects.
ivPreview.setOnObjectClickListener { objectImage ->
startProductImageSearch(objectImage)
}
// Default display
setViewAndDetect(getBitmapFromAsset(IMAGE_PRESET_2))
}
}
/**
* Start the product image search activity
*/
private fun startProductImageSearch(objectImage: Bitmap) {
}
/**
* Update the UI with the input image and start object detection
*/
private fun setViewAndDetect(bitmap: Bitmap?) {
bitmap?.let {
// Clear the dots indicating the previous detection result
viewBinding.ivPreview.drawDetectionResults(emptyList())
// Display the input image on the screen.
viewBinding.ivPreview.setImageBitmap(bitmap)
// Run object detection and show the detection results.
runObjectDetection(bitmap)
}
}
/**
* Detect Objects in a given Bitmap
*/
private fun runObjectDetection(bitmap: Bitmap) {
// Step 1: create ML Kit's InputImage object
val image = InputImage.fromBitmap(bitmap, 0)
// Step 2: acquire detector object
val options = ObjectDetectorOptions.Builder()
.setDetectorMode(ObjectDetectorOptions.SINGLE_IMAGE_MODE)
.enableMultipleObjects()
.enableClassification()
.build()
val objectDetector = ObjectDetection.getClient(options)
// Step 3: feed given image to detector and setup callback
objectDetector.process(image)
.addOnSuccessListener { results ->
debugPrint(results)
// Keep only the FASHION_GOOD objects
val filteredResults = results.filter { result ->
result.labels.indexOfFirst { it.text == PredefinedCategory.FASHION_GOOD } != -1
}
// Visualize the detection result
runOnUiThread {
viewBinding.ivPreview.drawDetectionResults(filteredResults)
}
}
.addOnFailureListener {
// Task failed with an exception
Log.e(TAG, it.message.toString())
}
}
/**
* Show Camera App to take a picture based Intent
*/
private fun dispatchTakePictureIntent() {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
// Ensure that there's a camera activity to handle the intent
takePictureIntent.resolveActivity(packageManager)?.also {
// Create the File where the photo should go
val photoFile: File? = try {
createImageFile(TAKEN_BY_CAMERA_FILE_NAME)
} catch (ex: IOException) {
// Error occurred while creating the File
null
}
// Continue only if the File was successfully created
photoFile?.also {
cameraPhotoUri = FileProvider.getUriForFile(
this,
"com.google.codelabs.productimagesearch.fileprovider",
it
)
// Setting output file to take a photo
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraPhotoUri)
// Open camera based Intent.
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
}
} ?: run {
Toast.makeText(this, getString(R.string.camera_app_not_found), Toast.LENGTH_LONG)
.show()
}
}
}
/**
* Show gallery app to pick photo from intent.
*/
private fun choosePhotoFromGalleryApp() {
startActivityForResult(Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
type = "image/*"
addCategory(Intent.CATEGORY_OPENABLE)
}, REQUEST_IMAGE_GALLERY)
}
/**
* The output file will be stored on private storage of this app
* By calling function getExternalFilesDir
* This photo will be deleted when uninstall app.
*/
@Throws(IOException::class)
private fun createImageFile(fileName: String): File {
// Create an image file name
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
fileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
)
}
/**
* Method to copy asset files sample to private app folder.
* Return the Uri of an output file.
*/
private fun getBitmapFromAsset(fileName: String): Bitmap? {
return try {
BitmapFactory.decodeStream(assets.open(fileName))
} catch (ex: IOException) {
null
}
}
/**
* Function to get the Bitmap From Uri.
* Uri is received by using Intent called to Camera or Gallery app
* SuppressWarnings => we have covered this warning.
*/
private fun getBitmapFromUri(imageUri: Uri): Bitmap? {
val bitmap = try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
ImageDecoder.decodeBitmap(ImageDecoder.createSource(contentResolver, imageUri))
} else {
// Add Suppress annotation to skip warning by Android Studio.
// This warning resolved by ImageDecoder function.
@Suppress("DEPRECATION")
MediaStore.Images.Media.getBitmap(contentResolver, imageUri)
}
} catch (ex: IOException) {
null
}
// Make a copy of the bitmap in a desirable format
return bitmap?.copy(Bitmap.Config.ARGB_8888, false)
}
/**
* Function to log information about object detected by ML Kit.
*/
private fun debugPrint(detectedObjects: List<DetectedObject>) {
detectedObjects.forEachIndexed { index, detectedObject ->
val box = detectedObject.boundingBox
Log.d(TAG, "Detected object: $index")
Log.d(TAG, " trackingId: ${detectedObject.trackingId}")
Log.d(TAG, " boundingBox: (${box.left}, ${box.top}) - (${box.right},${box.bottom})")
detectedObject.labels.forEach {
Log.d(TAG, " categories: ${it.text}")
Log.d(TAG, " confidence: ${it.confidence}")
}
}
}
}
| apache-2.0 | 63a3b1b6e10a1ce6b334f296b89203bc | 36.852399 | 104 | 0.627315 | 5.108566 | false | false | false | false |
carlphilipp/chicago-commutes | android-app/src/foss/kotlin/fr/cph/chicago/rx/BusesFunction.kt | 1 | 2513 | /**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.rx
import android.view.View
import android.widget.ListView
import android.widget.RelativeLayout
import android.widget.TextView
import com.mapbox.geojson.Feature
import fr.cph.chicago.R
import fr.cph.chicago.core.activity.map.BusMapActivity
import fr.cph.chicago.core.adapter.BusMapSnippetAdapter
import fr.cph.chicago.core.model.BusArrival
import io.reactivex.rxjava3.functions.Function
import org.apache.commons.lang3.StringUtils
import java.lang.ref.WeakReference
import java.util.Date
class BusesFunction(busMapActivity: BusMapActivity, private val feature: Feature, private val loadAll: Boolean) : Function<List<BusArrival>, View>, AFunction() {
val activity: WeakReference<BusMapActivity> = WeakReference(busMapActivity)
override fun apply(busArrivalsRes: List<BusArrival>): View {
val view = createView(feature, activity)
val arrivals = view.findViewById<ListView>(R.id.arrivals)
val error = view.findViewById<TextView>(R.id.error)
var busArrivals = busArrivalsRes.toMutableList()
if (!loadAll && busArrivals.size > 7) {
busArrivals = busArrivals.subList(0, 6)
val busArrival = BusArrival(Date(), "added bus", view.context.getString(R.string.bus_all_results), 0, 0, StringUtils.EMPTY, StringUtils.EMPTY, StringUtils.EMPTY, Date(), false)
busArrivals.add(busArrival)
}
if (busArrivals.isNotEmpty()) {
val container = view.findViewById<RelativeLayout>(R.id.container)
addParams(container, busArrivals.size)
val ada = BusMapSnippetAdapter(busArrivals)
arrivals.adapter = ada
arrivals.visibility = ListView.VISIBLE
error.visibility = TextView.GONE
} else {
arrivals.visibility = ListView.GONE
error.visibility = TextView.VISIBLE
}
return view
}
}
| apache-2.0 | 3497960e8d2c247ea38d60c98b8ba99a | 37.661538 | 188 | 0.71548 | 4.28109 | false | false | false | false |
jitsi/jitsi-videobridge | jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/rtp/RedAudioRtpPacket.kt | 1 | 1708 | /*
* 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.nlj.rtp
import org.jitsi.rtp.rtp.RedPacketBuilder
import org.jitsi.rtp.rtp.RedPacketParser
import java.lang.IllegalStateException
class RedAudioRtpPacket(
buffer: ByteArray,
offset: Int,
length: Int
) : AudioRtpPacket(buffer, offset, length) {
private var removed = false
fun removeRed() {
if (removed) throw IllegalStateException("RED encapsulation already removed.")
parser.decapsulate(this, parseRedundancy = false)
removed = true
}
fun removeRedAndGetRedundancyPackets(): List<AudioRtpPacket> =
if (removed) throw IllegalStateException("RED encapsulation already removed.")
else parser.decapsulate(this, parseRedundancy = true).also { removed = true }
override fun clone(): RedAudioRtpPacket =
RedAudioRtpPacket(
cloneBuffer(BYTES_TO_LEAVE_AT_START_OF_PACKET),
BYTES_TO_LEAVE_AT_START_OF_PACKET,
length
)
companion object {
val parser = RedPacketParser(::AudioRtpPacket)
val builder = RedPacketBuilder(::RedAudioRtpPacket)
}
}
| apache-2.0 | 756bb019deae6d6d72275cc706f8f043 | 32.490196 | 86 | 0.703162 | 4.368286 | false | false | false | false |
PizzaGames/emulio | core/src/main/com/github/emulio/ui/screens/util/FontCache.kt | 1 | 1770 | package com.github.emulio.ui.screens.util
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.files.FileHandle
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator
object FontCache {
private val freeFontGeneratorCache = mutableMapOf<FileHandle, FreeTypeFontGenerator>()
private val fontCache = mutableMapOf<Triple<FileHandle, Int, Color?>, BitmapFont>()
fun freeTypeFontGenerator() = getFreeTypeFontGenerator(Gdx.files.internal("fonts/RopaSans-Regular.ttf"))
fun getFont(fileHandle: FileHandle, fontSize: Int, fontColor: Color? = null): BitmapFont {
val triple = Triple(fileHandle, fontSize, fontColor)
return if (fontCache.containsKey(triple)) {
fontCache[triple]!!
} else {
val parameter = FreeTypeFontGenerator.FreeTypeFontParameter().apply {
size = fontSize
if (fontColor != null) {
color = fontColor
borderWidth = 0.4f
borderColor = fontColor
}
shadowColor = Color(0.2f, 0.2f, 0.2f, 0.2f)
shadowOffsetX = 1
shadowOffsetY = 1
}
getFreeTypeFontGenerator(fileHandle).generateFont(parameter).apply {
fontCache[triple] = this
}
}
}
private fun getFreeTypeFontGenerator(fileHandle: FileHandle): FreeTypeFontGenerator {
return if (freeFontGeneratorCache.containsKey(fileHandle)) {
freeFontGeneratorCache[fileHandle]!!
} else {
FreeTypeFontGenerator(fileHandle).apply { freeFontGeneratorCache[fileHandle] = this }
}
}
} | gpl-3.0 | e924682d812a9013fa4cc31060c48e3b | 34.42 | 108 | 0.641808 | 4.903047 | false | false | false | false |
spark/photon-tinker-android | mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepSetEthernetPinStatus.kt | 1 | 899 | package io.particle.mesh.setup.flow.setupsteps
import io.particle.firmwareprotos.ctrl.Config.Feature
import io.particle.mesh.setup.flow.*
import io.particle.mesh.setup.flow.context.SetupContexts
class StepSetEthernetPinStatus(val flowUi: FlowUiDelegate) : MeshSetupStep() {
override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) {
val activate = ctxs.device.shouldEthernetBeEnabled == true
flowUi.showGlobalProgressSpinner(true)
val target = ctxs.requireTargetXceiver()
target.sendSetFeature(Feature.ETHERNET_DETECTION, activate).throwOnErrorOrAbsent()
target.sendStopListeningMode().throwOnErrorOrAbsent()
flowUi.showGlobalProgressSpinner(false)
val toggleString = if (activate) "activated" else "deactivated"
flowUi.showCongratsScreen("Ethernet pins $toggleString", PostCongratsAction.RESET_TO_START)
}
}
| apache-2.0 | 0abe21f97e65535afb64417511d9595c | 38.086957 | 99 | 0.760845 | 4.540404 | false | false | false | false |
spark/photon-tinker-android | mesh/src/main/java/io/particle/mesh/ota/FirmwareUpdateManager.kt | 1 | 3008 | package io.particle.mesh.ota
import androidx.annotation.WorkerThread
import com.squareup.okhttp.OkHttpClient
import io.particle.android.sdk.cloud.ParticleCloud
import io.particle.android.sdk.cloud.ParticleDevice.ParticleDeviceType
import io.particle.mesh.common.Result
import io.particle.mesh.setup.connection.ProtocolTransceiver
import io.particle.mesh.setup.connection.ResultCode
import io.particle.mesh.setup.flow.throwOnErrorOrAbsent
import kotlinx.coroutines.delay
import mu.KotlinLogging
import java.net.URL
enum class FirmwareUpdateResult {
HAS_LATEST_FIRMWARE,
DEVICE_IS_UPDATING
}
class FirmwareUpdateManager(
private val cloud: ParticleCloud,
private val okHttpClient: OkHttpClient
) {
private val log = KotlinLogging.logger {}
@WorkerThread
suspend fun needsUpdate(
xceiver: ProtocolTransceiver,
deviceType: ParticleDeviceType
): Boolean {
return getUpdateUrl(xceiver, deviceType) != null
}
@WorkerThread
suspend fun startUpdateIfNecessary(
xceiver: ProtocolTransceiver,
deviceType: ParticleDeviceType,
listener: ProgressListener
): FirmwareUpdateResult {
val firmwareUpdateUrl = getUpdateUrl(xceiver, deviceType)
if (firmwareUpdateUrl == null) {
return FirmwareUpdateResult.HAS_LATEST_FIRMWARE
}
val updater = FirmwareUpdater(xceiver, okHttpClient)
updater.updateFirmware(firmwareUpdateUrl) {
log.debug { "Firmware progress: $it" }
listener(it)
}
xceiver.disconnect()
return FirmwareUpdateResult.DEVICE_IS_UPDATING
}
@WorkerThread
private suspend fun getUpdateUrl(
xceiver: ProtocolTransceiver,
deviceType: ParticleDeviceType
): URL? {
val systemFwVers = xceiver.sendGetSystemFirmwareVersion().throwOnErrorOrAbsent()
log.info { "Getting update URL for device currently on firmware version ${systemFwVers.version}" }
val (ncpVersion, ncpModuleVersion) = getNcpVersions(xceiver)
val updateUrl = cloud.getFirmwareUpdateInfo(
deviceType.intValue,
systemFwVers.version,
ncpVersion,
ncpModuleVersion
)
log.info { "Update URL for device $updateUrl" }
return updateUrl
}
private suspend fun getNcpVersions(xceiver: ProtocolTransceiver): Pair<String?, Int?> {
val ncpFwReply = xceiver.sendGetNcpFirmwareVersion()
return when (ncpFwReply) {
is Result.Present -> Pair(ncpFwReply.value.version, ncpFwReply.value.moduleVersion)
is Result.Error -> {
if (ncpFwReply.error == ResultCode.NOT_SUPPORTED) {
Pair(null, null)
} else {
throw IllegalStateException("Error getting NCP FW version: ${ncpFwReply.error}")
}
}
is Result.Absent -> throw IllegalStateException("No result received!")
}
}
} | apache-2.0 | 7b3fee5c635968b960021e8d71320710 | 30.673684 | 106 | 0.676197 | 4.955519 | false | false | false | false |
square/leakcanary | shark-graph/src/test/java/shark/HprofWriterTest.kt | 2 | 6891 | package shark
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import shark.HprofHeapGraph.Companion.openHeapGraph
import shark.HprofRecord.HeapDumpEndRecord
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.ClassDumpRecord
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.ClassDumpRecord.FieldRecord
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.ClassDumpRecord.StaticFieldRecord
import shark.HprofRecord.HeapDumpRecord.ObjectRecord.InstanceDumpRecord
import shark.HprofRecord.LoadClassRecord
import shark.HprofRecord.StringRecord
import shark.StreamingRecordReaderAdapter.Companion.asStreamingRecordReader
import shark.ValueHolder.BooleanHolder
import shark.ValueHolder.IntHolder
import shark.ValueHolder.ReferenceHolder
class HprofWriterTest {
private var lastId = 0L
private val id: Long
get() = ++lastId
@Test
fun writeAndReadStringRecord() {
val record = StringRecord(id, MAGIC_WAND_CLASS_NAME)
val bytes = listOf(record).asHprofBytes()
val readRecords = bytes.readAllRecords()
assertThat(readRecords).hasSize(1)
assertThat(readRecords[0]).isInstanceOf(StringRecord::class.java)
assertThat((readRecords[0] as StringRecord).id).isEqualTo(record.id)
assertThat((readRecords[0] as StringRecord).string).isEqualTo(record.string)
}
@Test
fun writeAndReadClassRecord() {
val className = StringRecord(id, MAGIC_WAND_CLASS_NAME)
val loadClassRecord = LoadClassRecord(1, id, 1, className.id)
val classDump = ClassDumpRecord(
id = loadClassRecord.id,
stackTraceSerialNumber = 1,
superclassId = 0,
classLoaderId = 0,
signersId = 0,
protectionDomainId = 0,
instanceSize = 0,
staticFields = emptyList(),
fields = emptyList()
)
val bytes = listOf(className, loadClassRecord, classDump).asHprofBytes()
bytes.openHeapGraph().use { graph: HeapGraph ->
assertThat(graph.findClassByName(className.string)).isNotNull
}
}
@Test
fun writeAndReadStaticField() {
val className = StringRecord(id, MAGIC_WAND_CLASS_NAME)
val field1Name = StringRecord(id, "field1")
val field2Name = StringRecord(id, "field2")
val loadClassRecord = LoadClassRecord(1, id, 1, className.id)
val classDump = ClassDumpRecord(
id = loadClassRecord.id,
stackTraceSerialNumber = 1,
superclassId = 0,
classLoaderId = 0,
signersId = 0,
protectionDomainId = 0,
instanceSize = 0,
staticFields = listOf(
StaticFieldRecord(field1Name.id, PrimitiveType.BOOLEAN.hprofType, BooleanHolder(true)),
StaticFieldRecord(field2Name.id, PrimitiveType.INT.hprofType, IntHolder(42))
),
fields = emptyList()
)
val bytes = listOf(className, field1Name, field2Name, loadClassRecord, classDump)
.asHprofBytes()
bytes.openHeapGraph().use { graph: HeapGraph ->
val heapClass = graph.findClassByName(className.string)!!
val staticFields = heapClass.readStaticFields().toList()
assertThat(staticFields).hasSize(2)
assertThat(staticFields[0].name).isEqualTo(field1Name.string)
assertThat(staticFields[0].value.asBoolean).isEqualTo(true)
assertThat(staticFields[1].name).isEqualTo(field2Name.string)
assertThat(staticFields[1].value.asInt).isEqualTo(42)
}
}
@Test
fun writeAndReadHprof() {
val records = createRecords()
val bytes = records.asHprofBytes()
val readRecords = bytes.readAllRecords()
assertThat(readRecords).hasSameSizeAs(records + HeapDumpEndRecord)
bytes.openHeapGraph().use { graph: HeapGraph ->
val treasureChestClass = graph.findClassByName(
TREASURE_CHEST_CLASS_NAME
)!!
val baguetteInstance =
treasureChestClass[CONTENT_FIELD_NAME]!!.value.asObject!!.asInstance!!
assertThat(
baguetteInstance[BAGUETTE_CLASS_NAME, ANSWER_FIELD_NAME]!!.value.asInt!!
).isEqualTo(42)
}
}
private fun createRecords(): List<HprofRecord> {
val magicWandClassName = StringRecord(id, MAGIC_WAND_CLASS_NAME)
val baguetteClassName = StringRecord(id, BAGUETTE_CLASS_NAME)
val answerFieldName = StringRecord(id, ANSWER_FIELD_NAME)
val treasureChestClassName = StringRecord(
id,
TREASURE_CHEST_CLASS_NAME
)
val contentFieldName = StringRecord(id, CONTENT_FIELD_NAME)
val loadMagicWandClass = LoadClassRecord(1, id, 1, magicWandClassName.id)
val loadBaguetteClass = LoadClassRecord(1, id, 1, baguetteClassName.id)
val loadTreasureChestClass = LoadClassRecord(1, id, 1, treasureChestClassName.id)
val magicWandClassDump = ClassDumpRecord(
id = loadMagicWandClass.id,
stackTraceSerialNumber = 1,
superclassId = 0,
classLoaderId = 0,
signersId = 0,
protectionDomainId = 0,
instanceSize = 0,
staticFields = emptyList(),
fields = emptyList()
)
val baguetteClassDump = ClassDumpRecord(
id = loadBaguetteClass.id,
stackTraceSerialNumber = 1,
superclassId = loadMagicWandClass.id,
classLoaderId = 0,
signersId = 0,
protectionDomainId = 0,
instanceSize = 0,
staticFields = emptyList(),
fields = listOf(FieldRecord(answerFieldName.id, PrimitiveType.INT.hprofType))
)
val baguetteInstanceDump = InstanceDumpRecord(
id = id,
stackTraceSerialNumber = 1,
classId = loadBaguetteClass.id,
fieldValues = byteArrayOf(0x0, 0x0, 0x0, 0x2a)
)
val treasureChestClassDump = ClassDumpRecord(
id = loadTreasureChestClass.id,
stackTraceSerialNumber = 1,
superclassId = 0,
classLoaderId = 0,
signersId = 0,
protectionDomainId = 0,
instanceSize = 0,
staticFields = listOf(
StaticFieldRecord(
contentFieldName.id, PrimitiveType.REFERENCE_HPROF_TYPE,
ReferenceHolder(baguetteInstanceDump.id)
)
),
fields = emptyList()
)
return listOf(
magicWandClassName, baguetteClassName, answerFieldName, treasureChestClassName,
contentFieldName, loadMagicWandClass,
loadBaguetteClass, loadTreasureChestClass,
magicWandClassDump, baguetteClassDump, baguetteInstanceDump, treasureChestClassDump
)
}
private fun DualSourceProvider.readAllRecords(): MutableList<HprofRecord> {
val readRecords = mutableListOf<HprofRecord>()
StreamingHprofReader.readerFor(this).asStreamingRecordReader()
.readRecords(setOf(HprofRecord::class)) { position, record ->
readRecords += record
}
return readRecords
}
companion object {
const val MAGIC_WAND_CLASS_NAME = "com.example.MagicWand"
const val BAGUETTE_CLASS_NAME = "com.example.Baguette"
const val ANSWER_FIELD_NAME = "answer"
const val TREASURE_CHEST_CLASS_NAME = "com.example.TreasureChest"
const val CONTENT_FIELD_NAME = "content"
}
}
| apache-2.0 | dc948ff4f4dacc6a44705c8138829895 | 33.979695 | 95 | 0.713975 | 4.542518 | false | false | false | false |
gravidence/gravifon | gravifon/src/main/kotlin/org/gravidence/gravifon/ui/PlaybackControlComposable.kt | 1 | 6898 | package org.gravidence.gravifon.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.Button
import androidx.compose.material.Icon
import androidx.compose.material.Slider
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.SkipNext
import androidx.compose.material.icons.filled.SkipPrevious
import androidx.compose.material.icons.filled.Stop
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import org.gravidence.gravifon.GravifonContext
import org.gravidence.gravifon.event.EventBus
import org.gravidence.gravifon.event.playback.PausePlaybackEvent
import org.gravidence.gravifon.event.playback.RepositionPlaybackPointAbsoluteEvent
import org.gravidence.gravifon.event.playback.StopPlaybackEvent
import org.gravidence.gravifon.event.playlist.PlayCurrentFromPlaylistEvent
import org.gravidence.gravifon.event.playlist.PlayNextFromPlaylistEvent
import org.gravidence.gravifon.event.playlist.PlayPreviousFromPlaylistEvent
import org.gravidence.gravifon.playback.PlaybackStatus
import org.gravidence.gravifon.ui.state.PlaybackPositionState
import org.gravidence.gravifon.util.DurationUtil
import org.gravidence.gravifon.util.DualStateObject
import kotlin.time.DurationUnit
import kotlin.time.toDuration
class PlaybackControlState {
companion object {
fun onPrev() {
GravifonContext.activePlaylist.value?.let { EventBus.publish(PlayPreviousFromPlaylistEvent(it)) }
}
fun onStop() {
EventBus.publish(StopPlaybackEvent())
}
fun onPause() {
EventBus.publish(PausePlaybackEvent())
}
fun onPlay() {
GravifonContext.activePlaylist.value?.let { EventBus.publish(PlayCurrentFromPlaylistEvent(it)) }
}
fun onNext() {
GravifonContext.activePlaylist.value?.let { EventBus.publish(PlayNextFromPlaylistEvent(it)) }
}
fun onPositionChange(rawPosition: Float) {
val position = rawPosition.toLong().toDuration(DurationUnit.MILLISECONDS)
EventBus.publish(RepositionPlaybackPointAbsoluteEvent(position))
}
fun elapsedTime(playbackPositionState: PlaybackPositionState): String {
return DurationUtil.formatShortHours(playbackPositionState.runningPosition)
}
fun remainingTime(playbackPositionState: PlaybackPositionState): String {
return DurationUtil.formatShortHours(playbackPositionState.endingPosition.minus(playbackPositionState.runningPosition))
}
}
}
@Composable
fun PlaybackControlComposable() {
Box(
modifier = Modifier
.padding(5.dp)
) {
Column {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(5.dp),
modifier = Modifier
.padding(10.dp)
) {
PlaybackControl()
Spacer(Modifier.width(5.dp))
PositionControl()
}
}
}
}
@Composable
fun PlaybackControl() {
val playbackButtonModifier = remember {
DualStateObject(
Modifier
.size(48.dp)
.padding(0.dp),
Modifier
.size(52.dp)
.padding(0.dp)
)
}
val playbackIconModifier = remember {
DualStateObject(
Modifier
.requiredSize(24.dp),
Modifier
.requiredSize(32.dp)
)
}
val playbackStatus = GravifonContext.playbackStatusState.value
Button(
onClick = PlaybackControlState::onPrev,
modifier = playbackButtonModifier.state()
) {
Icon(
imageVector = Icons.Filled.SkipPrevious,
contentDescription = "Previous",
modifier = playbackIconModifier.state()
)
}
Button(
onClick = PlaybackControlState::onStop,
modifier = playbackButtonModifier.state(playbackStatus != PlaybackStatus.STOPPED)
) {
Icon(
imageVector = Icons.Filled.Stop,
contentDescription = "Stop",
modifier = playbackIconModifier.state(playbackStatus != PlaybackStatus.STOPPED)
)
}
Button(
onClick = PlaybackControlState::onPause,
modifier = playbackButtonModifier.state(playbackStatus != PlaybackStatus.PAUSED)
) {
Icon(
imageVector = Icons.Filled.Pause,
contentDescription = "Pause",
modifier = playbackIconModifier.state(playbackStatus != PlaybackStatus.PAUSED)
)
}
Button(
onClick = PlaybackControlState::onPlay,
modifier = playbackButtonModifier.state(playbackStatus != PlaybackStatus.PLAYING)
) {
Icon(
imageVector = Icons.Filled.PlayArrow,
contentDescription = "Play",
modifier = playbackIconModifier.state(playbackStatus != PlaybackStatus.PLAYING)
)
}
Button(
onClick = PlaybackControlState::onNext,
modifier = playbackButtonModifier.state()
) {
Icon(
imageVector = Icons.Filled.SkipNext,
contentDescription = "Next",
modifier = playbackIconModifier.state()
)
}
}
@Composable
fun RowScope.PositionControl() {
val playbackPositionState = GravifonContext.playbackPositionState.value
Text(text = PlaybackControlState.elapsedTime(playbackPositionState), fontWeight = FontWeight.Light)
Slider(
value = playbackPositionState.runningPosition
.inWholeMilliseconds.toFloat(),
valueRange = 0f..playbackPositionState.endingPosition
.inWholeMilliseconds.toFloat(),
onValueChange = {
PlaybackControlState.onPositionChange(it)
},
modifier = Modifier
.weight(1f)
.fillMaxWidth()
)
Text(text = "-${PlaybackControlState.remainingTime(playbackPositionState)}", fontWeight = FontWeight.Light)
} | mit | 96c450ed6a13edfaa9b8cb56300f59ab | 33.323383 | 131 | 0.690635 | 5.194277 | false | false | false | false |
xfournet/intellij-community | platform/diff-impl/src/com/intellij/diff/util/DiffLineMarkerRenderer.kt | 1 | 4413 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff.util
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.markup.LineMarkerRendererEx
import com.intellij.openapi.editor.markup.RangeHighlighter
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.Rectangle
internal class DiffLineMarkerRenderer(
private val myHighlighter: RangeHighlighter,
private val myDiffType: TextDiffType,
private val myIgnoredFoldingOutline: Boolean,
private val myResolved: Boolean,
private val mySkipped: Boolean,
private val myHideWithoutLineNumbers: Boolean,
private val myEmptyRange: Boolean,
private val myFirstLine: Boolean,
private val myLastLine: Boolean
) : LineMarkerRendererEx {
override fun paint(editor: Editor, g: Graphics, range: Rectangle) {
editor as EditorEx
g as Graphics2D
val gutter = editor.gutterComponentEx
var x1 = 0
val x2 = x1 + gutter.width
var y1: Int
var y2: Int
if (myEmptyRange && myLastLine) {
y1 = DiffDrawUtil.lineToY(editor, DiffUtil.getLineCount(editor.document))
y2 = y1
}
else {
val startLine = editor.document.getLineNumber(myHighlighter.startOffset)
val endLine = editor.document.getLineNumber(myHighlighter.endOffset) + 1
y1 = DiffDrawUtil.lineToY(editor, startLine)
y2 = if (myEmptyRange) y1 else DiffDrawUtil.lineToY(editor, endLine)
}
if (myEmptyRange && myFirstLine) {
y1++
y2++
}
if (myHideWithoutLineNumbers && !editor.getSettings().isLineNumbersShown) {
// draw only in "editor" part of the gutter (rightmost part of foldings' "[+]" )
x1 = gutter.whitespaceSeparatorOffset
}
else {
val annotationsOffset = gutter.annotationsAreaOffset
val annotationsWidth = gutter.annotationsAreaWidth
if (annotationsWidth != 0) {
drawMarker(editor, g, x1, annotationsOffset, y1, y2)
x1 = annotationsOffset + annotationsWidth
}
}
if (mySkipped) {
val xOutline = gutter.whitespaceSeparatorOffset
drawMarker(editor, g, xOutline, x2, y1, y2, paintBackground = false, paintBorder = true) // over "editor"
drawMarker(editor, g, x1, xOutline, y1, y2, paintBackground = true, paintBorder = true, useIgnoredBackgroundColor = true) // over "gutter"
}
else if (myIgnoredFoldingOutline) {
val xOutline = gutter.whitespaceSeparatorOffset
drawMarker(editor, g, xOutline, x2, y1, y2, useIgnoredBackgroundColor = true) // over "editor"
drawMarker(editor, g, x1, xOutline, y1, y2) // over "gutter"
}
else {
drawMarker(editor, g, x1, x2, y1, y2)
}
}
private fun drawMarker(editor: Editor, g: Graphics2D,
x1: Int, x2: Int, y1: Int, y2: Int,
paintBackground: Boolean = !myResolved,
paintBorder: Boolean = myResolved,
dottedLine: Boolean = myResolved,
useIgnoredBackgroundColor: Boolean = false) {
if (x1 >= x2) return
val color = myDiffType.getColor(editor)
if (y2 - y1 > 2) {
if (paintBackground) {
g.color = if (useIgnoredBackgroundColor) myDiffType.getIgnoredColor(editor) else color
g.fillRect(x1, y1, x2 - x1, y2 - y1)
}
if (paintBorder) {
DiffDrawUtil.drawChunkBorderLine(g, x1, x2, y1, color, false, dottedLine)
DiffDrawUtil.drawChunkBorderLine(g, x1, x2, y2 - 1, color, false, dottedLine)
}
}
else {
// range is empty - insertion or deletion
// Draw 2 pixel line in that case
DiffDrawUtil.drawChunkBorderLine(g, x1, x2, y1 - 1, color, true, dottedLine)
}
}
override fun getPosition(): LineMarkerRendererEx.Position = LineMarkerRendererEx.Position.CUSTOM
}
| apache-2.0 | ddf190a1444cab9aa169bf5ad0ac987b | 36.084034 | 144 | 0.682982 | 3.975676 | false | false | false | false |
yshrsmz/monotweety | app2/src/main/java/net/yslibrary/monotweety/App.kt | 1 | 1799 | package net.yslibrary.monotweety
import android.app.Application
import android.content.Context
import com.codingfeline.twitter4kt.core.ConsumerKeys
import com.codingfeline.twitter4kt.core.model.oauth1a.AccessToken
import kotlinx.datetime.Clock
class App : Application() {
private val appComponent: AppComponent by lazy {
DaggerAppComponent.factory().create(
context = this,
consumerKeys = getTwitterConsumerKeys(),
clock = Clock.System
)
}
private var userComponent: UserComponent? = null
override fun onCreate() {
super.onCreate()
AppInitializerProvider.get().init(this)
}
companion object {
fun get(context: Context): App = context.applicationContext as App
fun appComponent(context: Context): AppComponent = get(context).appComponent
fun getOrCreateUserComponent(context: Context, accessToken: AccessToken): UserComponent {
val app = get(context)
return app.userComponent ?: kotlin.run {
val userComponent = app.appComponent.userComponent().build(accessToken)
app.userComponent = userComponent
userComponent
}
}
fun userComponent(context: Context): UserComponent {
val app = get(context)
return requireNotNull(app.userComponent)
}
fun clearUserComponent(context: Context) {
get(context).userComponent = null
}
}
}
private fun getTwitterConsumerKeys(): ConsumerKeys {
return ConsumerKeys(
key = (BuildConfig.TWITTER_API_KEY_1 to BuildConfig.TWITTER_API_KEY_2).concatAlternately(),
secret = (BuildConfig.TWITTER_API_SECRET_1 to BuildConfig.TWITTER_API_SECRET_2).concatAlternately()
)
}
| apache-2.0 | f320d7c301402e9b26bffa60ad68ee97 | 32.943396 | 107 | 0.665926 | 4.997222 | false | true | false | false |
Kotlin/dokka | integration-tests/gradle/src/integrationTest/kotlin/org/jetbrains/dokka/it/gradle/BasicGradleIntegrationTest.kt | 1 | 7919 | package org.jetbrains.dokka.it.gradle
import org.gradle.testkit.runner.TaskOutcome
import org.junit.runners.Parameterized.Parameters
import java.io.File
import kotlin.test.*
class BasicGradleIntegrationTest(override val versions: BuildVersions) : AbstractGradleIntegrationTest() {
companion object {
@get:JvmStatic
@get:Parameters(name = "{0}")
val versions = TestedVersions.BASE
}
@BeforeTest
fun prepareProjectFiles() {
val templateProjectDir = File("projects", "it-basic")
templateProjectDir.listFiles().orEmpty()
.filter { it.isFile }
.forEach { topLevelFile -> topLevelFile.copyTo(File(projectDir, topLevelFile.name)) }
File(templateProjectDir, "src").copyRecursively(File(projectDir, "src"))
val customResourcesDir = File(templateProjectDir, "customResources")
if (customResourcesDir.exists() && customResourcesDir.isDirectory) {
val destination = File(projectDir.parentFile, "customResources")
destination.mkdirs()
destination.deleteRecursively()
customResourcesDir.copyRecursively(destination)
}
}
@Test
fun execute() {
runAndAssertOutcome(TaskOutcome.SUCCESS)
runAndAssertOutcome(TaskOutcome.UP_TO_DATE)
}
private fun runAndAssertOutcome(expectedOutcome: TaskOutcome) {
val result = createGradleRunner(
"dokkaHtml",
"dokkaJavadoc",
"dokkaGfm",
"dokkaJekyll",
"-i",
"-s"
).buildRelaxed()
assertEquals(expectedOutcome, assertNotNull(result.task(":dokkaHtml")).outcome)
assertEquals(expectedOutcome, assertNotNull(result.task(":dokkaJavadoc")).outcome)
assertEquals(expectedOutcome, assertNotNull(result.task(":dokkaGfm")).outcome)
assertEquals(expectedOutcome, assertNotNull(result.task(":dokkaJekyll")).outcome)
File(projectDir, "build/dokka/html").assertHtmlOutputDir()
File(projectDir, "build/dokka/javadoc").assertJavadocOutputDir()
File(projectDir, "build/dokka/gfm").assertGfmOutputDir()
File(projectDir, "build/dokka/jekyll").assertJekyllOutputDir()
}
private fun File.assertHtmlOutputDir() {
assertTrue(isDirectory, "Missing dokka html output directory")
val imagesDir = File(this, "images")
assertTrue(imagesDir.isDirectory, "Missing images directory")
val scriptsDir = File(this, "scripts")
assertTrue(scriptsDir.isDirectory, "Missing scripts directory")
val reactFile = File(this, "scripts/main.js")
assertTrue(reactFile.isFile, "Missing main.js")
val stylesDir = File(this, "styles")
assertTrue(stylesDir.isDirectory, "Missing styles directory")
val reactStyles = File(this, "styles/main.css")
assertTrue(reactStyles.isFile, "Missing main.css")
val navigationHtml = File(this, "navigation.html")
assertTrue(navigationHtml.isFile, "Missing navigation.html")
val moduleOutputDir = File(this, "-basic -project")
assertTrue(moduleOutputDir.isDirectory, "Missing module directory")
val moduleIndexHtml = File(this, "index.html")
assertTrue(moduleIndexHtml.isFile, "Missing module index.html")
val modulePackageDir = File(moduleOutputDir, "it.basic")
assertTrue(modulePackageDir.isDirectory, "Missing it.basic package directory")
val modulePackageIndexHtml = File(modulePackageDir, "index.html")
assertTrue(modulePackageIndexHtml.isFile, "Missing module package index.html")
val moduleJavaPackageDir = File(moduleOutputDir, "it.basic.java")
assertTrue(moduleJavaPackageDir.isDirectory, "Missing it.basic.java package directory")
allHtmlFiles().forEach { file ->
assertContainsNoErrorClass(file)
assertNoUnresolvedLinks(file)
assertNoHrefToMissingLocalFileOrDirectory(file)
assertNoSuppressedMarker(file)
assertNoEmptyLinks(file)
assertNoEmptySpans(file)
}
assertTrue(
allHtmlFiles().any { file -> "Basic Project" in file.readText() },
"Expected configured moduleName to be present in html"
)
assertTrue(
allHtmlFiles().any { file ->
"https://github.com/Kotlin/dokka/tree/master/" +
"integration-tests/gradle/projects/it-basic/" +
"src/main/kotlin/it/basic/PublicClass.kt" in file.readText()
},
"Expected `PublicClass` source link to GitHub"
)
assertTrue(
allHtmlFiles().any { file ->
"https://github.com/Kotlin/dokka/tree/master/" +
"integration-tests/gradle/projects/it-basic/" +
"src/main/java/it/basic/java/SampleJavaClass.java" in file.readText()
},
"Expected `SampleJavaClass` source link to GitHub"
)
val anchorsShouldNotHaveHashes = "<a data-name=\".*#.*\"\\sanchor-label=\"*.*\">".toRegex()
assertTrue(
allHtmlFiles().all { file ->
!anchorsShouldNotHaveHashes.containsMatchIn(file.readText())
},
"Anchors should not have hashes inside"
)
assertEquals(
"""#logo{background-image:url('https://upload.wikimedia.org/wikipedia/commons/9/9d/Ubuntu_logo.svg');}""",
stylesDir.resolve("logo-styles.css").readText().replace("\\s".toRegex(), ""),
)
assertTrue(stylesDir.resolve("custom-style-to-add.css").isFile)
assertEquals("""/* custom stylesheet */""", stylesDir.resolve("custom-style-to-add.css").readText())
allHtmlFiles().forEach { file ->
if (file.name != "navigation.html") assertTrue(
"custom-style-to-add.css" in file.readText(),
"custom styles not added to html file ${file.name}"
)
}
assertTrue(imagesDir.resolve("custom-resource.svg").isFile)
assertConfiguredVisibility(this)
}
private fun File.assertJavadocOutputDir() {
assertTrue(isDirectory, "Missing dokka javadoc output directory")
val indexFile = File(this, "index.html")
assertTrue(indexFile.isFile, "Missing index.html")
assertTrue(
"""<title>Basic Project 1.7.20-SNAPSHOT API </title>""" in indexFile.readText(),
"Header with version number not present in index.html"
)
assertTrue {
allHtmlFiles().all {
"0.0.1" !in it.readText()
}
}
}
private fun File.assertGfmOutputDir() {
assertTrue(isDirectory, "Missing dokka gfm output directory")
}
private fun File.assertJekyllOutputDir() {
assertTrue(isDirectory, "Missing dokka jekyll output directory")
}
private fun assertConfiguredVisibility(outputDir: File) {
val allHtmlFiles = outputDir.allHtmlFiles().toList()
assertContentVisibility(
contentFiles = allHtmlFiles,
documentPublic = true,
documentProtected = true, // sourceSet documentedVisibilities
documentInternal = false,
documentPrivate = true // for overriddenVisibility package
)
assertContainsFilePaths(
outputFiles = allHtmlFiles,
expectedFilePaths = listOf(
// documentedVisibilities is overridden for package `overriddenVisibility` specifically
// to include private code, so html pages for it are expected to have been created
Regex("it\\.overriddenVisibility/-visible-private-class/private-method\\.html"),
Regex("it\\.overriddenVisibility/-visible-private-class/private-val\\.html"),
)
)
}
}
| apache-2.0 | a5e67c683df2521b5bac3466d572eec6 | 38.79397 | 118 | 0.633792 | 4.885256 | false | false | false | false |
ac-opensource/Matchmaking-App | app/src/main/java/com/youniversals/playupgo/flux/model/MatchModel.kt | 1 | 2278 | package com.youniversals.playupgo.flux.model
import com.onesignal.OneSignal
import com.pixplicity.easyprefs.library.Prefs
import com.youniversals.playupgo.api.RestApi
import com.youniversals.playupgo.data.Match
import com.youniversals.playupgo.data.MatchJson
import com.youniversals.playupgo.data.User
import com.youniversals.playupgo.data.UserMatch
import rx.Observable
import java.util.concurrent.TimeUnit
/**
* YOYO HOLDINGS
* @author A-Ar Andrew Concepcion
* *
* @since 20/12/2016
*/
class MatchModel(val restApi: RestApi) {
fun getUsersByMatchId(matchId: Long): Observable<List<UserMatch>> {
val filterString = """{"where":{"matchId": $matchId}, "include":[{"relation": "user"}]}"""
return restApi.getUsersByMatchId(filterString)
}
fun getNearbyMatches(latLng: String, maxDistance: Int, sportId: Long): Observable<List<Match>> {
return restApi.nearMatches(location=latLng, maxDistance = maxDistance, sportId = sportId).timeout(3000, TimeUnit.SECONDS)
}
fun joinMatch(matchId: Long, group: Long) : Observable<UserMatch> {
val userMatch = UserMatch(matchId, Prefs.getLong("userId", 0), group = group)
return restApi.joinMatch(userMatch).map {
OneSignal.sendTag("matchId", matchId.toString())
it.copy(user = User(
id = Prefs.getLong("userId", 0),
username = Prefs.getString("username", "")))
}
}
fun acceptJoinMatch(um: UserMatch) : Observable<UserMatch> {
val userMatch = UserMatch(um.matchId, um.userId, id = um.id!!, group = um.group, isApproved = true)
return restApi.acceptJoinMatch(userMatch).map {
OneSignal.sendTag("matchId", um.matchId.toString())
it.copy(user = User(
id = um.userId,
username = um.user!!.username))
}
}
fun createMatch(newMatch: MatchJson): Observable<Match> {
return restApi.createMatch(newMatch).flatMap { createdMatch ->
OneSignal.sendTag("matchId", createdMatch.id.toString())
joinMatch(createdMatch.id, group = 1).map { createdMatch }
}
}
fun getMatches(userId: Long): Observable<List<Match>> {
return restApi.getMatches(userId)
}
}
| agpl-3.0 | 09345932cb61a2923db76420b8fe1da7 | 35.741935 | 129 | 0.661106 | 4.010563 | false | false | false | false |
toastkidjp/Yobidashi_kt | app/src/main/java/jp/toastkid/yobidashi/browser/webview/WebViewPool.kt | 2 | 2820 | package jp.toastkid.yobidashi.browser.webview
import android.content.Context
import android.webkit.WebView
import androidx.annotation.ColorInt
import androidx.collection.LruCache
/**
* [WebView] pool.
*
* @param poolSize (Optional) Count of containing [WebView] instance. If you don't passed it,
* it use default size.
*
* @author toastkidjp
*/
internal class WebViewPool(poolSize: Int = DEFAULT_MAXIMUM_POOL_SIZE) {
/**
* Containing [WebView] instance.
*/
private val pool: LruCache<String, WebView> =
LruCache(if (0 < poolSize) poolSize else DEFAULT_MAXIMUM_POOL_SIZE)
/**
* Latest tab's ID.
*/
private var latestTabId: String? = null
/**
* Get specified [WebView] by tab ID.
*
* @param tabId tab ID
* @return [WebView] (Nullable)
*/
fun get(tabId: String?): WebView? {
if (tabId == null) {
return null
}
latestTabId = tabId
return pool[tabId]
}
/**
* Get latest [WebView].
*
* @return [WebView] (Nullable)
*/
fun getLatest(): WebView? = latestTabId?.let { return@let pool.get(it) }
fun put(tabId: String, webView: WebView) {
pool.put(tabId, webView)
}
fun containsKey(tabId: String?) = tabId != null && pool.snapshot().containsKey(tabId)
/**
* Remove [WebView] by tab ID.
*
* @param tabId tab ID
*/
fun remove(tabId: String?) {
if (tabId == null) {
return
}
pool.remove(tabId)
}
/**
* Resize poll size.
*
* @param newSize new pool size
*/
fun resize(newSize: Int) {
if (newSize == pool.maxSize() || newSize <= 0) {
return
}
pool.resize(newSize)
}
fun applyNewAlpha(@ColorInt newAlphaBackground: Int) {
pool.snapshot().values.forEach { it.setBackgroundColor(newAlphaBackground) }
}
fun onResume() {
getLatest()?.resumeTimers()
pool.snapshot().values.forEach { it.onResume() }
}
fun onPause() {
getLatest()?.pauseTimers()
pool.snapshot().values.forEach { it.onPause() }
}
fun storeStates(context: Context) {
val useCase = WebViewStateUseCase.make(context)
pool.snapshot().entries.forEach {
useCase.store(it.value, it.key)
}
}
/**
* Destroy all [WebView].
*/
fun dispose() {
pool.snapshot().values.forEach { it.destroy() }
pool.evictAll()
}
fun getTabId(webView: WebView): String? {
return pool.snapshot().entries.firstOrNull { it.value.hashCode() == webView.hashCode() }?.key
}
companion object {
/**
* Default pool size.
*/
private const val DEFAULT_MAXIMUM_POOL_SIZE = 6
}
}
| epl-1.0 | ad773e6634e47f98aaacf90fe7ab56fe | 21.741935 | 101 | 0.571986 | 4.110787 | false | true | false | false |
google/prefab | api/src/main/kotlin/com/google/prefab/api/Package.kt | 1 | 3252 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.prefab.api
import java.io.File
import java.nio.file.Path
/**
* Checks if a version string is in the right format for CMake.
*
* @param[version] The version string.
* @return True if the version string is compatible.
*/
internal fun isValidVersionForCMake(version: String): Boolean =
Regex("""^\d+(\.\d+(\.\d+(\.\d+)?)?)?$""").matches(version)
/**
* A Prefab package.
*
* @property[path] The path to the package on disk.
*/
class Package(val path: Path) {
/**
* The metadata object loaded from the prefab.json.
*/
private val metadata: PackageMetadataV1 = PackageMetadata.loadAndMigrate(
SchemaVersion.from(path), path
)
/**
* The name of the package.
*/
val name: String = metadata.name
/**
* The list of other packages this package requires.
*/
val dependencies: List<String> = metadata.dependencies
/**
* The version of the package
*/
val version: String? = metadata.version.also {
require(it == null || isValidVersionForCMake(it)) {
"version must be compatible with CMake, if present"
}
}
/**
* The schema version of the package being loaded.
*
* If successfully constructed the data will have been migrated to the
* current schema version. This property defines the schema version used by
* the files being loaded.
*/
private val schemaVersion: SchemaVersion =
SchemaVersion.from(metadata.schemaVersion)
/**
* The path to the package's module directory.
*/
private val moduleDir: File = path.resolve("modules").toFile()
/**
* The list of modules in this package.
*/
val modules: List<Module> =
// Some file browsers helpfully create extra hidden files in any
// directory they view. It may have been better to just ignore anything
// without a module.json, but https://github.com/google/prefab/pull/106
// made module.json optional, so technically any directory is a valid
// module now and we need a new schema revision to change that behavior.
// We could alternatively add an explicit module list to prefab.json,
// but that would also require a new schema revision.
//
// For now, just ignore all files (fixes the .DS_Store case) and any
// hidden directories (just in case).
moduleDir.listFiles()?.filter { it.isDirectory && !it.isHidden }
?.map { Module(it.toPath(), this, schemaVersion) }
?: throw RuntimeException(
"Unable to retrieve file list for $moduleDir"
)
}
| apache-2.0 | e49a298bacc2ba0d32adb21b4f9ccc61 | 32.525773 | 80 | 0.653444 | 4.370968 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.