repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/systems/multiblocks/ContextBlockComponent.kt
2
2087
package com.cout970.magneticraft.systems.multiblocks import com.cout970.magneticraft.Debug import com.cout970.magneticraft.misc.vector.plus import net.minecraft.block.state.IBlockState import net.minecraft.item.ItemStack import net.minecraft.util.math.BlockPos import net.minecraft.util.text.ITextComponent import net.minecraftforge.fml.common.FMLCommonHandler import net.minecraftforge.fml.relauncher.Side /** * Created by cout970 on 28/08/2016. */ class ContextBlockComponent( val getter: (MultiblockContext) -> IBlockState, val stack: ItemStack, val replacement: IBlockState, val errorMsg: (MultiblockContext, IBlockState, BlockPos) -> ITextComponent ) : IMultiblockComponent { override fun checkBlock(relativePos: BlockPos, context: MultiblockContext): List<ITextComponent> { val pos = context.center + relativePos val state = context.world.getBlockState(pos) if (state != getter(context)) { if (Debug.DEBUG && context.player != null && FMLCommonHandler.instance().effectiveSide == Side.SERVER) { context.world.setBlockState(pos, getter(context)) } return listOf(errorMsg(context, state, pos)) } return emptyList() } override fun getBlockData(relativePos: BlockPos, context: MultiblockContext): BlockData { val pos = context.center + relativePos val state = context.world.getBlockState(pos) return BlockData(state, pos) } override fun activateBlock(relativePos: BlockPos, context: MultiblockContext) { val pos = context.center + relativePos context.world.setBlockState(pos, replacement) super.activateBlock(relativePos, context) } override fun deactivateBlock(relativePos: BlockPos, context: MultiblockContext) { val pos = context.center + relativePos super.deactivateBlock(relativePos, context) context.world.setBlockState(pos, getter(context)) } override fun getBlueprintBlocks(multiblock: Multiblock, blockPos: BlockPos): List<ItemStack> = listOf(stack) }
gpl-2.0
20c290afbeb32b162590f4d81453b8ad
38.396226
116
0.720652
4.468951
false
false
false
false
lanhuaguizha/Christian
common/src/main/java/com/christian/common/CommonUtil.kt
1
4058
package com.christian.common import android.content.Context import android.view.inputmethod.InputMethodManager import android.widget.EditText import android.widget.ProgressBar import androidx.appcompat.widget.Toolbar import androidx.constraintlayout.widget.Guideline import java.text.SimpleDateFormat import java.util.* import java.util.regex.Pattern const val ADMIN_EMAIL = "[email protected]" const val ADMIN = "lanhuaguizha" const val GOSPEL_ZH = "gospel_zh" const val GOSPEL_EN = "gospel_en" const val GOSPELS = "gospels"// others, not contained in language list const val GOSPEL_ID = "gospel_id" const val DISCIPLE_EN = "disciple_en" const val DISCIPLE_ZH = "disciple_zh" const val DISCIPLES = "disciples"// others, not contained in language list const val TAB_ID = "tab_id" const val USER_ID = "user_id" const val ME_ZH = "me_zh" const val ME_EN = "me_en" const val MES = "mes" const val ME1_ZH = "me1_zh" const val ME1_EN = "me1_en" const val ME1S = "me1s" /** 判断设置页面显不显示退出按钮 */ const val showExitButton = "showExitButton" const val SETTING_ID = "setting_id" /** 用于获取跳转页面的标题栏名称 */ const val ACTION_BAR_TITLE = "action_bar_title" const val SUB_TITLE = "sub_title" /** * Dp转Px */ fun Context.dp2px(dp: Int): Int { val scale = resources.displayMetrics.density return (dp * scale + 0.5f).toInt() } /** * Px转Dp */ fun Context.px2dp(px: Int): Int { val scale = resources.displayMetrics.density return (px / scale + 0.5f).toInt() } /** * 判断是不是夜间模式 */ fun getDarkMode(): Boolean { return false } /** * 获取屏幕宽度 */ fun getDisplayWidth(context: Context): Int { val dm = context.resources.displayMetrics // var density: Float = dm.density // val width: Int = dm.widthPixels // var height: Int = dm.heightPixels return dm.widthPixels } /** * 获取屏幕高度 */ fun getDisplayHeight(context: Context): Int { val dm = context.resources.displayMetrics return dm.heightPixels } fun EditText.requestFocusWithKeyboard() { requestFocus() val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.showSoftInput(this, InputMethodManager.SHOW_FORCED) } /** * 获取当前日期和时间 */ fun getDateAndCurrentTime(): String { val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) return sdf.format(Date()) } /** * Immersive bar */ fun getStatusBarHeight(activity: Context): Int { val resourceId = activity.resources.getIdentifier("status_bar_height", "dimen", "android") return if (resourceId > 0) { activity.resources.getDimensionPixelSize(resourceId) } else 0 } fun immersiveToolbar(ctx: Context, tb: Toolbar) { val params = tb.layoutParams params.height = ctx.dp2px(56) + getStatusBarHeight(ctx) tb.layoutParams = params tb.setPadding(0, getStatusBarHeight(ctx), 0, 0) } fun getPropLan(): String = Locale.getDefault().language fun getLanMap(): Map<String, String> { val languages = mutableMapOf<String, String>() for ((i, locale) in Locale.getAvailableLocales().withIndex()) { languages[locale.language] = if (locale.displayName.contains(Regex("\\s"))) locale.language + "_" + " [" + locale.displayName.filterLanguageNameThroughDisplayName() + "]" else locale.language + "_" + " [" + locale.displayName + "]" } return languages } fun getLocaleLan() = getLanMap()[getPropLan()] fun String.filterLanguageNameThroughDisplayName(): String { val pattern = "^\\S*" val p = Pattern.compile(pattern) val m = p.matcher(this) if (m.find()) { return m.group(0).trim() } return "" } /** * Px转Sp */ fun Context.px2sp(px: Int): Int { val scale = resources.displayMetrics.scaledDensity return (px / scale + 0.5f).toInt() } /** * Sp转Px */ fun Context.sp2px(sp: Int): Int { val scale = resources.displayMetrics.scaledDensity return (sp * scale + 0.5f).toInt() }
gpl-3.0
6088b750fd4461a7769b14ce5d2e592c
23.748428
110
0.683274
3.379725
false
false
false
false
jilees/Fuel
fuel/src/main/kotlin/com/github/kittinunf/fuel/core/Response.kt
1
928
package com.github.kittinunf.fuel.core import java.net.URL class Response { lateinit var url: URL var httpStatusCode = -1 var httpResponseMessage = "" var httpResponseHeaders = emptyMap<String, List<String>>() var httpContentLength = 0L //data var data = ByteArray(0) override fun toString(): String { val elements = mutableListOf("<-- $httpStatusCode ($url)") //response message elements.add("Response : $httpResponseMessage") //content length elements.add("Length : $httpContentLength") //body elements.add("Body : ${if (data.isNotEmpty()) String(data) else "(empty)"}") //headers //headers elements.add("Headers : (${httpResponseHeaders.size})") for ((key, value) in httpResponseHeaders) { elements.add("$key : $value") } return elements.joinToString("\n") } }
mit
002c21a28c4c8fdeae2fa90bd36b2a0b
22.794872
84
0.604526
4.526829
false
false
false
false
toastkidjp/Jitte
app/src/test/java/jp/toastkid/yobidashi/wikipedia/random/WikipediaApiTest.kt
1
2930
/* * Copyright (c) 2021 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.wikipedia.random import io.mockk.MockKAnnotations import io.mockk.every import io.mockk.impl.annotations.InjectMockKs import io.mockk.impl.annotations.MockK import io.mockk.mockkConstructor import io.mockk.unmockkAll import io.mockk.verify import jp.toastkid.yobidashi.wikipedia.random.model.Query import jp.toastkid.yobidashi.wikipedia.random.model.Response import org.junit.After import org.junit.Before import org.junit.Test import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory class WikipediaApiTest { @InjectMockKs private lateinit var wikipediaApi: WikipediaApi @MockK private lateinit var urlDecider: UrlDecider @MockK private lateinit var converterFactory: MoshiConverterFactory @MockK private lateinit var requestBuilder: Retrofit.Builder @MockK private lateinit var retrofit: Retrofit @MockK private lateinit var service: WikipediaService @MockK private lateinit var call: Call<Response> @MockK private lateinit var response: retrofit2.Response<Response> @MockK private lateinit var body: Response @Before fun setUp() { MockKAnnotations.init(this) every { urlDecider.invoke() }.returns("https://en.wikipedia.org/") mockkConstructor(Retrofit.Builder::class) every { anyConstructed<Retrofit.Builder>().baseUrl(any<String>()) }.returns(requestBuilder) every { requestBuilder.addConverterFactory(any()) }.returns(requestBuilder) every { requestBuilder.build() }.returns(retrofit) every { retrofit.create(any<Class<WikipediaService>>()) }.returns(service) every { service.call() }.returns(call) every { call.execute() }.returns(response) every { response.body() }.returns(body) val query = Query() query.random = emptyArray() every { body.query }.returns(query) } @After fun tearDown() { unmockkAll() } @Test fun testInvoke() { wikipediaApi.invoke() verify(exactly = 1) { urlDecider.invoke() } verify(exactly = 1) { anyConstructed<Retrofit.Builder>().baseUrl(any<String>()) } verify(exactly = 1) { requestBuilder.addConverterFactory(any()) } verify(exactly = 1) { requestBuilder.build() } verify(exactly = 1) { retrofit.create(any<Class<WikipediaService>>()) } verify(exactly = 1) { service.call() } verify(exactly = 1) { call.execute() } verify(exactly = 1) { response.body() } verify(exactly = 1) { body.query } } }
epl-1.0
1ce4eec7846b5e339b6546d52bcaa1b7
29.852632
99
0.69727
4.386228
false
false
false
false
josesamuel/remoter
remoter/src/main/java/remoter/compiler/kbuilder/StringParamBuilder.kt
1
4856
package remoter.compiler.kbuilder import com.squareup.kotlinpoet.FunSpec import javax.lang.model.element.Element import javax.lang.model.element.ExecutableElement import javax.lang.model.element.VariableElement import javax.lang.model.type.TypeKind import javax.lang.model.type.TypeMirror /** * A [ParamBuilder] for String type parameters */ internal class StringParamBuilder(remoterInterfaceElement: Element, bindingManager: KBindingManager) : ParamBuilder(remoterInterfaceElement, bindingManager) { override fun writeParamsToProxy(param: VariableElement, paramType: ParamType, methodBuilder: FunSpec.Builder) { if (param.asType().kind == TypeKind.ARRAY) { if (paramType == ParamType.OUT) { writeArrayOutParamsToProxy(param, methodBuilder) } else { methodBuilder.addStatement("$DATA.writeStringArray(" + param.simpleName + ")") } } else { methodBuilder.addStatement("$DATA.writeString(" + param.simpleName + ")") } } override fun readResultsFromStub(methodElement: ExecutableElement, resultType: TypeMirror, methodBuilder: FunSpec.Builder) { if (resultType.kind == TypeKind.ARRAY) { methodBuilder.addStatement("$REPLY.writeStringArray($RESULT)") } else { methodBuilder.addStatement("$REPLY.writeString($RESULT)") } } override fun readResultsFromProxy(methodType: ExecutableElement, methodBuilder: FunSpec.Builder) { val resultMirror = methodType.getReturnAsTypeMirror() val resultType = methodType.getReturnAsKotlinType() if (resultMirror.kind == TypeKind.ARRAY) { methodBuilder.addStatement("$RESULT = $REPLY.createStringArray()") } else { if(resultType.isNullable) { methodBuilder.addStatement("$RESULT = $REPLY.readString()") } else { methodBuilder.addStatement("$RESULT = $REPLY.readString()!!") } } } override fun readOutResultsFromStub(param: VariableElement, paramType: ParamType, paramName: String, methodBuilder: FunSpec.Builder) { if (param.asType().kind == TypeKind.ARRAY) { methodBuilder.addStatement("$REPLY.writeStringArray($paramName)") } } override fun writeParamsToStub(methodType: ExecutableElement, param: VariableElement, paramType: ParamType, paramName: String, methodBuilder: FunSpec.Builder) { super.writeParamsToStub(methodType, param, paramType, paramName, methodBuilder) if (param.asType().kind == TypeKind.ARRAY) { if (paramType == ParamType.OUT) { writeOutParamsToStub(param, paramType, paramName, methodBuilder) } else { if (param.isNullable()) { methodBuilder.addStatement("$paramName = $DATA.createStringArray()") } else { methodBuilder.addStatement("$paramName = $DATA.createStringArray()!!") } } } else { if (param.isNullable()) { methodBuilder.addStatement("$paramName = $DATA.readString()") } else { methodBuilder.addStatement("$paramName = $DATA.readString()!!") } } } /** * Called to generate code to write @[remoter.annotations.ParamOut] params for stub */ override fun writeOutParamsToStub(param: VariableElement, paramType: ParamType, paramName: String, methodBuilder: FunSpec.Builder) { if (paramType != ParamType.IN) { methodBuilder.addStatement("val " + paramName + "_length = $DATA.readInt()") methodBuilder.beginControlFlow("if (" + paramName + "_length < 0 )") if (param.isNullable()) { methodBuilder.addStatement("$paramName = null") } else { methodBuilder.addStatement(paramName + " = " + param.asKotlinType() + "(0){\"\"}") } methodBuilder.endControlFlow() methodBuilder.beginControlFlow("else") methodBuilder.addStatement(paramName + " = " + param.asKotlinType().copy(false) + "(" + paramName + "_length){\"\"}") methodBuilder.endControlFlow() } } override fun readOutParamsFromProxy(param: VariableElement, paramType: ParamType, methodBuilder: FunSpec.Builder) { if (param.asType().kind == TypeKind.ARRAY && paramType != ParamType.IN) { if (param.isNullable()){ methodBuilder.beginControlFlow("if (${param.simpleName} != null)") } methodBuilder.addStatement("$REPLY.readStringArray(" + param.simpleName + ")") if (param.isNullable()){ methodBuilder.endControlFlow() } } } }
apache-2.0
a1b1cb0604704f20ddf467707890c897
43.154545
164
0.621293
5.30131
false
true
false
false
gameover-fwk/gameover-fwk
src/main/kotlin/gameover/fwk/libgdx/gfx/PerspectiveTiledMapRenderer.kt
1
2856
package gameover.fwk.libgdx.gfx import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.maps.MapLayer import com.badlogic.gdx.maps.MapLayers import com.badlogic.gdx.maps.tiled.TiledMap import com.badlogic.gdx.maps.tiled.TiledMapTileLayer import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer import com.badlogic.gdx.maps.tiled.tiles.AnimatedTiledMapTile /** * This tiled map renderer can be used to produce a perspective effect. * The rendering is separated in 3 methods: * `#renderFloorLayers()` * `#renderWallsLayers()`. * `#renderTopLayers()` * In order to differentiate at which level the layer is drawn, the renderer is looking to * property `level` which can be set to `walls` or to `top`. * By default, a layer is rendered at the floor layer. * The old method render will call the 3 methods in a row to have the old behaviour. */ open class PerspectiveTiledMapRenderer(m: TiledMap, unitScale: Float, spriteBatch: SpriteBatch, wallsLayerLevelName: String = "walls", topLayerLevelName: String = "top") : OrthogonalTiledMapRenderer(m, unitScale, spriteBatch) { private val wallsLayers = filterLayers(m.layers, wallsLayerLevelName) private val topLayers = filterLayers(m.layers, topLayerLevelName) open fun filterLayers(layers: MapLayers, levelName: String) : List<MapLayer> { val ret = ArrayList<MapLayer>() val it = layers.iterator() while (it.hasNext()) { val layer = it.next() val lvl = layer.properties.get("level", String::class.java) if (lvl != null && lvl == levelName) ret += layer } return ret } override fun render() { renderFloorLayers() renderWallsLayers() renderTopLayers() } open fun renderFloorLayers() { AnimatedTiledMapTile.updateAnimationBaseTime() val layers = map.layers batch.begin() for (i in 0 until layers.count) { val layer = layers.get(i) if ((!wallsLayers.contains(layer)) && (!topLayers.contains(layer)) && layer.isVisible) { if (layer is TiledMapTileLayer) { renderTileLayer(layer) } else { layer.objects.forEach { renderObject(it) } } } } batch.end() } open fun renderWallsLayers() { wallsLayers.forEach { renderSuppLayer(it) } } open fun renderTopLayers() { topLayers.forEach { renderSuppLayer(it) } } private fun renderSuppLayer(layer: MapLayer) { if (layer.isVisible) { batch.begin() if (layer is TiledMapTileLayer) renderTileLayer(layer) else layer.objects.forEach { renderObject(it) } batch.end() } } }
mit
3f3565fc907cf243de5530c347d54085
33.841463
169
0.638305
4.13913
false
false
false
false
google/evergreen-checker
evergreen/src/main/java/app/evergreen/ui/QrCodeFragment.kt
1
2112
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package app.evergreen.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.fragment.app.DialogFragment import app.evergreen.R import app.evergreen.services.log import coil.load import java.net.URLEncoder.encode class QrCodeFragment : DialogFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = inflater.inflate(R.layout.fragment_qr_code, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) arguments?.let { args -> if (args.containsKey(EXTRA_TEXT)) { setQrCodeText(args.getString(EXTRA_TEXT) ?: "") } } } private fun setQrCodeText(text: String) { view?.findViewById<TextView>(R.id.qr_code_issue_text)?.text = text val qrCodeImageView = view?.findViewById<ImageView>(R.id.qr_code_image) val qrCodeUrl = "https://chart.googleapis.com/chart?cht=qr&chs=500x500&chl=${encode(text, "UTF-8")}" log(TAG, "qrCodeUrl: $qrCodeUrl") qrCodeImageView?.load(qrCodeUrl) { placeholder(R.drawable.dots_horizontal) } } companion object { const val TAG = "QrCodeFragment" private const val EXTRA_TEXT = "text" fun withText(text: String) = QrCodeFragment().apply { arguments = Bundle().apply { putString(EXTRA_TEXT, text) } } } }
apache-2.0
1097aefd9da36ae47264e1252ced3370
32.52381
107
0.726326
3.940299
false
false
false
false
Yubyf/QuoteLock
app/src/main/java/com/crossbowffs/quotelock/utils/IOUtils.kt
1
2245
@file:JvmName("IOUtils") package com.crossbowffs.quotelock.utils import com.crossbowffs.quotelock.BuildConfig import com.crossbowffs.quotelock.consts.Urls import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runInterruptible import java.io.* import java.net.HttpURLConnection import java.net.URL @Throws(IOException::class) fun InputStream.readString( encoding: String? = "UTF-8", bufferSize: Int = 2048, ): String { val buffer = CharArray(bufferSize) val sb = StringBuilder() InputStreamReader(this, encoding).use { reader -> while (true) { val count = reader.read(buffer, 0, bufferSize) if (count < 0) break sb.append(buffer, 0, count) } } return sb.toString() } @Throws(IOException::class) suspend fun String.downloadUrl( headers: Map<String, String?>? = null, ): String = runInterruptible(Dispatchers.IO) { val ua = "QuoteLock/${BuildConfig.VERSION_NAME} (+${Urls.GITHUB_QUOTELOCK})" val connection = URL(this@downloadUrl).openConnection() as HttpURLConnection try { connection.setRequestProperty("User-Agent", ua) headers?.run { forEach { (key, value) -> connection.addRequestProperty(key, value) } } val responseCode = connection.responseCode if (connection.responseCode == 200) { connection.inputStream.readString() } else { throw IOException("Server returned non-200 status code: $responseCode") } } finally { connection.disconnect() } } @Throws(IOException::class) fun InputStream.toFile(file: File) = use { inputStream -> val fos: OutputStream = FileOutputStream(file) val buffer = ByteArray(1024) var length: Int while (inputStream.read(buffer).also { length = it } > 0) { fos.write(buffer, 0, length) } fos.flush() fos.close() } @Throws(IOException::class) fun OutputStream.fromFile(file: File) = use { outputStream -> val fis = FileInputStream(file) val buffer = ByteArray(1024) var length: Int fis.use { while ((fis.read(buffer).also { length = it }) > 0) { outputStream.write(buffer, 0, length) } } outputStream.flush() }
mit
e0d54bfe8775fe3fb0ef2e9d331247c8
28.946667
83
0.653007
4.119266
false
false
false
false
Vavassor/Tusky
app/src/main/java/com/keylesspalace/tusky/ListsActivity.kt
1
7343
package com.keylesspalace.tusky import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.appcompat.widget.Toolbar import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.keylesspalace.tusky.LoadingState.* import com.keylesspalace.tusky.di.Injectable import com.keylesspalace.tusky.entity.MastoList import com.keylesspalace.tusky.fragment.TimelineFragment import com.keylesspalace.tusky.network.MastodonApi import com.keylesspalace.tusky.util.ThemeUtils import com.keylesspalace.tusky.util.hide import com.keylesspalace.tusky.util.show import com.mikepenz.google_material_typeface_library.GoogleMaterial import com.mikepenz.iconics.IconicsDrawable import kotlinx.android.synthetic.main.activity_lists.* import retrofit2.Call import retrofit2.Response import java.io.IOException import java.lang.ref.WeakReference import javax.inject.Inject /** * Created by charlag on 1/4/18. */ interface ListsView { fun update(state: State) fun openTimeline(listId: String) } enum class LoadingState { INITIAL, LOADING, LOADED, ERROR_NETWORK, ERROR_OTHER } data class State(val lists: List<MastoList>, val loadingState: LoadingState) class ListsViewModel(private val api: MastodonApi) { private var _view: WeakReference<ListsView>? = null private val view: ListsView? get() = _view?.get() private var state = State(listOf(), INITIAL) fun attach(view: ListsView) { this._view = WeakReference(view) updateView() loadIfNeeded() } fun detach() { this._view = null } fun didSelectItem(id: String) { view?.openTimeline(id) } fun retryLoading() { loadIfNeeded() } private fun loadIfNeeded() { if (state.loadingState == LOADING || !state.lists.isEmpty()) return updateState(state.copy(loadingState = LOADING)) api.getLists().enqueue(object : retrofit2.Callback<List<MastoList>> { override fun onResponse(call: Call<List<MastoList>>, response: Response<List<MastoList>>) { updateState(state.copy(lists = response.body() ?: listOf(), loadingState = LOADED)) } override fun onFailure(call: Call<List<MastoList>>, err: Throwable?) { updateState(state.copy( loadingState = if (err is IOException) ERROR_NETWORK else ERROR_OTHER )) } }) } private fun updateState(state: State) { this.state = state view?.update(state) } private fun updateView() { view?.update(state) } } class ListsActivity : BaseActivity(), ListsView, Injectable { companion object { @JvmStatic fun newIntent(context: Context): Intent { return Intent(context, ListsActivity::class.java) } } @Inject lateinit var mastodonApi: MastodonApi private lateinit var viewModel: ListsViewModel private val adapter = ListsAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_lists) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) val bar = supportActionBar if (bar != null) { bar.title = getString(R.string.title_lists) bar.setDisplayHomeAsUpEnabled(true) bar.setDisplayShowHomeEnabled(true) } listsRecycler.adapter = adapter listsRecycler.layoutManager = LinearLayoutManager(this) listsRecycler.addItemDecoration( DividerItemDecoration(this, DividerItemDecoration.VERTICAL)) viewModel = lastNonConfigurationInstance as? ListsViewModel ?: ListsViewModel(mastodonApi) viewModel.attach(this) } override fun onDestroy() { viewModel.detach() super.onDestroy() } override fun onRetainCustomNonConfigurationInstance(): Any { return viewModel } override fun update(state: State) { adapter.update(state.lists) progressBar.visibility = if (state.loadingState == LOADING) View.VISIBLE else View.GONE when (state.loadingState) { INITIAL, LOADING -> messageView.hide() ERROR_NETWORK -> { messageView.show() messageView.setup(R.drawable.elephant_offline, R.string.error_network) { viewModel.retryLoading() } } ERROR_OTHER -> { messageView.show() messageView.setup(R.drawable.elephant_error, R.string.error_generic) { viewModel.retryLoading() } } LOADED -> if (state.lists.isEmpty()) { messageView.show() messageView.setup(R.drawable.elephant_friend_empty, R.string.message_empty, null) } else { messageView.hide() } } } override fun openTimeline(listId: String) { startActivityWithSlideInAnimation( ModalTimelineActivity.newIntent(this, TimelineFragment.Kind.LIST, listId)) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() return true } return false } private inner class ListsAdapter : RecyclerView.Adapter<ListsAdapter.ListViewHolder>() { private val items = mutableListOf<MastoList>() fun update(list: List<MastoList>) { this.items.clear() this.items.addAll(list) notifyDataSetChanged() } override fun getItemCount(): Int = items.size override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder { return LayoutInflater.from(parent.context).inflate(R.layout.item_list, parent, false) .let(this::ListViewHolder) .apply { val context = nameTextView.context val icon = IconicsDrawable(context, GoogleMaterial.Icon.gmd_list).sizeDp(20) ThemeUtils.setDrawableTint(context, icon, android.R.attr.textColorTertiary) nameTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(icon, null, null, null) } } override fun onBindViewHolder(holder: ListViewHolder, position: Int) { holder.nameTextView.text = items[position].title } private inner class ListViewHolder(view: View) : RecyclerView.ViewHolder(view), View.OnClickListener { val nameTextView: TextView = view.findViewById(R.id.list_name_textview) init { view.setOnClickListener(this) } override fun onClick(v: View?) { viewModel.didSelectItem(items[adapterPosition].id) } } } }
gpl-3.0
d12418952f83aa44628af8d18e3c813a
31.069869
108
0.637614
4.87907
false
false
false
false
vilnius/tvarkau-vilniu
app/src/main/java/lt/vilnius/tvarkau/activity/ViispLoginActivity.kt
1
3528
package lt.vilnius.tvarkau.activity import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.webkit.WebChromeClient import android.webkit.WebSettings import android.webkit.WebView import android.webkit.WebViewClient import kotlinx.android.synthetic.main.activity_viisp_login.* import kotlinx.android.synthetic.main.app_bar.* import lt.vilnius.tvarkau.BaseActivity import lt.vilnius.tvarkau.R import lt.vilnius.tvarkau.dagger.module.RestAdapterModule import lt.vilnius.tvarkau.extensions.gone import okhttp3.HttpUrl import javax.inject.Inject import javax.inject.Named class ViispLoginActivity : BaseActivity() { @field:[Inject Named(RestAdapterModule.VIISP_AUTH_URI)] lateinit var viispAuthUri: String @SuppressLint("SetJavaScriptEnabled") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_viisp_login) setSupportActionBar(toolbar) setTitle(R.string.title_sign_in_with_viisp) with(web_view.settings) { useWideViewPort = true javaScriptEnabled = true loadWithOverviewMode = true setAppCacheEnabled(true) databaseEnabled = true domStorageEnabled = true setSupportZoom(true) builtInZoomControls = true displayZoomControls = false if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { layoutAlgorithm = WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING } } web_view.webChromeClient = object : WebChromeClient() { override fun onReceivedTitle(view: WebView?, title: String?) { super.onReceivedTitle(view, title) if (title.isNullOrEmpty()) return if (title!!.startsWith(viispAuthUri)) return [email protected] = title } } web_view.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { return if (url.startsWith(CALLBACK_URI)) { val parsed = Uri.parse(url)!! val ticket = parsed.getQueryParameter("ticket") val data = Intent().apply { putExtra(LoginActivity.RESULT_TICKET, ticket) } setResult(Activity.RESULT_OK, data) finish() true } else { false } } override fun onPageFinished(view: WebView?, url: String?) { if (url != null && !url.startsWith(viispAuthUri)) { progress_bar.gone() } super.onPageFinished(view, url) } } web_view.post { val parsed = HttpUrl.parse(viispAuthUri)!! .newBuilder() .addQueryParameter("redirect_uri", CALLBACK_URI) .build() web_view.loadUrl(parsed.toString()) } } override fun onBackPressed() { if (web_view.canGoBack()) { web_view.goBack() } else { super.onBackPressed() } } companion object { private const val CALLBACK_URI = "lt.tvarkauvilniu://viisp/callback" } }
mit
ce7b30e2287765f899d4ba061942ce38
30.783784
88
0.60119
4.872928
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/mappers/CollectionViewMapper.kt
1
397
package com.boardgamegeek.mappers import com.boardgamegeek.entities.CollectionViewEntity import com.boardgamegeek.export.model.CollectionView import com.boardgamegeek.export.model.Filter fun CollectionViewEntity.mapToExportable() = CollectionView( name = this.name, sortType = this.sortType, starred = false, filters = this.filters?.map { Filter(it.type, it.data) }.orEmpty(), )
gpl-3.0
5428cba51b30795804b0fa38c7ca220f
32.083333
71
0.775819
4.010101
false
false
false
false
songzhw/Hello-kotlin
KotlinPlayground/src/main/kotlin/ca/six/klplay/advanced/delegation/PropertyDelegationDemo.kt
1
1068
package ca.six.klplay.advanced.delegation import kotlin.properties.ReadOnlyProperty import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty class Apple { var id : String by IdPropertyDelegate() val date : String by DatePropertyDelegate() } class DatePropertyDelegate : ReadOnlyProperty<Apple, String> { override fun getValue(thisRef: Apple, property: KProperty<*>): String { return "${property.name} from $thisRef" } } class IdPropertyDelegate : ReadWriteProperty<Apple, String> { override fun getValue(thisRef: Apple, property: KProperty<*>): String { return "${property.name} from $thisRef" } override fun setValue(thisRef: Apple, property: KProperty<*>, value: String) { println("$value has been assigned to ${property.name} in $thisRef") } } fun main(args: Array<String>) { val apple = Apple() apple.id = "23" //=> 23 has been assigned to id in Apple@37f8bb67 println(apple.id) //=> id from Apple@37f8bb67 println(apple.date) //=> date from Apple@37f8bb67 }
apache-2.0
84fd94a60603efe274ea15d495953989
31.363636
82
0.697566
4.060837
false
false
false
false
KDatabases/Kuery
src/test/kotlin/com/sxtanna/database/tests/KKueryTestOrm.kt
1
2785
package com.sxtanna.database.tests import com.sxtanna.database.Kuery import com.sxtanna.database.ext.PrimaryKey import com.sxtanna.database.task.builder.Create import com.sxtanna.database.task.builder.Delete import com.sxtanna.database.task.builder.Insert import com.sxtanna.database.task.builder.Select import com.sxtanna.database.type.base.SqlObject import java.io.File import kotlin.test.assertEquals class KKueryTestOrm : DatabaseTest<Kuery>() { override fun create() = Kuery[File("../SqlConfig.json")] override fun runTest() { database.addCreator { User(getString("name")) } database { // You can either use the #invoke() function or use a direct call createUser() // You can either use the #invoke(obj : T) function or use a direct call val (emilie, ranald) = User("Emiliee") to User("Sxtanna") insertUser(emilie) insertUser(ranald) var users = 0 // Select blocks will run for each returned object, in it's scope selectUsers { users++ // Since we are in the scope of the object, // we have direct access to its properties, ex. "name" println("Found user $name") } assertEquals(2, users, "Should have found 2 users, Sxtanna and Emiliee") selectSNames { assertEquals("Sxtanna", name, "Name should have been Sxtanna") println("Found user $name") } val names = mutableListOf<String>() selectAscendNames { println("Found user $name") names.add(name) } assertEquals(names, listOf("Emiliee", "Sxtanna"), "Results were in wrong order") deleteSNames() deleteSNames(emilie) } } companion object { /** * Simple create statement, will gather information from the class */ val createUser = Create.from<User>() /** * Simple insert statement, will update primary key if duplicate. * * [Insert.onDupeUpdate] accepts specific columns. */ val insertUser = Insert.into<User>().onDupeUpdate() /** * Simple select statement, will select all rows */ val selectUsers = Select.from<User>() /** * This statement will select all users whose name starts with the letter 'S' */ val selectSNames = Select.from<User>().startsWith("name", "S") /** * This statement will select all users and order them by name */ val selectAscendNames = Select.from<User>().ascend("name") /** * This statement will delete all users whose name starts with the letter 'S' */ val deleteSNames = Delete.from<User>().startsWith("name", "S") /** * This will outline the database table, each field will get its own row. * * A [PrimaryKey] annotation will denote which field is the table's primary key */ data class User(@PrimaryKey val name : String) : SqlObject } }
apache-2.0
b9a7faf41e032de4f9727a227d160c75
23.438596
85
0.67684
3.698539
false
false
false
false
debop/debop4k
debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/timeranges/HalfyearTimeRange.kt
1
1863
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package debop4k.timeperiod.timeranges import debop4k.core.kodatimes.today import debop4k.timeperiod.* import debop4k.timeperiod.models.Halfyear import debop4k.timeperiod.utils.* import org.joda.time.DateTime open class HalfyearTimeRange @JvmOverloads constructor(moment: DateTime = today(), val halfyearCount: Int = 1, calendar: ITimeCalendar = DefaultTimeCalendar) : CalendarTimeRange(moment.relativeHalfyearPeriod(halfyearCount), calendar) { val halfyearOfStart: Halfyear get() = start.halfyearOf() val halfyearOfEnd: Halfyear get() = end.halfyearOf() val halfyear: Halfyear get() = halfyearOfStart val isMultipleCalendarYears: Boolean get() = startYear != endYear fun quarterSequence(): Sequence<QuarterRange> { return quarterRangeSequence(start, halfyearCount * QuartersPerHalfyear, calendar) } fun quarters(): List<QuarterRange> { return quarterSequence().toList() } fun monthSequence(): Sequence<MonthRange> { return monthRangeSequence(start, halfyearCount * MonthsPerHalfyear, calendar) } fun months(): List<MonthRange> { return monthSequence().toList() } }
apache-2.0
a9f7350757411fdecc05b5fde9cc279b
33.518519
103
0.707998
4.332558
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/view/TopCropImageView.kt
1
2002
/* * ************************************************************************ * TopAlignedImageView.java * ************************************************************************* * Copyright © 2019 VLC authors and VideoLAN * Author: Nicolas POMEPUY * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * ************************************************************************** * * */ package org.videolan.vlc.gui.view import android.content.Context import android.util.AttributeSet import androidx.appcompat.widget.AppCompatImageView class TopCropImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : AppCompatImageView(context, attrs, defStyle) { override fun setFrame(l: Int, t: Int, r: Int, b: Int): Boolean { val width = r - l val height = b - t val matrix = imageMatrix val scaleFactorWidth = width.toFloat() / drawable.intrinsicWidth.toFloat() val scaleFactorHeight = height.toFloat() / drawable.intrinsicHeight.toFloat() val scaleFactor = if (scaleFactorHeight > scaleFactorWidth) { scaleFactorHeight } else { scaleFactorWidth } matrix.setScale(scaleFactor, scaleFactor, 0f, 0f) imageMatrix = matrix return super.setFrame(l, t, r, b) } }
gpl-2.0
c11edc92bae524c5347e5bcd500274bf
36.773585
163
0.625687
4.845036
false
false
false
false
ledao/chatbot
src/main/kotlin/com/davezhao/lexicons/UserWordDict.kt
1
1033
package com.davezhao.lexicons import org.slf4j.LoggerFactory import java.io.File @Deprecated("稍后会删除") class UserWordDict(filepath: String = "") { val log = LoggerFactory.getLogger(this::class.java) val dict = mutableMapOf<String, Pair<String, String>>() init { val path = if (filepath == "") UserWordDict::class.java.getResource("/lexicons/user_word_dict.txt").path else filepath File(path).readLines().map { it.trim() }.filter { it != "" && !it.startsWith("#") }.map { it.split(":") }.filter { it.size == 3 }.forEach{ cols -> val pos = cols[0].trim() val concept = cols[1].trim() if (pos.isEmpty() || concept.isEmpty()) { log.warn("broken line ${cols.joinToString(":")}") } else { val words = cols[2].trim().split(" ").filter { !it.isEmpty() }.forEach { word-> this.dict.put(word, Pair(pos, concept)) } } } } }
gpl-3.0
094278b79d15025eb425b1fe0c3d369b
33.133333
126
0.530792
3.889734
false
false
false
false
ofalvai/BPInfo
app/src/main/java/com/ofalvai/bpinfo/notifications/DescriptionMaker.kt
1
6056
/* * Copyright 2018 Olivér Falvai * * 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.ofalvai.bpinfo.notifications import android.content.Context import androidx.core.os.ConfigurationCompat import com.ofalvai.bpinfo.R import java.util.* object DescriptionMaker { private const val DATA_KEY_ROUTE_BUS = "route_bus" private const val DATA_KEY_ROUTE_FERRY = "route_ferry" private const val DATA_KEY_ROUTE_RAIL = "route_rail" private const val DATA_KEY_ROUTE_TRAM = "route_tram" private const val DATA_KEY_ROUTE_TROLLEYBUS = "route_trolleybus" private const val DATA_KEY_ROUTE_SUBWAY = "route_subway" private const val DATA_KEY_ROUTE_OTHER = "route_other" private const val DATA_KEY_ROUTE_SEPARATOR = "|" /** * Makes the localized description of affected routes, grouped by route types. * One route type per line, structure of line (route list) depends on locale. * @param routeData Map of route type keys and route short names separated by "|" * @param context Needed for localized string resources */ @JvmStatic fun makeDescription(routeData: Map<String, String>, context: Context): String { val subwayList = makeRouteList(routeData[DATA_KEY_ROUTE_SUBWAY], context, DATA_KEY_ROUTE_SUBWAY) val busList = makeRouteList(routeData[DATA_KEY_ROUTE_BUS], context, DATA_KEY_ROUTE_BUS) val tramList = makeRouteList(routeData[DATA_KEY_ROUTE_TRAM], context, DATA_KEY_ROUTE_TRAM) val trolleyList = makeRouteList( routeData[DATA_KEY_ROUTE_TROLLEYBUS], context, DATA_KEY_ROUTE_TROLLEYBUS ) val railList = makeRouteList(routeData[DATA_KEY_ROUTE_RAIL], context, DATA_KEY_ROUTE_RAIL) val ferryList = makeRouteList(routeData[DATA_KEY_ROUTE_FERRY], context, DATA_KEY_ROUTE_FERRY) val otherList = makeRouteList(routeData[DATA_KEY_ROUTE_OTHER], context, DATA_KEY_ROUTE_OTHER) return arrayListOf( subwayList, busList, tramList, trolleyList, railList, ferryList, otherList ) .asSequence() .filter { it.isNotEmpty() } .joinToString(separator = "\n") } private fun makeRouteList(routeData: String?, context: Context, routeType: String): String { val langCode = ConfigurationCompat.getLocales(context.resources.configuration)[0].language return if (langCode == "hu") { makeRouteLineHu(routeData, context, routeType) } else { makeRouteLineEn(routeData, context, routeType) } } private fun getLocalizedRouteType(context: Context, routeType: String): String { return when (routeType) { DATA_KEY_ROUTE_BUS -> context.getString(R.string.route_bus_alt) DATA_KEY_ROUTE_FERRY -> context.getString(R.string.route_ferry_alt) DATA_KEY_ROUTE_RAIL -> context.getString(R.string.route_rail_alt) DATA_KEY_ROUTE_TRAM -> context.getString(R.string.route_tram_alt) DATA_KEY_ROUTE_TROLLEYBUS -> context.getString(R.string.route_trolleybus_alt) DATA_KEY_ROUTE_SUBWAY -> context.getString(R.string.route_subway_alt) DATA_KEY_ROUTE_OTHER -> context.getString(R.string.route_other) else -> context.getString(R.string.route_other) } } private fun makeRouteLineHu( routeData: String?, context: Context, routeType: String ): String { @Suppress("LiftReturnOrAssignment") if (routeData != null && routeData.isNotEmpty()) { val routeList: String = routeData .split(DATA_KEY_ROUTE_SEPARATOR) .asSequence() .map { it.trim() } .filter { it.isNotEmpty() } .map(this::numberPostfixHu) .distinct() .joinToString(separator = ", ") if (routeType == DATA_KEY_ROUTE_OTHER) { // We don't append the type of route, because the route's shortName is the type itself return routeList } else { val name = getLocalizedRouteType(context, routeType) return "$routeList $name" } } else { return "" } } private fun makeRouteLineEn( routeData: String?, context: Context, routeType: String ): String { val sb = StringBuilder() if (routeData != null && routeData.isNotEmpty()) { val name = getLocalizedRouteType(context, routeType) sb.append("$name ") val routeList = routeData .split(DATA_KEY_ROUTE_SEPARATOR) .joinToString(separator = ", ") { it.trim() } sb.append(routeList) } return sb.toString().capitalize(Locale.getDefault()) } private fun numberPostfixHu(name: String): String { if (name.isEmpty()) return "" return when (name.last()) { 'A', 'E', 'M' -> name '1', '2', '4', '7', '9' -> "$name-es" '3', '8' -> "$name-as" '5' -> "$name-ös" '6' -> "$name-os" '0' -> when (name.takeLast(2)) { "10", "40", "50", "70", "90" -> "$name-es" "20", "30", "60", "80", "00" -> "$name-as" else -> name } else -> name } } }
apache-2.0
46bd659a6281b816d9b10d7dca8864d6
37.075472
102
0.595309
4.046791
false
false
false
false
olonho/carkot
kotstd/kt/LongArray.kt
1
2959
package kotlin external fun kotlinclib_long_array_get_ix(dataRawPtr: Int, index: Int): Long external fun kotlinclib_long_array_set_ix(dataRawPtr: Int, index: Int, value: Long) external fun kotlinclib_long_size(): Int class LongArray(var size: Int) { val dataRawPtr: Int /** Returns the number of elements in the array. */ //size: Int init { this.dataRawPtr = malloc_array(kotlinclib_long_size() * this.size) var index = 0 while (index < this.size) { set(index, 0) index = index + 1 } } /** Returns the array element at the given [index]. This method can be called using the index operator. */ operator fun get(index: Int): Long { return kotlinclib_long_array_get_ix(this.dataRawPtr, index) } /** Sets the element at the given [index] to the given [value]. This method can be called using the index operator. */ operator fun set(index: Int, value: Long) { kotlinclib_long_array_set_ix(this.dataRawPtr, index, value) } fun clone(): LongArray { val newInstance = LongArray(this.size) var index = 0 while (index < this.size) { val value = this.get(index) newInstance.set(index, value) index = index + 1 } return newInstance } } fun LongArray.print() { var index = 0 print('[') while (index < size) { print(get(index)) index++ if (index < size) { print(';') print(' ') } } print(']') } fun LongArray.println() { this.print() //println() } fun LongArray.copyOf(newSize: Int): LongArray { val newInstance = LongArray(newSize) var index = 0 val end = if (newSize > this.size) this.size else newSize while (index < end) { val value = this.get(index) newInstance.set(index, value) index = index + 1 } while (index < newSize) { newInstance.set(index, 0) index = index + 1 } return newInstance } fun LongArray.copyOfRange(fromIndex: Int, toIndex: Int): LongArray { val newInstance = LongArray(toIndex - fromIndex) var index = fromIndex while (index < toIndex) { val value = this.get(index) newInstance.set(index - fromIndex, value) index = index + 1 } return newInstance } operator fun LongArray.plus(element: Long): LongArray { val index = size val result = this.copyOf(index + 1) result[index] = element return result } operator fun LongArray.plus(elements: LongArray): LongArray { val thisSize = size val arraySize = elements.size val resultSize = thisSize + arraySize val newInstance = this.copyOf(resultSize) var index = thisSize while (index < resultSize) { val value = elements.get(index - thisSize) newInstance.set(index, value) index = index + 1 } return newInstance }
mit
6f97c1484260d694ee56c57a9abc7075
24.084746
122
0.604258
3.961178
false
false
false
false
nickbutcher/plaid
core/src/main/java/io/plaidapp/core/data/prefs/DeprecatedSources.kt
1
1426
/* * Copyright 2019 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.plaidapp.core.data.prefs import android.content.SharedPreferences /** * When DesignerNews updated from v1 to v2 of their API, they removed the recent data source. This * file checks/removes the data source key from [SharedPreferences]. */ private const val DEPRECATED_SOURCE_DESIGNER_NEWS_RECENT = "SOURCE_DESIGNER_NEWS_RECENT" fun isDeprecatedDesignerNewsSource(key: String) = key == DEPRECATED_SOURCE_DESIGNER_NEWS_RECENT /** * When Dribbble updated from v1 to v2 of their API, they removed a number of data sources. This * file checks/removes data source keys from [SharedPreferences] referring to any of the removed * API sources. */ private const val DEPRECATED_V1_SOURCE_KEY_PREFIX = "SOURCE_DRIBBBLE_" fun isDeprecatedDribbbleV1Source(key: String) = key.startsWith(DEPRECATED_V1_SOURCE_KEY_PREFIX)
apache-2.0
4d69dd44d332710bb32baa047b252195
36.526316
98
0.761571
4.016901
false
false
false
false
deadpixelsociety/twodee
src/main/kotlin/com/thedeadpixelsociety/twodee/systems/GroupSystem.kt
1
1862
package com.thedeadpixelsociety.twodee.systems import com.badlogic.ashley.core.Entity import com.badlogic.ashley.core.Family import com.badlogic.gdx.utils.Array import com.badlogic.gdx.utils.IntMap import com.thedeadpixelsociety.twodee.components.GroupMask import com.thedeadpixelsociety.twodee.components.mapper import com.thedeadpixelsociety.twodee.gdxArray /** * A container system used to store and track grouped entities. */ class GroupSystem : ContainerSystem(Family.all(GroupMask::class.java).get()) { private val entityMap = IntMap<Array<Entity>>() private val groupMapper by mapper<GroupMask>() /** * Gets all entities with the specified group mask. * @param mask The group mask to retrieve. * @return A list of entities in the specified group(s). */ operator fun get(mask: Int): List<Entity> { val list = arrayListOf<Entity>() entityMap.forEach { val id = it.key if (mask and id == id) list.addAll(getInner(id)) } return list } private fun getInner(id: Int): Array<Entity> { var array = entityMap.get(id) if (array == null) { array = gdxArray() entityMap.put(id, array) } return array } override fun onEntityAdded(entity: Entity) { val group = groupMapper[entity] ?: return if (group.mask == GroupMask.INVALID) return for (i in 0..31) { val id = 1 shl i if (group.mask and id == id) getInner(id).add(entity) } } override fun onEntityRemoved(entity: Entity) { val group = groupMapper[entity] ?: return if (group.mask == GroupMask.INVALID) return for (i in 0..31) { val id = 1 shl i if (group.mask and id == id) getInner(id).removeValue(entity, true) } } }
mit
89109788a6ea2f4e81b428ee1dbb2d38
30.05
79
0.628894
4.047826
false
false
false
false
REBOOTERS/AndroidAnimationExercise
imitate/src/main/java/com/engineer/imitate/ui/widget/headsup/Pudding.kt
1
4281
package com.engineer.imitate.ui.widget.headsup import android.graphics.PixelFormat import android.os.Handler import android.os.Looper import android.util.Log import android.view.Gravity import android.view.View import android.view.ViewGroup import android.view.WindowManager import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.OnLifecycleEvent import java.lang.ref.WeakReference class Pudding : LifecycleObserver { private lateinit var choco: Choco private var windowManager: WindowManager? = null // after create fun show() { windowManager?.also { try { it.addView(choco, initLayoutParameter()) } catch (e: Exception) { e.printStackTrace() } } // time over dismiss choco.postDelayed({ if (choco.enableInfiniteDuration) { return@postDelayed } choco.hide() }, Choco.DISPLAY_TIME) // click dismiss choco.setOnClickListener { choco.hide() } } // window manager must associate activity's lifecycle @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun onDestroy(owner: LifecycleOwner) { // this owner is your activity instance choco.hide(true) owner.lifecycle.removeObserver(this) if (puddingMapX.containsKey(owner.toString())) { puddingMapX.remove(owner.toString()) } } private fun initLayoutParameter(): WindowManager.LayoutParams { // init layout params val layoutParams = WindowManager.LayoutParams( WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, 0, 0, PixelFormat.TRANSPARENT ) layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT layoutParams.gravity = Gravity.TOP layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or // 不获取焦点,以便于在弹出的时候 下层界面仍然可以进行操作 WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR // 确保你的内容不会被装饰物(如状态栏)掩盖. // popWindow的层级为 TYPE_APPLICATION_PANEL layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL return layoutParams } // must invoke first private fun setActivity(activity: AppCompatActivity, block: Choco.() -> Unit, view: View) { activityWeakReference = WeakReference(activity) choco = Choco(activity) windowManager = activity.windowManager activity.lifecycle.addObserver(this) // 指定使用者的高阶函数named dsl 配置 choco属性 choco.apply(block) Log.e("zyq", "view height " + view.measuredHeight) choco.addView(view) } companion object { @JvmStatic private fun log(e: String) { Log.e(this::class.java.simpleName, "${this} $e") } private var activityWeakReference: WeakReference<AppCompatActivity>? = null // each Activity hold itself pudding list private val puddingMapX: MutableMap<String, Pudding> = mutableMapOf() @JvmStatic fun create(activity: AppCompatActivity, view: View, block: Choco.() -> Unit): Pudding { val pudding = Pudding() pudding.setActivity(activity, block, view) Handler(Looper.getMainLooper()).post { puddingMapX[activity.toString()]?.choco?.let { if (it.isAttachedToWindow) { ViewCompat.animate(it).alpha(0F).withEndAction { if (it.isAttachedToWindow) { activity.windowManager.removeViewImmediate(it) } } } } puddingMapX[activity.toString()] = pudding } return pudding } } }
apache-2.0
5ef65c60e01c6f140b4e7db246a754f7
31.217054
95
0.62142
4.848308
false
false
false
false
soywiz/korge
korge-swf/src/commonMain/kotlin/com/soywiz/korge/ext/swf/SWFShapeExporter.kt
1
8398
package com.soywiz.korge.ext.swf import com.soywiz.korfl.as3swf.* import com.soywiz.kds.* import com.soywiz.kmem.* import com.soywiz.korim.bitmap.* import com.soywiz.korim.color.* import com.soywiz.korim.paint.* import com.soywiz.korim.vector.* import com.soywiz.korma.geom.* import com.soywiz.korma.geom.vector.* import kotlin.math.* /** * @TODO: Line ScaleMode not supported right now. * @TODO: Default behaviour for strokes: * @TODO: - smaller keeps at least 1 pixel * @TODO: - bigger: ScaleMode.NONE - keeps the size, ScaleMode.NORMAL - scales the stroke * @TODO: It would be possible to emulate using another texture with distances + colors * @TODO: But probably no worth */ class SWFShapeExporter( val swf: SWF, val debug: Boolean, val bounds: Rectangle, val export: (ShapeExporter) -> Unit, val rasterizerMethod: ShapeRasterizerMethod, val antialiasing: Boolean, val requestScale: Double = 2.0, val minSide: Int = 16, val maxSide: Int = 512, val path: GraphicsPath = GraphicsPath(), val charId: Int = -1 ) : ShapeExporter() { //val bounds: Rectangle = dshape.shapeBounds.rect //val bmp = Bitmap32(bounds.width.toIntCeil(), bounds.height.toIntCeil()) val realBoundsWidth = max(1, bounds.width.toIntCeil()) val realBoundsHeight = max(1, bounds.height.toIntCeil()) val desiredBoundsWidth = (realBoundsWidth * requestScale).toInt() val desiredBoundsHeight = (realBoundsHeight * requestScale).toInt() val limitBoundsWidth = desiredBoundsWidth.clamp(minSide, maxSide) val limitBoundsHeight = desiredBoundsHeight.clamp(minSide, maxSide) val actualScale = min( limitBoundsWidth.toDouble() / realBoundsWidth.toDouble(), limitBoundsHeight.toDouble() / realBoundsHeight.toDouble() ) //val actualScale = 0.5 val actualBoundsWidth = (realBoundsWidth * actualScale).toInt() val actualBoundsHeight = (realBoundsHeight * actualScale).toInt() private var cshape = CompoundShape(listOf()) private val shapes = arrayListOf<Shape>() val actualShape: CompoundShape by lazy { export(if (debug) LoggerShapeExporter(this) else this) //this.dshape.export(if (debug) LoggerShapeExporter(this) else this) cshape } val image: Bitmap by lazy { BitmapVector( shape = actualShape, bounds = bounds, scale = actualScale, rasterizerMethod = rasterizerMethod, antialiasing = antialiasing, width = actualBoundsWidth, height = actualBoundsHeight, premultiplied = true ) } val imageWithScale by lazy { BitmapWithScale(image, actualScale, bounds) } var drawingFill = true var apath = GraphicsPath() override fun beginShape() { //ctx.beginPath() } override fun endShape() { cshape = CompoundShape(shapes) //ctx.closePath() } override fun beginFills() { flush() drawingFill = true } override fun endFills() { flush() } override fun beginLines() { flush() drawingFill = false } override fun endLines() { flush() } fun GradientSpreadMode.toCtx() = when (this) { GradientSpreadMode.PAD -> CycleMethod.NO_CYCLE GradientSpreadMode.REFLECT -> CycleMethod.REFLECT GradientSpreadMode.REPEAT -> CycleMethod.REPEAT } var fillStyle: Paint = NonePaint override fun beginFill(color: Int, alpha: Double) { flush() drawingFill = true fillStyle = ColorPaint(decodeSWFColor(color, alpha)) } private fun createGradientPaint( type: GradientType, colors: List<Int>, alphas: List<Double>, ratios: List<Int>, matrix: Matrix, spreadMethod: GradientSpreadMode, interpolationMethod: GradientInterpolationMode, focalPointRatio: Double ): GradientPaint { val aratios = DoubleArrayList(*ratios.map { it.toDouble() / 255.0 }.toDoubleArray()) val acolors = IntArrayList(*colors.zip(alphas).map { decodeSWFColor(it.first, it.second).value }.toIntArray()) val m2 = Matrix() m2.copyFrom(matrix) m2.pretranslate(-0.5, -0.5) m2.prescale(1638.4 / 2.0, 1638.4 / 2.0) val imethod = when (interpolationMethod) { GradientInterpolationMode.NORMAL -> GradientInterpolationMethod.NORMAL GradientInterpolationMode.LINEAR -> GradientInterpolationMethod.LINEAR } return when (type) { GradientType.LINEAR -> GradientPaint( GradientKind.LINEAR, -1.0, 0.0, 0.0, +1.0, 0.0, 0.0, aratios, acolors, spreadMethod.toCtx(), m2, imethod ) GradientType.RADIAL -> GradientPaint( GradientKind.RADIAL, focalPointRatio, 0.0, 0.0, 0.0, 0.0, 1.0, aratios, acolors, spreadMethod.toCtx(), m2, imethod ) } } override fun beginGradientFill( type: GradientType, colors: List<Int>, alphas: List<Double>, ratios: List<Int>, matrix: Matrix, spreadMethod: GradientSpreadMode, interpolationMethod: GradientInterpolationMode, focalPointRatio: Double ) { flush() drawingFill = true fillStyle = createGradientPaint( type, colors, alphas, ratios, matrix, spreadMethod, interpolationMethod, focalPointRatio ) } override fun beginBitmapFill(bitmapId: Int, matrix: Matrix, repeat: Boolean, smooth: Boolean) { flush() drawingFill = true val bmp = swf.bitmaps[bitmapId] ?: Bitmap32(1, 1) fillStyle = BitmapPaint( bmp, matrix.clone(), CycleMethod.fromRepeat(repeat), CycleMethod.fromRepeat(repeat), smooth ) } override fun endFill() { flush() } private fun __flushFill() { if (apath.isEmpty()) return shapes += FillShape(apath, null, fillStyle, Matrix()) apath = GraphicsPath() } private fun __flushStroke() { if (apath.isEmpty()) return shapes += PolylineShape( apath, null, strokeStyle, Matrix(), lineWidth, true, LineScaleMode.NORMAL, lineCap, lineCap, LineJoin.MITER, miterLimit ) apath = GraphicsPath() } private fun flush() { if (drawingFill) { __flushFill() } else { __flushStroke() } } private var lineWidth: Double = 1.0 private var lineScaleMode = LineScaleMode.NORMAL private var miterLimit = 1.0 private var lineCap: LineCap = LineCap.ROUND private var strokeStyle: Paint = ColorPaint(Colors.BLACK) override fun lineStyle( thickness: Double, color: Int, alpha: Double, pixelHinting: Boolean, scaleMode: LineScaleMode, startCaps: LineCapsStyle, endCaps: LineCapsStyle, joints: String?, miterLimit: Double ) { flush() this.drawingFill = false this.lineWidth = thickness this.lineScaleMode = scaleMode this.miterLimit = miterLimit this.strokeStyle = ColorPaint(decodeSWFColor(color, alpha)) this.lineCap = when (startCaps) { LineCapsStyle.NO -> LineCap.BUTT LineCapsStyle.ROUND -> LineCap.ROUND LineCapsStyle.SQUARE -> LineCap.SQUARE } } override fun lineGradientStyle( type: GradientType, colors: List<Int>, alphas: List<Double>, ratios: List<Int>, matrix: Matrix, spreadMethod: GradientSpreadMode, interpolationMethod: GradientInterpolationMode, focalPointRatio: Double ) { flush() drawingFill = false strokeStyle = createGradientPaint( type, colors, alphas, ratios, matrix, spreadMethod, interpolationMethod, focalPointRatio ) } override fun moveTo(x: Double, y: Double) { apath.moveTo(x, y) //println("moveTo($x, $y)") if (drawingFill) path.moveTo(x, y) } override fun lineTo(x: Double, y: Double) { apath.lineTo(x, y) //println("lineTo($x, $y)") if (drawingFill) path.lineTo(x, y) } override fun curveTo(controlX: Double, controlY: Double, anchorX: Double, anchorY: Double) { apath.quadTo(controlX, controlY, anchorX, anchorY) //println("curveTo($controlX, $controlY, $anchorX, $anchorY)") if (drawingFill) path.quadTo(controlX, controlY, anchorX, anchorY) } override fun closePath() { apath.close() if (drawingFill) path.close() } } fun SWFColorTransform.toColorTransform() = ColorTransform(rMult, gMult, bMult, aMult, rAdd, gAdd, bAdd, aAdd) fun decodeSWFColor(color: Int, alpha: Double = 1.0) = RGBA(color.extract8(16), color.extract8(8), color.extract8(0), (alpha * 255).toInt())
apache-2.0
e0b08ba97355f0a52bdbd5a665d49ab0
25.408805
118
0.670636
3.431957
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/view/camera/Camera.kt
1
12461
package com.soywiz.korge.view.camera import com.soywiz.klock.* import com.soywiz.kmem.* import com.soywiz.korge.view.* import com.soywiz.korio.async.* import com.soywiz.korma.geom.* import com.soywiz.korma.geom.Point import com.soywiz.korma.geom.interpolate import com.soywiz.korma.interpolation.* import kotlin.math.* inline fun Container.cameraContainer( width: Double, height: Double, clip: Boolean = true, noinline contentBuilder: (camera: CameraContainer) -> Container = { FixedSizeContainer(it.width, it.height) }, noinline block: @ViewDslMarker CameraContainer.() -> Unit = {}, content: @ViewDslMarker Container.() -> Unit = {} ) = CameraContainer(width, height, clip, contentBuilder, block).addTo(this).also { content(it.content) } class CameraContainer( width: Double = 100.0, height: Double = 100.0, clip: Boolean = true, contentBuilder: (camera: CameraContainer) -> Container = { FixedSizeContainer(it.width, it.height) }, block: @ViewDslMarker CameraContainer.() -> Unit = {} ) : FixedSizeContainer(width, height, clip), View.Reference { var clampToBounds: Boolean = false val cameraViewportBounds: Rectangle = Rectangle(0, 0, 4096, 4096) private val contentContainer = Container() class ContentContainer(val cameraContainer: CameraContainer) : FixedSizeContainer(cameraContainer.width, cameraContainer.height), Reference { override fun getLocalBoundsInternal(out: Rectangle) { //out.setTo(0, 0, cameraContainer.width, cameraContainer.height) out.setTo(0, 0, width, height) } } val content: Container by lazy { contentBuilder(this) } private val sourceCamera = Camera(x = width / 2.0, y = height / 2.0, anchorX = 0.5, anchorY = 0.5) private val currentCamera = sourceCamera.copy() private val targetCamera = sourceCamera.copy() override var width: Double = width set(value) { field = value sync() } override var height: Double = height set(value) { field = value sync() } var cameraX: Double set(value) { currentCamera.x = value manualSet() } get() = currentCamera.x var cameraY: Double set(value) { currentCamera.y = value manualSet() } get() = currentCamera.y var cameraZoom: Double set(value) { currentCamera.zoom = value manualSet() } get() = currentCamera.zoom var cameraAngle: Angle set(value) { currentCamera.angle = value manualSet() } get() = currentCamera.angle var cameraAnchorX: Double set(value) { currentCamera.anchorX = value manualSet() } get() = currentCamera.anchorX var cameraAnchorY: Double set(value) { currentCamera.anchorY = value manualSet() } get() = currentCamera.anchorY private fun manualSet() { elapsedTime = transitionTime sync() } val onCompletedTransition = Signal<Unit>() fun getCurrentCamera(out: Camera = Camera()): Camera = out.copyFrom(currentCamera) fun getDefaultCamera(out: Camera = Camera()): Camera = out.setTo(x = width / 2.0, y = height / 2.0, anchorX = 0.5, anchorY = 0.5) companion object { fun getCameraRect(rect: Rectangle, scaleMode: ScaleMode = ScaleMode.SHOW_ALL, cameraWidth: Double, cameraHeight: Double, cameraAnchorX: Double, cameraAnchorY: Double, out: Camera = Camera()): Camera { val size = Rectangle(0.0, 0.0, cameraWidth, cameraHeight).place(rect.size, Anchor.TOP_LEFT, scale = scaleMode).size val scaleX = size.width / rect.width val scaleY = size.height / rect.height return out.setTo( rect.x + rect.width * cameraAnchorX, rect.y + rect.height * cameraAnchorY, zoom = min(scaleX, scaleY), angle = 0.degrees, anchorX = cameraAnchorX, anchorY = cameraAnchorY ) } } fun getCameraRect(rect: Rectangle, scaleMode: ScaleMode = ScaleMode.SHOW_ALL, out: Camera = Camera()): Camera = getCameraRect(rect, scaleMode, width, height, cameraAnchorX, cameraAnchorY, out) fun getCameraToFit(rect: Rectangle, out: Camera = Camera()): Camera = getCameraRect(rect, ScaleMode.SHOW_ALL, out) fun getCameraToCover(rect: Rectangle, out: Camera = Camera()): Camera = getCameraRect(rect, ScaleMode.COVER, out) private var transitionTime = 1.0.seconds private var elapsedTime = 0.0.milliseconds //var easing = Easing.EASE_OUT private var easing = Easing.LINEAR private var following: View? = null fun follow(view: View?, setImmediately: Boolean = false) { following = view if (setImmediately) { val point = getFollowingXY(tempPoint) cameraX = point.x cameraY = point.y sourceCamera.x = cameraX sourceCamera.y = cameraY } } fun unfollow() { following = null } fun updateCamera(block: Camera.() -> Unit) { block(currentCamera) } fun setCurrentCamera(camera: Camera) { elapsedTime = transitionTime following = null sourceCamera.copyFrom(camera) currentCamera.copyFrom(camera) targetCamera.copyFrom(camera) sync() } fun setTargetCamera(camera: Camera, time: TimeSpan = 1.seconds, easing: Easing = Easing.LINEAR) { elapsedTime = 0.seconds this.transitionTime = time this.easing = easing following = null sourceCamera.copyFrom(currentCamera) targetCamera.copyFrom(camera) } suspend fun tweenCamera(camera: Camera, time: TimeSpan = 1.seconds, easing: Easing = Easing.LINEAR) { setTargetCamera(camera, time, easing) onCompletedTransition.waitOne() } fun getFollowingXY(out: Point = Point()): Point { val followGlobalX = following!!.globalX val followGlobalY = following!!.globalY val localToContentX = content!!.globalToLocalX(followGlobalX, followGlobalY) val localToContentY = content!!.globalToLocalY(followGlobalX, followGlobalY) return out.setTo(localToContentX, localToContentY) } private val tempPoint = Point() init { block(this) contentContainer.addTo(this) content.addTo(contentContainer) addUpdater { when { following != null -> { val point = getFollowingXY(tempPoint) cameraX = 0.1.interpolate(currentCamera.x, point.x) cameraY = 0.1.interpolate(currentCamera.y, point.y) sourceCamera.x = cameraX sourceCamera.y = cameraY //cameraX = 0.0 //cameraY = 0.0 //println("$cameraX, $cameraY - ${following?.x}, ${following?.y}") sync() } elapsedTime < transitionTime -> { elapsedTime += it val ratio = (elapsedTime / transitionTime).coerceIn(0.0, 1.0) currentCamera.setToInterpolated(easing(ratio), sourceCamera, targetCamera) /* val ratioCamera = easing(ratio) val ratioZoom = easing(ratio) currentCamera.zoom = ratioZoom.interpolate(sourceCamera.zoom, targetCamera.zoom) currentCamera.x = ratioCamera.interpolate(sourceCamera.x, targetCamera.x) currentCamera.y = ratioCamera.interpolate(sourceCamera.y, targetCamera.y) currentCamera.angle = ratioCamera.interpolate(sourceCamera.angle, targetCamera.angle) currentCamera.anchorX = ratioCamera.interpolate(sourceCamera.anchorX, targetCamera.anchorX) currentCamera.anchorY = ratioCamera.interpolate(sourceCamera.anchorY, targetCamera.anchorY) */ sync() if (ratio >= 1.0) { onCompletedTransition() } } } } } fun sync() { //val realScaleX = (content.unscaledWidth / width) * cameraZoom //val realScaleY = (content.unscaledHeight / height) * cameraZoom val realScaleX = cameraZoom val realScaleY = cameraZoom val contentContainerX = width * cameraAnchorX val contentContainerY = height * cameraAnchorY //println("content=${content.getLocalBoundsOptimized()}, contentContainer=${contentContainer.getLocalBoundsOptimized()}, cameraViewportBounds=$cameraViewportBounds") content.x = if (clampToBounds) -cameraX.clamp(contentContainerX + cameraViewportBounds.left, contentContainerX + cameraViewportBounds.width - width) else -cameraX content.y = if (clampToBounds) -cameraY.clamp(contentContainerY + cameraViewportBounds.top, contentContainerY + cameraViewportBounds.height - height) else -cameraY contentContainer.x = contentContainerX contentContainer.y = contentContainerY contentContainer.rotation = cameraAngle contentContainer.scaleX = realScaleX contentContainer.scaleY = realScaleY } fun setZoomAt(anchor: Point, zoom: Double) { setAnchorPosKeepingPos(anchor.x, anchor.y) cameraZoom = zoom } fun setZoomAt(anchorX: Double, anchorY: Double, zoom: Double) { setAnchorPosKeepingPos(anchorX, anchorY) cameraZoom = zoom } fun setAnchorPosKeepingPos(anchor: Point) { setAnchorPosKeepingPos(anchor.x, anchor.y) } fun setAnchorPosKeepingPos(anchorX: Double, anchorY: Double) { setAnchorRatioKeepingPos(anchorX / width, anchorY / height) } fun setAnchorRatioKeepingPos(ratioX: Double, ratioY: Double) { currentCamera.setAnchorRatioKeepingPos(ratioX, ratioY, width, height) sync() } } data class Camera( var x: Double = 0.0, var y: Double = 0.0, var zoom: Double = 1.0, var angle: Angle = 0.degrees, var anchorX: Double = 0.5, var anchorY: Double = 0.5 ) : MutableInterpolable<Camera> { fun setTo( x: Double = 0.0, y: Double = 0.0, zoom: Double = 1.0, angle: Angle = 0.degrees, anchorX: Double = 0.5, anchorY: Double = 0.5 ): Camera = this.apply { this.x = x this.y = y this.zoom = zoom this.angle = angle this.anchorX = anchorX this.anchorY = anchorY } fun setAnchorRatioKeepingPos(anchorX: Double, anchorY: Double, width: Double, height: Double) { val sx = width / zoom val sy = height / zoom val oldPaX = this.anchorX * sx val oldPaY = this.anchorY * sy val newPaX = anchorX * sx val newPaY = anchorY * sy this.x += newPaX - oldPaX this.y += newPaY - oldPaY this.anchorX = anchorX this.anchorY = anchorY //println("ANCHOR: $anchorX, $anchorY") } fun copyFrom(source: Camera) = source.apply { [email protected](x, y, zoom, angle, anchorX, anchorY) } // @TODO: Easing must be adjusted from the zoom change // @TODO: This is not exact. We have to preserve final pixel-level speed while changing the zoom fun posEasing(zoomLeft: Double, zoomRight: Double, lx: Double, rx: Double, it: Double): Double { val zoomChange = zoomRight - zoomLeft return if (zoomChange <= 0.0) { it.pow(sqrt(-zoomChange).toInt().toDouble()) } else { val inv = it - 1.0 inv.pow(sqrt(zoomChange).toInt().toDouble()) + 1 } } override fun setToInterpolated(ratio: Double, l: Camera, r: Camera): Camera { // Adjust based on the zoom changes val posRatio = posEasing(l.zoom, r.zoom, l.x, r.x, ratio) return setTo( posRatio.interpolate(l.x, r.x), posRatio.interpolate(l.y, r.y), ratio.interpolate(l.zoom, r.zoom), ratio.interpolate(l.angle, r.angle), // @TODO: Fix KorMA angle interpolator ratio.interpolate(l.anchorX, r.anchorX), ratio.interpolate(l.anchorY, r.anchorY) ) } }
apache-2.0
b3cd83a15f3ab58b19e686443483d7d2
36.533133
208
0.61231
4.25
false
false
false
false
cashapp/sqldelight
sqldelight-idea-plugin/src/main/kotlin/app/cash/sqldelight/intellij/run/window/SqlDelightToolWindowFactory.kt
1
1933
package app.cash.sqldelight.intellij.run.window import app.cash.sqldelight.dialect.api.ConnectionManager import app.cash.sqldelight.intellij.run.ConnectionOptions import com.intellij.openapi.project.Project import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.ui.components.JBTextArea import com.intellij.ui.content.Content import com.intellij.ui.content.ContentManager import java.awt.BorderLayout import java.awt.Component import java.awt.Insets import javax.swing.GroupLayout import javax.swing.JPanel internal class SqlDelightToolWindowFactory( private val connectionManager: ConnectionManager, ) : ToolWindowFactory { override fun createToolWindowContent( project: Project, toolWindow: ToolWindow, ) { val runSqlText = JPanel(BorderLayout()).apply { add( JBTextArea("Create a connection to get started.").apply { margin = Insets(8, 8, 8, 8) isEditable = false }, BorderLayout.CENTER, ) } toolWindow.contentManager.apply { val content = createWithConnectionSidePanel(project, connectionManager, runSqlText) content.isCloseable = false addContent(content) } } } internal fun ContentManager.createWithConnectionSidePanel( project: Project, connectionManager: ConnectionManager, component: Component, name: String? = null, ): Content { val panel = JPanel() val layout = GroupLayout(panel) panel.layout = layout val connectionList = ConnectionListPanel(ConnectionOptions(project), connectionManager, project) layout.setHorizontalGroup( layout.createSequentialGroup() .addComponent(connectionList, 50, 200, 300) .addComponent(component), ) layout.setVerticalGroup( layout.createParallelGroup() .addComponent(connectionList) .addComponent(component), ) return factory.createContent(panel, name, false) }
apache-2.0
d2c7705b1158df7875bbbb94039701ab
27.426471
98
0.750129
4.548235
false
false
false
false
absurdhero/parsekt
src/main/kotlin/net/raboof/parsekt/Parser.kt
1
5470
package net.raboof.parsekt // based on http://blogs.msdn.com/b/lukeh/archive/2007/08/19/monadic-parser-combinators-using-c-3-0.aspx /** A Parser is both a function and an object with methods that return derivative parsers */ open class Parser<TInput, TValue>(val f: (TInput) -> Result<TInput, TValue>) { /** A parser can be invoked as a function of an input that returns a result */ operator fun invoke(input: TInput): Result<TInput, TValue> = f(input) /* the following filter and map functions are the building blocks used to derive new parsers */ fun filter(pred: (TValue) -> Boolean): Parser<TInput, TValue> { return Parser { input -> val result = this(input) when (result) { is Result.Value -> if (pred(result.value)) { result } else { Result.ParseError("filter", null, result.rest) } is Result.ParseError -> result } } } fun <TValue2> mapResult(selector: (Result.Value<TInput, TValue>) -> Result<TInput, TValue2>): Parser<TInput, TValue2> { return Parser { input -> val result = this(input) when (result) { is Result.Value -> selector(result) is Result.ParseError -> Result.ParseError(result) } } } fun <TValue2> map(selector: (TValue) -> TValue2): Parser<TInput, TValue2> = mapResult { result -> Result.Value(selector(result.value), result.rest) } /** This function is a convenient way to build parsers that act on more that one input parser. * * It invokes "this" followed by the parser returned from the selector function. * It then passes the two resulting values to the projector which returns one result. * * The selector "maps" the value from "this" to an intermediate parser. * Then the projector "joins" the original value and the mapped value into a new value. * * See usages of this function in this library for examples of how to make use of it. */ fun <TIntermediate, TValue2> mapJoin( selector: (TValue) -> Parser<TInput, TIntermediate>, projector: (TValue, TIntermediate) -> TValue2 ): Parser<TInput, TValue2> { return Parser { input -> val res = this(input) when (res) { is Result.ParseError -> Result.ParseError(res) is Result.Value -> { val v = res.value val res2 = selector(v)(res.rest) when (res2) { is Result.ParseError -> Result.ParseError(res2) is Result.Value -> Result.Value(projector(v, res2.value), res2.rest) } } } } } /* These are some essential combinators which are functions that take parsers as arguments and return a new parser */ infix fun or(other: Parser<TInput, TValue>): Parser<TInput, TValue> { return Parser { input -> val result = this(input) when (result) { is Result.Value -> result is Result.ParseError -> other(input) } } } infix fun <TValue2> and(other: Parser<TInput, TValue2>): Parser<TInput, TValue2> = this.mapJoin({ other }, { _, i -> i }) // like "and" but returns the value of the first parser infix fun <TValue2> before(other: Parser<TInput, TValue2>): Parser<TInput, TValue> = this.mapJoin({ other }, { v, _ -> v }) /* error tracking */ /** Allows a reported error from a parser to be modified. * * This is useful when the combinator knows more about why an error happened. */ fun mapError(errorFunc: (Result.ParseError<TInput, TValue>) -> Result.ParseError<TInput, TValue>): Parser<TInput, TValue> { return Parser { input -> val result = this(input) when (result) { is Result.Value -> result is Result.ParseError -> errorFunc(result) } } } fun withErrorLabel(label: String) : Parser<TInput, TValue> { return mapError { Result.ParseError(label, it.child, it.rest) } } fun wrapError(label: String) : Parser<TInput, TValue> { return mapError { Result.ParseError(label, it) } } /* Generally useful functions */ /** curry the projector function in mapJoin * * @see mapJoin */ fun <TIntermediate, TValue2> project(projector: (TValue, TIntermediate) -> TValue2) : ((TValue) -> Parser<TInput, TIntermediate>) -> Parser<TInput, TValue2> { return { selector: (TValue) -> Parser<TInput, TIntermediate> -> mapJoin(selector, projector) } } // extract the result of this parser from the input between two other parsers fun between(start: Parser<TInput, *>, end: Parser<TInput, *> = start): Parser<TInput, TValue> { return (start and this before end).wrapError("between") } fun asList(): Parser<TInput, List<TValue>> { return mapResult { Result.Value(listOf(it.value), it.rest) } } // sometimes useful for working around covariance problems (or from T to T?) fun <TValue2> cast() : Parser<TInput, TValue2> { @Suppress("UNCHECKED_CAST") return this as Parser<TInput, TValue2> } }
apache-2.0
2a9dfcdcd70e53861337ef67dd68905d
37.258741
127
0.585558
4.013206
false
false
false
false
digammas/damas
solutions.digamma.damas.jcr/src/main/kotlin/solutions/digamma/damas/jcr/auth/JcrPermission.kt
1
3960
package solutions.digamma.damas.jcr.auth import solutions.digamma.damas.auth.AccessRight import solutions.digamma.damas.auth.JaasConfiguration import solutions.digamma.damas.auth.Permission import solutions.digamma.damas.common.WorkspaceException import solutions.digamma.damas.content.File import solutions.digamma.damas.jcr.common.Exceptions import solutions.digamma.damas.jcr.content.JcrFile import solutions.digamma.damas.jcr.login.UserLoginModule import solutions.digamma.damas.jcr.sys.SystemSessions import java.util.Arrays import javax.jcr.Node import javax.jcr.Session import javax.jcr.security.AccessControlEntry import javax.jcr.security.Privilege /** * JCR implementation of a permission entry. * * @author Ahmad Shahwan */ internal class JcrPermission @Throws(WorkspaceException::class) private constructor( private val node: Node, private val subject: String, private val acl: List<AccessControlEntry>? = null ): Permission { override fun getAccessRights(): AccessRight = Exceptions.uncheck { val acl = this.acl ?: Permissions .getAppliedEntries(this.node, this.subject) val acm = this.node.session.accessControlManager val jcrRead = acm.privilegeFromName(Privilege.JCR_READ) val jcrWrite = acm.privilegeFromName(Privilege.JCR_WRITE) val jcrAll = acm.privilegeFromName(Privilege.JCR_ALL) if (acl.isEmpty()) AccessRight.NONE else acl.map { when { it.privileges.contains(jcrAll) -> AccessRight.MAINTAIN it.privileges.contains(jcrWrite) -> AccessRight.WRITE it.privileges.contains(jcrRead) -> AccessRight.READ else -> AccessRight.NONE } }.reduce(::maxOf) } override fun setAccessRights(value: AccessRight?) = Exceptions.uncheck { if (value != null) { if (isProtected()) { throw PermissionProtectedException(subjectId, node.path) } Permissions.writePrivileges(this.node, this.subject, value) } } override fun getSubjectId(): String = this.subject override fun getObject(): File = Exceptions.uncheck { JcrFile.of(this.node) } fun remove() = Exceptions.uncheck { if (isProtected()) { throw PermissionProtectedException(subjectId, node.path) } Permissions.writePrivileges( this.node, this.subject, AccessRight.NONE) } /** * Whether this permission is protected. Protected permissions are * immutable. * All permissions applying to a system role, or the current user are * protected. * Current user is not allowed to modify its own permissions. */ private fun isProtected(): Boolean = this.subject in Arrays.asList( SystemSessions.RO_USERNAME, SystemSessions.SU_USERNAME, UserLoginModule.ADMIN_USERNAME, JaasConfiguration.SYS_SHADOW, this.node.session.userID ) companion object { @Throws(WorkspaceException::class) fun of(session: Session, fileId: String, subjectId: String) = Exceptions.check { /* Retrieve object node, a file. */ val node = session.getNodeByIdentifier(fileId) JcrPermission(node, subjectId) } /** * Optimized way to retrieve all permissions applied at a given node. */ @Throws(WorkspaceException::class) fun lisOf(session: Session, fileId: String): List<JcrPermission> = Exceptions.check { /* Retrieve object node, a file. */ val node = session.getNodeByIdentifier(fileId) Permissions.getAppliedPolicy(node)?.accessControlEntries?.groupBy { it.principal.name }?.map { JcrPermission(node, it.key, it.value) } ?: emptyList() } } }
mit
4b03b59c28dff4127e7765a28218e3ac
35
79
0.652273
4.464487
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/edit/Edit.kt
1
966
package org.wikipedia.edit import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import org.wikipedia.dataclient.mwapi.MwPostResponse @Serializable class Edit : MwPostResponse() { val edit: Result? = null @Serializable class Result { private val captcha: Captcha? = null @SerialName("result") val status: String? = null @SerialName("newrevid") val newRevId: Long = 0 val code: String? = null val info: String? = null val warning: String? = null val spamblacklist: String? = null val editSucceeded get() = "Success" == status val captchaId get() = captcha?.id.orEmpty() val hasEditErrorCode get() = code != null val hasCaptchaResponse get() = captcha != null val hasSpamBlacklistResponse get() = spamblacklist != null } @Serializable private class Captcha { val id: String? = null } }
apache-2.0
f60f9510849a8706ccc5e9ceaa5d8b88
26.6
66
0.638716
4.472222
false
false
false
false
AndroidX/androidx
wear/compose/compose-material/src/commonMain/kotlin/androidx/wear/compose/material/Picker.kt
3
23309
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.material import androidx.compose.animation.core.CubicBezierEasing import androidx.compose.animation.core.DecayAnimationSpec import androidx.compose.animation.core.Easing import androidx.compose.animation.core.exponentialDecay import androidx.compose.foundation.MutatePriority import androidx.compose.foundation.gestures.FlingBehavior import androidx.compose.foundation.gestures.ScrollScope import androidx.compose.foundation.gestures.ScrollableState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.drawscope.ContentDrawScope import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.onClick import androidx.compose.ui.semantics.scrollToIndex import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch /** * A scrollable list of items to pick from. By default, items will be repeated * "infinitely" in both directions, unless [PickerState#repeatItems] is specified as false. * * Example of a simple picker to select one of five options: * @sample androidx.wear.compose.material.samples.SimplePicker * * Example of dual pickers, where clicking switches which one is editable and which is read-only: * @sample androidx.wear.compose.material.samples.DualPicker * * @param state The state of the component * @param contentDescription Text used by accessibility services to describe what the * selected option represents. This text should be localized, such as by using * [androidx.compose.ui.res.stringResource] or similar. Typically, the content description is * inferred via derivedStateOf to avoid unnecessary recompositions, like this: * val description by remember { derivedStateOf { /* expression using state.selectedOption */ } } * @param modifier Modifier to be applied to the Picker * @param readOnly Determines whether the Picker should display other available options for this * field, inviting the user to scroll to change the value. When readOnly = true, * only displays the currently selected option (and optionally a label). This is intended to be * used for screens that display multiple Pickers, only one of which has the focus at a time. * @param readOnlyLabel A slot for providing a label, displayed above the selected option * when the [Picker] is read-only. The label is overlaid with the currently selected * option within a Box, so it is recommended that the label is given [Alignment.TopCenter]. * @param onSelected Action triggered when the Picker is selected by clicking. Used by * accessibility semantics, which facilitates implementation of multi-picker screens. * @param scalingParams The parameters to configure the scaling and transparency effects for the * component. See [ScalingParams] * @param separation The amount of separation in [Dp] between items. Can be negative, which can be * useful for Text if it has plenty of whitespace. * @param gradientRatio The size relative to the Picker height that the top and bottom gradients * take. These gradients blur the picker content on the top and bottom. The default is 0.33, * so the top 1/3 and the bottom 1/3 of the picker are taken by gradients. Should be between 0.0 and * 0.5. Use 0.0 to disable the gradient. * @param gradientColor Should be the color outside of the Picker, so there is continuity. * @param flingBehavior logic describing fling behavior. * @param option A block which describes the content. Inside this block you can reference * [PickerScope.selectedOption] and other properties in [PickerScope]. When read-only mode is in * use on a screen, it is recommended that this content is given [Alignment.Center] in order to * align with the centrally selected Picker value. */ @Composable public fun Picker( state: PickerState, contentDescription: String?, modifier: Modifier = Modifier, readOnly: Boolean = false, readOnlyLabel: @Composable (BoxScope.() -> Unit)? = null, onSelected: () -> Unit = {}, scalingParams: ScalingParams = PickerDefaults.scalingParams(), separation: Dp = 0.dp, /* @FloatRange(from = 0.0, to = 0.5) */ gradientRatio: Float = PickerDefaults.DefaultGradientRatio, gradientColor: Color = MaterialTheme.colors.background, flingBehavior: FlingBehavior = PickerDefaults.flingBehavior(state), option: @Composable PickerScope.(optionIndex: Int) -> Unit ) { require(gradientRatio in 0f..0.5f) { "gradientRatio should be between 0.0 and 0.5" } val pickerScope = remember(state) { PickerScopeImpl(state) } var forceScrollWhenReadOnly by remember { mutableStateOf(false) } val coroutineScope = rememberCoroutineScope() Box(modifier = modifier) { ScalingLazyColumn( modifier = Modifier.clearAndSetSemantics { onClick { coroutineScope.launch { onSelected() } true } scrollToIndex { coroutineScope.launch { state.scrollToOption(it) onSelected() } true } if (!state.isScrollInProgress && contentDescription != null) { this.contentDescription = contentDescription } }.then( if (!readOnly && gradientRatio > 0.0f) { Modifier .drawWithContent { drawContent() drawGradient(gradientColor, gradientRatio) } // b/223386180 - add padding when drawing rectangles to // prevent jitter on screen. .padding(vertical = 1.dp) .align(Alignment.Center) } else if (readOnly) { Modifier .drawWithContent { drawContent() val visibleItems = state.scalingLazyListState.layoutInfo.visibleItemsInfo if (visibleItems.isNotEmpty()) { val centerItem = visibleItems.find { info -> info.index == state.scalingLazyListState.centerItemIndex } ?: visibleItems[visibleItems.size / 2] val shimHeight = (size.height - centerItem.unadjustedSize.toFloat() - separation.toPx()) / 2.0f drawShim(gradientColor, shimHeight) } } // b/223386180 - add padding when drawing rectangles to // prevent jitter on screen. .padding(vertical = 1.dp) .align(Alignment.Center) } else { Modifier.align(Alignment.Center) } ), state = state.scalingLazyListState, content = { items(state.numberOfItems()) { ix -> with(pickerScope) { option((ix + state.optionsOffset) % state.numberOfOptions) } } }, contentPadding = PaddingValues(0.dp), scalingParams = scalingParams, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy( space = separation ), flingBehavior = flingBehavior, autoCentering = AutoCenteringParams(itemIndex = 0) ) if (readOnly && readOnlyLabel != null) { readOnlyLabel() } } SideEffect { if (!readOnly) { forceScrollWhenReadOnly = true } } // If a Picker switches to read-only during animation, the ScalingLazyColumn can be // out of position, so we force an instant scroll to the selected option so that it is // correctly lined up when the Picker is next displayed. LaunchedEffect(readOnly, forceScrollWhenReadOnly) { if (readOnly && forceScrollWhenReadOnly) { state.scrollToOption(state.selectedOption) forceScrollWhenReadOnly = false } } } /** * A scrollable list of items to pick from. By default, items will be repeated * "infinitely" in both directions, unless [PickerState#repeatItems] is specified as false. * * Example of a simple picker to select one of five options: * @sample androidx.wear.compose.material.samples.SimplePicker * * Example of dual pickers, where clicking switches which one is editable and which is read-only: * @sample androidx.wear.compose.material.samples.DualPicker * * @param state The state of the component * @param modifier Modifier to be applied to the Picker * @param readOnly Determines whether the Picker should display other available options for this * field, inviting the user to scroll to change the value. When readOnly = true, * only displays the currently selected option (and optionally a label). This is intended to be * used for screens that display multiple Pickers, only one of which has the focus at a time. * @param readOnlyLabel A slot for providing a label, displayed above the selected option * when the [Picker] is read-only. The label is overlaid with the currently selected * option within a Box, so it is recommended that the label is given [Alignment.TopCenter]. * @param scalingParams The parameters to configure the scaling and transparency effects for the * component. See [ScalingParams] * @param separation The amount of separation in [Dp] between items. Can be negative, which can be * useful for Text if it has plenty of whitespace. * @param gradientRatio The size relative to the Picker height that the top and bottom gradients * take. These gradients blur the picker content on the top and bottom. The default is 0.33, * so the top 1/3 and the bottom 1/3 of the picker are taken by gradients. Should be between 0.0 and * 0.5. Use 0.0 to disable the gradient. * @param gradientColor Should be the color outside of the Picker, so there is continuity. * @param flingBehavior logic describing fling behavior. * @param option A block which describes the content. Inside this block you can reference * [PickerScope.selectedOption] and other properties in [PickerScope]. When read-only mode is in * use on a screen, it is recommended that this content is given [Alignment.Center] in order to * align with the centrally selected Picker value. */ @Deprecated("This overload is provided for backwards compatibility with Compose for Wear OS 1.0." + "A newer overload is available with additional contentDescription and onSelected parameters, " + "which improves accessibility of [Picker].") @Composable public fun Picker( state: PickerState, modifier: Modifier = Modifier, readOnly: Boolean = false, readOnlyLabel: @Composable (BoxScope.() -> Unit)? = null, scalingParams: ScalingParams = PickerDefaults.scalingParams(), separation: Dp = 0.dp, /* @FloatRange(from = 0.0, to = 0.5) */ gradientRatio: Float = PickerDefaults.DefaultGradientRatio, gradientColor: Color = MaterialTheme.colors.background, flingBehavior: FlingBehavior = PickerDefaults.flingBehavior(state), option: @Composable PickerScope.(optionIndex: Int) -> Unit ) = Picker( state = state, contentDescription = null, modifier = modifier, readOnly = readOnly, readOnlyLabel = readOnlyLabel, scalingParams = scalingParams, separation = separation, gradientRatio = gradientRatio, gradientColor = gradientColor, flingBehavior = flingBehavior, option = option ) // Apply a shim on the top and bottom of the Picker to hide all but the selected option. private fun ContentDrawScope.drawShim( gradientColor: Color, height: Float ) { drawRect( color = gradientColor, size = Size(size.width, height) ) drawRect( color = gradientColor, topLeft = Offset(0f, size.height - height), size = Size(size.width, height) ) } // Apply a fade-out gradient on the top and bottom of the Picker. private fun ContentDrawScope.drawGradient( gradientColor: Color, gradientRatio: Float ) { drawRect( Brush.linearGradient( colors = listOf(gradientColor, Color.Transparent), start = Offset(size.width / 2, 0f), end = Offset(size.width / 2, size.height * gradientRatio) ) ) drawRect( Brush.linearGradient( colors = listOf(Color.Transparent, gradientColor), start = Offset(size.width / 2, size.height * (1 - gradientRatio)), end = Offset(size.width / 2, size.height) ) ) } /** * Creates a [PickerState] that is remembered across compositions. * * @param initialNumberOfOptions the number of options * @param initiallySelectedOption the option to show in the center at the start * @param repeatItems if true (the default), the contents of the component will be repeated */ @Composable public fun rememberPickerState( initialNumberOfOptions: Int, initiallySelectedOption: Int = 0, repeatItems: Boolean = true ): PickerState = rememberSaveable( initialNumberOfOptions, initiallySelectedOption, repeatItems, saver = PickerState.Saver ) { PickerState(initialNumberOfOptions, initiallySelectedOption, repeatItems) } /** * A state object that can be hoisted to observe item selection. * * In most cases, this will be created via [rememberPickerState]. * * @param initialNumberOfOptions the number of options * @param initiallySelectedOption the option to show in the center at the start * @param repeatItems if true (the default), the contents of the component will be repeated */ @Stable public class PickerState constructor( /*@IntRange(from = 1)*/ initialNumberOfOptions: Int, initiallySelectedOption: Int = 0, val repeatItems: Boolean = true ) : ScrollableState { init { verifyNumberOfOptions(initialNumberOfOptions) } private var _numberOfOptions by mutableStateOf(initialNumberOfOptions) var numberOfOptions get() = _numberOfOptions set(newNumberOfOptions) { verifyNumberOfOptions(newNumberOfOptions) // We need to maintain the mapping between the currently selected item and the // currently selected option. optionsOffset = positiveModule( selectedOption.coerceAtMost(newNumberOfOptions - 1) - scalingLazyListState.centerItemIndex, newNumberOfOptions ) _numberOfOptions = newNumberOfOptions } internal fun numberOfItems() = if (!repeatItems) numberOfOptions else LARGE_NUMBER_OF_ITEMS // The difference between the option we want to select for the current numberOfOptions // and the selection with the initial numberOfOptions. // Note that if repeatItems is true (the default), we have a large number of items, and a // smaller number of options, so many items map to the same options. This variable is part of // that mapping since we need to adjust it when the number of options change. // The mapping is that given an item index, subtracting optionsOffset and doing modulo the // current number of options gives the option index: // itemIndex - optionsOffset =(mod numberOfOptions) optionIndex internal var optionsOffset = 0 internal val scalingLazyListState = run { val repeats = if (repeatItems) LARGE_NUMBER_OF_ITEMS / numberOfOptions else 1 val centerOffset = numberOfOptions * (repeats / 2) ScalingLazyListState( centerOffset + initiallySelectedOption, 0 ) } /** * Index of the option selected (i.e., at the center) */ public val selectedOption: Int get() = (scalingLazyListState.centerItemIndex + optionsOffset) % numberOfOptions /** * Instantly scroll to an item. * Note that for this to work properly, all options need to have the same height, and this can * only be called after the Picker has been laid out. * * @sample androidx.wear.compose.material.samples.OptionChangePicker * * @param index The index of the option to scroll to. */ public suspend fun scrollToOption(index: Int) { val itemIndex = if (!repeatItems) { index } else { // Pick the itemIndex closest to the current one, that it's congruent modulo // numberOfOptions with index - optionOffset. // This is to try to work around http://b/230582961 val minTargetIndex = scalingLazyListState.centerItemIndex - numberOfOptions / 2 minTargetIndex + positiveModule(index - minTargetIndex, numberOfOptions) - optionsOffset } scalingLazyListState.scrollToItem(itemIndex, 0) } public companion object { /** * The default [Saver] implementation for [PickerState]. */ val Saver = listSaver<PickerState, Any?>( save = { listOf( it.numberOfOptions, it.selectedOption, it.repeatItems ) }, restore = { saved -> PickerState( initialNumberOfOptions = saved[0] as Int, initiallySelectedOption = saved[1] as Int, repeatItems = saved[2] as Boolean ) } ) } public override suspend fun scroll( scrollPriority: MutatePriority, block: suspend ScrollScope.() -> Unit ) { scalingLazyListState.scroll(scrollPriority, block) } public override fun dispatchRawDelta(delta: Float): Float { return scalingLazyListState.dispatchRawDelta(delta) } public override val isScrollInProgress: Boolean get() = scalingLazyListState.isScrollInProgress override val canScrollForward: Boolean get() = scalingLazyListState.canScrollForward override val canScrollBackward: Boolean get() = scalingLazyListState.canScrollBackward private fun verifyNumberOfOptions(numberOfOptions: Int) { require(numberOfOptions > 0) { "The picker should have at least one item." } require(numberOfOptions < LARGE_NUMBER_OF_ITEMS / 3) { // Set an upper limit to ensure there are at least 3 repeats of all the options "The picker should have less than ${LARGE_NUMBER_OF_ITEMS / 3} items" } } } /** * Contains the default values used by [Picker] */ public object PickerDefaults { /** * Scaling params are used to determine when items start to be scaled down and alpha applied, * and how much. For details, see [ScalingParams] */ public fun scalingParams( edgeScale: Float = 0.45f, edgeAlpha: Float = 1.0f, minElementHeight: Float = 0.0f, maxElementHeight: Float = 0.0f, minTransitionArea: Float = 0.45f, maxTransitionArea: Float = 0.45f, scaleInterpolator: Easing = CubicBezierEasing(0.25f, 0.00f, 0.75f, 1.00f), viewportVerticalOffsetResolver: (Constraints) -> Int = { (it.maxHeight / 5f).toInt() } ): ScalingParams = DefaultScalingParams( edgeScale = edgeScale, edgeAlpha = edgeAlpha, minElementHeight = minElementHeight, maxElementHeight = maxElementHeight, minTransitionArea = minTransitionArea, maxTransitionArea = maxTransitionArea, scaleInterpolator = scaleInterpolator, viewportVerticalOffsetResolver = viewportVerticalOffsetResolver ) /** * Create and remember a [FlingBehavior] that will represent natural fling curve with snap to * central item as the fling decays. * * @param state the state of the [Picker] * @param decay the decay to use */ @Composable public fun flingBehavior( state: PickerState, decay: DecayAnimationSpec<Float> = exponentialDecay() ): FlingBehavior { return remember(state, decay) { ScalingLazyColumnSnapFlingBehavior( state = state.scalingLazyListState, snapOffset = 0, decay = decay ) } } /** * Default Picker gradient ratio - the proportion of the Picker height allocated to each of the * of the top and bottom gradients. */ public val DefaultGradientRatio = 0.33f } /** * Receiver scope which is used by [Picker]. */ public interface PickerScope { /** * Index of the item selected (i.e., at the center) */ public val selectedOption: Int } private fun positiveModule(n: Int, mod: Int) = ((n % mod) + mod) % mod @Stable private class PickerScopeImpl( private val pickerState: PickerState ) : PickerScope { override val selectedOption: Int get() = pickerState.selectedOption } private const val LARGE_NUMBER_OF_ITEMS = 100_000_000
apache-2.0
6b8dd6ad8d92a65375f7df84fbdacce3
41.534672
100
0.668197
4.841919
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/notifications/service/delegates/SharedPreferencesNotificationsStore.kt
2
4464
package abi43_0_0.expo.modules.notifications.service.delegates import android.content.Context import android.content.SharedPreferences import expo.modules.notifications.notifications.model.NotificationRequest import java.io.IOException /** * A fairly straightforward [SharedPreferences] wrapper to be used by [NotificationSchedulingHelper]. * Saves and reads notifications (identifiers, requests and triggers) to and from the persistent storage. * * A notification request of identifier = 123abc, it will be persisted under key: * [SharedPreferencesNotificationsStore.NOTIFICATION_REQUEST_KEY_PREFIX]123abc */ class SharedPreferencesNotificationsStore(context: Context) { companion object { private const val SHARED_PREFERENCES_NAME = "expo.modules.notifications.SharedPreferencesNotificationsStore" private const val NOTIFICATION_REQUEST_KEY_PREFIX = "notification_request-" } private val sharedPreferences: SharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE) /** * Fetches scheduled notification info for given identifier. * * @param identifier Identifier of the notification. * @return Notification information: request and trigger. * @throws JSONException Thrown if notification request could not have been interpreted as a JSON object. * @throws IOException Thrown if there is an error when fetching trigger from the storage. * @throws ClassNotFoundException Thrown if there is an error when interpreting trigger fetched from the storage. */ @Throws(IOException::class, ClassNotFoundException::class) fun getNotificationRequest(identifier: String) = sharedPreferences.getString( preferencesNotificationRequestKey(identifier), null )?.asBase64EncodedObject<NotificationRequest>() /** * Fetches all scheduled notifications, ignoring invalid ones. * * Goes through all the [SharedPreferences] entries, interpreting only the ones conforming * to the expected format. * * @return Map with identifiers as keys and notification info as values */ val allNotificationRequests: Collection<NotificationRequest> get() = sharedPreferences .all .filter { it.key.startsWith(NOTIFICATION_REQUEST_KEY_PREFIX) } .mapNotNull { (_, value) -> return@mapNotNull try { (value as String?)?.asBase64EncodedObject<NotificationRequest>() } catch (e: ClassNotFoundException) { // do nothing null } catch (e: IOException) { // do nothing null } } /** * Saves given notification in the persistent storage. * * @param notificationRequest Notification request * @throws IOException Thrown if there is an error while serializing trigger */ @Throws(IOException::class) fun saveNotificationRequest(notificationRequest: NotificationRequest) = sharedPreferences.edit() .putString( preferencesNotificationRequestKey(notificationRequest.identifier), notificationRequest.encodedInBase64() ) .apply() /** * Removes notification info for given identifier. * * @param identifier Notification identifier */ fun removeNotificationRequest(identifier: String) = removeNotificationRequest(sharedPreferences.edit(), identifier).apply() /** * Perform notification removal on provided [SharedPreferences.Editor] instance. Can be reused * to batch deletion. * * @param editor Editor to apply changes onto * @param identifier Notification identifier * @return Returns a reference to the same Editor object, so you can * chain put calls together. */ private fun removeNotificationRequest(editor: SharedPreferences.Editor, identifier: String) = editor.remove(preferencesNotificationRequestKey(identifier)) /** * Removes all notification infos, returning removed IDs. */ fun removeAllNotificationRequests(): Collection<String> = with(sharedPreferences.edit()) { allNotificationRequests.map { removeNotificationRequest(this, it.identifier) it.identifier }.let { this.apply() it } } /** * @param identifier Notification identifier * @return Key under which notification request will be persisted in the storage. */ private fun preferencesNotificationRequestKey(identifier: String) = NOTIFICATION_REQUEST_KEY_PREFIX + identifier }
bsd-3-clause
4673e841d91b515bbfd785ba802ff9ea
36.512605
128
0.729615
5.227166
false
false
false
false
RSDT/Japp16
app/src/main/java/nl/rsdt/japp/jotial/data/structures/area348/HunterInfo.kt
1
6244
package nl.rsdt.japp.jotial.data.structures.area348 import android.os.Parcel import android.os.Parcelable import android.util.Log import com.google.gson.Gson import com.google.gson.JsonObject import com.google.gson.JsonParseException import com.google.gson.JsonParser import com.google.gson.stream.JsonReader import nl.rsdt.japp.R import nl.rsdt.japp.jotial.maps.deelgebied.Deelgebied import org.acra.ktx.sendWithAcra /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 20-10-2015 * Class that servers as deserialization object for the HunterInfo. */ class HunterInfo /** * Initializes a new instance of HunterInfo from the parcel. * * @param in The parcel where the instance should be created from. */ protected constructor(`in`: Parcel) : BaseInfo(`in`), Parcelable { /** * The dateTime the HunterInfo was created. */ var datetime: String? = null /** * The user of the HunterInfo. */ var hunter: String? = null /** * The icon of the HunterInfo. */ var icon: Int = 0 val associatedDrawable: Int get() = getAssociatedDrawable(icon, hunter?:"") init { datetime = `in`.readString() hunter = `in`.readString() icon = `in`.readInt() } override fun writeToParcel(dest: Parcel, flags: Int) { super.writeToParcel(dest, flags) dest.writeString(datetime) dest.writeString(hunter) dest.writeInt(icon) } override fun describeContents(): Int { return 0 } companion object CREATOR: Parcelable.Creator<HunterInfo>{ override fun createFromParcel(`in`: Parcel): HunterInfo { return HunterInfo(`in`) } override fun newArray(size: Int): Array<HunterInfo?> { return arrayOfNulls(size) } fun getAssociatedDrawable(icon: Int, hunter:String): Int { val dgName = hunter.split('.')[0] val dg = Deelgebied.parse(dgName)?: Deelgebied.Xray when (icon) { 0 -> return getDeelgebiedDrawable(dg) 1 -> return R.drawable.hunter_1 2 -> return R.drawable.hunter_2 3 -> return R.drawable.hunter_3 4 -> return R.drawable.hunter_4 5 -> return R.drawable.hunter_5 6 -> return R.drawable.hunter_6 7 -> return R.drawable.hunter_7 8 -> return R.drawable.hunter_8 9 -> return R.drawable.hunter_9 10 -> return R.drawable.hunter_10 11 -> return R.drawable.hunter_11 12 -> return R.drawable.hunter_12 13 -> return R.drawable.hunter_13 14 -> return R.drawable.hunter_14 15 -> return R.drawable.hunter_15 else -> return R.drawable.hunter_0 } } private fun getDeelgebiedDrawable(dg: Deelgebied): Int { when (dg.dgColor){ MetaColorInfo.ColorNameInfo.DeelgebiedColor.Groen -> return R.drawable.hunter_groen MetaColorInfo.ColorNameInfo.DeelgebiedColor.Rood -> return R.drawable.hunter_rood MetaColorInfo.ColorNameInfo.DeelgebiedColor.Paars -> return R.drawable.hunter_paars MetaColorInfo.ColorNameInfo.DeelgebiedColor.Oranje -> return R.drawable.hunter_oranje MetaColorInfo.ColorNameInfo.DeelgebiedColor.Blauw -> return R.drawable.hunter_blauw MetaColorInfo.ColorNameInfo.DeelgebiedColor.Zwart -> return R.drawable.hunter_zwart MetaColorInfo.ColorNameInfo.DeelgebiedColor.Turquoise -> return R.drawable.hunter_turquoise MetaColorInfo.ColorNameInfo.DeelgebiedColor.Onbekend -> return R.drawable.hunter_0 } } /** * Deserializes a HunterInfo from JSON. * * @param json The JSON where the HunterInfo should be deserialized from. * @return A HunterInfo. */ fun fromJson(json: String): HunterInfo? { try { val jsonReader = JsonReader(java.io.StringReader(json)) jsonReader.isLenient = true return Gson().fromJson<HunterInfo>(jsonReader, HunterInfo::class.java) } catch (e: JsonParseException) { Log.e("HunterInfo", e.message, e) e.sendWithAcra() } return null } /** * Deserializes a array of HunterInfo from JSON. * * @param json The JSON where the array of HunterInfo should be deserialized from. * @return A array of HunterInfo. */ fun fromJsonArray(json: String): Array<HunterInfo>? { try { val jsonReader = JsonReader(java.io.StringReader(json)) jsonReader.isLenient = true return Gson().fromJson<Array<HunterInfo>>(jsonReader, Array<HunterInfo>::class.java) } catch (e: JsonParseException) { Log.e("HunterInfo", e.message, e) e.sendWithAcra() } return null } /** * Deserializes a 2D array of HunterInfo from JSON. * * @param json The JSON where the 2D array of HunterInfo should be deserialized from. * @return A 2D array of HunterInfo. */ fun formJsonArray2D(json: String): Array<Array<HunterInfo>?> { try { val jsonReader = JsonReader(java.io.StringReader(json)) jsonReader.isLenient = true val parser = JsonParser() val `object` = parser.parse(jsonReader) as JsonObject val buffer = arrayOfNulls<Array<HunterInfo>>(`object`.entrySet().size) var count = 0 for ((_, value) in `object`.entrySet()) { buffer[count] = fromJsonArray(value.toString()) count++ } return buffer } catch (e: JsonParseException) { Log.e("HunterInfo", e.message, e) e.sendWithAcra() } return emptyArray() } } }
apache-2.0
94e8e5006c470f61bab15a57332bf371
34.078652
107
0.578475
4.511561
false
false
false
false
androidx/androidx
benchmark/benchmark-common/src/main/java/androidx/benchmark/Shell.kt
3
26468
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.benchmark import android.os.Build import android.os.Looper import android.os.ParcelFileDescriptor import android.os.ParcelFileDescriptor.AutoCloseInputStream import android.os.SystemClock import android.util.Log import androidx.annotation.CheckResult import androidx.annotation.RequiresApi import androidx.annotation.RestrictTo import androidx.test.platform.app.InstrumentationRegistry import androidx.tracing.trace import java.io.Closeable import java.io.File import java.io.InputStream import java.nio.charset.Charset /** * Wrappers for UiAutomation.executeShellCommand to handle compat behavior, and add additional * features like script execution (with piping), stdin/stderr. * * @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) object Shell { /** * Returns true if the line from ps output contains the given process/package name. * * NOTE: On API 25 and earlier, the processName of unbundled executables will include the * relative path they were invoked from: * * ``` * root 10065 10061 14848 3932 poll_sched 7bcaf1fc8c S /data/local/tmp/tracebox * root 10109 1 11552 1140 poll_sched 78c86eac8c S ./tracebox * ``` * * On higher API levels, the process name will simply be e.g. "tracebox". * * As this function is also used for package names (which never have a leading `/`), we * simply check for either. */ private fun psLineContainsProcess(psOutputLine: String, processName: String): Boolean { return psOutputLine.endsWith(" $processName") || psOutputLine.endsWith("/$processName") } /** * Equivalent of [psLineContainsProcess], but to be used with full process name string * (e.g. from pgrep) */ private fun fullProcessNameMatchesProcess( fullProcessName: String, processName: String ): Boolean { return fullProcessName == processName || fullProcessName.endsWith("/$processName") } fun connectUiAutomation() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { ShellImpl // force initialization } } /** * Run a command, and capture stdout, dropping / ignoring stderr * * Below L, returns null */ fun optionalCommand(command: String): String? { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { executeScriptCaptureStdoutStderr(command).stdout } else { null } } /** * Function for reading shell-accessible proc files, like scaling_max_freq, which can't be * read directly by the app process. */ fun catProcFileLong(path: String): Long? { return optionalCommand("cat $path") ?.trim() ?.run { try { toLong() } catch (exception: NumberFormatException) { // silently catch exception, as it may be not readable (e.g. due to offline) null } } } /** * Get a checksum for a given path * * Note: Does not check for stderr, as this method is used during ShellImpl init, so stderr not * yet available */ @RequiresApi(21) internal fun getChecksum(path: String): String { val sum = if (Build.VERSION.SDK_INT >= 23) { ShellImpl.executeCommandUnsafe("md5sum $path").substringBefore(" ") } else { // this isn't good, but it's good enough for API 22 val out = ShellImpl.executeCommandUnsafe("ls -l $path").split(Regex("\\s+"))[3] println("value is $out") out } check(sum.isNotBlank()) { "Checksum for $path was blank" } return sum } /** * Copy file and make executable * * Note: this operation does checksum validation of dst, since it's used during setup of the * shell script used to capture stderr, so stderr isn't available. */ @RequiresApi(21) private fun moveToTmpAndMakeExecutable(src: String, dst: String) { ShellImpl.executeCommandUnsafe("cp $src $dst") if (Build.VERSION.SDK_INT >= 23) { ShellImpl.executeCommandUnsafe("chmod +x $dst") } else { // chmod with support for +x only added in API 23 // While 777 is technically more permissive, this is only used for scripts and temporary // files in tests, so we don't worry about permissions / access here ShellImpl.executeCommandUnsafe("chmod 777 $dst") } // validate checksums instead of checking stderr, since it's not yet safe to // read from stderr. This detects the problem where root left a stale executable // that can't be modified by shell at the dst path val srcSum = getChecksum(src) val dstSum = getChecksum(dst) if (srcSum != dstSum) { throw IllegalStateException("Failed to verify copied executable $dst, " + "md5 sums $srcSum, $dstSum don't match. Check if root owns" + " $dst and if so, delete it with `adb root`-ed shell session.") } } /** * Writes the inputStream to an executable file with the given name in `/data/local/tmp` * * Note: this operation does not validate command success, since it's used during setup of shell * scripting code used to parse stderr. This means callers should validate. */ @RequiresApi(21) fun createRunnableExecutable(name: String, inputStream: InputStream): String { // dirUsableByAppAndShell is writable, but we can't execute there (as of Q), // so we copy to /data/local/tmp val externalDir = Outputs.dirUsableByAppAndShell val writableExecutableFile = File.createTempFile( /* prefix */ "temporary_$name", /* suffix */ null, /* directory */ externalDir ) val runnableExecutablePath = "/data/local/tmp/$name" try { writableExecutableFile.outputStream().use { inputStream.copyTo(it) } moveToTmpAndMakeExecutable( src = writableExecutableFile.absolutePath, dst = runnableExecutablePath ) } finally { writableExecutableFile.delete() } return runnableExecutablePath } /** * Returns true if the shell session is rooted or su is usable, and thus root commands can be * run (e.g. atrace commands with root-only tags) */ @RequiresApi(21) fun isSessionRooted(): Boolean { return ShellImpl.isSessionRooted || ShellImpl.isSuAvailable } @RequiresApi(21) fun getprop(propertyName: String): String { return executeScriptCaptureStdout("getprop $propertyName").trim() } /** * Convenience wrapper around [android.app.UiAutomation.executeShellCommand] which adds * scripting functionality like piping and redirects, and which throws if stdout or stder was * produced. * * Unlike `executeShellCommand()`, this method supports arbitrary multi-line shell * expressions, as it creates and executes a shell script in `/data/local/tmp/`. * * Note that shell scripting capabilities differ based on device version. To see which utilities * are available on which platform versions,see * [Android's shell and utilities](https://android.googlesource.com/platform/system/core/+/master/shell_and_utilities/README.md#) * * @param script Script content to run * @param stdin String to pass in as stdin to first command in script * * @return Stdout string */ @RequiresApi(21) fun executeScriptSilent(script: String, stdin: String? = null) { val output = executeScriptCaptureStdoutStderr(script, stdin) check(output.isBlank()) { "Expected no stdout/stderr from $script, saw $output" } } /** * Convenience wrapper around [android.app.UiAutomation.executeShellCommand] which adds * scripting functionality like piping and redirects, and which captures stdout and throws if * stderr was produced. * * Unlike `executeShellCommand()`, this method supports arbitrary multi-line shell * expressions, as it creates and executes a shell script in `/data/local/tmp/`. * * Note that shell scripting capabilities differ based on device version. To see which utilities * are available on which platform versions,see * [Android's shell and utilities](https://android.googlesource.com/platform/system/core/+/master/shell_and_utilities/README.md#) * * @param script Script content to run * @param stdin String to pass in as stdin to first command in script * * @return Stdout string */ @RequiresApi(21) @CheckResult fun executeScriptCaptureStdout(script: String, stdin: String? = null): String { val output = executeScriptCaptureStdoutStderr(script, stdin) check(output.stderr.isBlank()) { "Expected no stderr from $script, saw ${output.stderr}" } return output.stdout } data class Output(val stdout: String, val stderr: String) { /** * Returns true if both stdout and stderr are blank * * This can be used with silent-if-successful shell commands: * * ``` * check(Shell.executeScriptWithStderr("mv $src $dest").isBlank()) { "Oh no mv failed!" } * ``` */ fun isBlank(): Boolean = stdout.isBlank() && stderr.isBlank() } /** * Convenience wrapper around [android.app.UiAutomation.executeShellCommand] which adds * scripting functionality like piping and redirects, and which captures both stdout and stderr. * * Unlike `executeShellCommand()`, this method supports arbitrary multi-line shell * expressions, as it creates and executes a shell script in `/data/local/tmp/`. * * Note that shell scripting capabilities differ based on device version. To see which utilities * are available on which platform versions,see * [Android's shell and utilities](https://android.googlesource.com/platform/system/core/+/master/shell_and_utilities/README.md#) * * @param script Script content to run * @param stdin String to pass in as stdin to first command in script * * @return Output object containing stdout and stderr of full script, and stderr of last command */ @RequiresApi(21) @CheckResult fun executeScriptCaptureStdoutStderr( script: String, stdin: String? = null ): Output { return trace("executeScript $script".take(127)) { ShellImpl .createShellScript(script = script, stdin = stdin) .start() .getOutputAndClose() } } /** * Creates a executable shell script that can be started. Similar to [executeScriptCaptureStdoutStderr] * but allows deferring and caching script execution. * * @param script Script content to run * @param stdin String to pass in as stdin to first command in script * * @return ShellScript that can be started. */ @RequiresApi(21) fun createShellScript( script: String, stdin: String? = null ): ShellScript { return ShellImpl .createShellScript( script = script, stdin = stdin ) } @RequiresApi(21) fun isPackageAlive(packageName: String): Boolean { return getPidsForProcess(packageName).isNotEmpty() } @RequiresApi(21) fun getPidsForProcess(processName: String): List<Int> { if (Build.VERSION.SDK_INT >= 23) { return pgrepLF(pattern = processName) .mapNotNull { (pid, fullProcessName) -> // aggressive safety - ensure target isn't subset of another running package if (fullProcessNameMatchesProcess(fullProcessName, processName)) { pid } else { null } } } // NOTE: `pidof $processName` would work too, but filtering by process // (the whole point of the command) doesn't work pre API 24 // Can't use ps -A pre API 26, arg isn't supported. // Grep device side, since ps output by itself gets truncated // NOTE: `ps | grep` is slow (multiple seconds), so avoid whenever possible! return executeScriptCaptureStdout("ps | grep $processName") .split(Regex("\r?\n")) .map { it.trim() } .filter { psLineContainsProcess(psOutputLine = it, processName = processName) } .map { // map to int - split, and take 2nd column (PID) it.split(Regex("\\s+"))[1] .toInt() } } /** * pgrep -l -f <pattern> * * pgrep is *fast*, way faster than ps | grep, but requires API 23 * * -l, --list-name list PID and process name * -f, --full use full process name to match * * @return List of processes - pid & full process name */ @RequiresApi(23) private fun pgrepLF(pattern: String): List<Pair<Int, String>> { // Note: we use the unsafe variant for performance, since this is a // common operation, and pgrep is stable after API 23 see [ShellBehaviorTest#pgrep] return ShellImpl.executeCommandUnsafe("pgrep -l -f $pattern") .split(Regex("\r?\n")) .filter { it.isNotEmpty() } .map { val (pidString, process) = it.trim().split(" ") Pair(pidString.toInt(), process) } } @RequiresApi(21) fun getRunningProcessesForPackage(packageName: String): List<String> { require(!packageName.contains(":")) { "Package $packageName must not contain ':'" } // pgrep is nice and fast, but requires API 23 if (Build.VERSION.SDK_INT >= 23) { return pgrepLF(pattern = packageName) .mapNotNull { (_, process) -> // aggressive safety - ensure target isn't subset of another running package if (process == packageName || process.startsWith("$packageName:")) { process } else { null } } } // Grep device side, since ps output by itself gets truncated // NOTE: Can't use ps -A pre API 26, arg isn't supported, but would need // to pass it on 26 to see all processes. // NOTE: `ps | grep` is slow (multiple seconds), so avoid whenever possible! return executeScriptCaptureStdout("ps | grep $packageName") .split(Regex("\r?\n")) .map { // get process name from end it.substringAfterLast(" ") } .filter { // allow primary or sub process it == packageName || it.startsWith("$packageName:") } } /** * Checks if a process is alive, given a specified pid **and** process name. * * Both must match in order to return true. */ @RequiresApi(21) fun isProcessAlive(pid: Int, processName: String): Boolean { // unsafe, since this behavior is well tested, and performance here is important // See [ShellBehaviorTest#ps] return ShellImpl.executeCommandUnsafe("ps $pid") .split(Regex("\r?\n")) .any { psLineContainsProcess(psOutputLine = it, processName = processName) } } @RequiresApi(21) data class ProcessPid(val processName: String, val pid: Int) { fun isAlive() = isProcessAlive(pid, processName) } @RequiresApi(21) fun terminateProcessesAndWait( waitPollPeriodMs: Long, waitPollMaxCount: Int, processName: String ) { val processes = getPidsForProcess(processName).map { pid -> ProcessPid(pid = pid, processName = processName) } terminateProcessesAndWait( waitPollPeriodMs = waitPollPeriodMs, waitPollMaxCount = waitPollMaxCount, *processes.toTypedArray() ) } @RequiresApi(21) fun terminateProcessesAndWait( waitPollPeriodMs: Long, waitPollMaxCount: Int, vararg processes: ProcessPid ) { processes.forEach { // NOTE: we don't fail on stdout/stderr, since killing processes can be racy, and // killing one can kill others. Instead, validation of process death happens below. val stopOutput = executeScriptCaptureStdoutStderr("kill -TERM ${it.pid}") Log.d(BenchmarkState.TAG, "kill -TERM command output - $stopOutput") } var runningProcesses = processes.toList() repeat(waitPollMaxCount) { runningProcesses = runningProcesses.filter { isProcessAlive(it.pid, it.processName) } if (runningProcesses.isEmpty()) { return } userspaceTrace("wait for $runningProcesses to die") { SystemClock.sleep(waitPollPeriodMs) } Log.d(BenchmarkState.TAG, "Waiting $waitPollPeriodMs ms for $runningProcesses to die") } throw IllegalStateException("Failed to stop $runningProcesses") } @RequiresApi(21) fun pathExists(absoluteFilePath: String): Boolean { return ShellImpl.executeCommandUnsafe("ls $absoluteFilePath").trim() == absoluteFilePath } @RequiresApi(21) fun amBroadcast(broadcastArguments: String): Int? { // unsafe here for perf, since we validate the return value so we don't need to check stderr return ShellImpl.executeCommandUnsafe("am broadcast $broadcastArguments") .substringAfter("Broadcast completed: result=") .trim() .toIntOrNull() } } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) private object ShellImpl { init { require(Looper.getMainLooper().thread != Thread.currentThread()) { "ShellImpl must not be initialized on the UI thread - UiAutomation must not be " + "connected on the main thread!" } } private val uiAutomation = InstrumentationRegistry.getInstrumentation().uiAutomation /** * When true, the session is already rooted and all commands run as root by default. */ var isSessionRooted = false /** * When true, su is available for running commands and scripts as root. */ var isSuAvailable = false init { // These variables are used in executeCommand and executeScript, so we keep them as var // instead of val and use a separate initializer isSessionRooted = executeCommandUnsafe("id").contains("uid=0(root)") // use a script below, since direct `su` command failure brings down this process // on some API levels (and can fail even on userdebug builds) isSuAvailable = createShellScript( script = "su root id", stdin = null ).start().getOutputAndClose().stdout.contains("uid=0(root)") } /** * Reimplementation of UiAutomator's Device.executeShellCommand, * to avoid the UiAutomator dependency, and add tracing * * NOTE: this does not capture stderr, and is thus unsafe. Only use this when the more complex * Shell.executeScript APIs aren't appropriate (such as in their implementation) */ fun executeCommandUnsafe(cmd: String): String = trace("executeCommand $cmd".take(127)) { return@trace executeCommandNonBlockingUnsafe(cmd).fullyReadInputStream() } fun executeCommandNonBlockingUnsafe(cmd: String): ParcelFileDescriptor = trace("executeCommandNonBlocking $cmd".take(127)) { return@trace uiAutomation.executeShellCommand( if (!isSessionRooted && isSuAvailable) { "su root $cmd" } else { cmd } ) } fun createShellScript( script: String, stdin: String? ): ShellScript = trace("createShellScript") { // dirUsableByAppAndShell is writable, but we can't execute there (as of Q), // so we copy to /data/local/tmp val externalDir = Outputs.dirUsableByAppAndShell val scriptContentFile = File.createTempFile("temporaryScript", null, externalDir) // only create/read/delete stdin/stderr files if they are needed val stdinFile = stdin?.run { File.createTempFile("temporaryStdin", null, externalDir) } // we use a path on /data/local/tmp (as opposed to externalDir) because some shell // commands fail to redirect stderr to externalDir (notably, `am start`). // This also means we need to `cat` the file to read it, and `rm` to remove it. val stderrPath = "/data/local/tmp/" + scriptContentFile.name + "_stderr" try { stdinFile?.writeText(stdin) scriptContentFile.writeText(script) return@trace ShellScript( stdinFile = stdinFile, scriptContentFile = scriptContentFile, stderrPath = stderrPath ) } catch (e: Exception) { throw Exception("Can't create shell script", e) } } } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @RequiresApi(Build.VERSION_CODES.LOLLIPOP) class ShellScript internal constructor( private val stdinFile: File?, private val scriptContentFile: File, private val stderrPath: String ) { private var cleanedUp: Boolean = false /** * Starts the shell script previously created. * * @return a [StartedShellScript] that contains streams to read output streams. */ fun start(): StartedShellScript = trace("ShellScript#start") { val stdoutDescriptor = ShellImpl.executeCommandNonBlockingUnsafe( scriptWrapperCommand( scriptContentPath = scriptContentFile.absolutePath, stderrPath = stderrPath, stdinPath = stdinFile?.absolutePath ) ) val stderrDescriptorFn = stderrPath.run { { ShellImpl.executeCommandUnsafe("cat $stderrPath") } } return@trace StartedShellScript( stdoutDescriptor = stdoutDescriptor, stderrDescriptorFn = stderrDescriptorFn, cleanUpBlock = ::cleanUp ) } /** * Manually clean up the shell script temporary files from the temp folder. */ fun cleanUp() = trace("ShellScript#cleanUp") { if (cleanedUp) { return@trace } // NOTE: while we could theoretically remove some of these files from the script, this isn't // safe when the script is called multiple times, expecting the intermediates to remain. // We need a rm to clean up the stderr file anyway (b/c it's not ready until stdout is // complete), so we just delete everything here, all at once. ShellImpl.executeCommandUnsafe( "rm -f " + listOfNotNull( stderrPath, scriptContentFile.absolutePath, stdinFile?.absolutePath ).joinToString(" ") ) cleanedUp = true } companion object { /** * Usage args: ```path/to/shellWrapper.sh <scriptFile> <stderrFile> [inputFile]``` */ private val scriptWrapperPath = Shell.createRunnableExecutable( "shellWrapper.sh", """ ### shell script which passes in stdin as needed, and captures stderr in a file # $1 == script content (not executable) # $2 == stderr # $3 == stdin (optional) if [[ $3 -eq "0" ]]; then /system/bin/sh $1 2> $2 else cat $3 | /system/bin/sh $1 2> $2 fi """.trimIndent().byteInputStream() ) fun scriptWrapperCommand( scriptContentPath: String, stderrPath: String, stdinPath: String? ): String = listOfNotNull( scriptWrapperPath, scriptContentPath, stderrPath, stdinPath ).joinToString(" ") } } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @RequiresApi(Build.VERSION_CODES.LOLLIPOP) class StartedShellScript internal constructor( private val stdoutDescriptor: ParcelFileDescriptor, private val stderrDescriptorFn: (() -> (String)), private val cleanUpBlock: () -> Unit ) : Closeable { /** * Returns a [Sequence] of [String] containing the lines written by the process to stdOut. */ fun stdOutLineSequence(): Sequence<String> = AutoCloseInputStream(stdoutDescriptor).bufferedReader().lineSequence() /** * Cleans up this shell script. */ override fun close() = cleanUpBlock() /** * Reads the full process output and cleans up the generated script */ fun getOutputAndClose(): Shell.Output { val output = Shell.Output( stdout = stdoutDescriptor.fullyReadInputStream(), stderr = stderrDescriptorFn.invoke() ) close() return output } } internal fun ParcelFileDescriptor.fullyReadInputStream(): String { AutoCloseInputStream(this).use { inputStream -> return inputStream.readBytes().toString(Charset.defaultCharset()) } }
apache-2.0
145f64356658c9f6406008e6e484778a
36.650071
133
0.617236
4.672198
false
false
false
false
sheungon/SotwtmSupportLib
lib-sotwtm-support/src/main/kotlin/com/sotwtm/support/util/databinding/TextViewHelpfulBindingAdapter.kt
1
4077
package com.sotwtm.support.util.databinding import android.content.Context import androidx.databinding.BindingAdapter import android.graphics.Paint import android.graphics.Typeface import android.graphics.drawable.Drawable import android.os.Build import androidx.core.content.ContextCompat import android.widget.TextView /** * DataBinding methods and BindingMethods created for easier implementation for Android DataBinding. * Implementation for [TextView] * * @author sheungon */ object TextViewHelpfulBindingAdapter { @JvmStatic @Synchronized @BindingAdapter( value = ["showError"], requireAll = false ) fun showError( view: TextView, error: String? ) { view.error = error if (error != null) { view.requestFocus() } } @JvmStatic @Synchronized @BindingAdapter( value = ["showErrorRes"], requireAll = false ) fun showError( view: TextView, errorRes: Int? ) { showError(view, if (errorRes == null) null else view.context.getString(errorRes)) } @JvmStatic @BindingAdapter("textColorRes") fun setTextColorRes( view: TextView, textColorRes: Int ) { view.setTextColor(ContextCompat.getColor(view.context, textColorRes)) } @JvmStatic @BindingAdapter( value = ["drawableResLeft", "drawableResRight", "drawableResTop", "drawableResBottom", "drawableResStart", "drawableResEnd"], requireAll = false ) fun setDrawablesRes( view: TextView, left: Int?, right: Int?, top: Int?, bottom: Int?, start: Int?, end: Int? ) { val context = view.context val topDrawable = top?.safeGetDrawable(context) val bottomDrawable = bottom?.safeGetDrawable(context) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { val startDrawable = start?.safeGetDrawable(context) val endDrawable = end?.safeGetDrawable(context) view.setCompoundDrawablesRelative( startDrawable, topDrawable, endDrawable, bottomDrawable ) if ((start == null && left != null) || (end == null && right != null) ) { val leftDrawable = if (start == null) left?.safeGetDrawable(context) else startDrawable val rightDrawable = if (end == null) right?.safeGetDrawable(context) else endDrawable view.setCompoundDrawables( leftDrawable, topDrawable, rightDrawable, bottomDrawable ) } } else { val leftDrawable = left?.safeGetDrawable(context) val rightDrawable = right?.safeGetDrawable(context) view.setCompoundDrawables( leftDrawable, topDrawable, rightDrawable, bottomDrawable ) } } @JvmStatic @BindingAdapter("underlineText") fun underLineText( textView: TextView, underline: Boolean ) { if (underline) { textView.paintFlags = textView.paintFlags or Paint.UNDERLINE_TEXT_FLAG } else { textView.paintFlags = textView.paintFlags and Paint.UNDERLINE_TEXT_FLAG.inv() } } @JvmStatic @BindingAdapter( "typeface", "textStyle", requireAll = false ) fun decorateText( view: TextView, typeface: Typeface?, textStyle: Int? ) { view.setTypeface( typeface ?: view.typeface, textStyle ?: Typeface.NORMAL ) } @JvmStatic private fun Int.safeGetDrawable(context: Context): Drawable? = if (this == 0) null else ContextCompat.getDrawable(context, this) }
apache-2.0
b24abc7910d8736a4b97ba1200b801f6
26.547297
100
0.568801
5.09625
false
false
false
false
Soya93/Extract-Refactoring
platform/configuration-store-impl/testSrc/ModuleStoreRenameTest.kt
4
5281
package com.intellij.configurationStore import com.intellij.ProjectTopics import com.intellij.ide.highlighter.ModuleFileType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.components.stateStore import com.intellij.openapi.module.ModifiableModuleModel import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.ModuleAdapter import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.systemIndependentPath import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.testFramework.* import com.intellij.util.Function import com.intellij.util.SmartList import org.assertj.core.api.Assertions.assertThat import org.junit.ClassRule import org.junit.Rule import org.junit.Test import org.junit.rules.ExternalResource import java.io.File import java.nio.file.Paths import java.util.* import kotlin.properties.Delegates internal class ModuleStoreRenameTest { companion object { @JvmField @ClassRule val projectRule = ProjectRule() private val Module.storage: FileBasedStorage get() = (stateStore.stateStorageManager as StateStorageManagerImpl).getCachedFileStorages(listOf(StoragePathMacros.MODULE_FILE)).first() } var module: Module by Delegates.notNull() // we test fireModuleRenamedByVfsEvent private val oldModuleNames = SmartList<String>() private val tempDirManager = TemporaryDirectory() private val ruleChain = RuleChain( tempDirManager, object : ExternalResource() { override fun before() { runInEdtAndWait { module = projectRule.createModule(tempDirManager.newPath(refreshVfs = true).resolve("m.iml")) } module.messageBus.connect().subscribe(ProjectTopics.MODULES, object : ModuleAdapter() { override fun modulesRenamed(project: Project, modules: MutableList<Module>, oldNameProvider: Function<Module, String>) { assertThat(modules).containsOnly(module) oldModuleNames.add(oldNameProvider.`fun`(module)) } }) } // should be invoked after project tearDown override fun after() { (ApplicationManager.getApplication().stateStore.stateStorageManager as StateStorageManagerImpl).getVirtualFileTracker()!!.remove { if (it.storageManager.componentManager == module) { throw AssertionError("Storage manager is not disposed, module $module, storage $it") } false } } }, DisposeModulesRule(projectRule) ) @Rule fun getChain() = ruleChain fun changeModule(task: ModifiableModuleModel.() -> Unit) { runInEdtAndWait { val model = ModuleManager.getInstance(projectRule.project).modifiableModel runWriteAction { model.task() model.commit() } } } // project structure @Test fun `rename module using model`() { runInEdtAndWait { module.saveStore() } val storage = module.storage val oldFile = storage.file assertThat(oldFile).isFile() val oldName = module.name val newName = "foo" changeModule { renameModule(module, newName) } assertRename(newName, oldFile) assertThat(oldModuleNames).containsOnly(oldName) } // project view @Test fun `rename module using rename virtual file`() { runInEdtAndWait { module.saveStore() } var storage = module.storage val oldFile = storage.file assertThat(oldFile).isFile() val oldName = module.name val newName = "foo" runInEdtAndWait { runWriteAction { LocalFileSystem.getInstance().refreshAndFindFileByIoFile(oldFile)!!.rename(null, "$newName${ModuleFileType.DOT_DEFAULT_EXTENSION}") } } assertRename(newName, oldFile) assertThat(oldModuleNames).containsOnly(oldName) } // we cannot test external rename yet, because it is not supported - ModuleImpl doesn't support delete and create events (in case of external change we don't get move event, but get "delete old" and "create new") private fun assertRename(newName: String, oldFile: File) { val newFile = module.storage.file assertThat(newFile.name).isEqualTo("$newName${ModuleFileType.DOT_DEFAULT_EXTENSION}") assertThat(oldFile) .doesNotExist() .isNotEqualTo(newFile) assertThat(newFile).isFile() // ensure that macro value updated assertThat(module.stateStore.stateStorageManager.expandMacros(StoragePathMacros.MODULE_FILE)).isEqualTo(newFile.systemIndependentPath) } @Test fun `rename module parent virtual dir`() { runInEdtAndWait { module.saveStore() } val storage = module.storage val oldFile = storage.file val parentVirtualDir = storage.getVirtualFile()!!.parent runInEdtAndWait { runWriteAction { parentVirtualDir.rename(null, UUID.randomUUID().toString()) } } val newFile = Paths.get(parentVirtualDir.path, "${module.name}${ModuleFileType.DOT_DEFAULT_EXTENSION}") try { assertThat(newFile).isRegularFile() assertRename(module.name, oldFile) assertThat(oldModuleNames).isEmpty() } finally { runInEdtAndWait { runWriteAction { parentVirtualDir.delete(this) } } } } }
apache-2.0
941cd6a5ddd0802d81ad366841ee6ae5
35.427586
214
0.734899
4.907993
false
true
false
false
bhargavms/QrCodeGenerator
lib-droid-qr-gen/src/main/java/com/bhargavms/WrapperDroidQrGen/QRImageGenerator.kt
1
1690
package com.bhargavms.WrapperDroidQrGen import android.graphics.Bitmap import com.mogra.zxing.BarcodeFormat import com.mogra.zxing.MultiFormatWriter import com.mogra.zxing.WriterException import com.mogra.zxing.common.BitMatrix import android.graphics.Color.BLACK import android.graphics.Color.WHITE /** * Qr code image generator. */ object QRImageGenerator { /** * Encode the given string to a QR format Bitmap. * * @param stringToEncode the string that needs to be encoded into QR format * @param preferredWidth the preferred width in pixels of the Generated Bitmap * @param preferredHeight the preferred height in pixels of the Generated Bitmap * @return the generated QR formatted Bitmap. */ @JvmStatic @Throws(EncodingException::class) fun encodeAsBitmap(stringToEncode: String, preferredWidth: Int, preferredHeight: Int): Bitmap { try { val result = MultiFormatWriter() .encode(stringToEncode, BarcodeFormat.QR_CODE, preferredWidth, preferredHeight, null) val width = result.width val height = result.height val pixels = IntArray(width * height) for (y in 0 until height) { val offset = y * width for (x in 0 until width) { pixels[offset + x] = if (result.get(x, y)) BLACK else WHITE } } val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) bitmap.setPixels(pixels, 0, width, 0, 0, width, height) return bitmap } catch (ex: Exception) { throw EncodingException() } } }
apache-2.0
62412e4f2d590454db7788f10437a1ba
34.957447
105
0.643195
4.401042
false
false
false
false
codebutler/odyssey
retrograde-app-tv/src/main/java/com/codebutler/retrograde/app/shared/GamePresenter.kt
1
3691
/* * GamePresenter.kt * * Copyright (C) 2017 Retrograde Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.codebutler.retrograde.app.shared import android.content.Context import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import androidx.leanback.widget.ImageCardView import androidx.leanback.widget.Presenter import androidx.appcompat.view.ContextThemeWrapper import android.view.ViewGroup import android.widget.ImageView import com.codebutler.retrograde.R import com.codebutler.retrograde.app.shared.ui.ItemViewLongClickListener import com.codebutler.retrograde.lib.library.db.entity.Game import com.squareup.picasso.Picasso class GamePresenter( private val context: Context, private val longClickListener: ItemViewLongClickListener ) : Presenter() { private val themedContext = ContextThemeWrapper(context, R.style.GameCardTheme) private lateinit var defaultCardImage: Drawable private lateinit var starImage: Drawable private var imageWidth: Int = -1 private var imageHeight: Int = -1 override fun onCreateViewHolder(parent: ViewGroup): Presenter.ViewHolder { defaultCardImage = ColorDrawable(Color.BLACK) starImage = context.resources.getDrawable(R.drawable.ic_favorite_white_16dp, context.theme) val cardView = ImageCardView(themedContext) imageWidth = context.resources.getDimensionPixelSize(R.dimen.card_width) imageHeight = context.resources.getDimensionPixelSize(R.dimen.card_height) cardView.setMainImageScaleType(ImageView.ScaleType.CENTER) cardView.isFocusable = true cardView.isFocusableInTouchMode = true cardView.setMainImageDimensions(imageWidth, imageHeight) return Presenter.ViewHolder(cardView) } override fun onBindViewHolder(viewHolder: Presenter.ViewHolder, item: Any) { viewHolder.view.setOnLongClickListener { _ -> longClickListener.onItemLongClicked(viewHolder, item) } when (item) { is Game -> { val cardView = viewHolder.view as ImageCardView cardView.titleText = item.title cardView.contentText = item.developer cardView.badgeImage = if (item.isFavorite) starImage else null if (item.coverFrontUrl != null) { Picasso.get() .load(item.coverFrontUrl) .error(defaultCardImage) .resize(imageWidth, imageHeight) .centerInside() .into(cardView.mainImageView) } else { cardView.mainImage = defaultCardImage } } } } override fun onUnbindViewHolder(viewHolder: Presenter.ViewHolder) { val cardView = viewHolder.view as ImageCardView Picasso.get().cancelRequest(cardView.mainImageView) cardView.mainImage = null cardView.badgeImage = null } }
gpl-3.0
562142534f654d6d7581480221df555e
37.852632
99
0.69385
4.941098
false
false
false
false
pedroSG94/rtmp-rtsp-stream-client-java
rtmp/src/main/java/com/pedro/rtmp/rtmp/Handshake.kt
1
5658
/* * Copyright (C) 2021 pedroSG94. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pedro.rtmp.rtmp import android.util.Log import com.pedro.rtmp.utils.readUntil import com.pedro.rtmp.utils.socket.RtmpSocket import java.io.IOException import java.io.InputStream import java.io.OutputStream import kotlin.random.Random /** * Created by pedro on 8/04/21. * * The C0 and S0 packets are a single octet * * The version defined by this * specification is 3. Values 0-2 are deprecated values used by * earlier proprietary products; 4-31 are reserved for future * implementations; and 32-255 are not allowed * 0 1 2 3 4 5 6 7 * +-+-+-+-+-+-+-+-+ * | version | * +-+-+-+-+-+-+-+-+ * * The C1 and S1 packets are 1536 octets long * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | time (4 bytes) | local generated timestamp * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | zero (4 bytes) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | random bytes | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | random bytes | * | (cont) | * | .... | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * The C2 and S2 packets are 1536 octets long, and nearly an echo of S1 and C1 (respectively). * * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | time (4 bytes) | s1 timestamp for c2 or c1 for s2. In this case s1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | time2 (4 bytes) | timestamp of previous packet (s1 or c1). In this case c1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | random echo | random data field sent by the peer in s1 for c2 or s2 for c1. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | random echo | random data field sent by the peer in s1 for c2 or s2 for c1. * | (cont) | * | .... | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ class Handshake { private val TAG = "Handshake" private val protocolVersion = 0x03 private val handshakeSize = 1536 private var timestampC1 = 0 @Throws(IOException::class) fun sendHandshake(socket: RtmpSocket): Boolean { var output = socket.getOutStream() writeC0(output) val c1 = writeC1(output) socket.flush() var input = socket.getInputStream() readS0(input) val s1 = readS1(input) output = socket.getOutStream() writeC2(output, s1) socket.flush() input = socket.getInputStream() readS2(input, c1) return true } @Throws(IOException::class) private fun writeC0(output: OutputStream) { Log.i(TAG, "writing C0") output.write(protocolVersion) Log.i(TAG, "C0 write successful") } @Throws(IOException::class) private fun writeC1(output: OutputStream): ByteArray { Log.i(TAG, "writing C1") val c1 = ByteArray(handshakeSize) timestampC1 = (System.currentTimeMillis() / 1000).toInt() Log.i(TAG, "writing time $timestampC1 to c1") val timestampData = ByteArray(4) timestampData[0] = (timestampC1 ushr 24).toByte() timestampData[1] = (timestampC1 ushr 16).toByte() timestampData[2] = (timestampC1 ushr 8).toByte() timestampData[3] = timestampC1.toByte() System.arraycopy(timestampData, 0, c1, 0, timestampData.size) Log.i(TAG, "writing zero to c1") val zeroData = byteArrayOf(0x00, 0x00, 0x00, 0x00) System.arraycopy(zeroData, 0, c1, timestampData.size, zeroData.size) Log.i(TAG, "writing random to c1") val random = Random.Default val randomData = ByteArray(handshakeSize - 8) for (i in randomData.indices step 1) { //step UInt8 size //random with UInt8 max value val uInt8 = random.nextInt().toByte() randomData[i] = uInt8 } System.arraycopy(randomData, 0, c1, 8, randomData.size) output.write(c1) Log.i(TAG, "C1 write successful") return c1 } @Throws(IOException::class) private fun writeC2(output: OutputStream, s1: ByteArray) { Log.i(TAG, "writing C2") output.write(s1) Log.i(TAG, "C2 write successful") } @Throws(IOException::class) private fun readS0(input: InputStream): ByteArray { Log.i(TAG, "reading S0") val response = input.read() if (response == protocolVersion || response == 72) { Log.i(TAG, "read S0 successful") return byteArrayOf(response.toByte()) } else { throw IOException("$TAG error, unexpected $response S0 received") } } @Throws(IOException::class) private fun readS1(input: InputStream): ByteArray { Log.i(TAG, "reading S1") val s1 = ByteArray(handshakeSize) input.readUntil(s1) Log.i(TAG, "read S1 successful") return s1 } @Throws(IOException::class) private fun readS2(input: InputStream, c1: ByteArray): ByteArray { Log.i(TAG, "reading S2") val s2 = ByteArray(handshakeSize) input.readUntil(s2) //S2 should be equals to C1 but we can skip this if (!s2.contentEquals(c1)) { Log.e(TAG, "S2 content is different that C1") } Log.i(TAG, "read S2 successful") return s2 } }
apache-2.0
4a6110af7b15ca052bc7cc678665e092
31.901163
94
0.591198
3.817814
false
false
false
false
dropbox/Store
store/src/test/java/com/dropbox/android/external/store4/impl/ValueFetcherTest.kt
1
1989
package com.dropbox.android.external.store4.impl import com.dropbox.android.external.store4.Fetcher import com.dropbox.android.external.store4.FetcherResult import com.dropbox.android.external.store4.testutil.assertThat import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.TestCoroutineScope import kotlinx.coroutines.test.runBlockingTest import org.junit.Test @ExperimentalCoroutinesApi @FlowPreview class ValueFetcherTest { private val testScope = TestCoroutineScope() @Test fun `GIVEN valueFetcher WHEN invoke THEN result is wrapped`() = testScope.runBlockingTest { val fetcher = Fetcher.ofFlow<Int, Int> { flowOf(it * it) } assertThat(fetcher(3)) .emitsExactly(FetcherResult.Data(value = 9)) } @Test fun `GIVEN valueFetcher WHEN exception in flow THEN exception returned as result`() = testScope.runBlockingTest { val e = Exception() val fetcher = Fetcher.ofFlow<Int, Int> { flow { throw e } } assertThat(fetcher(3)) .emitsExactly(FetcherResult.Error.Exception(e)) } @Test fun `GIVEN nonFlowValueFetcher WHEN invoke THEN result is wrapped`() = testScope.runBlockingTest { val fetcher = Fetcher.of<Int, Int> { it * it } assertThat(fetcher(3)) .emitsExactly(FetcherResult.Data(value = 9)) } @Test fun `GIVEN nonFlowValueFetcher WHEN exception in flow THEN exception returned as result`() = testScope.runBlockingTest { val e = Exception() val fetcher = Fetcher.of<Int, Int> { throw e } assertThat(fetcher(3)) .emitsExactly(FetcherResult.Error.Exception(e)) } }
apache-2.0
81e6b1ef0f9efab0908371a0c654b86b
31.606557
96
0.644545
4.669014
false
true
false
false
pbauerochse/youtrack-worklog-viewer
application/src/main/java/de/pbauerochse/worklogviewer/datasource/dummy/DummyNames.kt
1
4165
package de.pbauerochse.worklogviewer.datasource.dummy import de.pbauerochse.worklogviewer.timereport.Tag object DummyNames { val projects = listOf( "CNP", "STUFF", "NON_WORK", "APP", "KFI", "MEET", "VID", "TWT", "STNDUP", "CRWLR", "JNR", "CNFR", "RFCTR", "RNDM" ) val issues = listOf( "That new cool feature", "Implementing a thing into the other thing", "A very strange bug", "Investigating", "Fixing that thing", "Meetings", "Migrating data from excel sheet", "Video conference with that client", "After work beer", "Slacking off", "Finding Nemo", "Get him to the greek", "IMPORTANT LAST MINUTE FEATURE!!", "Counting money", "Making profit", "Calming customer", "Working really hard", "Working really hard faster", "Being awesome", "Saving the planet", "Putting together hardware", "Onboarding new co-worker", "Merge conflicts", "Build problems", "Rage quitting", "Planning company party", "Telephone conference", "Cleaning up", "Writing stuff on post-its", "Talking to the new hot co-worker", "Watering plants", "Calculating last digit of Pi", "Looking busy", "Evaluate that thing", "Refactor the whole darn thing" ) val firstNames = listOf( "Patrick", "Peter", "Markus", "Martin", "Angela", "Penelope", "Dagobert", "Juan", "José", "Alfredo", "Dennis", "Daniel", "Ali", "Ahmed", "Ibrahim", "Sara", "Sarah", "Isabel", "María", "Mariam", "Nicolas", "Noah", "Liam", "Felix", "Luis", "Mateo", "David", "Richard", "Francisco", "Oliver", "Sebastian", "Diego", "Mats", "Leo", "Lucía", "Martina", "Catalina", "Emilia", "Zoe", "Chloe", "Emma", "Charlotte", "Alice", "Bob", "Elizabeth", "Linda", "Elsa", "Victoria", "Valeria", "George", "Jack", "Robert", "Elias", "Lina", "Mia", "Lara", "Jana", "Susanne", "Suzana", "Nora", "Ella" ) val lastNames = listOf( "Watson", "Holmes", "Jolie", "Pitt", "da Vito", "di Caprio", "Duck", "Rabbit", "Parker", "Wayne", "Travis", "Vermeer", "Fowler", "Keppler", "Norton", "Rickman", "De Niro", "Bale", "Waltz", "Freeman", "Williams", "Pacino", "Hernandez", "Svensson", "Murray", "Stewart", "Newman", "Franco", "Dominguez", "Chao", "Pesci", "Malkovich" ) val fields = listOf( ProjectField("Type", listOf("Issue", "Bug", "Feature Request", "Nonsense", "Question", "Investigation", "Evaluation", "Meeting")), ProjectField("Customer", listOf( "Evil Corp", "The Umbrella Corp", "Pearson Specter", "Pawtucket Brewery", "Multi National United", "Lunar Industries", "Acme Corporation", "Initech", "Dunder Mifflin", "Nakatomi Trading Co.", "Stark Industries", "Macmillan Toys", "Cyberdyne Systems", "Wonka's", "Monsters Inc.", "Wayne Enterprises" )), ProjectField("Component", listOf("Migration", "Import", "Export", "Interface", "App", "Communication")), ProjectField("Difficulty", listOf("Easy peasy", "Easy", "Quite alright", "Medium", "Not too easy", "Hard", "Tough", "Oh my gosh!", "Please help me!")), ProjectField("Costs", listOf("Thrift shop", "Cheap", "Affordable", "Moderate", "Tad expensive", "Rip off", "Muhahaha", "2nd mortgage")), ProjectField("Deadline", listOf("yesterday", "ASAP", "Now!", "Take your time", "Better work overtime")) ) val tags = listOf( Tag("Important", backgroundColor = "ff0000"), Tag("Hotfix", backgroundColor = "ff0000"), Tag("Feeback required", backgroundColor = "ddddff", foregroundColor = "ffffff"), Tag("Easy", backgroundColor = "ddffdd", foregroundColor = "000000"), Tag("Needs more details", backgroundColor = "ddffff", foregroundColor = "ff0000"), Tag("Ugly UI", backgroundColor = "00FF00", foregroundColor = "0000FF"), Tag("Refactoring", backgroundColor = "0000ff"), Tag("A very very long tag name", backgroundColor = "dd00dd"), Tag("DB Migration", backgroundColor = "bbbbbb", foregroundColor = "ffffff") ) data class ProjectField( val name : String, val possibleValues : List<String> ) }
mit
1145b4db6181a06f1a907367dbd2c4ca
58.471429
161
0.615569
3.425514
false
false
false
false
hastebrot/protokola
src/main/kotlin/protokola/transform/dolphinCodec.kt
1
2999
package protokola.transform import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import com.squareup.moshi.Types import protokola.println import protokola.transport.Transport fun main(vararg args: String) { val responseContext = Transport.ServerResponse(200, """ [{"p_id":"f6a23423-d104-41a8-84a9-c793ae2cee32","t":"@@@ HIGHLANDER_BEAN @@@","a":[{"n":"@@@ SOURCE_SYSTEM @@@","a_id":"920S","v":"server"},{"n":"controllerName","a_id":"921S","v":null},{"n":"controllerId","a_id":"922S","v":null},{"n":"model","a_id":"923S","v":null}],"id":"CreatePresentationModel"}] """.trimIndent()) responseContext.println val codec = DolphinCodec() val commands = codec.fromJson(responseContext) commands.println "commands".println commands.forEach { it.println it["id"].println } val commandsJson = codec.toJson(commands) commandsJson.println } class DolphinCodec { private val jsonAdapter = simpleJsonAdapter() fun fromJson(response: Transport.ServerResponse) = jsonAdapter.fromJson(response.body!!)!! fun toJson(commands: JsonCommandList) = jsonAdapter.toJson(commands)!! fun toCommand(response: Transport.ServerResponse): DolphinCommand.CreatePresentationModel { val commands = fromJson(response) val command = DolphinCommand.CreatePresentationModel( commands.index(0).keyed("id"), commands.index(0).keyed("p_id"), commands.index(0).keyed("t"), commands.index(0)!!.keyed<Any, List<Any>>("a").map { DolphinCommand.CreatePresentationModel.Attribute( it.keyed("a_id"), it.keyed("n"), it.keyed("v") ) } ) return command } } object DolphinCommand { class CreateContext class DestroyContext data class CreatePresentationModel(val id: String, val presentationModelId: String, val type: String, val attributes: List<Attribute>) { data class Attribute(val attributeId: String, val name: String, val value: Any?) } class DeletePresentationModel class CreateController class DestroyController class ValueChanged class CallAction } private fun simpleJsonAdapter(): JsonAdapter<JsonCommandList> { val moshi = Moshi.Builder().build() val listOfCommands = Types.newParameterizedType( List::class.java, Map::class.java ) return moshi.adapter(listOfCommands) } typealias JsonCommandList = List<Map<String, *>> fun <T> T.index(index: Int) = (this as List<*>)[index] fun <T> T.key(key: String) = (this as Map<*, *>)[key] inline fun <T, reified R> T.indexed(index: Int) = index(index) as R inline fun <T, reified R> T.keyed(key: String) = key(key) as R
apache-2.0
6c81c97130118ddd9f7857f35cdfc5e6
29.917526
308
0.611204
4.188547
false
false
false
false
ligee/kotlin-jupyter
src/main/kotlin/org/jetbrains/kotlinx/jupyter/repl/impl/InternalEvaluatorImpl.kt
1
7868
package org.jetbrains.kotlinx.jupyter.repl.impl import kotlinx.coroutines.runBlocking import org.jetbrains.kotlinx.jupyter.VariablesUsagesPerCellWatcher import org.jetbrains.kotlinx.jupyter.api.Code import org.jetbrains.kotlinx.jupyter.api.FieldValue import org.jetbrains.kotlinx.jupyter.api.VariableState import org.jetbrains.kotlinx.jupyter.api.VariableStateImpl import org.jetbrains.kotlinx.jupyter.compiler.CompiledScriptsSerializer import org.jetbrains.kotlinx.jupyter.compiler.util.SerializedCompiledScript import org.jetbrains.kotlinx.jupyter.compiler.util.SerializedCompiledScriptsData import org.jetbrains.kotlinx.jupyter.compiler.util.SourceCodeImpl import org.jetbrains.kotlinx.jupyter.exceptions.ReplCompilerException import org.jetbrains.kotlinx.jupyter.exceptions.ReplEvalRuntimeException import org.jetbrains.kotlinx.jupyter.repl.ContextUpdater import org.jetbrains.kotlinx.jupyter.repl.InternalEvalResult import org.jetbrains.kotlinx.jupyter.repl.InternalEvaluator import org.jetbrains.kotlinx.jupyter.repl.InternalVariablesMarkersProcessor import kotlin.reflect.KMutableProperty1 import kotlin.reflect.KProperty1 import kotlin.reflect.full.declaredMemberProperties import kotlin.script.experimental.api.ResultValue import kotlin.script.experimental.api.ResultWithDiagnostics import kotlin.script.experimental.jvm.BasicJvmReplEvaluator import kotlin.script.experimental.jvm.impl.KJvmCompiledScript internal class InternalEvaluatorImpl( val compiler: JupyterCompiler, private val evaluator: BasicJvmReplEvaluator, private val contextUpdater: ContextUpdater, override var logExecution: Boolean, private val internalVariablesMarkersProcessor: InternalVariablesMarkersProcessor, ) : InternalEvaluator { private var classWriter: ClassWriter? = null private val scriptsSerializer = CompiledScriptsSerializer() private val registeredCompiledScripts = arrayListOf<SerializedCompiledScript>() private fun serializeAndRegisterScript(compiledScript: KJvmCompiledScript) { val serializedData = scriptsSerializer.serialize(compiledScript) registeredCompiledScripts.addAll(serializedData.scripts) } override fun popAddedCompiledScripts(): SerializedCompiledScriptsData { val scripts = registeredCompiledScripts.toList() registeredCompiledScripts.clear() return SerializedCompiledScriptsData(scripts) } override var writeCompiledClasses: Boolean get() = classWriter != null set(value) { classWriter = if (!value) null else { val cw = ClassWriter() System.setProperty("spark.repl.class.outputDir", cw.outputDir.toString()) cw } } override val lastKClass get() = compiler.lastKClass override val lastClassLoader get() = compiler.lastClassLoader override val variablesHolder = mutableMapOf<String, VariableState>() override val cellVariables: Map<Int, Set<String>> get() = variablesWatcher.cellVariables private val variablesWatcher: VariablesUsagesPerCellWatcher<Int, String> = VariablesUsagesPerCellWatcher() private var isExecuting = false override fun eval(code: Code, cellId: Int, onInternalIdGenerated: ((Int) -> Unit)?): InternalEvalResult { try { if (isExecuting) { error("Recursive execution is not supported") } isExecuting = true if (logExecution) { println("Executing:\n$code") } val id = compiler.nextCounter() if (onInternalIdGenerated != null) { onInternalIdGenerated(id) } val codeLine = SourceCodeImpl(id, code) val (compileResult, evalConfig) = compiler.compileSync(codeLine) val compiledScript = compileResult.get() classWriter?.writeClasses(codeLine, compiledScript) val resultWithDiagnostics = runBlocking { evaluator.eval(compileResult, evalConfig) } contextUpdater.update() when (resultWithDiagnostics) { is ResultWithDiagnostics.Success -> { val pureResult = resultWithDiagnostics.value.get() return when (val resultValue = pureResult.result) { is ResultValue.Error -> throw ReplEvalRuntimeException( resultValue.error.message.orEmpty(), resultValue.error ) is ResultValue.Unit, is ResultValue.Value -> { serializeAndRegisterScript(compiledScript) updateDataAfterExecution(cellId, resultValue) if (resultValue is ResultValue.Unit) { InternalEvalResult( FieldValue(Unit, null), resultValue.scriptInstance!! ) } else { resultValue as ResultValue.Value InternalEvalResult( FieldValue(resultValue.value, resultValue.name), resultValue.scriptInstance!! ) } } is ResultValue.NotEvaluated -> { throw ReplEvalRuntimeException( "This snippet was not evaluated", resultWithDiagnostics.reports.firstOrNull()?.exception ) } else -> throw IllegalStateException("Unknown eval result type $this") } } is ResultWithDiagnostics.Failure -> { throw ReplCompilerException(code, resultWithDiagnostics) } else -> throw IllegalStateException("Unknown result") } } finally { isExecuting = false } } private fun updateVariablesState(cellId: Int) { variablesWatcher.removeOldUsages(cellId) variablesHolder.forEach { val state = it.value as VariableStateImpl if (state.update()) { variablesWatcher.addUsage(cellId, it.key) } } } private fun getVisibleVariables(target: ResultValue, cellId: Int): Map<String, VariableStateImpl> { val kClass = target.scriptClass ?: return emptyMap() val cellClassInstance = target.scriptInstance!! val fields = kClass.declaredMemberProperties return mutableMapOf<String, VariableStateImpl>().apply { for (property in fields) { @Suppress("UNCHECKED_CAST") property as KProperty1<Any, *> if (internalVariablesMarkersProcessor.isInternal(property)) continue val state = VariableStateImpl(property, cellClassInstance) variablesWatcher.addDeclaration(cellId, property.name) // it was val, now it's var if (property is KMutableProperty1) { variablesHolder.remove(property.name) } else { variablesHolder[property.name] = state continue } put(property.name, state) } } } private fun updateDataAfterExecution(lastExecutionCellId: Int, resultValue: ResultValue) { variablesWatcher.ensureStorageCreation(lastExecutionCellId) variablesHolder += getVisibleVariables(resultValue, lastExecutionCellId) updateVariablesState(lastExecutionCellId) } }
apache-2.0
dfd714e96f36a6e15f5086b7fe3e8c3d
40.193717
110
0.630147
5.540845
false
false
false
false
sebastiansokolowski/AuctionHunter---Allegro
server/src/main/kotlin/com/sebastiansokolowski/auctionhunter/model/SearchEngineModel.kt
1
6862
package com.sebastiansokolowski.auctionhunter.model import com.sebastiansokolowski.auctionhunter.allegro_api.AllegroClient import com.sebastiansokolowski.auctionhunter.allegro_api.response.Listing import com.sebastiansokolowski.auctionhunter.allegro_api.response.ListingOffer import com.sebastiansokolowski.auctionhunter.config.AuctionHunterProp import com.sebastiansokolowski.auctionhunter.dao.BlacklistUserDao import com.sebastiansokolowski.auctionhunter.dao.TargetDao import com.sebastiansokolowski.auctionhunter.entity.Offer import com.sebastiansokolowski.auctionhunter.entity.Target import org.springframework.beans.factory.annotation.Autowired import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* import java.util.concurrent.TimeUnit import java.util.logging.Logger import kotlin.collections.HashMap import kotlin.collections.set class SearchEngineModel { private val LOG = Logger.getLogger(javaClass.simpleName) @Autowired private lateinit var allegroClient: AllegroClient @Autowired private lateinit var mailSenderModel: MailSenderModel @Autowired private lateinit var telegramBotModel: TelegramBotModel @Autowired private lateinit var targetDao: TargetDao @Autowired private lateinit var blacklistUserDao: BlacklistUserDao @Autowired private lateinit var auctionHunterProp: AuctionHunterProp fun startSearching() { val timer = Timer() timer.scheduleAtFixedRate( SearchTask(), 0, TimeUnit.SECONDS.toMillis(auctionHunterProp.searchPeriodInS.toLong()) ) } inner class SearchTask : TimerTask() { override fun run() { if (!isNightTime()) { search() } } override fun scheduledExecutionTime(): Long { return super.scheduledExecutionTime() } override fun cancel(): Boolean { return super.cancel() } } private fun isNightTime(): Boolean { val calendar = Calendar.getInstance() val hour = calendar.get(Calendar.HOUR_OF_DAY) auctionHunterProp.nightMode?.run { if (hour in start..stop) { LOG.info("night mode on") return true } } return false } private fun search() { targetDao.findAll().forEach { target -> val parameters = HashMap<String, String>() target.parameters.forEach { parameter -> parameters[parameter.name] = parameter.value } allegroClient.getAllegroApi().getOffers( target.categoryId, target.phrase, parameters = parameters ).enqueue(object : Callback<Listing> { override fun onFailure(call: Call<Listing>, t: Throwable) { LOG.info(t.message) } override fun onResponse(call: Call<Listing>, response: Response<Listing>) { if (response.body() != null) { val offers = mutableListOf<ListingOffer>() offers.addAll(response.body()!!.items.promoted) offers.addAll(response.body()!!.items.regular) checkNewOffers(target, offers) } else { LOG.info("response body is null") } } }) } } private fun checkNewOffers(target: Target, offers: MutableList<ListingOffer>) { var filteredOffers = offers filteredOffers = filterOldOffers(target, filteredOffers) filteredOffers = filterIncludeKeywords(target, filteredOffers) filteredOffers = filterExcludeKeywords(target, filteredOffers) filteredOffers = filterBlacklistUsers(filteredOffers) target.offers.addAll(filteredOffers.map { Offer(offer_id = it.id) }) if (filteredOffers.isNotEmpty()) { filteredOffers.sortBy { it.sellingMode.price.amount } LOG.info("new offers! offersIds=${filteredOffers.map { it.id }}") if (auctionHunterProp.email.isNotEmpty()) { mailSenderModel.sendMail(filteredOffers) } if (auctionHunterProp.telegramBot != null) { telegramBotModel.sendMessage(filteredOffers) } targetDao.save(target) } } private fun filterOldOffers(target: Target, offers: MutableList<ListingOffer>): MutableList<ListingOffer> { val oldOffers = target.offers.map { it.offer_id } return offers.filterNot { oldOffers.contains(it.id) }.toMutableList() } private fun filterBlacklistUsers(offers: MutableList<ListingOffer>): MutableList<ListingOffer> { val matchedOffers = mutableListOf<ListingOffer>() val blacklistUsers = blacklistUserDao.findAll() offers.forEach { offer -> blacklistUsers.forEach blacklist_loop@{ blacklistUser -> val sellerLogin = offer.seller.login ?: return@blacklist_loop if (blacklistUser.regex && sellerLogin.matches(Regex(blacklistUser.username)) || sellerLogin == blacklistUser.username) { matchedOffers.add(offer) } } } return offers.minus(matchedOffers).toMutableList() } private fun filterIncludeKeywords(target: Target, offers: MutableList<ListingOffer>): MutableList<ListingOffer> { val matchedOffers = mutableListOf<ListingOffer>() val includeKeywords = target.keywords.filter { it.include }.map { it.phrase } if (includeKeywords.isNotEmpty()) { offers.forEach { offer -> includeKeywords.forEach { includeKeyword -> if (offer.name.contains(includeKeyword, ignoreCase = true)) { matchedOffers.add(offer) } } } } else { matchedOffers.addAll(offers) } return matchedOffers } private fun filterExcludeKeywords(target: Target, offers: MutableList<ListingOffer>): MutableList<ListingOffer> { val matchedOffers = mutableListOf<ListingOffer>() val excludeKeywords = target.keywords.filter { !it.include }.map { it.phrase } if (excludeKeywords.isNotEmpty()) { offers.forEach { offer -> excludeKeywords.forEach { excludeKeyword -> if (!offer.name.contains(excludeKeyword, ignoreCase = true)) { matchedOffers.add(offer) } } } } else { matchedOffers.addAll(offers) } return matchedOffers } }
apache-2.0
2f1d8708dbac238f3259fe87fbd5430b
34.931937
117
0.618041
4.958092
false
false
false
false
docker-client/docker-compose-v3
src/main/kotlin/de/gesellix/docker/compose/adapters/ReflectionUtil.kt
1
730
package de.gesellix.docker.compose.adapters import kotlin.reflect.KMutableProperty import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.full.memberProperties fun <R : Any?> readPropery(instance: Any, propertyName: String): R { val clazz = instance.javaClass.kotlin @Suppress("UNCHECKED_CAST") return clazz.declaredMemberProperties.first { it.name == propertyName }.get(instance) as R } fun writePropery(instance: Any, propertyName: String, value: Any?) { val clazz = instance.javaClass.kotlin @Suppress("UNCHECKED_CAST") return clazz.memberProperties .filterIsInstance<KMutableProperty<*>>() .first { it.name == propertyName }.setter.call(instance, value) }
mit
332281290151dc5a229c6017e00870d3
37.421053
94
0.739726
4.39759
false
false
false
false
fredyw/leetcode
src/main/kotlin/leetcode/Problem2165.kt
1
831
package leetcode /** * https://leetcode.com/problems/smallest-value-of-the-rearranged-number/ */ class Problem2165 { fun smallestNumber(num: Long): Long { if (num > 0) { val chars = num.toString().toCharArray() chars.sort() var count = 0 var i = 0 while (chars[i] == '0') { i++ count++ } var answer = chars[i++] + "0".repeat(count) while (i < chars.size) { answer += chars[i++] } return answer.toLong() } else if (num < 0) { val chars = num.toString().substring(1).toCharArray() chars.sortDescending() val answer = String(chars) return -1 * answer.toLong() } return 0 } }
mit
0034c7dfbb578892298b2e56797abbca
26.7
73
0.458484
4.175879
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/map/TangramQuestSpriteSheet.kt
1
3719
package de.westnordost.streetcomplete.map import android.content.Context import android.content.SharedPreferences import android.graphics.Bitmap import android.graphics.Canvas import androidx.core.content.edit import com.mapzen.tangram.SceneUpdate import de.westnordost.streetcomplete.BuildConfig import de.westnordost.streetcomplete.Prefs import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.quest.QuestTypeRegistry import java.util.* import javax.inject.Inject import javax.inject.Singleton import kotlin.math.ceil import kotlin.math.sqrt /** From all the quest types, creates and saves a sprite sheet of quest type pin icons, provides * the scene updates for tangram to access this sprite sheet */ @Singleton class TangramQuestSpriteSheet @Inject constructor( private val context: Context, private val questTypeRegistry: QuestTypeRegistry, private val prefs: SharedPreferences ) { val sceneUpdates: List<SceneUpdate> by lazy { val isSpriteSheetCurrent = prefs.getInt(Prefs.QUEST_SPRITES_VERSION, 0) == BuildConfig.VERSION_CODE val spriteSheet = if (isSpriteSheetCurrent && !BuildConfig.DEBUG) prefs.getString(Prefs.QUEST_SPRITES, "")!! else createSpritesheet() createSceneUpdates(spriteSheet) } private fun createSpritesheet(): String { val questIconResIds = questTypeRegistry.all.map { it.icon }.toSortedSet() val spriteSheetEntries: MutableList<String> = ArrayList(questIconResIds.size) val questPin = context.resources.getDrawable(R.drawable.quest_pin) val iconSize = questPin.intrinsicWidth val questIconSize = 2 * iconSize / 3 val questIconOffsetX = 56 * iconSize / 192 val questIconOffsetY = 18 * iconSize / 192 val sheetSideLength = ceil(sqrt(questIconResIds.size.toDouble())).toInt() val bitmapLength = sheetSideLength * iconSize val spriteSheet = Bitmap.createBitmap(bitmapLength, bitmapLength, Bitmap.Config.ARGB_8888) val canvas = Canvas(spriteSheet) for ((i, questIconResId) in questIconResIds.withIndex()) { val x = i % sheetSideLength * iconSize val y = i / sheetSideLength * iconSize questPin.setBounds(x, y, x + iconSize, y + iconSize) questPin.draw(canvas) val questIcon = context.resources.getDrawable(questIconResId) val questX = x + questIconOffsetX val questY = y + questIconOffsetY questIcon.setBounds(questX, questY, questX + questIconSize, questY + questIconSize) questIcon.draw(canvas) val questIconName = context.resources.getResourceEntryName(questIconResId) spriteSheetEntries.add("$questIconName: [$x,$y,$iconSize,$iconSize]") } context.deleteFile(QUEST_ICONS_FILE) val spriteSheetIconsFile = context.openFileOutput(QUEST_ICONS_FILE, Context.MODE_PRIVATE) spriteSheet.compress(Bitmap.CompressFormat.PNG, 0, spriteSheetIconsFile) spriteSheetIconsFile.close() val questSprites = "{${spriteSheetEntries.joinToString(",")}}" prefs.edit { putInt(Prefs.QUEST_SPRITES_VERSION, BuildConfig.VERSION_CODE) putString(Prefs.QUEST_SPRITES, questSprites) } return questSprites } private fun createSceneUpdates(questSprites: String): List<SceneUpdate> = listOf( SceneUpdate("textures.quests.url", "file://${context.filesDir}/$QUEST_ICONS_FILE"), SceneUpdate("textures.quests.sprites", questSprites) ) companion object { private const val QUEST_ICONS_FILE = "quests.png" } }
gpl-3.0
ecda5fcf53376f1d36ba2e32519074d4
40.786517
107
0.699382
4.568796
false
true
false
false
alorma/TimelineView
app/src/main/java/com/alorma/timelineview/app/ListExampleActivity.kt
1
2345
package com.alorma.timelineview.app import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.list_example_activity.* class ListExampleActivity : AppCompatActivity() { private val adapter = EventsAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.list_example_activity) buildList() buildLineStyle() buildLineColor() buildPointStyle() } private fun buildLineStyle() { lineLinear.setOnClickListener { adapter.lineStyle = SampleLineStyle.LINE } lineDashed.setOnClickListener { adapter.lineStyle = SampleLineStyle.DASHED } lineMixed.setOnClickListener { adapter.lineStyle = SampleLineStyle.MIXED } } private fun buildLineColor() { lineRed.setOnClickListener { adapter.lineColor = SampleLineColor.RED } lineGreen.setOnClickListener { adapter.lineColor = SampleLineColor.GREEN } lineColorMix.setOnClickListener { adapter.lineColor = SampleLineColor.MIXED } } private fun buildPointStyle() { pointCircle.setOnClickListener { adapter.pointStyle = SamplePointStyle.CIRCLE } pointSquare.setOnClickListener { adapter.pointStyle = SamplePointStyle.SQUARE } pointMixed.setOnClickListener { adapter.pointStyle = SamplePointStyle.MIXED } pointNone.setOnClickListener { adapter.pointStyle = SamplePointStyle.NONE } } private fun buildList() { val list = findViewById<RecyclerView>(R.id.list) val firstEvent = Event(getString(R.string.item_first)) val middleEvents = (1..19).map { getString(R.string.item_default, it) }.map { Event(it) } val lastElement = Event(getString(R.string.item_last)) val items = listOf(firstEvent).plus(middleEvents).plus(lastElement) list.layoutManager = LinearLayoutManager(this) list.adapter = adapter adapter.submitList(items) } }
apache-2.0
d4fb14a7e8c2eb434b752979d5213046
27.950617
75
0.654584
5.064795
false
false
false
false
docker-client/docker-compose-v3
src/main/kotlin/de/gesellix/docker/compose/types/ServiceVolume.kt
1
338
package de.gesellix.docker.compose.types data class ServiceVolume( var type: String = "", var source: String = "", var target: String = "", var readOnly: Boolean = false, var consistency: String = "", var bind: ServiceVolumeBind? = null, var volume: ServiceVolumeVolume? = null )
mit
3f75c942520deec5ad0a1974a47fd309
27.166667
47
0.600592
4.567568
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/quest/UndoableOsmQuestsSource.kt
1
2799
package de.westnordost.streetcomplete.data.quest import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuest import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestController import java.util.concurrent.CopyOnWriteArrayList import javax.inject.Inject import javax.inject.Singleton /** Access and listen to undoable (closed, hidden, answered) changes there are. * * Currently, only OsmQuests are undoable. If more things become undoable or conditionally * undoable, the structure of this needs to be re-thought. Probably undoable things should * implement an interface, and the source for this would return those instead of quests. */ @Singleton class UndoableOsmQuestsSource @Inject constructor( private val osmQuestController: OsmQuestController ){ private val listeners: MutableList<UndoableOsmQuestsCountListener> = CopyOnWriteArrayList() var count: Int = osmQuestController.getAllUndoableCount() set(value) { val diff = value - field field = value onUpdate(diff) } private val questStatusListener = object : OsmQuestController.QuestStatusListener { override fun onChanged(quest: OsmQuest, previousStatus: QuestStatus) { if(quest.status.isUndoable && !previousStatus.isUndoable) { ++count } else if (!quest.status.isUndoable && previousStatus.isUndoable) { --count } } override fun onRemoved(questId: Long, previousStatus: QuestStatus) { if (previousStatus.isUndoable) { --count } } override fun onUpdated(added: Collection<OsmQuest>, updated: Collection<OsmQuest>, deleted: Collection<Long>) { count = osmQuestController.getAllUndoableCount() } } init { osmQuestController.addQuestStatusListener(questStatusListener) } /** Get the last undoable quest (includes answered, hidden and uploaded) */ fun getLastUndoable(): OsmQuest? = osmQuestController.getLastUndoable() fun addListener(listener: UndoableOsmQuestsCountListener) { listeners.add(listener) } fun removeListener(listener: UndoableOsmQuestsCountListener) { listeners.remove(listener) } private fun onUpdate(diff: Int) { if (diff > 0) listeners.forEach { it.onUndoableOsmQuestsCountIncreased() } else if (diff < 0) listeners.forEach { it.onUndoableOsmQuestsCountDecreased() } } } interface UndoableOsmQuestsCountListener { fun onUndoableOsmQuestsCountIncreased() fun onUndoableOsmQuestsCountDecreased() } private val QuestStatus.isUndoable: Boolean get() = when(this) { QuestStatus.ANSWERED, QuestStatus.HIDDEN, QuestStatus.CLOSED -> true else -> false }
gpl-3.0
7a00942fcf4b1fee5635b000636dd97b
36.333333
119
0.701679
4.817556
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/catalog/ui/adapter/delegate/SimpleCourseListDefaultAdapterDelegate.kt
2
2246
package org.stepik.android.view.catalog.ui.adapter.delegate import android.view.View import android.view.ViewGroup import androidx.appcompat.content.res.AppCompatResources import androidx.core.view.ViewCompat import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.item_simple_course_list_default.* import org.stepic.droid.R import org.stepik.android.domain.catalog.model.CatalogCourseList import org.stepik.android.view.catalog.mapper.CourseCountMapper import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder class SimpleCourseListDefaultAdapterDelegate( private val courseCountMapper: CourseCountMapper, private val onCourseListClicked: (CatalogCourseList) -> Unit ) : AdapterDelegate<CatalogCourseList, DelegateViewHolder<CatalogCourseList>>() { override fun isForViewType(position: Int, data: CatalogCourseList): Boolean = true override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CatalogCourseList> = ViewHolder(createView(parent, R.layout.item_simple_course_list_default)) private inner class ViewHolder( override val containerView: View ) : DelegateViewHolder<CatalogCourseList>(containerView), LayoutContainer { private val colorSchemes = listOf( R.color.color_overlay_green, R.color.color_overlay_yellow, R.color.color_overlay_blue, R.color.color_overlay_violet ).map { AppCompatResources.getColorStateList(context, it) } init { containerView.setOnClickListener { onCourseListClicked(itemData ?: return@setOnClickListener) } } override fun onBind(data: CatalogCourseList) { simpleCourseListTitle.text = data.title simpleCourseListCount.text = courseCountMapper.mapCourseCountToString(context, data.coursesCount) val colorList = colorSchemes[adapterPosition % colorSchemes.size] simpleCourseListTitle.setTextColor(colorList) simpleCourseListCount.setTextColor(colorList) ViewCompat.setBackgroundTintList(itemView, colorList) } } }
apache-2.0
fc8e7ad0c01ac327a5abf515895755bb
41.396226
107
0.738646
4.980044
false
false
false
false
PlateStack/PlateAPI
src/main/kotlin/org/platestack/api/plugin/Relation.kt
1
1669
/* * Copyright (C) 2017 José Roberto de Araújo Júnior * * 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.platestack.api.plugin import org.platestack.api.plugin.version.VersionRange import org.platestack.structure.immutable.ImmutableList import org.platestack.structure.immutable.toImmutableList data class Relation(val type: RelationType, val id: String, val namespace: String, val versions: ImmutableList<VersionRange>) { constructor(type: RelationType, id: String, namespace: String, versions: Iterable<VersionRange>): this(type, id, namespace, versions.toImmutableList()) init { if(versions.isEmpty()) error("versions can't be empty.") //TODO Add support for empty version range } companion object { @JvmStatic fun from(annotation: org.platestack.api.plugin.annotation.Relation) = Relation(annotation.type, annotation.id.value, annotation.id.namespace, annotation.versions.map { VersionRange.from(it) }) } operator fun contains(metadata: PlateMetadata) = namespace == "plate" && id == metadata.id && versions.any { metadata.version in it } }
apache-2.0
a712533a45d4b9ba92f8ae3a46e91493
42.842105
155
0.72569
4.196474
false
true
false
false
zlyne0/colonization
core/src/net/sf/freecol/common/model/ai/missions/scout/ScoutMission.kt
1
3822
package net.sf.freecol.common.model.ai.missions.scout import net.sf.freecol.common.model.Game import net.sf.freecol.common.model.Tile import net.sf.freecol.common.model.Unit import net.sf.freecol.common.model.ai.missions.AbstractMission import net.sf.freecol.common.model.ai.missions.PlayerMissionsContainer import net.sf.freecol.common.model.ai.missions.TransportUnitMission import net.sf.freecol.common.model.ai.missions.UnitMissionsMapping import promitech.colonization.ai.CommonMissionHandler import promitech.colonization.savegame.XmlNodeAttributes import promitech.colonization.savegame.XmlNodeAttributesWriter class ScoutMission : AbstractMission { public enum class Phase { SCOUT, WAIT_FOR_TRANSPORT, NOTHING } val scout : Unit var phase: Phase = Phase.SCOUT private set // scout destination used only for other island var scoutDistantDestination: Tile? = null private set constructor(scout: Unit) : super(Game.idGenerator.nextId(ScoutMission::class.java)) { this.scout = scout } private constructor(scout: Unit, missionId: String) : super(missionId) { this.scout = scout } override fun toString(): String { return "scout: " + scout.id + ", phase: " + phase } override fun blockUnits(unitMissionsMapping: UnitMissionsMapping) { unitMissionsMapping.blockUnit(scout, this) } override fun unblockUnits(unitMissionsMapping: UnitMissionsMapping) { unitMissionsMapping.unblockUnitFromMission(scout, this) } fun isScoutExists(): Boolean { return CommonMissionHandler.isUnitExists(scout.owner, scout) } fun waitForTransport(scoutDistantDestination: Tile) { this.phase = ScoutMission.Phase.WAIT_FOR_TRANSPORT this.scoutDistantDestination = scoutDistantDestination } fun isWaitingForTransport(): Boolean { return this.phase == ScoutMission.Phase.WAIT_FOR_TRANSPORT } fun isScoutReadyToEmbark(embarkLocation: Tile): Boolean { val scoutLocation = scout.tile return scoutLocation.equalsCoordinates(embarkLocation) || scoutLocation.isStepNextTo(embarkLocation) } fun startScoutAfterTransport(game: Game) { if (game.map.isTheSameArea(scoutDistantDestination, scout.tile)) { phase = ScoutMission.Phase.SCOUT scoutDistantDestination = null } } fun setDoNothing() { phase = Phase.NOTHING } class Xml : AbstractMission.Xml<ScoutMission>() { private val ATTR_UNIT = "unit" private val ATTR_PHASE = "phase" private val ATTR_DESTINATION = "dest" override fun startElement(attr: XmlNodeAttributes) { val scout = PlayerMissionsContainer.Xml.getPlayerUnit(attr.getStrAttribute(ATTR_UNIT)) nodeObject = ScoutMission(scout, attr.id) nodeObject.phase = attr.getEnumAttribute(Phase::class.java, ATTR_PHASE) if (attr.hasAttr(ATTR_DESTINATION)) { nodeObject.scoutDistantDestination = game.map.getSafeTile(attr.getPoint(ATTR_DESTINATION)) } super.startElement(attr) } override fun startWriteAttr(mission: ScoutMission, attr: XmlNodeAttributesWriter) { super.startWriteAttr(mission, attr) attr.setId(mission) attr.set(ATTR_UNIT, mission.scout) attr.set(ATTR_PHASE, mission.phase) mission.scoutDistantDestination?.let { tile -> attr.setPoint(ATTR_DESTINATION, tile.x, tile.y) } } override fun getTagName(): String { return tagName() } companion object { @JvmStatic fun tagName(): String { return "scoutMission" } } } }
gpl-2.0
937a0e000f2a418c0df0c73cb5f7858a
32.535088
108
0.674254
4.338252
false
false
false
false
apollostack/apollo-android
apollo-runtime/src/main/java/com/apollographql/apollo3/internal/subscription/RealSubscriptionManager.kt
1
17888
package com.apollographql.apollo3.internal.subscription import com.apollographql.apollo3.api.ResponseAdapterCache import com.apollographql.apollo3.api.Operation import com.apollographql.apollo3.api.ApolloResponse import com.apollographql.apollo3.api.Subscription import com.apollographql.apollo3.api.internal.MapResponseParser import com.apollographql.apollo3.cache.normalized.CacheKeyResolver import com.apollographql.apollo3.exception.ApolloNetworkException import com.apollographql.apollo3.subscription.OnSubscriptionManagerStateChangeListener import com.apollographql.apollo3.subscription.OperationClientMessage import com.apollographql.apollo3.subscription.OperationServerMessage import com.apollographql.apollo3.subscription.SubscriptionConnectionParamsProvider import com.apollographql.apollo3.subscription.SubscriptionManagerState import com.apollographql.apollo3.subscription.SubscriptionTransport import java.util.ArrayList import java.util.LinkedHashMap import java.util.Timer import java.util.TimerTask import java.util.UUID import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.Executor import java.util.concurrent.TimeUnit class RealSubscriptionManager(private val responseAdapterCache: ResponseAdapterCache, transportFactory: SubscriptionTransport.Factory, private val connectionParams: SubscriptionConnectionParamsProvider, private val dispatcher: Executor, private val connectionHeartbeatTimeoutMs: Long, private val cacheKeyResolver: CacheKeyResolver, private val autoPersistSubscription: Boolean ) : SubscriptionManager { @JvmField var subscriptions: MutableMap<UUID, SubscriptionRecord> = LinkedHashMap() @Volatile override var state: SubscriptionManagerState = SubscriptionManagerState.DISCONNECTED val timer = AutoReleaseTimer() private val transport: SubscriptionTransport = transportFactory.create(SubscriptionTransportCallback(this, dispatcher)) private val connectionAcknowledgeTimeoutTimerTask = Runnable { onConnectionAcknowledgeTimeout() } private val inactivityTimeoutTimerTask = Runnable { onInactivityTimeout() } private val connectionHeartbeatTimeoutTimerTask = Runnable { onConnectionHeartbeatTimeout() } private val onStateChangeListeners: MutableList<OnSubscriptionManagerStateChangeListener> = CopyOnWriteArrayList() override fun <D : Subscription.Data> subscribe(subscription: Subscription<D>, callback: SubscriptionManager.Callback<D>) { dispatcher.execute { doSubscribe(subscription, callback) } } override fun unsubscribe(subscription: Subscription<*>) { dispatcher.execute { doUnsubscribe(subscription) } } /** * Set the [RealSubscriptionManager] to a connectible state. It is safe to call this method * at any time. Does nothing unless we are in the stopped state. */ override fun start() { var oldState: SubscriptionManagerState synchronized(this) { oldState = state if (state == SubscriptionManagerState.STOPPED) { state = SubscriptionManagerState.DISCONNECTED } } notifyStateChanged(oldState, state) } /** * Unsubscribe from all active subscriptions, and disconnect the web socket. It will not be * possible to add new subscriptions while the [SubscriptionManager] is stopping * because we check the state in [.doSubscribe]. We pass true to * [.disconnect] because we want to disconnect even if, somehow, a new subscription * is added while or after we are doing the [.doUnsubscribe] loop. */ override fun stop() { dispatcher.execute { doStop() } } override fun addOnStateChangeListener(onStateChangeListener: OnSubscriptionManagerStateChangeListener) { onStateChangeListeners.add(onStateChangeListener) } override fun removeOnStateChangeListener(onStateChangeListener: OnSubscriptionManagerStateChangeListener) { onStateChangeListeners.remove(onStateChangeListener) } fun doSubscribe(subscription: Subscription<*>, callback: SubscriptionManager.Callback<*>) { var oldState: SubscriptionManagerState synchronized(this) { oldState = state if (state != SubscriptionManagerState.STOPPING && state != SubscriptionManagerState.STOPPED) { timer.cancelTask(INACTIVITY_TIMEOUT_TIMER_TASK_ID) val subscriptionId = UUID.randomUUID() subscriptions[subscriptionId] = SubscriptionRecord(subscriptionId, subscription as Subscription<Subscription.Data>, callback as SubscriptionManager.Callback<Subscription.Data>) if (state == SubscriptionManagerState.DISCONNECTED) { state = SubscriptionManagerState.CONNECTING transport.connect() } else if (state == SubscriptionManagerState.ACTIVE) { transport.send( OperationClientMessage.Start(subscriptionId.toString(), subscription, responseAdapterCache, autoPersistSubscription, false) ) } } } if (oldState == SubscriptionManagerState.STOPPING || oldState == SubscriptionManagerState.STOPPED) { callback.onError(ApolloSubscriptionException( "Illegal state: " + state.name + " for subscriptions to be created." + " SubscriptionManager.start() must be called to re-enable subscriptions.")) } else if (oldState == SubscriptionManagerState.CONNECTED) { callback.onConnected() } notifyStateChanged(oldState, state) } fun doUnsubscribe(subscription: Subscription<*>) { synchronized(this) { var subscriptionRecord: SubscriptionRecord? = null for (record in subscriptions.values) { if (record.subscription === subscription) { subscriptionRecord = record } } if (subscriptionRecord != null) { subscriptions.remove(subscriptionRecord.id) if (state == SubscriptionManagerState.ACTIVE || state == SubscriptionManagerState.STOPPING) { transport.send(OperationClientMessage.Stop(subscriptionRecord.id.toString())) } } if (subscriptions.isEmpty() && state != SubscriptionManagerState.STOPPING) { startInactivityTimer() } } } fun doStop() { var subscriptionRecords: Collection<SubscriptionRecord> var oldState: SubscriptionManagerState synchronized(this) { oldState = state state = SubscriptionManagerState.STOPPING subscriptionRecords = subscriptions.values if (oldState == SubscriptionManagerState.ACTIVE) { for (subscriptionRecord in subscriptionRecords) { transport.send(OperationClientMessage.Stop(subscriptionRecord.id.toString())) } } state = SubscriptionManagerState.STOPPED transport.disconnect(OperationClientMessage.Terminate()) subscriptions = LinkedHashMap() } for (record in subscriptionRecords) { record.notifyOnCompleted() } notifyStateChanged(oldState, SubscriptionManagerState.STOPPING) notifyStateChanged(SubscriptionManagerState.STOPPING, state) } fun onTransportConnected() { val subscriptionRecords: MutableCollection<SubscriptionRecord> = ArrayList() var oldState: SubscriptionManagerState synchronized(this) { oldState = state if (state == SubscriptionManagerState.CONNECTING) { subscriptionRecords.addAll(subscriptions.values) state = SubscriptionManagerState.CONNECTED transport.send(OperationClientMessage.Init(connectionParams.provide())) } if (state == SubscriptionManagerState.CONNECTED) { timer.schedule(CONNECTION_ACKNOWLEDGE_TIMEOUT_TIMER_TASK_ID, connectionAcknowledgeTimeoutTimerTask, CONNECTION_ACKNOWLEDGE_TIMEOUT) } } for (record in subscriptionRecords) { record.callback.onConnected() } notifyStateChanged(oldState, state) } fun onConnectionAcknowledgeTimeout() { timer.cancelTask(CONNECTION_ACKNOWLEDGE_TIMEOUT_TIMER_TASK_ID) dispatcher.execute { onTransportFailure(ApolloNetworkException("Subscription server is not responding")) } } fun onInactivityTimeout() { timer.cancelTask(INACTIVITY_TIMEOUT_TIMER_TASK_ID) dispatcher.execute { disconnect(false) } } fun onTransportFailure(t: Throwable?) { val subscriptionRecords = disconnect(true) for (record in subscriptionRecords) { record.notifyOnNetworkError(t) } } fun onOperationServerMessage(message: OperationServerMessage?) { when (message) { is OperationServerMessage.ConnectionAcknowledge -> { onConnectionAcknowledgeServerMessage() } is OperationServerMessage.Data -> { onOperationDataServerMessage(message) } is OperationServerMessage.Error -> { onErrorServerMessage(message) } is OperationServerMessage.Complete -> { onCompleteServerMessage(message) } is OperationServerMessage.ConnectionError -> { disconnect(true) } is OperationServerMessage.ConnectionKeepAlive -> { resetConnectionKeepAliveTimerTask() } } } /** * Disconnect the web socket and update the state. If we are stopping, set the state to * [State.STOPPED] so that new subscription requests will **not** automatically re-open * the web socket. If we are not stopping, set the state to [State.DISCONNECTED] so that * new subscription requests **will** automatically re-open the web socket. * * @param force if true, always disconnect web socket, regardless of the status of [.subscriptions] */ fun disconnect(force: Boolean): Collection<SubscriptionRecord> { var oldState: SubscriptionManagerState var subscriptionRecords: Collection<SubscriptionRecord> synchronized(this) { oldState = state subscriptionRecords = subscriptions.values if (force || subscriptions.isEmpty()) { transport.disconnect(OperationClientMessage.Terminate()) state = if (state == SubscriptionManagerState.STOPPING) SubscriptionManagerState.STOPPED else SubscriptionManagerState.DISCONNECTED subscriptions = LinkedHashMap() } } notifyStateChanged(oldState, state) return subscriptionRecords } override fun reconnect() { var oldState: SubscriptionManagerState synchronized(this) { oldState = state state = SubscriptionManagerState.DISCONNECTED transport.disconnect(OperationClientMessage.Terminate()) state = SubscriptionManagerState.CONNECTING transport.connect() } notifyStateChanged(oldState, SubscriptionManagerState.DISCONNECTED) notifyStateChanged(SubscriptionManagerState.DISCONNECTED, SubscriptionManagerState.CONNECTING) } fun onConnectionHeartbeatTimeout() { reconnect() } fun onConnectionClosed() { var subscriptionRecords: Collection<SubscriptionRecord> var oldState: SubscriptionManagerState synchronized(this) { oldState = state subscriptionRecords = subscriptions.values state = SubscriptionManagerState.DISCONNECTED subscriptions = LinkedHashMap() } for (record in subscriptionRecords) { record.callback.onTerminated() } notifyStateChanged(oldState, state) } private fun resetConnectionKeepAliveTimerTask() { if (connectionHeartbeatTimeoutMs <= 0) { return } synchronized(this) { timer.schedule(CONNECTION_KEEP_ALIVE_TIMEOUT_TIMER_TASK_ID, connectionHeartbeatTimeoutTimerTask, connectionHeartbeatTimeoutMs) } } private fun startInactivityTimer() { timer.schedule(INACTIVITY_TIMEOUT_TIMER_TASK_ID, inactivityTimeoutTimerTask, INACTIVITY_TIMEOUT) } private fun onOperationDataServerMessage(message: OperationServerMessage.Data) { val subscriptionId = message.id ?: "" var subscriptionRecord: SubscriptionRecord? synchronized(this) { subscriptionRecord = try { subscriptions[UUID.fromString(subscriptionId)] } catch (e: IllegalArgumentException) { null } } if (subscriptionRecord != null) { val subscription = subscriptionRecord!!.subscription try { val response = MapResponseParser.parse(message.payload, subscription, responseAdapterCache) subscriptionRecord!!.notifyOnResponse(response) } catch (e: Exception) { subscriptionRecord = removeSubscriptionById(subscriptionId) if (subscriptionRecord != null) { subscriptionRecord!!.notifyOnError(ApolloSubscriptionException("Failed to parse server message", e)) } return } } } private fun onConnectionAcknowledgeServerMessage() { var oldState: SubscriptionManagerState synchronized(this) { oldState = state timer.cancelTask(CONNECTION_ACKNOWLEDGE_TIMEOUT_TIMER_TASK_ID) if (state == SubscriptionManagerState.CONNECTED) { state = SubscriptionManagerState.ACTIVE for (subscriptionRecord in subscriptions.values) { transport.send( OperationClientMessage.Start(subscriptionRecord.id.toString(), subscriptionRecord.subscription, responseAdapterCache, autoPersistSubscription, false) ) } } } notifyStateChanged(oldState, state) } private fun onErrorServerMessage(message: OperationServerMessage.Error) { val subscriptionId = message.id ?: "" val subscriptionRecord = removeSubscriptionById(subscriptionId) val resendSubscriptionWithDocument: Boolean resendSubscriptionWithDocument = if (autoPersistSubscription) { val error = MapResponseParser.parseError(message.payload) (PROTOCOL_NEGOTIATION_ERROR_NOT_FOUND.equals(error.message, ignoreCase = true) || PROTOCOL_NEGOTIATION_ERROR_NOT_SUPPORTED.equals(error.message, ignoreCase = true)) } else { false } if (resendSubscriptionWithDocument) { synchronized(this) { subscriptions[subscriptionRecord.id] = subscriptionRecord transport.send(OperationClientMessage.Start( subscriptionRecord.id.toString(), subscriptionRecord.subscription, responseAdapterCache, true, true )) } } else { subscriptionRecord.notifyOnError(ApolloSubscriptionServerException(message.payload)) } } private fun onCompleteServerMessage(message: OperationServerMessage.Complete) { val subscriptionId = message.id ?: "" val subscriptionRecord = removeSubscriptionById(subscriptionId) subscriptionRecord.notifyOnCompleted() } private fun removeSubscriptionById(subscriptionId: String?): SubscriptionRecord { var subscriptionRecord: SubscriptionRecord? synchronized(this) { subscriptionRecord = try { subscriptions.remove(UUID.fromString(subscriptionId)) } catch (e: IllegalArgumentException) { null } if (subscriptions.isEmpty()) { startInactivityTimer() } } return subscriptionRecord!! } private fun notifyStateChanged(oldState: SubscriptionManagerState, newState: SubscriptionManagerState) { if (oldState == newState) { return } for (onStateChangeListener in onStateChangeListeners) { onStateChangeListener.onStateChange(oldState, newState) } } class SubscriptionRecord internal constructor(val id: UUID, val subscription: Subscription<Subscription.Data>, val callback: SubscriptionManager.Callback<Subscription.Data>) { fun notifyOnResponse(response: ApolloResponse<*>?) { callback.onResponse(SubscriptionResponse(subscription, response as ApolloResponse<Subscription.Data>)) } fun notifyOnError(error: ApolloSubscriptionException?) { callback.onError(error!!) } fun notifyOnNetworkError(t: Throwable?) { callback.onNetworkError(t!!) } fun notifyOnCompleted() { callback.onCompleted() } } private class SubscriptionTransportCallback(private val delegate: RealSubscriptionManager, private val dispatcher: Executor) : SubscriptionTransport.Callback { override fun onConnected() { dispatcher.execute { delegate.onTransportConnected() } } override fun onFailure(t: Throwable) { dispatcher.execute { delegate.onTransportFailure(t) } } override fun onMessage(message: OperationServerMessage) { dispatcher.execute { delegate.onOperationServerMessage(message) } } override fun onClosed() { dispatcher.execute { delegate.onConnectionClosed() } } } class AutoReleaseTimer { val tasks: MutableMap<Int, TimerTask> = LinkedHashMap() var timer: Timer? = null fun schedule(taskId: Int, task: Runnable, delay: Long) { val timerTask: TimerTask = object : TimerTask() { override fun run() { try { task.run() } finally { cancelTask(taskId) } } } synchronized(this) { val previousTimerTask = tasks.put(taskId, timerTask) previousTimerTask?.cancel() if (timer == null) { timer = Timer("Subscription SmartTimer", true) } timer!!.schedule(timerTask, delay) } } fun cancelTask(taskId: Int) { synchronized(this) { val timerTask = tasks.remove(taskId) timerTask?.cancel() if (tasks.isEmpty() && timer != null) { timer!!.cancel() timer = null } } } } companion object { const val CONNECTION_ACKNOWLEDGE_TIMEOUT_TIMER_TASK_ID = 1 const val INACTIVITY_TIMEOUT_TIMER_TASK_ID = 2 const val CONNECTION_KEEP_ALIVE_TIMEOUT_TIMER_TASK_ID = 3 val CONNECTION_ACKNOWLEDGE_TIMEOUT = TimeUnit.SECONDS.toMillis(5) val INACTIVITY_TIMEOUT = TimeUnit.SECONDS.toMillis(10) const val PROTOCOL_NEGOTIATION_ERROR_NOT_FOUND = "PersistedQueryNotFound" const val PROTOCOL_NEGOTIATION_ERROR_NOT_SUPPORTED = "PersistedQueryNotSupported" } }
mit
d52c54582b470eaec7ed00cbb2558d3c
37.637149
184
0.720651
5.166956
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/presentation/more/settings/widget/AppThemePreferenceWidget.kt
1
9153
package eu.kanade.presentation.more.settings.widget import android.content.res.Configuration.UI_MODE_NIGHT_YES import androidx.compose.animation.animateContentSize import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxHeight 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.width import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip 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 eu.kanade.domain.ui.model.AppTheme import eu.kanade.presentation.components.DIVIDER_ALPHA import eu.kanade.presentation.components.MangaCover import eu.kanade.presentation.theme.TachiyomiTheme import eu.kanade.presentation.util.secondaryItemAlpha import eu.kanade.tachiyomi.util.system.DeviceUtil import eu.kanade.tachiyomi.util.system.isDynamicColorAvailable @Composable internal fun AppThemePreferenceWidget( title: String, value: AppTheme, amoled: Boolean, onItemClick: (AppTheme) -> Unit, ) { BasePreferenceWidget( title = title, subcomponent = { AppThemesList( currentTheme = value, amoled = amoled, onItemClick = onItemClick, ) }, ) } @Composable private fun AppThemesList( currentTheme: AppTheme, amoled: Boolean, onItemClick: (AppTheme) -> Unit, ) { val appThemes = remember { AppTheme.values() .filterNot { it.titleResId == null || (it == AppTheme.MONET && !DeviceUtil.isDynamicColorAvailable) } } LazyRow( modifier = Modifier .animateContentSize() .padding(vertical = 8.dp), contentPadding = PaddingValues(horizontal = PrefsHorizontalPadding), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { items( items = appThemes, key = { it.name }, ) { appTheme -> Column( modifier = Modifier .width(114.dp) .padding(top = 8.dp), ) { TachiyomiTheme( appTheme = appTheme, amoled = amoled, ) { AppThemePreviewItem( selected = currentTheme == appTheme, onClick = { onItemClick(appTheme) }, ) } Text( text = stringResource(appTheme.titleResId!!), modifier = Modifier .fillMaxWidth() .padding(top = 8.dp) .secondaryItemAlpha(), color = MaterialTheme.colorScheme.onSurface, textAlign = TextAlign.Center, maxLines = 2, style = MaterialTheme.typography.bodyMedium, ) } } } } @Composable fun AppThemePreviewItem( selected: Boolean, onClick: () -> Unit, ) { val dividerColor = MaterialTheme.colorScheme.onSurface.copy(alpha = DIVIDER_ALPHA) Column( modifier = Modifier .fillMaxWidth() .aspectRatio(9f / 16f) .border( width = 4.dp, color = if (selected) { MaterialTheme.colorScheme.primary } else { dividerColor }, shape = RoundedCornerShape(17.dp), ) .padding(4.dp) .clip(RoundedCornerShape(13.dp)) .background(MaterialTheme.colorScheme.background) .clickable(onClick = onClick), ) { // App Bar Row( modifier = Modifier .fillMaxWidth() .height(40.dp) .padding(8.dp), verticalAlignment = Alignment.CenterVertically, ) { Box( modifier = Modifier .fillMaxHeight(0.8f) .weight(0.7f) .padding(end = 4.dp) .background( color = MaterialTheme.colorScheme.onSurface, shape = RoundedCornerShape(9.dp), ), ) Box( modifier = Modifier.weight(0.3f), contentAlignment = Alignment.CenterEnd, ) { if (selected) { Icon( imageVector = Icons.Default.CheckCircle, contentDescription = null, tint = MaterialTheme.colorScheme.primary, ) } } } // Cover Box( modifier = Modifier .padding(start = 8.dp, top = 2.dp) .background( color = dividerColor, shape = RoundedCornerShape(9.dp), ) .fillMaxWidth(0.5f) .aspectRatio(MangaCover.Book.ratio), ) { Row( modifier = Modifier .padding(4.dp) .size(width = 24.dp, height = 16.dp) .clip(RoundedCornerShape(5.dp)), ) { Box( modifier = Modifier .fillMaxHeight() .width(12.dp) .background(MaterialTheme.colorScheme.tertiary), ) Box( modifier = Modifier .fillMaxHeight() .width(12.dp) .background(MaterialTheme.colorScheme.secondary), ) } } // Bottom bar Box( modifier = Modifier .fillMaxWidth() .weight(1f), contentAlignment = Alignment.BottomCenter, ) { Surface( tonalElevation = 3.dp, ) { Row( modifier = Modifier .height(32.dp) .fillMaxWidth() .background(MaterialTheme.colorScheme.surfaceVariant) .padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically, ) { Box( modifier = Modifier .size(17.dp) .background( color = MaterialTheme.colorScheme.primary, shape = CircleShape, ), ) Box( modifier = Modifier .padding(start = 8.dp) .alpha(0.6f) .height(17.dp) .weight(1f) .background( color = MaterialTheme.colorScheme.onSurface, shape = RoundedCornerShape(9.dp), ), ) } } } } } @Preview( name = "light", showBackground = true, ) @Preview( name = "dark", showBackground = true, uiMode = UI_MODE_NIGHT_YES, ) @Composable private fun AppThemesListPreview() { var appTheme by remember { mutableStateOf(AppTheme.DEFAULT) } TachiyomiTheme { AppThemesList( currentTheme = appTheme, amoled = false, onItemClick = { appTheme = it }, ) } }
apache-2.0
a031d5e9896baa9238677b5acfd3d134
32.527473
113
0.533923
5.327707
false
false
false
false
Heiner1/AndroidAPS
omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt
1
6218
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.BasalInsulinProgramElement import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util.ProgramBasalUtil import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util.ProgramTempBasalUtil import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ProgramReminder import java.nio.ByteBuffer import java.util.* // NOT SUPPORTED: percentage temp basal class ProgramTempBasalCommand private constructor( private val interlockCommand: ProgramInsulinCommand, uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, private val programReminder: ProgramReminder, insulinProgramElements: List<BasalInsulinProgramElement> ) : HeaderEnabledCommand(CommandType.PROGRAM_TEMP_BASAL, uniqueId, sequenceNumber, multiCommandFlag) { private val insulinProgramElements: List<BasalInsulinProgramElement> = ArrayList(insulinProgramElements) private fun getBodyLength(): Byte = (insulinProgramElements.size * 6 + 8).toByte() private fun getLength(): Short = (getBodyLength() + 2).toShort() class Builder : NonceEnabledCommandBuilder<Builder, ProgramTempBasalCommand>() { private var programReminder: ProgramReminder? = null private var rateInUnitsPerHour: Double? = null private var durationInMinutes: Short? = null fun setProgramReminder(programReminder: ProgramReminder): Builder { this.programReminder = programReminder return this } fun setRateInUnitsPerHour(rateInUnitsPerHour: Double): Builder { this.rateInUnitsPerHour = rateInUnitsPerHour return this } fun setDurationInMinutes(durationInMinutes: Short): Builder { require(durationInMinutes % 30 == 0) { "durationInMinutes must be dividable by 30" } this.durationInMinutes = durationInMinutes return this } override fun buildCommand(): ProgramTempBasalCommand { requireNotNull(programReminder) { "programReminder can not be null" } requireNotNull(rateInUnitsPerHour) { "rateInUnitsPerHour can not be null" } requireNotNull(durationInMinutes) { "durationInMinutes can not be null" } val durationInSlots = (durationInMinutes!! / 30).toByte() val pulsesPerSlot = ProgramTempBasalUtil.mapTempBasalToPulsesPerSlot(durationInSlots, rateInUnitsPerHour!!) val tenthPulsesPerSlot = ProgramTempBasalUtil.mapTempBasalToTenthPulsesPerSlot( durationInSlots.toInt(), rateInUnitsPerHour!! ) val shortInsulinProgramElements = ProgramTempBasalUtil.mapPulsesPerSlotToShortInsulinProgramElements( pulsesPerSlot ) val insulinProgramElements = ProgramTempBasalUtil.mapTenthPulsesPerSlotToLongInsulinProgramElements( tenthPulsesPerSlot ) val interlockCommand = ProgramInsulinCommand( uniqueId!!, sequenceNumber!!, multiCommandFlag, nonce!!, shortInsulinProgramElements, ProgramTempBasalUtil.calculateChecksum(durationInSlots, pulsesPerSlot[0], pulsesPerSlot), durationInSlots, 0x3840.toShort(), pulsesPerSlot[0], ProgramInsulinCommand.DeliveryType.TEMP_BASAL ) return ProgramTempBasalCommand( interlockCommand, uniqueId!!, sequenceNumber!!, multiCommandFlag, programReminder!!, insulinProgramElements ) } } override val encoded: ByteArray get() { val firstProgramElement = insulinProgramElements[0] val remainingTenthPulsesInFirstElement: Short val delayUntilNextTenthPulseInUsec: Int if (firstProgramElement.totalTenthPulses.toInt() == 0) { remainingTenthPulsesInFirstElement = firstProgramElement.numberOfSlots.toShort() delayUntilNextTenthPulseInUsec = ProgramBasalUtil.MAX_DELAY_BETWEEN_TENTH_PULSES_IN_USEC_AND_USECS_IN_BASAL_SLOT } else { remainingTenthPulsesInFirstElement = firstProgramElement.totalTenthPulses delayUntilNextTenthPulseInUsec = (firstProgramElement.numberOfSlots.toLong() * 1800.0 / remainingTenthPulsesInFirstElement * 1000000).toInt() } val buffer = ByteBuffer.allocate(getLength().toInt()) .put(commandType.value) .put(getBodyLength()) .put(programReminder.encoded) .put(0x00.toByte()) // Current slot index .putShort(remainingTenthPulsesInFirstElement) .putInt(delayUntilNextTenthPulseInUsec) for (element in insulinProgramElements) { buffer.put(element.encoded) } val tempBasalCommand = buffer.array() val interlockCommand = interlockCommand.encoded val header: ByteArray = encodeHeader( uniqueId, sequenceNumber, (tempBasalCommand.size + interlockCommand.size).toShort(), multiCommandFlag ) return appendCrc( ByteBuffer.allocate(header.size + interlockCommand.size + tempBasalCommand.size) .put(header) .put(interlockCommand) .put(tempBasalCommand) .array() ) } }
agpl-3.0
41b658339268ee30857116d84b7fa898
46.106061
128
0.66404
5.160166
false
false
false
false
Adventech/sabbath-school-android-2
common/design-compose/src/main/kotlin/app/ss/design/compose/widget/icon/ResIcon.kt
1
1911
/* * Copyright (c) 2022. Adventech <[email protected]> * * 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 app.ss.design.compose.widget.icon import androidx.annotation.DrawableRes import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource /** * An [IconSlot] from a [DrawableRes] */ @Immutable data class ResIcon( @DrawableRes val res: Int, val contentDescription: String? ) : IconSlot { @Composable override fun Content(contentColor: Color, modifier: Modifier) { Icon( painter = painterResource(id = res), contentDescription = contentDescription, tint = contentColor, modifier = modifier ) } }
mit
5a492c20b12042accc998fe817b48c49
36.470588
80
0.741497
4.496471
false
false
false
false
YsnKsy/react-native-geth
android/src/main/java/com/reactnativegeth/GethModule.kt
1
29087
package com.reactnativegeth import androidx.annotation.Nullable import com.facebook.react.bridge.* import com.facebook.react.bridge.Arguments.createArray import com.facebook.react.bridge.Arguments.createMap import com.facebook.react.modules.core.DeviceEventManagerModule import org.ethereum.geth.* class GethModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { private val ctx: ReactApplicationContext = reactContext private val dir: String = StringBuilder().append(reactApplicationContext.filesDir).append("/keystore").toString() private val ks: KeyStore = Geth.newKeyStore(dir, Geth.LightScryptN, Geth.LightScryptP) private val ctxEth: Context = Geth.newContext() private lateinit var eth: EthereumClient private lateinit var node: Node private lateinit var newHeadSubscription: Subscription private lateinit var filterLogsSubscription: Subscription private val newHeadHandler: NewHeadHandler = object : NewHeadHandler { override fun onError(e: String) { val res = createMap().also { it.putString("error", e) it.putNull("header") } sendEvent("onNewHead", res) } override fun onNewHead(header: Header) { val res = createMap().also { it.putString("header", header.encodeJSON()) it.putNull("error") } sendEvent("onNewHead", res) } } private val filterLogsHandler: FilterLogsHandler = object : FilterLogsHandler { override fun onError(e: String) { val res = createMap().also { it.putString("error", e) it.putNull("log") } sendEvent("onFilterLogs", res) } override fun onFilterLogs(log: Log?) { val res = createMap().also { it.putMap("log", log.toReadableMap()) it.putNull("error") } sendEvent("onFilterLogs", res) } } override fun getName(): String { return "Geth" } // KeyStore @ReactMethod fun newAccount(passphrase: String, promise: Promise) { val acc: Account try { acc = ks.newAccount(passphrase) promise.resolve(acc.toReadableMap()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getAccount(index: Int, promise: Promise) { try { val acc: Account = ks.accounts.get(index.toLong()) promise.resolve(acc.toReadableMap()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getAccounts(promise: Promise) { val size: Long = ks.accounts.size() val accounts: WritableArray = createArray() try { repeat(size.toInt()) { index -> val acc: Account = ks.accounts.get(index.toLong()) accounts.pushMap(acc.toReadableMap()) } promise.resolve(accounts) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun exportKey(index: Int, passphrase: String, newPassphrase: String, promise: Promise) { try { val acc: Account = ks.accounts.get(index.toLong()) val key: ByteArray = ks.exportKey(acc, passphrase, newPassphrase) promise.resolve(Geth.encodeToHex(key)) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun importKey(hexKey: String, passphrase: String, newPassphrase: String, promise: Promise) { try { val key: ByteArray = Geth.decodeFromHex(hexKey) val acc: Account = ks.importKey(key, passphrase, newPassphrase) promise.resolve(acc.toReadableMap()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun importECDSAKey(hexKey: String, passphrase: String, promise: Promise) { try { val key: ByteArray = Geth.decodeFromHex(hexKey) val acc: Account = ks.importECDSAKey(key, passphrase) promise.resolve(acc.toReadableMap()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun importPreSaleKey(hexKey: String, passphrase: String, promise: Promise) { try { val key: ByteArray = Geth.decodeFromHex(hexKey) val acc: Account = ks.importPreSaleKey(key, passphrase) promise.resolve(acc.toReadableMap()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun hasAddress(address: String, promise: Promise) { val hasAddress: Boolean = ks.hasAddress(Geth.newAddressFromHex(address)) promise.resolve(hasAddress) } @ReactMethod fun deleteAccount(address: String, passphrase: String, promise: Promise) { try { val account: Account = getAccount(address) val add: Address = Geth.newAddressFromHex(address) if (account.address === add) { ks.deleteAccount(account, passphrase) promise.resolve(true) } else { promise.resolve(false) } } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun lock(address: String, promise: Promise) { try { ks.lock(Geth.newAddressFromHex(address)) promise.resolve(true) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun signHash(address: String, hash: String, promise: Promise) { try { val add: Address = Geth.newAddressFromHex(address) val hsh: Hash = Geth.newHashFromHex(hash) val signBta: ByteArray = ks.signHash(add, hsh.bytes) val sign: String = Geth.encodeToHex(signBta) promise.resolve(sign) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun signHashPassphrase(address: String, passphrase: String, hash: String, promise: Promise) { try { val account: Account = getAccount(address) val add: Address = Geth.newAddressFromHex(address) if (account.address === add) { val hsh: Hash = Geth.newHashFromHex(hash) val signBta: ByteArray = ks.signHashPassphrase(account, passphrase, hsh.bytes) val sign: String = Geth.encodeToHex(signBta) promise.resolve(sign) } else { promise.resolve(false) } } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun signTx(address: String, tx: String, chainID: Int, promise: Promise) { try { val account: Account = getAccount(address) val add: Address = Geth.newAddressFromHex(address) if (account.address === add) { val txBta: ByteArray = Geth.decodeFromHex(tx) val uSignTx: Transaction = Geth.newTransactionFromRLP(txBta) val chain: BigInt = Geth.newBigInt(chainID.toLong()) val signTx: Transaction = ks.signTx(account, uSignTx, chain) promise.resolve(signTx.encodeJSON()) } else { promise.resolve(false) } } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun signTxPassphrase(address: String, passphrase: String, tx: String, chainID: Int, promise: Promise) { try { val account: Account = getAccount(address) val add: Address = Geth.newAddressFromHex(address) if (account.address === add) { val txBta: ByteArray = Geth.decodeFromHex(tx) val uSignTx: Transaction = Geth.newTransactionFromRLP(txBta) val chain: BigInt = Geth.newBigInt(chainID.toLong()) val signTx: Transaction = ks.signTxPassphrase(account, passphrase, uSignTx, chain) promise.resolve(signTx.encodeJSON()) } else { promise.resolve(false) } } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun timeUnlock(address: String, passphrase: String, timeout: Double, promise: Promise) { try { val account: Account = getAccount(address) val add: Address = Geth.newAddressFromHex(address) if (account.address === add) { ks.timedUnlock(account, passphrase, timeout.toLong()) promise.resolve(true) } else { promise.resolve(false) } } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun unlock(address: String, passphrase: String, promise: Promise) { try { val account: Account = getAccount(address) val add: Address = Geth.newAddressFromHex(address) if (account.address === add) { ks.unlock(account, passphrase) promise.resolve(true) } else { promise.resolve(false) } } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun updateAccount(address: String, passphrase: String, newPassphrase: String, promise: Promise) { try { val account: Account = getAccount(address) val add: Address = Geth.newAddressFromHex(address) if (account.address === add) { ks.updateAccount(account, passphrase, newPassphrase) promise.resolve(true) } else { promise.resolve(false) } } catch (e: Exception) { promise.reject(e.message, e.cause) } } // EthereumClient : provides access to the Ethereum APIs. @ReactMethod fun newEthereumClient(url: String, promise: Promise) { try { eth = Geth.newEthereumClient(url) promise.resolve(true) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getBalanceAt(address: String, number: Double, promise: Promise) { try { val account: Account = getAccount(address) val add: Address = Geth.newAddressFromHex(address) if (account.address === add) { val balance: BigInt = eth.getBalanceAt(ctxEth, account.address, number.toLong()) promise.resolve(balance.toString()) } else { promise.resolve(false) } } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getBlockByHash(hash: String, promise: Promise) { try { val hsh: Hash = Geth.newHashFromHex(hash) val block: Block = eth.getBlockByHash(ctxEth, hsh) promise.resolve(block.encodeJSON()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getBlockByNumber(number: Double, promise: Promise) { try { val block: Block = eth.getBlockByNumber(ctxEth, number.toLong()) promise.resolve(block.encodeJSON()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getCodeAt(address: String, number: Double, promise: Promise) { try { val account: Account = getAccount(address) val add: Address = Geth.newAddressFromHex(address) if (account.address === add) { val codeBta = eth.getCodeAt(ctxEth, account.address, number.toLong()) val code = Geth.encodeToHex(codeBta) promise.resolve(code) } else { promise.resolve(false) } } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getHeaderByHash(hash: String, promise: Promise) { try { val hsh: Hash = Geth.newHashFromHex(hash) val header: Header = eth.getHeaderByHash(ctxEth, hsh) promise.resolve(header.encodeJSON()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getHeaderByNumber(number: Double, promise: Promise) { try { val header: Header = eth.getHeaderByNumber(ctxEth, number.toLong()) promise.resolve(header.encodeJSON()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getNonceAt(address: String, number: Double, promise: Promise) { try { val account: Account = getAccount(address) val add: Address = Geth.newAddressFromHex(address) if (account.address === add) { val nonce: Long = eth.getNonceAt(ctxEth, account.address, number.toLong()) promise.resolve(nonce.toDouble()) } else { promise.resolve(false) } } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getPendingBalanceAt(address: String, promise: Promise) { try { val account: Account = getAccount(address) val add: Address = Geth.newAddressFromHex(address) if (account.address === add) { val balance: BigInt = eth.getPendingBalanceAt(ctxEth, account.address) promise.resolve(balance.toString()) } else { promise.resolve(false) } } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getPendingCodeAt(address: String, promise: Promise) { try { val account: Account = getAccount(address) val add: Address = Geth.newAddressFromHex(address) if (account.address === add) { val codeBta: ByteArray = eth.getPendingCodeAt(ctxEth, account.address) val code: String = Geth.encodeToHex(codeBta) promise.resolve(code) } else { promise.resolve(false) } } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getPendingNonceAt(address: String, promise: Promise) { try { val account: Account = getAccount(address) val add: Address = Geth.newAddressFromHex(address) if (account.address === add) { val nonce: Long = eth.getPendingNonceAt(ctxEth, account.address) promise.resolve(nonce.toDouble()) } else { promise.resolve(false) } } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getPendingStorageAt(address: String, hash: String, promise: Promise) { try { val account: Account = getAccount(address) val add: Address = Geth.newAddressFromHex(address) if (account.address === add) { val hsh: Hash = Geth.newHashFromHex(hash) val storageBta: ByteArray = eth.getPendingStorageAt(ctxEth, account.address, hsh) val storage: String = Geth.encodeToHex(storageBta) promise.resolve(storage) } else { promise.resolve(false) } } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getPendingTransactionCount(promise: Promise) { try { val count: Long = eth.getPendingTransactionCount(ctxEth) promise.resolve(count.toDouble()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getStorageAt(address: String, hash: String, number: Double, promise: Promise) { try { val account: Account = getAccount(address) val add: Address = Geth.newAddressFromHex(address) if (account.address === add) { val hsh: Hash = Geth.newHashFromHex(hash) val storageBta: ByteArray = eth.getStorageAt(ctxEth, account.address, hsh, number.toLong()) val storage: String = Geth.encodeToHex(storageBta) promise.resolve(storage) } else { promise.resolve(false) } } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getTransactionByHash(hash: String, promise: Promise) { try { val hsh: Hash = Geth.newHashFromHex(hash) val tx: Transaction = eth.getTransactionByHash(ctxEth, hsh) promise.resolve(tx.encodeJSON()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getTransactionCount(hash: String, promise: Promise) { try { val hsh: Hash = Geth.newHashFromHex(hash) val count: Long = eth.getTransactionCount(ctxEth, hsh) promise.resolve(count.toDouble()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getTransactionInBlock(hash: String, index: Double, promise: Promise) { try { val hsh: Hash = Geth.newHashFromHex(hash) val tx: Transaction = eth.getTransactionInBlock(ctxEth, hsh, index.toLong()) promise.resolve(tx.encodeJSON()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getTransactionReceipt(hash: String, promise: Promise) { try { val hsh: Hash = Geth.newHashFromHex(hash) val rcpt: Receipt = eth.getTransactionReceipt(ctxEth, hsh) promise.resolve(rcpt.encodeJSON()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun suggestGasPrice(promise: Promise) { try { val price: BigInt = eth.suggestGasPrice(ctxEth) promise.resolve(price.string()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun estimateGas(msg: WritableMap, promise: Promise) { try { val callMsg: CallMsg = msg.toCallMsg() val estimateGas: Long = eth.estimateGas(ctxEth, callMsg) promise.resolve(estimateGas.toDouble()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun getTransactionSender(hash: String, tx: String, index: Double, promise: Promise) { try { val hsh: Hash = Geth.newHashFromHex(hash) val txBta: ByteArray = Geth.decodeFromHex(tx) val uSignTx: Transaction = Geth.newTransactionFromRLP(txBta) val sender: Address = eth.getTransactionSender(ctxEth, uSignTx, hsh, index.toLong()) promise.resolve(sender.hex) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun pendingCallContract(msg: WritableMap, promise: Promise) { try { val callMsg: CallMsg = msg.toCallMsg() val output: ByteArray = eth.pendingCallContract(ctxEth, callMsg) promise.resolve(Geth.encodeToHex(output)) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun sendTransaction(tx: String, promise: Promise) { try { val txBta: ByteArray = Geth.decodeFromHex(tx) val uSignTx: Transaction = Geth.newTransactionFromRLP(txBta) eth.sendTransaction(ctxEth, uSignTx) promise.resolve(true) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun callContract(msg: WritableMap, number: Double, promise: Promise) { try { val callMsg: CallMsg = msg.toCallMsg() val output: ByteArray = eth.callContract(ctxEth, callMsg, number.toLong()) promise.resolve(Geth.encodeToHex(output)) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun syncProgress(promise: Promise) { try { val syncProgress: SyncProgress = eth.syncProgress(ctxEth) promise.resolve(syncProgress.toReadableMap()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun filterLogs(query: ReadableMap, promise: Promise) { try { val filterQuery: FilterQuery = query.toFilterQuery() val logs: Logs = eth.filterLogs(ctxEth, filterQuery) promise.resolve(logs.toReadableArray()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun subscribeNewHead(buffer: Double, promise: Promise) { try { newHeadSubscription = eth.subscribeNewHead(ctxEth, newHeadHandler, buffer.toLong()) promise.resolve(true) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun unsubscribeNewHead(promise: Promise) { try { newHeadSubscription.unsubscribe() promise.resolve(true) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun subscribeFilterLogs(query: ReadableMap, buffer: Double, promise: Promise) { try { filterLogsSubscription = eth.subscribeFilterLogs(ctxEth, query.toFilterQuery(), filterLogsHandler, buffer.toLong()) promise.resolve(true) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod fun unsubscribeFilterLogs(promise: Promise) { try { filterLogsSubscription.unsubscribe() promise.resolve(true) } catch (e: Exception) { promise.reject(e.message, e.cause) } } // Light Ethereum Node @ReactMethod private fun newNode(dir: String, config: ReadableMap, promise: Promise) { try { node = Geth.newNode(dir, config.toNodeConfig()) promise.resolve(true) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod private fun getNodeInfo(promise: Promise) { try { promise.resolve(node.nodeInfo.toReadableMap()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod private fun getPeersInfo(promise: Promise) { try { promise.resolve(node.peersInfo.toReadableMap()) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod private fun start(promise: Promise) { try { node.start() promise.resolve(true) } catch (e: Exception) { promise.reject(e.message, e.cause) } } @ReactMethod private fun stop(promise: Promise) { try { node.stop() promise.resolve(true) } catch (e: Exception) { promise.reject(e.message, e.cause) } } // Event Emitter private fun sendEvent(eventName: String, @Nullable params: Any) { ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java).emit(eventName, params) } private fun getAccount(address: String): Account { val add: Address = Geth.newAddressFromHex(address) val hasAddress: Boolean = ks.hasAddress(add) var account = Account() if (hasAddress) { val size: Long = ks.accounts.size() repeat(size.toInt()) { index -> val acc: Account = ks.accounts.get(index.toLong()) if (acc.address === add) { account = acc return account } } } return account } // Cast method's private fun Account?.toReadableMap(): ReadableMap { return createMap().also { it.putString("address", this?.address?.string()) it.putString("url", this?.url) } } private fun Hashes?.toReadableArray(): ReadableArray { return createArray().also { val size: Long? = this?.size() if (size != null) { repeat(size.toInt()) { index -> val hash: Hash? = this?.get(index.toLong()) it.pushString(hash?.hex) } } } } private fun Log?.toReadableMap(): ReadableMap { return createMap().also { it.putString("address", this?.address?.hex) it.putString("blockHash", this?.blockHash?.hex) this?.blockNumber?.toDouble()?.let { it1 -> it.putDouble("blockNumber", it1) } it.putString("data", Geth.encodeToHex(this?.data)) it.putArray("topics", this?.topics?.toReadableArray()) it.putString("txHash", this?.txHash?.hex) this?.txIndex?.toDouble()?.let { it1 -> it.putDouble("txIndex", it1) } this?.index?.toDouble()?.let { it1 -> it.putDouble("index", it1) } } } private fun Logs?.toReadableArray(): ReadableArray { return createArray().also { val size: Long? = this?.size() if (size != null) { repeat(size.toInt()) { index -> val log: Log? = this?.get(index.toLong()) it.pushMap(log.toReadableMap()) } } } } private fun SyncProgress?.toReadableMap(): ReadableMap { return createMap().also { this?.currentBlock?.toDouble()?.let { it1 -> it.putDouble("currentBlock", it1) } this?.highestBlock?.toDouble()?.let { it1 -> it.putDouble("highestBlock", it1) } this?.knownStates?.toDouble()?.let { it1 -> it.putDouble("knownStates", it1) } this?.pulledStates?.toDouble()?.let { it1 -> it.putDouble("pulledStates", it1) } this?.startingBlock?.toDouble()?.let { it1 -> it.putDouble("startingBlock", it1) } } } private fun NodeInfo?.toReadableMap(): ReadableMap { return createMap().also { this?.discoveryPort?.toInt()?.let { it1 -> it.putInt("discoveryPort", it1) } this?.enode?.toString()?.let { it1 -> it.putString("enode", it1) } this?.id?.toString()?.let { it1 -> it.putString("id", it1) } this?.ip?.toString()?.let { it1 -> it.putString("ip", it1) } this?.listenerAddress?.toString()?.let { it1 -> it.putString("listenerAddress", it1) } this?.listenerPort?.toString()?.let { it1 -> it.putString("listenerPort", it1) } this?.name?.toString()?.let { it1 -> it.putString("name", it1) } this?.protocols?.toString()?.let { it1 -> it.putString("protocols", it1) } } } private fun PeerInfo?.toReadableMap(): ReadableMap { return createMap().also { this?.caps?.toString()?.let { it1 -> it.putString("caps", it1) } this?.id?.toString()?.let { it1 -> it.putString("id", it1) } this?.localAddress?.toString()?.let { it1 -> it.putString("localAddress", it1) } this?.name?.toString()?.let { it1 -> it.putString("name", it1) } this?.remoteAddress?.toString()?.let { it1 -> it.putString("remoteAddress", it1) } } } private fun PeerInfos?.toReadableMap(): ReadableArray { return createArray().also { val size: Long? = this?.size() if (size != null) { repeat(size.toInt()) { index -> val peerInfo: PeerInfo? = this?.get(index.toLong()) it.pushMap(peerInfo.toReadableMap()) } } } } private fun ReadableArray?.toAddresses(): Addresses { val addresses: Addresses = Geth.newAddressesEmpty() val list: ArrayList<Any>? = this?.toArrayList() if (list != null) { for (item in list) { val address = Geth.newAddressFromHex(item as String?) addresses.append(address) } } return addresses } private fun ReadableArray?.toTopics(): Topics { val topics: Topics = Geth.newTopicsEmpty() val list = this?.toArrayList() if (list != null) { val hashes = Geth.newHashesEmpty() for (item in list) { val topic = Geth.newHashFromHex(item as String?) hashes.append(topic) } topics.append(hashes) } return topics } private fun ReadableMap?.toFilterQuery(): FilterQuery { val filterQuery: FilterQuery = Geth.newFilterQuery() if (this?.hasKey("addresses")!!) { filterQuery.addresses = this.getArray("addresses").toAddresses() } if (this.hasKey("fromBlock")) { val fromBlock = this.getDouble("fromBlock") filterQuery.fromBlock = Geth.newBigInt(fromBlock.toLong()) } if (this.hasKey("toBlock")) { val toBlock = this.getDouble("toBlock") filterQuery.toBlock = Geth.newBigInt(toBlock.toLong()) } if (this.hasKey("topics")) { filterQuery.topics = this.getArray("topics").toTopics() } return filterQuery } private fun ReadableMap?.toCallMsg(): CallMsg { val callMsg: CallMsg = Geth.newCallMsg() if (this?.hasKey("data")!!) callMsg.data = Geth.decodeFromHex(this.getString("data")) if (this.hasKey("from")) callMsg.from = Geth.newAddressFromHex(this.getString("from")) if (this.hasKey("gas")) callMsg.gas = this.getDouble("from").toLong() if (this.hasKey("gasPrice")) callMsg.gasPrice = Geth.newBigInt(this.getDouble("gasPrice").toLong()) if (this.hasKey("to")) callMsg.to = Geth.newAddressFromHex(this.getString("to")) if (this.hasKey("value")) callMsg.value = Geth.newBigInt(this.getDouble("value").toLong()) return callMsg } private fun ReadableArray?.toEnodes(): Enodes { val list = this?.toArrayList() val enodes: Enodes = Geth.newEnodesEmpty() if (list != null) { for (item in list) { val enode: Enode = Geth.newEnode(item as String?) enodes.append(enode) } } return enodes } // private fun Enodes?.toReadableArray(): ReadableArray { // return createArray().also { // val size: Long? = this?.size() // if (size != null) { // repeat(size.toInt()) { index -> // val enode: Enode? = this?.get(index.toLong()) // it.pushMap(enode.toReadableMap()) // } // } // } // } private fun ReadableMap?.toNodeConfig(): NodeConfig { val nodeConfig: NodeConfig = Geth.newNodeConfig() if (this?.hasKey("bootstrapNodes")!!) nodeConfig.bootstrapNodes = this.getArray("bootstrapNodes").toEnodes() if (this.hasKey("maxPeers")) nodeConfig.maxPeers = this.getDouble("maxPeers").toLong() if (this.hasKey("ethereumEnabled")) nodeConfig.ethereumEnabled = this.getBoolean("ethereumEnabled") if (this.hasKey("ethereumNetworkID")) nodeConfig.ethereumNetworkID = this.getDouble("ethereumNetworkID").toLong() if (this.hasKey("ethereumGenesis")) nodeConfig.ethereumGenesis = this.getString("ethereumGenesis") if (this.hasKey("ethereumDatabaseCache")) nodeConfig.ethereumDatabaseCache = this.getDouble("ethereumDatabaseCache").toLong() if (this.hasKey("ethereumNetStats")) nodeConfig.ethereumNetStats = this.getString("ethereumNetStats") if (this.hasKey("pprofAddress")) nodeConfig.pprofAddress = this.getString("pprofAddress") return nodeConfig } }
mit
cc60af308c4a44d9a5fe76ac1d080b52
30.310011
121
0.641455
3.723374
false
false
false
false
Hexworks/zircon
zircon.core/src/jvmMain/kotlin/org/hexworks/zircon/internal/util/AwtFontUtils.kt
1
1134
package org.hexworks.zircon.internal.util import java.awt.Font import java.awt.RenderingHints import java.awt.font.FontRenderContext object AwtFontUtils { /** * Tells whether the given [Font] is monospaced or not. */ @JvmStatic fun isFontMonospaced(font: Font): Boolean { val frc = getFontRenderContext() val iBounds = font.getStringBounds("i", frc) val mBounds = font.getStringBounds("W", frc) return iBounds.width == mBounds.width } /** * Calculates the width of a given [Font] in pixels. */ @JvmStatic fun getFontWidth(font: Font): Int { font.size2D return font.getStringBounds("W", getFontRenderContext()).width.toInt() } /** * Calculates the height of a given [Font] in pixels. */ @JvmStatic fun getFontHeight(font: Font): Int { return font.getStringBounds("W", getFontRenderContext()).height.toInt() } private fun getFontRenderContext() = FontRenderContext( null, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF, RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT ) }
apache-2.0
eab022ee3547a0d3dd142277e8e8cddf
26
79
0.650794
4.263158
false
false
false
false
benjamin-bader/thrifty
thrifty-schema/src/main/kotlin/com/microsoft/thrifty/schema/ErrorReporter.kt
1
2991
/* * Thrifty * * Copyright (c) Microsoft Corporation * * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.schema /** * An object that can collect warning and error reports generated during * parsing and schema validation. */ class ErrorReporter { /** * True if this reporter contains error-level reports. */ var hasError = false private set private val reports_: MutableList<Report> = mutableListOf() /** * All reports collected by this reporter. */ val reports: List<Report> get() = reports_ /** * Reports a warning at the given [location]. */ fun warn(location: Location, message: String) { reports_.add(Report(Level.WARNING, location, message)) } /** * Reports an error at the given [location]. */ fun error(location: Location, message: String) { hasError = true reports_.add(Report(Level.ERROR, location, message)) } /** * Returns a list of formatted warning and error reports contained in this * reporter. */ fun formattedReports(): List<String> { val list = mutableListOf<String>() val sb = StringBuilder() for (report in reports_) { when (report.level) { ErrorReporter.Level.WARNING -> sb.append("W: ") ErrorReporter.Level.ERROR -> sb.append("E: ") } sb.append(report.message) sb.append(" (at ") sb.append(report.location) sb.append(")") list += sb.toString() sb.setLength(0) } return list } /** * A structure containing a report level, content, and location. * * @property level The severity of the report. * @property location The point in a .thrift file containing the subject of the report. * @property message A description of the warning or error condition. */ data class Report( val level: Level, val location: Location, val message: String ) /** * The severities of reports. */ enum class Level { /** * A warning is non-fatal, but should be investigated. */ WARNING, /** * An error indicates that loading cannot proceed. */ ERROR } }
apache-2.0
1647ef1c9b210081268771d6bfc76cbc
26.449541
116
0.606486
4.559451
false
false
false
false
ingokegel/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/ui/preview/ResourceProvider.kt
4
5168
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.ui.preview import org.jetbrains.annotations.ApiStatus import java.io.File import kotlin.reflect.KClass interface ResourceProvider { /** * Resource description, containing resource content and it's type. * In case type is null, [PreviewStaticServer] will try to guess it based * on resource name. */ class Resource( val content: ByteArray, val type: String? = null ) /** * @return true if this resource provider can load resource [resourceName] * with it's [loadResource] method. */ fun canProvide(resourceName: String): Boolean /** * Load [resourceName] contents. * * @param resourceName Resource path. * @return [Resource] if resource was successfully loaded or null if load failed. */ fun loadResource(resourceName: String): Resource? /** * Default resource provider implementation with * [canProvide] and [loadResource] returning always false and null. */ class DefaultResourceProvider: ResourceProvider { override fun canProvide(resourceName: String): Boolean = false override fun loadResource(resourceName: String): Resource? = null } private class AggregatingResourceProvider(private val providers: Array<out ResourceProvider>): ResourceProvider { override fun canProvide(resourceName: String): Boolean { return providers.any { it.canProvide(resourceName) } } override fun loadResource(resourceName: String): Resource? { return providers.firstNotNullOfOrNull { it.loadResource(resourceName) } } } companion object { /** * Shared instance of [DefaultResourceProvider]. */ val default: ResourceProvider = DefaultResourceProvider() fun aggregating(vararg providers: ResourceProvider): ResourceProvider { return AggregatingResourceProvider(providers) } /** * Load resource using [cls]'s [ClassLoader]. * Note: You might want to explicitly set [contentType] for your resource * if you *care about the encoding*. * * @param cls Java class to get the [ClassLoader] of. * @param path Path of the resource to load. * @param contentType Explicit type of content. If null, [PreviewStaticServer] will * try to guess content type based on resource name. The [PreviewStaticServer] won't set * any charset for guessed content type (except for types declared in [PreviewStaticServer.typesForExplicitUtfCharset]). * You might want to [explicitly set](https://www.w3.org/International/articles/http-charset/index.en#charset) * [contentType] if you *care about encoding*. * @return [Resource] with the contents of resource, or null in case * the resource could not be loaded. */ @JvmStatic fun <T> loadInternalResource(cls: Class<T>, path: String, contentType: String? = null): Resource? { return cls.getResourceAsStream(path)?.use { Resource(it.readBytes(), contentType) } } /** * Load resource using [cls]'s [ClassLoader]. * * @param cls Kotlin class to get the [ClassLoader] of. * @param path Path of the resource to load. * @param contentType Explicit type of content. If null, [PreviewStaticServer] will * try to guess content type based on resource name. See [loadInternalResource]. * @return [Resource] with the contents of resource, or null in case * the resource could not be loaded. */ @JvmStatic fun <T : Any> loadInternalResource(cls: KClass<T>, path: String, contentType: String? = null): Resource? { return loadInternalResource(cls.java, path, contentType) } /** * See [loadInternalResource] */ @JvmStatic inline fun <reified T : Any> loadInternalResource(path: String, contentType: String? = null): Resource? { return loadInternalResource(T::class.java, path, contentType) } /** * Load resource from the filesystem. * * @param file File to load. * @param contentType Explicit type of content. If null, [PreviewStaticServer] will * try to guess content type based on resource name. See [loadInternalResource]. * @return [Resource] with the contents of resource, or null in case * the resource could not be loaded. */ @JvmStatic fun loadExternalResource(file: File, contentType: String? = null): Resource? { if (!file.exists()) { return null } val content = file.inputStream().use { it.readBytes() } return Resource(content, contentType) } @ApiStatus.Experimental @JvmStatic fun createResourceProviderChain(vararg providers: ResourceProvider): ResourceProvider { return object: ResourceProvider { override fun canProvide(resourceName: String): Boolean { return providers.any { it.canProvide(resourceName) } } override fun loadResource(resourceName: String): Resource? { return providers.firstNotNullOfOrNull { it.loadResource(resourceName) } } } } } }
apache-2.0
ebb7997b44094a5a02cfd773920ae58b
36.179856
140
0.690209
4.655856
false
false
false
false
benjamin-bader/thrifty
thrifty-schema/src/test/kotlin/com/microsoft/thrifty/schema/FieldNamingPolicyTest.kt
1
2330
/* * Thrifty * * Copyright (c) Microsoft Corporation * * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.schema import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test class FieldNamingPolicyTest { @Test fun defaultNamesAreUnaltered() { val policy = FieldNamingPolicy.DEFAULT policy.apply("SSLFlag") shouldBe "SSLFlag" policy.apply("MyField") shouldBe "MyField" } @Test fun javaPolicyCamelCasesNames() { val policy = FieldNamingPolicy.JAVA policy.apply("MyField") shouldBe "myField" policy.apply("X") shouldBe "x" policy.apply("abcde") shouldBe "abcde" } @Test fun javaPolicyPreservesAcronyms() { val policy = FieldNamingPolicy.JAVA policy.apply("OAuthToken") shouldBe "OAuthToken" policy.apply("SSLFlag") shouldBe "SSLFlag" } @Test fun javaPolicyDifferentCaseFormatCamelCaseNames() { val policy = FieldNamingPolicy.JAVA // lower_underscore policy.apply("my_field") shouldBe "myField" // lower-hyphen policy.apply("my-field") shouldBe "myField" // UpperCamel policy.apply("MyField") shouldBe "myField" // UPPER_UNDERSCORE policy.apply("MY_FIELD") shouldBe "myField" } @Test fun pascalPolicy() { val policy = FieldNamingPolicy.PASCAL policy.apply("my_field") shouldBe "MyField" policy.apply("my-field") shouldBe "MyField" policy.apply("MyField") shouldBe "MyField" policy.apply("MY_FIELD") shouldBe "MyField" policy.apply("my_f234") shouldBe "MyF234" policy.apply("myField") shouldBe "MyField" } }
apache-2.0
0e0b87f93f04f8d2a350f595cfc500dc
29.657895
116
0.672103
4.102113
false
true
false
false
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/conversation/colors/ui/ChatColorSelectionFragment.kt
1
4263
package org.thoughtcrime.securesms.conversation.colors.ui import android.os.Bundle import android.view.View import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import androidx.navigation.Navigation import androidx.recyclerview.widget.RecyclerView import com.google.android.material.dialog.MaterialAlertDialogBuilder import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.conversation.colors.ChatColors class ChatColorSelectionFragment : Fragment(R.layout.chat_color_selection_fragment) { private lateinit var viewModel: ChatColorSelectionViewModel override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val args: ChatColorSelectionFragmentArgs = ChatColorSelectionFragmentArgs.fromBundle(requireArguments()) viewModel = ChatColorSelectionViewModel.getOrCreate(requireActivity(), args.recipientId) val toolbar: Toolbar = view.findViewById(R.id.toolbar) val preview: ChatColorPreviewView = view.findViewById(R.id.preview) val recycler: RecyclerView = view.findViewById(R.id.recycler) val adapter = ChatColorSelectionAdapter( requireContext(), Callbacks(args, view) ) recycler.itemAnimator = null recycler.adapter = adapter toolbar.setNavigationOnClickListener { Navigation.findNavController(it).popBackStack() } viewModel.state.observe(viewLifecycleOwner) { state -> preview.setWallpaper(state.wallpaper) if (state.chatColors != null) { preview.setChatColors(state.chatColors) } adapter.submitList(state.chatColorModels) } viewModel.events.observe(viewLifecycleOwner) { event -> if (event is ChatColorSelectionViewModel.Event.ConfirmDeletion) { if (event.usageCount > 0) { showWarningDialogForMultipleUses(event) } else { showWarningDialogForNoUses(event) } } } } override fun onResume() { super.onResume() viewModel.refresh() } private fun showWarningDialogForNoUses(confirmDeletion: ChatColorSelectionViewModel.Event.ConfirmDeletion) { MaterialAlertDialogBuilder(requireContext()) .setMessage(R.string.ChatColorSelectionFragment__delete_chat_color) .setPositiveButton(R.string.ChatColorSelectionFragment__delete) { dialog, _ -> viewModel.deleteNow(confirmDeletion.chatColors) dialog.dismiss() } .setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.dismiss() } .show() } private fun showWarningDialogForMultipleUses(confirmDeletion: ChatColorSelectionViewModel.Event.ConfirmDeletion) { MaterialAlertDialogBuilder(requireContext()) .setTitle(R.string.ChatColorSelectionFragment__delete_color) .setMessage(resources.getQuantityString(R.plurals.ChatColorSelectionFragment__this_custom_color_is_used, confirmDeletion.usageCount, confirmDeletion.usageCount)) .setPositiveButton(R.string.delete) { dialog, _ -> viewModel.deleteNow(confirmDeletion.chatColors) dialog.dismiss() } .setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.dismiss() } .show() } inner class Callbacks( private val args: ChatColorSelectionFragmentArgs, private val view: View ) : ChatColorSelectionAdapter.Callbacks { override fun onSelect(chatColors: ChatColors) { viewModel.save(chatColors) } override fun onEdit(chatColors: ChatColors) { val startPage = if (chatColors.getColors().size == 1) 0 else 1 val directions = ChatColorSelectionFragmentDirections .actionChatColorSelectionFragmentToCustomChatColorCreatorFragment(args.recipientId, startPage) .setChatColorId(chatColors.id.longValue) Navigation.findNavController(view).navigate(directions) } override fun onDuplicate(chatColors: ChatColors) { viewModel.duplicate(chatColors) } override fun onDelete(chatColors: ChatColors) { viewModel.startDeletion(chatColors) } override fun onAdd() { val directions = ChatColorSelectionFragmentDirections.actionChatColorSelectionFragmentToCustomChatColorCreatorFragment(args.recipientId, 0) Navigation.findNavController(view).navigate(directions) } } }
gpl-3.0
2d4a21b21e3fd424e056caa2423dc633
34.231405
167
0.742669
4.811512
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/en1545/En1545FixedHex.kt
1
1914
/* * En1545Fixed.kt * * Copyright 2018 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.en1545 import au.id.micolous.metrodroid.multi.Log import au.id.micolous.metrodroid.util.ImmutableByteArray class En1545FixedHex(private val mName: String, private val mLen: Int) : En1545Field { override fun parseField(b: ImmutableByteArray, off: Int, path: String, holder: En1545Parsed, bitParser: En1545Bits): Int { var res = "" try { var i = mLen while (i > 0) { if (i >= 8) { var t = bitParser(b, off + i - 8, 8).toString(16) if (t.length == 1) t = "0$t" res = t + res i -= 8 continue } if (i >= 4) { res = bitParser(b, off + i - 4, 4).toString(16) + res i -= 4 continue } res = bitParser(b, off, i).toString(16) + res break } holder.insertString(mName, path, res) } catch (e: Exception) { Log.w("En1545FixedHex", "Overflow when parsing en1545", e) } return off + mLen } }
gpl-3.0
b3c474cff3d6ca4e34c12e0b765e2cde
33.178571
126
0.564786
4.133909
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/store/StoreViewController.kt
1
6907
package io.ipoli.android.store import android.content.res.ColorStateList import android.graphics.drawable.Drawable import android.graphics.drawable.GradientDrawable import android.os.Bundle import android.support.annotation.ColorRes import android.support.annotation.DrawableRes import android.support.annotation.StringRes import android.view.* import com.bluelinelabs.conductor.RestoreViewOnCreateController import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.changehandler.FadeChangeHandler import com.bluelinelabs.conductor.changehandler.VerticalChangeHandler import io.ipoli.android.R import io.ipoli.android.common.view.* import kotlinx.android.synthetic.main.item_store.view.* import kotlinx.android.synthetic.main.view_default_toolbar.view.* /** * Created by Polina Zhelyazkova <[email protected]> * on 3/23/18. */ class StoreViewController(args: Bundle? = null) : RestoreViewOnCreateController(args) { private val fadeChangeHandler = FadeChangeHandler() private var itemHeight: Int = 0 override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { setHasOptionsMenu(true) val view = inflater.inflate(R.layout.controller_store, container, false) view.post { itemHeight = view.height * 6 / 7 / VISIBLE_ITEMS_PER_SCREEN renderAll(view) } setToolbar(view.toolbar) return view } private fun renderAll(view: View) { StoreItem.values().forEach { renderItem( view = view.findViewById(it.id), color = it.color, icon = it.icon, title = it.title, open = open(it) ) } } private fun open(item: StoreItem): () -> Unit { when (item) { StoreItem.MEMBERSHIP -> return { navigate().toMembership(fadeChangeHandler) } StoreItem.POWER_UPS -> return { navigate().toPowerUpStore(fadeChangeHandler) } StoreItem.AVATARS -> return { navigate().toAvatarStore(fadeChangeHandler) } StoreItem.GEMS -> return { navigate().toGemStore(fadeChangeHandler) } StoreItem.PETS -> return { navigate().toPetStore(fadeChangeHandler) } StoreItem.THEMES -> return { navigate().toThemeStore(fadeChangeHandler) } StoreItem.COLORS -> return { navigate().toColorPicker() } StoreItem.ICONS -> return { navigate().toIconPicker() } } } override fun onAttach(view: View) { colorLayoutBars() super.onAttach(view) toolbarTitle = stringRes(R.string.drawer_store) showBackButton() } private fun colorLayoutBars() { activity?.window?.navigationBarColor = attrData(io.ipoli.android.R.attr.colorPrimary) activity?.window?.statusBarColor = attrData(io.ipoli.android.R.attr.colorPrimaryDark) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.help_menu, menu) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { return router.handleBack() } if (item.itemId == R.id.actionHelp) { navigate().toHelp( stringRes(R.string.help_dialog_store_title), stringRes(R.string.help_dialog_store_message) ) return true } return super.onOptionsItemSelected(item) } private fun renderItem( view: View, @ColorRes color: Int, @DrawableRes icon: Int, @StringRes title: Int, open: () -> Unit ) { val colorRes = colorRes(color) view.layoutParams.height = itemHeight view.post { val width = view.width * 4 / 3 view.storeItemBackground.layoutParams.width = width view.storeItemBackground.post { val xRadius = width / 2f val yRadius = view.storeItemBackground.height / 2f view.storeItemBackground.background = createLeftRoundedDrawable(xRadius, yRadius, colorRes) } } view.storeItemIcon.setImageResource(icon) view.storeItemIcon.drawable.setTint(colorRes) view.storeItemTitle.text = stringRes(title) view.setOnClickListener(Debounce.clickListener { open() }) } private fun createLeftRoundedDrawable(xRadius: Float, yRadius: Float, color: Int): Drawable { val d = GradientDrawable() d.shape = GradientDrawable.RECTANGLE d.cornerRadii = floatArrayOf(0f, 0f, 0f, 0f, xRadius, yRadius, xRadius, yRadius) d.color = ColorStateList.valueOf(color) return d } enum class StoreItem( val id: Int, @ColorRes val color: Int, @DrawableRes val icon: Int, @StringRes val title: Int ) { MEMBERSHIP( id = R.id.storeMembership, color = R.color.md_blue_600, icon = R.drawable.ic_card_membership_black_24px, title = R.string.membership ), POWER_UPS( id = R.id.storePowerUps, color = R.color.md_orange_600, icon = R.drawable.ic_rocket_black_24dp, title = R.string.power_ups ), AVATARS( id = R.id.storeAvatars, color = R.color.md_green_600, icon = R.drawable.ic_ninja_black_24dp, title = R.string.avatars ), PETS( id = R.id.storePets, color = R.color.md_purple_400, icon = R.drawable.ic_pets_white_24dp, title = R.string.pets ), GEMS( id = R.id.storeGems, color = R.color.md_blue_grey_400, icon = R.drawable.ic_diamond_black_24dp, title = R.string.gems ), THEMES( id = R.id.storeThemes, color = R.color.md_pink_400, icon = R.drawable.ic_theme_black_24dp, title = R.string.themes ), COLORS( id = R.id.storeColors, color = R.color.md_purple_600, icon = R.drawable.ic_color_palette_white_24dp, title = R.string.colors ), ICONS( id = R.id.storeIcons, color = R.color.md_red_400, icon = R.drawable.ic_icon_white_24dp, title = R.string.icons ) } companion object { const val VISIBLE_ITEMS_PER_SCREEN = 3 fun routerTransaction() = RouterTransaction.with(StoreViewController()) .pushChangeHandler(VerticalChangeHandler()) .popChangeHandler(VerticalChangeHandler()) } }
gpl-3.0
09f85f10d24d79014054294c3b676cc4
32.697561
97
0.603446
4.300747
false
false
false
false
pdvrieze/kotlinsql
direct/src/generators/kotlin/kotlinsql/builder/generate_selects.kt
1
7451
/* * Copyright (c) 2017. * * This file is part of ProcessManager. * * This file is licenced to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You should have received a copy of the license with the source distribution. * Alternatively, 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. */ /** * Created by pdvrieze on 04/04/16. */ package kotlinsql.builder import java.io.Writer @Suppress("unused") class GenerateSelectClasses { fun doGenerate(output: Writer, input: Any) { val count = input as Int output.apply { appendCopyright() appendLine() appendLine("package io.github.pdvrieze.kotlinsql.impl.gen") appendLine() appendLine("import java.sql.SQLException") appendLine() appendLine("import io.github.pdvrieze.kotlinsql.Column") appendLine("import io.github.pdvrieze.kotlinsql.Database") appendLine("import io.github.pdvrieze.kotlinsql.Database.*") appendLine("import io.github.pdvrieze.kotlinsql.IColumnType") // appendLine("import io.github.pdvrieze.kotlinsql.sql.NonMonadicApi") // appendLine("import io.github.pdvrieze.kotlinsql.executeHelper") // appendLine("import io.github.pdvrieze.kotlinsql.sequenceHelper") for (n in 2..count) { appendLine() append("interface Select$n<") (1..n).joinToString(",\n ") { m -> "T$m: Any, S$m: IColumnType<T$m,S$m,C$m>, C$m: Column<T$m, S$m, C$m>" } .apply { append(this) } appendLine(">:SelectStatement {") appendLine() append(" override val select: _Select$n<") (1..n).joinTo(this, ",") { m -> "T$m,S$m,C$m" } appendLine(">") appendLine() /* append(" fun <R>getList(connection: MonadicDBConnection<*>, factory:") appendFactorySignature(n) appendLine("): List<R>") if (n > 1) { appendLine() append(" fun getSingle(connection: MonadicDBConnection<*>): _Statement$n.Result<") (1..n).joinTo(this, ",") { m -> "T$m" } appendLine(">?") appendLine() append(" fun <R> getSingle(connection: MonadicDBConnection<*>, factory:") appendFactorySignature(n) appendLine("):R?") appendLine() append(" fun execute(connection: MonadicDBConnection<*>, block: (") (1..n).joinToString(",") { m -> "T$m?" }.apply { append(this) } appendLine(")->Unit):Boolean") } */ appendLine("}") if (n > 1) { /* appendLine() append("fun <DB: Database, In, ") (1..n).joinTo(this, ", ") { m -> "T$m: Any, C$m: Column<T$m, *, C$m>" } append(", R> EmptyDBTransaction<DB, In>.sequence(queryGen: DB.(In)->Select$n<") (1..n).joinTo(this, ", ") { m -> "T$m, *, C$m" } append(">, combine: (") (1..n).joinTo(this, ", ") { m -> "T$m?" } appendLine(") -> R): EvaluatableDBTransaction<DB, Sequence<R>> {") appendLine(" return sequenceHelper(queryGen) { query, rs ->") appendLine(" val s = query.select") append(" combine(") (1..n).joinTo(this, ", ") { m -> "s.col$m.fromResultSet(rs, $m)" } appendLine(") }") appendLine("}") */ } appendLine() appendLine("@Suppress(\"UNCHECKED_CAST\")") append("class _Select$n<") (1..n).joinToString(",\n ") { m -> "T$m:Any, S$m:IColumnType<T$m,S$m,C$m>, C$m: Column<T$m, S$m, C$m>" } .apply { append(this) } append(">(") append((1..n).joinToString { m -> "col$m: C$m" }) append("):\n _BaseSelect(") append((1..n).joinToString { m -> "col$m" }) appendLine("),") (1..n).joinTo(this, ", ", " Select$n<", "> {") { m -> "T$m, S$m, C$m" } appendLine() appendLine() append(" override val select: _Select$n<") (1..n).joinTo(this, ",") { m -> "T$m,S$m,C$m" } appendLine("> get() = this") appendLine() append(" override fun WHERE(config: _Where.() -> WhereClause?): Select$n<") (1..n).joinTo(this) { m -> "T$m, S$m, C$m" } appendLine("> =") appendLine(" _Where().config()?.let { _Statement$n(this, it) } ?: this") /* appendLine() append(" override fun execute(connection:MonadicDBConnection<*>, block: (") (1..n).joinToString(",") { m -> "T$m?" }.apply { append(this) } appendLine(")->Unit):Boolean {") appendLine(" return executeHelper(connection, block) { rs, block2 ->") append(" block2(") (1..n).joinToString(",\n${" ".repeat(19)}") { m -> "col$m.type.fromResultSet(rs, $m)" }.apply { append(this) } // if (n==1) { // append("select.col1.type.fromResultSet(rs, 1)") // } else { // } appendLine(')') appendLine(" }") appendLine(" }") appendLine() append(" override fun <R>getList(connection: MonadicDBConnection<*>, factory:") appendFactorySignature(n) appendLine("): List<R> {") appendLine(" val result=mutableListOf<R>()") append(" execute(connection) { ") (1..n).joinToString { "p$it" }.apply { append(this) } append(" -> result.add(factory(") (1..n).joinToString { "p$it" }.apply { append(this) } appendLine(")) }") appendLine(" return result") appendLine(" }") if (n > 1) { appendLine() appendLine(" @NonMonadicApi") append(" override fun getSingle(connection: MonadicDBConnection<*>)") append(" = getSingle(connection) { ") (1..n).joinTo(this, ",") { "p$it" } append(" -> _Statement$n.Result(") (1..n).joinTo(this, ",") { "p$it" } appendLine(")}") appendLine() appendLine(" @NonMonadicApi") append(" override fun <R> getSingle(connection: MonadicDBConnection<*>, factory:") appendFactorySignature(n) appendLine("):R? {") appendLine(" return connection.prepareStatement(toSQL()) {") appendLine(" setParams(this)") appendLine(" execute { rs ->") appendLine(" if (rs.next()) {") appendLine(" if (!rs.isLast) throw SQLException(\"Multiple results found, where only one or none expected\")") append(" factory(") (1..n).joinTo(this, ",\n${" ".repeat(18)}") { m -> "select.col$m.type.fromResultSet(rs, $m)" } appendLine(")") appendLine(" } else null ") appendLine(" }") appendLine(" }") appendLine(" }") } */ appendLine() for (m in 1..n) { appendLine(" val col$m: C$m get() = columns[${m - 1}] as C$m") } appendLine("}") } } } }
apache-2.0
0ac0447e49e77b4776b29b74416bbc3f
35.704433
131
0.530264
3.860622
false
false
false
false
Cryxnoob/TeamProjectTH-BingenEP-3
src/main/kotlin/project2/Network.kt
1
5876
package project2 import java.util.* class Network(val capacity:Int,val trains:List<Train>, val scheduleLength:Int, val capacities: MutableList<Int>) { private var segments:MutableList<Segment> = mutableListOf() private var currentStep:Int = 0 private var probPrio1: Int = 0 private var probPrio2: Int = 0 private var probPrio3: Int = 0 private var segmentTrainMapping: MutableList<MutableList<Train>> = mutableListOf() init{ var x:Int= 1 for (capacity in capacities){ segments.add(Segment(x, capacity)) x++ } } fun runSimulation() { while (currentStep < scheduleLength) { simulateOneStep() } } fun simulateOneStep(){ var diff: Int var x: Int var delayedTrains: MutableList<Int> = mutableListOf() /* reset segment train count */ segmentTrainMapping = mutableListOf() for(segment in segments) { segment.setCurrentCount(0) segmentTrainMapping.add(mutableListOf()) } for(train in trains) { train.setDelayed(false) } for(train in trains) { var segment:Int = train.getCurrentSegment(currentStep) - 1 if(segment > -1) { segments[segment].increaseCount() segmentTrainMapping[segment].add(train) } } var y = 0 for (segment in segments) { if (segment.getCurrentCount() > segment.capacity) { diff = segment.getCurrentCount() - segment.capacity x = diff // calculate probabilities var count1: Int = 0 var count2: Int = 0 var count3: Int = 0 for(mappedTrain in segmentTrainMapping[y]) { when(mappedTrain.priority) { 1 -> count1++ 2 -> count2++ 3 -> count3++ else -> { println("error: unknown priority") } } } if (count1 > 0 && count2 > 0 && count3 > 0) { probPrio1 = (100 / (count1 + (0.5 * count2) + (0.25 * count3))).toInt() probPrio2 = probPrio1 / 2 probPrio3 = probPrio2 / 2 } else if (count1 > 0 && count2 > 0 && count3 == 0) { probPrio1 = (100 / (count1 + (0.5 * count2) + (0.25 * count3))).toInt() probPrio2 = probPrio1 / 2 probPrio3 = 0 } else if (count1 > 0 && count2 == 0 && count3 > 0) { probPrio1 = (100 / (count1 + (0.5 * count2) + (0.25 * count3))).toInt() probPrio2 = 0 probPrio3 = probPrio1 / 2 } else if (count1 > 0 && count2 == 0 && count3 == 0) { probPrio1 = 100 probPrio2 = 0 probPrio3 = 0 } else if (count1 == 0 && count2 > 0 && count3 > 0) { probPrio1 = 0 probPrio2 = (100 / (count1 + (0.5 * count2) + (0.25 * count3))).toInt() probPrio3 = probPrio2 / 2 } else if (count1 == 0 && count2 > 0 && count3 == 0) { probPrio1 = 0 probPrio2 = 100 probPrio3 = 0 } else if (count1 == 0 && count2 == 0 && count3 > 0) { probPrio1 = 0 probPrio2 = 0 probPrio3 = 100 } var delayList: MutableList<Int> = mutableListOf() for(mappedTrain in segmentTrainMapping[y]) { var counter = 0 when(mappedTrain.priority) { 1 -> { counter = probPrio1 } 2 -> { counter = probPrio2 } 3 -> { counter = probPrio3 } else -> { println("error: unknown priority") } } while (counter > 0) { delayList.add(mappedTrain.id) counter-- } } while (x > 0) { var differentTrain: Boolean = false while (!differentTrain) { val newValue = Random().nextInt(delayList.size) if(delayList[newValue] !in delayedTrains) { delayedTrains.add(delayList[newValue]) differentTrain = true } } x-- } for(mappedTrain in segmentTrainMapping[y]) { if(mappedTrain.id in delayedTrains) { mappedTrain.setDelayed(true) mappedTrain.shiftSchedule(currentStep) } } } segment.persistCapacity() y++ } for (train in trains) { train.persistStep(currentStep) } currentStep++ } fun getSegmentsCapacityTracking(): MutableList<MutableList<Int>> { var masterList: MutableList<MutableList<Int>> = mutableListOf() for(segment in segments) { masterList.add(segment.getPersistentCapacities()) } return masterList } }
mit
2f08e5209dc9544f6a0e6ef91fa0025e
32.016854
114
0.423247
4.95865
false
false
false
false
Doctoror/ParticleConstellationsLiveWallpaper
app/src/main/java/com/doctoror/particleswallpaper/userprefs/engine/EnginePreference.kt
1
2494
/* * Copyright (C) 2019 Yaroslav Mytkalyk * * 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.doctoror.particleswallpaper.userprefs.engine import android.app.Fragment import android.content.Context import android.preference.ListPreference import android.util.AttributeSet import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import com.doctoror.particleswallpaper.framework.app.FragmentHolder import com.doctoror.particleswallpaper.framework.di.inject import org.koin.core.parameter.parametersOf class EnginePreference @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : ListPreference(context, attrs), EnginePreferenceView, LifecycleObserver, FragmentHolder { override var fragment: Fragment? = null private val valueMapper: EnginePreferenceValueMapper by inject( context = context ) private val presenter: EnginePreferencePresenter by inject( context = context, parameters = { parametersOf(this as EnginePreferenceView) } ) init { isPersistent = false entries = valueMapper.provideEntries() entryValues = valueMapper.provideEntryValues() setOnPreferenceChangeListener { _, v -> presenter.onPreferenceChange(v as CharSequence?) false } } @OnLifecycleEvent(Lifecycle.Event.ON_START) fun onStart() { presenter.onStart() } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onStop() { presenter.onStop() } override fun setValue(value: String) { super.setValue(value) applySummary() } override fun showRestartDialog(shouldEnableOpenGl: Boolean) { fragment?.let { newEngineRestartDialog(shouldEnableOpenGl) .show(it.fragmentManager, "MultisamplingRestartDialog") } } private fun applySummary() { summary = entry } }
apache-2.0
6c4f258411ca7260febb1b06f04bfe2b
30.175
93
0.715718
4.842718
false
false
false
false
sys1yagi/DroiDon
app/src/main/java/com/sys1yagi/mastodon/android/data/database/Credential.kt
1
795
package com.sys1yagi.mastodon.android.data.database import com.github.gfx.android.orma.annotation.Column import com.github.gfx.android.orma.annotation.PrimaryKey import com.github.gfx.android.orma.annotation.Table @Table("credential") class Credential { @PrimaryKey(autoincrement = true) var id: Long = 0L @Column("registration_id", indexed = true) var registrationId: Long = 0 @Column("instance_name", indexed = true) var instanceName: String = "" @Column("client_id") var clientId: String = "" @Column("client_secret") var clientSecret: String = "" override fun toString(): String { return "Credential(id=$id, registrationId=$registrationId, instanceName='$instanceName', clientId='$clientId', clientSecret='$clientSecret')" } }
mit
95b88a4639c017423d242c585935c1b1
27.392857
149
0.70566
4.076923
false
false
false
false
mdanielwork/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/ImageCollector.kt
1
14859
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.intellij.build.images import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.StringUtil import com.intellij.util.containers.ContainerUtil import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.module.JpsModuleSourceRoot import org.jetbrains.jps.util.JpsPathUtil import java.io.File import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.util.* import java.util.function.Consumer import java.util.regex.Pattern import java.util.stream.Stream import java.util.stream.StreamSupport import kotlin.collections.ArrayList internal const val ROBOTS_FILE_NAME = "icon-robots.txt" internal class ImagePaths(val id: String, val sourceRoot: JpsModuleSourceRoot, val phantom: Boolean) { private var flags: ImageFlags = ImageFlags() private var images: MutableList<Path> = ContainerUtil.createConcurrentList() fun addImage(file: Path, fileFlags: ImageFlags) { images.add(file) flags = mergeImageFlags(flags, fileFlags, file.toString()) } val files: List<Path> get() = images fun getFiles(vararg types: ImageType): List<Path> = files.filter { ImageType.fromFile(it) in types } val file: Path? get() = getFiles(ImageType.BASIC) .sortedBy { ImageExtension.fromFile(it) } .firstOrNull() val presentablePath: Path get() = file ?: files.first() ?: Paths.get("<unknown>") val used: Boolean get() = flags.used val deprecated: Boolean get() = flags.deprecation != null val deprecation: DeprecationData? get() = flags.deprecation } class ImageFlags(val skipped: Boolean, val used: Boolean, val deprecation: DeprecationData?) { constructor() : this(false, false, null) } data class DeprecationData(val comment: String?, val replacement: String?, val replacementContextClazz: String?, val replacementReference: String?) internal class ImageCollector(private val projectHome: Path, private val iconsOnly: Boolean = true, val ignoreSkipTag: Boolean = false, private val className: String? = null) { // files processed in parallel, so, concurrent data structures must be used private val icons = ContainerUtil.newConcurrentMap<String, ImagePaths>() private val phantomIcons = ContainerUtil.newConcurrentMap<String, ImagePaths>() private val usedIconsRobots: MutableSet<Path> = ContainerUtil.newConcurrentSet() fun collect(module: JpsModule, includePhantom: Boolean = false): List<ImagePaths> { for (sourceRoot in module.sourceRoots) { if (sourceRoot.rootType == JavaResourceRootType.RESOURCE) { processRoot(sourceRoot) } } val result = ArrayList(icons.values) if (includePhantom) { result.addAll(phantomIcons.values) } return result } fun printUsedIconRobots() { if (!usedIconsRobots.isEmpty()) { println(usedIconsRobots.joinToString(separator = "\n") { "Found icon-robots: $it" }) } } private fun processRoot(sourceRoot: JpsModuleSourceRoot) { val root = Paths.get(JpsPathUtil.urlToPath(sourceRoot.url)) if (!root.toFile().exists()) return val answer = downToRoot(root, root, null, IconRobotsData(), 0) val iconsRoot = (if (answer == null || Files.isDirectory(answer)) answer else answer.parent) ?: return val rootRobotData = upToProjectHome(root) if (rootRobotData.isSkipped(root)) return val robotData = rootRobotData.fork(iconsRoot, root) processDirectory(iconsRoot, sourceRoot, robotData, emptyList(), 0) processPhantomIcons(iconsRoot, sourceRoot, robotData, emptyList()) } private fun processDirectory(dir: Path, sourceRoot: JpsModuleSourceRoot, robotData: IconRobotsData, prefix: List<String>, level: Int) { // do not process in parallel for if level >= 3 because no sense - parents processed in parallel already dir.processChildren(level < 3) { file -> if (robotData.isSkipped(file)) { return@processChildren } if (Files.isDirectory(file)) { val root = Paths.get(JpsPathUtil.urlToPath(sourceRoot.url)) val childRobotData = robotData.fork(file, root) val childPrefix = prefix + file.fileName.toString() processDirectory(file, sourceRoot, childRobotData, childPrefix, level + 1) if (childRobotData != robotData) { processPhantomIcons(file, sourceRoot, childRobotData, childPrefix) } } else if (isImage(file, iconsOnly)) { processImageFile(file, sourceRoot, robotData, prefix) } } } private fun processImageFile(file: Path, sourceRoot: JpsModuleSourceRoot, robotData: IconRobotsData, prefix: List<String>) { val id = ImageType.getBasicName(file, prefix) val flags = robotData.getImageFlags(file) if (flags.skipped) return val iconPaths = icons.computeIfAbsent(id) { ImagePaths(id, sourceRoot, false) } iconPaths.addImage(file, flags) } private fun processPhantomIcons(root: Path, sourceRoot: JpsModuleSourceRoot, robotData: IconRobotsData, prefix: List<String>) { for (icon in robotData.getOwnDeprecatedIcons()) { val iconFile = root.resolve(icon.first.removePrefix("/").removePrefix(File.separator)) val id = ImageType.getBasicName(icon.first, prefix) if (icons.containsKey(id)) continue val paths = ImagePaths(id, sourceRoot, true) paths.addImage(iconFile, icon.second) if (phantomIcons.containsKey(id)) { throw Exception("Duplicated phantom icon found: $id\n$root/${ROBOTS_FILE_NAME}") } phantomIcons.put(id, paths) } } private fun upToProjectHome(dir: Path): IconRobotsData { if (FileUtil.pathsEqual(dir.toString(), projectHome.toString())) { return IconRobotsData() } val parent = dir.parent ?: return IconRobotsData() return upToProjectHome(parent).fork(parent, projectHome) } private fun downToRoot(root: Path, file: Path, common: Path?, robotData: IconRobotsData, level: Int): Path? { if (robotData.isSkipped(file)) { return common } when { file.toFile().isDirectory() -> { if (level == 1 && file.fileName.toString() == "META-INF") { return common } val childRobotData = robotData.fork(file, root) var childCommon = common Files.list(file).use { stream -> stream.forEachOrdered { childCommon = downToRoot(root, it, childCommon, childRobotData, level + 1) } } return childCommon } isImage(file, iconsOnly) -> { if (common == null) { return file } else { return FileUtil.findAncestor(common.toFile(), file.toFile())?.toPath() } } else -> return common } } private data class DeprecatedEntry(val matcher: Pattern, val data: DeprecationData) private data class OwnDeprecatedIcon(val relativeFile: String, val data: DeprecationData) private inner class IconRobotsData(private val parent: IconRobotsData? = null) { private val skip: MutableList<Pattern> = ArrayList() private val used: MutableList<Pattern> = ArrayList() private val deprecated: MutableList<DeprecatedEntry> = ArrayList() private val ownDeprecatedIcons: MutableList<OwnDeprecatedIcon> = ArrayList() fun getImageFlags(file: Path): ImageFlags { val isSkipped = !ignoreSkipTag && matches(file, skip) val isUsed = matches(file, used) val deprecationData = findDeprecatedData(file) val flags = ImageFlags(isSkipped, isUsed, deprecationData) val parentFlags = parent?.getImageFlags(file) ?: return flags return mergeImageFlags(flags, parentFlags, file.toString()) } fun getOwnDeprecatedIcons(): List<Pair<String, ImageFlags>> { return ownDeprecatedIcons.map { Pair(it.relativeFile, ImageFlags(false, false, it.data)) } } fun isSkipped(file: Path): Boolean { if (!ignoreSkipTag && matches(file, skip)) { return true } else { return parent?.isSkipped(file) ?: return false } } fun fork(dir: Path, root: Path): IconRobotsData { val robots = dir.resolve(ROBOTS_FILE_NAME) if (!robots.toFile().exists()) { return this } usedIconsRobots.add(robots) val answer = IconRobotsData(this) parse(robots, RobotFileHandler("skip:") { value -> answer.skip.add(compilePattern(dir, root, value)) }, RobotFileHandler("used:") { value -> answer.used.add(compilePattern(dir, root, value)) }, RobotFileHandler("deprecated:") { value -> val comment = StringUtil.nullize(value.substringAfter(";", "").trim()) val valueWithoutComment = value.substringBefore(";") val pattern = valueWithoutComment.substringBefore("->").trim() val replacementString = StringUtil.nullize(valueWithoutComment.substringAfter("->", "").trim()) val replacement = replacementString?.substringAfter('@')?.trim() val replacementContextClazz = StringUtil.nullize(replacementString?.substringBefore('@', "")?.trim()) val deprecatedData = DeprecationData(comment, replacement, replacementContextClazz, replacementReference = computeReplacementReference(comment)) answer.deprecated.add(DeprecatedEntry(compilePattern(dir, root, pattern), deprecatedData)) if (!pattern.contains('*') && !pattern.startsWith('/')) { answer.ownDeprecatedIcons.add(OwnDeprecatedIcon(pattern, deprecatedData)) } }, RobotFileHandler("name:") { _ -> }, // ignore directive for IconsClassGenerator RobotFileHandler("#") { _ -> } // comment ) return answer } private fun computeReplacementReference(comment: String?): String? { if (className == null) { return null } val result = StringUtil.nullize(comment?.substringAfter(" - use $className.", "")?.substringBefore(' ')?.trim()) ?: return null return "$className.$result" } private fun parse(robots: Path, vararg handlers: RobotFileHandler) { Files.lines(robots).forEach { line -> if (line.isBlank()) return@forEach for (h in handlers) { if (line.startsWith(h.start)) { h.handler(StringUtil.trimStart(line, h.start)) return@forEach } } throw Exception("Can't parse $robots. Line: $line") } } private fun compilePattern(dir: Path, root: Path, value: String): Pattern { var pattern = value.trim() if (pattern.startsWith('/')) { pattern = """${root.toAbsolutePath()}$pattern""" } else { pattern = "${dir.toAbsolutePath()}/$pattern" } val regExp = FileUtil.convertAntToRegexp(pattern, false) try { return Pattern.compile(regExp) } catch (e: Exception) { throw Exception("Cannot compile pattern: $pattern. Built on based in $dir/$ROBOTS_FILE_NAME") } } private fun findDeprecatedData(file: Path): DeprecationData? { val basicPath = getBasicPath(file) return deprecated.find { it.matcher.matcher(basicPath).matches() }?.data } private fun matches(file: Path, matchers: List<Pattern>): Boolean { if (matchers.isEmpty()) { return false } val basicPath = getBasicPath(file) return matchers.any { matcher -> try { matcher.matcher(basicPath).matches() } catch (e: Exception) { throw RuntimeException("cannot reset matcher ${matcher} with a new input $basicPath: $e") } } } private fun getBasicPath(file: Path): String { val path = FileUtil.toSystemIndependentName(file.toAbsolutePath().toString()) val pathWithoutExtension = FileUtilRt.getNameWithoutExtension(path) val extension = FileUtilRt.getExtension(path) val basicPathWithoutExtension = ImageType.stripSuffix(pathWithoutExtension) return basicPathWithoutExtension + if (extension.isNotEmpty()) ".$extension" else "" } } } private data class RobotFileHandler(val start: String, val handler: (String) -> Unit) private fun mergeImageFlags(flags1: ImageFlags, flags2: ImageFlags, comment: String): ImageFlags { return ImageFlags(flags1.skipped || flags2.skipped, flags1.used || flags2.used, mergeDeprecations(flags1.deprecation, flags2.deprecation, comment)) } private fun mergeDeprecations(data1: DeprecationData?, data2: DeprecationData?, comment: String): DeprecationData? { if (data1 == null) return data2 if (data2 == null) return data1 if (data1 == data2) return data1 throw AssertionError("Different deprecation statements found for icon: $comment\n$data1\n$data2") } fun Path.processChildren(isParallel: Boolean = true, consumer: (Path) -> Unit) { DirectorySpliterator.list(this, isParallel).use { it.forEach(consumer) } } // https://stackoverflow.com/a/34351591/1910191 private class DirectorySpliterator private constructor(iterator: Iterator<Path>, private var estimation: Long) : Spliterator<Path> { private var iterator: Iterator<Path>? = iterator companion object { // opposite to JDK, you don't need to close @Throws(IOException::class) fun list(parent: Path, isParallel: Boolean = true): Stream<Path> { val directoryStream = Files.newDirectoryStream(parent) val splitSize = Runtime.getRuntime().availableProcessors() + 1 return StreamSupport.stream(DirectorySpliterator(directoryStream.iterator(), splitSize.toLong()), isParallel) .onClose { directoryStream.close() } } } override fun tryAdvance(action: Consumer<in Path>): Boolean { val iterator = iterator if (iterator == null) { return false } val path = synchronized(iterator) { if (!iterator.hasNext()) { this.iterator = null return false } iterator.next() } action.accept(path) return true } override fun trySplit(): Spliterator<Path>? { val iterator = iterator if (iterator == null || estimation == 1L) { return null } val e = this.estimation.ushr(1) this.estimation -= e return DirectorySpliterator(iterator, e) } override fun estimateSize() = estimation override fun characteristics() = Spliterator.DISTINCT or Spliterator.NONNULL or Spliterator.IMMUTABLE }
apache-2.0
b1ff8d2d5419770b81c5d7537d319a9b
35.241463
176
0.671108
4.545427
false
false
false
false
kdwink/intellij-community
plugins/settings-repository/src/git/dirCacheEditor.kt
1
7834
/* * 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 org.jetbrains.jgit.dirCache import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import org.eclipse.jgit.dircache.BaseDirCacheEditor import org.eclipse.jgit.dircache.DirCache import org.eclipse.jgit.dircache.DirCacheEntry import org.eclipse.jgit.internal.JGitText import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.lib.FileMode import org.eclipse.jgit.lib.Repository import org.jetbrains.settingsRepository.byteBufferToBytes import org.jetbrains.settingsRepository.removeWithParentsIfEmpty import java.io.File import java.io.FileInputStream import java.text.MessageFormat import java.util.* private val EDIT_CMP = Comparator<org.jetbrains.jgit.dirCache.PathEdit> { o1, o2 -> val a = o1.path val b = o2.path DirCache.cmp(a, a.size, b, b.size) } /** * Don't copy edits, * DeletePath (renamed to DeleteFile) accepts raw path * Pass repository to apply */ public class DirCacheEditor(edits: List<PathEdit>, private val repository: Repository, dirCache: DirCache, estimatedNumberOfEntries: Int) : BaseDirCacheEditor(dirCache, estimatedNumberOfEntries) { private val edits = edits.sortedWith(EDIT_CMP) override fun commit(): Boolean { if (edits.isEmpty()) { // No changes? Don't rewrite the index. // cache.unlock() return true } return super.commit() } override fun finish() { if (!edits.isEmpty()) { applyEdits() replace() } } private fun applyEdits() { val maxIndex = cache.entryCount var lastIndex = 0 for (edit in edits) { var entryIndex = cache.findEntry(edit.path, edit.path.size) val missing = entryIndex < 0 if (entryIndex < 0) { entryIndex = -(entryIndex + 1) } val count = Math.min(entryIndex, maxIndex) - lastIndex if (count > 0) { fastKeep(lastIndex, count) } lastIndex = if (missing) entryIndex else cache.nextEntry(entryIndex) if (edit is DeleteFile) { continue } if (edit is DeleteDirectory) { lastIndex = cache.nextEntry(edit.path, edit.path.size, entryIndex) continue } if (missing) { val entry = DirCacheEntry(edit.path) edit.apply(entry, repository) if (entry.rawMode == 0) { throw IllegalArgumentException(MessageFormat.format(JGitText.get().fileModeNotSetForPath, entry.pathString)) } fastAdd(entry) } else if (edit is AddFile || edit is AddLoadedFile) { // apply to first entry and remove others var firstEntry = cache.getEntry(entryIndex) val entry: DirCacheEntry if (firstEntry.isMerged) { entry = firstEntry } else { entry = DirCacheEntry(edit.path) entry.creationTime = firstEntry.creationTime } edit.apply(entry, repository) fastAdd(entry) } else { // apply to all entries of the current path (different stages) for (i in entryIndex..lastIndex - 1) { val entry = cache.getEntry(i) edit.apply(entry, repository) fastAdd(entry) } } } val count = maxIndex - lastIndex if (count > 0) { fastKeep(lastIndex, count) } } } public interface PathEdit { val path: ByteArray public fun apply(entry: DirCacheEntry, repository: Repository) } abstract class PathEditBase(override final val path: ByteArray) : PathEdit private fun encodePath(path: String): ByteArray { val bytes = byteBufferToBytes(Constants.CHARSET.encode(path)) if (SystemInfo.isWindows) { for (i in 0..bytes.size - 1) { if (bytes[i].toChar() == '\\') { bytes[i] = '/'.toByte() } } } return bytes } class AddFile(private val pathString: String) : PathEditBase(encodePath(pathString)) { override fun apply(entry: DirCacheEntry, repository: Repository) { val file = File(repository.workTree, pathString) entry.fileMode = FileMode.REGULAR_FILE val length = file.length() entry.setLength(length) entry.lastModified = file.lastModified() val input = FileInputStream(file) val inserter = repository.newObjectInserter() try { entry.setObjectId(inserter.insert(Constants.OBJ_BLOB, length, input)) inserter.flush() } finally { inserter.close() input.close() } } } class AddLoadedFile(path: String, private val content: ByteArray, private val size: Int = content.size, private val lastModified: Long = System.currentTimeMillis()) : PathEditBase(encodePath(path)) { override fun apply(entry: DirCacheEntry, repository: Repository) { entry.fileMode = FileMode.REGULAR_FILE entry.length = size entry.lastModified = lastModified val inserter = repository.newObjectInserter() try { entry.setObjectId(inserter.insert(Constants.OBJ_BLOB, content, 0, size)) inserter.flush() } finally { inserter.close() } } } fun DeleteFile(path: String) = DeleteFile(encodePath(path)) public class DeleteFile(path: ByteArray) : PathEditBase(path) { override fun apply(entry: DirCacheEntry, repository: Repository) = throw UnsupportedOperationException(JGitText.get().noApplyInDelete) } public class DeleteDirectory(entryPath: String) : PathEditBase(encodePath(if (entryPath.endsWith('/') || entryPath.isEmpty()) entryPath else "$entryPath/")) { override fun apply(entry: DirCacheEntry, repository: Repository) = throw UnsupportedOperationException(JGitText.get().noApplyInDelete) } public fun Repository.edit(edit: PathEdit) { edit(listOf(edit)) } public fun Repository.edit(edits: List<PathEdit>) { if (edits.isEmpty()) { return } val dirCache = lockDirCache() try { DirCacheEditor(edits, this, dirCache, dirCache.entryCount + 4).commit() } finally { dirCache.unlock() } } private class DirCacheTerminator(dirCache: DirCache) : BaseDirCacheEditor(dirCache, 0) { override fun finish() { replace() } } public fun Repository.deleteAllFiles(deletedSet: MutableSet<String>? = null, fromWorkingTree: Boolean = true) { val dirCache = lockDirCache() try { if (deletedSet != null) { for (i in 0..dirCache.entryCount - 1) { val entry = dirCache.getEntry(i) if (entry.fileMode == FileMode.REGULAR_FILE) { deletedSet.add(entry.pathString) } } } DirCacheTerminator(dirCache).commit() } finally { dirCache.unlock() } if (fromWorkingTree) { val files = workTree.listFiles { file -> file.name != Constants.DOT_GIT } if (files != null) { for (file in files) { FileUtil.delete(file) } } } } public fun Repository.writePath(path: String, bytes: ByteArray, size: Int = bytes.size) { edit(AddLoadedFile(path, bytes, size)) FileUtil.writeToFile(File(workTree, path), bytes, 0, size) } public fun Repository.deletePath(path: String, isFile: Boolean = true, fromWorkingTree: Boolean = true) { edit((if (isFile) DeleteFile(path) else DeleteDirectory(path))) if (fromWorkingTree) { val workTree = workTree val ioFile = File(workTree, path) if (ioFile.exists()) { ioFile.removeWithParentsIfEmpty(workTree, isFile) } } }
apache-2.0
b8b4231c026b68a1525ee463beed75dd
29.019157
199
0.679602
4.065387
false
false
false
false
dahlstrom-g/intellij-community
platform/lang-api/src/com/intellij/refactoring/suggested/SignaturePresentationBuilder.kt
12
3315
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.refactoring.suggested import com.intellij.refactoring.suggested.SignatureChangePresentationModel.Effect import com.intellij.refactoring.suggested.SignatureChangePresentationModel.TextFragment import com.intellij.refactoring.suggested.SignatureChangePresentationModel.TextFragment.* import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Parameter import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Signature typealias ParameterFragmentsBuilder = ( fragments: MutableList<TextFragment>, parameter: Parameter, correspondingParameter: Parameter? ) -> Unit /** * Helper class to build presentation for one signature (either old or new). * * Note that presentation provided by this class is not the final presentation displayed to the user. * [SignatureChangePresentationModel.improvePresentation] is used to simplify its appearance: * * [Effect.Moved] should not be used, it's generated automatically based on connections between fragments (see [TextFragment.connectionId]) * * Only connections necessary to display moved elements are shown * @param signature signature (either old or new) to build presentation for * @param otherSignature other signature (either new or old) * @param isOldSignature true if [signature] represents the old signature, or false otherwise */ abstract class SignaturePresentationBuilder( protected val signature: Signature, protected val otherSignature: Signature, protected val isOldSignature: Boolean ) { protected val fragments = mutableListOf<TextFragment>() val result: List<TextFragment> get() = fragments abstract fun buildPresentation() protected fun effect(value: String, otherValue: String?): Effect { return if (otherValue.isNullOrEmpty()) { if (isOldSignature) Effect.Removed else Effect.Added } else { if (otherValue != value) Effect.Modified else Effect.None } } protected fun leaf(value: String, otherValue: String?): Leaf { val effect = effect(value, otherValue) return Leaf(value, effect) } @JvmOverloads protected fun buildParameterList(prefix: String = "(", suffix: String = ")", parameterBuilder: ParameterFragmentsBuilder) { fragments += Leaf(prefix) if (signature.parameters.isNotEmpty()) { fragments += LineBreak("", indentAfter = true) } for ((index, parameter) in signature.parameters.withIndex()) { if (index > 0) { fragments += Leaf(",") fragments += LineBreak(" ", indentAfter = true) } val correspondingParameter = otherSignature.parameterById(parameter.id) val connectionId = correspondingParameter?.id val effect = if (isOldSignature) { if (correspondingParameter == null) Effect.Removed else Effect.None } else { if (correspondingParameter == null) Effect.Added else Effect.None } fragments += Group( mutableListOf<TextFragment>().also { parameterBuilder(it, parameter, correspondingParameter) }, effect, connectionId ) } fragments += LineBreak("", indentAfter = false) fragments += Leaf(suffix) } }
apache-2.0
aba0bbf0528cf40e41a09ae3584e8f6a
36.681818
141
0.733635
4.962575
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/ActLanguageFilter.kt
1
16919
package jp.juggler.subwaytooter import android.annotation.SuppressLint import android.content.Intent import android.net.Uri import android.os.Bundle import android.os.PersistableBundle import android.os.Process import android.text.Editable import android.text.TextWatcher import android.view.View import android.view.ViewGroup import android.widget.* import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.content.FileProvider import jp.juggler.subwaytooter.api.entity.TootStatus import jp.juggler.subwaytooter.column.Column import jp.juggler.subwaytooter.dialog.ActionsDialog import jp.juggler.util.* import org.jetbrains.anko.textColor import java.io.File import java.io.FileOutputStream import java.util.* class ActLanguageFilter : AppCompatActivity(), View.OnClickListener { private class MyItem( val code: String, var allow: Boolean, ) companion object { internal val log = LogCategory("ActLanguageFilter") internal const val EXTRA_COLUMN_INDEX = "column_index" private const val STATE_LANGUAGE_LIST = "language_list" fun createIntent(activity: ActMain, idx: Int) = Intent(activity, ActLanguageFilter::class.java).apply { putExtra(EXTRA_COLUMN_INDEX, idx) } private val languageComparator = Comparator<MyItem> { a, b -> when { a.code == TootStatus.LANGUAGE_CODE_DEFAULT -> -1 b.code == TootStatus.LANGUAGE_CODE_DEFAULT -> 1 a.code == TootStatus.LANGUAGE_CODE_UNKNOWN -> -1 b.code == TootStatus.LANGUAGE_CODE_UNKNOWN -> 1 else -> a.code.compareTo(b.code) } } private fun equalsLanguageList(a: JsonObject?, b: JsonObject?): Boolean { fun JsonObject.encodeToString(): String { val clone = this.toString().decodeJsonObject() if (!clone.contains(TootStatus.LANGUAGE_CODE_DEFAULT)) { clone[TootStatus.LANGUAGE_CODE_DEFAULT] = true } return clone.keys.sorted().joinToString(",") { "$it=${this[it]}" } } val a_sign = (a ?: JsonObject()).encodeToString() val b_sign = (b ?: JsonObject()).encodeToString() return a_sign == b_sign } } private val languageNameMap by lazy { HashMap<String, String>().apply { // from https://github.com/google/cld3/blob/master/src/task_context_params.cc#L43 val languageNamesCld3 = arrayOf( "eo", "co", "eu", "ta", "de", "mt", "ps", "te", "su", "uz", "zh-Latn", "ne", "nl", "sw", "sq", "hmn", "ja", "no", "mn", "so", "ko", "kk", "sl", "ig", "mr", "th", "zu", "ml", "hr", "bs", "lo", "sd", "cy", "hy", "uk", "pt", "lv", "iw", "cs", "vi", "jv", "be", "km", "mk", "tr", "fy", "am", "zh", "da", "sv", "fi", "ht", "af", "la", "id", "fil", "sm", "ca", "el", "ka", "sr", "it", "sk", "ru", "ru-Latn", "bg", "ny", "fa", "haw", "gl", "et", "ms", "gd", "bg-Latn", "ha", "is", "ur", "mi", "hi", "bn", "hi-Latn", "fr", "yi", "hu", "xh", "my", "tg", "ro", "ar", "lb", "el-Latn", "st", "ceb", "kn", "az", "si", "ky", "mg", "en", "gu", "es", "pl", "ja-Latn", "ga", "lt", "sn", "yo", "pa", "ku" ) for (src1 in languageNamesCld3) { val src2 = src1.replace("-Latn", "") val isLatn = src2 != src1 val locale = Locale(src2) log.w("languageNameMap $src1 ${locale.language} ${locale.country} ${locale.displayName}") put( src1, if (isLatn) { "${locale.displayName}(Latn)" } else { locale.displayName } ) } put(TootStatus.LANGUAGE_CODE_DEFAULT, getString(R.string.language_code_default)) put(TootStatus.LANGUAGE_CODE_UNKNOWN, getString(R.string.language_code_unknown)) } } private fun getDesc(item: MyItem): String { val code = item.code return languageNameMap[code] ?: getString(R.string.custom) } private var columnIndex: Int = 0 internal lateinit var column: Column internal lateinit var appState: AppState internal var density: Float = 0f private lateinit var listView: ListView private lateinit var adapter: MyAdapter private val languageList = ArrayList<MyItem>() private var loadingBusy: Boolean = false private val arExport = ActivityResultHandler(log) { } private val arImport = ActivityResultHandler(log) { r -> if (r.isNotOk) return@ActivityResultHandler r.data?.handleGetContentResult(contentResolver) ?.firstOrNull()?.uri?.let { import2(it) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) backPressed { if (equalsLanguageList(column.languageFilter, encodeLanguageList())) { finish() } else { AlertDialog.Builder(this) .setMessage(R.string.language_filter_quit_waring) .setPositiveButton(R.string.ok) { _, _ -> finish() } .setNegativeButton(R.string.cancel, null) .show() } } arExport.register(this) arImport.register(this) App1.setActivityTheme(this) initUI() appState = App1.getAppState(this) density = appState.density columnIndex = intent.getIntExtra(EXTRA_COLUMN_INDEX, 0) column = appState.column(columnIndex)!! if (savedInstanceState != null) { try { val sv = savedInstanceState.getString(STATE_LANGUAGE_LIST, null) if (sv != null) { val list = sv.decodeJsonObject() load(list) return } } catch (ex: Throwable) { log.trace(ex) } } load(column.languageFilter) } override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) { super.onSaveInstanceState(outState, outPersistentState) outState.putString(STATE_LANGUAGE_LIST, encodeLanguageList().toString()) } private fun initUI() { setContentView(R.layout.act_language_filter) App1.initEdgeToEdge(this) Styler.fixHorizontalPadding(findViewById(R.id.llContent)) for (id in intArrayOf( R.id.btnAdd, R.id.btnSave, R.id.btnMore )) { findViewById<View>(id)?.setOnClickListener(this) } listView = findViewById(R.id.listView) adapter = MyAdapter() listView.adapter = adapter listView.onItemClickListener = adapter } // UIのデータをJsonObjectにエンコード private fun encodeLanguageList() = jsonObject { for (item in languageList) { put(item.code, item.allow) } } private fun load(src: JsonObject?) { loadingBusy = true try { languageList.clear() if (src != null) { for (key in src.keys) { languageList.add(MyItem(key, src.boolean(key) ?: true)) } } if (languageList.none { it.code == TootStatus.LANGUAGE_CODE_DEFAULT }) { languageList.add(MyItem(TootStatus.LANGUAGE_CODE_DEFAULT, true)) } languageList.sortWith(languageComparator) adapter.notifyDataSetChanged() } finally { loadingBusy = false } } private fun save() { column.languageFilter = encodeLanguageList() } private inner class MyAdapter : BaseAdapter(), AdapterView.OnItemClickListener { override fun getCount(): Int = languageList.size override fun getItemId(idx: Int): Long = 0L override fun getItem(idx: Int): Any = languageList[idx] override fun getView(idx: Int, viewArg: View?, parent: ViewGroup?): View { val tv = (viewArg ?: layoutInflater.inflate( R.layout.lv_language_filter, parent, false )) as TextView val item = languageList[idx] tv.text = "${item.code} ${getDesc(item)} : ${getString(if (item.allow) R.string.language_show else R.string.language_hide)}" tv.textColor = attrColor( when (item.allow) { true -> R.attr.colorContentText false -> R.attr.colorRegexFilterError } ) return tv } override fun onItemClick(parent: AdapterView<*>?, viewArg: View?, idx: Int, id: Long) { if (idx in languageList.indices) edit(languageList[idx]) } } override fun onClick(v: View) { when (v.id) { R.id.btnSave -> { save() val data = Intent() data.putExtra(EXTRA_COLUMN_INDEX, columnIndex) setResult(RESULT_OK, data) finish() } R.id.btnAdd -> edit(null) R.id.btnMore -> { ActionsDialog() .addAction(getString(R.string.clear_all)) { languageList.clear() languageList.add(MyItem(TootStatus.LANGUAGE_CODE_DEFAULT, true)) adapter.notifyDataSetChanged() } .addAction(getString(R.string.export)) { export() } .addAction(getString(R.string.import_)) { import() } .show(this) } } } private fun edit(myItem: MyItem?) = DlgLanguageFilter.open(this, myItem, object : DlgLanguageFilter.Callback { override fun onOK(code: String, allow: Boolean) { val it = languageList.iterator() while (it.hasNext()) { val item = it.next() if (item.code == code) { item.allow = allow adapter.notifyDataSetChanged() return } } languageList.add(MyItem(code, allow)) languageList.sortWith(languageComparator) adapter.notifyDataSetChanged() return } override fun onDelete(code: String) { val it = languageList.iterator() while (it.hasNext()) { val item = it.next() if (item.code == code) it.remove() } adapter.notifyDataSetChanged() } }) private object DlgLanguageFilter { interface Callback { fun onOK(code: String, allow: Boolean) fun onDelete(code: String) } @SuppressLint("InflateParams") fun open(activity: ActLanguageFilter, item: MyItem?, callback: Callback) { val view = activity.layoutInflater.inflate(R.layout.dlg_language_filter, null, false) val etLanguage: EditText = view.findViewById(R.id.etLanguage) val btnPresets: ImageButton = view.findViewById(R.id.btnPresets) val tvLanguage: TextView = view.findViewById(R.id.tvLanguage) val rbShow: RadioButton = view.findViewById(R.id.rbShow) val rbHide: RadioButton = view.findViewById(R.id.rbHide) when (item?.allow ?: true) { true -> rbShow.isChecked = true else -> rbHide.isChecked = true } fun updateDesc() { val code = etLanguage.text.toString().trim() val desc = activity.languageNameMap[code] ?: activity.getString(R.string.custom) tvLanguage.text = desc } val languageList = activity.languageNameMap.map { MyItem(it.key, true) }.sortedWith(languageComparator) btnPresets.setOnClickListener { val ad = ActionsDialog() for (a in languageList) { ad.addAction("${a.code} ${activity.getDesc(a)}") { etLanguage.setText(a.code) updateDesc() } } ad.show(activity, activity.getString(R.string.presets)) } etLanguage.setText(item?.code ?: "") updateDesc() etLanguage.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(p0: Editable?) { updateDesc() } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } }) if (item != null) { etLanguage.isEnabledAlpha = false btnPresets.setEnabledColor( activity, R.drawable.ic_edit, activity.attrColor(R.attr.colorVectorDrawable), false ) } val builder = AlertDialog.Builder(activity) .setView(view) .setCancelable(true) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.ok) { _, _ -> callback.onOK(etLanguage.text.toString().trim(), rbShow.isChecked) } if (item != null && item.code != TootStatus.LANGUAGE_CODE_DEFAULT) { builder.setNeutralButton(R.string.delete) { _, _ -> callback.onDelete(etLanguage.text.toString().trim()) } } builder.show() } } @Suppress("BlockingMethodInNonBlockingContext") private fun export() { launchProgress( "export language filter", doInBackground = { val data = JsonObject().apply { for (item in languageList) { put(item.code, item.allow) } } .toString() .encodeUTF8() val cacheDir = [email protected] cacheDir.mkdir() val file = File( cacheDir, "SubwayTooter-language-filter.${Process.myPid()}.${Process.myTid()}.json" ) FileOutputStream(file).use { it.write(data) } file }, afterProc = { val uri = FileProvider.getUriForFile( this@ActLanguageFilter, App1.FILE_PROVIDER_AUTHORITY, it ) val intent = Intent(Intent.ACTION_SEND) intent.type = contentResolver.getType(uri) intent.putExtra(Intent.EXTRA_SUBJECT, "SubwayTooter language filter data") intent.putExtra(Intent.EXTRA_STREAM, uri) intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION) arExport.launch(intent) } ) } private fun import() { arImport.launch(intentOpenDocument("*/*")) } @Suppress("BlockingMethodInNonBlockingContext") private fun import2(uri: Uri) { launchProgress( "import language filter", doInBackground = { log.d("import2 type=${contentResolver.getType(uri)}") try { contentResolver.openInputStream(uri)!!.use { it.readBytes().decodeUTF8().decodeJsonObject() } } catch (ex: Throwable) { showToast(ex, "openInputStream failed.") null } }, afterProc = { load(it) } ) } }
apache-2.0
0d42090b4c8d8c9acc558a34d226b91e
34.812636
130
0.509499
4.765087
false
false
false
false
ediTLJ/novelty
app/src/main/java/ro/edi/novelty/ui/InfoDialogFragment.kt
1
1876
/* * Copyright 2019 Eduard Scarlat * * 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 ro.edi.novelty.ui import android.app.Dialog import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.fragment.app.DialogFragment import com.google.android.material.dialog.MaterialAlertDialogBuilder import ro.edi.novelty.R import ro.edi.util.getAppVersionName class InfoDialogFragment : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { if (!isAdded) return super.onCreateDialog(savedInstanceState) val dialog = MaterialAlertDialogBuilder(requireActivity()) dialog.setTitle(R.string.app_name) dialog.setMessage(getString(R.string.info, getAppVersionName(requireActivity()))) dialog.setPositiveButton(R.string.btn_ok, null) dialog.setNegativeButton(R.string.btn_rate) { _, _ -> val i = Intent(Intent.ACTION_VIEW) i.flags = Intent.FLAG_ACTIVITY_NEW_TASK i.data = Uri.parse("market://details?id=ro.edi.novelty") startActivity(i) } // dialog.setNeutralButton(R.string.btn_other_apps) { _, _ -> // val i = Intent(Intent.ACTION_VIEW) // i.data = Uri.parse("market://search?q=pub:Eduard%20Scarlat") // startActivity(i) // } return dialog.create() } }
apache-2.0
4a272c9d96103a748bfab406a7a4d741
35.803922
89
0.705224
4.069414
false
false
false
false
Madrapps/Pikolo
pikolo/src/main/java/com/madrapps/pikolo/components/rgb/GreenComponent.kt
1
738
package com.madrapps.pikolo.components.rgb import android.graphics.Color import com.madrapps.pikolo.Metrics import com.madrapps.pikolo.Paints import com.madrapps.pikolo.components.ArcComponent internal class GreenComponent(metrics: Metrics, paints: Paints, arcLength: Float, arcStartAngle: Float) : ArcComponent(metrics, paints, arcLength, arcStartAngle) { override val componentIndex: Int = 1 override val range: Float = 255f override val noOfColors = 2 override val colors = IntArray(noOfColors) override val colorPosition = FloatArray(noOfColors) override fun getColorArray(color: FloatArray): IntArray { colors[0] = Color.BLACK colors[1] = Color.rgb(0, 255, 0) return colors } }
apache-2.0
442d3b59b627c23b282c43be65816ecf
34.190476
163
0.745257
3.746193
false
false
false
false
Pagejects/pagejects-core
src/test/kotlin/net/pagejects/core/impl/SelectorsTest.kt
1
1962
package net.pagejects.core.impl import net.pagejects.core.PagejectsManager import net.pagejects.core.error.CantFindSelectorOfElementException import net.pagejects.core.error.PageNotFoundException import org.openqa.selenium.By import org.openqa.selenium.support.How import org.testng.Assert.assertEquals import org.testng.annotations.AfterClass import org.testng.annotations.BeforeClass import org.testng.annotations.DataProvider import org.testng.annotations.Test @Test class SelectorsTest { private lateinit var browserGetter: () -> String private lateinit var selectorsFileName: String @BeforeClass fun setUp() { browserGetter = Selectors.cache.browserGetter selectorsFileName = PagejectsManager.instance.selectorsFileName PagejectsManager.instance.selectorsFileName = "classpath://test.yaml" Selectors.cache.browserGetter = { "chrome" } } @AfterClass fun tearDown() { Selectors.cache.browserGetter = browserGetter PagejectsManager.instance.selectorsFileName = selectorsFileName } @Test fun testGetElementSelector() { assertEquals(Selectors["page1", "element1"].selectBy, By.className(".test")) } @Test fun testGetPage() { assertEquals(Selectors["page1"], mapOf("element1" to Selector(How.CLASS_NAME, ".test"))) } @DataProvider(name = "dataForGetElementSelectorFailed") fun dataForGetElementSelectorFailed(): Array<Array<Any>> = arrayOf( arrayOf<Any>("page1", "no-element"), arrayOf<Any>("no-page", "element1") ) @Test(dataProvider = "dataForGetElementSelectorFailed", expectedExceptions = arrayOf(CantFindSelectorOfElementException::class)) fun testGetElementSelectorFailed(page: String, element: String) { Selectors[page, element] } @Test(expectedExceptions = arrayOf(PageNotFoundException::class)) fun testGetPageFailed() { Selectors["no-element"] } }
apache-2.0
232ccc1646bbdb70a00cd4ecc5c58068
32.271186
132
0.728338
4.5
false
true
false
false
paplorinc/intellij-community
python/src/com/jetbrains/python/run/PyVirtualEnvReader.kt
2
4408
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.run import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.SystemInfo import com.intellij.util.EnvironmentUtil import com.intellij.util.containers.ContainerUtil import com.jetbrains.python.packaging.PyCondaPackageService import com.jetbrains.python.sdk.PythonSdkType import java.io.File /** * @author traff */ class PyVirtualEnvReader(val virtualEnvSdkPath: String) : EnvironmentUtil.ShellEnvReader() { private val LOG = Logger.getInstance("#com.jetbrains.python.run.PyVirtualEnvReader") companion object { private val virtualEnvVars = listOf("PATH", "PS1", "VIRTUAL_ENV", "PYTHONHOME", "PROMPT", "_OLD_VIRTUAL_PROMPT", "_OLD_VIRTUAL_PYTHONHOME", "_OLD_VIRTUAL_PATH", "CONDA_SHLVL", "CONDA_PROMPT_MODIFIER", "CONDA_PREFIX", "CONDA_DEFAULT_ENV") /** * Filter envs that are setup by the activate script, adding other variables from the different shell can break the actual shell. */ fun filterVirtualEnvVars(env: Map<String, String>): Map<String, String> { return env.filterKeys { k -> virtualEnvVars.any { it.equals(k, true) } } } } // in case of Conda we need to pass an argument to an activate script that tells which exactly environment to activate val activate: Pair<String, String?>? = findActivateScript(virtualEnvSdkPath, shell) override fun getShell(): String? { if (File("/bin/bash").exists()) { return "/bin/bash" } else if (File("/bin/sh").exists()) { return "/bin/sh" } else { return super.getShell() } } fun readPythonEnv(): MutableMap<String, String> { try { if (SystemInfo.isUnix) { // pass shell environment for correct virtualenv environment setup (virtualenv expects to be executed from the terminal) return super.readShellEnv(EnvironmentUtil.getEnvironmentMap()) } else { if (activate != null) { return readBatEnv(File(activate.first), ContainerUtil.createMaybeSingletonList(activate.second)) } else { LOG.error("Can't find activate script for $virtualEnvSdkPath") } } } catch (e: Exception) { LOG.warn("Couldn't read shell environment: ${e.message}") } return mutableMapOf() } override fun getShellProcessCommand(): MutableList<String> { val shellPath = shell if (shellPath == null || !File(shellPath).canExecute()) { throw Exception("shell:" + shellPath) } return if (activate != null) { val activateArg = if (activate.second != null) "'${activate.first}' '${activate.second}'" else "'${activate.first}'" mutableListOf(shellPath, "-c", ". $activateArg") } else super.getShellProcessCommand() } } fun findActivateScript(sdkPath: String?, shellPath: String?): Pair<String, String?>? { if (PythonSdkType.isVirtualEnv(sdkPath)) { val shellName = if (shellPath != null) File(shellPath).name else null val activate = findActivateInPath(sdkPath!!, shellName) return if (activate != null && activate.exists()) { Pair(activate.absolutePath, null) } else null } else if (PythonSdkType.isConda(sdkPath)) { val condaExecutable = PyCondaPackageService.getCondaExecutable(sdkPath!!) if (condaExecutable != null) { val activate = findActivateInPath(File(condaExecutable).path, null) if (activate != null && activate.exists()) { return Pair(activate.path, condaEnvFolder(sdkPath)) } } } return null } private fun findActivateInPath(path: String, shellName: String?): File? { return if (SystemInfo.isWindows) findActivateOnWindows(path) else if (shellName == "fish" || shellName == "csh") File(File(path).parentFile, "activate.$shellName") else File(File(path).parentFile, "activate") } private fun condaEnvFolder(path: String?) = if (SystemInfo.isWindows) File(path).parent else File(path).parentFile.parent private fun findActivateOnWindows(path: String?): File? { for (location in arrayListOf("activate.bat", "Scripts/activate.bat")) { val file = File(File(path).parentFile, location) if (file.exists()) { return file } } return null }
apache-2.0
d91f16a6efc3691f1cab606bd06b7dac
33.992063
140
0.673321
4.092851
false
false
false
false
paplorinc/intellij-community
plugins/git4idea/tests/git4idea/update/GitComplexSubmoduleTest.kt
5
7023
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.update import com.intellij.dvcs.DvcsUtil.getPushSupport import com.intellij.dvcs.DvcsUtil.getShortRepositoryName import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtil.getRelativePath import com.intellij.openapi.vcs.Executor.cd import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile import git4idea.push.GitPushOperation import git4idea.push.GitPushSupport import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import git4idea.repo.GitSubmoduleInfo import git4idea.test.* import java.io.File import java.util.* /** * Main project with 3 submodules, one of which is a submodule of another. * ``` * project * |.git/ * |alib/ * | |younger/ * | | |.git * |elder/ * | |.git * | |grandchild/ * | | |.git * ``` */ class GitComplexSubmoduleTest : GitSubmoduleTestBase() { private lateinit var mainRepo: GitRepository private lateinit var elderRepo: GitRepository private lateinit var youngerRepo: GitRepository private lateinit var grandchildRepo: GitRepository private lateinit var grandchild: RepositoryAndParent private lateinit var elder: RepositoryAndParent private lateinit var younger: RepositoryAndParent private lateinit var main: RepositoryAndParent override fun setUp() { super.setUp() setUpRepositoryStructure() repositoryManager.updateAllRepositories() } fun `test submodules are properly detected`() { assertNoSubmodules(grandchildRepo) assertNoSubmodules(youngerRepo) assertSubmodules(elderRepo, listOf(grandchildRepo)) assertSubmodules(mainRepo, listOf(elderRepo, youngerRepo)) } fun `test dependency comparator`() { val comparator = GitRepositoryManager.DEPENDENCY_COMPARATOR infix operator fun GitRepository.compareTo(other: GitRepository) = comparator.compare(this, other) //Expected: grandchild <- younger <- elder <- main assertTrue(grandchildRepo < elderRepo) assertTrue(grandchildRepo < mainRepo) assertTrue("grandchild must be < youngerRepo to conform transitivity", grandchildRepo < youngerRepo) assertTrue(elderRepo < mainRepo) assertTrue("repos of the same level of submodularity must be compared by path", elderRepo > youngerRepo) assertTrue(mainRepo > youngerRepo) assertOrderedEquals(allRepositories().sortedWith(comparator), orderedRepositories()) } fun `test submodules are pushed before superprojects`() { allRepositories().forEach { cd(it) tac("f.txt") } val pushSpecs = allRepositories().map { it to makePushSpec(it, "master", "origin/master") }.toMap() val reposInActualOrder = mutableListOf<GitRepository>() git.pushListener = { reposInActualOrder.add(it) } GitPushOperation(project, getPushSupport(vcs) as GitPushSupport, pushSpecs, null, false, false).execute() assertOrder(reposInActualOrder) } private fun setUpRepositoryStructure() { // create separate git local and remote repositories outside of the project grandchild = createPlainRepo("grandchild") younger = createPlainRepo("younger") elder = createPlainRepo("elder") addSubmodule(elder.local, grandchild.remote) // setup project mainRepo = createRepository(projectPath) val parent = prepareRemoteRepo(mainRepo) git("push -u origin master") main = RepositoryAndParent("parent", File(projectPath), parent) elderRepo = addSubmoduleInProject(elder.remote, elder.name) youngerRepo = addSubmoduleInProject(younger.remote, younger.name, "alib/younger") mainRepo.git("submodule update --init --recursive") // this initializes the grandchild submodule grandchildRepo = registerRepo(project, "${projectPath}/elder/grandchild") cd(grandchildRepo) setupDefaultUsername() grandchildRepo.git("checkout master") // git submodule is initialized in detached HEAD state by default } /** * Adds the submodule to the given repository, pushes this change to the upstream, * and registers the repository as a VCS mapping. */ private fun addSubmoduleInProject(submoduleUrl: File, moduleName: String, relativePath: String? = null): GitRepository { addSubmodule(File(projectPath), submoduleUrl, relativePath) val rootPath = "${projectPath}/${relativePath ?: moduleName}" cd(rootPath) refresh(LocalFileSystem.getInstance().refreshAndFindFileByPath(rootPath)!!) setupDefaultUsername() return registerRepo(project, rootPath) } // second clone of the whole project with submodules private fun prepareSecondClone(): File { cd(testRoot) git("clone --recurse-submodules parent.git bro") val broDir = File(testRoot, "bro") cd(broDir) setupDefaultUsername() return broDir } private fun commitAndPushFromSecondClone(bro: File) { listOf(grandchild.local, elder.local, younger.local, bro).forEach { cd(it) tacp("g.txt") } } private fun assertSubmodules(repo: GitRepository, expectedSubmodules: List<GitRepository>) { assertSubmodulesInfo(repo, expectedSubmodules) assertSameElements("Submodules identified incorrectly for ${getShortRepositoryName(repo)}", repositoryManager.getDirectSubmodules(repo), expectedSubmodules) } private fun assertSubmodulesInfo(repo: GitRepository, expectedSubmodules: List<GitRepository>) { val expectedInfos = expectedSubmodules.map { val url = it.remotes.first().firstUrl!! GitSubmoduleInfo(FileUtil.toSystemIndependentName(getRelativePath(virtualToIoFile(repo.root), virtualToIoFile(it.root))!!), url) } assertSameElements("Submodules were read incorrectly for ${getShortRepositoryName(repo)}", repo.submodules, expectedInfos) } private fun assertNoSubmodules(repo: GitRepository) { assertTrue("No submodules expected, but found: ${repo.submodules}", repo.submodules.isEmpty()) } private fun assertOrder(reposInActualOrder: List<GitRepository>) { assertOrderedEquals("Repositories were processed in incorrect order", reposInActualOrder, orderedRepositories()) } private fun allRepositories(): List<GitRepository> { val list = mutableListOf(grandchildRepo, elderRepo, youngerRepo, mainRepo) Collections.shuffle(list) return list } private fun orderedRepositories() = listOf(grandchildRepo, youngerRepo, elderRepo, mainRepo) }
apache-2.0
0b54f5a18fe76a7543d694d51d028f75
35.769634
134
0.74612
4.411432
false
false
false
false
google/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/timeline/GHPRTimelineItemComponentFactory.kt
6
12915
// 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.ui.timeline import com.intellij.collaboration.async.CompletableFutureUtil.successOnEdt import com.intellij.collaboration.ui.codereview.timeline.TimelineItemComponentFactory import com.intellij.icons.AllIcons import com.intellij.ide.BrowserUtil import com.intellij.ide.plugins.newui.HorizontalLayout import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.project.Project import com.intellij.ui.components.ActionLink import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.components.labels.LinkListener import com.intellij.ui.components.panels.HorizontalBox import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.components.panels.VerticalLayout import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBDimension import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import org.intellij.lang.annotations.Language import org.jetbrains.plugins.github.GithubIcons import org.jetbrains.plugins.github.api.data.GHActor import org.jetbrains.plugins.github.api.data.GHGitActor import org.jetbrains.plugins.github.api.data.GHIssueComment import org.jetbrains.plugins.github.api.data.GHUser import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequest import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestCommitShort import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReview import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReviewState.* import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineEvent import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineItem import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.pullrequest.comment.convertToHtml import org.jetbrains.plugins.github.pullrequest.comment.ui.GHPRReviewThreadComponent import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRCommentsDataProvider import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRDetailsDataProvider import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRReviewDataProvider import org.jetbrains.plugins.github.pullrequest.ui.GHEditableHtmlPaneHandle import org.jetbrains.plugins.github.pullrequest.ui.GHTextActions import org.jetbrains.plugins.github.pullrequest.ui.changes.GHPRSuggestedChangeHelper import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider import org.jetbrains.plugins.github.ui.util.GHUIUtil import org.jetbrains.plugins.github.ui.util.HtmlEditorPane import java.awt.Dimension import java.util.* import javax.swing.* import kotlin.math.ceil import kotlin.math.floor class GHPRTimelineItemComponentFactory(private val project: Project, private val detailsDataProvider: GHPRDetailsDataProvider, private val commentsDataProvider: GHPRCommentsDataProvider, private val reviewDataProvider: GHPRReviewDataProvider, private val avatarIconsProvider: GHAvatarIconsProvider, private val reviewsThreadsModelsProvider: GHPRReviewsThreadsModelsProvider, private val reviewDiffComponentFactory: GHPRReviewThreadDiffComponentFactory, private val eventComponentFactory: GHPRTimelineEventComponentFactory<GHPRTimelineEvent>, private val selectInToolWindowHelper: GHPRSelectInToolWindowHelper, private val suggestedChangeHelper: GHPRSuggestedChangeHelper, private val currentUser: GHUser) : TimelineItemComponentFactory<GHPRTimelineItem> { override fun createComponent(item: GHPRTimelineItem): Item { try { return when (item) { is GHPullRequestCommitShort -> createComponent(item) is GHIssueComment -> createComponent(item) is GHPullRequestReview -> createComponent(item) is GHPRTimelineEvent -> eventComponentFactory.createComponent(item) is GHPRTimelineItem.Unknown -> throw IllegalStateException("Unknown item type: " + item.__typename) else -> error("Undefined item type") } } catch (e: Exception) { LOG.warn(e) return Item(AllIcons.General.Warning, HtmlEditorPane(GithubBundle.message("cannot.display.item", e.message ?: ""))) } } private fun createComponent(commit: GHPullRequestCommitShort): Item { val gitCommit = commit.commit val titlePanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(8))).apply { add(userAvatar(gitCommit.author)) add(HtmlEditorPane(gitCommit.messageHeadlineHTML)) add(ActionLink(gitCommit.abbreviatedOid) { selectInToolWindowHelper.selectCommit(gitCommit.abbreviatedOid) }) } return Item(AllIcons.Vcs.CommitNode, titlePanel) } fun createComponent(details: GHPullRequestShort): Item { val contentPanel: JPanel? val actionsPanel: JPanel? if (details is GHPullRequest) { val textPane = HtmlEditorPane(details.body.convertToHtml(project)) val panelHandle = GHEditableHtmlPaneHandle(project, textPane, details::body) { newText -> detailsDataProvider.updateDetails(EmptyProgressIndicator(), description = newText) .successOnEdt { textPane.setBody(it.body.convertToHtml(project)) } } contentPanel = panelHandle.panel actionsPanel = if (details.viewerCanUpdate) NonOpaquePanel(HorizontalLayout(JBUIScale.scale(8))).apply { add(GHTextActions.createEditButton(panelHandle)) } else null } else { contentPanel = null actionsPanel = null } val titlePanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(12))).apply { add(actionTitle(details.author, GithubBundle.message("pull.request.timeline.created"), details.createdAt)) if (actionsPanel != null && actionsPanel.componentCount > 0) add(actionsPanel) } return Item(userAvatar(details.author), titlePanel, contentPanel) } private fun createComponent(comment: GHIssueComment): Item { val textPane = HtmlEditorPane(comment.body.convertToHtml(project)) val panelHandle = GHEditableHtmlPaneHandle(project, textPane, comment::body) { newText -> commentsDataProvider.updateComment(EmptyProgressIndicator(), comment.id, newText) .successOnEdt { textPane.setBody(it.convertToHtml(project)) } } val actionsPanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(8))).apply { if (comment.viewerCanUpdate) add(GHTextActions.createEditButton(panelHandle)) if (comment.viewerCanDelete) add(GHTextActions.createDeleteButton { commentsDataProvider.deleteComment(EmptyProgressIndicator(), comment.id) }) } val titlePanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(12))).apply { add(actionTitle(comment.author, GithubBundle.message("pull.request.timeline.commented"), comment.createdAt)) if (actionsPanel.componentCount > 0) add(actionsPanel) } return Item(userAvatar(comment.author), titlePanel, panelHandle.panel) } private fun createComponent(review: GHPullRequestReview): Item { val reviewThreadsModel = reviewsThreadsModelsProvider.getReviewThreadsModel(review.id) val panelHandle: GHEditableHtmlPaneHandle? if (review.body.isNotEmpty()) { val textPane = HtmlEditorPane(review.body.convertToHtml(project)) panelHandle = GHEditableHtmlPaneHandle(project, textPane, review::body, { newText -> reviewDataProvider.updateReviewBody(EmptyProgressIndicator(), review.id, newText) .successOnEdt { textPane.setBody(it.convertToHtml(project)) } }) } else { panelHandle = null } val actionsPanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(8))).apply { if (panelHandle != null && review.viewerCanUpdate) add(GHTextActions.createEditButton(panelHandle)) } val contentPanel = NonOpaquePanel(VerticalLayout(12)).apply { border = JBUI.Borders.emptyTop(4) if (panelHandle != null) add(panelHandle.panel) add(GHPRReviewThreadsPanel.create(reviewThreadsModel) { GHPRReviewThreadComponent.createWithDiff(project, it, reviewDataProvider, avatarIconsProvider, reviewDiffComponentFactory, selectInToolWindowHelper, suggestedChangeHelper, currentUser) }) } val actionText = when (review.state) { APPROVED -> GithubBundle.message("pull.request.timeline.approved.changes") CHANGES_REQUESTED -> GithubBundle.message("pull.request.timeline.requested.changes") PENDING -> GithubBundle.message("pull.request.timeline.started.review") COMMENTED, DISMISSED -> GithubBundle.message("pull.request.timeline.reviewed") } val titlePanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(12))).apply { add(actionTitle(avatarIconsProvider, review.author, actionText, review.createdAt)) if (actionsPanel.componentCount > 0) add(actionsPanel) } val icon = when (review.state) { APPROVED -> GithubIcons.ReviewAccepted CHANGES_REQUESTED -> GithubIcons.ReviewRejected COMMENTED -> GithubIcons.Review DISMISSED -> GithubIcons.Review PENDING -> GithubIcons.Review } return Item(icon, titlePanel, contentPanel, NOT_DEFINED_SIZE) } private fun userAvatar(user: GHActor?): JLabel { return userAvatar(avatarIconsProvider, user) } private fun userAvatar(user: GHGitActor?): JLabel { return LinkLabel<Any>("", avatarIconsProvider.getIcon(user?.avatarUrl), LinkListener { _, _ -> user?.url?.let { BrowserUtil.browse(it) } }) } class Item(val marker: JLabel, title: JComponent, content: JComponent? = null, size: Dimension = getDefaultSize()) : JPanel() { constructor(markerIcon: Icon, title: JComponent, content: JComponent? = null, size: Dimension = getDefaultSize()) : this(createMarkerLabel(markerIcon), title, content, size) init { isOpaque = false layout = MigLayout(LC().gridGap("0", "0") .insets("0", "0", "0", "0") .fill()).apply { columnConstraints = "[]${JBUIScale.scale(8)}[]" } add(marker, CC().pushY()) add(title, CC().pushX()) if (content != null) add(content, CC().newline().skip().grow().push().maxWidth(size)) } companion object { private fun CC.maxWidth(dimension: Dimension) = if (dimension.width > 0) this.maxWidth("${dimension.width}") else this private fun createMarkerLabel(markerIcon: Icon) = JLabel(markerIcon).apply { val verticalGap = if (markerIcon.iconHeight < 20) (20f - markerIcon.iconHeight) / 2 else 0f val horizontalGap = if (markerIcon.iconWidth < 20) (20f - markerIcon.iconWidth) / 2 else 0f border = JBUI.Borders.empty(floor(verticalGap).toInt(), floor(horizontalGap).toInt(), ceil(verticalGap).toInt(), ceil(horizontalGap).toInt()) } } } companion object { private val LOG = logger<GHPRTimelineItemComponentFactory>() private val NOT_DEFINED_SIZE = Dimension(-1, -1) fun getDefaultSize() = Dimension(GHUIUtil.getPRTimelineWidth(), -1) fun userAvatar(avatarIconsProvider: GHAvatarIconsProvider, user: GHActor?): JLabel { return LinkLabel<Any>("", avatarIconsProvider.getIcon(user?.avatarUrl), LinkListener { _, _ -> user?.url?.let { BrowserUtil.browse(it) } }) } fun actionTitle(avatarIconsProvider: GHAvatarIconsProvider, actor: GHActor?, @Language("HTML") actionHTML: String, date: Date) : JComponent { return HorizontalBox().apply { add(userAvatar(avatarIconsProvider, actor)) add(Box.createRigidArea(JBDimension(8, 0))) add(actionTitle(actor, actionHTML, date)) } } fun actionTitle(actor: GHActor?, actionHTML: String, date: Date): JComponent { //language=HTML val text = """<a href='${actor?.url}'>${actor?.login ?: "unknown"}</a> $actionHTML ${GHUIUtil.formatActionDate(date)}""" return HtmlEditorPane(text).apply { foreground = UIUtil.getContextHelpForeground() } } } }
apache-2.0
1c3319255354d087b5b6d924c055477b
46.837037
140
0.713899
4.925629
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/SegmentedButtonImpl.kt
3
5332
// 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.ui.dsl.builder.impl import com.intellij.openapi.Disposable import com.intellij.openapi.observable.properties.ObservableMutableProperty import com.intellij.openapi.observable.properties.ObservableProperty import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.DialogPanel import com.intellij.ui.dsl.builder.RightGap import com.intellij.ui.dsl.builder.SegmentedButton import com.intellij.ui.dsl.builder.SpacingConfiguration import com.intellij.ui.dsl.gridLayout.Constraints import com.intellij.ui.dsl.gridLayout.Gaps import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.dsl.gridLayout.VerticalAlign import com.intellij.ui.layout.* import com.intellij.openapi.observable.util.bind import com.intellij.openapi.observable.util.whenItemSelected import com.intellij.openapi.observable.util.whenItemSelectedFromUi import com.intellij.ui.dsl.builder.components.SegmentedButtonComponent import com.intellij.ui.dsl.builder.components.SegmentedButtonComponent.Companion.bind import com.intellij.ui.dsl.builder.components.SegmentedButtonComponent.Companion.whenItemSelected import com.intellij.ui.dsl.builder.components.SegmentedButtonComponent.Companion.whenItemSelectedFromUi import com.intellij.util.ui.accessibility.ScreenReader import org.jetbrains.annotations.ApiStatus import javax.swing.DefaultComboBoxModel @ApiStatus.Internal internal class SegmentedButtonImpl<T>(parent: RowImpl, private val renderer: (T) -> String) : PlaceholderBaseImpl<SegmentedButton<T>>(parent), SegmentedButton<T> { private var items: Collection<T> = emptyList() private var property: ObservableProperty<T>? = null private var maxButtonsCount = SegmentedButton.DEFAULT_MAX_BUTTONS_COUNT private val comboBox = ComboBox<T>() private val segmentedButtonComponent = SegmentedButtonComponent(items, renderer) init { comboBox.renderer = listCellRenderer { value, _, _ -> text = renderer(value) } segmentedButtonComponent.isOpaque = false rebuild() } override fun horizontalAlign(horizontalAlign: HorizontalAlign): SegmentedButton<T> { super.horizontalAlign(horizontalAlign) return this } override fun verticalAlign(verticalAlign: VerticalAlign): SegmentedButton<T> { super.verticalAlign(verticalAlign) return this } override fun resizableColumn(): SegmentedButton<T> { super.resizableColumn() return this } override fun gap(rightGap: RightGap): SegmentedButton<T> { super.gap(rightGap) return this } override fun enabled(isEnabled: Boolean): SegmentedButton<T> { super.enabled(isEnabled) return this } override fun visible(isVisible: Boolean): SegmentedButton<T> { super.visible(isVisible) return this } override fun customize(customGaps: Gaps): SegmentedButton<T> { super.customize(customGaps) return this } override fun items(items: Collection<T>): SegmentedButton<T> { this.items = items rebuild() return this } override fun bind(property: ObservableMutableProperty<T>): SegmentedButton<T> { this.property = property comboBox.bind(property) segmentedButtonComponent.bind(property) rebuild() return this } override fun whenItemSelected(parentDisposable: Disposable?, listener: (T) -> Unit): SegmentedButton<T> { comboBox.whenItemSelected(parentDisposable, listener) segmentedButtonComponent.whenItemSelected(parentDisposable, listener) return this } override fun whenItemSelectedFromUi(parentDisposable: Disposable?, listener: (T) -> Unit): SegmentedButton<T> { comboBox.whenItemSelectedFromUi(parentDisposable, listener) segmentedButtonComponent.whenItemSelectedFromUi(parentDisposable, listener) return this } override fun maxButtonsCount(value: Int): SegmentedButton<T> { maxButtonsCount = value rebuild() return this } override fun init(panel: DialogPanel, constraints: Constraints, spacing: SpacingConfiguration) { super.init(panel, constraints, spacing) segmentedButtonComponent.spacing = spacing } private fun rebuild() { if (ScreenReader.isActive() || items.size > maxButtonsCount) { fillComboBox() component = comboBox } else { fillSegmentedButtonComponent() component = segmentedButtonComponent } } private fun fillComboBox() { val selectedItem = getSelectedItem() val model = DefaultComboBoxModel<T>() model.addAll(items) comboBox.model = model if (selectedItem != null && items.contains(selectedItem)) { comboBox.selectedItem = selectedItem } } private fun fillSegmentedButtonComponent() { val selectedItem = getSelectedItem() segmentedButtonComponent.items = items if (selectedItem != null && items.contains(selectedItem)) { segmentedButtonComponent.selectedItem = selectedItem } } private fun getSelectedItem(): T? { val result = property?.get() if (result != null) { return result } val c = component @Suppress("UNCHECKED_CAST") return when (c) { comboBox -> comboBox.selectedItem as? T segmentedButtonComponent -> segmentedButtonComponent.selectedItem else -> null } } }
apache-2.0
8fa1fd14e95fb911bbe7159deb320b38
32.325
120
0.757502
4.70194
false
false
false
false
denzelby/telegram-bot-bumblebee
telegram-bot-bumblebee-core/src/main/kotlin/com/github/bumblebee/command/statistics/MessageStatisticsHandler.kt
2
1218
package com.github.bumblebee.command.statistics import com.github.bumblebee.command.ChainedMessageListener import com.github.bumblebee.command.statistics.service.StatisticsService import com.github.bumblebee.util.logger import com.github.telegram.domain.ChatType import com.github.telegram.domain.Update import org.springframework.context.annotation.DependsOn import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import java.time.LocalDate @Component @DependsOn("timeZoneConfig") class MessageStatisticsHandler(private val statistics: StatisticsService) : ChainedMessageListener() { override fun onMessage(chatId: Long, message: String?, update: Update): Boolean { val msg = update.message ?: return false val from = msg.from if (from == null || from.isBot || msg.chat.type == ChatType.private) { return false } statistics.handleMessage(msg, from) return false } @Scheduled(cron = "0 00 00 * * *") fun cleanup() { val now = LocalDate.now() logger<MessageStatisticsHandler>().info("Statistics cleanup, current date: $now") statistics.cleanupStats(now) } }
mit
d73e35ca1a272bcfce15b9c53d0b2393
34.823529
102
0.73399
4.445255
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/RemoveExplicitTypeIntention.kt
1
8028
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.k2.codeinsight.intentions import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.calls.singleFunctionCallOrNull import org.jetbrains.kotlin.analysis.api.calls.symbol import org.jetbrains.kotlin.analysis.api.components.DefaultTypeClassIds import org.jetbrains.kotlin.analysis.api.components.KtConstantEvaluationMode import org.jetbrains.kotlin.analysis.api.components.buildClassType import org.jetbrains.kotlin.analysis.api.symbols.KtTypeParameterSymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithVisibility import org.jetbrains.kotlin.analysis.api.types.KtNonErrorClassType import org.jetbrains.kotlin.analysis.api.types.KtType import org.jetbrains.kotlin.analysis.api.types.KtTypeParameterType import org.jetbrains.kotlin.config.AnalysisFlags import org.jetbrains.kotlin.config.ExplicitApiMode import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.base.psi.textRangeIn import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.applicators.* import org.jetbrains.kotlin.idea.codeinsight.utils.getClassId import org.jetbrains.kotlin.idea.codeinsight.utils.isAnnotatedDeep import org.jetbrains.kotlin.idea.codeinsight.utils.isSetterParameter import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset class RemoveExplicitTypeIntention : AbstractKotlinApplicatorBasedIntention<KtDeclaration, KotlinApplicatorInput.Empty>( KtDeclaration::class ) { override fun getApplicator(): KotlinApplicator<KtDeclaration, KotlinApplicatorInput.Empty> = applicator { familyAndActionName(KotlinBundle.lazyMessage("remove.explicit.type.specification")) isApplicableByPsi { declaration -> when { declaration.typeReference == null || declaration.typeReference?.isAnnotatedDeep() == true -> false declaration is KtParameter -> declaration.isLoopParameter || declaration.isSetterParameter declaration is KtNamedFunction -> true declaration is KtProperty || declaration is KtPropertyAccessor -> declaration.getInitializerOrGetterInitializer() != null else -> false } } applyTo { declaration, _ -> declaration.removeTypeReference() } } override fun getApplicabilityRange(): KotlinApplicabilityRange<KtDeclaration> = applicabilityRanges ranges@{ declaration -> val typeReference = declaration.typeReference ?: return@ranges emptyList() if (declaration is KtParameter && declaration.isSetterParameter) { return@ranges listOf(typeReference.textRangeIn(declaration)) } val typeReferenceRelativeEndOffset = typeReference.endOffset - declaration.startOffset listOf(TextRange(0, typeReferenceRelativeEndOffset)) } override fun getInputProvider(): KotlinApplicatorInputProvider<KtDeclaration, KotlinApplicatorInput.Empty> = inputProvider { declaration -> when { declaration is KtParameter -> KotlinApplicatorInput.Empty declaration is KtNamedFunction && declaration.hasBlockBody() -> if (declaration.getReturnKtType().isUnit) KotlinApplicatorInput.Empty else null declaration is KtCallableDeclaration && publicReturnTypeShouldBePresentInApiMode(declaration) -> null explicitTypeMightBeNeededForCorrectTypeInference(declaration) -> null else -> KotlinApplicatorInput.Empty } } private val KtDeclaration.typeReference: KtTypeReference? get() = when (this) { is KtCallableDeclaration -> typeReference is KtPropertyAccessor -> returnTypeReference else -> null } private fun KtDeclaration.removeTypeReference() { if (this is KtCallableDeclaration) { typeReference = null } else if (this is KtPropertyAccessor) { val first = rightParenthesis?.nextSibling ?: return val last = returnTypeReference ?: return deleteChildRange(first, last) } } private fun KtDeclaration.getInitializerOrGetterInitializer(): KtExpression? { if (this is KtDeclarationWithInitializer && initializer != null) return initializer return (this as? KtProperty)?.getter?.initializer } private val KtDeclaration.isVar: Boolean get() { val property = (this as? KtProperty) ?: (this as? KtPropertyAccessor)?.property return property?.isVar == true } private fun KtAnalysisSession.publicReturnTypeShouldBePresentInApiMode(declaration: KtCallableDeclaration): Boolean { if (declaration.languageVersionSettings.getFlag(AnalysisFlags.explicitApiMode) == ExplicitApiMode.DISABLED) return false if (declaration.containingClassOrObject?.isLocal == true) return false if (declaration is KtFunction && declaration.isLocal) return false if (declaration is KtProperty && declaration.isLocal) return false val symbolWithVisibility = declaration.getSymbol() as? KtSymbolWithVisibility ?: return false return isPublicApi(symbolWithVisibility) } private fun KtAnalysisSession.explicitTypeMightBeNeededForCorrectTypeInference(declaration: KtDeclaration): Boolean { val initializer = declaration.getInitializerOrGetterInitializer() ?: return true val initializerType = getInitializerTypeIfContextIndependent(initializer) ?: return true val explicitType = declaration.getReturnKtType() val typeCanBeRemoved = if (declaration.isVar) { initializerType.isEqualTo(explicitType) } else { initializerType.isSubTypeOf(explicitType) } return !typeCanBeRemoved } private fun KtAnalysisSession.getInitializerTypeIfContextIndependent(initializer: KtExpression): KtType? { return when (initializer) { is KtStringTemplateExpression -> buildClassType(DefaultTypeClassIds.STRING) is KtConstantExpression -> initializer.getClassId()?.let { buildClassType(it) } is KtCallExpression -> { val isNotContextFree = initializer.typeArgumentList == null && returnTypeOfCallDependsOnTypeParameters(initializer) if (isNotContextFree) null else initializer.getKtType() } else -> { // get type for expressions that a compiler views as constants, e.g. `1 + 2` val evaluatedConstant = initializer.evaluate(KtConstantEvaluationMode.CONSTANT_EXPRESSION_EVALUATION) if (evaluatedConstant != null) initializer.getKtType() else null } } } private fun KtAnalysisSession.returnTypeOfCallDependsOnTypeParameters(callExpression: KtCallExpression): Boolean { val call = callExpression.resolveCall().singleFunctionCallOrNull() ?: return true val callSymbol = call.partiallyAppliedSymbol.symbol val typeParameters = callSymbol.typeParameters val returnType = callSymbol.returnType return typeParameters.any { typeReferencesTypeParameter(it, returnType) } } private fun KtAnalysisSession.typeReferencesTypeParameter(typeParameter: KtTypeParameterSymbol, type: KtType): Boolean { return when (type) { is KtTypeParameterType -> type.symbol == typeParameter is KtNonErrorClassType -> type.ownTypeArguments.mapNotNull { it.type }.any { typeReferencesTypeParameter(typeParameter, it) } else -> false } } }
apache-2.0
c09f93bb5b4fecf57dd297183c0d4901
50.140127
137
0.726956
5.625788
false
false
false
false
pledbrook/lazybones-kotlin
lazybones-app/src/main/kotlin/uk/co/cacoethes/lazybones/LazybonesScript.kt
1
14622
package uk.co.cacoethes.lazybones import groovy.io.FileType import groovy.lang.Script import groovy.lang.Writable import groovy.text.SimpleTemplateEngine import groovy.text.TemplateEngine import org.apache.commons.io.FilenameUtils import uk.co.cacoethes.lazybones.util.AntPathMatcher import uk.co.cacoethes.lazybones.util.NameType import uk.co.cacoethes.lazybones.util.Naming import java.io.* import java.lang.reflect.Method import java.util.logging.Level import java.util.logging.Logger val DEFAULT_ENCODING = "utf-8" /** * Base script that will be applied to the lazybones.groovy root script in a lazybones template * * @author Tommy Barker */ open class LazybonesScript : Script() { val log = Logger.getLogger(this.javaClass.getName()) /** * The target project directory. For project templates, this will be the * same as the directory into which the template was installed, i.e. * {@link #templateDir}. But for subtemplates, this will be the directory * of the project that the <code>generate</code> command is running in. */ var projectDir : File? = null /** * The location of the unpacked template. This will be the same as * {@link #projectDir} for project templates, but will be different for * subtemplates. This is the base path used when searching for files * that need filtering. * @since 0.7 */ var templateDir : File? = null /** * Stores the values for {@link #ask(java.lang.String, java.lang.Object, java.lang.String)} * calls when a parameter name is specified. * @since 0.7 */ val parentParams : MutableMap<String, Any?> = hashMapOf() /** * @since 0.7 */ var tmplQualifiers : List<String> = arrayListOf() /** * The encoding/charset used by the files in the template. This is UTF-8 * by default. */ var fileEncoding = DEFAULT_ENCODING var scmExclusionsFile : File? = null /** * The reader stream from which user input will be pulled. Defaults to a * wrapper around stdin using the platform's default encoding/charset. */ var reader = BufferedReader(InputStreamReader(System.`in`)) private var templateEngine : TemplateEngine? = SimpleTemplateEngine() private val registeredEngines : MutableMap<String, TemplateEngine> = hashMapOf() private val antPathMatcher = AntPathMatcher().pathSeparator(System.getProperty("file.separator")) /** * Provides access to the script's logger. * @since 0.9 */ // val getLog() : Logger { return this.log } /** * Declares the list of file patterns that should be excluded from SCM. * @since 0.5 */ fun scmExclusions(vararg exclusions : String) : Unit { if (scmExclusionsFile == null) return log.fine("Writing SCM exclusions file with: ${exclusions}") scmExclusionsFile!!.printWriter().use { writer : PrintWriter -> for (exclusion in exclusions) { writer.println(exclusion) } } } /** * Converts a name from one convention to another, e.g. from camel case to * natural form ("TestString" to "Test String"). * @param args Both {@code from} and {@code to} arguments are required and * must be instances of {@link NameType}. * @param name The string to convert. * @return The converted string, or {@code null} if the given name is {@code * null}, or an empty string if the given string is empty. * @since 0.5 */ fun transformText(args : Map<String, Any?>, name : String) : String? { if (!(args["from"] is NameType)) { throw IllegalArgumentException("Invalid or no value for 'from' named argument: ${args["from"]}") } if (!(args["to"] is NameType)) { throw IllegalArgumentException("Invalid or no value for 'to' named argument: ${args["to"]}") } return Naming.convert(args["from"] as NameType, args["to"] as NameType, name) } /** * Registers a template engine against a file suffix. For example, you can * register a {@code HandlebarsTemplateEngine} instance against the suffix * "hbs" which would result in *.hbs files being processed by that engine. * @param suffix The file suffix, excluding the dot ('.') * @param engine An instance of Groovy's {@code TemplateEngine}, e.g. * {@code SimpleTemplateEngine}. * @since 0.6 */ fun registerEngine(suffix : String, engine : TemplateEngine) : Unit { this.registeredEngines[suffix] = engine } /** * Registers a template engine as the default. This template engine will be * used by {@link #processTemplates(java.lang.String, java.util.Map)} for * files that don't have a template-specific suffix. The normal default is * an instance of Groovy's {@code SimpleTemplateEngine}. * @param engine An instance of Groovy's {@code TemplateEngine}, e.g. * {@code SimpleTemplateEngine}. Cannot be {@code null}. Use * {@link #clearDefaultEngine()} if you want to disable the default engine. * @since 0.6 */ fun registerDefaultEngine(engine : TemplateEngine) : Unit { this.templateEngine = engine } /** * Disables the default template engine. The result is that * {@link #processTemplates(java.lang.String, java.util.Map)} will simply * ignore any files that don't have a registered suffix (via * {@link #registerEngine(java.lang.String, groovy.text.TemplateEngine)}), * even if they match the given pattern. * @since 0.6 */ fun clearDefaultEngine() : Unit { this.templateEngine = null } /** * Prints a message asking for a property value. If the user has no response the default * value will be returned. null can be returned * * @param message * @param defaultValue * @return the response * @since 0.4 */ jvmOverloads fun ask(message : String, defaultValue : String? = null) : String? { print(message) return reader.readLine() ?: defaultValue } /** * <p>Prints a message asking for a property value. If a value for the property already exists in * the binding of the script, it is used instead of asking the question. If the user just presses * &lt;return&gt; the default value is returned.</p> * <p>This method also saves the value in the script's {@link #parentParams} map against the * <code>propertyName</code> key.</p> * * @param message The message to display to the user requesting some information. * @param defaultValue If the user doesn't provide a value, return this. * @param propertyName The name of the property in the binding whose value will * be used instead of prompting the user for input if that property exists. * @return The required value based on whether the message was displayed and * whether the user entered a value. * @since 0.4 */ fun ask(message : String, defaultValue : String?, propertyName : String) : String? { val value = if (propertyName.isNotBlank() && getBinding().hasVariable(propertyName)) getBinding().getVariable(propertyName)?.toString() else ask(message, defaultValue) parentParams[propertyName] = value return value } /** * Been deprecated as of lazybones 0.5, please use * {@link LazybonesScript#processTemplates(java.lang.String, java.util.Map)} * * @deprecated * @param filePattern * @param substitutionVariables * @since 0.4 */ fun filterFiles(filePattern : String, substitutionVariables : Map<String, Any?>) : Unit { val warningMessage = "The template you are using depends on a deprecated part of the API, [filterFiles], " + "which will be removed in Lazybones 1.0. Use a version of Lazybones prior to 0.5 with this template." log.warning(warningMessage) processTemplates(filePattern, substitutionVariables) } /** * @param filePattern classic ant pattern matcher * @param substitutionVariables model for processing the template * @return * @since 0.5 */ fun processTemplates(filePattern : String, substitutionVariables : Map<String, Any?>) : Script { if (projectDir == null) throw IllegalStateException("projectDir has not been set") if (templateDir == null) throw IllegalStateException("templateDir has not been set") var atLeastOneFileFiltered = false if (templateEngine != null) { log.fine("Processing files matching the pattern ${filePattern} using the default template engine") atLeastOneFileFiltered = processTemplatesWithEngine( findFilesByPattern(filePattern), substitutionVariables, templateEngine!!, true) || atLeastOneFileFiltered } for (entry in registeredEngines) { log.fine("Processing files matching the pattern ${filePattern} using the " + "template engine for '${entry.key}'") atLeastOneFileFiltered = processTemplatesWithEngine( findFilesByPattern(filePattern + '.' + entry.key), substitutionVariables, entry.value, false) || atLeastOneFileFiltered } if (!atLeastOneFileFiltered) { log.warning("No files filtered with file pattern [$filePattern] " + "and template directory [${templateDir!!.path}]") } // Not sure why this is here, but just in case someone actually relies on it... return this } /** * Returns a flat list of files in the target directory that match the * given Ant path pattern. The pattern should use forward slashes rather * than the platform file separator. */ private fun findFilesByPattern(pattern : String) : List<File> { val filePatternWithUserDir = File(templateDir!!.getCanonicalFile(), pattern).path return templateDir!!.walkTopDown().asSequence().filter { it.isFile() }.toList() } /** * Applies a specific template engine to a set of files. The files should be * templates of the appropriate type. * @param file The template files to process. * @param properties The model (variables and their values) for the templates. * @param engine The template engine to use for processing. * @param replace If {@code true}, replaces each source file with the text * generated by the processing. Otherwise, a new file is created with the same * name as the original, minus its final suffix (assumed to be a template-specific * suffix). * @throws IllegalArgumentException if any of the template file don't exist. */ protected fun processTemplatesWithEngine( files : List<File>, properties : Map<String, Any?>, engine : TemplateEngine, replace : Boolean) : Boolean { return files.fold(false) { filtered, file -> processTemplateWithEngine(file, properties, engine, replace) return true } } /** * Applies a specific template engine to a file. The file should be a * template of the appropriate type. * @param file The template file to process. * @param properties The model (variables and their values) for the template. * @param engine The template engine to use for processing. * @param replace If {@code true}, replaces the file with the text generated * by the processing. Otherwise, a new file is created with the same name as * the original, minus its final suffix (assumed to be a template-specific suffix). * @throws IllegalArgumentException if the template file doesn't exist. */ protected fun processTemplateWithEngine( file : File, properties : Map <String, Any?>, engine : TemplateEngine, replace : Boolean) : Unit { if (!file.exists()) { throw IllegalArgumentException("File ${file} does not exist") } log.fine("Filtering file ${file}${if (replace) " (replacing)" else ""}") val template = makeTemplate(engine, file, properties) val targetFile = if (replace) file else File(file.getParentFile(), FilenameUtils.getBaseName(file.path)) BufferedWriter(OutputStreamWriter(targetFile.outputStream(), fileEncoding)).use { writer -> template.writeTo(writer) } if (!replace) file.delete() } override fun run() : Any { throw UnsupportedOperationException("${this.javaClass.getName()} is not meant to be used directly. " + "It should instead be used as a base script") } /** * Determines whether the version of Lazybones loading the post-installation * script supports a particular feature. Current features include "ask" and * processTemplates for example. * @param featureName The name of the feature you want to check for. This should * be the name of a method on `LazybonesScript`. * @since 0.4 */ fun hasFeature(featureName : String) : Boolean { return this.javaClass.getMethods().any { method -> method.getName() == featureName } } /** * Returns the target project directory as a string. Only kept for backwards * compatibility and post-install scripts should switch to using {@link #projectDir} * as soon as possible. * @deprecated Will be removed before Lazybones 1.0 */ fun getTargetDir() : String { log.warning("The targetDir property is deprecated and should no longer be used by post-install scripts. " + "Use `projectDir` instead.") return projectDir!!.path } /** * Creates a new template instance from a file. * @param engine The template engine to use for parsing the file contents. * @param file The file to use as the content of the template. * @param properties The properties to populate the template with. Each key * in the map should correspond to a variable in the template. * @return The new template object */ protected fun makeTemplate(engine : TemplateEngine, file : File, properties : Map<String, Any?>) : Writable { BufferedReader(InputStreamReader(file.inputStream(), fileEncoding)).use { reader -> return engine.createTemplate(reader).make(properties) } } }
apache-2.0
32e4cfacd2d7c0d094326078ef82758d
39.280992
117
0.65251
4.582263
false
false
false
false
apollographql/apollo-android
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/java/file/OperationVariablesAdapterBuilder.kt
1
1446
package com.apollographql.apollo3.compiler.codegen.java.file import com.apollographql.apollo3.compiler.codegen.java.CodegenJavaFile import com.apollographql.apollo3.compiler.codegen.java.JavaClassBuilder import com.apollographql.apollo3.compiler.codegen.java.JavaContext import com.apollographql.apollo3.compiler.codegen.java.adapter.inputAdapterTypeSpec import com.apollographql.apollo3.compiler.codegen.java.helpers.toNamedType import com.apollographql.apollo3.compiler.ir.IrOperation import com.squareup.javapoet.ClassName import com.squareup.javapoet.TypeSpec class OperationVariablesAdapterBuilder( val context: JavaContext, val operation: IrOperation ): JavaClassBuilder { val packageName = context.layout.operationAdapterPackageName(operation.filePath) val simpleName = context.layout.operationVariablesAdapterName(operation) override fun prepare() { context.resolver.registerOperationVariablesAdapter( operation.name, ClassName.get(packageName, simpleName) ) } override fun build(): CodegenJavaFile { return CodegenJavaFile( packageName = packageName, typeSpec = typeSpec() ) } private fun typeSpec(): TypeSpec { return operation.variables.map { it.toNamedType() } .inputAdapterTypeSpec( context = context, adapterName = simpleName, adaptedTypeName = context.resolver.resolveOperation(operation.name) ) } }
mit
bf116dcd4b7f4995d50682ee699dfe1a
35.175
83
0.768326
4.634615
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/y2019/Day13.kt
1
1586
package com.nibado.projects.advent.y2019 import com.nibado.projects.advent.Day import com.nibado.projects.advent.Point object Day13 : Day { private val program = resourceIntCode(13) private fun IntCode.takePaintInstruction() = if (!terminated) Point(output.take().toInt(), output.take().toInt()) to output.take().toInt() else null override fun part1(): Int { val computer = IntCode(program) val out = computer.output var count = 0 while (!computer.terminated) { while (!computer.terminated && out.size < 3) computer.step() computer.takePaintInstruction()?.run { if (second == 2) count++ } } return count } override fun part2(): Int { val computer = IntCode(program).also { it.memory.set(0, 2) } var ball: Point var paddle = Point(0, 0) var score = 0 while (!computer.terminated) { while (!computer.terminated && computer.output.size < 3) computer.step() computer.takePaintInstruction()?.run { when { second == 3 -> paddle = first second == 4 -> { ball = first computer.input += when { ball.x > paddle.x -> 1L ball.x < paddle.x -> -1L else -> 0L } } first == Point(-1, 0) -> score = second } } } return score } }
mit
2461b3cb3cb858fec73e2774ea023320
28.943396
111
0.493064
4.570605
false
false
false
false
allotria/intellij-community
plugins/ide-features-trainer/src/training/learn/lesson/general/DuplicateLesson.kt
2
1347
// 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 training.learn.lesson.general import training.dsl.LessonContext import training.dsl.LessonSample import training.learn.LessonsBundle import training.learn.course.KLesson class DuplicateLesson(private val sample: LessonSample) : KLesson("Duplicate", LessonsBundle.message("duplicate.and.delete.lines.lesson.name")) { override val lessonContent: LessonContext.() -> Unit get() = { prepareSample(sample) actionTask("EditorDuplicate") { LessonsBundle.message("duplicate.and.delete.lines.duplicate.line", action(it)) } task("EditorDuplicate") { text( LessonsBundle.message("duplicate.and.delete.lines.duplicate.several.lines", action(it))) trigger(it, { val selection = editor.selectionModel val start = selection.selectionStartPosition?.line ?: 0 val end = selection.selectionEndPosition?.line ?: 0 end - start }, { _, new -> new >= 2 }) test { actions("EditorUp", "EditorLineStart", "EditorDownWithSelection", "EditorDownWithSelection", it) } } actionTask("EditorDeleteLine") { LessonsBundle.message("duplicate.and.delete.lines.delete.line", action(it)) } } }
apache-2.0
d2b5df8682a639836915189820a54016
41.125
140
0.69562
4.460265
false
false
false
false
allotria/intellij-community
plugins/markdown/test/src/org/intellij/plugins/markdown/html/MarkdownEmbeddedHtmlTest.kt
3
988
// 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.intellij.plugins.markdown.html import com.intellij.lang.html.HTMLLanguage import com.intellij.psi.impl.DebugUtil import com.intellij.testFramework.fixtures.BasePlatformTestCase import junit.framework.TestCase import org.intellij.plugins.markdown.MarkdownTestingUtil class MarkdownEmbeddedHtmlTest : BasePlatformTestCase() { override fun getTestDataPath(): String { return MarkdownTestingUtil.TEST_DATA_PATH + "/html/embedded/" } fun testHtml1() = doTest() fun testHtml2() = doTest() fun testHtml3() = doTest() fun doTest() { val name = getTestName(true) val file = myFixture.configureByFile("$name.md") val psi = DebugUtil.psiToString(file.viewProvider.getPsi(HTMLLanguage.INSTANCE), false, false) val tree = myFixture.configureByFile("$name.txt").text TestCase.assertEquals(psi, tree) } }
apache-2.0
3c4d11e30af8045c03f04363df362f02
31.966667
140
0.760121
4.204255
false
true
false
false
Tolriq/yatse-avreceiverplugin-api
api/src/main/java/tv/yatse/plugin/avreceiver/api/AVReceiverPluginService.kt
1
10169
/* * Copyright 2015 Tolriq / Genimee. * 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 tv.yatse.plugin.avreceiver.api import android.app.Service import android.content.Intent import android.os.IBinder import android.os.RemoteException /** * The AVReceiverPluginService service that any plugin must extend * * * Unless noted in command description most commands can be called from main thread so should handled this correctly : Fast and no network / disk access. */ abstract class AVReceiverPluginService : Service() { /** * Returns supported volume unit. * * @return the volume unit. Must be one of : [AVReceiverPluginService.UNIT_TYPE_NONE] / {link AVReceiverPluginService#UNIT_TYPE_PERCENT} */ protected abstract fun getVolumeUnitType(): Int /** * Gets volume minimal value. * * @return the volume minimal value. Should return 0 for {link AVReceiverPluginService#UNIT_VOLUME_PERCENT} */ protected abstract fun getVolumeMinimalValue(): Double /** * Gets volume maximal value. * * @return the volume maximal value. Should return 100 for {link AVReceiverPluginService#UNIT_VOLUME_PERCENT} */ protected abstract fun getVolumeMaximalValue(): Double /** * Sets mute status. * * @param status the new new mute status * @return true on success */ protected abstract fun setMuteStatus(status: Boolean): Boolean /** * Gets current mute status. * * @return the mute status */ protected abstract fun getMuteStatus(): Boolean /** * Toggle mute status. * * @return true on success */ protected abstract fun toggleMuteStatus(): Boolean /** * Sets new volume level. * * @param volume the volume * @return true on success */ protected abstract fun setVolumeLevel(volume: Double): Boolean /** * Gets current volume level. * * @return the volume level */ protected abstract fun getVolumeLevel(): Double /** * Update current volume up by a configured step. * * @return true on success */ protected abstract fun volumePlus(): Boolean /** * Update current volume down by a configured step. * * @return true on success */ protected abstract fun volumeMinus(): Boolean /** * Refresh the current status of the audio/video receiver. * This command should be synchronous and only returns when the internal data is up to date. * This command will be called from a background thread so can last a little and use network. * * @return true on success */ protected abstract fun refresh(): Boolean /** * Gets the list of default custom commands that Yatse can import. * * * For commands that can have a lot of different parameters like input change, * please offer the commands via the add custom command Activity and do not return hundreds * of commands. * * @return the list of custom commands. */ protected abstract fun getDefaultCustomCommands(): List<PluginCustomCommand> /** * Execute the given custom command. * * * * @param customCommand the custom command * @return true on success */ protected abstract fun executeCustomCommand(customCommand: PluginCustomCommand?): Boolean /** * This function is called each time Yatse binds to the service for a specific host. * This allows per host settings with the host uniqueId * * @param uniqueId the host unique id * @param name the host name * @param ip the host ip */ protected abstract fun connectToHost(uniqueId: String?, name: String?, ip: String?) /** * Gets settings version. * This function should return an increased value on each plugin settings change to allow Yatse * to backup plugin data for later restore * * @return the current settings version */ protected abstract fun getSettingsVersion(): Long /** * This function is called by Yatse to get the plugin settings data for backup purpose. * * @return the settings as a string. */ protected abstract fun getSettings(): String /** * This function is called by Yatse when it have a more recent version of the settings than the plugin itself, * like on a reinstall and restore from Cloud Save * * @param settings the settings as String * @param version the settings version * @return true on success */ protected abstract fun restoreSettings(settings: String?, version: Long): Boolean private val serviceBinder: IReceiverPluginInterface.Stub = object : IReceiverPluginInterface.Stub() { @Throws(RemoteException::class) override fun getVolumeUnitType(): Int { return [email protected]() } @Throws(RemoteException::class) override fun getVolumeMinimalValue(): Double { return [email protected]() } @Throws(RemoteException::class) override fun getVolumeMaximalValue(): Double { return [email protected]() } @Throws(RemoteException::class) override fun setMuteStatus(status: Boolean): Boolean { return [email protected](status) } @Throws(RemoteException::class) override fun getMuteStatus(): Boolean { return [email protected]() } @Throws(RemoteException::class) override fun toggleMuteStatus(): Boolean { return [email protected]() } @Throws(RemoteException::class) override fun setVolumeLevel(volume: Double): Boolean { return [email protected](volume) } @Throws(RemoteException::class) override fun getVolumeLevel(): Double { return [email protected]() } @Throws(RemoteException::class) override fun volumePlus(): Boolean { return [email protected]() } @Throws(RemoteException::class) override fun volumeMinus(): Boolean { return [email protected]() } @Throws(RemoteException::class) override fun refresh(): Boolean { return [email protected]() } @Throws(RemoteException::class) override fun getDefaultCustomCommands(): List<PluginCustomCommand> { return [email protected]() } @Throws(RemoteException::class) override fun executeCustomCommand(customCommand: PluginCustomCommand): Boolean { return [email protected](customCommand) } @Throws(RemoteException::class) override fun getSettingsVersion(): Long { return [email protected]() } @Throws(RemoteException::class) override fun getSettings(): String { return [email protected]() } @Throws(RemoteException::class) override fun restoreSettings(settings: String, version: Long): Boolean { return [email protected](settings, version) } } override fun onBind(intent: Intent): IBinder? { connectToHost( intent.getStringExtra(EXTRA_STRING_MEDIA_CENTER_UNIQUE_ID), intent.getStringExtra(EXTRA_STRING_MEDIA_CENTER_NAME), intent.getStringExtra(EXTRA_STRING_MEDIA_CENTER_IP) ) return serviceBinder } companion object { /** * String extra that will contains the associated media center unique id when Yatse connect to the service or start the settings activity. * This extra should always be filled, empty values should be checked and indicate a problem. */ const val EXTRA_STRING_MEDIA_CENTER_UNIQUE_ID = "tv.yatse.plugin.avreceiver.EXTRA_STRING_MEDIA_CENTER_UNIQUE_ID" /** * String extra that will contains the associated media center name when Yatse connect to the service or start the settings activity. */ const val EXTRA_STRING_MEDIA_CENTER_NAME = "tv.yatse.plugin.avreceiver.EXTRA_STRING_MEDIA_CENTER_NAME" /** * String extra that will contains the associated media center IP when Yatse connect to the service or start the settings activity. */ const val EXTRA_STRING_MEDIA_CENTER_IP = "tv.yatse.plugin.avreceiver.EXTRA_STRING_MEDIA_CENTER_IP" /** * This volume unit disable discrete volume values and only allows volumePlus and volumeMinus calls. */ const val UNIT_TYPE_NONE = 0 /** * Default volume unit. Volume is handled as a percent value between 0 and 100 */ const val UNIT_TYPE_PERCENT = 1 /** * Volume is handled as a db value between [AVReceiverPluginService.getVolumeMinimalValue] and [AVReceiverPluginService.getVolumeMaximalValue] * * * **This value is not yet supported by Yatse and will be treated as [AVReceiverPluginService.UNIT_TYPE_PERCENT] !** */ @Suppress("unused") const val UNIT_TYPE_DB = 2 } }
apache-2.0
d08409b387e7a24b7ca34131360a19c5
33.242424
153
0.662307
4.833175
false
false
false
false
zdary/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/PackageUpdateInspection.kt
1
3376
package com.jetbrains.packagesearch.intellij.plugin.extensibility import com.intellij.codeHighlighting.HighlightDisplayLevel import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.util.text.SemVer import com.intellij.util.text.VersionComparatorUtil import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.api.model.StandardV2Package import com.jetbrains.packagesearch.intellij.plugin.api.model.StandardV2Version import com.jetbrains.packagesearch.intellij.plugin.intentions.PackageUpdateQuickFix import com.jetbrains.packagesearch.intellij.plugin.looksLikeGradleVariable import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.PackageSearchToolWindowFactory import com.jetbrains.packagesearch.intellij.plugin.version.looksLikeStableVersion internal abstract class PackageUpdateInspection : LocalInspectionTool() { @JvmField var stableOnly: Boolean = true abstract fun shouldCheckFile(file: PsiFile): Boolean abstract fun getVersionElement(file: PsiFile, dependency: StandardV2Package): PsiElement? final override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? { if (!shouldCheckFile(file)) { return null } // val project = file.project // val rootModel = project.rootModel() // val module = ProjectModuleProvider.obtainAllProjectModulesFor(project).toList().find { // it.buildFile == file.virtualFile // } ?: return null val problemsHolder = ProblemsHolder(manager, file, isOnTheFly) // TODO replace this with a service access (also note the getVersionElement() signature has changed since) // rootModel.preparePackageOperationTargetsFor(listOf(module)).forEach { target -> // val dependency = target.dependencyModel.remoteInfo ?: return@forEach // val highestVersion = (dependency.versions?.map(StandardV2Version::version) ?: emptyList()) // .asSequence() // .filter { it.isNotBlank() && !looksLikeGradleVariable(it) } // .filter { !stableOnly || looksLikeStableVersion(it) } // .distinct() // .sortedWith(Comparator { o1, o2 -> VersionComparatorUtil.compare(o2, o1) }) // .firstOrNull() ?: return@forEach // // val semVerHighest = SemVer.parseFromText(highestVersion) ?: return@forEach // val semVerTarget = SemVer.parseFromText(target.version) ?: return@forEach // if (semVerHighest <= semVerTarget) return@forEach // val versionElement = getVersionElement(file, dependency) ?: return@forEach // // problemsHolder.registerProblem( // versionElement, // PackageSearchBundle.message("packagesearch.inspection.update.description", highestVersion), // PackageUpdateQuickFix(versionElement, target, dependency, highestVersion) // ) // } return problemsHolder.resultsArray } override fun getDefaultLevel() = HighlightDisplayLevel.WARNING!! }
apache-2.0
77f57f44a349791d3bb00fa6ea361d79
49.38806
125
0.728673
4.850575
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-entities/src/main/kotlin/slatekit/entities/core/EntityBuilder.kt
1
4831
package slatekit.entities.core import kotlin.reflect.KClass import slatekit.common.data.* import slatekit.common.crypto.Encryptor import slatekit.utils.naming.Namer import slatekit.entities.* import slatekit.meta.Reflector import slatekit.meta.models.Model /** * Responsible for building individual components of this Micro-ORM. * 1. Con : Database connection Info * 2. Db : JDBC wrapper ( depends on Con above ) * 3. Model : Schema ( columns ) of entity that can be persisted * 4. Mapper : Maps entities to/from sql * 5. Repo : Repository implementation ( depends on Db above ) * 6. Service : Service implementation ( depends on Repo above ) */ open class EntityBuilder( val dbCreator: (DbCon) -> IDb, val dbs: Connections, val enc: Encryptor? = null ) { /** * Builds the unique key for looking up an entity by its name, database key and shard. * @param entityType: The class name e.g. "MyApp.User" * @param dbKey: The name of the database key ( empty / "" by default if only 1 database ) * @param dbShard: The name of the database shard ( empty / "" by default if only 1 database ) */ fun key(entityType: KClass<*>, dbKey: String = "", dbShard: String = ""): String = key(entityType.qualifiedName!!, dbKey, dbShard) /** * Builds the unique key for looking up an entity by its name, database key and shard. * @param entityType: The class name e.g. "MyApp.User" ( qualified name ) * @param dbKey: The name of the database key ( empty / "" by default if only 1 database ) * @param dbShard: The name of the database shard ( empty / "" by default if only 1 database ) */ fun key(entityType: String, dbKey: String = "", dbShard: String = ""): String = "$entityType:$dbKey:$dbShard" /** * Builds the database connection based on the key/shard provided. * @param dbKey: The name of the database key ( empty / "" by default if only 1 database ) * @param dbShard: The name of the database shard ( empty / "" by default if only 1 database ) */ fun con(dbKey: String = "", dbShard: String = ""): DbCon { val db = dbs.let { dbs -> when { // Case 1: default connection dbKey.isEmpty() -> dbs.default() // Case 2: named connection dbShard.isEmpty() -> dbs.named(dbKey) // Case 3: shard else -> dbs.group(dbKey, dbShard) } } ?: throw Exception("Unable to get database connection with $dbKey, $dbShard") return db } /** * Builds the database by loading up the connection info for the database key / shard provided. * @param dbKey: The name of the database key ( empty / "" by default if only 1 database ) * @param dbShard: The name of the database shard ( empty / "" by default if only 1 database ) */ fun db(dbKey: String = "", dbShard: String = "", open: Boolean = true): IDb { val con = con(dbKey, dbShard) return db(con, open) } /** * Builds the database by loading up the connection info for the database key / shard provided. * @param con: The database connection with properties * @param open: whether or not to open the database */ fun db(con: DbCon, open: Boolean = true): IDb { require(con != DbCon.empty) { "Db connection supplied is empty" } return if (open) dbCreator(con).open() else dbCreator(con) } /** * Builds a Model representing the schema of the Entity ( using the Class name ) * NOTE: Currently the system enforces an primary key be named as "id" * This may be removed later */ fun model(entityType: KClass<*>, namer: Namer?, table: String?): Model { return Schema.load(entityType, EntityWithId<*>::id.name, namer, table) } /** * Dynamically builds an EntityService using the type and repo supplied. * @param entities: The top level Entities object to get instances of various types * @param serviceType: The KClass of the EntityService implementation to create * @param repo: The underlying Repo that handle persistence * @param args: Additional arguments to constructor of service during creation */ fun <TId, T> service( entities: Entities, serviceType: KClass<*>?, repo: EntityRepo<TId, T>, args: Any? ): EntityService<*, *> where TId : Comparable<TId>, T : Entity<TId> { return serviceType?.let { // Parameters to service is the context and repo val params = args?.let { args -> listOf(args, entities, repo) } ?: listOf(entities, repo) Reflector.createWithArgs<EntityService<*,*>>(it, params.toTypedArray()) } ?: EntityService(repo) } }
apache-2.0
877de01ac30fc754d674f92741615c0b
42.133929
113
0.63196
4.215532
false
false
false
false
leafclick/intellij-community
platform/object-serializer/src/primitiveBindings.kt
1
7066
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.serialization import java.lang.reflect.Type private fun resolved(binding: Binding): NestedBindingFactory = { binding } internal fun registerPrimitiveBindings(classToRootBindingFactory: MutableMap<Class<*>, RootBindingFactory>, classToNestedBindingFactory: MutableMap<Class<*>, NestedBindingFactory>) { classToRootBindingFactory.put(java.lang.String::class.java) { StringBinding() } val numberAsObjectBinding = NumberAsObjectBinding() classToRootBindingFactory.put(java.lang.Integer::class.java) { numberAsObjectBinding } classToRootBindingFactory.put(java.lang.Long::class.java) { numberAsObjectBinding } classToRootBindingFactory.put(java.lang.Short::class.java) { numberAsObjectBinding } // java.lang.Float cannot be cast to java.lang.Double classToRootBindingFactory.put(java.lang.Float::class.java) { FloatAsObjectBinding() } classToRootBindingFactory.put(java.lang.Double::class.java) { DoubleAsObjectBinding() } classToRootBindingFactory.put(java.lang.Boolean::class.java) { BooleanAsObjectBinding() } classToNestedBindingFactory.put(java.lang.Short.TYPE, resolved(ShortBinding())) classToNestedBindingFactory.put(Integer.TYPE, resolved(IntBinding())) classToNestedBindingFactory.put(java.lang.Long.TYPE, resolved(LongBinding())) classToNestedBindingFactory.put(java.lang.Float.TYPE, resolved(FloatBinding())) classToNestedBindingFactory.put(java.lang.Double.TYPE, resolved(DoubleBinding())) classToNestedBindingFactory.put(java.lang.Boolean.TYPE, resolved(BooleanBinding())) val char: NestedBindingFactory = { throw UnsupportedOperationException("char is not supported") } classToNestedBindingFactory.put(Character.TYPE, char) classToNestedBindingFactory.put(Character::class.java, char) val byte: NestedBindingFactory = { throw UnsupportedOperationException("byte is not supported") } classToNestedBindingFactory.put(java.lang.Byte.TYPE, byte) classToNestedBindingFactory.put(java.lang.Byte::class.java, byte) } private class FloatAsObjectBinding : Binding { override fun serialize(obj: Any, context: WriteContext) { context.writer.writeFloat((obj as Float).toDouble()) } override fun deserialize(context: ReadContext, hostObject: Any?) = context.reader.doubleValue().toFloat() } private class DoubleAsObjectBinding : Binding { override fun serialize(obj: Any, context: WriteContext) { context.writer.writeFloat(obj as Double) } override fun deserialize(context: ReadContext, hostObject: Any?) = context.reader.doubleValue() } internal class NumberAsObjectBinding : Binding { override fun createCacheKey(aClass: Class<*>?, type: Type) = aClass!! override fun serialize(obj: Any, context: WriteContext) { context.writer.writeInt((obj as Number).toLong()) } override fun deserialize(context: ReadContext, hostObject: Any?) = context.reader.intValue() } private class BooleanAsObjectBinding : Binding { override fun serialize(obj: Any, context: WriteContext) { context.writer.writeBool(obj as Boolean) } override fun deserialize(context: ReadContext, hostObject: Any?) = context.reader.booleanValue() } private class BooleanBinding : Binding { override fun serialize(obj: Any, context: WriteContext) { context.writer.writeBool(obj as Boolean) } override fun deserialize(context: ReadContext, hostObject: Any?) = context.reader.booleanValue() override fun serialize(hostObject: Any, property: MutableAccessor, context: WriteContext) { val writer = context.writer writer.setFieldName(property.name) writer.writeBool(property.readBoolean(hostObject)) } override fun deserialize(hostObject: Any, property: MutableAccessor, context: ReadContext) { property.setBoolean(hostObject, context.reader.booleanValue()) } } private open class IntBinding : Binding { override fun serialize(obj: Any, context: WriteContext) { context.writer.writeInt(obj as Long) } override fun deserialize(context: ReadContext, hostObject: Any?) = context.reader.intValue() override fun serialize(hostObject: Any, property: MutableAccessor, context: WriteContext) { val writer = context.writer writer.setFieldName(property.name) writer.writeInt(property.readInt(hostObject).toLong()) } override fun deserialize(hostObject: Any, property: MutableAccessor, context: ReadContext) { property.setInt(hostObject, context.reader.intValue()) } } private class ShortBinding : IntBinding() { override fun deserialize(hostObject: Any, property: MutableAccessor, context: ReadContext) { property.setShort(hostObject, context.reader.intValue().toShort()) } } private class LongBinding : Binding { override fun serialize(obj: Any, context: WriteContext) { context.writer.writeInt(obj as Long) } override fun deserialize(context: ReadContext, hostObject: Any?) = context.reader.longValue() override fun serialize(hostObject: Any, property: MutableAccessor, context: WriteContext) { val writer = context.writer writer.setFieldName(property.name) writer.writeInt(property.readLong(hostObject)) } override fun deserialize(hostObject: Any, property: MutableAccessor, context: ReadContext) { property.setLong(hostObject, context.reader.longValue()) } } private class FloatBinding : Binding { override fun serialize(obj: Any, context: WriteContext) { context.writer.writeFloat(obj as Double) } override fun deserialize(context: ReadContext, hostObject: Any?) = context.reader.doubleValue() override fun serialize(hostObject: Any, property: MutableAccessor, context: WriteContext) { val writer = context.writer writer.setFieldName(property.name) writer.writeFloat(property.readFloat(hostObject).toDouble()) } override fun deserialize(hostObject: Any, property: MutableAccessor, context: ReadContext) { property.setFloat(hostObject, context.reader.doubleValue().toFloat()) } } private class DoubleBinding : Binding { override fun serialize(obj: Any, context: WriteContext) { context.writer.writeFloat(obj as Double) } override fun deserialize(context: ReadContext, hostObject: Any?) = context.reader.doubleValue() override fun serialize(hostObject: Any, property: MutableAccessor, context: WriteContext) { val writer = context.writer writer.setFieldName(property.name) writer.writeFloat(property.readDouble(hostObject)) } override fun deserialize(hostObject: Any, property: MutableAccessor, context: ReadContext) { property.setDouble(hostObject, context.reader.doubleValue()) } } internal class StringBinding : Binding { override fun deserialize(context: ReadContext, hostObject: Any?): Any { return context.reader.stringValue() } override fun serialize(obj: Any, context: WriteContext) { val s = obj as String if (s.length < 64) { context.writer.writeSymbol(s) } else { context.writer.writeString(s) } } }
apache-2.0
18b14a2e7e67fa9615dca15c24676fc6
37.617486
182
0.763798
4.295441
false
false
false
false
peterLaurence/TrekAdvisor
app/src/main/java/com/peterlaurence/trekme/viewmodel/common/LocationProviderFactory.kt
1
3257
package com.peterlaurence.trekme.viewmodel.common import android.Manifest import android.content.Context import android.content.pm.PackageManager import androidx.core.app.ActivityCompat import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationResult import com.google.android.gms.location.LocationServices /** * Used by the MainActivity only, creates instances of [LocationProvider] based on how this class * is configured (configuration may change at runtime). * It needs a [Context] as some [LocationProvider] need one. This is also the reason why the * MainActivity is holding reference to [LocationProviderFactory], to avoid memory leak. */ class LocationProviderFactory(val context: Context) { private var source: LocationSource = LocationSource.GOOGLE_FUSE fun configure(source: LocationSource) { this.source = source } fun getLocationProvider(): LocationProvider { return when(source) { LocationSource.GOOGLE_FUSE -> GoogleLocationProvider(context) LocationSource.NMEA -> TODO() } } } enum class LocationSource { GOOGLE_FUSE, NMEA } sealed class LocationProvider { abstract fun start(locationCb: LocationCallback) abstract fun stop() } /** * [latitude] and [longitude] are in degrees * [speed] is in meters per second */ data class Location(val latitude: Double = 0.0, val longitude: Double = 0.0, val speed: Float = 0f) /** * Use the Google api to receive location. * It's set to receive a new location at most every second. */ private class GoogleLocationProvider(val context: Context): LocationProvider() { private val fusedLocationClient: FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context) val locationRequest = LocationRequest() lateinit var googleLocationCallback: com.google.android.gms.location.LocationCallback init { locationRequest.interval = 1000 locationRequest.fastestInterval = 1000 locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY } override fun start(locationCb: LocationCallback) { if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return } /** * Beware that this object holds a reference to the provided [locationCb] (which itself * hides a reference to a view), so [stop] method must be called when appropriate. */ googleLocationCallback = object : com.google.android.gms.location.LocationCallback() { override fun onLocationResult(locationResult: LocationResult?) { for (loc in locationResult!!.locations) { locationCb(Location(loc.latitude, loc.longitude, loc.speed)) } } } fusedLocationClient.requestLocationUpdates(locationRequest, googleLocationCallback, null) } override fun stop() { fusedLocationClient.removeLocationUpdates(googleLocationCallback) } } typealias LocationCallback = (Location) -> Unit
gpl-3.0
2a1d4ffef74849fe21632bf94830e4c5
34.791209
123
0.714154
4.980122
false
false
false
false
smmribeiro/intellij-community
plugins/git4idea/src/git4idea/stash/ui/GitStashActions.kt
4
2171
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.stash.ui import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataKey import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import git4idea.stash.GitStashOperations import git4idea.stash.GitStashTracker import git4idea.ui.StashInfo val STASH_INFO = DataKey.create<List<StashInfo>>("GitStashInfoList") abstract class GitSingleStashAction : DumbAwareAction() { abstract fun perform(project: Project, stashInfo: StashInfo): Boolean override fun update(e: AnActionEvent) { e.presentation.isEnabled = e.project != null && e.getData(STASH_INFO)?.size == 1 e.presentation.isVisible = e.isFromActionToolbar || (e.project != null && e.getData(STASH_INFO) != null) } override fun actionPerformed(e: AnActionEvent) { if (perform(e.project!!, e.getRequiredData(STASH_INFO).single())) { e.project!!.serviceIfCreated<GitStashTracker>()?.scheduleRefresh() } } } class GitDropStashAction : GitSingleStashAction() { override fun perform(project: Project, stashInfo: StashInfo): Boolean { return GitStashOperations.dropStashWithConfirmation(project, null, stashInfo) } } class GitPopStashAction : GitSingleStashAction() { override fun perform(project: Project, stashInfo: StashInfo): Boolean { return GitStashOperations.unstash(project, stashInfo, null, true, false) } } class GitApplyStashAction : GitSingleStashAction() { override fun perform(project: Project, stashInfo: StashInfo): Boolean { return GitStashOperations.unstash(project, stashInfo, null, false, false) } } class GitUnstashAsAction: GitSingleStashAction() { override fun perform(project: Project, stashInfo: StashInfo): Boolean { val dialog = GitUnstashAsDialog(project, stashInfo) if (dialog.showAndGet()) { return GitStashOperations.unstash(project, stashInfo, dialog.branch, dialog.popStash, dialog.keepIndex) } return false } }
apache-2.0
5f38d0702b3d7880ebdffd462d9b466e
37.105263
140
0.766928
4.333333
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/decompiler/navigation/AbstractNavigateFromLibrarySourcesTest.kt
6
1711
// 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.navigation import com.intellij.openapi.roots.LibraryOrderEntry import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.MockLibraryFacility abstract class AbstractNavigateFromLibrarySourcesTest : KotlinLightCodeInsightFixtureTestCase() { protected fun navigationElementForReferenceInLibrarySource(filePath: String, referenceText: String): PsiElement { val libraryOrderEntry = ModuleRootManager.getInstance(module).orderEntries .first { it is LibraryOrderEntry && it.libraryName == MockLibraryFacility.MOCK_LIBRARY_NAME } val libSourcesRoot = libraryOrderEntry.getUrls(OrderRootType.SOURCES)[0] val libUrl = "$libSourcesRoot/$filePath" val virtualFile = VirtualFileManager.getInstance().refreshAndFindFileByUrl(libUrl) ?: error("Can't find library: $libUrl") val psiFile = psiManager.findFile(virtualFile) ?: error("Can't find PSI file for $virtualFile") val indexOf = psiFile.text.indexOf(referenceText) val reference = psiFile.findReferenceAt(indexOf) ?: error("Can't find reference at index $indexOf") val resolvedElement = reference.resolve() ?: error("Can't resolve reference") return resolvedElement.navigationElement ?: error("Can't get navigation element") } }
apache-2.0
e4a2d7536ae91b1574193b8c77f95c32
62.37037
158
0.780245
4.95942
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/asJava/classes/FirLightClassForClassOrObjectSymbol.kt
2
7471
/* * 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.asJava import com.intellij.openapi.util.Comparing import com.intellij.psi.* import com.intellij.psi.impl.InheritanceImplUtil import com.intellij.psi.impl.PsiClassImplUtil import com.intellij.psi.search.SearchScope import com.intellij.psi.stubs.IStubElementType import com.intellij.psi.stubs.StubElement import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.asJava.classes.getOutermostClassOrObject import org.jetbrains.kotlin.asJava.classes.lazyPub import org.jetbrains.kotlin.asJava.elements.FirLightIdentifier import org.jetbrains.kotlin.asJava.elements.KtLightField import org.jetbrains.kotlin.idea.asJava.classes.getOrCreateFirLightClass import org.jetbrains.kotlin.idea.asJava.elements.FirLightTypeParameterListForSymbol import org.jetbrains.kotlin.idea.frontend.api.fir.analyzeWithSymbolAsContext import org.jetbrains.kotlin.idea.frontend.api.symbols.* import org.jetbrains.kotlin.idea.frontend.api.symbols.markers.KtSymbolKind import org.jetbrains.kotlin.idea.util.ifFalse import org.jetbrains.kotlin.idea.util.ifTrue import org.jetbrains.kotlin.load.java.structure.LightClassOriginKind import org.jetbrains.kotlin.psi.KtBlockExpression import org.jetbrains.kotlin.psi.KtClassBody import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.debugText.getDebugText import org.jetbrains.kotlin.psi.stubs.KotlinClassOrObjectStub internal abstract class FirLightClassForClassOrObjectSymbol( private val classOrObjectSymbol: KtClassOrObjectSymbol, manager: PsiManager ) : FirLightClassBase(manager), StubBasedPsiElement<KotlinClassOrObjectStub<out KtClassOrObject>> { private val isTopLevel: Boolean = classOrObjectSymbol.symbolKind == KtSymbolKind.TOP_LEVEL private val _isDeprecated: Boolean by lazyPub { classOrObjectSymbol.hasDeprecatedAnnotation() } override fun isDeprecated(): Boolean = _isDeprecated abstract override fun getModifierList(): PsiModifierList? abstract override fun getOwnFields(): List<KtLightField> abstract override fun getOwnMethods(): List<PsiMethod> private val _identifier: PsiIdentifier by lazyPub { FirLightIdentifier(this, classOrObjectSymbol) } override fun getNameIdentifier(): PsiIdentifier? = _identifier abstract override fun getExtendsList(): PsiReferenceList? abstract override fun getImplementsList(): PsiReferenceList? private val _typeParameterList: PsiTypeParameterList? by lazyPub { hasTypeParameters().ifTrue { val shiftCount = classOrObjectSymbol.isInner.ifTrue { (parent as? FirLightClassForClassOrObjectSymbol)?.classOrObjectSymbol?.typeParameters?.count() } ?: 0 FirLightTypeParameterListForSymbol( owner = this, symbolWithTypeParameterList = classOrObjectSymbol, innerShiftCount = shiftCount ) } } override fun hasTypeParameters(): Boolean = classOrObjectSymbol.typeParameters.isNotEmpty() override fun getTypeParameterList(): PsiTypeParameterList? = _typeParameterList override fun getTypeParameters(): Array<PsiTypeParameter> = _typeParameterList?.typeParameters ?: PsiTypeParameter.EMPTY_ARRAY abstract override fun getOwnInnerClasses(): List<PsiClass> override fun getTextOffset(): Int = kotlinOrigin?.textOffset ?: 0 override fun getStartOffsetInParent(): Int = kotlinOrigin?.startOffsetInParent ?: 0 override fun isWritable() = false override val kotlinOrigin: KtClassOrObject? = classOrObjectSymbol.psi as? KtClassOrObject protected fun addCompanionObjectFieldIfNeeded(result: MutableList<KtLightField>) { classOrObjectSymbol.companionObject?.run { result.add( FirLightFieldForObjectSymbol( objectSymbol = this, containingClass = this@FirLightClassForClassOrObjectSymbol, name = name.asString(), lightMemberOrigin = null ) ) } } private val _containingFile: PsiFile? by lazyPub { val kotlinOrigin = kotlinOrigin ?: return@lazyPub null val containingClass = isTopLevel.ifFalse { getOrCreateFirLightClass(getOutermostClassOrObject(kotlinOrigin)) } ?: this FirFakeFileImpl(kotlinOrigin, containingClass) } override fun getContainingFile(): PsiFile? = _containingFile override fun getNavigationElement(): PsiElement = kotlinOrigin ?: this override fun isEquivalentTo(another: PsiElement?): Boolean = basicIsEquivalentTo(this, another) || another is PsiClass && qualifiedName != null && Comparing.equal(another.qualifiedName, qualifiedName) abstract override fun equals(other: Any?): Boolean abstract override fun hashCode(): Int override fun getName(): String? = allowLightClassesOnEdt { classOrObjectSymbol.name.asString() } override fun hasModifierProperty(@NonNls name: String): Boolean = modifierList?.hasModifierProperty(name) ?: false abstract override fun isInterface(): Boolean abstract override fun isAnnotationType(): Boolean abstract override fun isEnum(): Boolean override fun isValid(): Boolean = kotlinOrigin?.isValid ?: true override fun isInheritor(baseClass: PsiClass, checkDeep: Boolean): Boolean = InheritanceImplUtil.isInheritor(this, baseClass, checkDeep) override fun toString() = "${this::class.java.simpleName}:${kotlinOrigin?.getDebugText()}" override fun getUseScope(): SearchScope = kotlinOrigin?.useScope ?: TODO() override fun getElementType(): IStubElementType<out StubElement<*>, *>? = kotlinOrigin?.elementType override fun getStub(): KotlinClassOrObjectStub<out KtClassOrObject>? = kotlinOrigin?.stub override val originKind: LightClassOriginKind get() = LightClassOriginKind.SOURCE override fun getQualifiedName() = kotlinOrigin?.fqName?.asString() override fun getInterfaces(): Array<PsiClass> = PsiClassImplUtil.getInterfaces(this) override fun getSuperClass(): PsiClass? = PsiClassImplUtil.getSuperClass(this) override fun getSupers(): Array<PsiClass> = PsiClassImplUtil.getSupers(this) override fun getSuperTypes(): Array<PsiClassType> = PsiClassImplUtil.getSuperTypes(this) override fun getContainingClass(): PsiClass? { val containingBody = kotlinOrigin?.parent as? KtClassBody val containingClass = containingBody?.parent as? KtClassOrObject containingClass?.let { return getOrCreateFirLightClass(it) } val containingBlock = kotlinOrigin?.parent as? KtBlockExpression // val containingScript = containingBlock?.parent as? KtScript // containingScript?.let { return KtLightClassForScript.create(it) } return null } override fun getParent(): PsiElement? = containingClass ?: containingFile override fun getScope(): PsiElement? = parent override fun isInheritorDeep(baseClass: PsiClass?, classToByPass: PsiClass?): Boolean = baseClass?.let { InheritanceImplUtil.isInheritorDeep(this, it, classToByPass) } ?: false abstract override fun copy(): FirLightClassForClassOrObjectSymbol }
apache-2.0
b4817ae66c281b9438be2506d955e79d
41.454545
126
0.747156
5.382565
false
false
false
false
nuxusr/walkman
okreplay-gradle-plugin/src/main/kotlin/okreplay/PullTapesTask.kt
1
1720
package okreplay import com.android.ddmlib.AdbCommandRejectedException import okreplay.OkReplayPlugin.Companion.LOCAL_TAPES_DIR import okreplay.OkReplayPlugin.Companion.REMOTE_TAPES_DIR import org.apache.commons.io.FileUtils import org.gradle.api.DefaultTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.TaskExecutionException import java.io.File import javax.inject.Inject open class PullTapesTask @Inject constructor() : DefaultTask(), TapeTask { @OutputDirectory private var outputDir: File? = null @Input var _packageName: String? = null @Input var _deviceBridge: DeviceBridge? = null init { description = "Pull OkReplay tapes from the Device SD Card" group = "okreplay" } @TaskAction internal fun pullTapes() { outputDir = project.file(LOCAL_TAPES_DIR) val localDir = outputDir!!.absolutePath FileUtils.forceMkdir(outputDir) _deviceBridge!!.devices().forEach { val externalStorage = it.externalStorageDir() if (externalStorage.isNullOrEmpty()) { throw TaskExecutionException(this, RuntimeException("Failed to retrieve the device external storage dir.")) } try { it.pullDirectory(localDir, "$externalStorage/$REMOTE_TAPES_DIR/$_packageName/") } catch (e: RuntimeException) { project.logger.error("ADB Command failed: ${e.message}") } } } override fun setDeviceBridge(deviceBridge: DeviceBridge) { _deviceBridge = deviceBridge } override fun setPackageName(packageName: String) { _packageName = packageName } companion object { internal val NAME = "pullOkReplayTapes" } }
apache-2.0
1778d1a10fd681ed764f3ab7a4332511
30.272727
87
0.73314
4.1247
false
false
false
false
fabmax/kool
kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/atmosphere/AtmosphericScatteringShader.kt
1
8256
package de.fabmax.kool.demo.atmosphere import de.fabmax.kool.math.Vec2f import de.fabmax.kool.math.Vec3f import de.fabmax.kool.modules.atmosphere.AtmosphereNode import de.fabmax.kool.modules.atmosphere.RaySphereIntersectionNode import de.fabmax.kool.pipeline.DepthCompareOp import de.fabmax.kool.pipeline.UniformMat4f import de.fabmax.kool.pipeline.deferred.DeferredPassSwapListener import de.fabmax.kool.pipeline.deferred.DeferredPasses import de.fabmax.kool.pipeline.shadermodel.* import de.fabmax.kool.pipeline.shading.ModeledShader import de.fabmax.kool.pipeline.shading.Texture2dInput import de.fabmax.kool.util.Color import kotlin.math.pow class AtmosphericScatteringShader : ModeledShader(atmosphereModel()), DeferredPassSwapListener { private var atmosphereNode: AtmosphereNode? = null val opticalDepthLut = Texture2dInput("tOpticalDepthLut") val sceneColor = Texture2dInput("tSceneColor") val scenePos = Texture2dInput("tScenePos") val skyColor = Texture2dInput("tSkyColor") var dirToSun = Vec3f(0f, 0f, 1f) set(value) { field = value atmosphereNode?.uDirToSun?.value?.set(value) } var sunColor = Color.WHITE set(value) { field = value atmosphereNode?.uSunColor?.value?.set(value) } var scatteringCoeffPow = 4.5f set(value) { field = value updateScatteringCoeffs() } var scatteringCoeffStrength = 1f set(value) { field = value updateScatteringCoeffs() } var scatteringCoeffs = Vec3f(0.5f, 0.8f, 1.0f) set(value) { field = value updateScatteringCoeffs() } var rayleighColor = Color(0.75f, 0.75f, 0.75f, 1f) set(value) { field = value atmosphereNode?.uRayleighColor?.value?.set(value) } var mieColor = Color(1f, 0.9f, 0.8f, 0.3f) set(value) { field = value atmosphereNode?.uMieColor?.value?.set(value) } var mieG = 0.99f set(value) { field = value atmosphereNode?.uMieG?.value = value } var planetCenter = Vec3f.ZERO set(value) { field = value atmosphereNode?.uPlanetCenter?.value?.set(value) } var surfaceRadius = 600f set(value) { field = value atmosphereNode?.uSurfaceRadius?.value = value } var atmosphereRadius = 609f set(value) { field = value atmosphereNode?.uAtmosphereRadius?.value = value } init { onPipelineSetup += { builder, _, _ -> builder.depthTest = DepthCompareOp.DISABLED } onPipelineCreated += { _, _, _ -> opticalDepthLut.connect(model) sceneColor.connect(model) scenePos.connect(model) skyColor.connect(model) atmosphereNode = model.findNodeByType() atmosphereNode?.apply { uDirToSun.value.set(dirToSun) uPlanetCenter.value.set(planetCenter) uSurfaceRadius.value = surfaceRadius uAtmosphereRadius.value = atmosphereRadius uRayleighColor.value.set(rayleighColor) uMieColor.value.set(mieColor) uMieG.value = mieG uSunColor.value.set(sunColor) updateScatteringCoeffs() } } } private fun updateScatteringCoeffs() { atmosphereNode?.uScatteringCoeffs?.value?.let { it.x = scatteringCoeffs.x.pow(scatteringCoeffPow) * scatteringCoeffStrength it.y = scatteringCoeffs.y.pow(scatteringCoeffPow) * scatteringCoeffStrength it.z = scatteringCoeffs.z.pow(scatteringCoeffPow) * scatteringCoeffStrength } } companion object { private fun atmosphereModel() = ShaderModel("atmo-scattering-shader").apply { val mvp: UniformBufferMvp val ifQuadPos: StageInterfaceNode val ifViewDir: StageInterfaceNode vertexStage { mvp = mvpNode() val quadPos = attrTexCoords().output val viewDir = addNode(XyToViewDirNode(stage)).apply { inScreenPos = quadPos } ifViewDir = stageInterfaceNode("ifViewDir", viewDir.outViewDir) ifQuadPos = stageInterfaceNode("ifTexCoords", quadPos) positionOutput = fullScreenQuadPositionNode(quadPos).outQuadPos } fragmentStage { addNode(RaySphereIntersectionNode(stage)) val fragMvp = mvp.addToStage(stage) val opticalDepthLut = texture2dNode("tOpticalDepthLut") val sceneColor = texture2dSamplerNode(texture2dNode("tSceneColor"), ifQuadPos.output).outColor val skyColor = texture2dSamplerNode(texture2dNode("tSkyColor"), ifQuadPos.output).outColor val viewPos = texture2dSamplerNode(texture2dNode("tScenePos"), ifQuadPos.output).outColor val view2world = addNode(ViewToWorldPosNode(stage)).apply { inViewPos = viewPos } val atmoNd = addNode(AtmosphereNode(opticalDepthLut, stage)).apply { inSceneColor = sceneColor inSceneDepth = splitNode(viewPos, "z").output inScenePos = view2world.outWorldPos inSkyColor = skyColor inViewDepth = splitNode(viewPos, "z").output inCamPos = fragMvp.outCamPos inLookDir = ifViewDir.output } colorOutput(hdrToLdrNode(atmoNd.outColor).outColor) } } } private class XyToViewDirNode(graph: ShaderGraph) : ShaderNode("xyToViewDir", graph) { private val uInvViewProjMat = UniformMat4f("uInvViewProjMat") var inScreenPos = ShaderNodeIoVar(ModelVar2fConst(Vec2f.ZERO)) val outViewDir = ShaderNodeIoVar(ModelVar3f("${name}_outWorldPos"), this) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(inScreenPos) shaderGraph.descriptorSet.apply { uniformBuffer(name, shaderGraph.stage) { +{ uInvViewProjMat } onUpdate = { _, cmd -> uInvViewProjMat.value.set(cmd.renderPass.camera.invViewProj) } } } } override fun generateCode(generator: CodeGenerator) { generator.appendMain(""" vec4 ${name}_near = $uInvViewProjMat * vec4(${inScreenPos.ref2f()} * 2.0 - 1.0, 0.0, 1.0); vec4 ${name}_far = $uInvViewProjMat * vec4(${inScreenPos.ref2f()} * 2.0 - 1.0, 1.0, 1.0); ${outViewDir.declare()} = (${name}_far.xyz / ${name}_far.w) - (${name}_near.xyz / ${name}_near.w); """) } } private class ViewToWorldPosNode(graph: ShaderGraph) : ShaderNode("view2worldPos", graph) { private val uInvViewMat = UniformMat4f("uInvViewMat") var inViewPos = ShaderNodeIoVar(ModelVar3fConst(Vec3f.ZERO)) val outWorldPos = ShaderNodeIoVar(ModelVar4f("${name}_outWorldPos"), this) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(inViewPos) shaderGraph.descriptorSet.apply { uniformBuffer(name, shaderGraph.stage) { +{ uInvViewMat } onUpdate = { _, cmd -> uInvViewMat.value.set(cmd.renderPass.camera.invView) } } } } override fun generateCode(generator: CodeGenerator) { generator.appendMain("${outWorldPos.declare()} = $uInvViewMat * vec4(${inViewPos.ref3f()}, 1.0);") } } override fun onSwap(previousPasses: DeferredPasses, currentPasses: DeferredPasses) { sceneColor(currentPasses.lightingPass.colorTexture) scenePos(currentPasses.materialPass.positionFlags) } }
apache-2.0
13e4881ec54d30f4e8d56ed6bc730f0d
36.876147
114
0.59593
4.057002
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/caches/resolve/JvmPlatformKindResolution.kt
5
5329
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.caches.resolve import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.projectRoots.Sdk import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.analyzer.PlatformAnalysisParameters import org.jetbrains.kotlin.analyzer.ResolverForModuleFactory import org.jetbrains.kotlin.analyzer.ResolverForProject import org.jetbrains.kotlin.builtins.DefaultBuiltIns import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.jvm.JvmBuiltIns import org.jetbrains.kotlin.context.ProjectContext import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl import org.jetbrains.kotlin.idea.base.projectStructure.IdeBuiltInsLoadingState import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.IdeaModuleInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.LibraryInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.SdkInfo import org.jetbrains.kotlin.idea.base.projectStructure.supportsAdditionalBuiltInsMembers import org.jetbrains.kotlin.idea.caches.resolve.BuiltInsCacheKey import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind import org.jetbrains.kotlin.resolve.TargetEnvironment import org.jetbrains.kotlin.resolve.jvm.JvmPlatformParameters import org.jetbrains.kotlin.resolve.jvm.JvmResolverForModuleFactory private val LOG = Logger.getInstance(JvmPlatformKindResolution::class.java) class JvmPlatformKindResolution : IdePlatformKindResolution { override fun createResolverForModuleFactory( settings: PlatformAnalysisParameters, environment: TargetEnvironment, platform: TargetPlatform ): ResolverForModuleFactory { return JvmResolverForModuleFactory(settings as JvmPlatformParameters, environment, platform) } override val kind get() = JvmIdePlatformKind override fun getKeyForBuiltIns(moduleInfo: ModuleInfo, sdkInfo: SdkInfo?, stdlibInfo: LibraryInfo?): BuiltInsCacheKey { if (IdeBuiltInsLoadingState.isFromClassLoader && stdlibInfo != null) { LOG.error("Standard library ${stdlibInfo.displayedName} provided for built-ins, but loading from dependencies is disabled") } return if (sdkInfo != null) CacheKeyByBuiltInsDependencies(sdkInfo.sdk, stdlibInfo) else BuiltInsCacheKey.DefaultBuiltInsKey } override fun createBuiltIns( moduleInfo: IdeaModuleInfo, projectContext: ProjectContext, resolverForProject: ResolverForProject<IdeaModuleInfo>, sdkDependency: SdkInfo?, stdlibDependency: LibraryInfo?, ): KotlinBuiltIns { return when { sdkDependency == null -> DefaultBuiltIns.Instance stdlibDependency == null || moduleInfo is SdkInfo -> createBuiltInsFromClassLoader(moduleInfo, projectContext, resolverForProject, sdkDependency) else -> createBuiltinsFromModuleDependencies(moduleInfo, projectContext, resolverForProject, sdkDependency, stdlibDependency) } } private fun createBuiltInsFromClassLoader( moduleInfo: IdeaModuleInfo, projectContext: ProjectContext, resolverForProject: ResolverForProject<IdeaModuleInfo>, sdkDependency: SdkInfo, ): JvmBuiltIns { return JvmBuiltIns(projectContext.storageManager, JvmBuiltIns.Kind.FROM_CLASS_LOADER).apply { setPostponedSettingsComputation { // SDK should be present, otherwise we wouldn't have created JvmBuiltIns in createBuiltIns val sdkDescriptor = resolverForProject.descriptorForModule(sdkDependency) val isAdditionalBuiltInsFeaturesSupported = moduleInfo.supportsAdditionalBuiltInsMembers(projectContext.project) JvmBuiltIns.Settings(sdkDescriptor, isAdditionalBuiltInsFeaturesSupported) } } } private fun createBuiltinsFromModuleDependencies( moduleInfo: IdeaModuleInfo, projectContext: ProjectContext, resolverForProject: ResolverForProject<IdeaModuleInfo>, sdkDependency: SdkInfo, stdlibDependency: LibraryInfo, ): JvmBuiltIns { if (IdeBuiltInsLoadingState.isFromClassLoader) { LOG.error("Incorrect attempt to create built-ins from module dependencies") } return JvmBuiltIns(projectContext.storageManager, JvmBuiltIns.Kind.FROM_DEPENDENCIES).apply { setPostponedBuiltinsModuleComputation { val stdlibDescriptor = resolverForProject.descriptorForModule(stdlibDependency) stdlibDescriptor as ModuleDescriptorImpl } setPostponedSettingsComputation { val sdkDescriptor = resolverForProject.descriptorForModule(sdkDependency) val isAdditionalBuiltInsFeaturesSupported = moduleInfo.supportsAdditionalBuiltInsMembers(projectContext.project) JvmBuiltIns.Settings(sdkDescriptor, isAdditionalBuiltInsFeaturesSupported) } } } data class CacheKeyByBuiltInsDependencies(val sdk: Sdk, val stdlib: LibraryInfo?) : BuiltInsCacheKey }
apache-2.0
9b8fc70299ea63791a6addb26c6b6f5b
45.745614
137
0.759617
5.90144
false
false
false
false
leafclick/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/StaticFileHandler.kt
1
3933
// 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.builtInWebServer import com.intellij.openapi.project.Project import com.intellij.util.PathUtilRt import io.netty.buffer.ByteBufUtf8Writer import io.netty.channel.Channel import io.netty.handler.codec.http.FullHttpRequest import io.netty.handler.codec.http.HttpHeaders import io.netty.handler.codec.http.HttpMethod import io.netty.handler.codec.http.HttpUtil import io.netty.handler.stream.ChunkedStream import org.jetbrains.builtInWebServer.ssi.SsiExternalResolver import org.jetbrains.builtInWebServer.ssi.SsiProcessor import org.jetbrains.io.FileResponses import org.jetbrains.io.addKeepAliveIfNeeded import org.jetbrains.io.flushChunkedResponse import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths private class StaticFileHandler : WebServerFileHandler() { override val pageFileExtensions = arrayOf("html", "htm", "shtml", "stm", "shtm") private var ssiProcessor: SsiProcessor? = null override fun process(pathInfo: PathInfo, canonicalPath: CharSequence, project: Project, request: FullHttpRequest, channel: Channel, projectNameIfNotCustomHost: String?, extraHeaders: HttpHeaders): Boolean { if (pathInfo.ioFile != null || pathInfo.file!!.isInLocalFileSystem) { val ioFile = pathInfo.ioFile ?: Paths.get(pathInfo.file!!.path) val nameSequence = ioFile.fileName.toString() //noinspection SpellCheckingInspection if (nameSequence.endsWith(".shtml", true) || nameSequence.endsWith(".stm", true) || nameSequence.endsWith(".shtm", true)) { processSsi(ioFile, PathUtilRt.getParentPath(canonicalPath.toString()), project, request, channel, extraHeaders) return true } FileResponses.sendFile(request, channel, ioFile, extraHeaders) return true } val file = pathInfo.file!! val response = FileResponses.prepareSend(request, channel, file.timeStamp, file.name, extraHeaders) ?: return true val isKeepAlive = response.addKeepAliveIfNeeded(request) if (request.method() != HttpMethod.HEAD) { HttpUtil.setContentLength(response, file.length) } channel.write(response) if (request.method() != HttpMethod.HEAD) { channel.write(ChunkedStream(file.inputStream)) } flushChunkedResponse(channel, isKeepAlive) return true } private fun processSsi(file: Path, path: String, project: Project, request: FullHttpRequest, channel: Channel, extraHeaders: HttpHeaders) { if (ssiProcessor == null) { ssiProcessor = SsiProcessor(false) } val buffer = channel.alloc().ioBuffer() val isKeepAlive: Boolean var releaseBuffer = true try { val lastModified = ssiProcessor!!.process(SsiExternalResolver(project, request, path, file.parent), file, ByteBufUtf8Writer(buffer)) val response = FileResponses.prepareSend(request, channel, lastModified, file.fileName.toString(), extraHeaders) ?: return isKeepAlive = response.addKeepAliveIfNeeded(request) if (request.method() != HttpMethod.HEAD) { HttpUtil.setContentLength(response, buffer.readableBytes().toLong()) } channel.write(response) if (request.method() != HttpMethod.HEAD) { releaseBuffer = false channel.write(buffer) } } finally { if (releaseBuffer) { buffer.release() } } flushChunkedResponse(channel, isKeepAlive) } } internal fun checkAccess(file: Path, root: Path = file.root): Boolean { var parent = file do { if (!hasAccess(parent)) { return false } parent = parent.parent ?: break } while (parent != root) return true } // deny access to any dot prefixed file internal fun hasAccess(result: Path) = Files.isReadable(result) && !(Files.isHidden(result) || result.fileName.toString().startsWith('.'))
apache-2.0
647c696f6fb2dd2cdd8cb02c3b5a80e1
36.466667
208
0.728197
4.37
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/notificationslist/BaseNotificationsListFragment.kt
1
2779
package io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.base.BaseFragment import io.github.feelfreelinux.wykopmobilny.models.dataclass.Notification import io.github.feelfreelinux.wykopmobilny.ui.adapters.NotificationsListAdapter import io.github.feelfreelinux.wykopmobilny.utils.isVisible import io.github.feelfreelinux.wykopmobilny.utils.prepare import io.github.feelfreelinux.wykopmobilny.utils.printout import io.github.feelfreelinux.wykopmobilny.utils.wykop_link_handler.WykopLinkHandlerApi import kotlinx.android.synthetic.main.activity_notifications_list.* abstract class BaseNotificationsListFragment : BaseFragment(), NotificationsListView, androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener { abstract var notificationAdapter: NotificationsListAdapter abstract var linkHandler: WykopLinkHandlerApi abstract fun markAsRead() abstract fun loadMore() private fun onNotificationClicked(position: Int) { val notification = notificationAdapter.data[position] notification.new = false notificationAdapter.notifyDataSetChanged() notification.url?.let { printout(notification.url) linkHandler.handleUrl(notification.url, true) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.activity_notifications_list, container, false) override fun onActivityCreated(savedInstanceState: Bundle?) { swiperefresh.setOnRefreshListener(this) notificationAdapter.loadNewDataListener = { loadMore() } notificationAdapter.itemClickListener = { onNotificationClicked(it) } recyclerView?.apply { prepare() adapter = notificationAdapter } swiperefresh?.isRefreshing = false super.onActivityCreated(savedInstanceState) } override fun addNotifications(notifications: List<Notification>, shouldClearAdapter: Boolean) { loadingView?.isVisible = false swiperefresh?.isRefreshing = false notificationAdapter.addData(if (!shouldClearAdapter) notifications.filterNot { notificationAdapter.data.contains(it) } else notifications, shouldClearAdapter) } override fun showReadToast() { onRefresh() Toast.makeText(context, R.string.read_notifications, Toast.LENGTH_SHORT).show() } override fun disableLoading() = notificationAdapter.disableLoading() }
mit
b4f83c112e60caa44b16f60354e554f3
38.15493
146
0.759266
5.273245
false
false
false
false
siosio/intellij-community
plugins/git-features-trainer/src/git4idea/ift/lesson/GitInteractiveRebaseLesson.kt
1
10104
// 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 git4idea.ift.lesson import com.intellij.openapi.actionSystem.CommonShortcuts import com.intellij.openapi.actionSystem.KeyboardShortcut import com.intellij.openapi.actionSystem.impl.ActionMenuItem import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.vcs.ui.CommitMessage import com.intellij.openapi.wm.ToolWindowId import com.intellij.openapi.wm.ToolWindowManager import com.intellij.ui.components.BasicOptionButtonUI import com.intellij.ui.table.JBTable import com.intellij.vcs.log.Hash import com.intellij.vcs.log.VcsCommitMetadata import com.intellij.vcs.log.data.VcsLogData import com.intellij.vcs.log.impl.VcsProjectLog import com.intellij.vcs.log.ui.table.VcsLogGraphTable import com.intellij.vcs.log.util.findBranch import git4idea.GitNotificationIdsHolder import git4idea.i18n.GitBundle import git4idea.ift.GitLessonsBundle import git4idea.ift.GitLessonsUtil.checkoutBranch import git4idea.ift.GitLessonsUtil.highlightLatestCommitsFromBranch import git4idea.ift.GitLessonsUtil.highlightSubsequentCommitsInGitLog import git4idea.ift.GitLessonsUtil.resetGitLogWindow import git4idea.ift.GitLessonsUtil.showWarningIfGitWindowClosed import git4idea.ift.GitLessonsUtil.triggerOnNotification import git4idea.rebase.interactive.dialog.GIT_INTERACTIVE_REBASE_DIALOG_DIMENSION_KEY import training.dsl.* import training.dsl.LessonUtil.adjustPopupPosition import training.dsl.LessonUtil.restorePopupPosition import training.ui.LearningUiHighlightingManager import java.awt.Point import java.awt.event.InputEvent import java.awt.event.KeyEvent import javax.swing.JButton import javax.swing.JDialog import javax.swing.KeyStroke class GitInteractiveRebaseLesson : GitLesson("Git.InteractiveRebase", GitLessonsBundle.message("git.interactive.rebase.lesson.name")) { override val existedFile = "git/martian_cat.yml" private val branchName = "fixes" private var backupRebaseDialogLocation: Point? = null override val testScriptProperties = TaskTestContext.TestScriptProperties(skipTesting = true) override val lessonContent: LessonContext.() -> Unit = { checkoutBranch(branchName) task("ActivateVersionControlToolWindow") { text(GitLessonsBundle.message("git.interactive.rebase.open.git.window", action(it))) stateCheck { val toolWindowManager = ToolWindowManager.getInstance(project) toolWindowManager.getToolWindow(ToolWindowId.VCS)?.isVisible == true } } resetGitLogWindow() task { text(GitLessonsBundle.message("git.interactive.rebase.introduction")) highlightLatestCommitsFromBranch(branchName, sequenceLength = 5, highlightInside = false, usePulsation = true) proceedLink() } task { var commitHashToHighlight: Hash? = null before { LearningUiHighlightingManager.clearHighlights() val vcsData = VcsProjectLog.getInstance(project).dataManager commitHashToHighlight = vcsData?.findFirstCommitInBranch(branchName) } highlightSubsequentCommitsInGitLog { it.id == commitHashToHighlight } } val interactiveRebaseMenuItemText = GitBundle.message("action.Git.Interactive.Rebase.text") lateinit var openRebaseDialogTaskId: TaskContext.TaskId task { openRebaseDialogTaskId = taskId text(GitLessonsBundle.message("git.interactive.rebase.open.context.menu")) text(GitLessonsBundle.message("git.interactive.rebase.click.commit.tooltip"), LearningBalloonConfig(Balloon.Position.above, 0)) triggerByUiComponentAndHighlight { ui: ActionMenuItem -> ui.text == interactiveRebaseMenuItemText } showWarningIfGitWindowClosed() } task { text(GitLessonsBundle.message("git.interactive.rebase.choose.interactive.rebase", strong(interactiveRebaseMenuItemText))) val rebasingDialogTitle = GitBundle.message("rebase.interactive.dialog.title") triggerByUiComponentAndHighlight(false, false) { ui: JDialog -> ui.title?.contains(rebasingDialogTitle) == true } restoreByUi(delayMillis = defaultRestoreDelay) } lateinit var movingCommitText: String task { before { if (backupRebaseDialogLocation == null) { backupRebaseDialogLocation = adjustPopupPosition(GIT_INTERACTIVE_REBASE_DIALOG_DIMENSION_KEY) } } text(GitLessonsBundle.message("git.interactive.rebase.select.one.commit")) highlightCommitInRebaseDialog(4) triggerByUiComponentAndHighlight(false, false) { ui: JBTable -> if (ui !is VcsLogGraphTable) { movingCommitText = ui.model.getValueAt(4, 1).toString() ui.selectedRow == 4 } else false } restoreByUi(openRebaseDialogTaskId) } task { val moveUpShortcut = CommonShortcuts.MOVE_UP.shortcuts.first() as KeyboardShortcut text(GitLessonsBundle.message("git.interactive.rebase.move.commit", LessonUtil.rawKeyStroke(moveUpShortcut.firstKeyStroke))) triggerByPartOfComponent(highlightInside = true, usePulsation = false) { ui: JBTable -> if (ui !is VcsLogGraphTable) { ui.getCellRect(1, 1, false).apply { height = 1 } } else null } triggerByUiComponentAndHighlight(false, false) { ui: JBTable -> ui.model.getValueAt(1, 1).toString() == movingCommitText } restoreState { Thread.currentThread().stackTrace.find { it.className.contains("GitInteractiveRebaseUsingLog") } == null } } task { val fixupShortcut = KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.ALT_DOWN_MASK) text(GitLessonsBundle.message("git.interactive.rebase.invoke.fixup", LessonUtil.rawKeyStroke(fixupShortcut), strong(GitBundle.message("rebase.entry.action.name.fixup")))) triggerByUiComponentAndHighlight { _: BasicOptionButtonUI.ArrowButton -> true } trigger("git4idea.rebase.interactive.dialog.FixupAction") } task { text(GitLessonsBundle.message("git.interactive.rebase.select.three.commits", LessonUtil.rawKeyStroke(KeyEvent.VK_SHIFT))) highlightSubsequentCommitsInRebaseDialog(startRowIncl = 2, endRowExcl = 5) triggerByUiComponentAndHighlight(false, false) { ui: JBTable -> ui.similarCommitsSelected() } } task { val squashShortcut = KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.ALT_DOWN_MASK) text(GitLessonsBundle.message("git.interactive.rebase.invoke.squash", LessonUtil.rawKeyStroke(squashShortcut), strong(GitBundle.message("rebase.entry.action.name.squash")))) triggerByUiComponentAndHighlight { _: BasicOptionButtonUI.MainButton -> true } trigger("git4idea.rebase.interactive.dialog.SquashAction") restoreState { val table = previous.ui as? JBTable ?: return@restoreState false !table.similarCommitsSelected() } } task { triggerByUiComponentAndHighlight(false, false) { _: CommitMessage -> true } } task { val applyRewordShortcut = CommonShortcuts.CTRL_ENTER.shortcuts.first() as KeyboardShortcut text(GitLessonsBundle.message("git.interactive.rebase.apply.reword", LessonUtil.rawKeyStroke(applyRewordShortcut.firstKeyStroke))) stateCheck { previous.ui?.isShowing != true } } task { val startRebasingButtonText = GitBundle.message("rebase.interactive.dialog.start.rebase") text(GitLessonsBundle.message("git.interactive.rebase.start.rebasing", strong(startRebasingButtonText))) triggerByUiComponentAndHighlight(usePulsation = true) { ui: JButton -> ui.text?.contains(startRebasingButtonText) == true } triggerOnNotification { it.displayId == GitNotificationIdsHolder.REBASE_SUCCESSFUL } } text(GitLessonsBundle.message("git.interactive.rebase.congratulations")) } override fun onLessonEnd(project: Project, lessonPassed: Boolean) { restorePopupPosition(project, GIT_INTERACTIVE_REBASE_DIALOG_DIMENSION_KEY, backupRebaseDialogLocation) backupRebaseDialogLocation = null } private fun TaskContext.highlightCommitInRebaseDialog(rowInd: Int) { highlightSubsequentCommitsInRebaseDialog(rowInd, rowInd + 1, highlightInside = true) } private fun TaskContext.highlightSubsequentCommitsInRebaseDialog(startRowIncl: Int, endRowExcl: Int, highlightInside: Boolean = false, usePulsation: Boolean = false) { triggerByPartOfComponent(highlightInside = highlightInside, usePulsation = usePulsation) { ui: JBTable -> if (ui !is VcsLogGraphTable) { val rect = ui.getCellRect(startRowIncl, 1, false) rect.height *= endRowExcl - startRowIncl rect } else null } } private fun JBTable.similarCommitsSelected(): Boolean { val rows = selectedRows return rows.size == 3 && (2..4).all { rows.contains(it) } } private fun VcsLogData.findFirstCommitInBranch(branchName: String): Hash? { val root = roots.single() val mainCommitHash = dataPack.findBranch("main", root)?.commitHash val lastCommitHash = dataPack.findBranch(branchName, root)?.commitHash return if (mainCommitHash != null && lastCommitHash != null) { var metadata = getCommitMetadata(lastCommitHash) while (metadata.parents.single() != mainCommitHash) { metadata = getCommitMetadata(metadata.parents.single()) } metadata.id } else null } private fun VcsLogData.getCommitMetadata(hash: Hash): VcsCommitMetadata { val index = getCommitIndex(hash, roots.single()) return topCommitsCache[index] ?: miniDetailsGetter.getCommitData(index, listOf(index)) } }
apache-2.0
817c1eb05ab8be22ce952740eda2381e
41.280335
140
0.720606
4.931186
false
false
false
false
jwren/intellij-community
java/compiler/impl/src/com/intellij/packaging/impl/elements/ProductionModuleSourcePackagingElement.kt
3
3017
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.packaging.impl.elements import com.intellij.openapi.module.ModulePointer import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.packaging.elements.PackagingElementOutputKind import com.intellij.packaging.elements.PackagingElementResolvingContext import com.intellij.packaging.impl.artifacts.workspacemodel.mutableElements import com.intellij.packaging.impl.ui.DelegatedPackagingElementPresentation import com.intellij.packaging.impl.ui.ModuleElementPresentation import com.intellij.packaging.ui.ArtifactEditorContext import com.intellij.packaging.ui.PackagingElementPresentation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder import com.intellij.workspaceModel.storage.bridgeEntities.ModuleId import com.intellij.workspaceModel.storage.bridgeEntities.addModuleSourcePackagingElementEntity import org.jetbrains.annotations.NonNls import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes class ProductionModuleSourcePackagingElement : ModulePackagingElementBase { constructor(project: Project) : super(ProductionModuleSourceElementType.ELEMENT_TYPE, project) {} constructor(project: Project, modulePointer: ModulePointer) : super(ProductionModuleSourceElementType.ELEMENT_TYPE, project, modulePointer) override fun getSourceRoots(context: PackagingElementResolvingContext): Collection<VirtualFile> { val module = findModule(context) ?: return emptyList() val rootModel = context.modulesProvider.getRootModel(module) return rootModel.getSourceRoots(JavaModuleSourceRootTypes.PRODUCTION) } override fun createPresentation(context: ArtifactEditorContext): PackagingElementPresentation { return DelegatedPackagingElementPresentation( ModuleElementPresentation(myModulePointer, context, ProductionModuleSourceElementType.ELEMENT_TYPE)) } override fun getFilesKind(context: PackagingElementResolvingContext) = PackagingElementOutputKind.OTHER override fun getOrAddEntity(diff: WorkspaceEntityStorageBuilder, source: EntitySource, project: Project): WorkspaceEntity { val existingEntity = getExistingEntity(diff) if (existingEntity != null) return existingEntity val moduleName = this.moduleName val addedEntity = if (moduleName != null) { diff.addModuleSourcePackagingElementEntity(ModuleId(moduleName), source) } else { diff.addModuleSourcePackagingElementEntity(null, source) } diff.mutableElements.addMapping(addedEntity, this) return addedEntity } @NonNls override fun toString() = "module sources:" + moduleName!! }
apache-2.0
26bc32ca8d9e96d58ebe5d2b3ebb774b
48.459016
140
0.793172
5.330389
false
false
false
false
google/playhvz
Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/declareallegiance/TakeQuizFragment.kt
1
8824
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.app.playhvz.screens.declareallegiance import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.content.res.AppCompatResources import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentTransaction import androidx.lifecycle.LiveData import androidx.navigation.fragment.findNavController import com.app.playhvz.R import com.app.playhvz.common.globals.CrossClientConstants.Companion.QUIZ_TYPE_INFO import com.app.playhvz.common.globals.CrossClientConstants.Companion.QUIZ_TYPE_MULTIPLE_CHOICE import com.app.playhvz.common.globals.CrossClientConstants.Companion.QUIZ_TYPE_ORDER import com.app.playhvz.common.globals.CrossClientConstants.Companion.QUIZ_TYPE_TRUE_FALSE import com.app.playhvz.common.globals.SharedPreferencesConstants import com.app.playhvz.firebase.classmodels.Game import com.app.playhvz.firebase.classmodels.Player import com.app.playhvz.firebase.classmodels.QuizQuestion import com.app.playhvz.firebase.viewmodels.GameViewModel import com.app.playhvz.firebase.viewmodels.QuizQuestionListViewModel import com.app.playhvz.navigation.NavigationUtil import com.app.playhvz.screens.quiz.displayquestions.DisplayInfoQuestionFragment import com.app.playhvz.screens.quiz.displayquestions.DisplayMultiAnswerQuestionFragment import com.app.playhvz.screens.quiz.displayquestions.DisplayOrderAnswerQuestionFragment import com.google.android.material.button.MaterialButton import com.google.android.material.floatingactionbutton.FloatingActionButton /** Fragment for going through the allegiance quiz.*/ class TakeQuizFragment : Fragment(), OnUpdateNextButtonInterface { companion object { val TAG = TakeQuizFragment::class.qualifiedName } private lateinit var gameViewModel: GameViewModel private lateinit var questionViewModel: QuizQuestionListViewModel private lateinit var fab: FloatingActionButton private lateinit var checkAnswersButton: MaterialButton private lateinit var helpButton: MaterialButton private lateinit var nextButton: MaterialButton private lateinit var loadingSpinner: ProgressBar private lateinit var quizQuestionLiveData: LiveData<List<QuizQuestion>> var currentOnCheckAnswersListener: OnCheckAnswersInterface? = null var gameId: String? = null var playerId: String? = null var game: Game? = null var player: Player? = null var questions: List<QuizQuestion> = listOf() var currentlyDisplayedQuestion = -1 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val sharedPrefs = activity?.getSharedPreferences( SharedPreferencesConstants.PREFS_FILENAME, 0 )!! gameViewModel = GameViewModel() questionViewModel = QuizQuestionListViewModel() gameId = sharedPrefs.getString(SharedPreferencesConstants.CURRENT_GAME_ID, null) playerId = sharedPrefs.getString(SharedPreferencesConstants.CURRENT_PLAYER_ID, null) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val view = inflater.inflate(R.layout.fragment_take_allegiance_quiz, container, false) fab = activity?.findViewById(R.id.floating_action_button)!! loadingSpinner = view.findViewById(R.id.progress_bar) helpButton = view.findViewById(R.id.help_button) checkAnswersButton = view.findViewById(R.id.check_answers_button) nextButton = view.findViewById(R.id.next_button) checkAnswersButton.setOnClickListener { if (currentOnCheckAnswersListener == null) { return@setOnClickListener } currentOnCheckAnswersListener!!.checkAnswers() } nextButton.setOnClickListener { showNextQuestion() } setupObservers() setupToolbar() setupFab() return view } fun setupToolbar() { val toolbar = (activity as AppCompatActivity).supportActionBar if (toolbar != null) { toolbar.title = requireContext().getString(R.string.take_quiz_title) } } private fun setupFab() { fab.visibility = View.GONE } private fun setupObservers() { if (gameId == null || playerId == null) { return } gameViewModel.getGameAndAdminObserver(this, gameId!!, playerId!!) .observe(viewLifecycleOwner, androidx.lifecycle.Observer { serverGameAndAdminStatus -> updateGame(serverGameAndAdminStatus) }) quizQuestionLiveData = questionViewModel.getGameQuizQuestions(gameId!!) var allowedUpdates = 2 quizQuestionLiveData.observe( viewLifecycleOwner, androidx.lifecycle.Observer { questionList -> allowedUpdates-- updateQuestionList(questionList, allowedUpdates) }) } private fun updateGame(serverUpdate: GameViewModel.GameWithAdminStatus?) { if (serverUpdate == null) { NavigationUtil.navigateToGameList(findNavController(), requireActivity()) } game = serverUpdate!!.game } private fun updateQuestionList(questions: List<QuizQuestion?>, allowedUpdates: Int) { if (allowedUpdates == 1) { return } else if (allowedUpdates == 0) { // The first update is always an emptylivedata, wait to remove the observer until after // our second update. loadingSpinner.visibility = View.GONE quizQuestionLiveData.removeObservers(viewLifecycleOwner) } val clean = mutableListOf<QuizQuestion>() for (question in questions) { if (question != null) { clean.add(question) } } clean.sortBy { question -> question.index } this.questions = clean.toList() if (this.questions.isEmpty()) { showAllegianceScreen() } else { showNextQuestion() } } private fun showNextQuestion() { currentlyDisplayedQuestion++ if (currentlyDisplayedQuestion >= questions.size) { showAllegianceScreen() return } var childFragment: Fragment? = null val question = questions[currentlyDisplayedQuestion] when (question.type) { QUIZ_TYPE_INFO -> { childFragment = DisplayInfoQuestionFragment(question) } QUIZ_TYPE_MULTIPLE_CHOICE -> { childFragment = DisplayMultiAnswerQuestionFragment(question) } QUIZ_TYPE_TRUE_FALSE -> { childFragment = DisplayMultiAnswerQuestionFragment(question) } QUIZ_TYPE_ORDER -> { childFragment = DisplayOrderAnswerQuestionFragment(question) } } currentOnCheckAnswersListener = if (childFragment is OnCheckAnswersInterface) { childFragment } else { null } val transaction: FragmentTransaction = childFragmentManager.beginTransaction() transaction.replace(R.id.quiz_question_display_container, childFragment!!).commit() enableNextButton(false) } private fun showAllegianceScreen() { currentOnCheckAnswersListener = null nextButton.setOnClickListener { } nextButton.icon = AppCompatResources.getDrawable(requireContext(), R.drawable.ic_check) val childFragment: Fragment = DeclareAllegianceFragment() val transaction: FragmentTransaction = childFragmentManager.beginTransaction() transaction.replace(R.id.quiz_question_display_container, childFragment).commit() } override fun enableNextButton(canEnableButton: Boolean) { if (canEnableButton) { checkAnswersButton.isEnabled = false nextButton.isEnabled = true } else { checkAnswersButton.isEnabled = true nextButton.isEnabled = false } } }
apache-2.0
90b06e5336e751855ccd1aa1f71513ee
38.048673
99
0.694243
4.971268
false
false
false
false